Search code examples
pythondiscorddiscord.py

How do I make, so my Discord.py bot counts a person's messages?


I have a leveling system in my Discord bot, but it doesn't really add anything. I want my bot to count messages a person has written, then for a specific amount of messages (i.e. 1000 messages) you will get a role. How do I do that?


Solution

  • You will need a database, I will use sqlitedict for simplicity but please take a look at other better tools like tortoise-orm.

    First define your database object. It would behave sort of like a dictionary in this example.

    from sqlitedict import SqliteDict
    db = SqliteDict(
      'db.sqlite', 
      tablename='foo', 
      autocommit=True
    )
    

    Now use it in your on_message handler

    @bot.event
    async def on_message(msg):
      if msg.guild:
        guild_db = db.get(msg.guild.id, {})
        user_db = guild_db.setdefault(
          msg.author.id, {'msgs': 0}
        )
        user_db['msgs'] += 1
        db[msg.guild.id] = guild_db
    

    The handler will now count the messages that come out from members on a per guild basis.

    You then use that information to do whatever you need

    user_db = (
      db.get(guild.id, {})
        .get(member.id, {'msgs', 0})
    )
    if user_db['msgs'] >= some_number:
      await member.add_roles(your_role)
    

    This again is not the best implementation, I just wanted to show how to keep track of a member's message count.

    For the real database look into tortoise-orm, aioslqlite, or any other more proper implementations.