Failed to send message to channel: maximum recursion depth exceeded while calling a Python object

i have this part of the code:

from telegram import Update, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from telegram.utils.helpers import mention_html
from datetime import datetime, timedelta
import os
from flask import Flask, request, jsonify

TOKEN = os.environ.get("TOKEN")

logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)

updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher

CHANNEL_ID = -

class TelegramChannelHandler(logging.Handler):
    def __init__(self, channel_id):
        super().__init__()
        self.channel_id = channel_id

    def emit(self, record):
        log_entry = self.format(record)
        try:
            updater.bot.send_message(chat_id=self.channel_id, text=log_entry)
        except Exception as e:
            logging.error(f"Failed to send message to channel: {e}")

telegram_handler = TelegramChannelHandler(CHANNEL_ID)
logging.getLogger().addHandler(telegram_handler)

And twice a day I get the following errors:

Failed to send message to channel: maximum recursion depth exceeded while calling a Python object

Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by ‘NewConnectionError(‘<telegram.vendor.ptb_urllib3.urllib3.connection.VerifiedHTTPSConnection object at >: Failed to establish a new connection: [Errno 111] Connection refused’)’: /TOKEN/sendMessage

What causes the error and how to deal with it?

Leave a Comment