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}')
python类HTTPException()的实例源码
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 on_member_join(self, member):
guild = member.guild
if guild.id in WHITELIST:
return
bots, humans, ratio = self.bot_human_ratio(guild)
bot_ratio = await self.guild_ratio(guild)
if ratio > bot_ratio:
log.info(f'[bh:leave:member_join] leaving {guild!r} {guild.id},'
f' {ratio} ({len(bots)} / {len(humans)}) > {bot_ratio}')
try:
await guild.owner.send('Your guild was classified as a bot'
'collection, josé automatically left.'
f'{len(bots)} bots, {len(humans)} humans, '
f'{ratio}b/h, ratio is over {BOT_RATIO_MAX}')
except discord.HTTPException:
pass
await guild.leave()
def check_reactions_clear(self, message, reactions):
"""Checks for reactions clears"""
#pylint: disable=unused-argument
#pylint: disable=too-many-nested-blocks
if message.author.id not in self.bot.blacklist:
for com in self.communications:
for msg in self.communications[com].messages:
if msg["id"] == message.id:
msg["reactions"] = {}
index = -1
for i in range(0, len(msg["embed"].fields)):
if msg["embed"].fields[i].name == "Reactions":
index = i
break
if index != -1:
msg["embed"].remove_field(index)
for message_sent in msg["messages"]:
try:
await self.bot.edit_message(message_sent, embed=msg["embed"])
except discord.HTTPException:
pass
def set_avatar(self, avatar_link : str):
"""Sets bot's avatar
Parameters:
avatar_link: The link of the the picture which will become the new bot's avatar
Example: [p]set_avatar http://i.imgur.com/bjmbH1e.png"""
r = requests.get(avatar_link)
if r.status_code == 200:
try:
await self.bot.edit_profile(avatar=r.content)
await self.bot.say("Done!")
except discord.HTTPException:
await self.bot.say("HTTP Exception")
except discord.InvalidArgument:
await self.bot.say("Wrong image format")
except requests.exceptions.MissingSchema:
await self.bot.say("Invalid URL")
else:
await self.bot.say("Error " + str(r.status_code) + ": The link must be incorrect, " \
+ "make sure the link finishes with `.png`, `.jpg`, `.jpeg`, etc")
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 check_new_comers(self, member):
"""Checks if a new comer is in the b1nzy banlist"""
if member.server.id in self.b1nzy_banlist:
if member.id in self.b1nzy_banlist[member.server.id]:
try:
await self.bot.ban(member)
self.b1nzy_banlist[member.server.id].remove(member.id)
if not self.b1nzy_banlist[member.server.id]:
del self.b1nzy_banlist[member.server.id]
self.save_b1nzy_banlist()
except discord.Forbidden:
await self.bot.send_message(member.server.owner, \
"Couldn't ban " + member.name + "#" + member.discriminator + \
" (" + member.id + ") who's in the b1nzy banlist --> missing permissions")
except discord.HTTPException:
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 kick(self, ctx, member: str, *, reason: str=None):
"""Kick a Member."""
member = getUser(ctx, member)
if member:
try:
await ctx.guild.kick(member, reason=reason)
except discord.Forbidden:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to kick this Member", ttl=5)
except discord.HTTPException:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Something went wrong while trying to kick...", ttl=5)
else:
e = discord.Embed(color=embedColor(self))
e.set_author(icon_url="https://cdn.discordapp.com/attachments/278603491520544768/301084579660300289/301063051296374794.png",
name="Kicked: " + str(member))
await edit(ctx, embed=e)
# Ban a Member
def ban(self, ctx, member: str, *, reason: str=None):
"""Ban a Member."""
member = getUser(ctx, member)
if member:
try:
await ctx.guild.ban(member, reason=reason)
except discord.Forbidden:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to ban this Member", ttl=5)
except discord.HTTPException:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Something went wrong while trying to ban...", ttl=5)
else:
e = discord.Embed(color=embedColor(self))
e.set_author(icon_url="https://cdn.discordapp.com/attachments/278603491520544768/301087009408024580/273910007857414147.png",
name="Banned: " + str(member))
await edit(ctx, embed=e)
# SoftBan a Member (ban, delelte messagea and unban)
def softban(self, ctx, member: str, *, reason: str=None):
"""Softban a Member(Kick and delete Messages)"""
member = getUser(ctx, member)
if member:
try:
await ctx.guild.ban(member, reason=reason)
await ctx.guild.unban(member)
except discord.Forbidden:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to ban this Member", ttl=5)
except discord.HTTPException:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Something went wrong while trying to ban...", ttl=5)
else:
e = discord.Embed(color=embedColor(self))
e.set_author(icon_url="https://cdn.discordapp.com/attachments/278603491520544768/301087009408024580/273910007857414147.png",
name="Soft Banned: " + str(member))
await edit(ctx, embed=e)
def _colour(self, ctx, role: str, colour: str):
"""Set the Color of a Role."""
role = getRole(ctx, role)
colour = getColor(colour)
if not role:
return await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Role not found", ttl=5)
elif not colour:
return await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Colour not found", ttl=5)
else:
value = discord.Colour(int((colour.hex_l.strip('#')), 16))
try:
await role.edit(colour=value)
except discord.HTTPException:
await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to edit this role", ttl=5)
else:
e = discord.Embed(color=value)
e.set_author(name="Changed Role Color of: " + str(role))
await edit(ctx, embed=e)
def raid_off(self, ctx):
"""Disables raid mode on the server.
When disabled, the server verification levels are set
back to Low levels and the bot will stop broadcasting
join messages.
"""
try:
await ctx.guild.edit(verification_level=discord.VerificationLevel.low)
except discord.HTTPException:
await ctx.send('\N{WARNING SIGN} Could not set verification level.')
query = """INSERT INTO guild_mod_config (id, raid_mode, broadcast_channel)
VALUES ($1, $2, NULL) ON CONFLICT (id)
DO UPDATE SET
raid_mode = EXCLUDED.raid_mode,
broadcast_channel = NULL;
"""
await ctx.db.execute(query, ctx.guild.id, RaidMode.off.value)
self._recently_kicked.pop(ctx.guild.id, None)
await ctx.send('Raid mode disabled. No longer broadcasting join messages.')
def nostalgia(self, ctx, date: date, *, channel: discord.TextChannel = None):
"""Pins an old message from a specific date.
If a channel is not given, then pins from the channel the
command was ran on.
The format of the date must be either YYYY-MM-DD or YYYY/MM/DD.
"""
channel = channel or ctx.channel
message = await channel.history(after=date, limit=1).flatten()
if len(message) == 0:
return await ctx.send('Could not find message.')
message = message[0]
try:
await message.pin()
except discord.HTTPException:
await ctx.send('Could not pin message.')
else:
await ctx.send('Pinned message.')
def feeds_delete(self, ctx, *, feed: str):
"""Removes a feed from the channel.
This will also delete the associated role so this
action is irreversible.
"""
query = 'DELETE FROM feeds WHERE channel_id=$1 AND name=$2 RETURNING *;'
records = await ctx.db.fetch(query, ctx.channel.id, feed)
self.get_feeds.invalidate(self, ctx.channel.id)
if len(records) == 0:
return await ctx.send('This feed does not exist.')
for record in records:
role = discord.utils.find(lambda r: r.id == record['role_id'], ctx.guild.roles)
if role is not None:
try:
await role.delete()
except discord.HTTPException:
continue
await ctx.send(f'{ctx.tick(True)} Removed feed.')
def _massmove(self, ctx, from_channel, to_channel):
"""Internal function: Massmove users to another voice channel"""
# check if channels are voice channels. Or moving will be very... interesting...
type_from = str(from_channel.type)
type_to = str(to_channel.type)
if type_from == 'text':
await self.bot.say('{} is not a valid voice channel'.format(from_channel.name))
log.debug('SID: {}, from_channel not a voice channel'.format(from_channel.server.id))
elif type_to == 'text':
await self.bot.say('{} is not a valid voice channel'.format(to_channel.name))
log.debug('SID: {}, to_channel not a voice channel'.format(to_channel.server.id))
else:
try:
log.debug('Starting move on SID: {}'.format(from_channel.server.id))
log.debug('Getting copy of current list to move')
voice_list = list(from_channel.voice_members)
for member in voice_list:
await self.bot.move_member(member, to_channel)
log.debug('Member {} moved to channel {}'.format(member.id, to_channel.id))
await asyncio.sleep(0.05)
except discord.Forbidden:
await self.bot.say('I have no permission to move members.')
except discord.HTTPException:
await self.bot.say('A error occured. Please try again')
def _mdm(self, ctx: commands.Context,
role: discord.Role, *, message: str):
"""Sends a DM to all Members with the given Role.
Allows for the following customizations:
{0} is the member being messaged.
{1} is the role they are being message through.
{2} is the person sending the message.
"""
server = ctx.message.server
sender = ctx.message.author
try:
await self.bot.delete_message(ctx.message)
except:
pass
dm_these = self._get_users_with_role(server, role)
for user in dm_these:
try:
await self.bot.send_message(user,
message.format(user, role, sender))
except (discord.Forbidden, discord.HTTPException):
continue
def run(self, token):
"""
Override's discord.py's function for running the bot
"""
try:
super().run(token, bot=(not self.config.selfbot))
except discord.LoginFailure:
log.critical("Incorrect login token")
if not self.config.selfbot:
log.critical(
"Using your own token? Change 'selfbot' to 'True' in the config")
else:
log.critical(
"Using an OAuth account? Change 'selfbot' to 'False' in the config")
except discord.HTTPException as e:
log.critical(e)
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