My Discord bot keeps crashing with this error:
TypeError: expected token to be a str, received NoneType instead
Here’s my bot code:
import discord
import os
permissions = discord.Intents.default()
permissions.typing = False
permissions.presences = False
bot = discord.Client(intents=permissions)
@bot.event
async def on_ready():
print(f'Bot is online as {bot.user}')
@bot.event
async def on_message(msg):
if msg.author == bot.user:
return
if msg.content.startswith('!greet'):
await msg.channel.send('Hi there!')
bot.run(os.getenv('BOT_TOKEN'))
I think the problem is with the token but I’m not sure how to fix it. The error happens when I try to start the bot. I’ve checked other similar questions but none of the solutions worked for me. What am I doing wrong here?
add a print statement before the run line to check if your BOT_TOKEN exists: print(os.getenv('BOT_TOKEN')). if it prints None, that’s def your problem. also double-check there arent any spaces or typos in your environment variable name.
Your BOT_TOKEN environment variable isn’t set correctly. When os.getenv('BOT_TOKEN') can’t find the variable, it returns None and causes that TypeError. First, make sure you’ve created a bot on Discord Developer Portal and copied the token. Then set the environment variable: use set BOT_TOKEN=your_actual_token_here on Windows or export BOT_TOKEN=your_actual_token_here on Linux/Mac. You can also create a .env file with BOT_TOKEN=your_token and use python-dotenv to load it. Just don’t commit your token to version control.
Your environment variable isn’t being read properly. I had this exact problem when I started with Discord bots. Skip the system environment variables - they’re a pain to set up right. Just create a config.py file in your project folder with TOKEN = 'your_bot_token_here' then import it with from config import TOKEN and use bot.run(TOKEN). Way more reliable for development and you can easily swap between different bot tokens. Don’t forget to add config.py to your .gitignore so you don’t accidentally push your token to GitHub.