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

Python运行Discord Bot提示'bot未定义'(NameError)问题求助

解决Discord Bot中NameError: name 'bot' is not defined错误

报错原因是你直接使用了bot对象,但代码里没有先创建这个对象的实例。Discord.py要求必须先实例化commands.Bot才能使用其装饰器和方法。

修正后的完整代码

import discord
from discord.ext import commands
import requests
import os 

TOKEN = os.getenv("TOKEN")

# 实例化Bot对象,设置命令前缀和必要的Intents
bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())
# 启用消息内容意图,否则无法监听消息内容
bot.intents.message_content = True

@bot.event
async def on_message(message):
    # 避免Bot响应自己的消息
    if message.author == bot.user:
        return
    if message.content == "hello":
        await message.channel.send("world")

bot.run(TOKEN)

关键修改说明

  • 添加bot = commands.Bot(...)行:创建Bot实例,指定命令前缀(可自定义),并初始化默认Intents。
  • 开启message_content意图:新版本Discord.py默认关闭消息内容权限,必须手动开启才能让on_message监听到消息内容。
  • 新增message.author == bot.user判断:防止Bot对自己发送的消息做出响应,避免循环。

额外注意:需要在Discord开发者平台的Bot设置中,找到"Privileged Gateway Intents",开启"Message Content Intent",否则代码运行后依然无法正常监听消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:20:30