discord.py – count how many times a user has bee mentioned in a specific channel

Question:

I’m coding a discord bot a for a friend using python (discord.py) and i’ve a specific task i want the bot to do that i can’t figure out how to code (i’m kinda a newbie with py), so here it is: we use a specific text-channel to post wins of the games we play mentioning every partecipant, i want the bot to count every mention a user has in that channel and return me the number. Reading here and there i saw i should be using either message.raw_mentions or message.mentions but i don’t know how to make it select the proper channel and how to just return the number of a specific user’s mentions. So far the code looks like this:

async def testcommand(self, context: Context, user: discord.User) -> None:
  
    member = context.guild.get_member(user.id) or await context.guild.fetch_member(user.id)
    mentions = message.mentions

    for user in mentions:
        if user.id in ???????????

    embed = discord.Embed(
        title="**Wins:**",
        description=f"{member}",
        color=0x9C84EF
    )
    await context.send(embed=embed)

Thanks for your help, have a nice day!

UPDATE:
Code works now and looks like this:

async def testcommand(self, context: Context, user: discord.Member, channel: discord.TextChannel) -> None:
    
    potato = 0
    async for message in channel.history(limit=None):
        if user in message.mentions:
            potato += 1
    
    embed = discord.Embed(
        title="**Test:**",
        description=f"{potato}",
        color=0x9C84EF
    )
    await context.send(embed=embed)

Problem is doesn’t fetch from channels that are too rich of messages, i get this error:

2022-12-09 14:52:26 ERROR    discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordapp_commandscommands.py", line 861, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:UsersGianvitoDesktopdts_botcogstemplate.py", line 44, in testcommand
    await context.send(embed=embed)
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordextcommandscontext.py", line 876, in send
    await self.interaction.response.send_message(**kwargs)
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordinteractions.py", line 769, in send_message
    await adapter.create_interaction_response(
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordwebhookasync_.py", line 218, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordextcommandshybrid.py", line 438, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordapp_commandscommands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'testcommand' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UsersGianvitoAppDataLocalProgramsPythonPython311Libsite-packagesdiscordclient.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:UsersGianvitoDesktopdts_botbot.py", line 201, in on_command_error
    raise error
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'testcommand' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

I’ve read somewhere that could be the discord API that requires a feedback in a span of time (2 or 3 seconds) that doesn’t get, i supposed, cause the bot requires more time to fetch a big channel.

Asked By: gianprito

||

Answers:

Maybe something like this, where it iterates over every message sent in the current channel?

@bot.command()
async def some_command(ctx):
    mentions = 0

    async for message in ctx.channel.history(limit=10000000):  # set limit to some big number
        if ctx.author in message.mentions:
            mentions += 1

    await ctx.send(mentions)

The above code counts the number of times the author is mentioned in the current channel.
Of course, this is highly inefficient, but it gets the job done.


If you wish to add more parameters (such as the user and the channel):

@bot.command()
async def better_command(ctx, user: discord.Member, channel: discord.TextChannel):
    mentions = 0

    async for message in channel.history(limit=10000000):  # set limit to some big number
        if user in message.mentions:
            mentions += 1

    await ctx.send(mentions)
Answered By: J Muzhen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.