我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.py()。
def on_ready(self): """ A listener for the event in which the bot is ready to work. """ lib.log("") lib.log("Using discord.py version: " + discord.__version__) lib.log("Logged in as :") lib.log("\t" + self.bot.user.name) lib.log("\t" + self.bot.user.id) lib.log("") await self.bot.update_status() message = "**[{}]** {}"\ .format(config.get_config().get_str('version'), config.get_config().get_str('startup_msg')) for server in self.bot.servers: await self.bot.send_message(server, message)
def on_command_error(self, error, ctx): ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure, commands.CommandNotFound, commands.UserInputError, discord.HTTPException) error = getattr(error, 'original', error) if isinstance(error, ignored): return if ctx.message.server: fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})' else: fmt = 'Channel: {0} (ID: {0.id})' exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False) description = '```py\n%s\n```' % ''.join(exc) time = datetime.datetime.utcnow() name = ctx.command.qualified_name author = '{0} (ID: {0.id})'.format(ctx.message.author) location = fmt.format(ctx.message.channel, ctx.message.server) message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description) self.bot.logs['discord'].critical(message)
def about(self, ctx): '''About me''' from clients import application_info changes = os.popen(r'git show -s HEAD~3..HEAD --format="[`%h`](https://github.com/Harmon758/Harmonbot/commit/%H) %s (%cr)"').read().strip() embed = discord.Embed(title = "About Me", color = clients.bot_color) embed.description = "[Changelog (Harmonbot Server)]({})\n[Invite Link]({})".format(clients.changelog, discord.utils.oauth_url(application_info.id)) # avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url # embed.set_author(name = ctx.message.author.display_name, icon_url = avatar) avatar = self.bot.user.avatar_url or self.bot.user.default_avatar_url # embed.set_thumbnail(url = avatar) embed.set_author(name = "Harmonbot (Discord ID: {})".format(self.bot.user.id), icon_url = avatar) if changes: embed.add_field(name = "Latest Changes:", value = changes, inline = False) embed.add_field(name = "Created on:", value = "February 10th, 2016") embed.add_field(name = "Version", value = clients.version) embed.add_field(name = "Library", value = "[discord.py](https://github.com/Rapptz/discord.py) v{0}\n([Python](https://www.python.org/) v{1.major}.{1.minor}.{1.micro})".format(discord.__version__, sys.version_info)) me = discord.utils.get(self.bot.get_all_members(), id = clients.owner_id) avatar = me.default_avatar_url if not me.avatar else me.avatar_url embed.set_footer(text = "Developer/Owner: {0} (Discord ID: {0.id})".format(me), icon_url = avatar) await self.bot.reply("", embed = embed) await self.bot.say("Changelog (Harmonbot Server): {}".format(clients.changelog))
def source(self, ctx, *, command: BotCommand): """Displays the source code for a particular command. There is a per-user, 2 times per 5 seconds cooldown in order to prevent spam. """ paginator = commands.Paginator(prefix='```py') for line in inspect.getsourcelines(command.callback)[0]: # inspect.getsourcelines returns the lines with the newlines at the # end. However, the paginator will add it's own newlines when joining # up the lines. We don't want to have double lines. So we have to # strip off the ends. # # Also, because we prefix each page with a code block (```), we need # to make sure that other triple-backticks don't prematurely end the # block. paginator.add_line(line.rstrip().replace('`', '\u200b`')) for p in paginator.pages: await ctx.send(p) # Credits to Reina
def convert(self, ctx, arg): match = self._get_id_match(arg) state = ctx._state if match: guild = ctx.bot.get_guild(int(match.group(1))) if guild: return guild if self.case_sensitive: guilds = [g for g in state._guilds.values() if g.name == arg] else: lowered = arg.lower() guilds = [g for g in state._guilds.values() if g.name.lower() == lowered] return await ctx.disambiguate(guilds) # A mapping for the discord.py class and it's corresponding searcher.
def join(self, invite_url: discord.Invite=None): """Joins new server""" if hasattr(self.bot.user, 'bot') and self.bot.user.bot is True: # Check to ensure they're using updated discord.py msg = ("I have a **BOT** tag, so I must be invited with an OAuth2" " link:\nFor more information: " "https://twentysix26.github.io/" "Red-Docs/red_guide_bot_accounts/#bot-invites") await self.bot.say(msg) if hasattr(self.bot, 'oauth_url'): await self.bot.whisper("Here's my OAUTH2 link:\n{}".format( self.bot.oauth_url)) return if invite_url is None: await self.bot.say("I need a Discord Invite link for the " "server you want me to join.") return try: await self.bot.accept_invite(invite_url) await self.bot.say("Server joined.") log.debug("We just joined {}".format(invite_url)) except discord.NotFound: await self.bot.say("The invite was invalid or expired.") except discord.HTTPException: await self.bot.say("I wasn't able to accept the invite." " Try again.")
def on_ready(self): """ Called once a connection has been established """ log.ready("Running discord.py version: " + discord.__version__) log.ready("Connected to Discord!") log.info("Logged in as {0.name}.{0.discriminator} ({0.id})" .format(self.user)) log.info("Prefix: " + self.config.prefix) log.info("SelfBot: " + ['true', 'false'][self.config.useToken]) self.loop.create_task(self.saveloop()) log.ready("Autosave coroutine running...") # self.loop.create_task(self.banloop()) log.ready("Auto-unban coroutine running...") if self.config.get("mysql") is not None: self.loop.create_task(self.askPatchLoop()) log.ready("MOTD system running...") pass else: log.warn("No mysql configuration in config.yaml," + "motd features are disabled") return
def wait_for_reaction_remove(bot, emoji=None, *, user=None, timeout=None, message=None, check=None): """Waits for a reaction to be removed by a user from a message within a time period. Made to act like other discord.py wait_for_* functions but is not fully implemented. Because of that, wait_for_reaction_remove(self, emoji: list, user, message, timeout=None) is a better representation of this function's def returns the actual event or None if timeout """ if not (emoji and message) or isinstance(emoji, str): raise NotImplementedError("wait_for_reaction_remove(self, emoji, " "message, user=None, timeout=None, " "check=None) is a better representation " "of this function definition") remove_event = ReactionRemoveEvent(emoji, user, check=check) _reaction_remove_events[message.id] = remove_event done, pending = await asyncio.wait([remove_event.wait()], timeout=timeout) res = _reaction_remove_events.pop(message.id) try: return done.pop().result() and res except: return None
def about(self): """Tells you information about the bot itself.""" revision = os.popen(r'git show -s HEAD --format="%s (%cr)"').read().strip() result = ['**About Me:**'] result.append('- Author: Mirai [ID: 173502573205127170]') result.append('- Library: discord.py (Python)') result.append('- Latest Change: {}'.format(revision)) result.append('- Uptime: {}'.format(self.get_bot_uptime())) result.append('- Servers: {}'.format(len(self.bot.servers))) result.append('- Commands Run: {}'.format(sum(self.bot.commands_used.values()))) # statistics total_members = sum(len(s.members) for s in self.bot.servers) total_online = sum(1 for m in self.bot.get_all_members() if m.status != discord.Status.offline) unique_members = set(self.bot.get_all_members()) unique_online = sum(1 for m in unique_members if m.status != discord.Status.offline) channel_types = Counter(c.type for c in self.bot.get_all_channels()) voice = channel_types[discord.ChannelType.voice] text = channel_types[discord.ChannelType.text] result.append('- Total Members: {} ({} online)'.format(total_members, total_online)) result.append('- Unique Members: {} ({} online)'.format(len(unique_members), unique_online)) result.append('- {} text channels, {} voice channels'.format(text, voice)) result.append('') result.append('Luna server: https://discord.gg/PDmtxWq') await self.bot.say('\n'.join(result))
def about(self, ctx): """Infos about the SelfBot.""" embed = discord.Embed() embed.set_author(name="Igneel's SelfBot", url="https://igneeldxd.github.io/Discord-SelfBot/") embed.description = "https://igneeldxd.github.io/Discord-SelfBot/\nThis is a Selfbot written by IgneelDxD#6666\nFor support or feedback you can join my [Server](https://discord.gg/DJK8h3n)" embed.colour = discord.Color.purple() async with aiohttp.ClientSession() as cs: async with cs.get("https://api.github.com/repos/IgneelDxD/Discord-SelfBot/commits") as resp: result = json.loads(await resp.text()) form = '[``{0}``](https://github.com/IgneelDxD/Discord-SelfBot/commit/{0}) {1} ({2})' com0 = form.format(result[0]['sha'][:7], result[0]['commit']['message'], getAgo(parser.parse(result[0]['commit']['author']['date'], ignoretz=True))) com1 = form.format(result[1]['sha'][:7], result[1]['commit']['message'], getAgo(parser.parse(result[1]['commit']['author']['date'], ignoretz=True))) embed.add_field(name='Latest Changes', value=f'{com0}\n{com1}') embed.set_thumbnail(url="https://i.imgur.com/cD51k3R.png") embed.set_footer(text='Made with discord.py | rewrite is the future!', icon_url='https://i.imgur.com/MyEXmz8.png') await edit(ctx, embed=embed) # User info on Server
def on_ready(): print('\nLogin Details:') print('---------------------') print('Logged in as:') print(client.user.name) print('Bot User ID:') print(client.user.id) print('---------------------\n') print('---------------------------------------') print('Running discord.py version ' + discord.__version__) print('---------------------------------------\n') print('STATUS: Finished Loading!') print('-------------------------\n') print('-----------------------------------------') print('Authors: AXAz0r, Awakening, Battlemuffins') print('Bot Version: Beta 0.12b') print('Build Date: 9. August 2016.') print('-----------------------------------------\n')
def repl(self, ctx): variables = {"self" : self, "ctx" : ctx, "last" : None} await self.bot.embed_reply("Enter code to execute or evaluate\n`exit` or `quit` to exit") while True: message = await self.bot.wait_for_message(author = ctx.message.author, channel = ctx.message.channel, check = lambda m: m.content.startswith('`')) if message.content.startswith("```py") and message.content.endswith("```"): code = message.content[5:-3].strip(" \n") else: code = message.content.strip("` \n") if code in ("quit", "exit", "quit()", "exit()"): await self.bot.embed_reply('Exiting repl') return function = exec if '\n' not in code: try: code = compile(code, "<repl>", "eval") except SyntaxError: pass else: function = eval if function is exec: try: code = compile(code, "<repl>", "exec") except SyntaxError as e: await self.bot.reply(clients.py_code_block.format("{0.text}{1:>{0.offset}}\n{2}: {0}".format(e, '^', type(e).__name__))) continue try: result = function(code, variables) if inspect.isawaitable(result): result = await result except: await self.bot.reply(clients.py_code_block.format("\n".join(traceback.format_exc().splitlines()[-2:]).strip())) else: if function is eval: try: await self.bot.reply(clients.py_code_block.format(result)) except Exception as e: await self.bot.reply(clients.py_code_block.format("{}: {}".format(type(e).__name__, e))) variables["last"] = result
def source(self, command : str = None): ''' Displays my full source code or for a specific command To display the source code of a subcommand you have to separate it by periods, e.g. tag.create for the create subcommand of the tag command Based on [R. Danny](https://github.com/Rapptz/RoboDanny)'s source command ''' source_url = "https://github.com/Harmon758/Harmonbot" if command is None: await self.bot.embed_reply(source_url) return code_path = command.split('.') obj = self.bot for cmd in code_path: try: obj = obj.get_command(cmd) if obj is None: await self.bot.embed_reply("Could not find the command " + cmd) return except AttributeError: await self.bot.embed_reply("{0.name} command has no subcommands".format(obj)) return # since we found the command we're looking for, presumably anyway, let's # try to access the code itself src = obj.callback.__code__ lines, firstlineno = inspect.getsourcelines(src) ## if not obj.callback.__module__.startswith("discord"): # not a built-in command location = os.path.relpath(src.co_filename).replace('\\', '/') ## else: ## location = obj.callback.__module__.replace('.', '/') + ".py" ## source_url = "https://github.com/Rapptz/discord.py" final_url = '<{}/blob/master/Discord/{}#L{}-L{}>'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1) await self.bot.embed_reply(final_url)
def about(self, ctx): """Display bot information.""" description = 'Uptime: {}\n[Invite Link]({})'.format(self.bot.get_uptime(brief=True), self.oauth_url) embed = discord.Embed(description=description) embed.set_author(name=str(self.bot.app.owner), icon_url=self.bot.app.owner.avatar_url) embed.add_field(name='Guilds', value=str(len(self.bot.guilds))) source = config.source if source: embed.add_field(name='Source', value=f'See [here]({source}).') embed.set_footer(text='Made with discord.py | Online Since', icon_url='http://i.imgur.com/5BFecvA.png') embed.timestamp = self.bot.start_time await ctx.send(embed=embed)
def about(message, client): a_details = discord.Embed(title='About Me', description='', colour=0x1f3A44) a_details.add_field(name='Creator\'s Discord Name:', value='Beefywhale#5424', inline=True) a_details.add_field(name='Creator\'s GitHub:', value='https://github.com/Beefywhale', inline=True) a_details.add_field(name='My Website:', value='https://beefywhale.github.io/WeenieBot/', inline=True) a_details.add_field(name='Invite Me:', value='https://tiny.cc/weeniebot', inline=True) a_details.add_field(name='Servers I am in:', value=len(client.servers), inline=True) a_details.add_field(name='Current Bot Owner:', value=str(client.bot_info.owner), inline=True) a_details.set_footer(text='Made in Python3.5+ with discord.py library!', icon_url='http://findicons.com/files/icons/2804/plex/512/python.png') a_details.set_image(url=message.server.me.avatar_url) a_details.set_author(name=message.server.me, icon_url=message.server.me.avatar_url) await client.send_message(message.channel, embed=a_details)
def randPokemon(message, client): parsedPokemon = random.randint(0, 709) try: pokemon = await getPokemonData2('/api/v1/pokemon/' + str(parsedPokemon), message, client) sprite_uri = pokemon['sprites'][0]['resource_uri'] description_uri = pokemon['descriptions'][0]['resource_uri'] type_uri = pokemon['types'][0]['resource_uri'] sprite = await getPokemonData2(sprite_uri, message, client) description = await getPokemonData2(description_uri, message, client) ptype = await getPokemonData2(type_uri, message, client) p_details = discord.Embed(title='', description='', colour=0x1f3A44) p_details.add_field(name='Pokemon:', value=pokemon['name'], inline=True) p_details.add_field(name='National Pokedex ID:', value=pokemon['national_id'], inline=True) p_details.add_field(name='Desc:', value=description['description'], inline=True) p_details.add_field(name='Type:', value=ptype['name'], inline=True) p_details.add_field(name='Defense:', value=pokemon['defense'], inline=True) p_details.add_field(name='Health Points:', value=pokemon['hp'], inline=True) p_details.add_field(name='Attack:', value=pokemon['attack'], inline=True) p_details.set_footer(text='Made in Python3.5+ with discord.py library!', icon_url='http://findicons.com/files/icons/2804/plex/512/python.png') p_details.set_image(url=BASE_URL + sprite['image']) p_details.set_author(name=pokemon['name'], icon_url=BASE_URL + sprite['image']) if message.server.id not in ['242887866730938378']: await client.send_message(message.channel, embed=p_details) print(pokemon['name']) print(description['description']) print(ptype['name']) print(pokemon['hp']) print(pokemon['defense']) print(pokemon['attack']) print(pokemon['national_id']) print(BASE_URL + sprite['image']) except TypeError as e: print(e) if message.server.id not in ['242887866730938378']: await client.send_message(message.channel, 'ERROR {} is not in the Pokedex! Try using all lowercase!'.format(parsedPokemon))
def getPokemon(message, client): try: parsedPokemon = message.content.replace(message.content.split()[0] + ' ','') pokemon = await getPokemonData2('/api/v1/pokemon/' + parsedPokemon, message, client) sprite_uri = pokemon['sprites'][0]['resource_uri'] description_uri = pokemon['descriptions'][0]['resource_uri'] type_uri = pokemon['types'][0]['resource_uri'] sprite = await getPokemonData2(sprite_uri, message, client) description = await getPokemonData2(description_uri, message, client) ptype = await getPokemonData2(type_uri, message, client) p_details = discord.Embed(title='', description='', colour=0x1f3A44) p_details.add_field(name='Pokemon:', value=pokemon['name'], inline=True) p_details.add_field(name='National Pokedex ID:', value=pokemon['national_id'], inline=True) p_details.add_field(name='Desc:', value=description['description'], inline=True) p_details.add_field(name='Type:', value=ptype['name'], inline=True) p_details.add_field(name='Defense:', value=pokemon['defense'], inline=True) p_details.add_field(name='Health Points:', value=pokemon['hp'], inline=True) p_details.add_field(name='Attack:', value=pokemon['attack'], inline=True) p_details.set_footer(text='Made in Python3.5+ with discord.py library!', icon_url='http://findicons.com/files/icons/2804/plex/512/python.png') p_details.set_image(url=BASE_URL + sprite['image']) p_details.set_author(name=pokemon['name'], icon_url=BASE_URL + sprite['image']) if message.server.id not in ['242887866730938378']: await client.send_message(message.channel, embed=p_details) print(pokemon['name']) print(description['description']) print(ptype['name']) print(pokemon['hp']) print(pokemon['defense']) print(pokemon['attack']) print(pokemon['national_id']) print(BASE_URL + sprite['image']) except TypeError: if message.server.id not in ['242887866730938378']: await client.send_message(message.channel, 'ERROR {} is not in the Pokedex!'.format(parsedPokemon))
def info(self, ctx): await ctx.send(f'```{self.bot.description}\n\nFramework: discord.py {discord.__version__}\nSource: https://github.com/Run1e/AceBot```')
def on_ready(): print('Inkxbot is logged in and online!') print("discord.py version is " + discord.__version__) print('--------------------------------') if not hasattr(bot, 'uptime'): bot.uptime = datetime.datetime.utcnow() bot.task = bot.loop.create_task(background_task())
def get_shard_count(self): r = requests.get(BOT_ENDPOINT, headers={ "Authorization": "Bot {}".format(self.token), "User-Agent": 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} requests/{2}'.format( discord.__version__, sys.version_info, requests.__version__) }) if r.status_code == 200: return r.json()['shards']+1 else: return None
def botinformation(cmd, message, args): version_data = cmd.bot.info.get_version().raw author_data = cmd.bot.info.get_authors().raw sigma_image = 'https://i.imgur.com/mGyqMe1.png' support_url = 'https://discordapp.com/invite/aEUCHwX' ver_nest = version_data["version"] full_version = f'{ver_nest["major"]}.{ver_nest["minor"]}.{ver_nest["patch"]}' if version_data['beta']: full_version += ' Beta' sigma_title = f'Apex Sigma: v{full_version} {version_data["codename"]}' env_text = f'Language: **Python {sys.version.split()[0]}**' env_text += f'\nLibrary: **discord.py** {discord.__version__}' env_text += f'\nPlatform: **{sys.platform.upper()}**' auth_text = '' for author in author_data: auth = discord.utils.find(lambda x: x.id == author['id'], cmd.bot.get_all_members()) if auth: auth_text += f'\n**{auth.name}**#{auth.discriminator}' else: auth_text += f'\n**{author["name"]}**#{author["discriminator"]}' response = discord.Embed(color=0x1B6F5F, timestamp=arrow.get(version_data['build_date']).datetime) response.set_author(name=sigma_title, icon_url=sigma_image, url=support_url) response.add_field(name='Authors', value=auth_text) response.add_field(name='Environment', value=env_text) response.set_footer(text=f'Last updated {arrow.get(version_data["build_date"]).humanize()}') await message.channel.send(embed=response)
def stats(bot, log=None): tmp = [] permed_ids = [] for ownr in permitted_id: permed_ids.append(str(ownr)) authors = userlist(bot.authors) donor_count = len(bot.donors) with open('VERSION') as version_file: content = yaml.safe_load(version_file) version = content['version'] build_date = datetime.datetime.fromtimestamp(content['build_date']).strftime('%B %d, %Y') v_major = version['major'] v_minor = version['minor'] v_patch = version['patch'] codename = content['codename'] beta_state = content['beta'] v_full = str(v_major) + '.' + str(v_minor) + '.' + str(v_patch) version_text = '' if beta_state: version_text += 'Beta ' version_text += v_full + ' Codename ' + codename tmp.append(multi('Logged In As: \"' + bot.user.name + '\"', log)) tmp.append(multi(f'Bot User ID: {bot.user.id}', log)) tmp.append(multi('Python version: ' + sys.version.split(' ')[0], log)) tmp.append(multi('discord.py version: ' + discord.__version__, log)) tmp.append(multi('Authors: {:s}'.format(authors), log)) tmp.append(multi('Donors: ' + str(donor_count), log)) tmp.append(multi('Bot Version: ' + version_text, log)) tmp.append(multi('Build Date: ' + build_date, log)) tmp.append(multi('Connected to [ {:d} ] servers'.format(len(bot.guilds)), log)) tmp.append(multi('Serving [ {:d} ] users'.format(len(list(bot.get_all_members()))), log)) tmp.append(multi(f'Permitted IDs: {", ".join(permed_ids)}', log)) return tmp
def _command_signature(cmd): # this is modified from discord.py source # which I wrote myself lmao result = [cmd.qualified_name] if cmd.usage: result.append(cmd.usage) return ' '.join(result) params = cmd.clean_params if not params: return ' '.join(result) for name, param in params.items(): if param.default is not param.empty: # We don't want None or '' to trigger the [name=value] case and instead it should # do [name] since [name=None] or [name=] are not exactly useful for the user. should_print = param.default if isinstance(param.default, str) else param.default is not None if should_print: result.append(f'[{name}={param.default!r}]') else: result.append(f'[{name}]') elif param.kind == param.VAR_POSITIONAL: result.append(f'[{name}...]') else: result.append(f'<{name}>') return ' '.join(result)
def _get_class_name(obj): # Thanks discord.py return obj.__class__.__name__.replace('Text', '')
def _list_cogs(self): cogs = [os.path.basename(f) for f in glob.glob("cogs/*.py")] return ["cogs." + os.path.splitext(f)[0] for f in cogs]
def repl_format_source(self, thing): """returns get_source formatted to be used in repl rtfs originated as this alias: debug (lambda cmd, bot=bot: (lambda f, out: out[0] if len(out) == 1 else (f(f,out[1:5] + (['{} more pages remaining..\njust tell them to read the actual source file man.'.format(len(out)-5)] if len(out) > 5 else [])) or out[0]))((lambda self, more: None if not more else bot.loop.create_task(bot.say('``'+'`py\n'+more.pop(0)+'``'+'`')).add_done_callback(self(self, more))), list(pagify((lambda ic, fc, pg: (lambda fcs: ic.getsourcefile(fc).split('/')[-1]+'\nline: {}'.format(fcs[1])+'``'+'`'+'\n'+'``'+'`py\n'+''.join(fcs[0]))(ic.getsourcelines(fc)))(__import__('inspect'), (cmd if not isinstance(cmd, str) else (lambda f, ms: f(f, __import__(ms.pop(0)), ms))((lambda f, prev, ms: getattr(prev, 'callback') if hasattr(prev, 'callback') else prev if not ms else f(f, getattr(prev, ms.pop(0)), ms)), cmd.split('.')) if '.' in cmd else (lambda end, cmds: end(end, cmds, bot.commands[cmds.pop(0)]).callback)((lambda end, names, cmd: cmd if not names else end(end, names, cmd.commands[names.pop(0)])), cmd.split()) ), __import__('cogs').utils.chat_formatting.pagify), delims=['\n', ' '], escape=False, shorten_by=12)) )) """ source = self.get_source(thing) msg = source.filename.split('/')[-1] + '\n' msg += 'line: {}'.format(source.line_number) msg += '``'+'`\n`'+'``py\n' # codeblock break msg += source.source return msg
def cleanup_code(self, content): """Automatically removes code blocks from the code.""" # remove ```py\n
if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` for p in self.settings["REPL_PREFIX"]: if content.startswith(p): if p == '`': return content.strip('` \n') content = content[len(p):] return content.strip(' \n')
```
def get_syntax_error(self, e): return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)
def print_results(self, ctx, results): msg = ctx.message nbs = '?' discord_fmt = nbs + '```py\n{}\n```' is_interactive = self.settings["OUTPUT_REDIRECT"] == "pages" res_len = len(discord_fmt.format(results)) if is_interactive and res_len > self.settings["PAGES_LENGTH"]: single_msg = not self.settings["MULTI_MSG_PAGING"] page = self.pagify_interactive_results(ctx, results, single_msg=single_msg) self.bot.loop.create_task(page) elif res_len > 2000: if self.settings["OUTPUT_REDIRECT"] == "pm": await self.bot.send_message(msg.channel, 'Content too big. Check your PMs') enough_paper = self.settings["PM_PAGES"] for page in pagify(results, ['\n', ' '], shorten_by=12): await self.bot.send_message(msg.author, discord_fmt.format(page)) enough_paper -= 1 if not enough_paper: await self.bot.send_message(msg.author, "**Too many pages! Think of the trees!**") return elif self.settings["OUTPUT_REDIRECT"] == "console": await self.bot.send_message(msg.channel, 'Content too big. Check your console') print(results) else: await self.bot.send_message(msg.channel, 'Content too big. Writing to file') with open(self.output_file, 'w') as f: f.write(results) open_cmd = self.settings["OPEN_CMD"] if open_cmd: subprocess.Popen([open_cmd, self.output_file]) else: await self.bot.send_message(msg.channel, discord_fmt.format(results))
def page_results(self, results, single_msg=True): nbs = '?' discord_fmt = nbs + '```py\n{}\n```' prompt = (" Output too long. Navigate pages with ({}close/next)" .format('' if single_msg else 'prev/')) pages = [p for p in pagify(results, ['\n', ' '], page_length=self.settings["PAGES_LENGTH"])] # results is not a generator, so no reason to keep this as one pages = [discord_fmt.format(p) + 'pg. {}/{}' .format(c + 1, len(pages)) for c, p in enumerate(pages)] pages[0] += prompt return pages
def source(self, command : str = None): """Displays my full source code or for a specific command. To display the source code of a subcommand you have to separate it by periods, e.g. tag.create for the create subcommand of the tag command. """ source_url = 'https://github.com/miraai/LunaBot' if command is None: await self.bot.say(source_url) return code_path = command.split('.') obj = self.bot for cmd in code_path: try: obj = obj.get_command(cmd) if obj is None: await self.bot.say('Could not find the command ' + cmd) return except AttributeError: await self.bot.say('{0.name} command has no subcommands'.format(obj)) return # since we found the command we're looking for, presumably anyway, let's # try to access the code itself src = obj.callback.__code__ if not obj.callback.__module__.startswith('discord'): # not a built-in command location = os.path.relpath(src.co_filename).replace('\\', '/') final_url = '<{}/blob/master/{}#L{}>'.format(source_url, location, src.co_firstlineno) else: location = obj.callback.__module__.replace('.', '/') + '.py' base = 'https://github.com/Rapptz/discord.py' final_url = '<{}/blob/master/{}#L{}>'.format(base, location, src.co_firstlineno) await self.bot.say(final_url)
def on_ready(): print("discord.py version: {}".format(discord.__version__)) print('Running script as: {}#{}({})'.format(bot.user.name, bot.user.discriminator, bot.user.id)) print('------------------------------------------------------------------') if not hasattr(bot, 'game_name'): bot.game_name = None if not hasattr(bot, 'status'): bot.status = discord.Status.online await bot.change_presence(status=bot.status) # reset these to empty list bot.log_servers = [] bot.log_private_channels_list = [] if bot.log_all_messages_on_start: print("Beginning to dump previous messages to log...") log.info("====================== Dumping Previous Messages ======================") # first log all servers and channels in servers for server in bot.servers: for channel in server.channels: permissions = channel.permissions_for(server.get_member(bot.user.id)) if all(getattr(permissions, perm, None) == True for perm in ["read_messages", "read_message_history"]): async for message in bot.logs_from(channel, limit=bot.message_channel_max): log_message(message) # now the same for PrivateChannels for channel in bot.private_channels: async for message in bot.logs_from(channel, limit=bot.message_channel_max): log_message(message) log.info("====================== End Previous Message Dump ======================") print("Finished dumping previous messages!")
def parse_commandline(argv): # get token from command line, if less than 1 (script), print error and exit if len(argv) > 1: # try to parse args try: # apparently needs to be sys.argv[1:], or it wont work... opts, args = getopt.getopt(argv[1:],"h",["token=", "help"]) # if no args, print error, usage and exit except: cleanup_handlers() invalid_token() usage(argv[0]) sys.exit(-1) for opt, arg in opts: # print usage statement and exit if opt in ('-h', "--help"): cleanup_handlers() usage(argv[0]) sys.exit(0) # grab token from arg for discord.py usage elif opt == '--token': token = arg token = token.strip() if token is None or token == "": cleanup_handlers() invalid_token() usage(argv[0]) sys.exit(-1) else: # DERP! forgot to add this here >.< cleanup_handlers() invalid_token() usage(argv[0]) sys.exit(-1)
def botinformation(cmd, message, args): version_data = cmd.bot.info.version.raw author_data = cmd.bot.info.authors.raw sigma_image = 'https://i.imgur.com/mGyqMe1.png' support_url = 'https://discordapp.com/invite/aEUCHwX' ver_nest = version_data["version"] full_version = f'{ver_nest["major"]}.{ver_nest["minor"]}.{ver_nest["patch"]}' if version_data['beta']: full_version += ' Beta' sigma_title = f'Apex Sigma: v{full_version} {version_data["codename"]}' env_text = f'Language: **Python {sys.version.split()[0]}**' env_text += f'\nLibrary: **discord.py** {discord.__version__}' env_text += f'\nPlatform: **{sys.platform.upper()}**' auth_text = '' for author in author_data: auth = discord.utils.find(lambda x: x.id == author['id'], cmd.bot.get_all_members()) if auth: auth_text += f'\n**{auth.name}**#{auth.discriminator}' else: auth_text += f'\n**{author["name"]}**#{author["discriminator"]}' response = discord.Embed(color=0x1B6F5F, timestamp=arrow.get(version_data['build_date']).datetime) response.set_author(name=sigma_title, icon_url=sigma_image, url=support_url) response.add_field(name='Authors', value=auth_text) response.add_field(name='Environment', value=env_text) response.set_footer(text=f'Last updated {arrow.get(version_data["build_date"]).humanize()}') await message.channel.send(embed=response)
def info(self, ctx): """Prints info about mangobyte""" github = "https://github.com/mdiller/MangoByte" python_version = "[Python {}.{}.{}]({})".format(*os.sys.version_info[:3], "https://www.python.org/") discordpy = "https://github.com/Rapptz/discord.py" embed = discord.Embed(description="The juiciest unsigned 8 bit integer you eva gonna see", color=discord.Color.green()) embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url, url=github) embed.add_field(name="Development Info", value=( "Developed as an open source project, hosted on [GitHub]({}). " "Implemented using {} and a python discord api wrapper [discord.py]({})".format(github, python_version, discordpy))) embed.add_field(name="Features", value=( "• Answers questions (`?ask`)\n" "• Plays audio clips (`?play`, `?dota`)\n" "• Greets users joining a voice channel\n" "• For a list of command categories, try `?help`")) help_guild_link = "https://discord.gg/d6WWHxx" embed.add_field(name="Help", value=( f"If you want to invite mangobyte to your server/guild, click this [invite link]({invite_link}). " f"If you have a question, suggestion, or just want to try out mah features, check out the [Help Server/Guild]({help_guild_link}).")) owner = (await self.bot.application_info()).owner embed.set_footer(text="MangoByte developed by {}".format(owner.name), icon_url=owner.avatar_url) await ctx.send(embed=embed)
def on_command_error(error, ctx): if isinstance(error, commands.errors.CommandNotFound): pass # ...don't need to know if commands don't exist if isinstance(error, commands.errors.CheckFailure): await bot.send_message(ctx.message.channel, "{} You don't have permission to use this command.".format(ctx.message.author.mention)) elif isinstance(error, commands.errors.MissingRequiredArgument): formatter = commands.formatter.HelpFormatter() await bot.send_message(ctx.message.channel, "{} You are missing required arguments.\n{}".format(ctx.message.author.mention, formatter.format_help_for(ctx, ctx.command)[0])) elif isinstance(error, commands.errors.CommandOnCooldown): try: await bot.delete_message(ctx.message) except discord.errors.NotFound: pass message = await bot.send_message(ctx.message.channel, "{} This command was used {:.2f}s ago and is on cooldown. Try again in {:.2f}s.".format(ctx.message.author.mention, error.cooldown.per - error.retry_after, error.retry_after)) await asyncio.sleep(10) await bot.delete_message(message) else: await bot.send_message(ctx.message.channel, "An error occured while processing the `{}` command.".format(ctx.command.name)) print('Ignoring exception in command {0.command} in {0.message.channel}'.format(ctx)) mods_msg = "Exception occured in `{0.command}` in {0.message.channel.mention}".format(ctx) # traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) tb = traceback.format_exception(type(error), error, error.__traceback__) print(''.join(tb)) await bot.send_message(bot.boterr_channel, mods_msg + '\n```' + ''.join(tb) + '\n```') # mostly taken from https://github.com/Rapptz/discord.py/blob/async/discord/client.py
def info(self, ctx): """Bot Info""" me = self.bot.user if not ctx.guild else ctx.guild.me appinfo = await self.bot.application_info() embed = discord.Embed() embed.set_author(name=me.display_name, icon_url=appinfo.owner.avatar_url, url="https://github.com/henry232323/PokeRPG-Bot") embed.add_field(name="Author", value='Henry#6174 (Discord ID: 122739797646245899)') embed.add_field(name="Library", value='discord.py (Python)') embed.add_field(name="Uptime", value=await self.bot.get_bot_uptime()) embed.add_field(name="Servers", value="{} servers".format(len(self.bot.guilds))) embed.add_field(name="Commands Run", value='{} commands'.format(sum(self.bot.commands_used.values()))) total_members = sum(len(s.members) for s in self.bot.guilds) total_online = sum(1 for m in self.bot.get_all_members() if m.status != discord.Status.offline) unique_members = set(map(lambda x: x.id, self.bot.get_all_members())) channel_types = Counter(isinstance(c, discord.TextChannel) for c in self.bot.get_all_channels()) voice = channel_types[False] text = channel_types[True] embed.add_field(name="Total Members", value='{} ({} online)'.format(total_members, total_online)) embed.add_field(name="Unique Members", value='{}'.format(len(unique_members))) embed.add_field(name="Channels", value='{} text channels, {} voice channels'.format(text, voice)) embed.add_field(name="Shards", value=f'Currently running {ctx.bot.shard_count} shards. This server is on shard {getattr(ctx.guild, "shard_id", 0)}') a = monotonic() await (await ctx.bot.shards[getattr(ctx.guild, "shard_id", 0)].ws.ping()) b = monotonic() ping = "{:.3f}ms".format((b - a) * 1000) embed.add_field(name="CPU Percentage", value="{}%".format(psutil.cpu_percent())) embed.add_field(name="Memory Usage", value=self.bot.get_ram()) embed.add_field(name="Observed Events", value=sum(self.bot.socket_stats.values())) embed.add_field(name="Ping", value=ping) embed.add_field(name="Source", value="[Github](https://github.com/henry232323/RPGBot)") embed.set_footer(text='Made with discord.py', icon_url='http://i.imgur.com/5BFecvA.png') embed.set_thumbnail(url=self.bot.user.avatar_url) await ctx.send(delete_after=60, embed=embed)
def source(self, ctx, command: str = None): """Displays my full source code or for a specific command. To display the source code of a subcommand you have to separate it by periods, e.g. tag.create for the create subcommand of the tag command. """ source_url = 'https://github.com/henry232323/RPGBot' if command is None: await ctx.send(source_url) return code_path = command.split('.') obj = self.bot for cmd in code_path: try: obj = obj.get_command(cmd) if obj is None: await ctx.send('Could not find the command ' + cmd) return except AttributeError: await ctx.send('{0.name} command has no subcommands'.format(obj)) return # since we found the command we're looking for, presumably anyway, let's # try to access the code itself src = obj.callback.__code__ if not obj.callback.__module__.startswith('discord'): # not a built-in command location = os.path.relpath(src.co_filename).replace('\\', '/') final_url = '<{}/tree/master/{}#L{}>'.format(source_url, location, src.co_firstlineno) else: location = obj.callback.__module__.replace('.', '/') + '.py' base = 'https://github.com/Rapptz/discord.py' final_url = '<{}/blob/master/{}#L{}>'.format(base, location, src.co_firstlineno) await ctx.send(final_url)
def on_message(self, message): channel = message.channel author = message.author if channel.id != DISCORD_PY_ID: return if author.status is discord.Status.offline: fmt = f'{author} (ID: {author.id}) has been automatically blocked for 5 minutes for being invisible' await channel.set_permissions(author, read_messages=False, reason='invisible block') await channel.send(fmt) try: msg = f'Heya. You have been automatically blocked from <#{DISCORD_PY_ID}> for 5 minutes for being ' \ 'invisible.\nTry chatting again in 5 minutes when you change your status. If you\'re curious ' \ 'why invisible users are blocked, it is because they tend to break the client and cause them to ' \ 'be hard to mention. Since we want to help you usually, we expect mentions to work without ' \ 'headaches.\n\nSorry for the trouble.' await author.send(msg) except discord.HTTPException: pass await asyncio.sleep(300) await channel.set_permissions(author, overwrite=None, reason='invisible unblock') return m = self.issue.search(message.content) if m is not None: url = 'https://github.com/Rapptz/discord.py/issues/' await channel.send(url + m.group('number'))
def rtfm(self, ctx, *, obj: str = None): """Gives you a documentation link for a discord.py entity. Events, objects, and functions are all supported through a a cruddy fuzzy algorithm. """ await self.do_rtfm(ctx, 'latest', obj)
def rtfm_rewrite(self, ctx, *, obj: str = None): """Gives you a documentation link for a rewrite discord.py entity.""" await self.do_rtfm(ctx, 'rewrite', obj)
def faq(self, ctx, *, query: str = None): """Shows an FAQ entry from the discord.py documentation""" if not hasattr(self, 'faq_entries'): await self.refresh_faq_cache() if query is None: return await ctx.send('http://discordpy.readthedocs.io/en/latest/faq.html') matches = fuzzy.extract_matches(query, self.faq_entries, scorer=fuzzy.partial_ratio, score_cutoff=40) if len(matches) == 0: return await ctx.send('Nothing found...') fmt = '\n'.join(f'**{key}**\n{value}' for key, _, value in matches) await ctx.send(fmt)
def join(self, invite_url: discord.Invite=None): """Joins new server""" if hasattr(self.bot.user, 'bot') and self.bot.user.bot is True: # Check to ensure they're using updated discord.py msg = ("I have a **BOT** tag, so I must be invited with an OAuth2" " link:\nFor more information: " "---" "---") await self.bot.say(msg) if hasattr(self.bot, 'oauth_url'): await self.bot.whisper("Here's my OAUTH2 link:\n{}".format( self.bot.oauth_url)) return if invite_url is None: await self.bot.say("I need a Discord Invite link for the " "server you want me to join.") return try: await self.bot.accept_invite(invite_url) await self.bot.say("Server joined.") log.debug("We just joined {}".format(invite_url)) except discord.NotFound: await self.bot.say("The invite was invalid or expired.") except discord.HTTPException: await self.bot.say("I wasn't able to accept the invite." " Try again.")
def set_cog(cog, value): # TODO: move this out of red.py data = dataIO.load_json("data/red/cogs.json") data[cog] = value dataIO.save_json("data/red/cogs.json", data)
def status(self, ctx): '''Infos über den Bot''' timeUp = time.time() - self.bot.startTime hours = timeUp / 3600 minutes = (timeUp / 60) % 60 seconds = timeUp % 60 admin = self.bot.get_user(self.bot.owner_id) users = 0 channel = 0 if len(self.bot.commands_used.items()): commandsChart = sorted(self.bot.commands_used.items(), key=lambda t: t[1], reverse=False) topCommand = commandsChart.pop() commandsInfo = '{} (Top-Command: {} x {})'.format(sum(self.bot.commands_used.values()), topCommand[1], topCommand[0]) else: commandsInfo = str(sum(self.bot.commands_used.values())) for guild in self.bot.guilds: users += len(guild.members) channel += len(guild.channels) embed = discord.Embed(color=ctx.me.top_role.colour) embed.set_footer(text='Dieser Bot ist Open-Source auf GitHub: https://github.com/Der-Eddy/discord_bot') embed.set_thumbnail(url=ctx.me.avatar_url) embed.add_field(name='Admin', value=admin, inline=False) embed.add_field(name='Uptime', value='{0:.0f} Stunden, {1:.0f} Minuten und {2:.0f} Sekunden\n'.format(hours, minutes, seconds), inline=False) embed.add_field(name='Beobachtete Benutzer', value=users, inline=True) embed.add_field(name='Beobachtete Server', value=len(self.bot.guilds), inline=True) embed.add_field(name='Beobachtete Channel', value=channel, inline=True) embed.add_field(name='Ausgeführte Commands', value=commandsInfo, inline=True) embed.add_field(name='Bot Version', value=self.bot.botVersion, inline=True) embed.add_field(name='Discord.py Version', value=discord.__version__, inline=True) embed.add_field(name='Python Version', value=platform.python_version(), inline=True) # embed.add_field(name='Speicher Auslastung', value=f'{round(memory_usage(-1)[0], 3)} MB', inline=True) embed.add_field(name='Betriebssystem', value=f'{platform.system()} {platform.release()} {platform.version()}', inline=False) await ctx.send('**:information_source:** Informationen über diesen Bot:', embed=embed)
def about(self, ctx): '''Info über mich''' msg = 'Shinobu Oshino gehört wohl zu den mysteriösesten Charakteren in Bakemonogatari. Sie war bis vorletzten Frühling ein hochangesehener, adeliger, skrupelloser Vampir, der weit über 500 Jahre alt ist. Gnadenlos griff sie Menschen an und massakrierte sie nach Belieben. Auch Koyomi Araragi wurde von ihr attackiert und schwer verwundet. Nur durch das Eingreifen des Exorzisten Meme Oshino konnte Kiss-shot Acerola-orion Heart-under-blade, wie sie damals bekannt war, bezwungen werden. Dabei verlor sie jedoch all ihre Erinnerungen und wurde von einer attraktiven, erwachsenen Frau in einen unschuldigen Mädchenkörper verwandelt.\n\n' msg += 'Seitdem lebt sie zusammen mit Meme in einem verlassenen Gebäude und wurde von ihm aufgenommen. Er gab ihr auch ihren Namen Shinobu. Das Vampirblut in ihr verlangt immer noch nach Opfern und da sich Koyomi in gewisser Art und Weise schuldig fühlt, stellt er sich regelmäßig als Nahrungsquelle für Shinobu zur Verfügung.\n\n' msg += 'Quelle: http://www.anisearch.de/character/6598,shinobu-oshino/\n\n' embed = discord.Embed(color=ctx.me.top_role.colour) embed.set_footer(text='Dieser Bot ist außerdem free, Open-Source, in Python und mit Hilfe von discord.py geschrieben! https://github.com/Der-Eddy/discord_bot\n') embed.set_thumbnail(url=ctx.me.avatar_url) embed.add_field(name='**:information_source: Shinobu Oshino (500 Jahre alt)**', value=msg, inline=False) await ctx.send(embed=embed)
def source(self, ctx, *, command: str = None): '''Zeigt den Quellcode für einen Befehl auf GitHub an Beispiel: ----------- :source kawaii ''' source_url = 'https://github.com/Der-Eddy/discord_bot' if command is None: await ctx.send(source_url) return obj = self.bot.get_command(command.replace('.', ' ')) if obj is None: return await ctx.send(':x: Konnte den Befehl nicht finden') # since we found the command we're looking for, presumably anyway, let's # try to access the code itself src = obj.callback.__code__ lines, firstlineno = inspect.getsourcelines(src) sourcecode = inspect.getsource(src).replace('```', '') if not obj.callback.__module__.startswith('discord'): # not a built-in command location = os.path.relpath(src.co_filename).replace('\\', '/') else: location = obj.callback.__module__.replace('.', '/') + '.py' source_url = 'https://github.com/Rapptz/discord.py' if len(sourcecode) > 1900: final_url = '{}/blob/master/{}#L{}-L{}'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1) else: final_url = '<{}/blob/master/{}#L{}-L{}>\n```Python\n{}```'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1, sourcecode) await ctx.send(final_url)