Ошибка 409 телеграм бот

для начала удалите

if __name__ == '__main__':
     bot.polling(none_stop=True)

а webhook, у меня работает так:

WEBHOOK_HOST = 'URL' #без http:// и https://
WEBHOOK_PORT = 88  # 443, 80, 88 or 8443 (port need to be 'open')
WEBHOOK_LISTEN = '0.0.0.0'  # In some VPS you may need to put here the IP addr

WEBHOOK_SSL_CERT = '/etc/nginx/ssl/FILE.cer'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = '/etc/nginx/ssl/FILE.key'  # Path to the ssl private key

WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/%s/" % (constant.token)

bot = telebot.TeleBot(constant.token)

class WebhookServer(object):
    @cherrypy.expose
    def index(self):
        if 'content-length' in cherrypy.request.headers and \
                        'content-type' in cherrypy.request.headers and \
                        cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            # Эта функция обеспечивает проверку входящего сообщения
            bot.process_new_updates([update])
            return ''
        else:
            raise cherrypy.HTTPError(403)
bot.remove_webhook()

bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
                certificate=open(WEBHOOK_SSL_CERT, 'r'))

cherrypy.config.update({
    'server.socket_host': WEBHOOK_LISTEN,
    'server.socket_port': WEBHOOK_PORT,
    'server.ssl_module': 'builtin',
    'server.ssl_certificate': WEBHOOK_SSL_CERT,
    'server.ssl_private_key': WEBHOOK_SSL_PRIV
})

cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})

2 Answers

Quoted from Telegram-Bot-Api,

Notes

  1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.

To solve this, delete the webhook you did setup using your bot-token by simply providing no url:

https://api.telegram.org/bot<token>/setWebhook

let’s say, your bot-token: 12345:abxef3ed

So, you just perform this:
https://api.telegram.org/bot12345:abxef3ed/setWebhook

make sure you wrote ‘bot’ before token, not only token itself!

*I know this is too late for you, but may help others.

shalnaya_bjilka's user avatar

answered May 17, 2018 at 19:38

user404's user avatar

user404user404

1,9341 gold badge17 silver badges32 bronze badges

5

  • @WiseStrawberry, just for your case it does not work(I wonder why not) you cast a downvote!!!??

    Sep 16, 2019 at 9:06

  • I use telegraf-js, and this doesnt fix it, i keep getting the same response when starting up my bot, I’d love to give you an upvote but for me personally it didnt do anything. What is supposed to happen/what is the expected response? I can only start my bot new if i delete the old api token. The downvote is more of a frustration with my bot than an attack on your answer :)

    Sep 16, 2019 at 9:28

  • I think you are following something else as you are saying starting up your bot(I assume). If possible follow their rest api I have mentioned in my answer and this thread q/a is for webhook.

    Sep 16, 2019 at 9:38

  • do you mean a webhook? Because im following multiple webhooks that are not telegram, is that something that is not going right? I’m gonna check again. I re-applied the +1 to your question

    Sep 16, 2019 at 10:39

  • yes, this q/a thread is about webhook problem and solutions are provided based on that. To activate and get data from your bot register webhook, if not needed, just clear that hook as mentioned in the answer. You can follow their RES API

    Sep 16, 2019 at 10:54

answered Mar 20, 2016 at 23:40

Giovanni S.'s user avatar

@setovi

Please answer these questions before submitting your issue. Thanks!

  1. What version of pyTelegramBotAPI are you using?

pyTelegramBotAPI 4.7.1

  1. What OS are you using?

docker images in Mac OS Ventura and Ubuntu 22.04 on Raspberry Pi 4. Same behaviour.

  1. What version of python are you using?

3.8-buster
3.9-bullseye

Same behaviour.

The bot runs fine but the following appears continuously in the logs. First every few seconds, some time later about 30+ seconds every exception.

2022-11-02 10:02:01,917 (init.py:1089 MainThread) ERROR — TeleBot: «Exception traceback:
Traceback (most recent call last):
File «/usr/local/lib/python3.8/site-packages/telebot/init.py», line 1077, in __threaded_polling
polling_thread.raise_exceptions()
File «/usr/local/lib/python3.8/site-packages/telebot/util.py», line 116, in raise_exceptions
raise self.exception_info
File «/usr/local/lib/python3.8/site-packages/telebot/util.py», line 98, in run
task(*args, **kwargs)
File «/usr/local/lib/python3.8/site-packages/telebot/init.py», line 653, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File «/usr/local/lib/python3.8/site-packages/telebot/init.py», line 627, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File «/usr/local/lib/python3.8/site-packages/telebot/apihelper.py», line 334, in get_updates
return _make_request(token, method_url, params=payload)
File «/usr/local/lib/python3.8/site-packages/telebot/apihelper.py», line 162, in _make_request
json_result = _check_result(method_name, result)
File «/usr/local/lib/python3.8/site-packages/telebot/apihelper.py», line 189, in _check_result
raise ApiTelegramException(method_name, result, result_json)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running

