gpt4 book ai didi

python - Discord.py - 检查用户是否具有执行命令的特定角色

转载 作者:行者123 更新时间:2023-12-01 08:51:29 26 4
gpt4 key购买 nike

我想检查执行命令的用户是否具有管理员角色

这是我的代码:

@client.command(pass_context=True)
@commands.has_role(name='Admin')
async def unban(self, ctx, user):
"""
unbans a user name
:user: user name not mentioned
"""
try:
ban_list = await client.get_bans(ctx.message.server)
if not ban_list:
await self.client.send_message(ctx.message.channel, 'Ban list is empty')
return
for bans in ban_list:
if user.lower() in str(bans).lower():
try:
await self.client.unban(ctx.message.server, bans)
await self.client.send_message(ctx.message.channel, 'Unbanned')
except discord.Forbidden:
await client.send_message(ctx.message.channel, "I don't have permissions to unban")
return
except discord.HTTPException:
await client.send_message(ctx.message.channel, 'Unban failed')
return
else:
await client.send_message(ctx.message.channel, 'This user is not banned from this server')
except:
await client.send_message(ctx.message.channel, "You don't have ``Admin`` role")

但是当我尝试在没有 Admin 角色的情况下执行该命令时,它会显示此错误:

    Ignoring exception in command unban
Traceback (most recent call last):
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
yield from command.invoke(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
yield from self.prepare(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 344, in prepare
self._verify_checks(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 339, in _verify_checks
raise CheckFailure('The check functions for command {0.qualified_name} failed.'.format(self))
discord.ext.commands.errors.CheckFailure: The check functions for command unban failed.

如何检查用户的角色列表中是否具有管理员角色,然后他可以执行此命令?

最佳答案

使用装饰器 @commands.has_role(name='Admin') 已经可以保护该方法免受非管理员用户的攻击。<​​/p>

它在调用方法时引发异常,而不是在方法内部引发异常。

编辑:正如帕特里克在评论中提到的,您需要实现错误处理才能捕获错误:https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#error-handling

关于python - Discord.py - 检查用户是否具有执行命令的特定角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com