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

Discord音乐Bot可正常启动但无法读取或响应用户命令求助

Discord音乐Bot无法响应命令的解决方案

问题根源分析

你的Bot无法响应命令,核心原因是没有正确配置Discord的消息内容意图(message_content),同时代码中存在intents对象误用:

  1. 你创建了自定义intents对象,但初始化client时又调用discord.Intents.default(),导致自定义配置失效。
  2. 当前Discord要求必须显式开启message_content意图才能读取用户消息内容,否则Bot无法获取命令文本。
  3. 代码未排除Bot自身发送的消息,可能引发不必要的逻辑执行。

修复步骤及完整代码

以下是修复后的代码,关键修改点已标注:

import discord
import os
import asyncio
import youtube_dl

TOKEN = "removed"

# 1. 正确配置intents,开启message_content意图
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True  # 必须开启此意图才能读取用户消息

# 2. 使用配置好的intents对象初始化client
client = discord.Client(intents=intents)

voice_clients = {}  # 重命名变量避免局部赋值覆盖全局字典

yt_dl_opts = {'format': 'bestaudio/best'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)

ffmpeg_options = {'options': "-vn"}

@client.event
async def on_ready():
    print("{0.user} is online!".format(client))

@client.event
async def on_message(message):
    # 3. 排除Bot自身的消息,避免循环处理
    if message.author == client.user:
        return

    if message.content.startswith("\play"):
        try:
            url = message.content.split()[1]

            # 4. 修复voice_client变量赋值逻辑
            voice_client = await message.author.voice.channel.connect()
            voice_clients[voice_client.guild.id] = voice_client

            loop = asyncio.get_event_loop()
            data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

            song = data['url']
            player = discord.FFmpegPCMAudio(song, **ffmpeg_options, executable="C:\\ffmpeg\\bin\\ffmpeg.exe")

            voice_client.play(player)

        except Exception as err:
            print(err)
            # 可选:给用户发送错误提示
            await message.channel.send(f"播放出错:{str(err)}")

client.run(TOKEN)

额外配置要求

除代码修改外,需在Discord开发者门户的Bot页面,找到Privileged Gateway Intents板块,手动开启Message Content Intent权限,否则代码配置的意图无法生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:35:20