Forums

MySQL Connection not available. Database PythonAnywhere for Telegram Bot, SQLAlchemy

The problem is this: I run the script, everything works fine. a few minutes pass and the script shuts down, leaving this error.

Here is the script:

import telebot
from sqlalchemy import create_engine, Column, Integer, BigInteger
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    telegram_id = Column(BigInteger, unique=True)
    money = Column(Integer)
    money_for_investing = Column(Integer)
    invited_friends = Column(Integer)

# Connect to the database
engine = create_engine('mysql+mysqlconnector://...', pool_recycle=300, pool_pre_ping=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# Initialize the bot and set the access token
bot = telebot.TeleBot("TOKEN")

# Define the /start command handler
@bot.message_handler(commands=["start"])
def start(message):
    # Get the user's input
    cash = 0
    user_id = message.from_user.id
    investing_cash = 0
    invited_friends = 0

    user = session.query(User).filter(User.telegram_id == user_id).first()

    # If the user is not in the database, store the data
    if not user:
        user = User(telegram_id=user_id, money=cash, money_for_investing=investing_cash, invited_friends=invited_friends)
        session.add(user)
        session.commit()

        # Send a confirmation message
        chat_id = message.chat.id
        bot.send_message(chat_id=chat_id, text="You are registered.")
    else:
        # Send an error message
        chat_id = message.chat.id
        bot.send_message(chat_id=chat_id, text="You are already registered.")

# Start the bot
bot.polling()

Error:

Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1719, in _execute_context context = constructor( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled self.cursor = self.create_cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor return self.create_default_cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor return self._dbapi_connection.cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor return self.dbapi_connection.cursor(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 590, in cursor raise errors.OperationalError("MySQL Connection not available.") mysql.connector.errors.OperationalError: MySQL Connection not available. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/alexknowsbest/telegram/telegram_bot.py", line 51, in <module> bot.polling() File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1043, in polling self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout, File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1118, in __threaded_polling raise e File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1074, in __threaded_polling self.worker_pool.raise_exceptions() File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/util.py", line 156, in raise_exceptions raise self.exception_info File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/util.py", line 100, in run task(*args, **kwargs) File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 6395, in _run_middlewares_and_handler result = handler['function'](message) File "/home/alexknowsbest/telegram/telegram_bot.py", line 34, in start user = session.query(User).filter(User.telegram_id == user_id).first() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/query.py", line 2819, in first return self.limit(1)._iter().first() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/query.py", line 2903, in _iter result = self.session.execute( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1696, in execute result = conn._execute_20(statement, params or {}, execution_options) File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1631, in _execute_20 return meth(self, args_10style, kwargs_10style, execution_options) File "/usr/local/lib/python3.10/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection return connection._execute_clauseelement( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1498, in _execute_clauseelement ret = self._execute_context( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1725, in _execute_context self._handle_dbapi_exception( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2043, in _handle_dbapi_exception util.raise_( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_ raise exception File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1719, in _execute_context context = constructor( File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled self.cursor = self.create_cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor return self.create_default_cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor return self._dbapi_connection.cursor() File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor return self.dbapi_connection.cursor(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 590, in cursor raise errors.OperationalError("MySQL Connection not available.") sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available. [SQL: SELECT users.id AS users_id, users.telegram_id AS users_telegram_id, users.money AS users_money, users.money_for_investing AS users_money_for_investing, users.invited_friends AS users_invited_friends FROM users WHERE users.telegram_id = %(telegram_id_1)s LIMIT %(param_1)s] [parameters: [{}]] (Background on this error at: https://sqlalche.me/e/14/e3q8)

I've been trying to fix this mistake for a day, I can't. I switch to different modules and still nothing happens. please help me solve this problem. I will be very grateful to you

Is it about five minutes before the bot goes down? If so, what happens if you drop the pool_recycle to, say, 150 seconds?

it's 10-15 minutes somewhere. i will try to put 150.

wow, the bot has been working for a long time

the same error unfortunately, but it has been working for more than 20 minutes.

please help

See our help page on managing sqlalchemy connections: https://help.pythonanywhere.com/pages/UsingSQLAlchemywithMySQL/

doesn't works..

same error

Make sure that you are not just creating one session and then re-using it the whole time. Create a new session for each message that comes in.