python - python discord 音乐机器人 youtube_dl
问题描述
import discord
import youtube_dl
from discord.ext import commands
-----------------------------------------------
@cat.command(pass_context=True)
async def play(ctx):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice.client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop = client.loop)
voice_channel.play(player)
await ctx.send(f'**Music:**{player.title}')
有没有办法解决这个错误?
AttributeError: 'Guild' object has no attribute 'voice'
解决方案
检查这个工作示例。
import discord
import youtube_dl
from discord.ext import commands
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
def endSong(guild, path):
os.remove(path)
@cat.command(pass_context=True)
async def play(ctx, url):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
voice_client = await channel.connect()
guild = ctx.message.guild
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
file = ydl.extract_info(url, download=True)
path = str(file['title']) + "-" + str(file['id'] + ".mp3")
voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
await ctx.send(f'**Music: **{url}')
可选的,有用的功能
如果你愿意,你可以让你的机器人在歌曲停止播放后离开语音频道。在代码末尾添加:
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
推荐阅读
- big-o - Big-O 渐近增长率排序函数
- reactjs - 从不相关的组件 React 刷新数据
- azure - 互联网无法访问部署在 kubernetes 上的服务
- docker-compose - 如何在 docker-compose 文件中自定义网络名称
- spring - Spring Security - 如何从自定义身份验证提供程序中捕获身份验证异常
- react-native - 检索产品列表并显示它们
- javascript - 如何将时间戳格式化为日历格式日期?
- java - 为什么我从 localhost:8080(正确的端口)上的 REST GET 收到 404 Not found 错误(使用 CL 和 Postman)
- javascript - ES6/Javascript:如何进行高效循环以在数组中创建 json 对象?
- php - 使用 PHP 循环遍历 JSON