Discord.py机器人不播放声音

编程语言 2026-07-09

我想做一个可以在收到指令时加入并播放名为“Open the noor”的音效的机器人,用来给朋友开个玩笑。但每次我启动它并执行命令时,它会连接进来却只是卡在那里,甚至不像专门的离开命令那样断开。我都在琢磨到底自己哪里做错了。

日志里没有什么异常,除了没有打印出日志信息“Noored”的那条。机器人也没有离开,这让我觉得它在音频部分卡住了。

所说的命令就是noor命令。

ffmpeg已安装并在系统PATH中。

import discord
from discord.ext import commands
import logging

handler = logging.FileHandler(filename='abyssal_log.log', encoding='utf-8', mode='w')

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='/', intents=intents)
token = #Omitted

@bot.event
async def on_ready():
    print('Ready')

@bot.command()
async def hello(ctx):
    await ctx.send("Hello!")

@bot.command()
async def jabberjoin(ctx):
    await ctx.author.voice.channel.connect()
    print('Bot joined')

@bot.command()
async def jabberleave(ctx):
    await ctx.voice_client.disconnect()
    print('Bot left')

@bot.command()
async def noor(ctx):
    vc = await ctx.author.voice.channel.connect()
    await vc.play(discord.FFmpegPCMAudio('noor.mp3'))
    await ctx.voice_client.disconnect()
    print('Noored')

bot.run(token, log_handler=handler)

解决方案

Remove await from the vc.play() line. Because vc.play() executes instantly in the background, you must use an asynchronous asyncio.sleep() delay to let the audio finish playing before the bot disconnects.

New noor code:

import asyncio  # Add this import at the top of your file

@bot.command()
async def noor(ctx):
    vc = await ctx.author.voice.channel.connect()

    # Removed the await from vc.play
    vc.play(discord.FFmpegPCMAudio('noor.mp3')) 

    # Wait for the duration of your audio file (e.g., 3 seconds)
    await asyncio.sleep(3) 

    await ctx.voice_client.disconnect()
    print('Noored')
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章