I’m running a Telegram bot that handles user commands through a background job processor. The bot works fine most of the time but randomly stops responding and I have to restart the background worker manually.
The weird thing is there are no error messages in the logs so I’m not sure what’s causing this issue. Has anyone experienced similar problems with Telegram bots going offline unexpectedly?
Here’s my worker class setup:
require 'telegram/bot'
class BotListenerWorker
include Sidekiq::Worker
sidekiq_options retry: 3, queue: :bots
API_TOKEN = Rails.application.credentials.telegram_api_key
def perform
Rails.logger.info 'Bot worker started'
Telegram::Bot::Client.run(API_TOKEN) do |client|
client.listen do |msg|
if msg.from.username.present?
# process user commands here
end
end
end
end
end
Any suggestions on where to look for the root cause or how to make the connection more stable?
This issue often arises from having webhook conflicts or multiple polling sessions active simultaneously. It’s crucial to ensure that there are no webhooks set up for your bot token; even those that are disabled can interfere with long polling. Utilize getWebhookInfo to review your current webhooks, and then employ deleteWebhook to clear any existing setups before initiating your polling worker. Additionally, running multiple bot instances at once can cause Telegram to reject connections, so make sure to implement a unique identifier or locking mechanism to restrict polling to a single worker at a time. Finally, avoid overwhelming Telegram with reconnection attempts; implementing an exponential backoff strategy will help you stay within their rate limits.
I faced a similar disconnect issue with my Telegram bot. It seems like the long polling can be quite sensitive to network fluctuations. One solution I found effective was implementing a mechanism to check the connectivity regularly. Specifically, I wrapped my client.listen within a retry loop and added a timeout. I also included a periodic check to see if the bot is still responsive by querying getMe. If the connection fails, I initiate a reconnect automatically. Additionally, it’s important to configure your Sidekiq worker timeout to allow the listening process to run continuously. Without this setup, the bot would unexpectedly drop connections with no error messages logged.
check if your heroku dyno’s going to sleep - that’s what bit me. also, telegram’s api has connection limits, so throw some error handling around that client.run block even if you’re not seeing errors yet.