Obviously no more than one instance running.

Thanks in advance

@Badiboy

Obviously no more than one instance running.

Not obviously without any details. If Telegram says it does — it definitely does.
Check your code, may be it runs in parallel.

@setovi

But this is the code 😀 :

from config import *
import telebot

bot = telebot.TeleBot(TELEGRAM_TOKEN)

@bot.message_handler(commands=[«start», «help»])
def cmd_start(message):
bot.reply_to(message, «Hi!»)

if name == «main«:
print(«Starting bot»)
bot.infinity_polling()
print(«End»)

Maybe when one run is finished, the Telegram API does not know so the next bot execution triggers the message?

@Badiboy

print("Starting bot»)

  1. Show the console output after program starts and before Telegram error.
  2. Show the config which you imports.

Nothing happens without reasons. The only thing is to find the problem in your code. :)

@setovi

Console output:

Starting bot
2022-11-03 13:45:22,690 (init.py:1087 MainThread) ERROR — TeleBot: «Threaded polling exception: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running»
2022-11-03 13:45:22,691 (init.py:1089 MainThread) ERROR — TeleBot: «Exception traceback:
Traceback (most recent call last):
File «/home/user/.local/lib/python3.10/site-packages/telebot/init.py», line 1077, in __threaded_polling
polling_thread.raise_exceptions()
File «/home/user/.local/lib/python3.10/site-packages/telebot/util.py», line 116, in raise_exceptions
raise self.exception_info
File «/home/user/.local/lib/python3.10/site-packages/telebot/util.py», line 98, in run
task(*args, **kwargs)
File «/home/user/.local/lib/python3.10/site-packages/telebot/init.py», line 653, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File «/home/user/.local/lib/python3.10/site-packages/telebot/init.py», line 627, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File «/home/user/.local/lib/python3.10/site-packages/telebot/apihelper.py», line 334, in get_updates
return _make_request(token, method_url, params=payload)
File «/home/user/.local/lib/python3.10/site-packages/telebot/apihelper.py», line 162, in _make_request
json_result = _check_result(method_name, result)
File «/home/user/.local/lib/python3.10/site-packages/telebot/apihelper.py», line 189, in _check_result
raise ApiTelegramException(method_name, result, result_json)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
«

The config.py is just one line,

TELEGRAM_TOKEN = «mybotprivatetoken»

@Badiboy

Can you try to simply remove this line?
if name == "main":

@setovi

@Badiboy

image

Everything is fine for me.

When running the below file I get the following error code 409 despite trying everything to ensure that I only have one local process making the infinity_polling() call. I have looked through all of the other stack overflow posts relating to this same error code 409 but I can’t find any that match my situation or whose solutions work for me.

Notes:

  • MacOS Ventura 13.5
  • VSCode 1.81.1 (Universal)
  • Python 3.9.12 in my project’s repo which is using pyenv 2.3.24
  • pip3 list contains pyTelegramBotAPI 4.13.0 and telebot 0.0.5, but my associate running the same code base has no issue with just pyTelegramBot 4.9.0 installed and no telebot.
  • pip 23.2.1 from /Users/*******/.pyenv/versions/3.9.12/lib/python3.9/site-packages/pip (python 3.9)
  • another member of my team runs the same code to perform tests from a different machine and that works just fine

What I’ve tried:

  • restarting my computer
  • tracking down every python and vscode process in activity monitor and killing them
  • deleting the whole local repo and re-cloning it
  • uninstalling pyTelegramBotAPI and telebot and re installing them via pip3
  • checking import statement: TelegramBot.py imports helper.py which imports fileNo2.py which imports TelegramBot.py with a from TelegramBot import * statement, but I’ve commented out that last statement to see if there is any issue with circular imports despite the if __name__ == '__main__': guard but nothing changes and I still get the error code 409.
  • using just pyTelegramBotAPI version 4.9.0 like my colleague and uninstalling telebot but this does not appear to affect anything.
  • adding a call to bot.remove_webhook() just above the bot.infinity_polling() line, but this also doesn’t appear to change anything.

What I would prefer not trying:

  • I would be really happy if I don’t end up having to create a new token or a new telegram bot: there are other people with whom I’m working that would make this complicated

What would help me understand this better:

  • Is the issue with the multiple bot instances running just a local issue? i.e. it’s ok to have two separate machines running this file making separate getUpdates requests to the telegram servers but not two processes on the same machine?
  • How could another process that calls bot.infinity_polling() be running if I’ve restarted my computer? Doesn’t restarting a computer kill all processes by definition?

The file:

import telebot
import emoji
import sys
import Helpers.helper as helper

TOKEN = '*************************************'

bot = telebot.TeleBot(TOKEN, parse_mode=None)

@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message, "// List of commands for the bot")

if __name__ == '__main__':
    try:
        print("before call to IP")
        bot.infinity_polling()
        print("after call to IP")
    except (KeyboardInterrupt, SystemExit):
        pass

