discord.py音乐播放Cog多命令别名功能代码修复求助
修复方案
你代码里存在多个语法错误和discord.py Cog规范使用错误,按以下方式修改即可正常使用双别名触发播放命令:
核心修改点
- Cog类内部定义命令不能使用
@client.command()装饰器,统一替换为@commands.command() - 命令别名直接通过装饰器的
aliases参数配置,你写的async def {playcmd}属于无效Python语法,不需要通过变量拼接函数名 - Cog类内的所有方法第一个参数必须是
self,你原有代码里所有命令函数都缺失该参数,运行会直接报错 - 修正代码缩进问题,Python对缩进要求严格,原有
__init__方法缩进不匹配会触发语法错误
修改后完整代码
import discord from discord.ext import commands import youtube_dl from urllib import parse, request import re class music(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def join(self, ctx): if ctx.author.voice: channel = ctx.message.author.voice.channel await channel.connect() else: await ctx.send("First join voice channel") @commands.command() async def leave(self, ctx): if ctx.voice_client: await ctx.guild.voice_client.disconnect() await ctx.send("Ok") # 这里配置命令别名,aliases里的内容都可以触发该命令 @commands.command(name="play", aliases=["p"]) async def play(self, ctx, *, search): if ctx.voice_client: print("already on voice channel") else: channel = ctx.message.author.voice.channel await channel.connect() query_string = parse.urlencode({'search_query': search}) html_content = request.urlopen('http://www.youtube.com/results?' + query_string) search_content= html_content.read().decode() search_results = re.findall(r'\/watch\?v=\w+', search_content) await ctx.send('Now playing: https://www.youtube.com' + search_results[0]) url = 'https://www.youtube.com' + search_results[0] 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 pause(self, ctx): await ctx.send("paused") await ctx.voice_client.pause() @commands.command() async def resume(self, ctx): await ctx.send("resumed") await ctx.voice_client.resume() @commands.command() async def youtube(self, ctx, *, search): query_string = parse.urlencode({'search_query': search}) html_content = request.urlopen('http://www.youtube.com/results?' + query_string) search_content= html_content.read().decode() search_results = re.findall(r'\/watch\?v=\w+', search_content) await ctx.send('https://www.youtube.com' + search_results[0]) def setup(client): client.add_cog(music(client))
内容的提问来源于stack exchange,提问作者sionka
相关产品推荐
相关产品推荐

