bitbot-3.11-fork/modules/imgur.py

70 lines
2.3 KiB
Python
Raw Normal View History

2018-10-31 16:12:28 +00:00
#--require-config imgur-api-key
import re
2018-10-31 16:12:28 +00:00
from src import ModuleManager, utils
REGEX_IMAGE = re.compile("https?://(?:i\.)?imgur.com/(\w+)")
2018-10-31 17:41:12 +00:00
REGEX_GALLERY = re.compile("https?://imgur.com/gallery/(\w+)")
2018-10-31 16:12:28 +00:00
URL_IMAGE = "https://api.imgur.com/3/image/%s"
URL_GALLERY = "https://api.imgur.com/3/gallery/%s"
2018-10-31 16:12:28 +00:00
class Module(ModuleManager.BaseModule):
2018-10-31 17:41:12 +00:00
def _prefix(self, data):
text = "%s: " % data["id"]
if data["nsfw"]:
text += "[NSFW] "
if data["account_url"]:
text += "%s " % data["account_url"]
return text
2018-10-31 17:41:12 +00:00
2018-10-31 16:12:28 +00:00
def _image_info(self, hash):
api_key = self.bot.config["imgur-api-key"]
result = utils.http.get_url(URL_IMAGE % hash,
headers={"Authorization": "Client-ID %s" % api_key},
2018-10-31 16:12:28 +00:00
json=True)
if result and result["success"]:
data = result["data"]
2018-10-31 17:41:12 +00:00
text = self._prefix(data)
2018-10-31 16:12:28 +00:00
text += "(%s %dx%d, %d views)" % (data["type"], data["width"],
2018-10-31 16:12:28 +00:00
data["height"], data["views"])
if data["title"]:
text += " %s" % data["title"]
2018-10-31 17:41:12 +00:00
return text
else:
raise utils.EventsResultsError()
def _gallery_info(self, hash):
api_key = self.bot.config["imgur-api-key"]
result = utils.http.get_url(URL_GALLERY % hash,
2018-10-31 17:41:12 +00:00
headers={"Authorization": "Client-ID %s" % api_key},
json=True)
if result and result["success"]:
data = result["data"]
text = self._prefix(data)
text += "(%d views, %d▲▼%d)" % (data["views"],
data["ups"], data["downs"])
2018-10-31 17:41:12 +00:00
if data["title"]:
text += " %s" % data["title"]
2018-10-31 16:12:28 +00:00
return text
else:
raise utils.EventsResultsError()
@utils.hook("received.command.imgur", min_args=1)
def imgur(self, event):
"""
:help: Get information about a given imgur image URL
:usage: <url>
"""
2018-10-31 17:41:12 +00:00
match = REGEX_GALLERY.match(event["args_split"][0])
if match:
event["stdout"].write(self._gallery_info(match.group(1)))
return
match = REGEX_IMAGE.match(event["args_split"][0])
if match:
event["stdout"].write(self._image_info(match.group(1)))
return