Search code examples
pythondiscorddiscord.pycounter

How do I count how often a command was executed?


I would like to display via bot how many times a command has been executed. For this I have already inquired here on the platform and have tried different things. About my code:

e = discord.Embed(color=discord.Colour.green())
user = ctx.author
e.title = f "New suggestion!"
e.set_footer(text=f"{user} | {user.id}")
e.description = f "**__Submitter:__**\n {ctx.author}"
e.add_field(name="__Suggestion:__", value=f"{text}")
e.set_thumbnail(url=ctx.message.author.avatar_url)
e.timestamp = datetime.utcnow()
await channel.send(embed=e)
await ctx.message.add_reaction("✅")

The bot should add Suggestion no. #number in the title, which will go up one at a time when the command is executed. I have already tried the following:

    def __init__(self, bot):
        self.bot = bot
        self.counter = 0

#Shortened
e.title = f "Suggestion no. {self.counter}"

Or just as well:

e.title = f "Suggestion no. {self.counter + 1}

But that didn't help, so how do I make sure that a correct number is displayed and that in case of a bot restart this number continues to rise and doesn't start again from the beginning. Note that a global event did not work for me somehow!


Solution

  • You actually need to update the counter variable

    self.counter += 1
    e.title = f"Suggestion no. {self.counter}"
    

    You can save it in a JSON or text file if you want the variable to continue after the bot restarts