PyTelegramBotAPI Connection Issues - Seeking Help

Hey folks! I’m having a bit of trouble with my Telegram bot using pyTelegramBotAPI. It keeps throwing this annoying error:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forced to be aborted by the remote host', None, 10054, None))

I’ve set up a simple function to send messages, but it’s not playing nice. Here’s what I’m working with:

import chatbot_lib
import pause
import log_manager

secret_key = 'MY_SECRET_KEY'
chatbot = chatbot_lib.ChatBot(secret_key)


def broadcast_update(content):
    recipient = 'GROUP_ID'
    try:
        chatbot.broadcast(recipient, content)
    except (NetworkIssueError, ServerDownError):
        pause.wait(1)
        chatbot.broadcast(recipient, content)

The bot should send 3 updates. It might send the first one at 14:21, then another at 14:30, but when it tries to send the last one, boom! Error city. Sometimes it even fails right from the get-go.

Any ideas on how to fix this? I’m scratching my head here!

I’ve dealt with similar connection issues using PyTelegramBotAPI. One approach that’s worked well for me is implementing a connection pool. This can help manage and reuse connections more efficiently, reducing the likelihood of abrupt disconnections.

Here’s a basic example of how you might modify your code:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retries = Retry(total=5, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504])
session.mount('https://', HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=10))


def broadcast_update(content):
    recipient = 'GROUP_ID'
    try:
        response = session.post(f'https://api.telegram.org/bot{secret_key}/sendMessage', data={'chat_id': recipient, 'text': content})
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        log_manager.log_error(f'Failed to send message: {str(e)}')
        raise

This approach has helped me reduce connection errors significantly. Remember to properly close the session when you’re done using it.

I’ve encountered similar issues with PyTelegramBotAPI. One effective solution is implementing a more robust error handling mechanism. Consider wrapping your broadcast function in a decorator that handles retries with exponential backoff. This approach can significantly improve reliability:

from functools import wraps
import time
import random


def retry_with_backoff(max_retries=5, backoff_in_seconds=1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            x = 0
            while True:
                try:
                    return func(*args, **kwargs)
                except (NetworkIssueError, ServerDownError) as e:
                    if x == max_retries:
                        raise e
                    sleep = (backoff_in_seconds * 2 ** x + random.uniform(0, 1))
                    time.sleep(sleep)
                    x += 1
        return wrapper
    return decorator

@retry_with_backoff()
def broadcast_update(content):
    recipient = 'GROUP_ID'
    chatbot.broadcast(recipient, content)

This approach provides a more flexible and resilient solution to handle intermittent network issues.

hey john, sounds like a pain! have u tried adding more retries? maybe smth like this:

for _ in range(5):
try:
chatbot.broadcast(recipient, content)
break
except:
pause.wait(5)

might help with those pesky connection issues. good luck!