Hey folks, I’m having trouble with my Telegram bot. It’s supposed to send notifications to users based on their ID. The problem is when I start checking for new data and sending it, everything freezes up. Users can’t make any more requests.
I tried using threads, but now I’m getting errors. Here’s what I’m working with:
# Main bot file
import telebot
from aiogram import Bot, Dispatcher, types
import threading
import notify_service
bot = Bot(token='your_token_here')
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def begin(message: types.Message):
user_id = message.from_user.id
await message.reply(f'Your ID: {user_id}')
threading.Thread(target=notify_service.start_notifications, args=(user_id,), daemon=True).start()
# Notification service
import requests
import time
async def start_notifications(user_id):
while True:
new_data = fetch_new_data()
if new_data:
send_notification(user_id, new_data)
time.sleep(60)
def fetch_new_data():
# API call to get new data
pass
def send_notification(user_id, data):
# Send message to user
pass
When I run this, the console says the thread started, but no messages are sent. Any ideas what I’m doing wrong? Thanks!
I’ve dealt with similar challenges with my Telegram bots before. A solution that worked well was integrating a message queue system like RabbitMQ or Redis. This lets the main bot process add notification tasks quickly without blocking, while a separate worker process handles sending out notifications. Using this approach keeps the bot responsive under load. In my experience, ensuring that all parts of the code use asyncio-compatible libraries is key. Although it required some refactoring, the performance and scalability improvements were well worth the effort.
I encountered similar issues when working with Telegram bots using asynchronous frameworks. In my experience, mixing synchronous functions with asynchronous code can lead to unexpected freezing. Instead of using threads with synchronous notifications, it is more reliable to refactor the notification service to be fully asynchronous. You can replace time.sleep with asyncio.sleep, use aiohttp for API calls, and explore aiogram’s built-in scheduling capabilities for handling periodic tasks. Making these changes should help maintain responsiveness and prevent the freezing issue while offering a more robust solution for concurrent processing.
hey man, i had the same problem. try using asyncio instead of threading. replace ur time.sleep with asyncio.sleep and use aiohttp for api calls. also, make sure ur notification funcs are async too. it worked for me and my bot runs smooth now. good luck!