Search code examples
pythondiscorddiscord.pybots

AFK command `on_message()` mentions check not working


I am trying to make a basic AFK command but when I check if a user is in the server AFK list and it has been mentioned and I try to send the afk message it doesn't work! It doesn't even show any error.

Here is my code:

import discord
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="-", intents=intents, case_insensitive=True)

afk_lists = {}

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

@bot.event
async def on_message(message):
    global afk_lists

    if message.mentions:
        for user in message.mentions:
            if user.id in afk_lists:
                await message.channel.send(f"{user.mention} is currently AFK!")

    await bot.process_commands(message)

@bot.command()
async def afk(ctx):
    global afk_lists

    server_id = ctx.guild.id
    if server_id not in afk_lists:
        afk_lists[server_id] = []
    user_id = ctx.author.id
    afk_lists[server_id].append(user_id)
    await ctx.send("AFK set!")

@bot.command()
async def show_afk_list(ctx):
    global afk_lists

    server_id = ctx.guild.id
    if server_id in afk_lists:
        afk_list = afk_lists[server_id]
        await ctx.send(f"AFK List: {afk_list}")
    else:
        await ctx.send("AFK List is empty!")

token = "MY_TOKEN"
bot.run(token)

Solution

  • below you write the user ids in this pattern afk_list[server_id] with the user id in it

    but in the check

    if user.id in afk_lists:
        await message.channel.send(f"{user.mention} is currently AFK!")
    

    where you check if the user id is in the list

    you need to check if the user id is in the server afk list

    like this

    if user.id in afk_lists[message.guild.id]:
        ...
    

    where you should add a check if the message is even sent on a guild to reduce error messages ;)