Advertisement
Guest User

Untitled

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