You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py机器人kill命令执行时报int与str减法不支持类型错误

问题根因

  • 第一个问题是缩进错误:kill函数内await ctx.send那一行的缩进层级高于前面的代码,Python对缩进高度敏感,异常缩进会导致代码块归属逻辑错误,甚至可能让前面的int(amount)类型转换没有被正常执行,最终g还是字符串类型,触发int和str无法做减法运算的类型报错。
  • 第二个问题是参数缺少类型校验与自动转换:你当前的命令参数写法没有指定类型,即使用户输入非数字内容也会被当作字符串传入,强制转换时很容易触发异常。

修复方案

你可以直接使用discord.py自带的参数类型标注功能,同时修正缩进即可,修复后的代码如下:

client.message_counter = 0

@client.event
async def on_ready():
    print ("Bot online!")
    

@client.command()
# 直接给amount标注int类型,discord.py会自动完成类型转换+输入校验
async def add(ctx, amount: int):
    client.message_counter += amount
    await ctx.send(f"{client.message_counter} pigs are spotted, how many are dying?")

@client.command()
async def kill(ctx, amount: int):
    # 不需要重复转换int,client.message_counter本身就是数字类型
    end = client.message_counter - amount
    # 修正缩进,同时修正原代码的拼写错误 where → were
    await ctx.send(f"{amount} pigs were killed \n {end} are left")

如果确实需要保留原有的*, amount写法(适配参数带空格的特殊场景),也可以只修正缩进和类型转换逻辑:

@client.command()
async def kill(ctx,*,amount):
  j = client.message_counter
  g = int(amount)
  end = j - g
  # 仅修正缩进即可
  await ctx.send(f"{g} pigs were killed \n {end} are left")

内容的提问来源于stack exchange,提问作者Derek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:06:02