Upload local file to Telegram channel

Question:

I have a goal to do python script for checking new videos at yt channel then download and upload as audio to tg channel.
I’ve done first part with checking/downloading/converting (youtube_dl library) and don’t see how to do upload part. (there are telegram-upload, python-telegram-bot, telethon libraries but i don’t get which one and how I can apply for uploading files to channel)

# importing module
import youtube_dl
import urllib.request
import re

html = urllib.request.urlopen("https://www.youtube.com/c/peterschiff/videos")

#all videos ids from yt page
video_ids = re.findall(r"watch?v=(S{11})", html.read().decode())

  
ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }]
}

#write all videos ids to local file 
txt_file = open('outfile.txt', 'r')
file_content = txt_file.read()
content_list = file_content.split()
txt_file.close()


x = video_ids
y = content_list

#get only new videos by comparing with local file
result = set(x) - set(y)

with open('outfile.txt', 'a') as outfile:
    outfile.write('n'.join(result))

#download new videos and convert to audio
def dwl_vid():
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([zxt])
  

for item in result:
    video_one = 'https://www.youtube.com/watch?v=' + item
    zxt = video_one.strip()
    dwl_vid()

Asked By: Sergio Iliev

||

Answers:

python-telegram-bot is a library that provides a wrapper for the Telegram Bot API. telethon and telegram-upload instead use the Telegram API (also called MTProto), which controls user (and also Bot accounts).

If you want to use a bot to send files to the channel, you’ll have to create a bot and make it an admin in that channel. Then you can use the api methods sendDocument or sendAudio to send the file. For that you can either manually make requests to the bot api (e.g. via the urllib or other libraries like requests or httpx) or use a library like python-telegram-bot, pyTelegramBotAPI, aiogram, botogram etc that provide wrappers for the bot api. You can also use user-bot libraries like telethon or pyrogram for that, as they can be used for bots as well.

If you don’t want to use a bot, you’ll have to use a user-bot, i.e. the Telegram API such that the audio is sent by your personal account. For that, you can use libraries like telethon, telegram-upload or pyrogram.

Answered By: CallMeStag

If you choose to use Telethon, be sure to read the First Steps of the documentation to get you started, and then use client.send_file:

await client.send_file(chat, '/my/videos/video.mp4', caption="Test video")

Note that telethon uses asyncio, so be wary if you use threading elsewhere.

Answered By: Lonami