как мне заставить моего бота discord.py воспроизводить mp3 в голосовом канале? - PullRequest
0 голосов
/ 04 декабря 2018

Я новичок в Python, и недавно я начал создавать бот-диск для некоторых друзей и меня. Идея состоит в том, чтобы напечатать! Startq и заставить бота присоединиться к каналу, воспроизводить mp3-файл, который локально хранится вта же папка, в которой находится bot.py.

import discord, chalk
from discord.ext import commands
import time
import asyncio

bot = commands.Bot(command_prefix = "!")

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

@bot.command()
async def q5(ctx):
    await ctx.send("@here QUEUE STARTING IN 5 MINUTES")

@bot.command()
async def q3(ctx):
    await ctx.send("@here QUEUE STARTING IN 3 MINUTES")

@bot.command()
async def q1(ctx):
    await ctx.send("@here QUEUE STARTING IN 1 MINUTES")

@bot.command()
async def ping(ctx):
    ping_ = bot.latency
    ping =  round(ping_ * 1000)
    await ctx.send(f"my ping is {ping}ms")

@bot.command()
async def startq(ctx):
    voicechannel = discord.utils.get(ctx.guild.channels, name='queue')
    vc = await voicechannel.connect()
    vc.play(discord.FFmpegPCMAudio("countdown.mp3"), after=lambda e: print('done', e))
    bot.run('TOKEN')

Пока мой бот нормально подключается к каналу, но на самом деле он не воспроизводит mp3.Я спросил бесчисленных людей в "Неофициальных Discord API Discord" и нескольких других программах Discords, но я пока не получил ответа.

Ответы [ 2 ]

0 голосов
/ 25 марта 2019

Вот как вы это сделаете для переписанной версии, которую я использую для моего бота для воспроизведения mp3-файлов.Вам также необходимо загрузить opus, что просто, а также иметь FFMPEG.

OPUS_LIBS = ['libopus-0.x86.dll', 'libopus-0.x64.dll', 'libopus-0.dll', 'libopus.so.0', 'libopus.0.dylib']


def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass

        raise RuntimeError('Could not load an opus lib. Tried %s' % (', '.join(opus_libs)))
@bot.command(aliases=['paly', 'queue', 'que'])
async def play(ctx):
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
    audio_source = discord.FFmpegPCMAudio('vuvuzela.mp3')
    if not voice_client.is_playing():
        voice_client.play(audio_source, after=None)
0 голосов
/ 15 декабря 2018

Я сделал что-то похожее с моим ботом разногласий, вот пример кода, на который вы можете ссылаться.Если вы воспроизводите mp3-файлы, обязательно установите ffmpeg, я следовал приведенным здесь инструкциям при настройке своего бота https://github.com/adaptlearning/adapt_authoring/wiki/Installing-FFmpeg

@client.command(
    name='vuvuzela',
    description='Plays an awful vuvuzela in the voice channel',
    pass_context=True,
)
async def vuvuzela(context):
    # grab the user who sent the command
    user=context.message.author
    voice_channel=user.voice.voice_channel
    channel=None
    # only play music if user is in a voice channel
    if voice_channel!= None:
        # grab user's voice channel
        channel=voice_channel.name
        await client.say('User is in channel: '+ channel)
        # create StreamPlayer
        vc= await client.join_voice_channel(voice_channel)
        player = vc.create_ffmpeg_player('vuvuzela.mp3', after=lambda: print('done'))
        player.start()
        while not player.is_done():
            await asyncio.sleep(1)
        # disconnect after the player has finished
        player.stop()
        await vc.disconnect()
    else:
        await client.say('User is not in a channel.')
...