File size: 7,371 Bytes
c8aea3c
60d2967
 
1bc04be
60d2967
 
 
 
636e642
c8aea3c
 
 
60d2967
c8aea3c
60d2967
 
c8aea3c
1bc04be
 
 
 
c8aea3c
60d2967
 
 
 
c8aea3c
 
 
 
 
 
 
60d2967
 
c8aea3c
60d2967
 
c8aea3c
 
 
 
 
 
 
 
60d2967
 
c8aea3c
60d2967
 
 
 
 
 
 
 
 
 
c8aea3c
1bc04be
60d2967
1bc04be
c8aea3c
1bc04be
 
c8aea3c
1bc04be
636e642
 
c8aea3c
636e642
1bc04be
 
 
 
 
60d2967
c8aea3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d2967
 
 
 
c8aea3c
60d2967
036628e
77815e1
036628e
 
 
 
77815e1
036628e
60d2967
c8aea3c
 
 
77815e1
 
c8aea3c
 
 
 
 
60d2967
 
 
c8aea3c
 
 
 
 
60d2967
1bc04be
60d2967
036628e
 
c8aea3c
60d2967
 
036628e
 
 
60d2967
036628e
 
c8aea3c
60d2967
 
 
 
 
036628e
 
 
60d2967
 
c8aea3c
60d2967
 
c8aea3c
60d2967
c8aea3c
60d2967
 
 
 
c8aea3c
60d2967
 
 
c8aea3c
60d2967
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# Import necessary libraries for Discord bot, HuggingFace integration, and UI
import discord
from discord.ext import commands
from huggingface_hub import hf_hub_download
import gradio as gr 
from dotenv import load_dotenv
import os
import threading
import asyncio
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import yt_dlp

# Load environment variables from .env file
load_dotenv()

# Create assets directory and download sample music if not exists
if os.path.exists('assets') is False:
    os.makedirs('assets', exist_ok=True)
    hf_hub_download("not-lain/assets", "sample.mp3", repo_type="dataset",local_dir="assets")

# Set up Discord bot with necessary intents
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

# Initialize Spotify client
spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
    client_id=os.getenv('SPOTIFY_CLIENT_ID'),
    client_secret=os.getenv('SPOTIFY_CLIENT_SECRET')
))

# Class to handle music playback functionality
class MusicBot:
    def __init__(self):
        # Initialize bot state variables
        self.is_playing = False
        self.voice_client = None
        self.ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }

    async def join_voice(self, ctx):
        # Method to join voice channel or move to user's channel
        if ctx.author.voice:
            channel = ctx.author.voice.channel
            if self.voice_client is None:
                self.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):
        # Method to play audio and handle playback completion
        if not self.is_playing:
            self.is_playing = True
            try:
                # Create audio source from local file
                audio_source = discord.FFmpegPCMAudio("assets/sample.mp3")
                def after_playing(e):
                    # Callback function when song ends
                    self.is_playing = False
                    if e:
                        print(f"Playback error: {e}")
                    # Test loop by default
                    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 = False

    async def play_spotify(self, ctx, track_url):
        if not self.is_playing:
            self.is_playing = True
            try:
                # Extract Spotify track ID
                track_id = track_url.split('/')[-1].split('?')[0]
                track_info = spotify.track(track_id)
                search_query = f"{track_info['name']} {track_info['artists'][0]['name']}"

                # Use yt-dlp to find and download the audio
                with yt_dlp.YoutubeDL(self.ydl_opts) as ydl:
                    # Search YouTube for the song
                    info = ydl.extract_info(f"ytsearch:{search_query}", download=False)
                    url = info['entries'][0]['url']
                    
                    # Play the audio
                    FFMPEG_OPTIONS = {
                        'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                        'options': '-vn',
                    }
                    audio_source = discord.FFmpegPCMAudio(url, **FFMPEG_OPTIONS)
                    
                    def after_playing(e):
                        self.is_playing = False
                        if e:
                            print(f"Playback error: {e}")
                    
                    self.voice_client.play(audio_source, after=after_playing)
                    return track_info['name']
                    
            except Exception as e:
                print(f"Error playing Spotify track: {e}")
                await ctx.send("Error playing the song.")
                self.is_playing = False
                return None

# Create instance of MusicBot
music_bot = MusicBot()

@bot.event
async def on_ready():
    # Event handler for when bot is ready and connected
    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 sync
        print("Successfully synced commands globally!")
    except discord.app_commands.errors.CommandSyncFailure as e:
        print(f"Failed to sync commands: {e}")
    except Exception as e:
        print(f"An error occurred while syncing commands: {e}")

@bot.tree.command(name="play", description="Play a song from Spotify")
async def play(interaction: discord.Interaction, url: str):
    # Command to start playing music
    await interaction.response.defer()
    ctx = await commands.Context.from_interaction(interaction)
    
    if not url.startswith('https://open.spotify.com/track/'):
        await interaction.followup.send('Please provide a valid Spotify track URL!')
        return
        
    await music_bot.join_voice(ctx)
    
    if not music_bot.is_playing:
        song_name = await music_bot.play_spotify(ctx, url)
        if song_name:
            await interaction.followup.send(f'Playing {song_name} from Spotify!')
        else:
            await interaction.followup.send('Failed to play the song!')
    else:
        await interaction.followup.send('Already playing!')

@bot.tree.command(name="skip", description="Skip the current song")
async def skip(interaction: discord.Interaction):
    # Command to skip current playing song
    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):
    # Command to disconnect bot from voice channel
    if music_bot.voice_client:
        await music_bot.voice_client.disconnect()
        music_bot.voice_client = None
        music_bot.queue = []
        music_bot.is_playing = False
        await interaction.response.send_message('Bot disconnected!')
    else:
        await interaction.response.send_message('Bot is not in a voice channel!')

def run_discord_bot():
    # Function to start the Discord bot
    bot.run(os.getenv('DISCORD_TOKEN'))

# Create Gradio interface for web control
with gr.Blocks() as iface:
    # Set up simple web interface
    gr.Markdown("# Discord Music Bot Control Panel")
    gr.Markdown("Bot is running in background")
    
if __name__ == "__main__":
    # Main entry point: start bot in background thread and launch web interface
    bot_thread = threading.Thread(target=run_discord_bot, daemon=True)
    bot_thread.start()
    
    # Launch Gradio interface in main thread
    iface.launch(debug=True)