Task was destroyed but it is pending! in aiomysql and discord.py

Viewed 167

I've been making a discord bot and I use MySQL to store some needed info. Until now I was using mysqlconnector but since that's not async I decided to change to aiomysql. The thing is, now, sometimes, I get the Task was destroyed but it is pending! error in events like on_message, on_reaction_add, etc (All events really). This is not always, sometimes it works, others it throws this.

Error example:

Task was destroyed but it is pending!
task: <ClientEventTask state=pending event=on_message coro=<function on_message at 0x7fcee572af70>>

This is how I'm doing eveything:

# mysqlconnection.py

import aiomysql

pool = None
loop = None

def setLoop(botloop):
    global loop
    loop = botloop

async def getpool():
    global pool
    pool = await aiomysql.create_pool(host="host", user="user", password="password", db="db", loop=loop, pool_recycle=0)

async def execute_search(search: str, vals: tuple = None):
    connection = await pool.acquire()
    cursor: aiomysql.cursors.Cursor = await connection.cursor()
    if vals is None:
        await cursor.execute(search)
    else:
        await cursor.execute(search, vals)
    result = await cursor.fetchall()
    await cursor.close()
    pool.release(connection)
    return result

async def execute_alter(query: str, vals: tuple):
    connection = await pool.acquire()
    cursor = await connection.cursor()
    await cursor.execute(query, vals)
    await connection.commit()
    await cursor.close()
    pool.release(connection)
# bot.py

from mysqlconnection import execute_search, execute_alter, setLoop, getpool

@bot.event
async def on_ready():
    setLoop(bot.loop)
    await getpool()
    print(f'{bot.user.name} has connected to Discord!')
    ...

Everytime I need to query the db I use either execute_search(If I'm doing a SELECT query) or execute_alter (if I'm doing an INSERT or UPDATE query).

What can I do to prevent these errors from happening?

0 Answers
Related