-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjam_machine.py
More file actions
214 lines (180 loc) · 8.09 KB
/
jam_machine.py
File metadata and controls
214 lines (180 loc) · 8.09 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import discord
from discord.ext import commands
import wavelink
import asyncio
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import logging
import re
# --- Logging Setup ---
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler("bot.log", mode='a', encoding='utf-8'),
logging.StreamHandler()
]
)
# --- Configuration ---
DISCORD_TOKEN = "MTQxNjExMTYwMzU0MzE4MzM5MA.GQpPYt.qmTvD9IGhHwCE8YP7BXhiueBxqQ9WaeUAbMFfg"
SPOTIPY_CLIENT_ID = "e2f8a777b6484a4d86077fbcb081430c"
SPOTIPY_CLIENT_SECRET = "c2c98daea50e423e82baa9b2339be9e5"
# --- Bot Setup ---
class MusicBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=intents)
self.sp = None
async def setup_hook(self) -> None:
nodes = [wavelink.Node(uri="http://localhost:2333", password="youshallnotpass")]
await wavelink.Pool.connect(nodes=nodes, client=self)
async def on_ready(self):
logging.info(f'Success! Logged in as {self.user.name}')
if wavelink.Pool.nodes:
logging.info(f'Wavelink is connected to {wavelink.Pool.get_node().uri}')
else:
logging.warning('Wavelink node is not connected. Please ensure Lavalink.jar is running.')
logging.info('------')
self.setup_spotify()
def setup_spotify(self):
try:
if 'SPOTIPY_CLIENT_ID' in globals() and 'SPOTIPY_CLIENT_SECRET' in globals() and SPOTIPY_CLIENT_ID:
auth_manager = SpotifyClientCredentials(
client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET
)
self.sp = spotipy.Spotify(auth_manager=auth_manager)
logging.info("Successfully authenticated with Spotify.")
else:
self.sp = None
logging.warning("Spotify credentials not found or are empty. Spotify features will be disabled.")
except Exception as e:
self.sp = None
logging.error(f"Could not authenticate with Spotify. Error: {e}")
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True
bot = MusicBot()
# --- Wavelink Event Listeners (Verified against Wavelink v3+ Docs) ---
@bot.event
async def on_wavelink_node_ready(payload: wavelink.NodeReadyEventPayload):
logging.info(f'Node: <{payload.node.uri}> is ready!')
@bot.event
async def on_wavelink_track_end(payload: wavelink.TrackEndEventPayload):
player = payload.player
logging.info(f"Track '{payload.track.title}' ended. Reason: {payload.reason}")
if hasattr(player, 'ctx') and player.queue and not player.playing:
ctx = player.ctx
next_song = player.queue.get()
await player.play(next_song)
await ctx.send(f"Now playing: **{next_song.title}**")
@bot.event
async def on_wavelink_track_exception(payload: wavelink.TrackExceptionEventPayload):
logging.critical(f"CRITICAL ERROR playing track '{payload.track.title}': {payload.exception}")
if hasattr(payload.player, 'ctx'):
await payload.player.ctx.send(f"Error playing **{payload.track.title}**: The track failed during playback.")
# --- Bot Commands (Logic audited and revised) ---
@bot.command(name='join')
async def join(ctx: commands.Context):
if not ctx.author.voice:
return await ctx.send("You are not connected to a voice channel.")
channel = ctx.author.voice.channel
player: wavelink.Player = await channel.connect(cls=wavelink.Player)
await ctx.send(f"Joined **{channel.name}**.")
player.ctx = ctx
@bot.command(name='leave')
async def leave(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if vc:
await vc.disconnect()
@bot.command(name='play')
async def play(ctx: commands.Context, *, query: str):
logging.info(f"Play command received with query: \"{query}\"")
if not ctx.voice_client:
await ctx.invoke(join)
vc: wavelink.Player = ctx.voice_client
vc.ctx = ctx
async with ctx.typing():
# --- REVISED SEARCH LOGIC (Verified against Vocard and other modern bots) ---
# Step 1: Check if the query is a URL. Lavalink handles URLs directly.
is_url = re.match(r"https?://", query)
# Step 2: If it's not a URL, get a better search term from Spotify.
if not is_url and bot.sp:
try:
# Use the original query to search Spotify
results = bot.sp.search(q=query, limit=1, type='track')
if results and results['tracks']['items']:
track_info = results['tracks']['items'][0]
artist_name = track_info['artists'][0]['name']
track_name = track_info['name']
# This becomes our new, high-quality search query.
query = f"{track_name} by {artist_name}"
logging.info(f"Spotify found a match. New search query: \"{query}\"")
await ctx.send(f"Found on Spotify: **{track_name} by {artist_name}**. Searching...")
except Exception:
# If Spotify fails for any reason, we just proceed with the user's original query.
pass
# Step 3: Construct the final Lavalink search identifier.
# If it's a URL, we pass it directly. If not, we explicitly tell Lavalink to search YouTube Music.
# This explicit `ytmsearch` is the modern, robust standard.
search_identifier = query if is_url else f"ytmsearch:{query}"
logging.info(f"Searching Lavalink with identifier: \"{search_identifier}\"")
tracks = await wavelink.Playable.search(search_identifier)
if not tracks:
logging.warning(f"Lavalink returned no tracks for identifier: \"{search_identifier}\"")
return await ctx.send(f"I couldn't find any songs matching your query.")
song = tracks[0]
if not vc.playing:
await vc.play(song)
await ctx.send(f"Now playing: **{song.title}**")
else:
vc.queue.put(song)
await ctx.send(f"Added to queue: **{song.title}**")
@bot.command()
async def skip(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if not vc or not vc.playing:
return await ctx.send("I am not playing anything.")
await vc.stop()
await ctx.send("Skipped.")
@bot.command()
async def stop(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if vc and vc.is_connected():
vc.queue.clear()
await vc.stop()
await ctx.send("Stopped and cleared the queue.")
@bot.command()
async def pause(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if vc and vc.playing:
await vc.pause()
await ctx.send("Paused.")
@bot.command()
async def resume(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if vc and vc.paused:
await vc.resume()
await ctx.send("Resumed.")
@bot.command()
async def queue(ctx: commands.Context):
vc: wavelink.Player = ctx.voice_client
if not vc or not vc.is_connected():
return await ctx.send("I am not in a voice channel.")
if vc.queue.is_empty:
return await ctx.send("The queue is empty.")
embed = discord.Embed(title="Song Queue", color=discord.Color.purple())
queue_list = "\n".join(f"`{i+1}.` {song.title}" for i, song in enumerate(vc.queue))
embed.description = queue_list
await ctx.send(embed=embed)
# --- Run the Bot (Verified as modern standard) ---
if __name__ == "__main__":
try:
# Check if the token variable has been filled in.
if 'DISCORD_TOKEN' in globals() and DISCORD_TOKEN:
asyncio.run(bot.run(DISCORD_TOKEN))
else:
logging.critical("CRITICAL: DISCORD_TOKEN is not defined. Please paste your credentials into the script.")
except discord.errors.LoginFailure:
logging.critical("CRITICAL: Login failed. Please check your DISCORD_TOKEN.")
except Exception as e:
logging.critical(f"An unexpected error occurred on startup: {e}")