问题描述
因此,我试图将Music bot功能集成到我的discord bot中,我将链接我怀疑有问题的代码。
import discord
from discord.ext import commands
import praw
import random
import os
import json
import ffmpeg
import youtube_dl
# music command
@client.command(pass_context=true)
async def play(ctx,url):
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = await voice.client.create_ytdl_player(url)
players[server.id] = player
player.start()
这是错误。
Traceback (most recent call last):
File "C:\Users\Trayambak\Desktop\Akihiko\bot.py",line 8,in <module>
import ffmpeg
ModuleNotFoundError: No module named 'ffmpeg'
[Finished in 52.353s]
解决方法
- 您不必导入FFmpeg。
- 服务器现在更改为 guild 。
- FFmpeg和youtube_dl进行了很大的更改,因此您应该检查我发布的可正常运行的音乐bot代码,并将其与您的代码进行比较。
import discord
import youtube_dl
from discord.ext import commands
Token = "your token here"
client = commands.Bot(command_prefix = "!!") #you can change your commands prefix here
ydl_opts = {
'format': 'bestaudio/best','postprocessors': [{
'key': 'FFmpegExtractAudio','preferredcodec': 'mp3','preferredquality': '192',}],}
def endSong(guild,path):
os.remove(path)
@client.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}')
client.run(Token)
可选的,有用的功能
如果您愿意,可以在歌曲/音乐停止播放后使机器人离开语音通道。在代码末尾添加此代码(在 client.run(Token) !!!之前)
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
使用方法
只需编写: !! play https://www.youtube.com/watch?v=dQw4w9WgXcQ #只记得您必须粘贴链接
,首先,我不知道名为ffmpeg
的模块。也许您已经创建了自己的邮件,但从我收到的消息中得知并非如此。
FFmpeg是基于许多C库构建的命令行工具。它本身不是Python包。我知道在Python中使用它的两种方法:
-
您可以在运行代码的计算机上安装FFmpeg,并运行本机FFmpeg命令。 (此tutorial中的信息)
-
其他选项,您使用
ffmpeg-python
(链接到pypi和git)。这是一个python绑定库,可在Python函数和FFmpeg函数/命令之间创建链接。
每种方法都有其优缺点。但我可以总结一下: 如果您想构建一个没有关键用途的基于FFmpeg的简单工具,请使用Python绑定,它是最简单的imo。如果您想很快在商业上使用FFmpeg,请花点时间学习它的真正工作原理并使用命令行。