Spaces:
Running
Running
revert
Browse filesFiles changed (3)
- .gitignore+2-1
- app.py+45-101
- requirements.txt+3-4
1 unmodified line23451 unmodified lineassets/.cachetest*cookies.txt1 unmodified line234561 unmodified lineassets/.cachetest*cookies.txt.gradio
1234567891011121314151617181920212223242526272829303132333435363738394041422 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495963 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351 unmodified line137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import discordfrom discord.ext import commandsimport gradio as grfrom dotenv import load_dotenvimport osimport threadingimport asynciofrom huggingface_hub import hf_hub_downloadimport yt_dlp# Load environment variablesload_dotenv()if os.path.exists('cookies.txt') is False:hf_hub_download("not-lain/secrets", "cookies.txt", repo_type="dataset",local_dir=".")# Check if cookies.txt exists# if not os.path.exists('cookies.txt'):# txt = os.getenv('COOKIES')# with open('cookies.txt', 'w') as f:# f.write(txt)# Bot configurationintents = discord.Intents.default()intents.message_content = Truebot = commands.Bot(command_prefix='!', intents=intents)class MusicBot:def __init__(self):self.is_playing = Falseself.voice_client = Noneself.queue = []self.ydl_opts = {'format': 'bestaudio/best','cookiefile': 'cookies.txt','quiet': True,'no_warnings': True,'extract_flat': 'in_playlist'}self.currently_playing = Noneasync def join_voice(self, ctx):if ctx.author.voice:2 unmodified linesself.voice_client = await channel.connect()else:await self.voice_client.move_to(channel)return Truereturn Falseasync def play_next(self, ctx):if self.queue and not self.is_playing:self.is_playing = Trueurl = self.queue.pop(0)try:with yt_dlp.YoutubeDL(self.ydl_opts) as ydl:info = ydl.extract_info(url, download=False)audio_url = info['url']title = info.get('title', 'Unknown title')self.currently_playing = title# Create FFmpeg audio sourceffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn -bufsize 64k'}audio_source = discord.FFmpegPCMAudio(audio_url, **ffmpeg_options)def after_playing(error):self.is_playing = Falseself.currently_playing = Noneif error:print(f"Playback error: {error}")asyncio.run_coroutine_threadsafe(self.play_next(ctx), bot.loop)# Apply volume transformation and playtransformed_source = discord.PCMVolumeTransformer(audio_source, volume=0.5)self.voice_client.play(transformed_source, after=after_playing)await ctx.send(f"Now playing: {title}")except Exception as e:print(f"Error playing URL {url}: {e}")self.is_playing = Falseawait ctx.send(f"Error playing the song: {str(e)}")await self.play_next(ctx)music_bot = MusicBot()@bot.eventasync def on_ready():print(f'Bot is ready! Logged in as {bot.user}')print("Syncing commands...")try:await bot.tree.sync(guild=None) # Set to None for global sync3 unmodified linesexcept Exception as e:print(f"An error occurred while syncing commands: {e}")@bot.tree.command(name="play", description="Play a YouTube URL")async def play(interaction: discord.Interaction, url: str):await interaction.response.defer()ctx = await commands.Context.from_interaction(interaction)if not await music_bot.join_voice(ctx):await interaction.followup.send("You need to be in a voice channel!")returntry:with yt_dlp.YoutubeDL(music_bot.ydl_opts) as ydl:info = ydl.extract_info(url, download=False)title = info.get('title', 'Unknown title')music_bot.queue.append(url)await interaction.followup.send(f'Added to queue: {title}')if not music_bot.is_playing:await music_bot.play_next(ctx)except Exception as e:await interaction.followup.send(f'Error: {str(e)}')@bot.tree.command(name="skip", description="Skip the current song")async def skip(interaction: discord.Interaction):if music_bot.voice_client:music_bot.voice_client.stop()await interaction.response.send_message('Skipped current song!')else:await interaction.response.send_message('No song is currently playing!')@bot.tree.command(name="leave", description="Disconnect bot from voice channel")async def leave(interaction: discord.Interaction):if music_bot.voice_client:1 unmodified linemusic_bot.voice_client = Nonemusic_bot.queue = []music_bot.is_playing = Falseawait interaction.response.send_message('Bot disconnected!')else:await interaction.response.send_message('Bot is not in a voice channel!')@bot.tree.command(name="queue", description="Show the current music queue")async def queue(interaction: discord.Interaction):await interaction.response.defer()if not music_bot.is_playing and not music_bot.queue:await interaction.followup.send("No songs in the queue!")returnqueue_list = []if music_bot.currently_playing:queue_list.append(f"Currently playing: {music_bot.currently_playing}")if music_bot.queue:with yt_dlp.YoutubeDL(music_bot.ydl_opts) as ydl:for i, url in enumerate(music_bot.queue, 1):try:info = ydl.extract_info(url, download=False)title = info.get('title', 'Unknown title')queue_list.append(f"{i}. {title}")except:queue_list.append(f"{i}. {url}")queue_text = "\n".join(queue_list)await interaction.followup.send(f"**Music Queue:**\n{queue_text}")def run_discord_bot():bot.run(os.getenv('DISCORD_TOKEN'))# Create the Gradio interfacewith gr.Blocks() as iface:gr.Markdown("# Discord Music Bot Control Panel")gr.Markdown("Bot is running in background")if __name__ == "__main__":# Start the Discord bot in a separate threadbot_thread = threading.Thread(target=run_discord_bot, daemon=True)bot_thread.start()# Run Gradio interface in the main threadiface.launch(debug=True)123456789101112131415161718192021222324252627282930312 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667683 unmodified lines727374757677787980818283848586878889909192939495969798991001011021 unmodified line104105106107108109110111112113114115116117118119120121122123124125126127import discordfrom discord.ext import commandsfrom huggingface_hub import hf_hub_downloadimport gradio as grfrom dotenv import load_dotenvimport osimport threadingimport asyncio# Load environment variablesload_dotenv()if os.path.exists("assets") is False:os.makedirs("assets", exist_ok=True)hf_hub_download("not-lain/assets", "lofi.mp3", repo_type="dataset", local_dir="assets")# Bot configurationintents = discord.Intents.default()intents.message_content = Truebot = commands.Bot(command_prefix="!", intents=intents)class MusicBot:def __init__(self):self.is_playing = Falseself.voice_client = Noneasync def join_voice(self, ctx):if ctx.author.voice:2 unmodified linesself.voice_client = await channel.connect()else:await self.voice_client.move_to(channel)else:await ctx.send("You need to be in a voice channel!")async def play_next(self, ctx):if not self.is_playing:self.is_playing = Truetry:audio_source = discord.FFmpegPCMAudio("assets/lofi.mp3")def after_playing(e):self.is_playing = False# test loop by defaultif e:print(f"Playback error: {e}")asyncio.run_coroutine_threadsafe(self.play_next(ctx), bot.loop)self.voice_client.play(audio_source, after=after_playing)except Exception as e:print(f"Error playing file: {e}")await ctx.send("Error playing the song.")self.is_playing = Falsemusic_bot = MusicBot()@bot.eventasync def on_ready():print(f"Bot is ready! Logged in as {bot.user}")print("Syncing commands...")try:await bot.tree.sync(guild=None) # Set to None for global sync3 unmodified linesexcept Exception as e:print(f"An error occurred while syncing commands: {e}")@bot.tree.command(name="play", description="Play the sample music")async def play(interaction: discord.Interaction):await interaction.response.defer()ctx = await commands.Context.from_interaction(interaction)await music_bot.join_voice(ctx)if not music_bot.is_playing:await music_bot.play_next(ctx)await interaction.followup.send("Playing sample music!")else:await interaction.followup.send("Already playing!")# Replace the existing skip command with this version@bot.tree.command(name="skip", description="Skip the current song")async def skip(interaction: discord.Interaction):if music_bot.voice_client:music_bot.voice_client.stop()await interaction.response.send_message("Skipped current song!")else:await interaction.response.send_message("No song is currently playing!")# Replace the existing leave command with this version@bot.tree.command(name="leave", description="Disconnect bot from voice channel")async def leave(interaction: discord.Interaction):if music_bot.voice_client:1 unmodified linemusic_bot.voice_client = Nonemusic_bot.queue = []music_bot.is_playing = Falseawait interaction.response.send_message("Bot disconnected!")else:await interaction.response.send_message("Bot is not in a voice channel!")def run_discord_bot():bot.run(os.getenv("DISCORD_TOKEN"))# Create the Gradio interfacewith gr.Blocks() as iface:gr.Markdown("# Discord Music Bot Control Panel")gr.Markdown("Bot is running in background")if __name__ == "__main__":# Start the Discord bot in a separate threadbot_thread = threading.Thread(target=run_discord_bot, daemon=True)bot_thread.start()# Run Gradio interface in the main threadiface.launch(debug=True)
1234567discord.pyPyNaClffmpeg-pythonpython-dotenvspotipygradioyt-dlp123456discord.pyyoutube_dlPyNaClffmpeg-pythonyt-dlppython-dotenv
.gitignore+2-1
app.py+45-101
requirements.txt+3-4