def clean(ctx, message):
"""
Cleans the previous messages
:param ctx:
:param message:
:return:
"""
try:
message_bucket = []
async for entry in ctx.logs_from(message.channel):
if entry.author == ctx.user:
message_bucket.append(entry)
await ctx.delete_messages(message_bucket)
await ctx.send_message(message.channel, ':sweat_drops: `Cleaned.`')
except discord.Forbidden:
await ctx.send_message(message.channel, '**Error**: `I do not have permissions to get channel logs`')
return
except discord.NotFound:
await ctx.send_message(message.channel, '**Error**: `The channel you are requesting for doesnt exist.`')
return
except discord.HTTPException:
return
python类NotFound()的实例源码
def ok(self, emoji: str = '\N{OK HAND SIGN}'):
"""
Adds a reaction to the command message, or sends it to the channel if
we can't add reactions. This should be used as feedback to commands,
just like how most bots send out `:ok_hand:` when a command completes
successfully.
"""
try:
await self.message.add_reaction(emoji)
except Forbidden:
# can't add reactions
await self.send(emoji)
except NotFound:
# the command message got deleted somehow
pass
def multiban(self, ctx, reason, delete_days: DeleteDays=2, *members: converters.RawMember):
"""
Bans multiple users.
Functions similarly to d?ban.
"""
progress = await ctx.send(f'Banning {len(members)} member(s)...')
reason = reason or 'No reason provided.'
paginator = commands.Paginator(prefix='', suffix='')
for member in members:
try:
await ctx.guild.ban(member, delete_message_days=delete_days,
reason=f'(Multi-banned by {ctx.author}) {reason}')
paginator.add_line(f'{ctx.green_tick} Banned {describe(member)}.')
except discord.NotFound:
# XXX: This code path might be unreachable, research further
paginator.add_line(f"{ctx.red_tick} {describe(member)} wasn't found.")
except discord.HTTPException:
paginator.add_line(f'{ctx.red_tick} Failed to ban {describe(member)}. No permissions?')
await progress.delete()
for page in paginator.pages:
await ctx.send(page)
def ban(self, ctx, member: converters.RawMember, delete_days: DeleteDays=2, *, reason=None):
"""
Bans someone.
This command is special in that you may specify an ID to ban, instead of regularly specifying a
member to ban. Banning users outside of the server is called "hackbanning", and is handy for banning
users who are not present in the server.
If you don't want to delete any messages, specify 0 for delete_days. delete_days has a
maximum of 7. By default, 2 days worth of messages are deleted.
"""
try:
reason = reason or 'No reason provided.'
await ctx.guild.ban(member, delete_message_days=delete_days, reason=f'(Banned by {ctx.author}) {reason}')
ctx.bot.dispatch('member_dog_ban', member, ctx.author, reason)
except discord.Forbidden:
await ctx.send("I can't do that.")
except discord.NotFound:
await ctx.send("User not found.")
else:
banned = await ctx.bot.get_user_info(member.id) if isinstance(member, discord.Object) else member
await ctx.send(f'\N{OK HAND SIGN} Banned {describe(banned)}.')
def adminlist(self, ctx):
"""List all bot admins defined.
Usage: adminlist"""
alist = ''
for i in self.bot.store['bot_admins']:
nid = ''
try:
_name = ctx.guild.get_member(i)
except AttributeError:
_name = None
if not _name:
try:
_name = await self.bot.get_user_info(i)
except discord.NotFound:
_name = 'UNKNOWN'
nid = i
if not nid:
nid = _name.id
alist += '**' + str(_name) + f'** (ID `{nid}`)\n'
await ctx.send('The following people are bot admins:\n' + alist)
def _loop(self):
for name, value in self._member_fields():
self._track.add_field(name=name, value=value, inline=False)
message = await self.ctx.send(embed=self._track)
while not self.is_completed():
await asyncio.sleep(random.uniform(1, 3))
self.update_game()
self.update_current_embed()
try:
await message.edit(embed=self._track)
except discord.NotFound:
message = await self.ctx.send(embed=self._track)
await asyncio.sleep(random.uniform(1, 3))
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 clean(ctx, message):
"""
Cleans the previous messages
:param ctx:
:param message:
:return:
"""
try:
message_bucket = []
async for entry in ctx.logs_from(message.channel):
if entry.author == ctx.user:
message_bucket.append(entry)
await ctx.delete_messages(message_bucket)
await ctx.send_message(message.channel, ':sweat_drops: `Cleaned.`')
except discord.Forbidden:
await ctx.send_message(message.channel, '**Error**: `I do not have permissions to get channel logs`')
return
except discord.NotFound:
await ctx.send_message(message.channel, '**Error**: `The channel you are requesting for doesnt exist.`')
return
except discord.HTTPException:
return
def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None, quiet=False):
msg = None
try:
msg = await self.send_message(dest, content, tts=tts)
if msg and expire_in:
asyncio.ensure_future(self._wait_delete_msg(msg, expire_in))
if also_delete and isinstance(also_delete, discord.Message):
asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in))
except discord.Forbidden:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, no permission" % dest.name)
except discord.NotFound:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, invalid channel?" % dest.name)
return msg
def whois(self, ctx, user_id: int):
"""
Searches for a user via ID
"""
try:
with ctx.channel.typing():
user = await self.bot.get_user_info(user_id)
embed = discord.Embed(colour=discord.Colour(0x30f9c7), description="ID: {}".format(user.id),
timestamp=datetime.datetime.now())
embed.set_thumbnail(
url=user.avatar_url)
embed.set_author(name=user)
embed.set_footer(text="Who Is: User")
embed.add_field(name="Bot?", value=user.bot, inline=False)
embed.add_field(name="Account Creation Date", value=user.created_at, inline=False)
await ctx.send(embed=embed)
except discord.NotFound:
await ctx.send("`No user found under this ID`")
except discord.HTTPException:
await ctx.send("`Error collecting user information`")
return
def edit_mod_entry(self, modcfg, data):
"""Edit a moderation entry."""
modlog = data['guild'].get_channel(modcfg['mod_log_id'])
if modlog is None:
raise self.SayException('Moderation channel not found')
try:
action_data = self.cache[data['action_id']]
except KeyError:
raise self.SayException("Can't find action ID in cache, sorry :c")
old_data = action_data['data']
old_data['reason'] = data['reason']
try:
message = await modlog.get_message(action_data['message_id'])
except discord.NotFound:
raise self.SayException('Message to edit not found')
except discord.Forbidden:
raise self.SayException("Can't read messages")
except discord.HTTPException as err:
raise self.SayException(f'fug `{err!r}`')
await message.edit(content=self.modlog_fmt(old_data))
def star(self, ctx, message_id: int):
"""Star a message."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
try:
await self.add_star(message, ctx.author)
await ctx.ok()
except (StarAddError, StarError) as err:
log.warning(f'[star_command] Errored: {err!r}')
return await ctx.send(f'Failed to add star: {err!r}')
def unstar(self, ctx, message_id: int):
"""Unstar a message."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
try:
await self.remove_star(message, ctx.author)
await ctx.ok()
except (StarRemoveError, StarError) as err:
log.warning(f'[unstar_cmd] Errored: {err!r}')
return await ctx.send(f'Failed to remove star: {err!r}')
def starrers(self, ctx, message_id: int):
"""Get the list of starrers from a message in the current channel."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
guild = ctx.guild
await self._get_starconfig(guild.id)
star = await self.get_star(guild.id, message.id)
if star is None:
return await ctx.send('Star object not found')
_, em = make_star_embed(star, message)
starrers = [guild.get_member(starrer_id)
for starrer_id in star['starrers']]
em.add_field(name='Starrers', value=', '.join([m.display_name
for m in starrers]))
await ctx.send(embed=em)
def streload(self, ctx, message_id: int):
"""Star reload.
Reload a message, its starrers and update the star in the starboard.
Useful if the starred message was edited.
"""
channel = ctx.channel
cfg = await self._get_starconfig(channel.guild.id)
try:
message = await channel.get_message(message_id)
except discord.NotFound:
raise self.SayException('message not found')
star = await self.get_star(ctx.guild.id, message_id)
if star is None:
raise self.SayException('star object not found')
try:
await self.update_star(cfg, star, msg=message)
except StarError as err:
log.error(f'force_reload: {err!r}')
raise self.SayException(f'rip {err!r}')
await ctx.ok()
def send_log(self, server: discord.Server, log: Log):
"""Sends a embed corresponding to the log in the log channel of the server"""
if server.id in self.servers_config["servers"]:
if "log channel" in self.servers_config["servers"][server.id]:
embed = log.get_embed(self.bot)
channel = self.servers_config["servers"][server.id]["log channel"]
try:
await self.bot.send_message(destination=channel, embed=embed)
except discord.Forbidden:
await self.bot.send_message(destination=server.owner, content=\
"I'm not allowed to send embeds in the log channel (#" + \
channel.name + "). Please change my permissions.")
except discord.NotFound:
await self.bot.send_message(destination=server.owner, content=\
"I'm not allowed to send embeds in the log channel because " + \
"it doesn't exists anymore. Please set another log channel " + \
"using the `[p]set_log_channel` command.")
except discord.HTTPException:
pass
except discord.InvalidArgument:
pass
def say_victory_message(self, msg_winner, msg_no_winner):
serverlist = list(self.bot.servers)
for s in serverlist:
if self.get_victory_messages(s):
try:
msg = msg_winner if self.get_show_result(s) else msg_no_winner
matches_channel = self.bot.get_channel(self.get_matches_channel(s))
if matches_channel:
try:
await self.bot.send_message(matches_channel, msg)
except (discord.Forbidden, discord.NotFound, discord.InvalidArgument):
pass
except discord.HTTPException:
pass
#except Exception as e:
# print("Unable to announce end of match: %s" % e)
def contact(self, ctx, *, message):
"""Sends a message to the bot owner (60s cooldown).
Is not affected by Octarine Core, Refresher Orb, Rearm, or cooldown reduction talents."""
try:
owner = await self.bot.get_owner()
except discord.NotFound:
await self.bot.say("Alas, I know not who my owner is.")
return
author = ctx.message.author
emb = discord.Embed(description = message)
emb.set_author(name = "Message from %s" % author)
try:
await self.bot.send_message(owner, embed = emb)
except discord.InvalidArgument:
await self.bot.say("Alas, I know not where my owner is.")
except discord.HTTPException:
await self.bot.say("Alas, I could not deliver your message. Perhaps it is too long?")
except:
await self.bot.say("Alas, for reasons yet unknown to me, I could not deliver your message.")
else:
await self.bot.say("I have delivered your message with utmost haste! I pray it should arrive safely.")
def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None):
msg = None
try:
msg = await self.send_message(dest, content, tts=tts)
if msg and expire_in:
asyncio.ensure_future(self._wait_delete_msg(msg, expire_in))
if also_delete and isinstance(also_delete, discord.Message):
asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in))
except discord.Forbidden:
if self.config.debug:
print('[PB][PERMISSIONS] Cannot send message to {0}, no permission'.format(dest.name))
except discord.NotFound:
if self.config.debug:
print('[PB][CHANNEL] Cannot send message to {0}, channel does not exist'.format(dest.name))
return msg
def item17(self, ctx, target: discord.Member):
"""Sabotage a weapon
!shop 17 [target]"""
message = ctx.message
language = prefs.getPref(message.server, "language")
if scores.getStat(message.channel, target, "sabotee", "-") == "-":
scores.addToStat(message.channel, message.author, "exp", -14)
scores.setStat(message.channel, target, "sabotee", message.author.name)
await comm.message_user(message, _(":ok: {target}'s weapon is now sabotaged... but they don't know it (14 exp)!", language).format(**{
"target": target.name
}), forcePv=True)
else:
await comm.message_user(message, _(":ok: {target}'s weapon is already sabotaged!", language).format(**{
"target": target.name
}), forcePv=True)
try:
await self.bot.delete_message(ctx.message)
except discord.Forbidden:
await comm.logwithinfos_ctx(ctx, "Error deleting message: forbidden.")
except discord.NotFound:
pass
def on_command(command, ctx):
bot.commands_used[command.name] += 1
await comm.logwithinfos_message(ctx.message, str(command) + " (" + ctx.message.clean_content + ") ")
if prefs.getPref(ctx.message.server, "delete_commands") and checks.is_activated_check(ctx.message.channel):
try:
await bot.delete_message(ctx.message)
except discord.Forbidden:
await comm.logwithinfos_ctx(ctx, "Error deleting message: forbidden.")
except discord.NotFound:
await comm.logwithinfos_ctx(ctx, "Error deleting message: not found (normal if the purgemessages command was used).")
# message = ctx.message
# destination = None
# if message.channel.is_private:
# destination = 'Private Message'
# else:
# destination = '#{0.channel.name} ({0.server.name})'.format(message)
#
# log.info('{0.timestamp}: {0.author.name} in {1}: {0.content}'.format(message, destination))
def hackban(self, ctx, user_id: int):
"""Bans a user outside of the server."""
author = ctx.message.author
guild = author.guild
user = guild.get_member(user_id)
if user is not None:
return await ctx.invoke(self.ban, user=user)
try:
await self.bot.http.ban(user_id, guild.id, 0)
await ctx.message.edit(content=self.bot.bot_prefix + 'Banned user: %s' % user_id)
except discord.NotFound:
await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user. '
'Invalid user ID was provided.')
except discord.errors.Forbidden:
await ctx.message.edit(content=self.bot.bot_prefix + 'Could not ban user. Not enough permissions.')
def edit_message(self, message, content, *, delete=0):
"""
Overrides discord.py's function for editing a message
"""
msg = None
try:
msg = await super().edit_message(message, content)
log.debug(
'Edited message ID {} in #{}'.format(msg.id, msg.channel))
if msg and delete and self.config.delete:
asyncio.ensure_future(self._delete_after(msg, delete))
except discord.Forbidden:
log.warning(
"No permission to edit a message in #{}".format(message.channel))
except discord.NotFound:
log.warning(
"Could not find message ID {} to edit".format(message.id))
except discord.HTTPException as e:
log.warning(
"Problem editing a message in #{}: {}".format(message.channel, e))
return msg
def unban(self, ctx):
"""Unban a user by their ID.
**Usage:** `g_unban <user>`
**Permission:** BAN_MEMBERS"""
if ctx.message.guild.me.guild_permissions.ban_members == True:
if ctx.message.author.guild_permissions.ban_members == True:
try:
umsg = ctx.message.content
args = umsg.split(' ')
uid = int(args[1])
try:
member = await self.bot.get_user_info(uid)
except discord.NotFound:
await ctx.send("I didn't find that user.")
else:
await self.bot.unban(ctx.message.guild, member)
await ctx.send(":white_check_mark: unbanned "+str(member))
except ValueError:
await ctx.send("That is not an ID.")
except IndexError:
await ctx.send("Usage: `{}unban <user id>`".format(self.bot.command_prefix))
else:
await ctx.send("You can't manage bans.")
else:
await ctx.send("I can't manage bans.")
def quote(self, ctx):
"""Get a message from either the current channel or a specified channel.
**Usage:** `g_quote [channel id] <message id>`
**Permission:** User"""
umsg = ctx.message.content
args = umsg.split(' ')
if '--s' in umsg:
await ctx.message.delete()
if len(args) > 1:
try:
if len(args) > 2:
channel = self.bot.get_channel(int(args[1]))
msg = await channel.get_message(int(args[2]))
else:
channel = ctx.message.channel
msg = await channel.get_message(int(args[1]))
em = discord.Embed(title="Found message!",description=msg.content,color=self.randomColour())
em.set_footer(text='Author: {}'.format(str(msg.author)))
em.timestamp = msg.created_at
await ctx.send(embed=em)
except ValueError:
await ctx.send(":x: Please enter an id (or multiple) to find a message.")
except discord.NotFound:
await ctx.send(":x: I'm sorry, but I couldn't find that message. :sob:")
else:
await ctx.send("Improper arguments.")
def edit_invite_blocker(ev, before, after):
if after.guild:
if isinstance(after.author, discord.Member):
if not after.author.permissions_in(after.channel).manage_guild:
active = await ev.db.get_guild_settings(after.guild.id, 'BlockInvites')
if active is None:
active = False
if active:
arguments = after.content.split(' ')
invite_found = False
for arg in arguments:
triggers = ['.gg', '.com', 'http']
for trigger in triggers:
if trigger in arg:
try:
invite_found = await ev.bot.get_invite(arg)
break
except discord.NotFound:
pass
if invite_found:
title = '? Invite links are not allowed on this server.'
response = discord.Embed(color=0xF9F9F9, title=title)
await after.delete()
try:
await after.author.send(embed=response)
except discord.Forbidden:
pass
log_embed = discord.Embed(color=0xF9F9F9)
author = f'{after.author.name}#{after.author.discriminator}'
log_embed.set_author(name=f'I removed {author}\'s invite link.',
icon_url=user_avatar(after.author))
log_embed.set_footer(
text=f'Posted In: #{after.channel.name} | Leads To: {invite_found.guild.name}')
await log_event(ev.db, after.guild, log_embed)
def send_invite_blocker(ev, message):
if message.guild:
if isinstance(message.author, discord.Member):
if not message.author.permissions_in(message.channel).manage_guild:
active = await ev.db.get_guild_settings(message.guild.id, 'BlockInvites')
if active is None:
active = False
if active:
arguments = message.content.split(' ')
invite_found = False
for arg in arguments:
triggers = ['.gg', '.com', 'http']
for trigger in triggers:
if trigger in arg:
try:
invite_found = await ev.bot.get_invite(arg)
break
except discord.NotFound:
pass
if invite_found:
title = '? Invite links are not allowed on this server.'
response = discord.Embed(color=0xF9F9F9, title=title)
await message.delete()
try:
await message.author.send(embed=response)
except discord.Forbidden:
pass
log_embed = discord.Embed(color=0xF9F9F9)
author = f'{message.author.name}#{message.author.discriminator}'
log_embed.set_author(name=f'I removed {author}\'s invite link.',
icon_url=user_avatar(message.author))
log_embed.set_footer(
text=f'Posted In: #{message.channel.name} | Leads To: {invite_found.guild.name}')
await log_event(ev.db, message.guild, log_embed)
def name_checker(ev):
while True:
guild_ids = []
guilds = []
actives = await ev.db[ev.db.db_cfg.database].ServerSettings.find({'ASCIIOnlyNames': True}).to_list(None)
for doc in actives:
gid = doc['ServerID']
guild_ids.append(gid)
for guild_id in guild_ids:
active_guild = discord.utils.find(lambda x: x.id == guild_id, ev.bot.guilds)
if active_guild:
guilds.append(active_guild)
for guild in guilds:
temp_name = await ev.db.get_guild_settings(guild.id, 'ASCIIOnlyTempName')
if temp_name is None:
temp_name = '<ChangeMyName>'
members = guild.members
for member in members:
nam = member.display_name
invalid = False
for char in nam:
if char not in string.printable:
invalid = True
break
if invalid:
try:
new_name = clean_name(nam, temp_name)
await member.edit(nick=new_name, reason='ASCII name enforcement.')
except discord.NotFound:
pass
except discord.Forbidden:
pass
await asyncio.sleep(60)
def mute_checker(ev, message):
if message.guild:
if isinstance(message.author, discord.Member):
if message.author.id not in ev.bot.cfg.dsc.owners:
if not message.author.permissions_in(message.channel).administrator:
mute_list = await ev.db.get_guild_settings(message.guild.id, 'MutedUsers')
if mute_list is None:
mute_list = []
if message.author.id in mute_list:
try:
await message.delete()
except discord.Forbidden:
pass
except discord.NotFound:
pass
def quote(cmd, message, args):
if args:
lookup = args[0]
try:
lookup = int(lookup)
except ValueError:
lookup = None
if lookup:
msg = None
for channel in message.guild.channels:
if isinstance(channel, discord.TextChannel):
try:
msg = await channel.get_message(lookup)
break
except discord.Forbidden:
msg = None
except discord.NotFound:
msg = None
if msg:
if msg.content:
location = f'{msg.guild.name} | #{msg.channel.name}'
response = discord.Embed(color=msg.author.color, timestamp=msg.created_at)
response.set_author(name=f'{msg.author.display_name}', icon_url=user_avatar(msg.author))
response.description = msg.content
response.set_footer(text=location)
else:
response = discord.Embed(color=0xBE1931, title='? That message has no text content.')
else:
response = discord.Embed(color=0xBE1931, title='? Message not found.')
else:
response = discord.Embed(color=0xBE1931, title='? Invalid ID given.')
else:
response = discord.Embed(color=0xBE1931, title='? No ID given.')
await message.channel.send(embed=response)