Telegram Bot To Download Youtube Video

Welcome all the programmers. In this article I am going to show you how to create our own Telegram bot to download Youtube video. I am keeping this article and the supporting video as simple as possible. However, If you still have any questions, feel free to comment.

The complete code is available at Google Colab as well which you can go to by following this link.

High level steps to create a Telegram bot to download Youtube Video

  1. Read Youtube URL from Telegram Group
  2. Download Video
  3. Send the video in the Telegram Group

**Read Latest Messages from Telegram**

Before we move forward, I assume that you have already create a Telegram Bot and added the bot in your Telegram Group. If you are new to Telegram Bot creation then please watch this video first.

Alright, now we are good to move on. So, let’s write our first python program which is going to read latest messages from the telegram group. Please make sure you update chat_id and token variables.

import requests

chat_id = "<your group id>"
token = "<your telegram bot token>"

base_url = "https://api.telegram.org/bot{}/getUpdates".format(token)

with open("/content/sample_data/offset.txt") as f:
  offset = f.read()

if not offset:
  offset = 1
else:
  offset = int(offset) + 1

parameters = {"offset" : offset }

resp = requests.get(base_url, data = parameters)

if len(resp.json()["result"]) > 0:
  update_id = str(resp.json()["result"][-1]["update_id"])
  with open("/content/sample_data/offset.txt", "w") as f:
    f.write(update_id)

for item in resp.json()["result"]:
  text = item["message"]["text"]
  print(text)

** Python Program To Download Youtube Video **

Here is a sample Python program to download Youtube video. You will need to install “pytube” library before running the code shown below.

from pytube import YouTube 


# Change below path to the directory where you want to store the downloaded file.
path = '/content/sample_data'

link= text

video = YouTube(link)
video = video.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()

video_saved_path = video.download(path)
print(video_saved_path)

**Send Video on Telegram**

Now we are ready to follow the last step which is to send the video on Telegram. Here is the sample code. Please make sure you change chat_id and token variable.

import requests

chat_id = "<your group id>"
token = "<your telegram bot token>"


base_url = "https://api.telegram.org/bot2007294251:AAHX3JS_k7YKoNqm05PYPYTn0Ehcpt-UgT4/sendVideo"


my_file = open(video_saved_path, "rb")

parameters = { "chat_id" : "-1001608236798" }

files = { "video" : my_file }

resp = requests.get(base_url, data = parameters, files=files)
print(resp.text)

That’s all ! Do Subscribe me on Youtube if this article helped you. Your support means a lot.

Continue reading for more Telegram Automations

Scroll to Top