Trouble connecting bot to Discord - python

I've recently decided that I wanted to start learning more about real-world Python and the applications associated therewith. As a way to do this, I tried to code a simple Discord bot. However, I'm running into a different problem than any other that I've seen on any platform — including this one: can't find '__main__' module in 'bot'. I get this error when I run python bot in the Command Prompt. Now, I assume that I should indeed be running python bot instead of python bot.py since .py only denotes that bot is a Python file. I assumed this because when I run python bot.py, I get the following message: python: can't open file 'bot.py': [Errno 2] No such file or directory. Here's 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(client.user(), "has connected to Discord!")
client.run(TOKEN)
Additionally, when I run bot.py in the Python shell, I receive the following message:
Traceback (most recent call last):
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\bot.py", line 17, in <module>
client.run(TOKEN)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 640, in run
return future.result()
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 621, in runner
await self.start(*args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 584, in start
await self.login(*args, bot=bot)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\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'
And, I'm not sure where (or even if) this was addressed in the code, but here's .env.txt:
#.env
DISCORD_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Ok, I think that covers everything. If anyone needs clarification for any section(s) of this, I would be happy to provide it. Thanks in advance.

You should pass the path of your .env file inside load_dotenv. Because at the moment your TOKEN is returning None
import os
import discord
from dotenv import load_dotenv
load_dotenv("myenvfile.env") # <-- you can enter your .env file like so
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
#client.event
async def on_ready():
print(client.user(), "has connected to Discord!")
client.run(TOKEN)
.env
DISCORD_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

Related

Discord bot- type error expected token to be str, received class none instead

I'm trying to write a bot in discord. At first I had this error: type error expected token to be str, received class none instead.
But after adding these lines-
from dotenv import load_dotenv
load_dotenv('token.env')
where token.env is the name of the file containing my token information for the bot. Now it works correctly.
Anyone who wants to try and do so too can try and use this template.
Here is my code:
import discord
import os
from dotenv import load_dotenv
load_dotenv('token.env')
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents, help_command=None)
client = discord.Client(intents=discord.Intents.default())
#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'):
await message.channel.send('Hello!')
print(os.getenv('TOKEN') is None)
client.run(os.getenv('TOKEN'))
here is what I get when I try to run it:
True
2022-08-18 08:59:59 INFO discord.client logging in using static token
Traceback (most recent call last):
File "main.py", line 26, in <module>
client.run(os.getenv('TOKEN'))
File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
await self.login(token)
File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__!r} instead')
TypeError: expected token to be a str, received <class 'NoneType'> instead
I am not well versed with Discord bots, but usually, the practice is for the environment file to be just named .env.
Anyway, the issue is that os.getenv('TOKEN') is getting nothing, because environment variable TOKEN does not exist.
Just make sure you named or put the environment variable correctly.
You can also set the default to something else via a second parameter in the getenv() function: https://www.educative.io/answers/what-is-osgetenv-method-in-python

I keep getting the error: AttributeError: 'NoneType' object has no attribute 'strip'

I am using python here.
when I run my code for a discord bot I am making with replit, I get this error: AttributeError: 'NoneType' object has no attribute 'strip'
I am making a discord bot with this tutorial: https://www.freecodecamp.org/news/create-a-discord-bot-with-python/
code:
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {Funni bot B)}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$IHaveNoBobux'):
await message.channel.send('haha sucks to be you B)')
if message.content.startswith('$GiveMeFreeBobuxNow'):
await message.channel.send('no stupid noob B)')
client.run(os.getenv('TOKEN'))
can someone help me fix this error? I have a small brain and no close to no python so some things might need a lot of explaning. :/
this is the full console when I run the code:
Traceback (most recent call last):
File "main.py", line 21, in
client.run(os.getenv('TOKEN'))
File "/home/runner/go-away-this-isnt-for-you/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/go-away-this-isnt-for-you/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/go-away-this-isnt-for-you/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/runner/go-away-this-isnt-for-you/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
I also have an env called "env" which has the following inside it:
TOKEN=[the discord bots token is would be right here but im not going to show it because its the password]
Please follow the steps mentioned to get token, it is empty.
When you created your bot user on Discord, you copied a token. Now we are going to create a .env file to store the token. If you are running your code locally, you don't need the .env file. Just replace os.getenv('TOKEN') with the token.
The file is supposed to be called .env not just env.
Assuming that's what it is already named and it still doesn't work for you, you can instead use a json file if you need to upload it to remote repository (don't forget to add the json file in .gitignore).
import json
import discord
client = discord.Client()
env_json = json.loads("env.json")
key = env_json['TOKEN']
#client.event
async def on_ready():
print(f'We have logged in as {client.username}')
client.run(key)

I get an error (RuntimeError: Event loop is closed) when i run my discord bot

I tried integrating my code on a different webhost because my friend said it was faster. But when I did, I get an error that says RuntimeError: Event loop is closed. It was working perfectly fine before moving.
At first I thought it was because the .env file I made was wrong but I tried running the bot without loading the .env file bot.run("token") and still got the same error.
here's the traceback:
Traceback (most recent call last):File "/home/discord_bot/main.py", line 1085, in <module>`
bot.run(bot_token)
File "/home/discord_bot/.local/lib/python3.9/site-packages/discord/client.py", line 695, in run
loop.add_signal_handler(signal.SIGINT, lambda: loop.stop())
File "/usr/local/lib/python3.9/asyncio/unix_events.py", line 89, in add_signal_handler
self._check_closed()
File "/usr/local/lib/python3.9/asyncio/base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
here's what in the .env file:
TOKEN = my_token
The code:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
bot_token = os.getenv('TOKEN')
bot = commands.Bot(command_prefix = commands.when_mentioned_or("."))
...some server commands
#bot.event
async def on_ready():
print('Bot is ready')
print('------------')
bot.run(bot_token)
Try add this up to you token
bot.close()

how to fix AttributeError: 'NoneType' object has no attribute 'strip' in this specific code?

I'm new to coding and I've been trying to make a simple discord bot, as an experiment, and I keep getting this when I try to run it on PythonAnywhere. I don't have this problem on repl.it though.
Traceback (most recent call last):
File "/home/DELICTREAJay/somthingother/somoo.py", line 10, in <module>
client.run(os.getenv('TOKEN'))
File "/home/DELICTREAJay/.local/lib/python3.8/site-packages/discord/client.py", line 718, in run
return future.result()
File "/home/DELICTREAJay/.local/lib/python3.8/site-packages/discord/client.py", line 697, in runner
await self.start(*args, **kwargs)
File "/home/DELICTREAJay/.local/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.login(*args, bot=bot)
File "/home/DELICTREAJay/.local/lib/python3.8/site-packages/discord/client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
Here is my code
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(os.getenv('TOKEN'))
I have a separate .env file in the same directory where the token is kept
You don't have specified variable named TOKEN in your environment variable. Just try to add a environment variable.
You are missing the load_dotenv():
import discord
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = "what you set in the .env file"
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(TOKEN)
hope this can help!

Error when attempting to run a discord bot

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().

Categories