【问题标题】:I want my bot to tell you that you must mention someone, when you dont我希望我的机器人告诉你你必须提到某人,当你不
【发布时间】:2020-11-26 14:45:55
【问题描述】:

我有很多有趣的命令,比如“拥抱、结婚等”。

他们正在合作

.拥抱用户

但如果您不提及用户,我希望我的 python 机器人告诉“您需要提及某人”。然而,每当我测试机器人时,什么都没有发生,用户也不知道他们需要提及用户

我的代码:

async def hug(ctx,user:discord.Member):
    if not discord.Member:
        await ctx.send("you need to mention someone")
        return

    embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
    embed.set_image(url="url")

    await ctx.send(embed=embed)``
   

【问题讨论】:

  • 实际问题是什么?执行代码时会发生什么?看起来它会起作用。添加所有相关信息有助于提供有用的答案
  • 什么都没有发生

标签: python discord.py


【解决方案1】:

解决方法很简单,消息对象有一个mentions属性,你可以检查消息提及的长度,如果不等于1则应该有错误。

async def hug(ctx, user:discord.Member):
    if len(ctx.message.mentions) != 1:
        await ctx.send("you must mention a user!")
        return

    embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
    embed.set_image(url="url")

    await ctx.send(embed=embed)``

关于 message.mentions attribute 的 Discord API 文档:https://discordpy.readthedocs.io/en/latest/api.html?highlight=message%20mentions#discord.Message.mentions

【讨论】:

    【解决方案2】:

    你检查的方式不对,你定义了一个名为user的属性,并给它一个类型discord.Member,所以你需要检查user是否通过。

    async def hug(ctx, user:discord.Member):
        if not user:
            await ctx.send("you must mention a user!")
            return
    
        embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
        embed.set_image(url="url")
    
        await ctx.send(embed=embed)
    

    问题是,如果您正在检查 len(ctx.message.mentions) != 1,当您使用: .hug xyz @billy 它也会通过 if 条件,但不会工作,而是会抛出错误。因为 BadArgument - xyz 第二次传递。

    【讨论】:

      最近更新 更多