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

Discord机器人修改代码后指令不生效是什么原因?

现有代码问题修复

你的修改后代码无法触发指令的原因和感叹号无关:str.lower是字符串的内置方法,必须添加括号()调用才会返回小写转换后的结果,你未加括号时是将方法对象本身和字符串做比较,结果永远为False,自然不会触发指令。
满足你要求(不区分大小写、仅匹配完全无多余内容的!hello指令)的修复后代码如下:

import discord
import os

client = discord.Client(intents=discord.Intents.all())

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # 调用lower()方法转小写后做全等匹配
    if message.content.lower() == "!hello":
        await message.channel.send("Hello!")

更适合后续新增大量指令的重构方案

你可以直接使用discord.py自带的commands.Bot框架,不需要手动在on_message里堆叠if判断,新增指令仅需添加对应装饰器即可,维护成本更低:

import discord
from discord.ext import commands
import os

# 设置指令前缀为!,全局不区分大小写
bot = commands.Bot(
    command_prefix='!',
    case_insensitive=True,
    intents=discord.Intents.all()
)

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))

# 定义!hello指令,ignore_extra=True表示带多余后缀内容时不触发
@bot.command(ignore_extra=True)
async def hello(ctx):
    await ctx.send("Hello!")

# 后续新增指令直接加对应装饰器即可,示例:新增!hi指令
@bot.command(ignore_extra=True)
async def hi(ctx):
    await ctx.send("Hi there!")

# 启动机器人,token建议从环境变量读取
bot.run(os.getenv("DISCORD_BOT_TOKEN"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:15:04