【问题标题】:Discord music bot not reading the commandDiscord 音乐机器人不读取命令
【发布时间】:2022-12-03 03:18:30
【问题描述】:

所以,我正在尝试制作一个不和谐的音乐机器人,并且每当我使用播放命令时我都会收到这个错误,我认为它没有加载齿轮或与此有关。这是我的主要功能

这是我在 music_player 类the error that I'm getting once I run the code 中的命令


import discord
from discord.ext import commands
import os
from youtube_dl import YoutubeDL

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"),
    description='Relatively simple music bot example',
    intents=intents,
)


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')


bot.add_cog("cogs.music_player")

音乐播放器.py


import os
import discord
from discord.ext import commands
from youtube_dl import YoutubeDL

class music_player(commands.Cog):
    
    def __init__(self, client):
        self.client = client

        # Checks whether the song is playing or not
        self.isplaying = False
        self.ispaused = False


        # The music queue ( this contains the song and the channel)
        self.musicque = []


        # The code below is taken from github to get the best quality of sound possible
        self.ytdl_format_options = {
        'format': 'bestaudio/best',
        'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
        'restrictfilenames': True,
        'noplaylist': True,
        'nocheckcertificate': True,
        'ignoreerrors': False,
        'logtostderr': False,
        'quiet': True,
        'no_warnings': True,
        'default_search': 'auto',
        'source_address': '0.0.0.0',  # bind to ipv4 since ipv6 addresses cause issues sometimes
    }
                           
        self.ffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

        self.vc = None

    # This small function searches a song on youtube
    def search_yt(self, song):

            # with youtube open as
            with YoutubeDL(self.ytdl_format_options) as ydl:

                # This will basically search youtube and return the entries we get from our search 
                try: 
                    info = ydl.extract_info("ytsearch:%s" % song, download=False)['entries'][0]
                except Exception: 
                    return False
            # Returns the info as source
            return {'source': info['formats'][0]['url'], 'title': info['title']}
    
    def play_next(self):
        if len(self.musicque) > 0:
            self.isplaying = True

            # Get the link of the first song in the que as we did in the play song function
            music_link = self.musicque[0][0]['source']

            # Remove the song currently playing same way we did in the play_song function
            self.musicque.pop(0)

            # same lambda function we used the play_song function
            self.vc.play(discord.FFmpegPCMAudio(music_link, **self.ffmpeg_options), after=lambda e: self.play_next())
        else:
            self.isplaying = False
    
    async def play_song(self, ctx):
        if len(self.musicque) > 0:
            self.isplaying = True

            # Get the link of the first song in the que
            music_link = self.musicque[0][0]['source']

            # Connect to the voice channel the user is currently in if bot is not already connected
            if self.vc == None or not self.vc.is_connected():
                self.vc = await self.musicque[0][1].connect()

                # if we fail to connect to the vc for whatever reason
                if self.vc == None:
                    await ctx.send("Could not connect to the voice channel")
                    return
            # Else if the bot is already in voice
            else:
                await self.vc.move_to(self.musicque[0][1])
            
            # Remove the first song in the que using the built in pop function in python as we're already playing the song
            self.musicque.pop(0)

            # Took this lambda play function from github
            self.vc.play(discord.FFmpegPCMAudio(music_link, **self.ffmpeg_options), after=lambda e: self.next_song())

            """WENT AHEAD AND MOVED NEXT_SONG FUNCTION ABOVE AS I REALIZED IT WOULD NOT WORK IF IT WAS BELOW"""

            """ALL THE FUNCTIONS WE NEEDED FOR OUR COMMANDS TO FUNCTION HAVE BEEN DEFINED NOW ONTO THE COMMAND"""

    @commands.command()
    async def play(self, ctx, *, args):

        # This is the song that the user will search and we will look up 
           using the yt-search function that we made earlier
        query = " ".join(args)

        # If user is not in the voice channel
        voice_channel = ctx.author.voice_channel
        if voice_channel is None:
            await ctx.send("You're not in a voice channel you dummy")
        # If any song in the que is currently paused resume it
        elif self.ispaused == True:
            self.vc.resume()
        
        else:
            # assign song to the search result of the youtube song
            song = self.search_yt(query)

            if type(song) == type(True):
                await ctx.send("Incorrect format of song could not play")

            else:
                await ctx.send("Song added")
                self.musicque.append([song, voice_channel])

                if self.isplaying == False:
                    await self.play_song(ctx)




I was expecting the program to play a song or atleast join thet voice channel but apparently it says the command is not found I've tried changing stuff with the cog but it didn't help so I'm fully lost at what I'm doing wrong. 

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:

    您在类中引入了一个命令,所以它看不到它,将其移出

    class music_player(commands.Cog):
    
    def __init__(self, client):
        self.client = client
    
    @commands.command()
    async def play(self, ctx, *, args):
        .
        .
        .
    

    【讨论】:

    • 我确实初始化了它我有两个单独的文件 music_player.py 和 main.py 我刚刚发送的 commands.command 代码只是 music_player.py 文件的一部分
    • 你能编辑它并提供你的完整代码吗?
    • 另外,您是否粘贴了错误的代码? @commands.command() 必须与 async def play(self, ctx, *, args) 具有相同的缩进:
    • 你去了,添加了完整的代码
    • 另外,现在出现不同的错误,甚至不允许我导入我的文件
    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2019-04-30
    • 2021-05-24
    • 2018-07-24
    • 2022-12-20
    • 2018-05-18
    相关资源
    最近更新 更多