【问题标题】:If...else statements not working as expectedIf...else 语句未按预期工作
【发布时间】:2020-03-11 21:49:02
【问题描述】:

我实际上是在尝试使用 discord.py 创建一个简单的 Discord 机器人。问题来了,当我尝试执行这段代码时:

import discord
from discord.ext import commands

myid = 3586xxxxxxxxxx
cliente = commands.Bot(command_prefix="!!")

@cliente.command()
async def clear(ctx, amount):

    if myid == ctx.author.id:

        print("Entering If statement")  # This is printed
        await ctx.channel.purge(limit=int(amount))  # This is not executed

    else:

        await ctx.channel.send("You don't have enough permissions.")  # This is executed

输出没有意义,当我在服务器上运行“!!clear 2”时,程序进入 If 并打印“Entering the If statement”,它没有删除任何内容,然后机器人发送消息在 else 里面。

我现在很困惑:s

【问题讨论】:

  • 只是因为我以前被抓过。检查您的“代码”是否具有清除权限。可能是 ctx 说不,不是你。
  • 您正在使用 await - 这意味着事情不会按顺序发生。可能是它在打印第二条消息时尚未完成一项任务(对于您看到的第一条消息)。如果您使用 await 不要期望事情会同步发生,那么您特别允许异步行为。
  • 那我该怎么办?尝试删除“await”关键字会导致这种错误:“RuntimeWarning: coroutine 'Messageable.send' was never awaited”。
  • purge 方法在其他情况下工作正常,所以我不认为这是一个 purge 问题@arcee123。
  • 您是否有任何可能干扰的on_message 事件或错误处理?如果您只运行此处的代码,您还会看到这种行为吗?

标签: python-3.x asynchronous discord.py discord.py-rewrite


【解决方案1】:

我仍然不知道为什么它不起作用,但是嘿!,我找到了一个很好的选择,它包括使用用户名。我举个例子:

import discord
from discord.ext import commands

myuname = "User#1234"
cliente = commands.Bot(command_prefix="!!")

@cliente.command()
async def clear(ctx, amount):

    if myuname == str(ctx.author): # For some reason using str() is neccessary or It won't work properly.

        print("Entering If statement")  # This is printed
        await ctx.channel.purge(limit=int(amount))  # This is not executed

    else:

        await ctx.channel.send("You don't have enough permissions")

就是这样,希望它对某人有所帮助:)

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多