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 !
Não pode escolher mais do que 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. Pode ver ficheiros e cloná-lo, mas não pode fazer envios ou lançar questões ou pedidos de integração.

198 linhas
7.0 KiB

  1. from discord.ext import commands
  2. from .utils.dataIO import dataIO
  3. from .utils import checks
  4. from .utils.chat_formatting import pagify, box
  5. import os
  6. import re
  7. class CustomCommands:
  8. """Custom commands
  9. Creates commands used to display text"""
  10. def __init__(self, bot):
  11. self.bot = bot
  12. self.file_path = "data/customcom/commands.json"
  13. self.c_commands = dataIO.load_json(self.file_path)
  14. @commands.group(aliases=["cc"], pass_context=True, no_pm=True)
  15. async def customcom(self, ctx):
  16. """Custom commands management"""
  17. if ctx.invoked_subcommand is None:
  18. await self.bot.send_cmd_help(ctx)
  19. @customcom.command(name="add", pass_context=True)
  20. @checks.mod_or_permissions(administrator=True)
  21. async def cc_add(self, ctx, command : str, *, text):
  22. """Adds a custom command
  23. Example:
  24. [p]customcom add yourcommand Text you want
  25. """
  26. server = ctx.message.server
  27. command = command.lower()
  28. if command in self.bot.commands:
  29. await self.bot.say("That command is already a standard command.")
  30. return
  31. if server.id not in self.c_commands:
  32. self.c_commands[server.id] = {}
  33. cmdlist = self.c_commands[server.id]
  34. if command not in cmdlist:
  35. cmdlist[command] = text
  36. self.c_commands[server.id] = cmdlist
  37. dataIO.save_json(self.file_path, self.c_commands)
  38. await self.bot.say("Custom command successfully added.")
  39. else:
  40. await self.bot.say("This command already exists. Use "
  41. "`{}customcom edit` to edit it."
  42. "".format(ctx.prefix))
  43. @customcom.command(name="edit", pass_context=True)
  44. @checks.mod_or_permissions(administrator=True)
  45. async def cc_edit(self, ctx, command : str, *, text):
  46. """Edits a custom command
  47. Example:
  48. [p]customcom edit yourcommand Text you want
  49. """
  50. server = ctx.message.server
  51. command = command.lower()
  52. if server.id in self.c_commands:
  53. cmdlist = self.c_commands[server.id]
  54. if command in cmdlist:
  55. cmdlist[command] = text
  56. self.c_commands[server.id] = cmdlist
  57. dataIO.save_json(self.file_path, self.c_commands)
  58. await self.bot.say("Custom command successfully edited.")
  59. else:
  60. await self.bot.say("That command doesn't exist. Use "
  61. "`{}customcom add` to add it."
  62. "".format(ctx.prefix))
  63. else:
  64. await self.bot.say("There are no custom commands in this server."
  65. " Use `{}customcom add` to start adding some."
  66. "".format(ctx.prefix))
  67. @customcom.command(name="delete", pass_context=True)
  68. @checks.mod_or_permissions(administrator=True)
  69. async def cc_delete(self, ctx, command : str):
  70. """Deletes a custom command
  71. Example:
  72. [p]customcom delete yourcommand"""
  73. server = ctx.message.server
  74. command = command.lower()
  75. if server.id in self.c_commands:
  76. cmdlist = self.c_commands[server.id]
  77. if command in cmdlist:
  78. cmdlist.pop(command, None)
  79. self.c_commands[server.id] = cmdlist
  80. dataIO.save_json(self.file_path, self.c_commands)
  81. await self.bot.say("Custom command successfully deleted.")
  82. else:
  83. await self.bot.say("That command doesn't exist.")
  84. else:
  85. await self.bot.say("There are no custom commands in this server."
  86. " Use `{}customcom add` to start adding some."
  87. "".format(ctx.prefix))
  88. @customcom.command(name="list", pass_context=True)
  89. async def cc_list(self, ctx):
  90. """Shows custom commands list"""
  91. server = ctx.message.server
  92. commands = self.c_commands.get(server.id, {})
  93. if not commands:
  94. await self.bot.say("There are no custom commands in this server."
  95. " Use `{}customcom add` to start adding some."
  96. "".format(ctx.prefix))
  97. return
  98. commands = ", ".join([ctx.prefix + c for c in sorted(commands)])
  99. commands = "Custom commands:\n\n" + commands
  100. if len(commands) < 1500:
  101. await self.bot.say(box(commands))
  102. else:
  103. for page in pagify(commands, delims=[" ", "\n"]):
  104. await self.bot.whisper(box(page))
  105. async def on_message(self, message):
  106. if len(message.content) < 2 or message.channel.is_private:
  107. return
  108. server = message.server
  109. prefix = self.get_prefix(message)
  110. if not prefix:
  111. return
  112. if server.id in self.c_commands and self.bot.user_allowed(message):
  113. cmdlist = self.c_commands[server.id]
  114. cmd = message.content[len(prefix):]
  115. if cmd in cmdlist:
  116. cmd = cmdlist[cmd]
  117. cmd = self.format_cc(cmd, message)
  118. await self.bot.send_message(message.channel, cmd)
  119. elif cmd.lower() in cmdlist:
  120. cmd = cmdlist[cmd.lower()]
  121. cmd = self.format_cc(cmd, message)
  122. await self.bot.send_message(message.channel, cmd)
  123. def get_prefix(self, message):
  124. for p in self.bot.settings.get_prefixes(message.server):
  125. if message.content.startswith(p):
  126. return p
  127. return False
  128. def format_cc(self, command, message):
  129. results = re.findall("\{([^}]+)\}", command)
  130. for result in results:
  131. param = self.transform_parameter(result, message)
  132. command = command.replace("{" + result + "}", param)
  133. return command
  134. def transform_parameter(self, result, message):
  135. """
  136. For security reasons only specific objects are allowed
  137. Internals are ignored
  138. """
  139. raw_result = "{" + result + "}"
  140. objects = {
  141. "message" : message,
  142. "author" : message.author,
  143. "channel" : message.channel,
  144. "server" : message.server
  145. }
  146. if result in objects:
  147. return str(objects[result])
  148. try:
  149. first, second = result.split(".")
  150. except ValueError:
  151. return raw_result
  152. if first in objects and not second.startswith("_"):
  153. first = objects[first]
  154. else:
  155. return raw_result
  156. return str(getattr(first, second, raw_result))
  157. def check_folders():
  158. if not os.path.exists("data/customcom"):
  159. print("Creating data/customcom folder...")
  160. os.makedirs("data/customcom")
  161. def check_files():
  162. f = "data/customcom/commands.json"
  163. if not dataIO.is_valid_json(f):
  164. print("Creating empty commands.json...")
  165. dataIO.save_json(f, {})
  166. def setup(bot):
  167. check_folders()
  168. check_files()
  169. bot.add_cog(CustomCommands(bot))