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 !
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

623 lines
22KB

  1. import asyncio
  2. import os
  3. import sys
  4. sys.path.insert(0, "lib")
  5. import logging
  6. import logging.handlers
  7. import traceback
  8. import datetime
  9. import subprocess
  10. try:
  11. from discord.ext import commands
  12. import discord
  13. except ImportError:
  14. print("Discord.py is not installed.\n")
  15. sys.exit(1)
  16. from cogs.utils.settings import Settings
  17. from cogs.utils.dataIO import dataIO
  18. from cogs.utils.chat_formatting import inline
  19. from collections import Counter
  20. from io import TextIOWrapper
  21. description = "KiTTY, a Discord bot powered by a cat."
  22. class Bot(commands.Bot):
  23. def __init__(self, *args, **kwargs):
  24. def prefix_manager(bot, message):
  25. """
  26. Returns prefixes of the message's server if set.
  27. If none are set or if the message's server is None
  28. it will return the global prefixes instead.
  29. Requires a Bot instance and a Message object to be
  30. passed as arguments.
  31. """
  32. return bot.settings.get_prefixes(message.server)
  33. self.counter = Counter()
  34. self.uptime = datetime.datetime.utcnow() # Refreshed before login
  35. self._message_modifiers = []
  36. self.settings = Settings()
  37. self._intro_displayed = False
  38. self._shutdown_mode = None
  39. self.logger = set_logger(self)
  40. self._last_exception = None
  41. self.oauth_url = ""
  42. if 'self_bot' in kwargs:
  43. self.settings.self_bot = kwargs['self_bot']
  44. else:
  45. kwargs['self_bot'] = self.settings.self_bot
  46. if self.settings.self_bot:
  47. kwargs['pm_help'] = False
  48. super().__init__(*args, command_prefix=prefix_manager, **kwargs)
  49. async def send_message(self, *args, **kwargs):
  50. if self._message_modifiers:
  51. if "content" in kwargs:
  52. pass
  53. elif len(args) == 2:
  54. args = list(args)
  55. kwargs["content"] = args.pop()
  56. else:
  57. return await super().send_message(*args, **kwargs)
  58. content = kwargs['content']
  59. for m in self._message_modifiers:
  60. try:
  61. content = str(m(content))
  62. except: # Faulty modifiers should not
  63. pass # break send_message
  64. kwargs['content'] = content
  65. return await super().send_message(*args, **kwargs)
  66. async def shutdown(self, *, restart=False):
  67. """Gracefully quits KiTTY with exit code 0
  68. If restart is True, the exit code will be 26 instead
  69. The launcher automatically restarts Red when that happens"""
  70. self._shutdown_mode = not restart
  71. await self.logout()
  72. def add_message_modifier(self, func):
  73. """
  74. Adds a message modifier to the bot
  75. A message modifier is a callable that accepts a message's
  76. content as the first positional argument.
  77. Before a message gets sent, func will get called with
  78. the message's content as the only argument. The message's
  79. content will then be modified to be the func's return
  80. value.
  81. Exceptions thrown by the callable will be catched and
  82. silenced.
  83. """
  84. if not callable(func):
  85. raise TypeError("The message modifier function "
  86. "must be a callable.")
  87. self._message_modifiers.append(func)
  88. def remove_message_modifier(self, func):
  89. """Removes a message modifier from the bot"""
  90. if func not in self._message_modifiers:
  91. raise RuntimeError("Function not present in the message "
  92. "modifiers.")
  93. self._message_modifiers.remove(func)
  94. def clear_message_modifiers(self):
  95. """Removes all message modifiers from the bot"""
  96. self._message_modifiers.clear()
  97. async def send_cmd_help(self, ctx):
  98. if ctx.invoked_subcommand:
  99. pages = self.formatter.format_help_for(ctx, ctx.invoked_subcommand)
  100. for page in pages:
  101. await self.send_message(ctx.message.channel, page)
  102. else:
  103. pages = self.formatter.format_help_for(ctx, ctx.command)
  104. for page in pages:
  105. await self.send_message(ctx.message.channel, page)
  106. def user_allowed(self, message):
  107. author = message.author
  108. if author.bot:
  109. return False
  110. if author == self.user:
  111. return self.settings.self_bot
  112. mod_cog = self.get_cog('Mod')
  113. global_ignores = self.get_cog('Owner').global_ignores
  114. if self.settings.owner == author.id:
  115. return True
  116. if author.id in global_ignores["blacklist"]:
  117. return False
  118. if global_ignores["whitelist"]:
  119. if author.id not in global_ignores["whitelist"]:
  120. return False
  121. if not message.channel.is_private:
  122. server = message.server
  123. names = (self.settings.get_server_admin(
  124. server), self.settings.get_server_mod(server))
  125. results = map(
  126. lambda name: discord.utils.get(author.roles, name=name),
  127. names)
  128. for r in results:
  129. if r is not None:
  130. return True
  131. if mod_cog is not None:
  132. if not message.channel.is_private:
  133. if message.server.id in mod_cog.ignore_list["SERVERS"]:
  134. return False
  135. if message.channel.id in mod_cog.ignore_list["CHANNELS"]:
  136. return False
  137. return True
  138. async def pip_install(self, name, *, timeout=None):
  139. """
  140. Installs a pip package in the local 'lib' folder in a thread safe
  141. way. On Mac systems the 'lib' folder is not used.
  142. Can specify the max seconds to wait for the task to complete
  143. Returns a bool indicating if the installation was successful
  144. """
  145. IS_MAC = sys.platform == "darwin"
  146. interpreter = sys.executable
  147. if interpreter is None:
  148. raise RuntimeError("Couldn't find Python's interpreter")
  149. args = [
  150. interpreter, "-m",
  151. "pip", "install",
  152. "--upgrade",
  153. "--target", "lib",
  154. name
  155. ]
  156. if IS_MAC: # --target is a problem on Homebrew. See PR #552
  157. args.remove("--target")
  158. args.remove("lib")
  159. def install():
  160. code = subprocess.call(args)
  161. sys.path_importer_cache = {}
  162. return not bool(code)
  163. response = self.loop.run_in_executor(None, install)
  164. return await asyncio.wait_for(response, timeout=timeout)
  165. class Formatter(commands.HelpFormatter):
  166. def __init__(self, *args, **kwargs):
  167. super().__init__(*args, **kwargs)
  168. def _add_subcommands_to_page(self, max_width, commands):
  169. for name, command in sorted(commands, key=lambda t: t[0]):
  170. if name in command.aliases:
  171. # skip aliases
  172. continue
  173. entry = ' {0:<{width}} {1}'.format(name, command.short_doc,
  174. width=max_width)
  175. shortened = self.shorten(entry)
  176. self._paginator.add_line(shortened)
  177. def initialize(bot_class=Bot, formatter_class=Formatter):
  178. formatter = formatter_class(show_check_failure=False)
  179. bot = bot_class(formatter=formatter, description=description, pm_help=None)
  180. import __main__
  181. __main__.send_cmd_help = bot.send_cmd_help # Backwards
  182. __main__.user_allowed = bot.user_allowed # compatibility
  183. __main__.settings = bot.settings # sucks
  184. async def get_oauth_url():
  185. try:
  186. data = await bot.application_info()
  187. except Exception as e:
  188. return "Couldn't retrieve invite link.Error: {}".format(e)
  189. return discord.utils.oauth_url(data.id)
  190. async def set_bot_owner():
  191. if bot.settings.self_bot:
  192. bot.settings.owner = bot.user.id
  193. return "[Selfbot mode]"
  194. if bot.settings.owner:
  195. owner = discord.utils.get(bot.get_all_members(),
  196. id=bot.settings.owner)
  197. if not owner:
  198. try:
  199. owner = await bot.get_user_info(bot.settings.owner)
  200. except:
  201. owner = None
  202. if not owner:
  203. owner = bot.settings.owner # Just the ID then
  204. return owner
  205. how_to = "Do `[p]set owner` in chat to set it"
  206. if bot.user.bot: # Can fetch owner
  207. try:
  208. data = await bot.application_info()
  209. bot.settings.owner = data.owner.id
  210. bot.settings.save_settings()
  211. return data.owner
  212. except:
  213. return "Failed to fetch owner. " + how_to
  214. else:
  215. return "Yet to be set. " + how_to
  216. @bot.event
  217. async def on_ready():
  218. if bot._intro_displayed:
  219. return
  220. bot._intro_displayed = True
  221. owner_cog = bot.get_cog('Owner')
  222. total_cogs = len(owner_cog._list_cogs())
  223. users = len(set(bot.get_all_members()))
  224. servers = len(bot.servers)
  225. channels = len([c for c in bot.get_all_channels()])
  226. login_time = datetime.datetime.utcnow() - bot.uptime
  227. login_time = login_time.seconds + login_time.microseconds/1E6
  228. print("Login successful. ({}ms)\n".format(login_time))
  229. owner = await set_bot_owner()
  230. print("------------------")
  231. print("KiTTY - Discord Cat")
  232. print("------------------")
  233. print(str(bot.user))
  234. print("\nConnected to:")
  235. print("{} servers".format(servers))
  236. print("{} channels".format(channels))
  237. print("{} users\n".format(users))
  238. prefix_label = 'Prefix'
  239. if len(bot.settings.prefixes) > 1:
  240. prefix_label += 'es'
  241. print("{}: {}".format(prefix_label, " ".join(bot.settings.prefixes)))
  242. print("Owner: " + str(owner))
  243. print("{}/{} active cogs with {} commands".format(
  244. len(bot.cogs), total_cogs, len(bot.commands)))
  245. print("-----------------")
  246. if bot.settings.token and not bot.settings.self_bot:
  247. print("\nUse this url to bring your bot to a server:")
  248. url = await get_oauth_url()
  249. bot.oauth_url = url
  250. print(url)
  251. await bot.get_cog('Owner').disable_commands()
  252. @bot.event
  253. async def on_resumed():
  254. bot.counter["session_resumed"] += 1
  255. @bot.event
  256. async def on_command(command, ctx):
  257. bot.counter["processed_commands"] += 1
  258. @bot.event
  259. async def on_message(message):
  260. bot.counter["messages_read"] += 1
  261. if bot.user_allowed(message):
  262. await bot.process_commands(message)
  263. @bot.event
  264. async def on_command_error(error, ctx):
  265. channel = ctx.message.channel
  266. if isinstance(error, commands.MissingRequiredArgument):
  267. await bot.send_cmd_help(ctx)
  268. elif isinstance(error, commands.BadArgument):
  269. await bot.send_cmd_help(ctx)
  270. elif isinstance(error, commands.DisabledCommand):
  271. await bot.send_message(channel, "This command is disabled.")
  272. elif isinstance(error, commands.CommandInvokeError):
  273. # A bit hacky, couldn't find a better way
  274. no_dms = "Cannot send messages to this user"
  275. is_help_cmd = ctx.command.qualified_name == "help"
  276. is_forbidden = isinstance(error.original, discord.Forbidden)
  277. if is_help_cmd and is_forbidden and error.original.text == no_dms:
  278. msg = ("I couldn't send the help message to you in DM. Either"
  279. " you blocked me or you disabled DMs in this server.")
  280. await bot.send_message(channel, msg)
  281. return
  282. bot.logger.exception("Exception in command '{}'".format(
  283. ctx.command.qualified_name), exc_info=error.original)
  284. message = ("Error in command '{}'. Check your console or "
  285. "logs for details."
  286. "".format(ctx.command.qualified_name))
  287. log = ("Exception in command '{}'\n"
  288. "".format(ctx.command.qualified_name))
  289. log += "".join(traceback.format_exception(type(error), error,
  290. error.__traceback__))
  291. bot._last_exception = log
  292. await ctx.bot.send_message(channel, inline(message))
  293. elif isinstance(error, commands.CommandNotFound):
  294. pass
  295. elif isinstance(error, commands.CheckFailure):
  296. pass
  297. elif isinstance(error, commands.NoPrivateMessage):
  298. await bot.send_message(channel, "That command is not "
  299. "available in DMs.")
  300. elif isinstance(error, commands.CommandOnCooldown):
  301. await bot.send_message(channel, "This command is on cooldown. "
  302. "Try again in {:.2f}s"
  303. "".format(error.retry_after))
  304. else:
  305. bot.logger.exception(type(error).__name__, exc_info=error)
  306. return bot
  307. def check_folders():
  308. folders = ("data", "data/red", "cogs", "cogs/utils")
  309. for folder in folders:
  310. if not os.path.exists(folder):
  311. print("Creating " + folder + " folder...")
  312. os.makedirs(folder)
  313. def interactive_setup(settings):
  314. first_run = settings.bot_settings == settings.default_settings
  315. if first_run:
  316. print("KiTTY - First run configuration\n")
  317. print("If you haven't already, create a new account:\n"
  318. "https://twentysix26.github.io/Red-Docs/red_guide_bot_accounts/"
  319. "#creating-a-new-bot-account")
  320. print("and obtain your bot's token like described.")
  321. if not settings.login_credentials:
  322. print("\nInsert your bot's token:")
  323. while settings.token is None and settings.email is None:
  324. choice = input("> ")
  325. if "@" not in choice and len(choice) >= 50: # Assuming token
  326. settings.token = choice
  327. elif "@" in choice:
  328. settings.email = choice
  329. settings.password = input("\nPassword> ")
  330. else:
  331. print("That doesn't look like a valid token.")
  332. settings.save_settings()
  333. if not settings.prefixes:
  334. print("\nChoose a prefix. A prefix is what you type before a command."
  335. "\nA typical prefix would be the exclamation mark.\n"
  336. "Can be multiple characters. You will be able to change it "
  337. "later and add more of them.\nChoose your prefix:")
  338. confirmation = False
  339. while confirmation is False:
  340. new_prefix = ensure_reply("\nPrefix> ").strip()
  341. print("\nAre you sure you want {0} as your prefix?\nYou "
  342. "will be able to issue commands like this: {0}help"
  343. "\nType yes to confirm or no to change it".format(
  344. new_prefix))
  345. confirmation = get_answer()
  346. settings.prefixes = [new_prefix]
  347. settings.save_settings()
  348. if first_run:
  349. print("\nInput the admin role's name. Anyone with this role in Discord"
  350. " will be able to use the bot's admin commands")
  351. print("Leave blank for default name (Transistor)")
  352. settings.default_admin = input("\nAdmin role> ")
  353. if settings.default_admin == "":
  354. settings.default_admin = "Transistor"
  355. settings.save_settings()
  356. print("\nInput the moderator role's name. Anyone with this role in"
  357. " Discord will be able to use the bot's mod commands")
  358. print("Leave blank for default name (Process)")
  359. settings.default_mod = input("\nModerator role> ")
  360. if settings.default_mod == "":
  361. settings.default_mod = "Process"
  362. settings.save_settings()
  363. print("\nThe configuration is done. Leave this window always open to"
  364. " keep Red online.\nAll commands will have to be issued through"
  365. " Discord's chat, *this window will now be read only*.\n"
  366. "Please read this guide for a good overview on how Red works:\n"
  367. "https://twentysix26.github.io/Red-Docs/red_getting_started/\n"
  368. "Press enter to continue")
  369. input("\n")
  370. def set_logger(bot):
  371. logger = logging.getLogger("red")
  372. logger.setLevel(logging.INFO)
  373. red_format = logging.Formatter(
  374. '%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
  375. '%(message)s',
  376. datefmt="[%d/%m/%Y %H:%M]")
  377. stdout_handler = logging.StreamHandler(sys.stdout)
  378. stdout_handler.setFormatter(red_format)
  379. if bot.settings.debug:
  380. stdout_handler.setLevel(logging.DEBUG)
  381. logger.setLevel(logging.DEBUG)
  382. else:
  383. stdout_handler.setLevel(logging.INFO)
  384. logger.setLevel(logging.INFO)
  385. fhandler = logging.handlers.RotatingFileHandler(
  386. filename='data/red/red.log', encoding='utf-8', mode='a',
  387. maxBytes=10**7, backupCount=5)
  388. fhandler.setFormatter(red_format)
  389. logger.addHandler(fhandler)
  390. logger.addHandler(stdout_handler)
  391. dpy_logger = logging.getLogger("discord")
  392. if bot.settings.debug:
  393. dpy_logger.setLevel(logging.DEBUG)
  394. else:
  395. dpy_logger.setLevel(logging.WARNING)
  396. handler = logging.FileHandler(
  397. filename='data/red/discord.log', encoding='utf-8', mode='a')
  398. handler.setFormatter(logging.Formatter(
  399. '%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
  400. '%(message)s',
  401. datefmt="[%d/%m/%Y %H:%M]"))
  402. dpy_logger.addHandler(handler)
  403. return logger
  404. def ensure_reply(msg):
  405. choice = ""
  406. while choice == "":
  407. choice = input(msg)
  408. return choice
  409. def get_answer():
  410. choices = ("yes", "y", "no", "n")
  411. c = ""
  412. while c not in choices:
  413. c = input(">").lower()
  414. if c.startswith("y"):
  415. return True
  416. else:
  417. return False
  418. def set_cog(cog, value): # TODO: move this out of red.py
  419. data = dataIO.load_json("data/red/cogs.json")
  420. data[cog] = value
  421. dataIO.save_json("data/red/cogs.json", data)
  422. def load_cogs(bot):
  423. defaults = ("alias", "audio", "customcom", "downloader", "economy",
  424. "general", "image", "mod", "streams", "trivia")
  425. try:
  426. registry = dataIO.load_json("data/red/cogs.json")
  427. except:
  428. registry = {}
  429. bot.load_extension('cogs.owner')
  430. owner_cog = bot.get_cog('Owner')
  431. if owner_cog is None:
  432. print("The owner cog is missing. It contains core functions without "
  433. "which Red cannot function. Reinstall.")
  434. exit(1)
  435. if bot.settings._no_cogs:
  436. bot.logger.debug("Skipping initial cogs loading (--no-cogs)")
  437. if not os.path.isfile("data/red/cogs.json"):
  438. dataIO.save_json("data/red/cogs.json", {})
  439. return
  440. failed = []
  441. extensions = owner_cog._list_cogs()
  442. if not registry: # All default cogs enabled by default
  443. for ext in defaults:
  444. registry["cogs." + ext] = True
  445. for extension in extensions:
  446. if extension.lower() == "cogs.owner":
  447. continue
  448. to_load = registry.get(extension, False)
  449. if to_load:
  450. try:
  451. owner_cog._load_cog(extension)
  452. except Exception as e:
  453. print("{}: {}".format(e.__class__.__name__, str(e)))
  454. bot.logger.exception(e)
  455. failed.append(extension)
  456. registry[extension] = False
  457. dataIO.save_json("data/red/cogs.json", registry)
  458. if failed:
  459. print("\nFailed to load: {}\n".format(" ".join(failed)))
  460. def main(bot):
  461. check_folders()
  462. if not bot.settings.no_prompt:
  463. interactive_setup(bot.settings)
  464. load_cogs(bot)
  465. if bot.settings._dry_run:
  466. print("Quitting: dry run")
  467. bot._shutdown_mode = True
  468. exit(0)
  469. print("Logging into Discord...")
  470. bot.uptime = datetime.datetime.utcnow()
  471. if bot.settings.login_credentials:
  472. yield from bot.login(*bot.settings.login_credentials,
  473. bot=not bot.settings.self_bot)
  474. else:
  475. print("No credentials available to login.")
  476. raise RuntimeError()
  477. yield from bot.connect()
  478. if __name__ == '__main__':
  479. sys.stdout = TextIOWrapper(sys.stdout.detach(),
  480. encoding=sys.stdout.encoding,
  481. errors="replace",
  482. line_buffering=True)
  483. bot = initialize()
  484. loop = asyncio.get_event_loop()
  485. try:
  486. loop.run_until_complete(main(bot))
  487. except discord.LoginFailure:
  488. bot.logger.error(traceback.format_exc())
  489. if not bot.settings.no_prompt:
  490. choice = input("Invalid login credentials. If they worked before "
  491. "Discord might be having temporary technical "
  492. "issues.\nIn this case, press enter and try again "
  493. "later.\nOtherwise you can type 'reset' to reset "
  494. "the current credentials and set them again the "
  495. "next start.\n> ")
  496. if choice.lower().strip() == "reset":
  497. bot.settings.token = None
  498. bot.settings.email = None
  499. bot.settings.password = None
  500. bot.settings.save_settings()
  501. print("Login credentials have been reset.")
  502. except KeyboardInterrupt:
  503. loop.run_until_complete(bot.logout())
  504. except Exception as e:
  505. bot.logger.exception("Fatal exception, attempting graceful logout",
  506. exc_info=e)
  507. loop.run_until_complete(bot.logout())
  508. finally:
  509. loop.close()
  510. if bot._shutdown_mode is True:
  511. exit(0)
  512. elif bot._shutdown_mode is False:
  513. exit(26) # Restart
  514. else:
  515. exit(1)