Creating a media scheduling bot using python-telegram-bot v21 involves several steps, including setting up a bot with appropriate message handlers, creating functions to process incoming media, and scheduling messages based on an interval. We'll also use SQLite to store the last scheduled time for each chat. Below is an example implementation:
import logging
import sqlite3
from datetime import datetime, timedelta
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# Database setup
def setup_database():
conn = sqlite3.connect('schedule.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS schedules (
chat_id INTEGER PRIMARY KEY,
last_scheduled_time TEXT
)''')
conn.commit()
conn.close()
def get_last_scheduled_time(chat_id):
conn = sqlite3.connect('schedule.db')
c = conn.cursor()
c.execute('SELECT last_scheduled_time FROM schedules WHERE chat_id = ?', (chat_id,))
row = c.fetchone()
conn.close()
if row:
return datetime.fromisoformat(row[0])
return None
def update_last_scheduled_time(chat_id, time):
conn = sqlite3.connect('schedule.db')
c = conn.cursor()
c.execute('REPLACE INTO schedules (chat_id, last_scheduled_time) VALUES (?, ?)', (chat_id, time.isoformat()))
conn.commit()
conn.close()
# Configuration
CHANNEL_GROUP_ID = 'YOUR_CHANNEL_OR_GROUP_ID'
INTERVAL = timedelta(minutes=5) # Adjust your interval here
# Bot functionality
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello! Send me photos or videos to schedule!")
async def handle_media(update: Update, context: ContextTypes.DEFAULT_TYPE):
media_message = update.message
chat_id = CHANNEL_GROUP_ID
# Get the last scheduled time
last_scheduled_time = get_last_scheduled_time(chat_id)
now = datetime.now()
if last_scheduled_time and last_scheduled_time > now:
next_schedule_time = last_scheduled_time + INTERVAL
else:
next_schedule_time = now + INTERVAL
# Calculate schedule delay
delay = (next_schedule_time - now).total_seconds()
# Schedule the media to be sent
context.job_queue.run_once(send_media, delay, context=(chat_id, media_message))
# Update the last scheduled time
update_last_scheduled_time(chat_id, next_schedule_time)
await update.message.reply_text("Media scheduled!")
async def send_media(context: ContextTypes.DEFAULT_TYPE):
job_context = context.job.context
chat_id, media_message = job_context
# Re-send media (either photo or video)
if media_message.photo:
file_id = media_message.photo[-1].file_id
await context.bot.send_photo(chat_id=chat_id, photo=file_id)
elif media_message.video:
file_id = media_message.video.file_id
await context.bot.send_video(chat_id=chat_id, video=file_id)
# Main function to run the bot
async def main():
setup_database() # Setup SQLite database
# Create Application
application = ApplicationBuilder().token("YOUR_BOT_TOKEN").build()
# Handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.PHOTO | filters.VIDEO, handle_media))
# Run the bot
await application.run_polling()
# Entry point
if __name__ == '__main__':
import asyncio
asyncio.run(main())
Key Points:
- Database Setup: A SQLite database is used to track the last scheduled time for any given chat using its
chat_id.
- Media Handling: Filters are applied to identify photo and video messages to schedule them.
- Scheduling Logic: It computes when to schedule the next media based on the last scheduled time and a specified interval.
- Bot Token: Replace
"YOUR_BOT_TOKEN" and "YOUR_CHANNEL_OR_GROUP_ID" with your actual bot token and channel/group ID.
- Execution: This script continuously runs, processing new media messages and scheduling them appropriately based on delays with the
JobQueue.
Ensure you have the required library installed if not already:
pip install python-telegram-bot==21.0