'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 1:[1]

First thing you seem to be new and i suggest you take a look at how to ask more proper questions.

Second. 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChrisDewa