Certainly! To create a bot using python-telegram-bot version 21 that schedules media content to be sent at specified intervals, you can follow the steps below.
First, make sure you have the python-telegram-bot library installed:
pip install python-telegram-bot==21.0
Below is a Python script that creates a Telegram bot to schedule and send media files:
import logging
from telegram import Update, InputFile
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
from datetime import datetime, timedelta
import asyncio
# Set up logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
# List to hold scheduled media content
scheduled_media = []
# Define a command that starts the bot
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('Hi! Send me media to schedule it.')
# Define a message handler for media content (photos/videos)
async def media_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Get the file id, based on media type
media_file = None
if update.message.photo:
media_file = update.message.photo[-1]
elif update.message.video:
media_file = update.message.video
if media_file:
file_id = media_file.file_id
send_at_time = datetime.now() + timedelta(seconds=context.bot_data['interval'])
# Add to scheduled media list
scheduled_media.append((file_id, send_at_time))
await update.message.reply_text(f"Media scheduled to be sent at {send_at_time}")
# Define a function that sends scheduled media
async def send_scheduled_media(context: ContextTypes.DEFAULT_TYPE):
chat_id = context.bot_data['channel_id']
current_time = datetime.now()
for media in scheduled_media[:]:
file_id, send_time = media
if current_time >= send_time:
# Use InputFile to send the media
input_file = InputFile(file_id)
try:
await context.bot.send_document(chat_id=chat_id, document=input_file)
scheduled_media.remove(media)
except Exception as e:
logger.error(f"Failed to send media: {e}")
# Entry point for the bot
async def main():
token = 'YOUR_BOT_TOKEN' # Replace with your bot's token
channel_id = 'YOUR_CHANNEL_ID' # Replace with your channel or group ID
send_interval = 10 # Time interval in seconds
# Create the Application and pass it your bot's token.
application = ApplicationBuilder().token(token).build()
# Save channel_id and send_interval in bot data
application.bot_data['channel_id'] = channel_id
application.bot_data['interval'] = send_interval
# Register handlers
application.add_handler(CommandHandler('start', start))
application.add_handler(MessageHandler(filters.MEDIA, media_handler))
# Schedule task to run every second to check and send scheduled media
application.job_queue.run_repeating(send_scheduled_media, interval=1, first=1)
# Run the bot
await application.run_polling()
# Execute the bot
asyncio.run(main())
Explanation
-
Initialization:
- The
ApplicationBuilder is used to create the bot application, with the bot token provided.
-
Handlers:
- A
/start command handler (start) welcomes users and explains the bot.
- A
MessageHandler listens for media content (photos/videos) and schedules it for sending via the scheduled_media list.
-
Scheduling:
- The
send_scheduled_media function sends media from scheduled_media once its scheduled time has arrived.
job_queue.run_repeating sets this function to run every second to check if any media need to be sent.
-
Parameters:
channel_id: The ID of the channel or group where media will be sent.
send_interval: The interval in seconds after which media should be sent.
Note:
- Replace
'YOUR_BOT_TOKEN' and 'YOUR_CHANNEL_ID' with your bot's API token and target channel/group ID respectively.
- You may need to adjust file handling (
InputFile) based on your specific requirements or limitations of Telegram.
- Make sure your bot has the necessary permissions to post messages/photos/videos in the channel/group.