для начала удалите
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, {'/': {}})
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 theif __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 thebot.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
Please answer these questions before submitting your issue. Thanks!
- What version of pyTelegramBotAPI are you using?
pyTelegramBotAPI 4.7.1
- What OS are you using?
docker images in Mac OS Ventura and Ubuntu 22.04 on Raspberry Pi 4. Same behaviour.
- 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
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.
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?
print("Starting
bot»)
- Show the console output after program starts and before Telegram error.
- Show the config which you imports.
Nothing happens without reasons. The only thing is to find the problem in your code.
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»
Can you try to simply remove this line?
if name == "main":
Everything is fine for me.
Ошибки 409 в телеграмм боте могут возникать при использовании библиотеки pyTelegramBotAPI при разработке ботов для мессенджера Telegram. Данная статья рассмотрит потенциальные причины возникновения этих ошибок и предложит способы их устранения с использованием библиотеки pyTelegramBotAPI.
Что означает ошибка 409 в телеграмм боте?
Ошибка 409 в телеграмм боте означает, что запрос от бота был отклонен сервером Telegram, и причина отказа связана с попыткой отправить дубликат сообщения. Ошибка 409 имеет код ответа 409 Conflict и может возникать, например, при попытке повторно отправить сообщение с одним и тем же уникальным идентификатором.
Причины возникновения ошибки 409
Ошибки 409 в телеграмм боте могут возникать по разным причинам. Некоторые из них включают:
- Повторная отправка сообщений с одинаковым уникальным идентификатором.
- Превышение ограничений Telegram API на скорость и количество запросов.
- Нарушение правил использования возможностей Telegram API.
- Конфликт с другими запросами, которые влияют на обработку сообщений.
Устранение ошибок 409 с помощью библиотеки pyTelegramBotAPI
Библиотека pyTelegramBotAPI предоставляет набор инструментов, которые могут помочь устранить ошибки 409 в телеграмм боте. Ниже приведены некоторые способы их устранения:
1. Генерация уникального идентификатора сообщения
Для каждого сообщения, отправляемого ботом, необходимо генерировать уникальный идентификатор. Это может быть любой уникальный идентификатор, такой как время в миллисекундах, GUID или другой уникальный идентификатор. Это поможет избежать попытки отправки дубликатов сообщений.
import uuid
message_id = str(uuid.uuid4())
bot.send_message(chat_id, text, reply_to_message_id=message_id)
2. Контроль скорости отправки запросов
Telegram API имеет ограничения на скорость и количество запросов. Чтобы избежать ошибки 409, необходимо контролировать скорость отправки запросов. Один из способов это сделать — использовать модуль time для добавления задержки между запросами.
import time
# Отправка сообщения
bot.send_message(chat_id, text)
# Задержка перед следующим запросом
time.sleep(2)
3. Обработка ошибок
Для обработки ошибок 409 можно использовать конструкцию try-except. Если при отправке сообщения произошла ошибка 409, можно повторить запрос или выполнить другие действия в зависимости от требований вашего бота.
try:
bot.send_message(chat_id, text)
except telebot.apihelper.ApiException as e:
if e.result.status_code == 409:
# Повторный запрос или другие действия
pass
Заключение
Ошибки 409 в телеграмм боте могут возникать по разным причинам, связанным с отправкой дубликатов сообщений и ограничениями Telegram API. Библиотека pyTelegramBotAPI предлагает способы устранения этих ошибок, такие как генерация уникального идентификатора сообщения, контроль скорости отправки запросов и обработка ошибок. Использование этих подходов поможет создать более надежные и эффективные телеграмм боты с помощью библиотеки pyTelegramBotAPI.
I have deployed my Telegram bot on Heroku written in Python (PyTelegramBotAPI) before and it was working without any issue. Today I tried to migrate it to Render.com. I stopped my Dyno and deployed it on Render and it logs below error. I tried deleting the Dyno completely and render still logs the same error. Finally I tried revoking the bot key but the issue is still the same. I’m certain I don’t run any extra instance of the bot. The weird part is the bot still responds for a little time after all the instances are stopped or deleted. Finally I deployed it again on Heroku and it’s working just fine. How can I fix that?
Botcode
Error:
(__init__.py:688 MainThread) ERROR - TeleBot: "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"
asked Mar 15, 2022 at 16:34