Error when attempting to run a discord bot - python

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

Related

How to make a python script send me a dm via discord if x happens within the code?

I run a small python bot that requires data from Github. To not get blocked by Github I download the data and automatically update it every week. I would like to get notified via a discord dm in case the bot couldn't connect to Github and update it's data.
I already have a check for if the bot couldn't update it's data and now all I need is that the bot sends me a dm. Because of schedule I run the automatic updater in a thread.
The problem I face is that this results in: AttributeError: 'NoneType' object has no attribute 'request' in the guild = await bot.fetch_guild(GUILD_ID) line and I don't see why it doesn't work. I already created a little test bot to test if the notify_on_no_respond function works and if triggered by a command from discord it works perfectly.
Full Error:
Exception in thread Thread-1 (start_updater):
Traceback (most recent call last):
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "\\StationDS216\home\Projects\Python\Discord Bots\test lab\Bot_auto_updater.py", line 7, in start_updater
Thread_Auto_Updater = auto_updater(
File "\\StationDS216\home\Projects\Python\Discord Bots\test lab\Bot_auto_updater.py", line 22, in __init__
self.data['Bot'].problem_occured()
File "\\StationDS216\home\Projects\Python\Discord Bots\test lab\Bot_main.py", line 70, in problem_occured
asyncio.run(notify_on_no_respond())
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "\\StationDS216\home\Projects\Python\Discord Bots\test lab\Bot_main.py", line 74, in notify_on_no_respond
guild = await bot.fetch_guild(GUILD_ID)
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1188, in fetch_guild
data = await self.http.get_guild(guild_id)
File "C:\Users\[User]\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
AttributeError: 'NoneType' object has no attribute 'request'
If anyone knows how to fix this problem I would love to hear it. Thanks in advance.
If you need anything from me to help you help me ask and I will try to provide it.
This replicates the code I use but for some reason creates a different error: (you will have to provide your own token etc. in an .env)
# Bot_Game_main.py
import Bot_Game_auto_updater
import os
import discord
import threading
import asyncio
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
MY_ID = os.getenv('DISCORD_MY_ID')
GUILD_ID = os.getenv('DISCORD_GUILD_ID')
bot = commands.Bot(command_prefix='/')
class maintainer(object):
def __init__(self):
pass
def start_thread(self, Bot_Game):
threading.Thread(target=Bot_Game_auto_updater.start_updater,
args=(Bot_Game,), daemon=True).start()
def problem_occured(self):
asyncio.run(notify_on_no_respond())
async def notify_on_no_respond():
guild = await bot.fetch_guild(GUILD_ID)
user = await guild.fetch_member(MY_ID)
await user.send('a problem occured')
Bot_Game = maintainer()
Bot_Game.start_thread(Bot_Game)
bot.run(TOKEN)
# Bot_Game_auto_updater.py
def start_updater(Bot_Game):
Thread_Auto_Updater = auto_updater(Bot_Game)
class auto_updater(object):
def __init__(self, Bot_Game):
Bot_Game.problem_occured()
First of all to you main Problem: I would recommend not using that code, there is a way better way to do so with the get_user method:
from discord.utils import get
user = await client.get_user(user_id)
To DM a user I use this code:
channel = await user.create_dm()
await channel.send("a problem occured")
Hope this helped :D

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)

Repl.it environment secret variables are None type

I am trying to make a discord bot.
Using secret environment variables in repl.it, when I try to take the value of the variable, it says its of None type
import discord
import os
client = discord.Client()
#client.event
async def onReady():
print('Yeah Bwoi I am here : {0.user}'.format(client))
#client.event
async def onMessage(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Yeee')
TK=os.environ.get('TOKEN')
print(TK)
client.run(TK)
Result:
None
Traceback (most recent call last):
File "main.py", line 20, in <module>
client.run(TK)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/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'
This Traceback shows that the "TK" variable is empty. This can happen if you haven't actually added a secret into the replit env secrets, if thats the case add one like this:
replit preview
Having a .env file won't help your case as repl recently remove support for them.
What I did is I recreated my repl and make sure you create a Python repl.

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!

Trouble connecting bot to Discord

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"

Categories