V
V
Vova Putsyk2018-05-09 15:09:19
MySQL
Vova Putsyk, 2018-05-09 15:09:19

How to use django orm in telegram bot?

I have a bot written in the PyTelegramBotAPI library, in which I use django ORM. I used to get the MySQL Server has gone away error, I increased MAX_CONNECTION and now the bot just stops working without throwing any errors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rustam, 2020-06-27
@vovawed

Although the question was asked a long time ago, but I also encountered this problem.
tldr:
bot needs to be initialized bot = telebot.TeleBot(TOKEN, threaded=False)
long version:
The fact is that by default the telebot starts up with the ability to run multiple threads for each event handler. In the case of django and webhooks, this is done like this:

@csrf_exempt
def bot_view(request):
    if request.method != 'POST':
        return HttpResponse(status=403)
    if request.META.get('CONTENT_TYPE') != 'application/json':
        return HttpResponse(status=403)

    json_string = request.body.decode('utf-8')
    update = telebot.types.Update.de_json(json_string)
    bot.process_new_updates([update])

    return HttpResponse(status=200)

@bot.message_handler(commands=['start'])
def start(message):
    user = message.chat.id
    ...обработка

If someone said /start to the bot, then the following happens:
1) a post request comes to bot_view, it is queued, bot_view does not create any transaction and finishes work
2) the start method is launched in a separate thread, which is not a request. It starts and ends its work in a separate thread, while no cleanup of resources, including closing the database connection, occurs.
Here you can do the following:
either manually close all connections in each handler, release resources, or prohibit the creation of new threads for handlers. For option 2, it is enough to initialize telebot with the option threaded=False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question