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

如何让discord.py机器人随机发送消息并修复指令失效问题

问题核心原因

  1. 自定义on_message事件会覆盖Discord.py等框架默认的指令处理流程,未手动触发命令处理的情况下,所有注册的前缀指令都会无法响应。
  2. 现有随机判断逻辑存在设计缺陷:每个分支都重新生成随机数,既不符合「单条消息仅生成一次随机数匹配回复」的设计预期,也大幅降低了回复触发概率,还存在冗余性能消耗。

修复方案

调整逻辑,单次消息仅生成一次随机数,同时在事件末尾添加指令处理调用,修复后的代码如下:

@client.event
async def on_message(message):
    # 过滤机器人自身发送的消息,避免死循环
    if message.author == client.user:
        return

    # 单条消息仅生成一次随机数
    random_val = random.randint(0, 500)
    
    if random_val == 42:
        await message.channel.send("bruh")
    elif random_val == 69:
        await message.channel.send("good plan")
    elif random_val == 99:
        await message.channel.send("awwww hellll nahhhhhhh")
    elif random_val == 76:
        await message.channel.send("I think we should see other people...")
    elif random_val == 25:
        await message.channel.send("no.")
    elif random_val == 56:
        await message.channel.send("bad idea")

    # 触发框架默认指令处理逻辑,原有指令即可正常生效
    await client.process_commands(message)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:45:09