【问题标题】:Unable to connect lavalink server to bot.py无法将 lavalink 服务器连接到 bot.py
【发布时间】:2022-06-29 08:15:28
【问题描述】:

你好,我试图在 repl.it 上托管 lavalink 服务器,但它没有连接它说 NODE-hongkong-la********.vnns.repl.co:443] The remote server returned code 400, the expected code was 101. This usually indicates that the remote server is a webserver and not Lavalink. Check your ports, and try again.。我希望你能帮我解决我的问题

这是我的 cogs.music

# cogs.music
class music(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
    self.bot.music = lavalink.Client(self.bot.user.id)
    self.bot.music.add_node('la********.vnns.repl.co', 443, 'test', 'hongkong', 'music-node')
    self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
    self.bot.music.add_event_hook(self.track_hook)

application.yml 片段

server: 
  port: 443
  address: 0.0.0.0
lavalink:
  server:
    password: "test"
    sources:
      youtube: true
      bandcamp: true
      soundcloud: true
      twitch: true
      vimeo: true
      mixer: true
      http: true
      local: false
    bufferDurationMs: 400 # The duration of the NAS buffer. Higher values fare better against longer GC pauses
    frameBufferDurationMs: 5000 # How many milliseconds of audio to keep buffered
    youtubePlaylistLoadLimit: 6 # Number of pages at 100 each
    playerUpdateInterval: 5 # How frequently to send player updates to clients, in seconds
    youtubeSearchEnabled: true

【问题讨论】:

    标签: discord.py


    【解决方案1】:

    lavalink 改变了一切,我真的不推荐使用 lavalink,我使用了 wavelink,它完全可以正常工作。 如果您想要完整的指南,here。 在您观看该视频后,我有一个升级的代码,它添加了队列、歌曲列表和其他内容,如果您愿意,可以在您的音乐 cog 中使用它:

    import discord
    import wavelink
    import typing
    import sqlite3
    from discord.ext import commands
    
    class Music(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
            bot.loop.create_task(self.create_nodes())
    
        async def create_nodes(self):
            await self.bot.wait_until_ready()
            await wavelink.NodePool.create_node(bot=self.bot, host="YOUR_ADRESS(Your adress shouldent be 0.0.0.0, do something like 127.0.0.1)", port="YOUR_PORT", password="youshallnotpass", region="asia")
    
        @commands.Cog.listener()
        async def on_ready(self):
            print("music cog ready! (beta)")
    
        @commands.Cog.listener()
        async def on_wavelink_node_ready(self, node: wavelink.Node):
            print(f"Node <{node.identifier}> ready!")
    
        @commands.Cog.listener()
        async def on_command_error(self, ctx, error):
            if isinstance(error, commands.CommandNotFound):
                await ctx.send(f"Unknown command")
    
        @commands.Cog.listener()
        async def on_wavelink_track_end(self, player: wavelink.Player, track: wavelink.Track, reason):
            ctx = player.ctx
            vc: player = ctx.voice_client
    
            if vc.loop:
                return await vc.play(track)
        
            if vc.queue.is_empty:
                return await ctx.send("The queue is empty")
        
            next_song = vc.queue.get()
            song = await wavelink.YouTubeTrack.search(query=str(next_song), return_first=True)
            if not song.uri == None:
                    ur = song.uri
            else:
                ur = "None"
            if not song.author == None:
                au = song.author
            else:
                au = "None"
            if song.is_stream():
                stream = "True"
            else:
                stream = "False"
            await vc.play(song)
            embed = discord.Embed(title=f"Now Playing `{song.title}`", description=f"Info:\nSong length(second), {song.duration}\nAuthor, {au}\nLink, {ur}\nStream, {stream}", color=discord.Color.from_rgb(255, 255, 255))
            await ctx.send(embed=embed)
        
    
        @commands.command(name="join", aliases=["connect", "summon"], description="Join the voice channel you provided or the music channel you are in")
        async def join_commad(self, ctx, channel: typing.Optional[discord.VoiceChannel]):
            try:
                if channel is None:
                    channel = ctx.author.voice.channel
            
                node = wavelink.NodePool.get_node()
                player = node.get_player(ctx.guild)
    
                if player is not None:
                    if player.is_connected():
                        return await ctx.send("bot is already connected to a voice channel")
            
                await channel.connect(cls=wavelink.Player)
                embed = discord.Embed(title=f"Connected to {channel.name}", color=discord.Color.from_rgb(255, 255, 255))
                await ctx.send(embed=embed)
            except AttributeError:
                await ctx.send("You are not in a voice channel!")
    
        @commands.command(name="leave", aliases=["disconnect", "quit"], description="Leave the Voice channel")
        async def leave_command(self, ctx):
            node = wavelink.NodePool.get_node()
            player = node.get_player(ctx.guild)
    
            if player is None:
                return await ctx.send("bot is not connected to any voice channel")
        
            await player.disconnect()
            embed=discord.Embed(title="Disconnected", color=discord.Color.from_rgb(255, 255, 255))
            await ctx.send(embed=embed)
    
        @commands.command(name="play", description="search the music name you provided and play it")
        async def play_command(self, ctx, *, search: str):
            if not ctx.author.voice:
                return await ctx.send("Join a voice channel first!")
            song = await wavelink.YouTubeTrack.search(query=search, return_first=True)
        
            if not ctx.voice_client:
                vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
            else:
                vc: wavelink.Player = ctx.voice_client
        
            if vc.queue.is_empty and not vc.is_playing():
                await vc.play(song)
                if not song.uri == None:
                    ur = song.uri
                else:
                    ur = "None"
                if not song.author == None:
                    au = song.author
                else:
                    au = "None"
                if song.is_stream():
                    stream = "True"
                else:
                    stream = "False"
                embed = discord.Embed(title=f"Now Playing `{song.title}`", description=f"Info:\nSong length(second), {song.duration}\nAuthor, {au}\nLink, {ur}\nStream, {stream}", color=discord.Color.from_rgb(255, 255, 255))
            else:
                await vc.queue.put_wait(song)
                embed = discord.Embed(title=f"Added `{song}` to the queue")
            await ctx.send(embed=embed)
            vc.ctx = ctx
            setattr(vc, "loop", False)
    
        @commands.command(name="overrideplay", description="Play the music without adding it to the query and override all songs")
        async def overrideplay_command(self, ctx, *, search: str):
            if not ctx.author.voice:
                return await ctx.send("Join a voice channel first!")
            song = await wavelink.YouTubeTrack.search(query=search, return_first=True)
        
            if not ctx.voice_client:
                vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
            else:
                vc: wavelink.Player = ctx.voice_client
        
            if vc.queue.is_empty:
                await vc.play(song)
                if not song.uri == None:
                    ur = song.uri
                else:
                    ur = "None"
                if not song.author == None:
                    au = song.author
                else:
                    au = "None"
                if song.is_stream():
                    stream = "True"
                else:
                    stream = "False"
                embed = discord.Embed(title=f"Now Playing `{song.title}`", description=f"Info:\nSong length(second), {song.duration}\nAuthor, {au}\nLink, {ur}\nStream, {stream}", color=discord.Color.from_rgb(255, 255, 255))
        else:
                await ctx.send("The queue is not empty, use the stop command to clear the queue!")
            await ctx.send(embed=embed)
            vc.ctx = ctx
            setattr(vc, "loop", False)
    
        @commands.command(name="stop", description="Finish the music(It will finish the music it is not resume if you want to play it again do rr?play <song name>)")
        async def stop_command(self, ctx):
            try:
                node = wavelink.NodePool.get_node()
                player = node.get_player(ctx.guild)
    
                if player is None:
                    return await ctx.send("Bot is not connected to any voice channel")
                else:
                    vc: wavelink.Player = ctx.voice_client
            
                if player.is_playing:
                    if not vc.queue.is_empty:
                        vc.queue.clear()
                        await player.stop()
                    else:
                        await player.stop()
                    embed=discord.Embed(title="Playback Stoped", color=discord.Color.from_rgb(255, 255, 255))
                    return await ctx.send(embed=embed)
                else:
                    return await ctx.send("Nothing is playing")
            except Exception as e:
                print(e)
    
        @commands.command(name="skip", description="Skip this song and move on to the next song if there is one")
        async def skip_command(self, ctx):
            node = wavelink.NodePool.get_node()
            player = node.get_player(ctx.guild)
    
            if player is None:
                return await ctx.send("Bot is not connected to any voice channel")
            else:
                vc: wavelink.Player = ctx.voice_client
        
            if player.is_playing:
                await player.stop()
                embed=discord.Embed(title="Playback Skipped", color=discord.Color.from_rgb(255, 255, 255))
                return await ctx.send(embed=embed)
            else:
                return await ctx.send("Nothing is playing")
    
        @commands.command(name="pause", description="pause the music if it is playing one")
        async def pause_command(self, ctx):
            node = wavelink.NodePool.get_node()
            player = node.get_player(ctx.guild)
    
            if player is None:
                return await ctx.send("Bot is not connected to any voice channel")
        
            if not player.is_paused():
                if player.is_playing():
                    await player.pause()
                    embed = discord.Embed(title="Playback Paused", color=discord.Color.from_rgb(255, 255, 255))
                    return await ctx.send(embed=embed)
                else:
                    return await ctx.send("Nothing is playing")
            else:
                return await ctx.send("Playback is Already paused")
    
        @commands.command(name="resume", aliases=["continue"], description="resume the music if it is playing one")
        async def resume_command(self, ctx):
            node = wavelink.NodePool.get_node()
            player = node.get_player(ctx.guild)
    
            if player is None:
                return await ctx.send("bot is not connected to any voice channel")
        
            if player.is_paused():
                await player.resume()
                embed = discord.Embed(title="Playback resumed", color=discord.Color.from_rgb(255, 255, 255))
                return await ctx.send(embed=embed)
            else:
                return await ctx.send("playback is not paused")
    
        @commands.command(name="volume", description="Change the music volume between 1 and 100")
        async def volume_command(self, ctx, to:int):
            if not ctx.voice_client:
                return await ctx.send("I am not even in a voice channel!")
            if to > 100:
                return await ctx.send("Volume should be between 1 and 100")
            elif to < 1:
                return await ctx.send("Volume should be between 1 and 100")
        
            node = wavelink.NodePool.get_node()
            player = node.get_player(ctx.guild)
    
            await player.set_volume(to)
            embed = discord.Embed(title=f"Changed volume to {to}", color=discord.Color.from_rgb(255, 255, 255))
            await ctx.send(embed=embed)
    
        @commands.command(name="loop", description="Loop the music")
        async def loop_command(self, ctx):
            if not ctx.voice_client:
                return await ctx.send("I am not in a voice channel!")
            elif not ctx.author.voice:
                return await ctx.send("You are not in a voice channel!")
            else:
                vc: wavelink.Player = ctx.voice_client
        
            if vc.loop == False:
                vc.loop = True
            else:
                setattr(vc, "loop", False)
        
            if vc.loop:
                return await ctx.send("Loop is now **Enabled!**")
            else:
                return await ctx.send("Loop is now **Disabled!**")
    
        @commands.command(name="queue", description="Show the queue")
        async def queue_command(self, ctx):
            if not ctx.voice_client:
                return await ctx.send("I'm not in a voice channel!")
            elif not ctx.author.voice:
                return await ctx.send("You are not in a voice channel!")
            else:
                vc: wavelink.Player = ctx.voice_client
    
            if vc.queue.is_empty:
                return await ctx.send("Queue is empty")
        
            embed = discord.Embed(title="Queue", color=discord.Color.from_rgb(255, 255, 255))
            queue = vc.queue.copy()
            song_count = 0
            for song in queue:
                song_count += 1
                embed.add_field(name=f"Song {song_count}", value=f"`{song}`")
    
            return await ctx.send(embed=embed)
    
        @commands.command(name="info", description="search the music name you provided and show the info of it", aliases=["information"])
        async def info_command(self, ctx, *, search: str):
            song = await wavelink.YouTubeTrack.search(query=search, return_first=True)
            if not song.uri == None:
                ur = song.uri
            else:
                ur = "None"
            if not song.author == None:
                au = song.author
            else:
                au = "None"
            if song.is_stream():
                stream = "True"
            else:
                stream = "False"
            embed = discord.Embed(title=f"Info about `{song.title}`", description=f"Info:\nSong length(second), {song.duration}\nAuthor, {au}\nLink, {ur}\nStream, {stream}", color=discord.Color.from_rgb(255, 255, 255))
            await ctx.send(embed=embed)
    
        @commands.command(name="addsong", description="Add a song to your song list")
        async def addsong_command(self, ctx, *, song: str):
            try:
                so = await wavelink.YouTubeTrack.search(query=song, return_first=True)
                so1 = str(so) + ", "
                db = sqlite3.connect('main.sqlite')
                cursor = db.cursor()
                cursor.execute(f"SELECT song_list FROM main WHERE user_id = {ctx.author.id}")
                result = cursor.fetchone()
                if result is None:
                    sql = ("INSERT INTO main(user_id, song_list) VALUES(?,?)")
                    val = (ctx.author.id, so1)
                    await ctx.send(f"First song added! {so}")
                elif result is not None:
                    sfinal = result[0] + (so1)
                    sql = ("UPDATE main SET song_list = ? WHERE user_id = ?")
                    val = (sfinal, ctx.author.id,)
                    await ctx.send(f"Song has been added: {so}")
                cursor.execute(sql, val)
                db.commit()
                cursor.close()
                db.close()
            except Exception as e:
                await ctx.send(e)
    
        @commands.command(name="mysonglist", description="Show your song list")
        async def mysonglist_command(self, ctx):
            try:
                db = sqlite3.connect('main.sqlite')
                cursor = db.cursor()
                cursor.execute(f"SELECT song_list FROM main WHERE user_id = {ctx.author.id}")
                result = cursor.fetchone()
                if result is None:
                    cursor.close()
                    db.close()
                    return await ctx.send("You don't have any song in your list")
                elif result is not None:
                    result = " ".join(result)
                    embed = discord.Embed(title="Your song list", description=f"{result}", color=discord.Color.from_rgb(255, 255, 255))
                    await ctx.send(embed=embed)
                    cursor.close()
                    db.close()
            except Exception as e:
                await ctx.send(e)
    
        @commands.command(name="deletesonglist", description="Delete your song list")
        async def deletesonglist_command(self, ctx):
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute(f"SELECT song_list FROM main WHERE user_id = {ctx.author.id}")
            result = cursor.fetchone()
            if result is not None:
                try:
                    sql = ("DELETE FROM main WHERE user_id = ?")
                    val = (ctx.author.id,)
                    cursor.execute(sql, val)
                    await ctx.send("Sucessfully removed your song list")
                except Exception as e:
                    await ctx.send(e)
            elif result is None:
                db.commit()
                cursor.close()
                db.close()
                return await ctx.send("You don't have a song list!")
            db.commit()
            cursor.close()
            db.close()
    
    def setup(bot):
      bot.add_cog(Music(bot))`
    

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2020-01-24
      • 1970-01-01
      • 2011-12-29
      • 2018-12-09
      相关资源
      最近更新 更多