如何检查命令discord.py后是否有消息

2024-09-28 01:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编辑代码,以便它检查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.


Tags: 字符串命令messagetitleischannelembedauthor
2条回答

主要有两种方法,在discord.py重写中不需要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)

@client.command()
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.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的decordor,它允许您在执行命令之前进行检查:

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

相关问题 更多 >

    热门问题