问题描述
我正在尝试编辑代码,以便它检查discord.py命令后是否有任何字符串,如下所示。
@client.command(pass_context=True)
async def dankrate(ctx,*,message):
message_author = ctx.author
message_channel = ctx.channel
print(message)
aaaaa = random.randint(1,101)
print("{} issued .dankrate ?".format(message_author))
if aaaaa == 101:
embedVar = discord.Embed(title="Dank r8 Machine",description=f"you broke the dank machine >:( :fire:\n{message} is {aaaaa}% dank",color=15105570)
else:
embedVar = discord.Embed(title="Dank r8 Machine",description=f"{message} is {aaaaa}% dank",color=3066993)
await message_channel.send(embed=embedVar)
它按预期工作,但是当您使用带有字符串的dankrate命令 运行时,例如“ .dankrate e”,但是如果在命令之后运行不带字符串的命令,它将返回
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
解决方法
主要有2种方法,而discord.py rewrite不需要pass_context
@client.command()
async def dankrate(ctx,*,message=None):
if not message: #nothing is passed after the command
return await ctx.send("**Please pass in required arguments**")
message_author = ctx.author
message_channel = ctx.channel
print(message)
aaaaa = random.randint(1,101)
print("{} issued .dankrate ?".format(message_author))
if aaaaa == 101:
embedVar = discord.Embed(title="Dank r8 Machine",description=f"you broke the dank machine >:( :fire:\n{message} is {aaaaa}% dank",color=15105570)
else:
embedVar = discord.Embed(title="Dank r8 Machine",description=f"{message} is {aaaaa}% dank",color=3066993)
await message_channel.send(embed=embedVar)
OR
@client.command()
async def dankrate(ctx,message):
message_author = ctx.author
message_channel = ctx.channel
print(message)
aaaaa = random.randint(1,color=3066993)
await message_channel.send(embed=embedVar)
@dankrate.error
async def dankrate_error(ctx,error):
if isinstance(error,commands.MissingRequiredArgument):
return await ctx.send("**Please pass in required arguments**")
else:
raise(error)
,
您可以使用 Discordpy 的装饰器,它允许您在执行命令之前进行检查:
def check_if_it_is_owner(ctx):
return ctx.message.author.id == OWNER_ID
@bot.command()
@commands.check(check_if_it_is_owner)
async def only_the_cool_guy(ctx):
await ctx.send('Super user command execution')
更多信息:https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#checks