【问题标题】:How to handle the error "command "play" not found" while coding a discord bot with python?使用python编写discord bot时如何处理错误“命令“播放”未找到”?
【发布时间】:2021-11-14 09:42:37
【问题描述】:

我尝试找出一个不和谐的 python 音乐机器人,它在某些方面可以工作,例如,当我告诉它加入或断开连接时它会这样做,但每当我尝试播放音乐时,它都会告诉我这样的命令不存在。我还放了一个错误处理程序,所以它在终端中告诉我没有这样的命令。我观看视频以便我可以帮助自己的那个人没有这个问题。

这是我的代码:

<main.py>
    import discord
    from discord.ext import commands
    #import os
    import music
    
    cogs = [music]
    
    client = commands.Bot(command_prefix='$', intents = discord.Intents.all())
    
    
    
    
    for i in range(len(cogs)):
      cogs[i].setup(client)
    
    @client.event
    async def on_command_error(ctx, error): 
        if isinstance(error, commands.CommandNotFound): 
            em = discord.Embed(title=f"Error!!!", description=f"Command not found.", color=ctx.author.color) 
            await ctx.send(embed=em)
    
    @client.event
    async def on_ready():
        print('Bot is on!')
    
    #@client.event
    #async def on_message(message):
        #if message.author == client.user:
            #return
        #if message.content.startswith('$hello'):
            #await message.channel.send('Hello, sir!')
    
    
    client.run('Token here')
    
<music.py>    

    import discord
    from discord.ext import commands
    import youtube_dl
    
    
    class music(commands.Cog):
      def __init__(self, client):
        self.client = client
      
      
    
        @commands.command()
        async def join(self,ctx):
          if ctx.author.voice is None:
              await ctx.send('You need to be in a vc in order to play music!')
          voice_channel = ctx.author.voice.channel
          if ctx.voice_client is None: 
              await voice_channel.connect()
          else:
            await ctx.voice_client.move_to(voice_channel)  
    
        @commands.command()
        async def disconnect(self,ctx):
            await ctx.voice_client.disconnect()
    
        @commands.command(name="play")     
        async def play(self,ctx,url):
            ctx.voice_client.stop()
            FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
            YDL_OPTIONS = {'format': "bestaudio"}
            vc = ctx.voice_client
    
            with youtube_dl.YoutubeDL (YDL_OPTIONS) as ydl:
                info = ydl.extract_info(url, download=False)
                url2 = info['formats'][0]['url']
                source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
                vc.play(source)
    
        @commands.command()
        async def pausel(self,ctx):
            await ctx.voice_client.pause()
            await ctx.send("Paused")
    
        @commands.command()
        async def resume (self, ctx):
            await ctx.voice_client.resume ()
            await ctx.send("Resumed")
    
    
    
    def setup(client):
      client.add_cog(music(client))

【问题讨论】:

标签: python discord discord.py bots


【解决方案1】:

我不知道为什么从另一个模块添加 cogs 不起作用,但是您可以将音乐类放在 main.py 中,然后在 cog 中添加音乐类:

import discord
from discord.ext import commands
import youtube_dl
#import os
    
    
client = commands.Bot(command_prefix='$', intents = discord.Intents.all())
    

class music(commands.Cog):
  def __init__(self, client):
    self.client = client
      
      
    
  @commands.command()
  async def join(self,ctx):
    if ctx.author.voice is None:
      await ctx.send('You need to be in a vc in order to play music!')
    voice_channel = ctx.author.voice.channel
    if ctx.voice_client is None: 
      await voice_channel.connect()
    else:
      await ctx.voice_client.move_to(voice_channel)  
    
  @commands.command()
  async def disconnect(self,ctx):
    await ctx.voice_client.disconnect()
    
  @commands.command(name="play")     
  async def play(self,ctx,url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format': "bestaudio"}
    vc = ctx.voice_client
    
    with youtube_dl.YoutubeDL (YDL_OPTIONS) as ydl:
      info = ydl.extract_info(url, download=False)
      url2 = info['formats'][0]['url']
      source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
      vc.play(source)
    
  @commands.command()
  async def pausel(self,ctx):
    await ctx.voice_client.pause()
    await ctx.send("Paused")
    
  @commands.command()
  async def resume (self, ctx):
    await ctx.voice_client.resume ()
    await ctx.send("Resumed")
    
@client.event
async def on_command_error(ctx, error): 
  if isinstance(error, commands.CommandNotFound): 
    em = discord.Embed(title=f"Error!!!", description=f"Command not found.", color=ctx.author.color) 
    await ctx.send(embed=em)
    
@client.event
async def on_ready():
  print('Bot is on!')
    
    
client.add_cog(music(client))
client.run('token')

另外,我建议您为命令添加别名,这样输入整个命令就不会很麻烦。

例子:

@commands.command(name="play", aliases = ["p", "sing"])

尝试(prefix)help 查看机器人的所有命令以测试它是否有效。

【讨论】:

  • 谢谢您,先生!这有很大帮助!事实上,我终于成功地建造了它! :)
猜你喜欢
  • 2021-04-30
  • 1970-01-01
  • 2019-11-12
  • 2022-01-14
  • 2021-08-07
  • 1970-01-01
  • 2019-05-20
  • 2020-11-26
  • 1970-01-01
相关资源
最近更新 更多