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

如何让Discord机器人每次触发时发送随机内容而非固定重复消息?

解决方案

问题根源

全局作用域下定义的random_q仅在程序启动时执行一次随机计算,后续所有指令触发都复用同一个固定值,不会重新随机选取。

修复方案

将随机取值逻辑移动到指令触发的判断分支内部,每次用户触发smeagol指令时重新执行随机选取操作。

修复后完整代码

import os
import discord
import random

client = discord.Client()

q_list = ('It came to me. My own. My love. My own. My precious', "Lost! Lost! My Precious is lost!!", "Bagginses? What is a Bagginses, precious?", "What has it got in its nasty little pocketses?", "Curse it and crush it! We hates it forever!")

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('smeagol'):
        random_q = random.choice(q_list)
        await message.channel.send(random_q)

bot_token = os.environ['bottoken']

client.run(bot_token)

补充说明

  • random.choice()每次调用都会从传入的序列中独立随机抽取元素,和上一次抽取结果无关联
  • 语录列表q_list保留在全局作用域即可,无需重复声明占用额外资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:24:04