I’m working on a Telegram bot that tracks sports events and stores them in a database. The bot can respond to commands like /upcoming, /list, and /schedule when users ask for information. Right now everything works fine when people manually use commands, but I want to add automatic notifications.
My main issues:
- Automatic messaging doesn’t work - I can’t get my notification function to send messages automatically to channels or private chats
- Commands in channels - Users can use commands in groups but not in channels
- Daily reminders - I want the bot to check every morning if there’s an event today and automatically post to the channel
import sqlite3
import asyncio
from datetime import datetime
from telegram import Update
from telegram.ext import Application, CommandHandler, CallbackContext
db_connection = sqlite3.connect('sports_events.db')
cursor = db_connection.cursor()
async def fetch_today_event():
today = datetime.today().strftime("%Y-%m-%d")
cursor.execute("SELECT * FROM events WHERE date = ?", (today,))
result = cursor.fetchone()
return result
async def fetch_upcoming_event():
cursor.execute("SELECT * FROM events ORDER BY date")
all_events = cursor.fetchall()
current_date = datetime.today().strftime("%Y-%m-%d")
for event in all_events:
if event[2] >= current_date:
return event
return None
async def send_notification(update: Update, context: CallbackContext):
event = await fetch_today_event()
if event:
notification_text = f"🔔 <b>EVENT TODAY!</b> 🔔\n\n"
notification_text += f"📋 <b>{event[0]}\n⚽ {event[1]}\n📅 {event[2]}\n⏰ {event[3]}</b>"
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=notification_text,
parse_mode="HTML"
)
else:
no_event_msg = "<b>❌ NO EVENTS SCHEDULED TODAY ❌</b>"
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=no_event_msg,
parse_mode="HTML"
)
def setup_bot():
application = Application.builder().token("YOUR_BOT_TOKEN").build()
application.add_handler(CommandHandler("notify", send_notification))
application.add_handler(CommandHandler("upcoming", fetch_upcoming_event))
application.run_polling()
if __name__ == "__main__":
setup_bot()
The bot works great for manual commands but I need help making it send automatic reminders to channels and groups. How can I implement scheduled messaging that runs independently of user commands?