Thursday, 24 March 2022

How can i improve the performance of my python task?

I have a problem. So I have a task that runs every time when a user writes a chat message on my discord server - it's called on_message. So my bot has many things to do in this event, and I often get this kind of error:

Task was destroyed but it is pending!
task: <Task pending name='pycord: on_message' coro=<Client._run_event() done, defined at /Bots/gift-bot/discord/client.py:374> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f68a7bdfc10>()]>>

So I think if I want to fix this, I need to speedup my code. But sadly, I don't have any clue how i can do it to fix this error.

Edit: I integrated timings and this is what I get printed:

after cooldown: 7.677078247070312e-05
after mysql: 0.07229304313659668
after cooldown: 7.557868957519531e-05
after mysql: 0.05353689193725586


  @commands.Cog.listener("on_message")
  async def on_message(self, message):
    start = time.time()


    if message.author.bot:
        return

    if message.type != discord.MessageType.default:
        return

    if isinstance(message.channel, discord.channel.DMChannel):
        return


    # Cooldown


    self.member_cooldown_list = [i for i in self.member_cooldown_list if i[1] + self.cooldown_val > int(time.time())]
    member_index = next((i for i, v in enumerate(self.member_cooldown_list) if v[0] == message.author.id), None)
    if member_index is not None:
        if self.member_cooldown_list[member_index][1] + self.cooldown_val > int(time.time()):
            return

    self.member_cooldown_list.append((message.author.id, int(time.time())))

    print(f"after cooldown: {time.time() - start}")
    start2 = time.time()


    # Role-Check (Bonus/Ignore)


    count = 1
    mydb = await getConnection()
    mycursor = await mydb.cursor()
    await mycursor.execute("SELECT ignore_role_id, bonus_role_id FROM guild_role_settings WHERE guild_id = %s", (message.author.guild.id,))
    in_database = await mycursor.fetchone()
    if in_database:
        if in_database[0] is not None:
            role_list = in_database[0].split(" ")
            for roleid in role_list:
                try:
                    int(roleid)
                except ValueError:
                    continue

                role = message.author.guild.get_role(int(roleid))
                if role is None:
                    continue

                if role in message.author.roles:
                    await mycursor.close()
                    mydb.close()
                    return

        if in_database[1] is not None:
            role_list = in_database[1].split(" ")
            for roleid in role_list:
                try:
                    int(roleid)
                except ValueError:
                    continue

                role = message.author.guild.get_role(int(roleid))
                if role is None:
                    continue

                if role in message.author.roles:
                    count += 1


    # Channel-Check (Bonus/Ignore)


    await mycursor.execute("SELECT ignore_channel_id FROM guild_channel_settings WHERE guild_id = %s", (message.author.guild.id,))
    in_database1 = await mycursor.fetchone()
    if in_database1:
        if in_database1[0] is not None:
            channel_list = in_database1[0].split(" ")
            for channelid in channel_list:

                try:
                    int(channelid)
                except ValueError:
                    continue

                if int(message.channel.id) == int(channelid):
                    await mycursor.close()
                    mydb.close()
                    return


    # write to database


    await mycursor.execute("SELECT * FROM guild_message_count WHERE guild_id = %s AND user_id = %s", (message.author.guild.id, message.author.id))
    in_database2 = await mycursor.fetchone()
    if in_database2:
        await mycursor.execute("INSERT INTO guild_message_count (user_id, message_count, guild_id) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE message_count = message_count + 1", (message.author.id, count, message.author.guild.id))

    await mydb.commit()
    await mycursor.close()
    mydb.close()

    print(f"after mysql: {time.time() - start2}")


from How can i improve the performance of my python task?

No comments:

Post a Comment