KiTTY, un bot Discord qui est un petit chat :) Il est basé sur une ancienne version du bot Red, sous Python 3.6 et qui a des fonctionnalités bien sympatiques !
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
Este repositório está arquivado. Você pode visualizar os arquivos e realizar clone, mas não poderá realizar push nem abrir issues e pull requests.

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