Advertisement
Guest User

Untitled

a guest
Jun 17th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.37 KB | None | 0 0
  1. from random import choice, randint
  2. import random
  3. import aiohttp
  4. import discord
  5. import asyncio
  6. from discord.ext import commands
  7. from .utils.chat_formatting import *
  8. from .utils.dataIO import dataIO
  9. from cogs.utils import checks
  10. import os
  11. import string
  12.  
  13. class AddImage:
  14. def __init__(self, bot):
  15. self.bot = bot
  16. self.images = dataIO.load_json("data/addimage/settings.json")
  17. self.session = aiohttp.ClientSession(loop=self.bot.loop)
  18.  
  19. def __unload(self):
  20. self.session.close()
  21.  
  22. async def first_word(self, msg):
  23. return msg.split(" ")[0].lower()
  24.  
  25. async def get_prefix(self, server, msg):
  26. prefixes = self.bot.settings.get_prefixes(server)
  27. for p in prefixes:
  28. if msg.startswith(p):
  29. return p
  30. return None
  31.  
  32. async def part_of_existing_command(self, alias, server):
  33. '''Command or alias'''
  34. for command in self.bot.commands:
  35. if alias.lower() == command.lower():
  36. return True
  37. return False
  38.  
  39. async def make_server_folder(self, server):
  40. if not os.path.exists("data/addimage/{}".format(server.id)):
  41. print("Creating server folder")
  42. os.makedirs("data/addimage/{}".format(server.id))
  43.  
  44. async def on_message(self, message):
  45. if len(message.content) < 2 or message.channel.is_private:
  46. return
  47.  
  48. msg = message.content
  49. server = message.server
  50. channel = message.channel
  51. prefix = await self.get_prefix(server, msg)
  52. if not prefix:
  53. return
  54. alias = await self.first_word(msg[len(prefix):])
  55.  
  56. if alias in self.images["global"]:
  57. image = self.images["global"][alias]
  58. await self.bot.send_typing(channel)
  59. await self.bot.send_file(channel, image)
  60. if server.id not in self.images["server"]:
  61. return
  62. elif alias in self.images["server"][server.id]:
  63. image = self.images["server"][server.id][alias]
  64. await self.bot.send_typing(channel)
  65. await self.bot.send_file(channel, image)
  66.  
  67. async def check_command_exists(self, command, server):
  68. if command in self.images["server"][server.id]:
  69. return True
  70. elif await self.part_of_existing_command(command, server):
  71. return True
  72. elif command in self.images["global"]:
  73. return True
  74. else:
  75. return False
  76.  
  77. @commands.group(pass_context=True, no_pm=True, invoke_without_command=True)
  78. async def listimages(self, ctx):
  79. """List images for the server or globally"""
  80. if ctx.invoked_subcommand is None:
  81. await ctx.invoke(self.listimages_server)
  82.  
  83. @listimages.command(pass_context=True, name="server")
  84. async def listimages_server(self, ctx):
  85. """List images added to bot"""
  86. msg = ""
  87. server = ctx.message.server
  88. channel = ctx.message.channel
  89. if server.id not in self.images["server"]:
  90. await self.bot.say("{} does not have any images saved!".format(server.name))
  91. return
  92.  
  93. for image in self.images["server"][server.id].keys():
  94. msg += image + ", "
  95. em = discord.Embed(timestamp=ctx.message.timestamp)
  96. em.description = msg[:len(msg)-2]
  97. em.set_author(name=server.name, icon_url=server.icon_url)
  98. await self.bot.send_message(channel, embed=em)
  99.  
  100. @listimages.command(pass_context=True, name="global", aliases=["all"])
  101. async def listimages_global(self, ctx):
  102. """List images added to bot"""
  103. msg = ""
  104. server = ctx.message.server
  105. channel = ctx.message.channel
  106.  
  107. for image in self.images["global"].keys():
  108. msg += image + ", "
  109. em = discord.Embed(timestamp=ctx.message.timestamp)
  110. em.description = msg[:len(msg)-2]
  111. em.set_author(name=self.bot.user.display_name, icon_url=self.bot.user.avatar_url)
  112. await self.bot.send_message(channel, embed=em)
  113.  
  114. @commands.group(pass_context=True, no_pm=True, invoke_without_command=True)
  115. @checks.serverowner_or_permissions(moderator=True)
  116. async def remimage(self, ctx, cmd):
  117. """Remove images from server"""
  118. if ctx.invoked_subcommand is None:
  119. await ctx.invoke(self.rem_image_server, cmd=cmd)
  120.  
  121. @checks.serverowner_or_permissions(moderator=True)
  122. @remimage.command(pass_context=True, name="server")
  123. async def rem_image_server(self, ctx, cmd):
  124. """Remove a selected images"""
  125. author = ctx.message.author
  126. server = ctx.message.server
  127. channel = ctx.message.channel
  128. cmd = cmd.lower()
  129. if server.id not in self.images["server"]:
  130. await self.bot.say("I have no images on this server!")
  131. return
  132. if cmd not in self.images["server"][server.id]:
  133. await self.bot.say("{} is not an image for this server!".format(cmd))
  134. return
  135. os.remove(self.images["server"][server.id][cmd])
  136. del self.images["server"][server.id][cmd]
  137. dataIO.save_json("data/addimage/settings.json", self.images)
  138. await self.bot.say("{} has been deleted from this server!".format(cmd))
  139.  
  140. @checks.serverowner_or_permissions(moderator=True)
  141. @remimage.command(hidden=True, pass_context=True, name="global")
  142. async def rem_image_global(self, ctx, cmd):
  143. """Remove a selected images"""
  144. author = ctx.message.author
  145. server = ctx.message.server
  146. channel = ctx.message.channel
  147. cmd = cmd.lower()
  148. if cmd not in self.images["global"]:
  149. await self.bot.say("{} is not a global image!".format(cmd))
  150. return
  151. os.remove(self.images["global"][cmd])
  152. del self.images["global"][cmd]
  153. dataIO.save_json("data/addimage/settings.json", self.images)
  154. await self.bot.say("{} has been deleted globally!".format(cmd))
  155.  
  156.  
  157. @commands.group(pass_context=True, no_pm=True, invoke_without_command=True)
  158. @checks.serverowner_or_permissions(moderator=True)
  159. async def addimage(self, ctx, cmd):
  160. """Add images for the bot to upload per server"""
  161. if ctx.invoked_subcommand is None:
  162. await ctx.invoke(self.add_image_server, cmd=cmd)
  163.  
  164. @checks.serverowner_or_permissions(moderator=True)
  165. @addimage.command(pass_context=True, name="server")
  166. async def add_image_server(self, ctx, cmd):
  167. """Add an image to direct upload."""
  168. author = ctx.message.author
  169. server = ctx.message.server
  170. channel = ctx.message.channel
  171. prefix = await self.get_prefix(server, ctx.message.content)
  172. msg = ctx.message
  173. if server.id not in self.images["server"]:
  174. await self.make_server_folder(server)
  175. self.images["server"][server.id] = {}
  176. if cmd is not "":
  177. if await self.check_command_exists(cmd, server):
  178. await self.bot.say("{} is already in the list, try another!".format(cmd))
  179. return
  180. else:
  181. await self.bot.say("{} added as the command!".format(cmd))
  182. await self.bot.say("Upload an image for me to use!")
  183. while msg is not None:
  184. msg = await self.bot.wait_for_message(author=author, timeout=60)
  185. if msg is None:
  186. await self.bot.say("No image uploaded then.")
  187. break
  188.  
  189. if msg.attachments != []:
  190. filename = msg.attachments[0]["filename"][-5:]
  191.  
  192. directory = "data/addimage/{}/{}".format(server.id, filename)
  193. if cmd is None:
  194. cmd = filename.split(".")[0]
  195. cmd = cmd.lower()
  196. seed = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
  197. directory = "data/addimage/{}/{}-{}".format(server.id, seed, filename)
  198. self.images["server"][server.id][cmd] = directory
  199. dataIO.save_json("data/addimage/settings.json", self.images)
  200. async with self.session.get(msg.attachments[0]["url"]) as resp:
  201. test = await resp.read()
  202. with open(self.images["server"][server.id][cmd], "wb") as f:
  203. f.write(test)
  204. await self.bot.send_message(channel, "{} has been added to my files!"
  205. .format(cmd))
  206. break
  207. if msg.content.lower().strip() == "exit":
  208. await self.bot.say("Your changes have been saved.")
  209. break
  210.  
  211. @checks.serverowner_or_permissions(moderator=True)
  212. @addimage.command(hidden=True, pass_context=True, name="global")
  213. async def add_image_global(self, ctx, cmd):
  214. """Add an image to direct upload."""
  215. author = ctx.message.author
  216. server = ctx.message.server
  217. channel = ctx.message.channel
  218. prefix = await self.get_prefix(server, ctx.message.content)
  219. msg = ctx.message
  220. if cmd is not "":
  221. if await self.check_command_exists(cmd, server):
  222. await self.bot.say("{} is already in the list, try another!".format(cmd))
  223. return
  224. else:
  225. await self.bot.say("{} added as the command!".format(cmd))
  226. await self.bot.say("Upload an image for me to use!")
  227. while msg is not None:
  228. msg = await self.bot.wait_for_message(author=author, timeout=60)
  229. if msg is None:
  230. await self.bot.say("No image uploaded then.")
  231. break
  232.  
  233. if msg.attachments != []:
  234. filename = msg.attachments[0]["filename"][-5:]
  235.  
  236. directory = "data/addimage/global/{}".format(filename)
  237. if cmd is None:
  238. cmd = filename.split(".")[0]
  239. cmd = cmd.lower()
  240. seed = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
  241. directory = "data/addimage/{}/{}-{}".format(server.id, seed, filename)
  242. self.images["global"][cmd] = directory
  243. dataIO.save_json("data/addimage/settings.json", self.images)
  244. async with self.session.get(msg.attachments[0]["url"]) as resp:
  245. test = await resp.read()
  246. with open(self.images["global"][cmd], "wb") as f:
  247. f.write(test)
  248. await self.bot.send_message(channel, "{} has been added to my files!"
  249. .format(cmd))
  250. break
  251. if msg.content.lower().strip() == "exit":
  252. await self.bot.say("Your changes have been saved.")
  253. break
  254.  
  255. def check_folder():
  256. if not os.path.exists("data/addimage"):
  257. print("Creating data/addimage folder")
  258. os.makedirs("data/addimage")
  259. if not os.path.exists("data/addimage/global"):
  260. print("Creating data/addimage/global folder")
  261. os.makedirs("data/addimage/global")
  262.  
  263. def check_file():
  264. data = {"global":{}, "server":{}}
  265. f = "data/addimage/settings.json"
  266. if not dataIO.is_valid_json(f):
  267. print("Creating default settings.json...")
  268. dataIO.save_json(f, data)
  269.  
  270.  
  271. def setup(bot):
  272. check_folder()
  273. check_file()
  274. n = AddImage(bot)
  275. bot.add_cog(n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement