TypeError: token must be of type str, not NoneType

Question:

I’m trying to make a Discord bot with python but I get this error when I run it:

TypeError: token must be of type str, not NoneType

If you want to see my code, here is it:

import discord
import os
import random
from dotenv import load_dotenv

load_dotenv()

client = discord.Bot()
token = os.getenv('Token')

@client.event
async def on_ready():
    print("Logged in as a bot {0.user}".format(client))

@client.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    channel = str(message.channel.name)
    user_message = str(message.content)

    print(f'Message {user_message} by {username} on {channel}')

    if message.author == client.user:
        return

    if channel == "random":
        if user_message.lower() == "hello" or user_message.lower() == "hi":
            await message.channel.send(f'Hello {username}')
            return
        elif user_message.lower() == "bye":
            await message.channel.send(f'Bye {username}')
        elif user_message.lower() == "tell me a joke":
            jokes = [" Can someone please shed more
            light on how my lamp got stolen?",
                    "Why is she called llene? She
                    stands on equal legs.",
                    "What do you call a gazelle in a 
                    lions territory? Denzel."]
            await message.channel.send(random.choice(jokes))

client.run(token)

My bot token is fake because I don’t want anyone know it’s token. Please help me solve this problem. Thank you so much!

Asked By: Tom

||

Answers:

Your token value should be got from env var name:

And if the token is None, then don’t do anything else, because your program cannot run without token

token = os.getenv('MY_TOKEN_VAR')
if not token:
    print('ERROR: Token var is missing: MY_TOKEN_VAR')
    sys.exit(-1)
Answered By: Roberto

if your discord bot is hosted locally, without needing to be shared publicly or hosted online, you may simply set token variable directly to the string of your token.

token = 'MTAwNjA1NTQ4NTg3MjUzNzcwMQ.GcPn03.xeIRE4c1W0OF8aNtkA4hj1Nl2V6mowLV1BqWuU'

If you would like to make use of environment variables to keep your bot token secure, (usually when you would like to run your discord bot online), the argument passed into os.getenv() should be the key which you set in the environment variables.

Answered By: piplup
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.