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
Related
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
I am trying to make a "!invite" command to generate an invite link to the server and send it to the user's DM.
The command works, but I am getting the following error on console:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\001\Envs\Pix\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\001\PycharmProjects\Testing bot\cogs\invite.py", line 27, in on_message
if ctx.author.guild_permissions.administrator:
AttributeError: 'ClientUser' object has no attribute 'guild_permissions'
Nevertheless, I get the link: My DM screenshot.
How can I fix this error?
Code:
from discord.ext import commands
from var.canais import inviteChannel
class Invite(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command(
name='invite',
pass_context=True
)
async def invite(self, ctx):
invitelink = await ctx.channel.create_invite(
max_uses=1,
unique=True
)
if inviteChannel:
await ctx.message.delete()
await ctx.author.send(f'Invite link: {invitelink}')
#commands.Cog.listener()
async def on_message(self, ctx):
if inviteChannel:
if ctx.author.guild_permissions.administrator:
return
else:
if not ctx.content.startswith('!invite'):
await ctx.delete()
def setup(client):
client.add_cog(Invite(client))
This error is occurring because the on_message event is also called when the bot sends a message, and in your case the bot is sending the message in a dm, therefore it should be a User object (Member objects are guild only), and user objects don't have permissions since they are not inside a server. It's a ClientUser object instead of User which is a special class like User that is unique to the bot. this is a separate class compared to User because this has some special methods that only the bot can use like one for editing the bot's name and more
to fix this just ignore if the message is sent from a bot so the code would be
#commands.Cog.listener()
async def on_message(self, ctx):
if message.author.bot:
return
if inviteChannel:
if ctx.author.guild_permissions.administrator:
return
if not ctx.content.startswith('!invite'):
await ctx.delete()
Here I added if message.author.bot: return so that it stops the function execution if the author is a bot. and I also removed the unnecessary else statement
As the error says:
The line
if ctx.author.guild_permissions.administrator:
throw an AttributeError error because 'ctx.author' (of type ClientUser) does not have guild_permissions attribute.
The error massage also entail that the error was ignored, and so the code proceed without stoping.
I found this
answer that might help you overcome this issue
good luck!
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.
If we look at the Guild Create event in the discord dev documentation, we see the following:
I have a couple of questions about this. First of all, I am not sure exactly when I can create a server using a bot account. Following the "when a user is initially connecting" section, I attempted to place the server creation into the on_ready function, like so:
import discord
import asyncio
import bot.client.getkey as _getkey
from bot.utils import get_owner
class ImABot(discord.Client):
async def on_ready(self):
ts = await self.create_server("test")
inv = await self.create_invite(ts.default_channel)
await self.send_message(get_owner()) #get owner simply gets the user who owns the bot, me.
Bot = ImABot()
Bot.run(_getkey.key())
However, I get the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "/Users/edl/Desktop/ /Programming/Github/Democracy-Bot/demobot/client/client.py", line 22, in on_ready
inv = await self.create_invite(ts.default_channel)
File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 2628, in create_invite
data = yield from self.http.create_invite(destination.id, **options)
AttributeError: 'NoneType' object has no attribute 'id'
I assume this means the server was not created. I hope someone can give me information on when creating a server will work, and whether or not it is possible in the first place. Thanks!
Guilds no longer have default channels, so it is best to avoid using them.
To get the first created channel for the server, your best bet is to use
discord.utils.get(new_server.channels, type=discord.ChannelType.text)
Or if you use discord.py rewrite, then
new_server.text_channels[0]
Then you can create the invite from that channel.
I am working on a bot to do some simple commands for my discord server and I haven't been able to figure out how to get the bot to mention people who aren't the author.
if message.content.startswith("+prank"):
user = client.get_user_info(id)
await client.send_message(message.channel, user.mention + 'mention')
When I try to run the command i come up with the error message:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:/Users/user/Desktop/Murk-Bot 2.0.py", line 130, in on_message
await client.send_message(message.channel, user.mention + 'mention')
AttributeError: 'generator' object has no attribute 'mention'
This happens if I use the command with a mention before, after, and not at all. If it gives some more context here are the imports I am using
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
The specific error you are getting is caused by not awaiting a coroutine. client.get_user_info is a coroutine and must use await.
If you want "+prank" to work by mentioning by username, you can find a member object by using server.get_member_named.
Example code provided below. This will check the server the command was called from for the specified username and return the member object.
if message.content.startswith("+prank"):
username = message.content[7:]
member_object = message.server.get_member_named(username)
await client.send_message(message.channel, member_object.mention + 'mention')
It looks like you're trying to implement commands without actually using commands. Don't put everything in the on_message event. If you're not sure how to use the discord.ext.commands module, you can look at the documentation for the experimental rewrite branch.
import discord
from discord.ext.commands import Bot
bot = Bot(command_prefix='+')
#bot.command()
async def prank(target: discord.Member):
await bot.say(target.mention + ' mention')
bot.run('token')
You would use this command with +prank Johnny. The bot would then respond in the same channel #Johnny mention