我想在“ {ready
”命令中添加一些if语句,例如:“如果用户具有角色A,B,C中的任何一个”,则执行操作。否则,如果用户具有D,E,F角色中的任何一个,则执行其他操作。我认为,如果有人可以帮助我解决下面的堆栈跟踪错误,那么它很可能会解决代码下方的问题
import logging
import time
import discord
import asyncio
import time
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument
prefix = "!"
bot = commands.Bot(command_prefix=prefix, case_insensitive=True)
token = open("token.txt", "r").read()
class MemberRoles(commands.MemberConverter):
async def convert(self, ctx, argument):
member = await super().convert(ctx, argument)
return [role.name for role in member.roles[1:]] # Remove everyone role!
@bot.command()
#i prefer not using @commands.has_any_role decorator because i want my 1 "ready" command to branch based on the role(s) the user has
#I am trying to make my bot command able to do multiple role checks
#I am trying to adapt this example "async def roles(ctx, *, member: MemberRoles):" from https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html
async def ready(ctx, *, message: str, member: MemberRoles):
'''
!ready must include text after the command and can only be used if you are assigned ANY of these roles: Admin, Newbie
'''
if message is None:
return
else:
try:
#stuff
except Exception as e:
print(str(e))
#This part, about detecting which roles a member has does not work, see the question below the code for more information
await ctx.send('I see the following roles: ' + ', '.join(member))
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.channel.send("Cannot ready without a message. Type !ready <your message> and try again.")
else:
raise error
bot.run(token)
我认为,如果有人可以帮助我解决此堆栈跟踪错误,那么我可以解决下面的“问题”。 堆栈跟踪错误在“ raise error
”点出现。我看到的错误是“ discord.ext.commands.errors.CommandInvokeError:命令引发了异常:TypeError:ready()缺少1个仅关键字必需的参数:'member'“
问题:假定“ MemberRoles”类是实现此目的的好方法,那么我如何在“ ready”命令中使用它来实现A,B,C和D,E ,F如果我需要其他分支?
感谢您的帮助!
答案 0 :(得分:1)
在命令中只能有一个仅关键字参数,因为discord.py使用仅关键字参数to collect the end of a message。实际上,您只需要作者角色,因此根本不需要使用转换器:
@bot.command
async def ready(ctx, *, message: str):
author_roles = ctx.author.roles
...
关于检查角色,您可以做类似
的操作roles_one = {"A", "B", "B"}
roles_two = {"D", "E", "F"}
if any(role.name in roles_one for role in author_roles):
...
elif not any(role.name in roles_two for role in author_roles):
...