【问题标题】:Python equality operator not working with discord.py IDsPython 相等运算符不适用于 discord.py ID
【发布时间】:2021-02-26 03:17:27
【问题描述】:

我为 Discord 机器人设置了一个非常简单的命令。这应该是为了响应!positions 命令,检查作者和频道,如果作者是我,频道是我与机器人的 DM 频道,做一些事情(比如发送回复消息)。

我的帐户 ID 是 285538805728149504。当命令!positions 运行时,它会输出:

Author ID 285538805728149504
DM channel 814250853669666887
Current channel 814250853669666887

您可以看到它打印出的作者 ID 完全与我要与之比较的硬编码用户 ID 相同。您还可以看到比较的两个频道 ID 完全相同相同。

但是,它不会通过任何 if 语句。

代码如下:

@commands.command()
async def positions(self, ctx):

    positions_file = Path("positions.json")
    positions = json.loads(positions_file.read_text())

    message_author = ctx.message.author.id

    print("id " + str(message_author))
    print("dm channel " + str(ctx.message.author.dm_channel.id))
    print("Current channel " + str(ctx.message.channel.id))

    my_id = "285538805728149504"
    if message_author == my_id:
        print("Author ID is my ID")
        if ctx.message.author.dm_channel.id == ctx.message.channel.id:
            print("Channel ID is my DM channel")
            await ctx.message.author.dm_channel.send("reply")

为什么我不能成功比较这些数字?

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您似乎正在比较这一行中的 str 对象和 int 对象:

    if message_author == my_id:
    

    请注意,id 默认情况下是一个整数(关于该here 的文档)。

    要么将my_id 更改为整数,要么在前面提到的行中使用str(message_author)

    【讨论】:

    • 你是对的,看起来问题与类型有关!我删除了引号使其成为整数,但直到我使用内置的 int() 函数将硬编码的 ID 和变量 ID 都强制为 ints 之前它仍然不起作用。
    【解决方案2】:

    is 更改为== 并尝试一下。 还可以尝试将ctx.message.author.id 放入 var

    【讨论】:

    • 哦不,对不起,我实际上是在测试is 是否会比== 工作得更好,但在问这个问题之前我忘了把它切换回来。当我使用== 时,我仍然遇到同样的问题。我尝试将 ID 存储在一个变量中(问题已使用我当前的代码进行了更新),但这也无济于事。
    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 2022-01-11
    • 2012-06-19
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    相关资源
    最近更新 更多