|
2 | 2 | import json |
3 | 3 | import os |
4 | 4 | import requests |
| 5 | +import random |
5 | 6 | from io import BytesIO |
6 | 7 | from discord import Role, Member, Object |
7 | 8 | from typing import Mapping |
@@ -243,3 +244,41 @@ async def on_member_join(self, member: discord.Member): |
243 | 244 | else: |
244 | 245 | print(f"Welcome channel with ID {welcome_channel_id} not found in guild {member.guild.name} or globally for bot.") |
245 | 246 |
|
| 247 | +class MusicClient(discord.Client): |
| 248 | + def __init__(self, path_to_playlist, intents: discord.Intents): |
| 249 | + super().__init__(intents=intents) |
| 250 | + self.voice_recorders = {} |
| 251 | + self.playlist = path_to_playlist |
| 252 | + |
| 253 | + async def on_ready(self): |
| 254 | + if (self.user is not None): |
| 255 | + print(f"Logged in as {self.user} (ID: {self.user.id})") |
| 256 | + print("------") |
| 257 | + await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Music")) |
| 258 | + async def on_message(self, message: discord.Message): |
| 259 | + if message.author == self.user: |
| 260 | + return |
| 261 | + if message.content.startswith("!join"): |
| 262 | + if isinstance(message.author, discord.Member) and message.author.voice and message.author.voice.channel: |
| 263 | + voice_channel = message.author.voice.channel |
| 264 | + try: |
| 265 | + voice_client = await voice_channel.connect() |
| 266 | + await message.channel.send(f"Joined {voice_channel.name}!") |
| 267 | + |
| 268 | + if (os.path.isdir(self.playlist)): |
| 269 | + files = [os.path.join(self.playlist, f) for f in os.listdir(self.playlist) if f.endswith(".mp3")] |
| 270 | + def after_callback(error): |
| 271 | + if error: |
| 272 | + print(f'Player error: {error}') |
| 273 | + else: |
| 274 | + audio = discord.FFmpegPCMAudio(random.choice(files)) |
| 275 | + voice_client.play(audio, after=after_callback) |
| 276 | + |
| 277 | + audio_source = discord.FFmpegPCMAudio(random.choice(files)) |
| 278 | + voice_client.play(audio_source, after=after_callback) |
| 279 | + |
| 280 | + await message.channel.send("Now playing music on loop!") |
| 281 | + except Exception as e: |
| 282 | + await message.channel.send(f"Error joining voice channel: {str(e)}") |
| 283 | + else: |
| 284 | + await message.channel.send("You need to be in a voice channel first!") |
0 commit comments