Reputation: 81
I'm a new coder, and I've been following atutorial on how to create a discord bot with the code below having been virtually copied the code straight out from the tutorial, and I've create a .env file to store my AuthToken. Every time I run the code, I get error below aforementioned code. Any tips? Thanks in advance!
Code:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
Error:
Traceback (most recent call last): File "/Users/XXXXXXXXXXXX/scratch/discordbot/app.py", line 16, in <module>
client.run(TOKEN) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 640, in run
return future.result() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 621, in runner
await self.start(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 584, in start
await self.login(*args, bot=bot) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 442, in login
await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'
Upvotes: 8
Views: 15386
Reputation: 96
It seems that the read token is a 'NoneType' object.
So if you use client.run(str(TOKEN))
instead of client.run(TOKEN)
the method should be able to handle the token correctly and your bot should work.
Upvotes: 0
Reputation: 1
I got the same problem and I know how to solve it. So basically for some reason vscode won't accept os.getenv(TOKEN). So what I did was to put the token directly into the client.run("Your TOKEN here") function.
Upvotes: 0
Reputation: 736
you have to remove the spaces from the .env file. So if you file looks like this
DISCORD_TOKEN = 1234ABC
It wont accept it. It needs to look like this
DISCORD_TOKEN=1234ABC
Upvotes: 0
Reputation: 15
I was getting the same problem where load_dotenv()
wouldn't find the .env file located in the same exact folder as my .py file which resulted in the error Attribute Error:'NoneType' object has no attribute 'strip'.
I tried a bunch of different fixes, from load_dotenv(find_dotenv())
to os.envrion['TOKEN']
instead of os.getenv("TOKEN")
as well as all the other fixes other people gave us in this stack overflow thread. You may have tried those already with no luck like I had.
To get around this, I used:
load_dotenv(dotenv_path = os.path.abspath(os.getcwd()) + "\DiscordBot\discordbot.env")
This specifies the exact file that load_dotenv() will load (I think). Take note of os.path.abspath(os.getcwd())
. This returns the current working directory (getcwd()) of where your project file is located. In my case, it would return this string:
F:\dev\Python\YaykobDiscordBot
.
My actual .py file was located deeper, in another folder: "F:\dev\Python\YaykobDiscordBot\DiscordBot\YaykobBot.py"
, and in the same file right next to it was
"F:\dev\Python\YaykobDiscordBot\DiscordBot\discordbot.env"
which is where I store my token.
You may notice that really, you just need to give load_dotenv()
the file path of wherever the .env file is located. In my case, I can write:
load_dotenv(dotenv_path = "F:\dev\Python\YaykobDiscordBot\DiscordBot\discordbot.env")
and it would work perfectly. I use os.path.abspath
because it works whenever I want to clone my repository from Github.
Upvotes: 0
Reputation: 11
Been looking around a few forums then came across this - life savers thank you!
Sorted now with;
load_dotenv('Token.env')
TOKEN = os.getenv('DISCORD_TOKEN')
Token.env;
DISCORD_TOKEN=Token here
Upvotes: 1
Reputation: 81
I was following the same tutorial and ran into the same error. Issue for me was that I had created the ".env" file incorrectly. In the tutorial it says "Create a file named .env in the same directory as bot.py:" - this was my issue. If you create a new text document, paste in the code, then save it with the name ".env", what you'll actaully be creating is a text file called ".env.txt".
To get around this, go to the directory where you have the python script saved (for me this is C:\Thonny\DiscordBots), then right-click in that folder and select "New > Text Document". Don't change the filename yet, just leave it as "New Text Document". Open this file (should open in Notepad), then paste in the code from the tutorial (also, remember to substitute your bot's actual token in for the placeholder variable called {your-bot-token}). Now, go to "File > Save As" and in the File Name field, type ".env" just like the tutorial says to; BEFORE you hit save, also click the Save as type dropdown (should be right below File Name) and instead of leaving it as the default type (*.txt), change this to "All Files".
If you've done this correctly, you should see your ".env" file in file explorer, and the "Type" column will now show "ENV File" instead of "text document". Try to run the code again.
This is what helped me. My understanding is that "load_dotenv()" is looking for a file of the ENV type, not just any document called ".env" (of any type). As long as this file is placed in the same directory as the script you're running, it should work.
Upvotes: 8
Reputation: 31
This error arises due to the failure of fetching TOKEN value in. env file which can be resolved by-
from dotenv import load_dotenv
load_dotenv('---.env')
It worked for me !!!
Upvotes: 3
Reputation: 11
In your .env file, is it like "BOT_TOKEN={WHAT_EVER_TOKEN}" or something else? If it is that, then it'll be wrong The correct way is "BOT_TOKEN=WHAT_EVER_TOKEN", just without the "{}"
Upvotes: 1
Reputation: 1097
The error is due to TOKEN
being set to None
, which is what os.getenv('DISCORD_TOKEN')
returns if the variable doesn't exist or it exists and is set to None
.
Make sure your .env file is in the same directory, for example:
.
├── .env
└── bot.py
The token is an environment variable, not a python variable. Assignment of environment variables follow the syntax of the shell you are using. This means no spaces around the =
sign.
Note the order of operations when using dotenv
to export variables to your shell (see readme here):
Python-dotenv can interpolate variables using POSIX variable expansion.
The value of a variable is the first of the values defined in the following list:
- Value of that variable in the environment.
- Value of that variable in the .env file.
- Default value, if provided.
- Empty string.
Ensure that variables are surrounded with {} like ${HOME} as bare variables such as $HOME are not expanded.
And the example given is:
CONFIG_PATH=${HOME}/.config/foo
DOMAIN=example.org
EMAIL=admin@${DOMAIN}
DEBUG=${DEBUG:-false
For this reason, you may need to clear your relevant shell variables before proceeding, as the first thing dotenv
will try is to use the already defined variable, which was probably set to an empty string on your initial setup (e.g. unset DISCORD_TOKEN
, or restarting your shell with something like source ~/.bashrc
or similar).
For debugging purposes, I would recommend print(os.getenv('DISCORD_TOKEN'))
to see exactly what this variable is set to. You might also try seeing the output of load_dotenv(verbose=True)
during the environment setup.
Upvotes: 1