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)
python类py()的实例源码
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