Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
8.3 kB
4
Indexable
Never
import os
import re
import time
import urllib.parse
import urllib.request
import bs4
import requests
import discord
import youtube_dl
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()
bot = commands.Bot(command_prefix='!')

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





class MyView(discord.ui.View):
    def __init__(self, query: str):
        self.ctx = ctx
        super(MyView, self).__init__()

        query_string = urllib.parse.urlencode({
            'search_query': query
        })
        htm_content = urllib.request.urlopen('https://www.youtube.com/results?' + query_string)
        global search_results
        search_results = re.findall(r"watch\?v=(\S{11})", htm_content.read().decode())

        req = requests.get("https://www.youtube.com/watch?v=" + search_results[0])
        req2 = requests.get("https://www.youtube.com/watch?v=" + search_results[1])
        req3 = requests.get("https://www.youtube.com/watch?v=" + search_results[2])
        req4 = requests.get("https://www.youtube.com/watch?v=" + search_results[3])
        req5 = requests.get("https://www.youtube.com/watch?v=" + search_results[4])
        soup = bs4.BeautifulSoup(req.text, 'html.parser')
        soup1 = bs4.BeautifulSoup(req2.text, 'html.parser')
        soup2 = bs4.BeautifulSoup(req3.text, 'html.parser')
        soup3 = bs4.BeautifulSoup(req4.text, 'html.parser')
        soup4 = bs4.BeautifulSoup(req5.text, 'html.parser')
        soupText = soup.get_text()
        soupText1 = soup1.get_text()
        soupText2 = soup2.get_text()
        soupText3 = soup3.get_text()
        soupText4 = soup4.get_text()
        remove = re.compile(r'- YouTube.*')
        title = remove.sub("", soupText)
        title1 = remove.sub("", soupText1)
        title2 = remove.sub("", soupText2)
        title3 = remove.sub("", soupText3)
        title4 = remove.sub("", soupText4)
        titles = [[title], [title1], [title2], [title3], [title4]]
        titles_str = str(titles)
        titles_str = titles_str.strip("[]")
        search_list = discord.Embed(
            title="Top 5 results for: " + query + "(React with the number assigned to the song below)",
            description="1:" + title + "\n" +
                        "2:" + title1 + "\n" +
                        "3:" + title2 + "\n" +
                        "4:" + title3 + "\n" +
                        "5:" + title4 + "\n"

        )

    @discord.ui.button(style=discord.ButtonStyle.green, emoji='1️⃣')
    async def button_callback(self, button, interaction):
        voice = discord.utils.get(discord.Bot.voice_clients, guild=interaction.guild)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download(search_results[0])
        for file in os.listdir("/"):
            if file.endswith(".mp3"):
                os.rename(file, "search_result.mp3")
        voice.play(discord.FFmpegPCMAudio('search_result.mp3'))
        await interaction.response.send_message('Downloading, Thanks for tuning in!')
        return

    @discord.ui.button(style=discord.ButtonStyle.green, emoji='2️⃣')
    async def button_callback_1(self, button, interaction):
        voice = discord.utils.get(discord.Bot.voice_clients, guild=ctx.guild)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download(search_results[1])
        for file in os.listdir("/"):
            if file.endswith(".mp3"):
                os.rename(file, "search_result.mp3")
        voice.play(discord.FFmpegPCMAudio('search_result.mp3'))
        await interaction.response.send_message('Downloading, Thanks for tuning in!')
        return

    @discord.ui.button(style=discord.ButtonStyle.green, emoji='3️⃣')
    async def button_callback_2(self, button, interaction):
        voice = discord.utils.get(discord.Bot.voice_clients, guild=interaction.guild)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download(search_results[2])
        for file in os.listdir("/"):
            if file.endswith(".mp3"):
                os.rename(file, "search_result.mp3")
        voice.play(discord.FFmpegPCMAudio('search_result.mp3'))
        await interaction.response.send_message('Downloading, Thanks for tuning in!')
        return

    @discord.ui.button(style=discord.ButtonStyle.green, emoji='4️⃣')
    async def button_callback_3(self, button, interaction):
        voice = discord.utils.get(discord.Bot.voice_clients, guild=interaction.guild)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download(search_results[3])
        for file in os.listdir("/"):
            if file.endswith(".mp3"):
                os.rename(file, "search_result.mp3")
        voice.play(discord.FFmpegPCMAudio('search_result.mp3'))
        await interaction.response.send_message('Downloading, Thanks for tuning in!')
        return

    @discord.ui.button(style=discord.ButtonStyle.green, emoji='5️⃣')
    async def button_callback_4(self, button, interaction):
        voice = discord.utils.get(discord.Bot.voice_clients, guild=interaction.guild)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download(search_results[4])
        for file in os.listdir("/"):
            if file.endswith(".mp3"):
                os.rename(file, "search_result.mp3")
        voice.play(discord.FFmpegPCMAudio('search_result.mp3'))
        await interaction.response.send_message('Downloading, Thanks for tuning in!')
        return


class MusicCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def search(self, ctx, *, query: str):
        connected = ctx.author.voice
        song_there = os.path.isfile("search_result.mp3")
        try:
            if song_there:
                os.remove("search_result.mp3")
        except PermissionError:
            await ctx.send("Şimdi Çalan şarkının bitmesini bekleyin. Yada '!stop' komutunu kullanın.")
            return
        try:
            await connected.channel.connect()
        except:
            pass
        query_string = urllib.parse.urlencode({
            'search_query': query
        })
        htm_content = urllib.request.urlopen('https://www.youtube.com/results?' + query_string)
        global search_results
        search_results = re.findall(r"watch\?v=(\S{11})", htm_content.read().decode())

        req = requests.get("https://www.youtube.com/watch?v=" + search_results[0])
        req2 = requests.get("https://www.youtube.com/watch?v=" + search_results[1])
        req3 = requests.get("https://www.youtube.com/watch?v=" + search_results[2])
        req4 = requests.get("https://www.youtube.com/watch?v=" + search_results[3])
        req5 = requests.get("https://www.youtube.com/watch?v=" + search_results[4])
        soup = bs4.BeautifulSoup(req.text, 'html.parser')
        soup1 = bs4.BeautifulSoup(req2.text, 'html.parser')
        soup2 = bs4.BeautifulSoup(req3.text, 'html.parser')
        soup3 = bs4.BeautifulSoup(req4.text, 'html.parser')
        soup4 = bs4.BeautifulSoup(req5.text, 'html.parser')
        soupText = soup.get_text()
        soupText1 = soup1.get_text()
        soupText2 = soup2.get_text()
        soupText3 = soup3.get_text()
        soupText4 = soup4.get_text()
        remove = re.compile(r'- YouTube.*')
        title = remove.sub("", soupText)
        title1 = remove.sub("", soupText1)
        title2 = remove.sub("", soupText2)
        title3 = remove.sub("", soupText3)
        title4 = remove.sub("", soupText4)
        titles = [[title], [title1], [title2], [title3], [title4]]
        titles_str = str(titles)
        titles_str = titles_str.strip("[]")
        search_list = discord.Embed(
            title="Top 5 results for: " + query + "(React with the number assigned to the song below)",
            description="1:" + title + "\n" +
                        "2:" + title1 + "\n" +
                        "3:" + title2 + "\n" +
                        "4:" + title3 + "\n" +
                        "5:" + title4 + "\n"

        )
        time.sleep(10)

        await ctx.send(embed=search_list, view=MyView())