avatarRonny Fahrudin

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2347

Abstract

or integrating Python and Telegram bot.</li><li>Pytube: This module is for downloading YouTube Videos.</li><li>Pydub: This module is for playing, splitting, merging, and editing our WAV audio file format.</li></ul><p id="2759">here is the code for installing those libraries:</p><div id="e7e1"><pre>pip install python-telegram-bot==<span class="hljs-number">13.7</span> pip install pydub pip install pytube</pre></div><h2 id="be54">4. Code for telegram bot YouTube downloader to mp3</h2><p id="1723">Here is the script to make a bot downloader mp3 from YouTube. follow this code:</p><div id="ee39"><pre><span class="hljs-keyword">import</span> os <span class="hljs-keyword">import</span> logging <span class="hljs-keyword">from</span> telegram <span class="hljs-keyword">import</span> Update <span class="hljs-keyword">from</span> telegram.ext <span class="hljs-keyword">import</span> Updater, CommandHandler, MessageHandler, Filters, CallbackContext <span class="hljs-keyword">from</span> pytube <span class="hljs-keyword">import</span> YouTube <span class="hljs-keyword">from</span> moviepy.editor <span class="hljs-keyword">import</span> VideoFileClip

<span class="hljs-comment"># Set up logging</span> logging.basicConfig(<span class="hljs-built_in">format</span>=<span class="hljs-string">'%(asctime)s - %(name)s - %(levelname)s - %(message)s'</span>, level=logging.INFO)

<span class="hljs-comment"># Your Telegram Bot Token</span> TOKEN=<span class="hljs-string">''</span>

<span class="hljs-comment"># Function to handle the /start command</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">update: Update, context: CallbackContext</span>): update.message.reply_text(<span class="hljs-string">"Welcome to the YouTube to MP3 downloader bot! Send me a YouTube link, and I'll convert it to MP3 for you."</span>)

<span class="hljs-comment"># Function to handle YouTube links and convert to MP3</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">convert_to_mp3</span>(<span class="hljs-params">update: Update, context: CallbackContext</span>): url = update.message.text <span class="hljs-keyword">try</span>: yt = YouTube(url) stream = yt.streams.<span class="hljs-built_in">filter</span>(only_audio=<span class="hljs

Options

-literal">True</span>).first()

    <span class="hljs-comment"># Download the video as MP4</span>
    mp4_file = stream.download(output_path=<span class="hljs-string">'downloads'</span>)

    <span class="hljs-comment"># Convert MP4 to MP3 using moviepy</span>
    video = VideoFileClip(mp4_file)
    audio = video.audio
    mp3_file = <span class="hljs-string">'downloads/output.mp3'</span>
    audio.write_audiofile(mp3_file)

    <span class="hljs-comment"># Send the MP3 file to the user</span>
    context.bot.send_audio(update.message.chat_id, audio=<span class="hljs-built_in">open</span>(mp3_file, <span class="hljs-string">'rb'</span>))

    <span class="hljs-comment"># Remove the downloaded files</span>
    os.remove(mp4_file)
    os.remove(mp3_file)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
    update.message.reply_text(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{<span class="hljs-built_in">str</span>(e)}</span>"</span>)

<span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>(): updater = Updater(token=TOKEN, use_context=<span class="hljs-literal">True</span>) dispatcher = updater.dispatcher

<span class="hljs-comment"># Command handlers</span>
dispatcher.add_handler(CommandHandler(<span class="hljs-string">"start"</span>, start))

<span class="hljs-comment"># Message handler for YouTube links</span>
dispatcher.add_handler(MessageHandler(Filters.regex(<span class="hljs-string">r'^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$'</span>), convert_to_mp3))

updater.start_polling()
updater.idle()

<span class="hljs-keyword">if</span> name == <span class="hljs-string">'main'</span>: main()</pre></div><h2 id="5c1b">5. Run Python code and start your telegram bot</h2><p id="acba">If you have done follow that script. Next, you can run your Python script. Then open the telegram bot. Then the result will be like this:</p><figure id="d85c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*gsbqdfYaVPTJBffqdlcAZw.jpeg"><figcaption></figcaption></figure><p id="a009">Now, You can download YouTube videos into MP3 only.</p><p id="a02e">Thanks. Let me know if you have a problem…</p></article></body>

Making a Telegram Bot to Download MP3 from Youtube

Step by step creating telegram bot

Photo by Lana Codes on Unsplash

Here are the outlines of steps to make a telegram bot for downloading MP3s from YouTube videos.

  1. Make a new bot from BotFather on Telegram
  2. Set up Python Environment
  3. Install Required Libraries
  4. Code the Telegram Bot
  5. Run Bot

These are the details of each step.

1. Make a new bot from BotFather on Telegram

First, you have to go to Telegram and search @BotFather. Then make a new bot with the command “/newbot”. Then follow the steps in the picture below.

Bot Father result

Next, our bot name was registered into @FatherBot. We have HTTP API to insert our program. Here, we are inserting our program through Python. But, We have to make a new Python environment.

2. Set up Python Environment

To set up a Python environment you can follow this article.

3. Install Requirement Library

The libraries that we need are:

  • Python-telegram-bot version 13.7: This module is for integrating Python and Telegram bot.
  • Pytube: This module is for downloading YouTube Videos.
  • Pydub: This module is for playing, splitting, merging, and editing our WAV audio file format.

here is the code for installing those libraries:

pip install python-telegram-bot==13.7
pip install pydub
pip install pytube

4. Code for telegram bot YouTube downloader to mp3

Here is the script to make a bot downloader mp3 from YouTube. follow this code:

import os
import logging
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from pytube import YouTube
from moviepy.editor import VideoFileClip

# Set up logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

# Your Telegram Bot Token
TOKEN=''

# Function to handle the /start command
def start(update: Update, context: CallbackContext):
    update.message.reply_text("Welcome to the YouTube to MP3 downloader bot! Send me a YouTube link, and I'll convert it to MP3 for you.")

# Function to handle YouTube links and convert to MP3
def convert_to_mp3(update: Update, context: CallbackContext):
    url = update.message.text
    try:
        yt = YouTube(url)
        stream = yt.streams.filter(only_audio=True).first()

        # Download the video as MP4
        mp4_file = stream.download(output_path='downloads')

        # Convert MP4 to MP3 using moviepy
        video = VideoFileClip(mp4_file)
        audio = video.audio
        mp3_file = 'downloads/output.mp3'
        audio.write_audiofile(mp3_file)

        # Send the MP3 file to the user
        context.bot.send_audio(update.message.chat_id, audio=open(mp3_file, 'rb'))

        # Remove the downloaded files
        os.remove(mp4_file)
        os.remove(mp3_file)
    except Exception as e:
        update.message.reply_text(f"An error occurred: {str(e)}")

def main():
    updater = Updater(token=TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    # Command handlers
    dispatcher.add_handler(CommandHandler("start", start))

    # Message handler for YouTube links
    dispatcher.add_handler(MessageHandler(Filters.regex(r'^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$'), convert_to_mp3))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

5. Run Python code and start your telegram bot

If you have done follow that script. Next, you can run your Python script. Then open the telegram bot. Then the result will be like this:

Now, You can download YouTube videos into MP3 only.

Thanks. Let me know if you have a problem…

Python
Telegram
Programming
Engineering
Data Science
Recommended from ReadMedium