Issue with Discord bot authentication in Python

I’m developing a connect four game bot for Discord using Python, but I’m facing issues with authentication. Interestingly, the exact code runs smoothly on another computer, but fails on this one, even though I have the same libraries installed.

Here’s the code snippet:

# Required imports
import discord
import random
from discord.ext import commands

perms = discord.Intents.all()
perms.members = True
bot = commands.Bot(command_prefix='!', intents=perms)

# Variables for the game
player1 = ""
player2 = ""
current_turn = ""
game_completed = True
game_grid = []

winning_combinations = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
]

@bot.event
async def on_ready():
    total_servers = 0
    for server in bot.guilds:
        print(f'Server ID: {server.id} Name: {server.name}')
        total_servers += 1
    print(f'Bot is active in {total_servers} servers')

@bot.event
async def on_message(msg):
    if '!connectfour' in msg.content:
        global player1, player2, current_turn, game_completed, game_grid
        await msg.channel.send('Who would you like to play against?')
        
        try:
            response = await bot.wait_for('message', 
                check=lambda m: m.author == msg.author and m.channel == msg.channel, 
                timeout=20)
        except asyncio.TimeoutError:
            await msg.channel.send('You ran out of time')
        else:
            if game_completed:
                game_grid = [":blue_square:" for _ in range(9)]
                current_turn = ""
                game_completed = False
                
                player1 = msg.author
                player2 = response.mentions[0]
                
                # Displaying the game board
                board_state = ""
                for i in range(len(game_grid)):
                    if i in [2, 5, 8]:
                        board_state += game_grid[i]
                        await msg.channel.send(board_state)
                        board_state = ""
                    else:
                        board_state += game_grid[i]
                
                # Randomly selecting the starting player
                starter = random.randint(1, 2)
                if starter == 1:
                    current_turn = player1
                    await msg.channel.send(f"<@{player1.id}> goes first")
                else:
                    current_turn = player2
                    await msg.channel.send(f"<@{player2.id}> goes first")
            else:
                await msg.channel.send('A game is currently in progress')

bot.run('YOUR_BOT_TOKEN_HERE')

I’m encountering the following error:

Traceback (most recent call last):
  File "discord/http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "discord/http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "mybot.py", line 96, in <module>
    bot.run('TOKEN_STRING_HERE')
  File "discord/client.py", line 723, in run
    return future.result()
  File "discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "discord/http.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.

Why does it work on one computer but not on the other? What could be causing this authentication issue?

Had this exact problem migrating my bot between dev environments. It’s usually config issues, not code problems. Check if your working machine loads the token from a .env file or environment variables - this one might not have that setup. Different Python versions can also mess with string encoding. I wasted hours debugging once only to find Python 3.9 vs 3.11 was causing weird character encoding issues with my token. Print your token string length and compare it between machines - should be identical character count. Also make sure your system locale settings match on both computers.

Your token’s probably corrupted or formatted wrong on this machine. I’ve seen this before when copying tokens between systems - invisible characters sometimes sneak in during copy/paste. Just regenerate a fresh token in Discord’s developer portal instead of reusing the old one. Also double-check there’s no extra characters or whitespace around the token string. Could also be that your working computer runs a different discord.py version that handles token validation differently. Run pip freeze on both machines to make sure you’ve got identical library versions.

you’re using a hardcoded placeholder instead of your real bot token. did you replace ‘YOUR_BOT_TOKEN_HERE’ with the actual token from discord’s developer portal? the working computer probably has it stored in environment variables.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.