The terminal output (note that I use ctrl-C to kill it after one error message):

before call to IP
2023-08-26 14:40:01,906 (__init__.py:1083 MainThread) ERROR - TeleBot: "Threaded polling exception: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"
2023-08-26 14:40:01,906 (__init__.py:1085 MainThread) ERROR - TeleBot: "Exception traceback:
Traceback (most recent call last):
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/__init__.py", line 1073, in __threaded_polling
    polling_thread.raise_exceptions()
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/util.py", line 108, in raise_exceptions
    raise self.exception_info
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/util.py", line 90, in run
    task(*args, **kwargs)
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/__init__.py", line 649, in __retrieve_updates
    updates = self.get_updates(offset=(self.last_update_id + 1),
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/__init__.py", line 623, in get_updates
    json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/apihelper.py", line 321, in get_updates
    return _make_request(token, method_url, params=payload)
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/apihelper.py", line 162, in _make_request
    json_result = _check_result(method_name, result)
  File "/Users/anonymous/.pyenv/versions/3.9.12/lib/python3.9/site-packages/telebot/apihelper.py", line 189, in _check_result
    raise ApiTelegramException(method_name, result, result_json)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
"
^C2023-08-26 14:40:03,895 (__init__.py:966 MainThread) ERROR - TeleBot: "Infinity polling: polling exited"
2023-08-26 14:40:03,895 (__init__.py:968 MainThread) ERROR - TeleBot: "Break infinity polling"
after call to IP

Ошибка 409 в телеграмм боте, возникающая при использовании pyTelegramBotAPI, является распространенной проблемой, с которой сталкиваются разработчики при работе с Telegram API. В данной статье мы рассмотрим эффективные стратегии и лучшие практики, которые помогут устранить данную ошибку.

Что такое ошибка 409?

Ошибка 409 в телеграмм боте является HTTP-кодом ошибки, который указывает на конфликт между запросом и текущим состоянием ресурса на сервере. Она может возникать в различных ситуациях, но чаще всего ошибка связана с некорректным использованием API методов или параллельными запросами от нескольких пользователей.

Почему возникает ошибка 409 в телеграмм боте?

Ошибка 409 может возникнуть по нескольким причинам:

  1. Повторное создание объекта с уже существующим идентификатором.

  2. Изменение данных, которые уже были обновлены другим запросом.

  3. Параллельные запросы на изменение одного и того же ресурса.

Эффективные стратегии для устранения ошибки 409

  1. Проверка идентификаторов объектов перед их созданием. Убедитесь, что вы не пытаетесь создать объект с уже существующим идентификатором. Это можно проверить, выполнив запрос к серверу для получения информации о существующих объектах и сравнивая передаваемые идентификаторы с полученными данными.

  2. Используйте механизм блокировок для предотвращения параллельных запросов на изменение данных. Вы можете использовать семафоры или мьютексы, чтобы гарантировать, что только один поток будет иметь доступ к ресурсу в определенный момент времени.

  3. Используйте транзакции при выполнении нескольких операций на сервере. Транзакции обеспечивают атомарность операций, что означает, что во время транзакции другие клиенты не смогут внести изменения в данные, пока транзакция не будет завершена. Таким образом, вы сможете избежать конфликтов и ошибок 409.

  4. Внимательно изучите документацию Telegram API и pyTelegramBotAPI. Установите последнюю версию библиотеки pyTelegramBotAPI, так как в новых версиях часто исправляются ошибки и улучшается обработка ошибок.

Лучшие практики для работы с телеграмм ботом

  1. Регулярно проверяйте работу вашего телеграмм бота, особенно после внесения изменений в код. Так вы сможете обнаружить и исправить ошибки намного быстрее, прежде чем пользователи их заметят.

  2. Хорошо тестируйте вашего телеграмм бота, используя различные сценарии взаимодействия и проверяя его на надежность и устойчивость к ошибкам.

  3. Внимательно изучайте документацию Telegram API и pyTelegramBotAPI, чтобы быть в курсе всех возможностей и ограничений API.

  4. Реализуйте механизм обработки ошибок в вашем боте. Обработка ошибок поможет избежать возникновения проблем при работе с API и предоставит пользователю дружественное сообщение об ошибке.

Заключение

Ошибка 409 в телеграмм боте при использовании pyTelegramBotAPI может быть вызвана некорректным использованием API методов или параллельными запросами от нескольких пользователей. Однако, следуя эффективным стратегиям и лучшим практикам, можно избежать данной ошибки и обеспечить более стабильную работу вашего телеграмм бота. Будьте внимательны к документации и постоянно совершенствуйте свои навыки в разработке телеграмм ботов для достижения наилучших результатов.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 409 сбербанк
  • Ошибка 409 при загрузке
  • Ошибка 4063 тигуан
  • Ошибка 409 не найден необходимый сос crl
  • Ошибка 406 шевроле лачетти

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии