0
votes

I'm working on a python discord bot that needs mysql. The problem is this script is supposed to be active for long times and not always using the mysql. When some time has passed and it tries to connect to the database I can't connect because it lost connection to the server mid-query and then the connection went away. I want to make sure it never loses connection. I'm using mysql-connector. I also have no access to the mysql server itself. I can only access the database and tables etc, nothing more. I've already tried a thread that runs 3 in 3 minutes just fetching random data from it the problem is when I start the thread the bot doesn't respond to any command in discord... Code:

def keep_mysql():
    while True:
        keepalive = "SELECT * FROM prefixes"
        mycursor.execute(keepalive)
        result = mycursor.fetchall()
        print("Keeping mysql connection alive")
        time.sleep(180)


@bot.event
async def on_ready():
    keepalive = threading.Thread(target=keep_mysql())
    keepalive.start()
1

1 Answers

0
votes

How about using a loop that runs infinitely? I use something like this to continuously check the time.

import asyncio
from discord.ext.tasks import loop

@loop(count=None)
async def keep_sql():
    await client.wait_until_ready()
    keepalive = "SELECT * FROM prefixes"
    mycursor.execute(keepalive)
    result = mycursor.fetchall()
    print("Keeping mysql connection alive")
    asyncio.sleep(180)

@bot.event
async def on_ready():
    print("Bot is online")

keep_sql.start()
bot.run(token)