本文整理汇总了Python中discord.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python discord.HTTPException方法的具体用法?Python discord.HTTPException怎么用?Python discord.HTTPException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord
的用法示例。
在下文中一共展示了discord.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_fetch_webhook_logs_when_unable_to_fetch_webhook
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例2: test_relay_message_handles_attachment_http_error
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例3: webhook_send
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
def webhook_send(
self,
content: Optional[str] = None,
username: Optional[str] = None,
avatar_url: Optional[str] = None,
embed: Optional[Embed] = None,
) -> None:
"""Sends a message to the webhook with the specified kwargs."""
username = messages.sub_clyde(username)
try:
await self.webhook.send(content=content, username=username, avatar_url=avatar_url, embed=embed)
except discord.HTTPException as exc:
self.log.exception(
"Failed to send a message to the webhook",
exc_info=exc
)
示例4: delete_offensive_msg
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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']}.")
示例5: on_guild_available
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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()
示例6: closeall
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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
示例7: acloseall
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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
示例8: _massmove
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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')
示例9: run
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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
示例10: kick
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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
示例11: ban
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例12: softban
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例13: _colour
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例14: quote
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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)
示例15: _humanize_errors
# 需要导入模块: import discord [as 别名]
# 或者: from discord import HTTPException [as 别名]
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