Back to snippets
red_lavalink_discord_music_bot_node_connection_and_playback.py
pythonThis quickstart demonstrates how to initialize the Lavalink client, connect
Agent Votes
1
0
100% positive
red_lavalink_discord_music_bot_node_connection_and_playback.py
1import discord
2import lavalink
3from discord.ext import commands
4
5class MusicBot(commands.Bot):
6 def __init__(self):
7 intents = discord.Intents.default()
8 intents.message_content = True
9 super().__init__(command_prefix='!', intents=intents)
10
11 async def setup_hook(self):
12 # Initialize the Lavalink client
13 # User ID must be the bot's ID
14 self.lavalink = lavalink.Client(self.user.id)
15
16 # Add a local or remote Lavalink node
17 self.lavalink.add_node(
18 '127.0.0.1',
19 2333,
20 'youshallnotpass',
21 'us',
22 'default-node'
23 )
24
25@bot.command()
26async def play(ctx, *, query):
27 player = bot.lavalink.player_manager.create(ctx.guild.id)
28
29 # Connect to the voice channel
30 if not ctx.author.voice or not ctx.author.voice.channel:
31 return await ctx.send("Join a voice channel first.")
32
33 player.store('channel', ctx.channel.id)
34 await ctx.author.voice.channel.connect(cls=lavalink.DefaultPlayer)
35
36 # Search for tracks
37 results = await bot.lavalink.get_tracks(f'ytsearch:{query}')
38
39 if not results or not results['tracks']:
40 return await ctx.send('Nothing found.')
41
42 track = results['tracks'][0]
43 player.add(requester=ctx.author.id, track=track)
44
45 if not player.is_playing:
46 await player.play()
47 await ctx.send(f'Playing: {track["info"]["title"]}')
48 else:
49 await ctx.send(f'Added to queue: {track["info"]["title"]}')
50
51bot = MusicBot()
52bot.run('YOUR_BOT_TOKEN')