import discord
from discord.ext import commands
import os
import asyncio
import yt_dlp
from dotenv import load_dotenv
import urllib.parse, urllib.request, re
import nacl

def run_bot():
    load_dotenv()
    TOKEN = os.getenv('discord_token')
    intents= discord.Intents.default()
    intents.message_content = True
    client = commands.Bot(command_prefix=".",intents=intents)

    queues = {}
    voice_clients = {}
    youtube_base_url = 'https://www.youtube.com/'
    youtube_results_url = youtube_base_url + 'results?'
    youtube_watch_url= youtube_base_url + 'watch?v='
    yt_dl_options = {"format": "bestaudio/best"}
    ytdl = yt_dlp.YoutubeDL(yt_dl_options)

    ffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn -filter:a "volume=0.5"'}

    @client.event
    async def on_ready():
        print("f{client.user} E pe beat.")

    async def play_next(ctx):
        if(queues[ctx.guid.id] != []):
            link = queues[ctx.guild.id].pop(0)
            await play(ctx, link=link)

    @client.command(name="play")
    async def play(ctx, *, link):
        try:
            voice_client = await ctx.author.voice.channel.connect()
            voice_clients[voice_client.guild.id] = voice_client
        except Exception as e:
            print(e)
        try:
            if youtube_base_url not in link:
                query_string = urllib.parseurlencode({
                    'search_query':link
                })

                content = urllib.request.urlopen(
                    youtube_results_url + query_string
                )
                search_results = re.findall(r'/watch\?v=(.{11})')
                link=youtube_watch_url + search_results[0]
            loop = asyncio.get_event_loop()
            data = await loop.run_in_executor(None, lambda: ytdl.extract_info(link, download = False))
            song = data['url']
            player = discord.FFmpegOpusAudio(song, **ffmpeg_options)
            voice_clients[ctx.guild.id].play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next(ctx), client.loop))
        except Exception as e:
            print(e)
        try:
             if ctx.guild.id not in queues:
                queues[ctx.guild.id] = []
                queues[ctx.guild.id].append(link)
                await ctx.send("Adaugat la cur!")
        except Exception as e:
            print(e)
            

    @client.command(name="clear")
    async def clear_queue(ctx):
        if ctx.guild.id in queues:
            queues[ctx.guild.id].clear()
            await ctx.send("A plecat toata lumea de la coada la gogosi!")
        else:
            await ctx.send("N-am boss la ce sa dau clear")

    @client.command(name="pause")
    async def pause(ctx):
        try:
            voice_clients[ctx.ui.id].pause()
            await ctx.send("S-a pus pauza la distractie!")
        except Exception as e:
            print(e) 

    @client.command(name="resume")
    async def resume(ctx):
        try:
            voice_clients[ctx.guild.id].resume()
            await ctx.send("Reincepe petrecerea!")
        except Exception as e:
            print(e)

    @client.command(name="stop")
    async def stop(ctx):
        try:
            voice_clients[ctx.guild.id].stop()
            await voice_clients[ctx.guild.id].disconnect()
            del voice_clients[ctx.guild.id]
        except Exception as e:
            print(e)

    @client.command(name="skip")
    async def skip(ctx):
        if ctx.voice_client and ctx.voice_client.is_playing():
            ctx.voice_client.stop()
            await play_next(ctx)
            await ctx.send("Skip la prostia asta!")
        else:
            await ctx.send("Nu am la ce sa dau skip B0$$!")

    @client.command(name="queue")
    async def queue(ctx, *, url):
        if ctx.guild.id not in queues:
            queues[ctx.guild.id] = []
        queues[ctx.guild.id].append(url)
        await ctx.send("Adaugat la cur!")

    client.run(TOKEN)
    

improve this bot