Guest User

InputFile in InputMedia*

a guest
Jan 14th, 2026
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. import logging
  2. from contextlib import ExitStack
  3. from pathlib import Path
  4.  
  5. from telegram import InputFile, InputMediaPhoto, InputMediaVideo, Update
  6. from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
  7.  
  8. logging.basicConfig(
  9.     format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  10.     level=logging.DEBUG,
  11. )
  12.  
  13. TOKEN = "TOKEN"
  14.  
  15.  
  16. async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
  17.     if not update.effective_message:
  18.         raise RuntimeError
  19.    
  20.     image1, video1 = files = (
  21.         Path("./files/image1.jpg").resolve(),
  22.         Path("./files/video1.mp4").resolve(),
  23.     )
  24.  
  25.     for file in files:
  26.         if not file.exists():
  27.             raise RuntimeError
  28.  
  29.     image1, video1 = files
  30.  
  31.     try:
  32.         with ExitStack() as stack:
  33.             image1_input = InputFile(stack.enter_context(image1.open("rb")), filename="image1.jpg", read_file_handle=False)
  34.             video1_input = InputFile(stack.enter_context(video1.open("rb")), filename="video1.mp4", read_file_handle=False)
  35.  
  36.             media_group = [
  37.                 InputMediaPhoto(media=image1_input),
  38.                 InputMediaVideo(media=video1_input),
  39.             ]
  40.  
  41.             logging.info("Attempting to send media group...")
  42.             await update.effective_message.reply_media_group(media=media_group)
  43.  
  44.  
  45.     except Exception as exception:
  46.         logging.error("Failed to send media group: %s", exception)
  47.         await update.effective_message.reply_text(f"Caught exception: {exception}")
  48.  
  49.  
  50. if __name__ == "__main__":
  51.     application = ApplicationBuilder().token(TOKEN).build()
  52.     application.add_handler(CommandHandler("test", test_command))
  53.     logging.info("Bot is polling. Send /test in Telegram.")
  54.     application.run_polling()
  55.  
Advertisement
Add Comment
Please, Sign In to add comment