提问者:小点点

不和谐机器人无法读取命令


我一直在遵循这个教程https://www.youtube.com/watch?v=dRHUW_KnHLs如何创建一个不和谐机器人,它认不出我的命令。这是我的主要代码:

import discord
from discord.ext import commands

import os 

from help_cog import help_cog
from music_cog import music_cog

# Command prefix
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!",intents=intents)

@bot.event
async def on_ready():
    print("Bot is up and ready!")

bot.remove_command("help")

bot.add_cog(help_cog(bot))
bot.add_cog(music_cog(bot))    

# Run the client
with open('token.txt', 'r') as file:
    token = file.readlines()[0]
bot.run(token)

以下是我的music_cog:

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

class music_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.is_playing = False
        self.is_paused = False

        self.music_queue = []
        self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
        self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 - reconnect_streamed 1 -reconnected_delay_max 5', 'options': '-vn'}

        self.vc = None
    
def setup(bot):
    bot.add_cog(music_cog(bot))

    def search_yt(self, item):
        with YoutubeDL(self.YDL_OPTIONS) as ydl:
            try:
                info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
            except Exception:
                return False
        return {'source': info['formats'][0]['url'], 'title': info['title']}

    def play_next(self):
        if len(self.music_queue) > 0:
            self.is_playing = True

            m_url = self.music_queue[0][0]['source']

            self.music_queue.pop(0)

            self.vc.play(discord.FFmpegAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
        else:
            self.is_playing = False

    async def play_music(self, ctx):
        if len(self.music_queue) > 0:
            self.is_playing = True
            m_url = self.music_queue[0][0]['sorce']

            if self.vc == None or not self.vc.is_connected():
                self.vc == await self.music_queue[0][1].connect()

                if self.vc == None:
                    await ctx.send("Could not connect to the voice channel :-(")
                    return
            else:
                await self.vc.move_to(self.music_queue[0][1])

            self.music_queue.pop(0)

            self.vc.play(discord.FFmpegPCMAudio(m_url, ** self.FFMPEG_OPTIONS), after=lambda e: self.play_next())

        else:
            self.is_playing = False

    # Play music command
    @commands.command(name="play", aliases=["p", "playing"], help="Play a song from youtube")
    async def play(self, ctx, *args):
        query = " ".join(args)

        voice_channel = ctx.author.voice.channel
        if voice_channel is None:
            await ctx.send("Connect to a voice channel!")
        elif self.is_paused:
            self.vc.resume()
        else:
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send("Could not download the song. Incorrect format, try a different keyword")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])

                if self.is_playing == False:
                    await self.play_musci(ctx)
    
    # Pause music command
    @commands.command(name="pause", aliases=["stop", "paused"], help="Pauses the current song being played")
    async def pause(self, ctx, *args):
        if self.is_playing:
            self.is_playing = False
            self.is_paused = True
            self.vc.pause()
        elif self.is_pause:
            self.is_playing = True
            self.is_paused = False
            self.vc.resume()
    
    # Resume music command
    @commands.command(name="resume", aliases=["r", "unpause"], help="Resumes playing the current song")
    async def resume(self, ctx, *args):
        if self.is_paused:
            self.is_playing = True
            self.is_paused = False
            self.vc.resume()

    # Skip music command
    @commands.command(name="skip", aliases=["s"], help="Skips the currently played song")
    async def skip(self, ctx, *args):
        if self.vc != None and self.vc:
            self.vc.stop()
            await self.play_music(ctx)

    # Queue command
    @commands.command(name="queue", aliases=["q"], help="Displays all the songs currently in the queue")
    async def queue(self, ctx, *args):
        retval = ""

        for i in range(0, len(self.music_queue)):
            if i > 4: break
            retval += self.music_queue[i][0]['title'] + '\n'

        if retval != "":
            await ctx.send(retval)
        else:
            await ctx.send("No music in the queue.")
    
    # Clear command
    @commands.command(name="clear", aliases=["c", "bin"], help="Stops the current song and clears the queue")
    async def clear(self, ctx, *args):
        if self.vc != None and self.is_playing:
            self.vc.stop()
        self.music_queue = []
        await ctx.send("Music queue cleared")

    # Leave command
    @commands.command(name="leave", aliases=["disconnect", "l", "d"], help="Kick the bot from the voice channel")
    async def leave(self, ctx, *args):
        self.is_playing = False
        self.is_paused = False
        await self.vc.disconnect()

以下是我的help_cog:

import discord
from discord.ext import commands

class help_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

        self.help_message = """

通用命令:!help-显示所有可用命令!p-在youtube上查找歌曲并在当前频道播放。如果暂停,将继续播放当前歌曲!q-显示当前音乐队列!跳过-跳过正在播放的当前歌曲!清除-停止音乐并清除队列!离开-断开机器人与语音频道的连接!暂停-暂停正在播放的当前歌曲,如果已经暂停,则恢复播放!恢复-继续播放当前歌曲

"""

        self.text_channel_text = []

def setup(bot):
    bot.add_cog(help_cog(bot))

    @commands.Cog.listener()
    async def on_ready(self):
        for guild in self.bot.guilds:
            for channel in guild.text_channels:
                self.text_channel_text.append(channel)

        await self.send_to_all(self.help_message)

    async def send_to_all(self,msg):
        for text_channel in self.text_channel_text:
            await text_channel.send(msg)

    # Help command
    @commands.command(name='help', help="Displays all the avaiable commands")
    async def help(self, ctx):
        await ctx.send(self.help_message)

我尝试了很多东西,比如路径,试图以不同的方式加载齿轮。我似乎找不到问题所在。


共1个答案

匿名用户

根据您的代码,版本2.0中发生的许多更新包含许多关于如何启动、刷新和保存齿轮文件的更新。让我带你四处看看。

在齿轮添加过程中,您需要设置加载函数,然后设置定义的变量,最后设置异步函数。基本齿轮文件的主要示例如下:

import discord
from discord.ext import commands

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

    @commands.command()
    async def hi(self, ctx):
      await ctx.reply("Hello there!")


async def setup(client): 
  await client.add_cog(basic(client))

现在重要的是将此齿轮文件与on_ready事件一起添加到main.py文件中。它看起来像这样:

intents = discord.Intents.all()
client = commands.Bot(command_prefix="$", intents=intents
)
client.remove_command("help")


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Activity(
            type=discord.ActivityType.playing, name=f"with {len(client.guilds)} servers and {len(client.users)} members"))
  
    await client.load_extension("cogs.basic")

这应该和你一起工作,如果有任何问题发生,请随时评论这篇文章,让我帮助你进一步的帮助。请不要忘记参考API,因为它包含了很多值得知道的东西!