Python机器人开发报错求助:NameError: name 'commands' is not defined 如何解决?
Hey there! That error is super common when you're starting out with Discord bots in Python—let's break down what's going on and fix it right away.
What's Causing the Error?
The NameError means your code is trying to use the commands object, but Python has no idea what that is because you haven't imported the required module from the discord.py library.
Step-by-Step Fix
First, make sure you have discord.py installed
If you haven't already, open your terminal/command prompt and run this command to install the library:pip install discord.pyAdd the missing import statement
At the very top of yourmain.pyfile, add this line to import thecommandsmodule:from discord.ext import commandsYou'll also need to import the base
discordmodule to set up intents, so your full imports should look like this:import discord from discord.ext import commandsDouble-check your intents setup
Discord requires explicit intents for bots to access certain features now. Make sure your intents are properly initialized before creating the bot instance. Here's a complete minimal working example:import discord from discord.ext import commands # Initialize intents (required for modern Discord bots) intents = discord.Intents.default() intents.message_content = True # Enable this if your bot needs to read message content # Now create your bot instance correctly bot = commands.Bot(command_prefix=".", intents=intents) # Test with a simple command to verify it works @bot.command() async def ping(ctx): await ctx.send(f"Pong! {round(bot.latency * 1000)}ms") # Replace this with your actual bot token (keep this secret!) bot.run("YOUR_BOT_TOKEN_HERE")
Quick Tips
- Never share your bot token with anyone—it gives full control over your bot.
- If your YouTube tutorial is a bit outdated, it might skip the intents setup, which is mandatory for discord.py v2.x and newer versions.
内容的提问来源于stack exchange,提问作者Nguyễn Kiến

