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

Python Discord Bot运行报错NameError: name 'client' is not defined求助

问题原因

NameError: name 'client' is not defined 报错的核心原因是你在使用@client.event、@client.command这些装饰器之前,没有先实例化client对象。

解决步骤
  1. 在导入模块的代码之后,所有带@client装饰器的代码之前,添加client实例化逻辑。当前discord.py v2.x版本要求显式声明Intents权限,需要同步配置:
import discord
import os
import random
from discord.ext import commands

# 新增以下3行代码
intents = discord.Intents.default()
intents.message_content = True # 读取消息内容响应命令必须开启
client = commands.Bot(command_prefix=';', intents=intents) # 前缀和你配置的;help对应
  1. 修正代码里的其他语法问题:
  • unload命令现在缩进在load函数内部,需要取消缩进和其他命令平级
  • print('bot is ready.')现在是全局代码,需要缩进放到on_ready函数内部,否则程序启动就会打印,不是bot上线触发
修正后完整代码
import discord
import os
import random
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix=';', intents=intents)

@client.event
async def on_ready():
  await client.change_presence(status=discord.Status.online, activity=discord.Game(';help'))
  print('bot is ready.')

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

@client.command(aliases=['8ball', 'test'])
async def eightball(ctx, *, question):
    responses = ['Maybe Yes', 'Maybe No', 'Probably No', 'Probably Yes', 'Never', 'Always', 'Yes', 'No', 'Try again later']
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')

@client.command()
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)

@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
    await member.kick(reason=reason)

@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
    await member.ban(reason=reason)

@client.command()
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run('你的Bot Token')
额外注意

你需要在Discord开发者后台的Bot设置页,打开Message Content Intent开关,否则bot无法读取消息内容响应普通前缀命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:45:02