Search code examples
pythonmethodsdiscordbotsclient

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.


Solution

  • enter image description here

    Here is the solution, I've finally found it, I wasn't that far, I knew I could do it without using ctx