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

使用discord.py开发Discord机器人时接收空字符串而非消息的问题

问题解决:Discord机器人接收空消息字符串

核心原因

Discord.py v2.0及以上版本中,message_content 意图默认关闭,导致机器人无法读取消息内容,只能获取空字符串。同时需要在Discord开发者后台手动开启该权限。

解决步骤

1. 在Discord开发者后台开启消息内容权限

  • 打开Discord开发者后台,找到你的机器人应用
  • 进入Bot选项卡,向下滚动找到Privileged Gateway Intents
  • 开启Message Content Intent开关

2. 修改bot.py中的Intents配置

将原来的默认Intents配置替换为包含消息内容权限的版本:

修改后的bot.py关键代码片段:

def run_discord_bot():
    TOKEN = 'Our_Token'
    # 配置Intents,开启消息内容读取权限
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    # 后续事件处理代码保持不变...

额外优化(可选)

在send_message函数中补充处理无匹配响应的情况,避免因response为None导致报错:

async def send_message(message, user_message, is_private):
    try:
        response = responses.handle_response(user_message)
        # 无匹配规则时返回默认提示
        if response is None:
            response = 'Yeah, I don\'t know. Try typing "!help".'
        await message.author.send(response) if is_private else await message.channel.send(response)

    except Exception as e:
        print(e)

验证修改

重启机器人后发送消息,控制台将正常打印消息内容,机器人也会按预设规则返回对应响应。

内容的提问来源于stack exchange,提问作者Mitko.Vtori

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:25:16