PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/cogs/image.py

https://bitbucket.org/btirelan86/chibibot
Python | 168 lines | 161 code | 6 blank | 1 comment | 2 complexity | 4ea222233eee8c6bb54a7ebba62e79a7 MD5 | raw file
Possible License(s): GPL-3.0
  1. from discord.ext import commands
  2. from random import choice, shuffle
  3. import aiohttp
  4. import functools
  5. import asyncio
  6. try:
  7. from imgurpython import ImgurClient
  8. except:
  9. ImgurClient = False
  10. CLIENT_ID = "1fd3ef04daf8cab"
  11. CLIENT_SECRET = "f963e574e8e3c17993c933af4f0522e1dc01e230"
  12. GIPHY_API_KEY = "dc6zaTOxFJmzC"
  13. class Image:
  14. """Image related commands."""
  15. def __init__(self, bot):
  16. self.bot = bot
  17. self.imgur = ImgurClient(CLIENT_ID, CLIENT_SECRET)
  18. @commands.group(name="imgur", no_pm=True, pass_context=True)
  19. async def _imgur(self, ctx):
  20. """Retrieves pictures from imgur"""
  21. if ctx.invoked_subcommand is None:
  22. await self.bot.send_cmd_help(ctx)
  23. @_imgur.command(pass_context=True, name="random")
  24. async def imgur_random(self, ctx, *, term: str=None):
  25. """Retrieves a random image from Imgur
  26. Search terms can be specified"""
  27. if term is None:
  28. task = functools.partial(self.imgur.gallery_random, page=0)
  29. else:
  30. task = functools.partial(self.imgur.gallery_search, term,
  31. advanced=None, sort='time',
  32. window='all', page=0)
  33. task = self.bot.loop.run_in_executor(None, task)
  34. try:
  35. results = await asyncio.wait_for(task, timeout=10)
  36. except asyncio.TimeoutError:
  37. await self.bot.say("Error: request timed out")
  38. else:
  39. if results:
  40. item = choice(results)
  41. link = item.gifv if hasattr(item, "gifv") else item.link
  42. await self.bot.say(link)
  43. else:
  44. await self.bot.say("Your search terms gave no results.")
  45. @_imgur.command(pass_context=True, name="search")
  46. async def imgur_search(self, ctx, *, term: str):
  47. """Searches Imgur for the specified term and returns up to 3 results"""
  48. task = functools.partial(self.imgur.gallery_search, term,
  49. advanced=None, sort='time',
  50. window='all', page=0)
  51. task = self.bot.loop.run_in_executor(None, task)
  52. try:
  53. results = await asyncio.wait_for(task, timeout=10)
  54. except asyncio.TimeoutError:
  55. await self.bot.say("Error: request timed out")
  56. else:
  57. if results:
  58. shuffle(results)
  59. msg = "Search results...\n"
  60. for r in results[:3]:
  61. msg += r.gifv if hasattr(r, "gifv") else r.link
  62. msg += "\n"
  63. await self.bot.say(msg)
  64. else:
  65. await self.bot.say("Your search terms gave no results.")
  66. @_imgur.command(pass_context=True, name="subreddit")
  67. async def imgur_subreddit(self, ctx, subreddit: str, sort_type: str="top", window: str="day"):
  68. """Gets images from the specified subreddit section
  69. Sort types: new, top
  70. Time windows: day, week, month, year, all"""
  71. sort_type = sort_type.lower()
  72. if sort_type not in ("new", "top"):
  73. await self.bot.say("Only 'new' and 'top' are a valid sort type.")
  74. return
  75. elif window not in ("day", "week", "month", "year", "all"):
  76. await self.bot.send_cmd_help(ctx)
  77. return
  78. if sort_type == "new":
  79. sort = "time"
  80. elif sort_type == "top":
  81. sort = "top"
  82. links = []
  83. task = functools.partial(self.imgur.subreddit_gallery, subreddit,
  84. sort=sort, window=window, page=0)
  85. task = self.bot.loop.run_in_executor(None, task)
  86. try:
  87. items = await asyncio.wait_for(task, timeout=10)
  88. except asyncio.TimeoutError:
  89. await self.bot.say("Error: request timed out")
  90. return
  91. for item in items[:3]:
  92. link = item.gifv if hasattr(item, "gifv") else item.link
  93. links.append("{}\n{}".format(item.title, link))
  94. if links:
  95. await self.bot.say("\n".join(links))
  96. else:
  97. await self.bot.say("No results found.")
  98. @commands.command(pass_context=True, no_pm=True)
  99. async def gif(self, ctx, *keywords):
  100. """Retrieves first search result from giphy"""
  101. if keywords:
  102. keywords = "+".join(keywords)
  103. else:
  104. await self.bot.send_cmd_help(ctx)
  105. return
  106. url = ("http://api.giphy.com/v1/gifs/search?&api_key={}&q={}"
  107. "".format(GIPHY_API_KEY, keywords))
  108. async with aiohttp.get(url) as r:
  109. result = await r.json()
  110. if r.status == 200:
  111. if result["data"]:
  112. await self.bot.say(result["data"][0]["url"])
  113. else:
  114. await self.bot.say("No results found.")
  115. else:
  116. await self.bot.say("Error contacting the API")
  117. @commands.command(pass_context=True, no_pm=True)
  118. async def gifr(self, ctx, *keywords):
  119. """Retrieves a random gif from a giphy search"""
  120. if keywords:
  121. keywords = "+".join(keywords)
  122. else:
  123. await self.bot.send_cmd_help(ctx)
  124. return
  125. url = ("http://api.giphy.com/v1/gifs/random?&api_key={}&tag={}"
  126. "".format(GIPHY_API_KEY, keywords))
  127. async with aiohttp.get(url) as r:
  128. result = await r.json()
  129. if r.status == 200:
  130. if result["data"]:
  131. await self.bot.say(result["data"]["url"])
  132. else:
  133. await self.bot.say("No results found.")
  134. else:
  135. await self.bot.say("Error contacting the API")
  136. def setup(bot):
  137. if ImgurClient is False:
  138. raise RuntimeError("You need the imgurpython module to use this.\n"
  139. "pip3 install imgurpython")
  140. bot.add_cog(Image(bot))