A request to the Telegram API was unsuccessful. Error code: 403. Description: Forbidden: bot was kicked from the supergroup chat #2205
Replies: 9 comments
-
Nothing wrong / strange. Your code failed to process request and did not send confirmation - thus Telegram retries. Handle errors in code (like you did) and everything will be fine. |
Beta Was this translation helpful? Give feedback.
-
ExceptionHandler handles updates processing to handle exceptions when code is called not by you. For outgoing requests you did them yourself and you can easily handle exceptions. |
Beta Was this translation helpful? Give feedback.
-
No, not my code. I use telebot method |
Beta Was this translation helpful? Give feedback.
-
You should go deeper in my answers. |
Beta Was this translation helpful? Give feedback.
-
Not an issue. |
Beta Was this translation helpful? Give feedback.
-
Alright, let me show you similar situation but with different telebot behaviour. In code I'm using telebot method 2024-03-27 13:36:38,182 (async_telebot.py:576 MainThread) INFO - TeleBot: "Received 1 new updates"
2024-03-27 13:36:38,182 (request_logger.py:17 MainThread) INFO - TeleBot: "Message received: {'message_id': 14949, 'from': {'id': id, 'is_bot': False, 'first_name': 'my_first_name', 'last_name': 'my_last_name', 'username': 'my_username', 'language_code': 'en'}, 'chat': {'id': chat_id, 'first_name': 'my_first_name', 'last_name': 'my_last_name', 'username': 'my_username', 'type': 'private'}, 'date': 1711546598, 'text': 'some_message_text'}"
2024-03-27 13:36:38,674 (async_telebot.py:2728 MainThread) WARNING - TeleBot: "The parameter 'disable_web_page_preview' is deprecated. Use 'link_preview_options' instead."
2024-03-27 13:36:42,576 (exception_handler.py:14 MainThread) ERROR - TeleBot: "ApiTelegramException('A request to the Telegram API was unsuccessful. Error code: 403. Description: Forbidden: bot was blocked by the user')"
2024-03-27 13:36:42,579 (exception_handler.py:15 MainThread) ERROR - TeleBot: "Exception traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/telebot/async_telebot.py", line 525, in _run_middlewares_and_handlers
result = await handler['function'](message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/bot/main.py", line 670, in bot_command_called
await app.bot.send_photo(
File "/usr/local/lib/python3.11/site-packages/telebot/async_telebot.py", line 3189, in send_photo
await asyncio_helper.send_photo(
File "/usr/local/lib/python3.11/site-packages/telebot/asyncio_helper.py", line 491, in send_photo
return await _process_request(token, method_url, params=payload, files=files, method='post')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/telebot/asyncio_helper.py", line 99, in _process_request
raise e
File "/usr/local/lib/python3.11/site-packages/telebot/asyncio_helper.py", line 95, in _process_request
json_result = await _check_result(url, resp)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/telebot/asyncio_helper.py", line 274, in _check_result
raise ApiTelegramException(method_name, result, result_json)
telebot.asyncio_helper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 403. Description: Forbidden: bot was blocked by the user
"
2024-03-27 13:36:42,746 (request_logger.py:25 MainThread) INFO - TeleBot: "Message processing finished: 14949"
INFO: 127.0.0.6:40139 - "POST /process HTTP/1.1" 200 OK In both cases I use telebot methods, but behaviour is different. In this example ExceptionHandler handles the error and everything ok (server answer status 200). |
Beta Was this translation helpful? Give feedback.
-
I do not see any difference in processing of get_chat and send_photo. Please, provide full function code where you process updates with get_chat and with send_photo. |
Beta Was this translation helpful? Give feedback.
-
Hm, I understood the difference:
from telebot.asyncio_handler_backends import BaseMiddleware
from telebot.types import Message
class UserDataMiddleware(BaseMiddleware):
def __init__(self, app: Application):
super().__init__()
self.update_types = ['message']
self.app = app
async def pre_process(self, message: Message, data: dict):
chat = message.chat
full_chat_info = await app.bot.get_chat(chat.id)
async def post_process(self, obj: Message, data: dict, exception=None):
pass
bot = AsyncTeleBot(
token=settings.telegram.bot_token.get_secret_value(),
exception_handler=BotExceptionHandler(app),
)
bot.setup_middleware(SaveUserDataMiddleware(app))
@api.post(f'/{API_NAME}/process')
async def process_webhook(update: dict):
if update:
update = Update.de_json(update)
await bot.process_new_updates([update])
return None
@bot.message_handler(func=lambda x: True)
async def some_handler(message: Message):
# long sending photo with delay for having time to block bot
await bot.send_photo(...) |
Beta Was this translation helpful? Give feedback.
-
Yes, in middleware methods ExceptionHandler doesn't work (is it normal behaviour?). Any import traceback
from telebot.asyncio_handler_backends import BaseMiddleware
from telebot.async_telebot import logger, ExceptionHandler
from telebot.types import Message
from bot.application import Application
class SomeMiddleware(BaseMiddleware):
def __init__(self, app: Application):
super().__init__()
self.update_types = ['message']
self.app = app
async def pre_process(self, message: Message, data: dict):
chat = message.chat
time.sleep(10) # Time to block bot
await self.app.bot.send_message(
chat_id=chat.id,
text='Text to check how exception handler works in middleware',
)
async def post_process(self, obj: Message, data: dict, exception=None):
pass
class BotExceptionHandler(ExceptionHandler):
def __init__(self, app: Application):
self.app = app
async def handle(self, exception: Exception):
error_str = repr(exception)
logger.error(error_str)
logger.error("Exception traceback:\n%s", traceback.format_exc())
message = f'Bot exception occurred:\n{error_str}'
await self.app.notifier.notify(message)
return True
bot = AsyncTeleBot(
token=settings.telegram.bot_token.get_secret_value(),
exception_handler=BotExceptionHandler(app),
)
bot.setup_middleware(SomeMiddleware(app))
app.set_bot(bot)
@api.post(f'/{API_NAME}/process')
async def process_webhook(update: dict):
if update:
update = Update.de_json(update)
await bot.process_new_updates([update])
return None After sending message to bot I blocked it and got in logs: INFO: 127.0.0.6:42739 - "POST /process HTTP/1.1" 500 Internal Server Error After that telegram repeat sending my message to bot again and again... |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Please answer these questions before submitting your issue. Thanks!
What version of pyTelegramBotAPI are you using?
pyTelegramBotAPI=4.15.5
fastapi=0.97.0
uvicorn=0.22.0
What OS are you using?
debian
What version of python are you using?
3.11
Full stacktrace
Received pprinted message:
Context
Bot uses webhooks, see above the method POST /process.
On every received message bot trying to get information about sender chat with method
chat = await app.bot.get_chat(chat_id)
and save it insave_telegram_chat
function. Somebody deleted my bot from supergroup and after that calling methodbot.get_chat(chat_id)
raisesApiTelegramException
. The strange thing is:ApiTelegramException
produces 500 Internal Server Error and then telegram didn't receive 200 status and repeat sending the same message (with 'message_id': 10) again and again to bot. Also bot has ExceptionHandler and in this case exception handler doesn't work:Error was fixed with adding try-except in
save_telegram_chat
function:But this fix seems as not a proper way, because the error looks like a bug somewhere in pyTelegramBotAPI.
Logs after fixing with try-except:
Beta Was this translation helpful? Give feedback.
All reactions