Beginning to learn to write a simple Discord bot in Python. My bot's token is in a .env file but I'm getting the error discord.errors.LoginFailure: Improper token has been passed.
Putting the token in client.run(TOKEN_HERE) doesn't work for me as it does with some people.
I'm using the token from the Bot page on the Discord Developer Portal not the Client Secret from the General Information page.
I'm using Visual Studio Code.
bot.py:
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)
.env:
DISCORD_TOKEN=secret_token_here
Full error output:
Eds-MacBook-Pro:~ ed$ python3 /users/ed/documents/supremesauce/supremesauce.py
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/http.py", line 261, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/http.py", line 225, 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 "/users/ed/documents/supremesauce/supremesauce.py", line 15, in <module>
client.run(TOKEN)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 640, in run
return future.result()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 621, in runner
await self.start(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 584, in start
await self.login(*args, bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/client.py", line 442, in login
await self.http.static_login(token.strip(), bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/discord/http.py", line 265, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Eds-MacBook-Pro:~ ed$
Thanks :)
As some of the comments have said, make sure that your token has quotation marks around it. Beyond that, it might be worth trying regenerate a new token, and go from there.
I would once again make sure you are passing in a string.
Related
Traceback (most recent call last):
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\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 "e:\all in one bot\cafe-musain-bot\bot.py", line 79, in <module>
client.run('OTU1NjAyMjY1NzEwOTQ0Mjc2.YjkD9g.n0Qqhng0EA63JOcxwzajjm--wi0')
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\site-packages\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.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022765565550>
Traceback (most recent call last):
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\youssef\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
here is the code:
import asyncio
import discord
from discord.ext import commands
import random
token = 'Token'
intents=discord.Intents.all()
client = commands.Bot(command_prefix='?')
#client.event
async def on_ready():
print("bot is ready")
the rest...
client.run(token)
i tried restting the token multiple times and checked that the token is a string nothing happens same error, tried making a new discord application guessing that the problem is in the one im already using got the same error asked in the discord.py guild no one knew how to fix it.
Without code, it's hard to give an accurate answer, but this sounds like your bot token is incorrect.
The line of the error that suggests your token is incorrect/improper:
raise LoginFailure('Improper token has been passed.') from exc
How to ensure the bot starts correctly:
token = ''
bot.run(token) # client.run(token)
You can find your token here. You need to ensure that the token is correct - otherwise, authentication will not succeed.
Here is the improved code. First make sure to create a config.py file in your main directory containg the following:
TOKEN="Your Token"
And here is the main.py code:
import asyncio
import discord
from discord.ext import commands
import random
from config import TOKEN
client = commands.Bot(command_prefix='?', intents=intents)
#client.event
async def on_ready():
print("bot is ready")
'''
The rest Goes Code Here
'''
client.run(TOKEN)
Hi i keep getting the error message
discord.errors.LoginFailure: Improper token has been passed.
this is my code
import discord
import os
client = discord.Client()
token = os.environ['token']
async def on_ready():
await client.change_presence(game=discord.Game(name=" dm for support ;)"))
client.run("token")
this is the full error message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 247, 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 "main.py", line 11, in <module>
client.run("token")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 718, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 697, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 297, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
and finally this is a screen shot of the token
image of token in replit secrets
any help??
Two things that I think are the cause:
In this part of the code
token = os.environ['token']
You are retrieving an environment variable, called 'token', that you should set before running your program. In case you haven't, that's easy to do:
Windows:
SET token=<value of token>
Linux based OS:
export token=<value of token>
In this way, you make sure this environment variable is set.
Second problem:
In this part of your code
client.run("token")
You are not using this variable that you previously extracted with token = os.environ['token'] , instead you are literally using the string token as your token, which I imagine is not really your token. This could be fixed, like this:
client.run(token)
Note that in this case, I'm using the variable token previously declared, instead of the string "token".
Also, this question could be helpful.
My code is simple because I am new to coding my discord bot, I want it so the bot sends a random meme from a subreddit when the word !meme is sent in discord, here is the code:
import discord
import os
import praw
import random
client = discord.Client()
reddit = praw.Reddit(client_id='the client id',
client_secret='the client secret',
user_agent='Memri TV Bot by /u/Hezbolloli')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
subreddit = reddit.subreddit("memritvmemes")
all_subs = []
top = subreddit.hot(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title=name)
em.set_image(url=url)
await ctx.send(embed=em)
client.run('Token')
My error is here and I am not sure where I should start looking at this because this is by far the longest error I have ever got in my coding career:
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 28, in on_message
for submission in top:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/praw/models/listing/generator.py", line 63, in __next__
self._next_batch()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/praw/models/listing/generator.py", line 73, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/praw/reddit.py", line 566, in get
return self._objectify_request(method="GET", params=params, path=path)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/praw/reddit.py", line 666, in _objectify_request
self.request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/praw/reddit.py", line 848, in request
return self._core.request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/sessions.py", line 324, in request
return self._request_with_retries(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/sessions.py", line 222, in _request_with_retries
response, saved_exception = self._make_request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/sessions.py", line 179, in _make_request
response = self._rate_limiter.call(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/sessions.py", line 277, in _set_header_callback
self._authorizer.refresh()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/auth.py", line 346, in refresh
self._request_token(grant_type="client_credentials")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/auth.py", line 155, in _request_token
response = self._authenticator._post(url, **data)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/prawcore/auth.py", line 38, in _post
raise ResponseException(response)
prawcore.exceptions.ResponseException: received 401 HTTP response
It seems the problem lies in your request to Reddit. As you are working in a asynchronous environment, you need to use the asyncpraw module instead (docs: Asyncpraw for reddit docs). The code is almost the same:
import discord
import os
import asyncpraw # install it using "pip install asyncpraw"
import random
client = discord.Client()
reddit = asyncpraw.Reddit(client_id='the client id',
client_secret='the client secret',
user_agent='Memri TV Bot by /u/Hezbolloli')
Also, you did not define ctx. Try : message.channel.send(...), or setup a bot.
If you are coding a bot, I would also strongly recommend that you use the discord bot commands as a way of adding functions, instead of reading the messages content (you could also use slash commands).
Here is a link to the docs : https://discordpy.readthedocs.io/en/stable/#getting-started
There is quite a lot of info about that online. If you run into trouble I'd be glad to help.
I've been trying to build myself a discord bot based on a tutorial series that I'm watching. When i try to run the code below, I get a Runtime Error. I left the Token that you need to connect to with the bot out in the last line because I obviously don't want any one to be able to connect to him.
Traceback (most recent call last):
File "c:\Users\Frederik\Desktop\Python\main.py", line 11, in <module>
client.run("y9QHVpnw5u8aJWYZHMAatZ-nCSrM17YF")
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 708, in run
return future.result()
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 687, in runner
await self.start(*args, **kwargs)
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 650, in start
await self.login(*args, bot=bot)
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 499, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 295, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000249A4C08E50>
Traceback (most recent call last):
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Frederik\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
PS C:\Users\Frederik\Desktop\Python>
import discord
class MyClient(discord.Client):
async def on_ready(self):
print("Eingeloggt!")
async def on_message(self, message):
print("Nachricht von" + str(message.author) + "enthält" + str(message.content))
client = MyClient()
client.run("")
Make sure that you're copying the bot's token, and not the client secret. Go to the developer portal (discord.com/developers), click on your application, click on the Bot tab, copy the token, and pass it to client.run.
i think it's an error installation:
File "c:\Users\Frederik\Desktop\Python\main.py", line 11, in <module>
client.run("y9QHVpnw5u8aJWYZHMAatZ-nCSrM17YF")
and you let your token ^^
try to reinstall the library discord.py and change the token :D
Using the Discord API requires an auth token to connect to the service (it's like the bot logging into the website). You can customize the privacy of your bot during token generation.
I'd recommend you create a token following these instructions:
https://discordpy.readthedocs.io/en/latest/discord.html#discord-intro
If that still doesn't work, double check your bot against the quickstart in the docs:
https://discordpy.readthedocs.io/en/latest/quickstart.html
I'd also recommend you read through the documentation on the Python wrapper for the Discord API here:
https://discordpy.readthedocs.io/en/latest/
Good luck!!!
I have been running into an unusual issue where I have no idea how to solve. I am attempting to start coding a discord bot and have been following a tutorial, however, when I run the following line of code it gives an error. I have changed the token in before posting this.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('NjgzODg1NjczNjg5OTA3MjE1.XlyOfw.UMm8vjHOgEbaSgfRMUglAimOP7Q')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(token) # The error occurs here
Any help with trying to run this would be greatly appreciated.
Error given:
Traceback (most recent call last):
File "C:/Users/Jeffr/PycharmProjects/HypixelAPI/DiscordStatsBot.py", line 18, in <module>
client.run(token)
File "C:\Users\Jeffr\PycharmProjects\HypixelAPI\venv\lib\site-packages\discord\client.py", line 640, in run
return future.result()
File "C:\Users\Jeffr\PycharmProjects\HypixelAPI\venv\lib\site-packages\discord\client.py", line 621, in runner
await self.start(*args, **kwargs)
File "C:\Users\Jeffr\PycharmProjects\HypixelAPI\venv\lib\site-packages\discord\client.py", line 584, in start
await self.login(*args, bot=bot)
File "C:\Users\Jeffr\PycharmProjects\HypixelAPI\venv\lib\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'
In your situation you have to assign token directly
token = 'NjgzODg1NjczNjg5OTA3MjE1.XlyOfw.UMm8vjHOgEbaSgfRMUglAimOP7Q'
Function os.getenv() is used to get value from system's variable - ie. from 'DISCORD_TOKEN'
token = os.getenv('DISCORD_TOKEN')
This way you don't keep token directly in code and you can safely share code on forums or GitHub.
If code works then you can search information how to set system's variable and then you can use os.getenv().