Discord Bot - "Attribute Error: 'NoneType' object has no attribute 'strip.'

11,014

Solution 1

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.

Solution 2

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 !!!

Solution 3

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.

Solution 4

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

Solution 5

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 "{}"

Share:
11,014

Related videos on Youtube

Jake
Author by

Jake

Updated on June 04, 2022

Comments

  • Jake
    Jake almost 2 years

    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' 
    
    
    • sanitizedUser
      sanitizedUser almost 4 years
      Try it without the spaces. In the tutorial there are no spaces between DISCORD_TOKEN and its value.
  • Jake
    Jake almost 4 years
    You're totally right about the name - fixed that. And I did make adjustments to the .env file to have no spaces, but it still came up with the same error. I tried a couple of different ways of writing it, to no success
  • jacob
    jacob almost 4 years
    What about making it a string? (i.e. DISCORD_TOKEN="my-token-here")
  • Jake
    Jake almost 4 years
    Tried that just now, unfortunately same result (thank you for the suggestions btw, i really do appreciate the help!)
  • jacob
    jacob almost 4 years
    Can you see what the output of load_dotenv(verbose=True) is?
  • Jake
    Jake almost 4 years
    Just tried it now, and same result - it didn't change the output of the error type
  • jacob
    jacob almost 4 years
    You probably have to wrap it in a print statement to get output (e.g. print(load_dotenv(verbose=True)) or something like load_output = load_dotenv(verbose=True) then print(load_output).
  • Jake
    Jake almost 4 years
    Just tried that and now I'm still getting that same error, but at the top of the error it now says "File doesn't exist." What does the command verbose=True do within the code? Apologies if that's a super simple question, I'm still very new to everything!
  • jacob
    jacob almost 4 years
    Yeah, sounds like the load_env() function call goes looking for your .env file but can't find it. where is your .env file relative to your bot.py file? The dotenv library is on git hub here: github.com/theskumar/python-dotenv/tree/…
  • Jake
    Jake almost 4 years
    I created it under the same directory as my bot.py file by just adding it via the new file action in Visual Studio Code. I'll check out that library to see if I can figure anything from there
  • jacob
    jacob almost 4 years
    Change your import statement to from dotenv import load_dotenv, find_dotenv then call print(find_dotenv('.env', True, False)) and print(find_dotenv('.env', True, True)) to see if dotenv is finding your environment file, where your environment file is called '.env', the 2nd True is to raise an error if not found, and the 3rd bool is whether or not to start looking in the current directory. This is all covered in the python-dotenv/src/dotenv/main.py file at the git hub repo I linked to earlier.
  • Admin
    Admin over 3 years
    I know this problem because I have met this problem before, and it's the EXACT same... if that doesn't work, then it's probably something with the IDE or something.
  • Admin
    Admin over 3 years
    there aren't supposed to be anything, just the token itself and the 'variable'.
  • MRT
    MRT about 3 years
    Thanks for this. I'm following the same tutorial and this solved the error. 10/10
  • Andrei
    Andrei almost 3 years
    Thanks :) While the original already had those 2 lines, I didn't and this helped!
  • b.geisb
    b.geisb over 2 years
    Although this is a solution, it is strongly recommended to avoid using tokens, passwords or other sensitive data directly in the productive code.