Advertisement
Guest User

main

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