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

使用discord.py开发Discord机器人遇空消息发送报错问题

解决Discord机器人发送空消息报错的问题

问题根源

你的get_response函数在未匹配到用户输入时返回None,但Discord消息发送API不允许提交空内容,因此触发了50006错误。

修复方案

1. 保留现有响应函数逻辑

你的响应判断逻辑本身无问题,继续保留返回None的分支即可,同时修正类型注解使其更规范:

from random import randint

def get_response(user_input: str) -> str | None:
    lowered: str = user_input.lower()

    if lowered == '':
        return 'Estás muito silencioso, manda alguma coisa.'
    elif 'ola' in lowered:
        return 'Olá!'
    elif 'como estas' in lowered:
        return 'Bem, obrigado'
    elif 'adeus' in lowered:
        return 'Adeus..'
    elif 'lança um dado' in lowered:
        return f'Calhou {randint(1, 6)}.'
    else:
        return None

2. 修改消息发送逻辑

在调用get_response并发送消息的代码中,增加判断:仅当返回值不为None时,才执行发送操作。

假设你原本的消息处理代码是这样的:

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    response = get_response(message.content)
    await message.channel.send(response)  # 此处因response可能为None报错

修改为:

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    response = get_response(message.content)
    if response is not None:  # 增加非空判断,避免发送空消息
        await message.channel.send(response)

错误原因说明

  • 直接将None或空值传给send()方法时,Discord API会拒绝请求,因为平台不允许发送空消息。
  • 在else分支重新调用函数会引发无限循环,未匹配的输入会反复触发函数调用,最终导致栈溢出或其他异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:19:56