本文整理汇总了Python中discord.Forbidden方法的典型用法代码示例。如果您正苦于以下问题:Python discord.Forbidden方法的具体用法?Python discord.Forbidden怎么用?Python discord.Forbidden使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord
的用法示例。
在下文中一共展示了discord.Forbidden方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _change_cooldown_role
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def _change_cooldown_role(self, member: discord.Member, coro_func: CoroutineFunc) -> None:
"""
Change `member`'s cooldown role via awaiting `coro_func` and handle errors.
`coro_func` is intended to be `discord.Member.add_roles` or `discord.Member.remove_roles`.
"""
guild = self.bot.get_guild(constants.Guild.id)
role = guild.get_role(constants.Roles.help_cooldown)
if role is None:
log.warning(f"Help cooldown role ({constants.Roles.help_cooldown}) could not be found!")
return
try:
await coro_func(role)
except discord.NotFound:
log.debug(f"Failed to change role for {member} ({member.id}): member not found")
except discord.Forbidden:
log.debug(
f"Forbidden to change role for {member} ({member.id}); "
f"possibly due to role hierarchy"
)
except discord.HTTPException as e:
log.error(f"Failed to change role for {member} ({member.id}): {e.status} {e.code}")
示例2: convert
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def convert(self, ctx, argument):
id_regex = re.compile(r'^(?:(?P<channel_id>[0-9]{15,21})-)?(?P<message_id>[0-9]{15,21})$')
link_regex = re.compile(
r'^https?://(?:(ptb|canary)\.)?discord(?:app)?\.com/channels/'
r'(?:([0-9]{15,21})|(@me))'
r'/(?P<channel_id>[0-9]{15,21})/(?P<message_id>[0-9]{15,21})/?$'
)
match = id_regex.match(argument) or link_regex.match(argument)
if not match:
raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
message_id = int(match.group("message_id"))
channel_id = match.group("channel_id")
message = ctx.bot._connection._get_message(message_id)
if message:
return message
channel = ctx.bot.get_channel(int(channel_id)) if channel_id else ctx.channel
if not channel:
raise BadArgument('Channel "{channel}" not found.'.format(channel=channel_id))
try:
return await channel.fetch_message(message_id)
except discord.NotFound:
raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
except discord.Forbidden:
raise BadArgument("Can't read messages in {channel}".format(channel=channel.mention))
示例3: on_command_error
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def on_command_error(self, ctx, exception):
self.stats.increment("RPGBot.errors", tags=["RPGBot:errors"], host="scw-8112e8")
logging.info(f"Exception in {ctx.command} {ctx.guild}:{ctx.channel} {exception}")
exception = getattr(exception, "original", exception)
traceback.print_tb(exception.__traceback__)
print(exception)
try:
if isinstance(exception, commands.MissingRequiredArgument):
await ctx.send(f"```{exception}```")
elif isinstance(exception, TimeoutError):
await ctx.send(await _(ctx, "This operation ran out of time! Please try again"))
elif isinstance(exception, discord.Forbidden):
await ctx.send(await _(ctx, "Error: This command requires the bot to have permission to send links."))
else:
await ctx.send(f"`{exception} If this is unexpected, please report this to the bot creator`")
except discord.Forbidden:
pass
示例4: _massmove
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [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')
示例5: item23
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def item23(self, ctx):
"""Buy a mechanical duck (40 exp)
!shop 23"""
message = ctx.message
_ = self.bot._;
language = await self.bot.db.get_pref(ctx.channel, "language")
try:
await ctx.message.delete()
except discord.Forbidden:
await self.bot.hint(ctx=ctx, message=_("If you ask a server admin to give me the `manage_message` permission, I will be able to delete that kind of shop commands ;)", language))
except discord.NotFound:
pass
await self.bot.db.add_to_stat(message.channel, message.author, "exp", -40)
await self.bot.send_message(ctx=ctx, force_pm=True, message=_(":money_with_wings: You prepared a mechanical duck on the channel for 40 exp. It's wrong, but so funny!", language))
async def spawn_mech_duck():
await asyncio.sleep(90)
duck = await ducks.MechanicalDuck.create(self.bot, ctx.channel, user=ctx.message.author)
await spawning.spawn_duck(self.bot, ctx.channel, instance=duck, ignore_event=True)
asyncio.ensure_future(spawn_mech_duck())
示例6: kick
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def kick(self, ctx, user, *, reason=""):
"""Kicks a user (if you have the permission)."""
user = get_user(ctx.message, user)
if user:
try:
await user.kick(reason=reason)
return_msg = "Kicked user `{}`".format(user.mention)
if reason:
return_msg += " for reason `{}`".format(reason)
return_msg += "."
await ctx.message.edit(content=self.bot.bot_prefix + return_msg)
except discord.Forbidden:
await ctx.message.edit(content=self.bot.bot_prefix + 'Could not kick user. Not enough permissions.')
else:
return await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user.')
# TODO: Add reason with ban
示例7: hackban
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
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.')
示例8: mute
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def mute(self, ctx, *, user: str):
"""Chat mutes a user (if you have the permission)."""
if ctx.invoked_subcommand is None:
user = get_user(ctx.message, user)
if user and user != self.bot.user:
failed = []
channel_length = 0
for channel in ctx.message.guild.channels:
if type(channel) != discord.channel.TextChannel:
continue
overwrites = channel.overwrites_for(user)
overwrites.send_messages = False
channel_length += 1
try:
await channel.set_permissions(user, overwrite=overwrites)
except discord.Forbidden:
failed.append(channel)
if failed and len(failed) < channel_length:
await ctx.message.edit(content=self.bot.bot_prefix + "Muted user in {}/{} channels: {}".format(channel_length - len(failed), channel_length, user.mention))
elif failed:
await ctx.message.edit(content=self.bot.bot_prefix + "Failed to mute user. Not enough permissions.")
else:
await ctx.message.edit(content=self.bot.bot_prefix + 'Muted user: %s' % user.mention)
else:
await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user.')
示例9: channel
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def channel(self, ctx, *, user: str):
user = get_user(ctx.message, user)
if user:
overwrites = ctx.message.channel.overwrites_for(user)
is_empty = self.are_overwrites_empty(overwrites)
try:
if not is_empty:
ctx.message.channel.set_permissions(user, overwrite=overwrites)
else:
await channel.set_permissions(user, overwrite=None)
await channel.set_permissions(user, overwrite=overwrites)
await ctx.message.edit(content=self.bot.bot_prefix + 'Unmuted user in this channel: %s' % user.mention)
except discord.Forbidden:
await ctx.message.edit(content=self.bot.bot_prefix + 'Unable to unmute user. Not enough permissions.')
else:
await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user.')
示例10: servercount
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def servercount(self, ctx: commands.Context):
"""Send servers stats of the bot."""
msg = _(
"{name} is running on `{shard_count}` {shards}.\n"
"Serving `{servs}` servers (`{channels}` channels).\n"
"For a total of `{users}` users (`{unique}` unique).\n"
"(`{users}` visible now, `{real_total}` total)"
).format(
name=ctx.bot.user.name,
shard_count=humanize_number(self.bot.shard_count),
shards=_("shards") if self.bot.shard_count > 1 else _("shard"),
servs=humanize_number(len(self.bot.guilds)),
channels=humanize_number(sum(len(s.channels) for s in self.bot.guilds)),
users=humanize_number(sum(len(s.members) for s in self.bot.guilds)),
unique=humanize_number(len(self.bot.users)),
real_total=humanize_number(sum(s.member_count for s in self.bot.guilds)),
)
try:
em = discord.Embed(color=await ctx.embed_colour(), description=msg)
await ctx.send(embed=em)
except discord.Forbidden:
await ctx.send(msg)
示例11: removerole
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def removerole(self, ctx, rolename, user: discord.Member=None):
"""Removes a role from user, defaults to author
Role name must be in quotes if there are spaces."""
server = ctx.message.server
author = ctx.message.author
role = self._role_from_string(server, rolename)
if role is None:
await self.bot.say("Role not found.")
return
if user is None:
user = author
if role in user.roles:
try:
await self.bot.remove_roles(user, role)
await self.bot.say("Role successfully removed.")
except discord.Forbidden:
await self.bot.say("I don't have permissions to manage roles!")
else:
await self.bot.say("User does not have that role.")
示例12: whisper
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def whisper(self, ctx, id, *, text):
author = ctx.message.author
target = discord.utils.get(self.bot.get_all_members(), id=id)
if target is None:
target = self.bot.get_channel(id)
if target is None:
target = self.bot.get_server(id)
prefix = "Hello, you're getting a message from {} ({})".format(
author.name, author.id)
payload = "{}\n\n{}".format(prefix, text)
try:
for page in pagify(payload, delims=[" ", "\n"], shorten_by=10):
await self.bot.send_message(target, box(page))
except discord.errors.Forbidden:
log.debug("Forbidden to send message to {}".format(id))
except (discord.errors.NotFound, discord.errors.InvalidArgument):
log.debug("{} not found!".format(id))
else:
await self.bot.say("Done.")
示例13: sendembed
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def sendembed(self, ctx, color:Optional[discord.Color]=None, *, text):
"""
Send an embed.
Use the optional parameter `color` to change the color of the embed.
The embed will contain the text `text`.
All normal discord formatting will work inside the embed.
"""
if color is None:
color = await ctx.embed_color()
embed = discord.Embed(
description=text,
color=color
)
await ctx.send(embed=embed)
try:
await ctx.message.delete()
except discord.Forbidden:
pass
示例14: on_member_join
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def on_member_join(self, m):
config = await self.bot.db.config.find_one({'_id': str(m.guild.id)})
if not config:
return
try:
type = config['welctype']
except KeyError:
return
if type is False:
return
channel = int(config['welcchannel'])
msg = config['welc']
success = False
i = 0
while not success:
try:
await self.bot.get_channel(channel).send(msg.format(name=m, server=m.guild, mention=m.mention, member=m, membercount=len(m.guild.members)))
except (discord.Forbidden, AttributeError):
i += 1
except IndexError:
# the channel set doesn't allow remixbot to send messages
pass
else:
success = True
示例15: say
# 需要导入模块: import discord [as 别名]
# 或者: from discord import Forbidden [as 别名]
def say(channel, *args, **kwargs):
if type(channel) is str:
# Server/Channel id
server_id, channel_id = channel.split("/")
channel = get_server(server_id).get_channel(channel_id)
if "client" in kwargs:
client = kwargs["client"]
del kwargs["client"]
else:
client = get_client(channel.server.id)
if asyncio.get_event_loop() != client.loop:
# Allows it to speak across shards
client.run_task(say, *((channel,) + args), **kwargs)
else:
try:
await client.send_message(channel, *args, **kwargs)
except discord.Forbidden as send_error:
raise SendMessagePermMissing(send_error)