I’m building a Telegram bot using Python with the pyrogram framework. The bot connects to a MySQL database during startup like this:
bot = Client("telegram_bot", api_id=settings.API_ID, api_hash=settings.API_HASH,
bot_token=settings.BOT_TOKEN, parse_mode=enums.ParseMode.DEFAULT)
with bot:
try:
db_connection = mysql.connector.connect(host="localhost", user=settings.DB_USER,
password=settings.DB_PASS, database=settings.DB_NAME)
except Exception as error:
print(f'Database Error: {error}')
exit()
I have a message handler that looks like this:
@bot.on_message(filters.private & filters.text & filters.user(settings.ADMIN_LIST))
async def processAdminMessage(client: Client, msg: types.Message):
content = msg.text.lower()
sender_id = msg.from_user.id
conversation_id = msg.chat.id
message_id = msg.id
if content == 'count':
cursor = db_connection.cursor(buffered=True)
cursor.execute('SELECT COUNT(*) FROM members')
data = cursor.fetchone()
if not data:
data = [0]
cursor.close()
response = f'Total members: {data[0]}'
await msg.reply(response, reply_to_message_id=message_id)
return
The bot works fine when I run it normally. However, when I start it with nohup python bot.py & and let it run for several hours, I get this error:
File "/path/to/mysql/connector/connection_cext.py", line 772, in cursor
raise OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
Why does this happen? Does MySQL automatically close connections after some time? How can I fix this issue?