Python discord.HTTPException() Examples
The following are 30
code examples of discord.HTTPException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: filtering.py From bot with MIT License | 7 votes |
def delete_offensive_msg(self, msg: Mapping[str, str]) -> None: """Delete an offensive message, and then delete it from the db.""" try: channel = self.bot.get_channel(msg['channel_id']) if channel: msg_obj = await channel.fetch_message(msg['id']) await msg_obj.delete() except NotFound: log.info( f"Tried to delete message {msg['id']}, but the message can't be found " f"(it has been probably already deleted)." ) except HTTPException as e: log.warning(f"Failed to delete message {msg['id']}: status {e.status}") await self.bot.api_client.delete(f'bot/offensive-messages/{msg["id"]}') log.info(f"Deleted the offensive message with id {msg['id']}.")
Example #2
Source File: core.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def closeall(self, ctx, *, reason: str = None): category = (await self.bot.get_data(ctx.guild.id))[2] category = ctx.guild.get_channel(category) if category: for channel in category.text_channels: if checks.is_modmail_channel2(self.bot, channel): msg = copy.copy(ctx.message) msg.channel = channel new_ctx = await self.bot.get_context(msg, cls=type(ctx)) await self.close_channel(new_ctx, reason) try: await ctx.send( embed=discord.Embed( description="All channels are successfully closed.", colour=self.bot.primary_colour, ) ) except discord.HTTPException: pass
Example #3
Source File: bot.py From seasonalbot with MIT License | 6 votes |
def set_nickname(self, new_name: str) -> bool: """Set the bot nickname in the main guild to `new_name`.""" member = self.member if member is None: log.info("Failed to get bot member instance, aborting asset upload") return False log.info(f"Attempting to set nickname to {new_name}") try: await member.edit(nick=new_name) except discord.HTTPException as discord_error: log.exception("Setting nickname failed", exc_info=discord_error) return False else: log.info("Nickname set successfully") return True
Example #4
Source File: bot.py From seasonalbot with MIT License | 6 votes |
def send_log(self, title: str, details: str = None, *, icon: str = None) -> None: """Send an embed message to the devlog channel.""" await self.wait_until_guild_available() devlog = self.get_channel(Channels.devlog) if not devlog: log.info(f"Fetching devlog channel as it wasn't found in the cache (ID: {Channels.devlog})") try: devlog = await self.fetch_channel(Channels.devlog) except discord.HTTPException as discord_exc: log.exception("Fetch failed", exc_info=discord_exc) return if not icon: icon = self.user.avatar_url_as(format="png") embed = Embed(description=details) embed.set_author(name=title, icon_url=icon) await devlog.send(embed=embed)
Example #5
Source File: bot.py From rhinobot_heroku with MIT License | 6 votes |
def cmd_setname(self, leftover_args, name): """ Usage: {command_prefix}setname name Changes the bot's username. Note: This operation is limited by discord to twice per hour. """ name = ' '.join([name, *leftover_args]) try: await self.user.edit(username=name) except discord.HTTPException: raise exceptions.CommandError( "Failed to change name. Did you change names too many times? " "Remember name changes are limited to twice per hour.") except Exception as e: raise exceptions.CommandError(e, expire_in=20) return Response("Set the bot's username to **{0}**".format(name), delete_after=20)
Example #6
Source File: roles.py From NabBot with Apache License 2.0 | 6 votes |
def autorole_refresh(self, ctx: NabCtx): """Triggers a refresh on all members. This will apply existing rules to all members. Note that guild changes from members that haven't been online won't be detected. Deleted rules won't have any effect. This command can only be used once per server every day. """ msg = await ctx.send("This will make me check the guilds of all registered characters to apply existing rules." "\nNote that character with outdated information won't be updated until they are online " "again or checked using `whois`\nAre you sure you want this?.") confirm = await ctx.react_confirm(msg, timeout=60, delete_after=True) if not confirm: ctx.command.reset_cooldown(ctx) return msg: discord.Message = await ctx.send("Dispatching events...") for member in ctx.guild.members: self.bot.dispatch("character_change", member.id) try: await msg.edit(content=f"{ctx.tick()} Refresh done, roles will be updated shortly.") except discord.HTTPException: await ctx.success("Refresh done, roles will be updated shortly.")
Example #7
Source File: settings.py From bot with MIT License | 6 votes |
def load_invites(self, gid: int = None): guilds = [g for g in self.bot.premium_guilds] if not gid else [gid] for g in guilds: guild = self.bot.get_guild(g) if not guild: continue invites = [] try: invites = await guild.invites() if 'VANITY_URL' in guild.features: vanity = await guild.vanity_invite() invites.append(vanity) except (discord.Forbidden, discord.HTTPException) as e: if isinstance(e, discord.Forbidden): continue if isinstance(e, discord.HTTPException) and invites == []: continue ginvites = {guild.id: {}} for invite in invites: ginvites[guild.id][invite.code] = invite.uses await self.bot.redis.set(f'invites.{guild.id}', json.dumps(ginvites)) if gid and len(guilds) == 1: return ginvites[guild.id]
Example #8
Source File: timers.py From NabBot with Apache License 2.0 | 6 votes |
def on_event_notification(self, event: 'Event', reminder): """Announces upcoming events""" log.info(f"{self.tag} Sending event notification | Event '{event.name}' | ID: {event.id}") guild: Optional[discord.Guild] = self.bot.get_guild(event.server_id) if guild is None: return author = guild.get_member(event.user_id) author_name = author.display_name if author else "unknown" delta = HumanDelta(NOTIFICATIONS[reminder]) message = f"Event: **{event.name}** (ID: {event.id} | by **@{author_name}**) - Is starting {delta.long(1)}" announce_channel_id = await get_server_property(self.bot.pool, guild.id, "events_channel", default=0) if announce_channel_id == 0: return announce_channel = self.bot.get_channel_or_top(guild, announce_channel_id) if announce_channel is not None: try: await announce_channel.send(message) except discord.HTTPException: log.debug(f"{self.tag} Could not send event event notification " f"| Channel {announce_channel.id} | Server {announce_channel.guild.id}") await self.notify_subscribers(event, message)
Example #9
Source File: test_duck_pond.py From bot with MIT License | 6 votes |
def test_relay_message_handles_attachment_http_error(self, send_attachments, send_webhook): """The `relay_message` method should handle irretrievable attachments.""" message = helpers.MockMessage(clean_content="message", attachments=["attachment"]) self.cog.webhook = helpers.MockAsyncWebhook() log = logging.getLogger("bot.cogs.duck_pond") side_effect = discord.HTTPException(MagicMock(), "") send_attachments.side_effect = side_effect with self.subTest(side_effect=type(side_effect).__name__): with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher: await self.cog.relay_message(message) send_webhook.assert_called_once_with( content=message.clean_content, username=message.author.display_name, avatar_url=message.author.avatar_url ) self.assertEqual(len(log_watcher.records), 1) record = log_watcher.records[0] self.assertEqual(record.levelno, logging.ERROR)
Example #10
Source File: test_duck_pond.py From bot with MIT License | 6 votes |
def test_fetch_webhook_logs_when_unable_to_fetch_webhook(self): """The `fetch_webhook` method should log an exception when it fails to fetch the webhook.""" self.bot.fetch_webhook.side_effect = discord.HTTPException(response=MagicMock(), message="Not found.") self.cog.webhook_id = 1 log = logging.getLogger('bot.cogs.duck_pond') with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher: asyncio.run(self.cog.fetch_webhook()) self.bot.wait_until_guild_available.assert_called_once() self.bot.fetch_webhook.assert_called_once_with(1) self.assertEqual(len(log_watcher.records), 1) record = log_watcher.records[0] self.assertEqual(record.levelno, logging.ERROR)
Example #11
Source File: meta.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def support(self, context): """Directs you to the support server.""" ch = self.bot.get_channel(self.bot.config['support_server'].get('invite_channel_id')) if ch is None: await context.send(_('This command is temporarily unavailable. Try again later?')) return reason = f'Created for {context.author} (ID: {context.author.id})' invite = await ch.create_invite(max_age=self.INVITE_DURATION_SECONDS, max_uses=self.MAX_INVITE_USES, reason=reason) try: await context.author.send(_('Official support server invite: {invite}').format(invite=invite)) except discord.Forbidden: await context.try_add_reaction(utils.SUCCESS_EMOJIS[False]) with contextlib.suppress(discord.HTTPException): await context.send(_('Unable to send invite in DMs. Please allow DMs from server members.')) else: await context.try_add_reaction('\N{open mailbox with raised flag}')
Example #12
Source File: bot.py From bot with MIT License | 6 votes |
def on_guild_available(self, guild: discord.Guild) -> None: """ Set the internal guild available event when constants.Guild.id becomes available. If the cache appears to still be empty (no members, no channels, or no roles), the event will not be set. """ if guild.id != constants.Guild.id: return if not guild.roles or not guild.members or not guild.channels: msg = "Guild available event was dispatched but the cache appears to still be empty!" log.warning(msg) try: webhook = await self.fetch_webhook(constants.Webhooks.dev_log) except discord.HTTPException as e: log.error(f"Failed to fetch webhook to send empty cache warning: status {e.status}") else: await webhook.send(f"<@&{constants.Roles.admin}> {msg}") return self._guild_available.set()
Example #13
Source File: core.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def acloseall(self, ctx, *, reason: str = None): category = (await self.bot.get_data(ctx.guild.id))[2] category = ctx.guild.get_channel(category) if category: for channel in category.text_channels: if checks.is_modmail_channel2(self.bot, channel): msg = copy.copy(ctx.message) msg.channel = channel new_ctx = await self.bot.get_context(msg, cls=type(ctx)) await self.close_channel(new_ctx, reason, True) try: await ctx.send( embed=discord.Embed( description="All channels are successfully closed anonymously.", colour=self.bot.primary_colour, ) ) except discord.HTTPException: pass
Example #14
Source File: massmove.py From refactored-cogs with Mozilla Public License 2.0 | 6 votes |
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')
Example #15
Source File: logging.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def _log(self, *, event, nsfw, embed) -> typing.List[discord.Message]: await self.configured.wait() # don't let people bypass logging by taking actions before logging is set up async def send(channel): try: return await channel.send(embed=embed) except discord.HTTPException as exception: logging.error(f'Sending a log ({embed}) to {channel!r} failed:') logging.error(utils.format_http_exception(exception)) coros = [ send(channel) for channel in self.channels if await self.can_log(event=event, nsfw=nsfw, channel=channel)] return [ result # ignore all exceptions in sending to any of the channels, # and don't cancel sending messages if one of the channels fails for result in await asyncio.gather(*coros, return_exceptions=True) if isinstance(result, discord.Message)]
Example #16
Source File: emote.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def on_message(self, message): """Reply to messages containing :name: or ;name; with the corresponding emotes. This is like half the functionality of the bot """ await self.bot.set_locale(message) if not await self._should_auto_reply(message): return reply, has_emotes = await self.extract_emotes(message, log_usage=True) if not has_emotes: return try: reply = await message.channel.send(reply) except discord.HTTPException: return await self.db.add_reply_message(message.id, MessageReplyType.auto, reply.id)
Example #17
Source File: emote.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def _humanize_errors(error): if isinstance(error, errors.PermissionDeniedError): return 1, _('**Not authorized:**') if isinstance(error, errors.EmoteExistsError): # translator's note: the next five strings are displayed as errors # when the user tries to add/remove an emote return 2, _('**Already exists:**') if isinstance(error, errors.EmoteNotFoundError): # same priority as EmoteExists return 2, _('**Not found:**') if isinstance(error, (discord.HTTPException, errors.HTTPException)): return 3, _('**Server returned error code {error.status}:**').format(error=error) if isinstance(error, asyncio.TimeoutError): return 4, _('**Took too long to retrieve or resize:**') if isinstance(error, errors.NoMoreSlotsError): return 5, _('**Failed because I ran out of backend servers:**') # unhandled errors are still errors raise error
Example #18
Source File: paginator.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def run(self) -> typing.Optional[Message]: """ Starts the pagination session. Returns ------- Optional[Message] If it's closed before running ends. """ if not self.running: await self.show_page(self.current) while self.running: try: reaction, user = await self.ctx.bot.wait_for( "reaction_add", check=self.react_check, timeout=self.timeout ) except asyncio.TimeoutError: return await self.close(delete=False) else: action = self.reaction_map.get(reaction.emoji) await action() try: await self.base.remove_reaction(reaction, user) except (HTTPException, InvalidArgument): pass
Example #19
Source File: emote.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def quote(self, context, *, message): """Quotes your message, with :foo: and ;foo; replaced with their emote forms""" if not message: return message, has_emotes = await self.quote_emotes(context.message, message) should_track_reply = True if self.bot.has_permissions(context.message, manage_messages=True): # no space because rest_is_raw preserves the space after "ec/quote" message = _('{context.author.mention} said:').format(**locals()) + message # Since delete() with a delay defers execution to a Task, we need not handle HTTPException here. # We delay the deletion to work around a bug in Discord for Android where quickly-deleted messages # persist client-side. await context.message.delete(delay=0.2) should_track_reply = False reply = await context.send(message) if should_track_reply: await self.db.add_reply_message(context.message.id, MessageReplyType.quote, reply.id)
Example #20
Source File: mod.py From Discord-SelfBot with MIT License | 6 votes |
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
Example #21
Source File: mod.py From Discord-SelfBot with MIT License | 6 votes |
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)
Example #22
Source File: mod.py From Discord-SelfBot with MIT License | 6 votes |
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)
Example #23
Source File: mod.py From Discord-SelfBot with MIT License | 6 votes |
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)
Example #24
Source File: misc.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def format_http_exception(exception: discord.HTTPException): """Formats a discord.HTTPException for relaying to the user. Sample return value: BAD REQUEST (status code: 400): Invalid Form Body In image: File cannot be larger than 256 kb. """ return ( f'{exception.response.reason} (status code: {exception.response.status}):' f'\n{exception.text}')
Example #25
Source File: paginator.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def add_reactions(self): for reaction in self.reaction_emojis: if self.maximum_pages == 2 and reaction in {'⏮', '⏭'}: # no |<< or >>| buttons if we only have two pages # we can't forbid it if someone ends up using it but remove # it from the default set continue with contextlib.suppress(discord.HTTPException): await self.message.add_reaction(reaction)
Example #26
Source File: roles.py From NabBot with Apache License 2.0 | 5 votes |
def group(self, ctx: NabCtx, *, _group: InsensitiveRole): """Joins or leaves a group (role). If you're not in the group, you will be added. If you're already in the group, you will be removed. To see a list of joinable groups, use `group list`""" group: discord.Role = _group exists = await ctx.pool.fetchval("SELECT true FROM role_joinable WHERE role_id = $1", group.id) if not exists: await ctx.error(f"Group `{group.name}` doesn't exists.") return # Check if user already has the role member_role = discord.utils.get(ctx.author.roles, id=group.id) try: if member_role is None: await ctx.author.add_roles(group, reason="Joined group") else: await ctx.author.remove_roles(member_role, reason="Left group") except discord.Forbidden: await ctx.error("I need `Manage Roles` to manage groups.") except discord.HTTPException: await ctx.error("Something went wrong. Try again later.") else: if member_role is None: await ctx.success(f"Joined `{group.name}`.") else: await ctx.success(f"You left `{group.name}`.")
Example #27
Source File: paginator.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def numbered_page(self): """lets you type a page number to go to""" to_delete = [] to_delete.append(await self.channel.send(_('What page do you want to go to?'))) def message_check(m): return m.author == self.author and \ self.channel == m.channel and \ m.content.isdigit() try: msg = await self.bot.wait_for('message', check=message_check, timeout=30.0) except asyncio.TimeoutError: to_delete.append(await self.channel.send(_('You took too long.'))) await asyncio.sleep(5) else: page = int(msg.content) to_delete.append(msg) if page != 0 and page <= self.maximum_pages: await self.show_page(page) else: to_delete.append(await self.channel.send(_( 'Invalid page given. ({page}/{self.maximum_pages})').format(**locals()))) await asyncio.sleep(5) for message in to_delete: # we could use self.channel.delete_messages, but doing so would stop as soon as one of them fails # doing it this way ensures all of them are deleted with contextlib.suppress(discord.HTTPException): await message.delete()
Example #28
Source File: backend_creator.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def delete_guilds(): for guild in bot.guilds: with contextlib.suppress(discord.HTTPException): await guild.delete()
Example #29
Source File: help.py From seasonalbot with MIT License | 5 votes |
def stop(self) -> None: """Stops the help session, removes event listeners and attempts to delete the help message.""" self._bot.remove_listener(self.on_reaction_add) self._bot.remove_listener(self.on_message_delete) # ignore if permission issue, or the message doesn't exist with suppress(HTTPException, AttributeError): if self._cleanup: await self.message.delete() else: await self.message.clear_reactions()
Example #30
Source File: backend_creator.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
def create_guild(): global guild_count try: guild = await bot.create_guild(format_guild_name(guild_count)) except discord.HTTPException: return guild_count += 1 return guild