繁体   English   中英

discord python(带有int检查的bot.command)

[英]discord python (bot.command with int check)

import discord

from discord.ext import commands
from discord.utils import get
from discord.ext.commands import bot

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix='!', intents=intents)


@bot.event
async def on_ready():
    print("The 'Superbot' is now online.")

@bot.command()
async def clear(ctx, amount):
    amount = int(amount)
    if amount == int:
        await ctx.channel.purge(limit=amount)
    elif amount != int:
        return await ctx.send("!Clear [Integer]")
bot.run('removed')`

EnyoS: !clear dfk Superbot: The Command 引发了一个异常:ValueError: invalid literal for int() with base 10: 'dfk'

EnyoS: !clear 10 超级机器人: !Clear [整数]

我想让它返回!Clear [Integer]并且当我写一个数字时它就可以工作,谢谢!

尝试并排除 ValueError。 其格式为: Try: amount = int(amount) Except ValueError: await ctx.send("!Clear [Integer]")这也消除了对 if 语句的需要。 缩进不太好,但这会有所帮助: https : //www.w3schools.com/python/python_try_except.asp

您将要检查传递的参数是否可以转换为int

@bot.command()
async def clear(ctx, amount):
    try:
        amount = int(amount)
        return await ctx.channel.purge(limit=amount)
    except ValueError:
        return await ctx.send("!Clear [Integer]")

但这不是我想要的,我试图将(金额)作为整数,所以即使你写了一个数字你也不能因为它仍然算作一个刺痛

我不是 100% 确定你的意思是什么,但我认为我的回答满足了你的需要。 这样,当您传入一个数字(确实是string ,它会尝试将其转换为int以查看它是否是实际数字(而不是一些随机文本)。 你要去关error message ,发送该命令的用法,这就是你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM