This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/disabled_stuff/imgur.py

83 lines
2.3 KiB
Python
Raw Normal View History

2013-09-30 14:53:57 +02:00
import re
import random
2014-02-14 04:36:57 +01:00
from util import hook, http, web
2013-09-30 14:53:57 +02:00
base_url = "http://reddit.com/r/{}/.json"
imgur_re = re.compile(r'http://(?:i\.)?imgur\.com/(a/)?(\w+\b(?!/))\.?\w?')
2013-09-30 14:53:57 +02:00
album_api = "https://api.imgur.com/3/album/{}/images.json"
2013-09-30 14:53:57 +02:00
def is_valid(data):
if data["domain"] in ["i.imgur.com", "imgur.com"]:
return True
else:
return False
@hook.command(autohelp=False)
2013-09-30 14:53:57 +02:00
def imgur(inp):
2014-02-14 05:03:08 +01:00
"""imgur [subreddit] -- Gets the first page of imgur images from [subreddit] and returns a link to them.
If [subreddit] is undefined, return any imgur images"""
if inp:
# see if the input ends with "nsfw"
show_nsfw = inp.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
if show_nsfw:
inp = inp[:-5].strip().lower()
url = base_url.format(inp.strip())
else:
url = "http://www.reddit.com/domain/imgur.com/.json"
show_nsfw = False
2013-09-30 14:53:57 +02:00
try:
data = http.get_json(url, user_agent=http.ua_chrome)
2013-09-30 14:53:57 +02:00
except Exception as e:
return "Error: " + str(e)
data = data["data"]["children"]
random.shuffle(data)
2013-09-30 15:37:00 +02:00
# filter list to only have imgur links
filtered_posts = [i["data"] for i in data if is_valid(i["data"])]
2013-09-30 14:53:57 +02:00
if not filtered_posts:
2013-09-30 14:53:57 +02:00
return "No images found."
items = []
headers = {
2014-02-14 05:03:08 +01:00
"Authorization": "Client-ID b5d127e6941b07a"
2013-09-30 14:53:57 +02:00
}
# loop over the list of posts
for post in filtered_posts:
if post["over_18"] and not show_nsfw:
continue
match = imgur_re.search(post["url"])
if match.group(1) == 'a/':
# post is an album
2013-09-30 14:53:57 +02:00
url = album_api.format(match.group(2))
images = http.get_json(url, headers=headers)["data"]
2013-09-30 14:53:57 +02:00
2013-09-30 15:37:00 +02:00
# loop over the images in the album and add to the list
for image in images:
items.append(image["id"])
2013-09-30 14:53:57 +02:00
elif match.group(2) is not None:
# post is an image
items.append(match.group(2))
2013-09-30 14:53:57 +02:00
if not items:
return "No images found (use .imgur <subreddit> nsfw to show explicit content)"
2013-09-30 16:06:53 +02:00
if show_nsfw:
return "{} \x02NSFW\x02".format(web.isgd("http://imgur.com/" + ','.join(items)))
else:
2013-11-12 07:06:06 +01:00
return web.isgd("http://imgur.com/" + ','.join(items))