DEV Community

Vlyth_r
Vlyth_r

Posted on • Updated on

Video Downloader Bot for Telegram - Tutorial

A step-by-step tutorial on how to create a chatbot for Telegram that can download videos from websites like YouTube.

We'll be using Python and a popular library called python-telegram-bot to build the chatbot. Let's get started!

Step 1: Set Up a Telegram Bot

  • Open Telegram and search for the "BotFather" bot.
  • Start a chat with the BotFather and follow the instructions to create a new bot.
  • Once your bot is created, you will receive an API token. Save this token as you'll need it later.

Step 2: Set Up Your Development Environment

  • Install Python on your computer if you haven't already. You can download it from the official Python website (python.org).
  • Choose a code editor for Python. Some popular options are Visual Studio Code, PyCharm, or Sublime Text. Install your preferred editor.

Step 3: Install the Required Libraries

  • Open a terminal or command prompt and run the following command to install the python-telegram-bot library:
 pip install python-telegram-bot youtube_dl
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a New Python Script

  • Open your code editor and create a new Python script. You can name it telegram_video_downloader.py or choose any name you prefer.

Step 5: Import the Required Libraries

  • Add the following lines at the beginning of your Python script to import the necessary libraries:
  import logging
  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
  import youtube_dl
Enter fullscreen mode Exit fullscreen mode

Step 6: Set Up Logging

  • Add the following lines of code to enable logging in your script. This will help you debug any issues that may occur:
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                      level=logging.INFO)
  logger = logging.getLogger(__name__)
Enter fullscreen mode Exit fullscreen mode

Step 7: Define a Function to Handle the /start Command

  • Add the following code to define a function that will handle the /start command when it is received by the bot:
  def start(update, context):
      context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm a video downloader bot. Just send me the URL of the video you want to download.")
Enter fullscreen mode Exit fullscreen mode

Step 8: Define a Function to Handle Video Downloads

  • Add the following code to define a function that will handle the video download functionality:
def download_video(update, context):
    url = update.message.text

    ydl_opts = {
        'outtmpl': '%(title)s.%(ext)s',  # Output file name template
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',  
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(url, download=False)
            video_title = info['title']
            video_url = info['url']
            ydl.download([url])
            context.bot.send_message(chat_id=update.effective_chat.id, text="Video downloaded successfully!")
                        context.bot.send_video(chat_id=update.effective_chat.id, video=video_url, caption=video_title)
        except Exception as e:
            logger.error(f"Error downloading video: {e}")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to download the video.")
Enter fullscreen mode Exit fullscreen mode

Step 9: Set Up the Main Function

  • Add the following code to set up the main function that will run the bot:
  def main():
      updater = Updater(token='YOUR_API_TOKEN', use_context=True)

      dispatcher = updater.dispatcher

      dispatcher.add_handler(CommandHandler("start", start))
      dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, download_video))

      updater.start_polling()

      updater.idle()
Enter fullscreen mode Exit fullscreen mode

Step 10: Run the Bot

  • Replace 'YOUR_API_TOKEN' in the main() function with the API token you received from the BotFather in Step 1.
  • Add the following code at the bottom of your script to run the bot:
  if __name__ == '__main__':
      main()
Enter fullscreen mode Exit fullscreen mode

Step 11: Test Your Bot

  • Save the Python script and run it from your terminal or command prompt using the command:
  python telegram_video_downloader.py
Enter fullscreen mode Exit fullscreen mode
  • Open Telegram and search for the name of your bot.
  • Start a chat with your bot, and send it a YouTube video URL.
  • The bot should respond with a message indicating that the video has been downloaded successfully.

Your bot's full code should look like this:

import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import youtube_dl

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm a video downloader bot. Just send me the URL of the video you want to download.")

def download_video(update, context):
    url = update.message.text

    ydl_opts = {
        'outtmpl': '%(title)s.%(ext)s',
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(url, download=False)
            video_title = info['title']
            video_url = info['url']
            ydl.download([url])
            context.bot.send_message(chat_id=update.effective_chat.id, text="Video downloaded successfully!")
            context.bot.send_video(chat_id=update.effective_chat.id, video=video_url, caption=video_title)
        except Exception as e:
            logger.error(f"Error downloading video: {e}")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to download the video.")

def main():
    updater = Updater(token='YOUR_API_TOKEN', use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, download_video))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Enter fullscreen mode Exit fullscreen mode

Remember to replace 'YOUR_API_TOKEN' in the main() function with the API token you received from the BotFather.

Top comments (1)

Collapse
 
gabriel01 profile image
Iovany

First of all, thanks for the information.

I have a question; The code works for any video site, for example ok.ru?.