Discord.py Errors - python

Today I wanted to try to create a discord bot with python. The problem i have is, that there is always an error message when I start the program:
Traceback (most recent call last):
File "D:\...\Discord Bot\PythonGPU_Bot\bot.py", line 1, in <module>
import discord
File "C:\Users\...\Python\Python39\lib\discord\__init__.py", line 4, in <module>
client = discord.Client()
AttributeError: partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)
Thats the Error message I always get.
This is my script:
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print('Logged in as {}'.format(client.user.name))
client.loop.create_task(status_task())
async def status_task():
while True:
await client.change_presence(activity=discord.Game('Hello <:'))
await asyncio.sleep(1)
await client.change_presence(activity=discord.Game('Hello c:'))
await asyncio.sleep(1)
#client.event
async def on_message(message):
if message.auther.bot:
return
if '.status' in message.content:
await message.channel.send('SSSS')
client.run('ID')
I hope someone can help me out.

The name of your file is discord.py, rename the file
rename it to bot.py or main.py or anything you like and your issue will be fixed
Why does it happen?
Since your file name is discord.py, it is actually importing that file and not the actual discord.py module you installed with pip.

Related

AttributeError: 'Member' object has no attribute 'avatar_url'

I am trying to make a Discord bot and one of the features is a welcoming from my bot using on_member_join. This is the event:
#bot.event
async def on_member_join(member, self):
embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f"Welcome to Rebellions server! You are the{len(list(member.guild.members))}th member!")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
await welcome_channel.send(embed=embed)
Although when the bot is working and running and someone joins my server I get this error:
[2022-11-07 19:38:10] [ERROR ] discord.client: Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\stene\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\stene\OneDrive\Documents\GitHub\bot\main.py", line 25, in on_member_join
embed.set_thumbnail(url=f"{member.avatar_url}")
^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'
I am running the latest version of discord.py and python.
Thanks!
welcome cog:
import discord
from discord.ext import commands
import asyncio
import datetime
class WelcomeCog(commands.Cog, name="Welcome"):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_member_join(self, member):
embed = discord.Embed(colour=discord.Colour(0x95efcc), description=f"Welcome to Rebellions server! You are the{len(list(member.guild.members))}th member!")
embed.set_thumbnail(url=member.avatar.url)
embed.set_author(name=member.name, icon_url=member.avatar.url)
embed.set_footer(text=member.guild)
embed.timestamp = datetime.datetime.utcnow()
channel = self.bot.get_channel(1038893507961692290)
await channel.send(embed=embed)
async def setup(bot):
await bot.add_cog(WelcomeCog(bot))
print("Welcome cog has been loaded successfully!")
In discord.py 2.0 the attribute Member.avatar_url got removed and replaced by Member.avatar. To access the URL, you should use member.avatar.url.
Check out the migration guide for similar instances. Using pip freeze you can check which version of discord.py you have installed, but I assume it's 2.x, and probably you followed a tutorial or copied a code example that used discord.py 1.x.
Following your code you have several errors, which can be corrected in the following code:
First: async def on_member_join(member, self): is an incorrect code.
self always comes before any other argument if this event is in a cog file, but still it isn't a required argument so completely remove it. The correct code for this line is async def on_member_join(member):
Second: Make sure you're using the correct event listener.
#client.event or #bot.event if this is in your Main file, and #commands.Cog.listener() if this is in your cog file.
Third: Please change (member, self): to (member:discord.Member)
Good luck! :D

Discord if statement with message author role

I know that I must not be the first one trying to do this. But I really cannot find the solution to my problem. Here is what i'm trying to do. I'm trying to print the member role in the channel only if is role is "member". The thing is, i'm not able to get is role and use it in the IF statement. I tried a lot of thing until I finally understood that the object Client doesn't have a get_context method. But everyone is using it and seems to be able to make things work. I've read the official API docs and I can clearly see that the object "Client" doesn't have a get_context method, but the ext.command.Bot object does. What can I do to make things work ?.
Here is the error I get:
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Discord-Moderator/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 21, in on_message
ctx = await client.get_context(message)
AttributeError: 'Client' object has no attribute 'get_context'
Here is my code:
import discord
import os
import random
from stayin_alive import stayin_alive
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
msg = message.content.lower()
ctx = await client.get_context(message)
if message.author == client.user:
return
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.server.roles)
if role in message.author.roles:
await message.channel.send("You are a member")
I even tried with the commands thing in order to do it like this Discord.py bot.get_context() does not return ctx object
import commands
from stayin_alive import stayin_alive
client = discord.Client()
bot = commands.Bot(command_prefix=("!sm"))
But I get this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
import commands
ModuleNotFoundError: No module named 'commands'
Here is everything I checked out:
https://www.codegrepper.com/code-examples/python/discord.py+add+role+to+user
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html (Bot command Object official Doc)
https://discordpy.readthedocs.io/en/stable/api.html (Client Object Official Doc)
Discord.py bot.get_context() does not return ctx object
https://www.reddit.com/r/learnpython/comments/o8jpi6/so_im_making_a_discord_bot/
How can I get a Discord Context Object from the on_message event?
Can someone please help me to find the solution to my problem. I simply wanna use the message.author.role in my IF statement.
Here is the solution, I've finally found it, I wasn't that far, I knew I could do it without using ctx

