首页 > 解决方案 > If...else 语句未按预期工作

问题描述

我实际上是在尝试使用 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

标签: python-3.xasynchronousdiscord.pydiscord.py-rewrite

解决方案


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

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")

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


推荐阅读