You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py机器人连接语音频道时程序终止问题求助

解决Discord.py机器人连接语音频道后程序终止的问题

问题原因分析

你的代码在await voice_channel.connect()后无输出且终止,核心原因是该调用抛出了未捕获的异常(比如权限不足、频道ID无效、网络波动等),导致on_ready协程直接崩溃,进而终止整个程序。此外代码还存在几个潜在漏洞:

  • 未校验voice_channel对象是否获取成功,若VoiceChannelIdHere无效会直接触发后续报错
  • 语音客户端的判断逻辑不够精准,可能出现重复连接或误判的情况
  • 全程无异常捕获机制,任何环节出错都会直接终止程序

修复步骤

1. 增加异常捕获逻辑

在连接语音和播放音频的关键代码块外层添加try-except,捕获并打印异常,避免程序直接崩溃。

2. 优化语音客户端检查

直接通过目标公会获取语音客户端,判断逻辑更准确。

3. 提前校验核心对象有效性

先确认voice_channel和目标公会是否存在,避免后续无效调用。

修复后的完整代码

import discord
from discord.ext import commands
import asyncio
import os

intents = discord.Intents.all()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)

@bot.event
async def on_ready():
    voice_channel_id = VoiceChannelIdHere  # 替换为实际频道ID
    voice_channel = bot.get_channel(voice_channel_id)
    if not voice_channel:
        print(f"无法找到ID为{voice_channel_id}的语音频道")
        return
    
    ffmpegPath = r"C:\ffmpeg-master-latest-win64-gpl\ffmpeg-master-latest-win64-gpl\bin\ffmpeg.exe"
    target_guild = discord.utils.get(bot.guilds, name="Sui Ape DAO")
    if not target_guild:
        print("无法找到名为Sui Ape DAO的服务器")
        return

    while True:
        for filename in os.listdir("Music"):
            # 通过目标公会获取语音客户端
            vc = discord.utils.get(bot.voice_clients, guild=target_guild)
            if not vc:
                print(1)
                try:
                    vc = await voice_channel.connect()
                    print(2)
                except Exception as e:
                    print(f"连接语音频道失败: {str(e)}")
                    await asyncio.sleep(5)
                    continue

            try:
                # 加载音频文件并播放
                audio_source = discord.FFmpegPCMAudio(executable=ffmpegPath, source=f"Music\\{filename}")
                vc.source = discord.PCMVolumeTransformer(audio_source, volume=0.4)
                vc.play(vc.source)

                while vc.is_playing():
                    await asyncio.sleep(1)
            except Exception as e:
                print(f"播放音频失败: {str(e)}")
                # 播放出错时断开连接,避免残留无效客户端
                if vc.is_connected():
                    await vc.disconnect()
                await asyncio.sleep(5)

        await asyncio.sleep(4)

if __name__ == "__main__":
    print("Radio")
    bot.run('MyTokenHere')

额外排查点

  • 确认机器人在目标服务器中拥有连接语音频道和播放音频的权限
  • 检查ffmpegPath是否正确,ffmpeg可执行文件是否存在
  • 验证Music文件夹中的音频文件格式是否被ffmpeg支持(如MP3、WAV等)
  • 前往Discord开发者门户,确认机器人的所有intents已启用

内容的提问来源于stack exchange,提问作者FDFD FDFD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:33:09