Discord.py ctx commands not recognised

im fairly new to coding in general and recently started trying to code my own bot. Almost all of the tutorials i have seen use the ctx command however, whenever i use it i get this error:
"NameError: name 'ctx' is not defined"
Here is part of my code that uses the ctx command. The aim is to get it to delete the last 3 messages sent.
#client.event
async def purge(ctx):
"""clear 3 messages from current channel"""
channel = ctx.message.channel
await ctx.message.delete()
await channel.purge(limit=3, check=None, before=None)
return True
#client.event
async def on_message(message):
if message.content.startswith("purge"):
await purge(ctx)
client.run(os.environ['TOKEN'])
Full error:
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 31, in on_message
await purge(ctx)
NameError: name 'ctx' is not defined
I'm hosting the server on repl.it if that makes any difference and as i said, im pretty new to coding so it's possible i have missed something very obvious, any help is appreciated. ^_^
A fix to that is:
async def purge(message):
await message.delete()
channel = message.channel
await channel.purge(limit=3)
#client.event
async def on_message(message):
if message.content.startswith("purge"):
await purge(message)
The problem is the on_message function uses message and not ctx. Replacing message with ctx wont work because im pretty sure the on_message cant use ctx

AttributeError: 'Member' object has no attribute 'client'

I am a new user of discord.py, and i'm facing an issue with a simple code :
from dotenv import load_dotenv
import discord
from discord.ext.commands import Bot
import os
load_dotenv()
class Bothoven:
def __init__(self):
self.version = 0.1
self.client = discord.Client()
self.bot = Bot(command_prefix='$')
#self.bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(self.bot))
#self.bot.command()
async def test(ctx):
print(ctx)
await ctx.send("oui maitre")
self.bot.run(os.getenv("BOT_TOKEN"))
When I run it, everything seems good, the bot prints :
We have logged in as Bothoven#9179
But when I type something in the guild, it rises an exception :
Ignoring exception in on_message
Traceback (most recent call last):
File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\ext\commands\bot.py", line 942, in on_message
await self.process_commands(message)
File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\ext\commands\bot.py", line 935, in process_commands
if message.author.client:
AttributeError: 'Member' object has no attribute 'client'
I understand the error, and I agree that author has no attribute client, but this statement is in bot.py, a library file.
Have you some idea of how to proceed ?
I'm runing python3.8 and discord.py 1.6
EDIT :
Despite pip was telling me all packages were up to date, deleting my venv and rebuilding it resolved my issue.
There are a few things wrong with your Cog setup:
You have to use commands.Cog.listener() to exploit events
To create commands, use the commands.command() decorator
Your self.bot definition is wrong and you don't need self.client
Here how you would setup your cog correctly:
from os import environ
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
class Bothoven(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready():
print('Logged in as {0.user}'.format(self.bot))
#commands.command()
async def test(ctx):
print(ctx)
await ctx.send("Oui maƮtre")
bot.add_cog(Bothoven(bot))
bot.run(environ["BOT_TOKEN"])
You can find more about cogs here.
EDIT : Turns out it was a venv issue, re-building it solved the problem.

Discord.py int has no attribute send

Hey so I got this code
import discord
import asyncio
import random
import os
import time
from discord.ext import tasks, commands
client = discord.Client()
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format (client))
async def background_loop():
await client.wait_until_ready()
while not client.is_closed():
channel =(814588208091365426)
messages = ["Test1", "Test2", "Test3"]
await channel.send(random.choice(messages))
await asyncio.sleep(60)
client.loop.create_task(background_loop())
client.run(os.getenv('token'))
and I am getting this error:
future: <Task finished name='Task-1' coro=<background_loop() done, defined at main.py:15> exception=AttributeError("'int' object has no attribute 'send'")>
Traceback (most recent call last):
File "main.py", line 20, in background_loop
await channel.send(random.choice(messages))
AttributeError: 'int' object has no attribute 'send'
I also tried adding
return messages
I didnt get an error but the bot also didnt do anything.
Thanks in advance
You are trying to call the function send on the number 814588208091365426, this is the channel id, you need to convert the channel id to a channel with:
channel = client.get_channel(814588208091365426)

Categories