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

Python Discord Bot查找数字停止功能及返回带括号数字问题咨询

返回结果带括号的问题

random.choices() 方法返回值为列表类型,你直接将其作为消息发送时,会把列表的方括号和格式一起输出。
你可以换成返回单个元素的random.choice()方法,或者取random.choices()返回结果的第一个元素,示例:

# 方法1:用random.choice(无权重参数时直接用这个即可)
await message.channel.send(random.choice(list4))
# 方法2:保留权重规则,取choices结果的第一个元素
await message.channel.send(random.choices(list4, weights=(100, 30, 59, 40))[0])

另外你现有代码的if判断逻辑存在错误:or ("1") 的写法在Python中会被判定为永久True,导致无论消息内容是什么都会触发该分支逻辑,正确的多前缀判断写法如下:

# startswith支持传入元组匹配多个前缀
if message.content.startswith(('FindNumber2', '1', '3', '4')):

找到数字2自动停止的问题

你可以在拿到随机返回值后做判断,若结果为'2',直接调用机器人实例的close()方法终止运行即可,完整修正后的逻辑示例:

import random, time
import discord

client = discord.Client(intents=discord.Intents.all())
list4 = ['1', '2', '3', '4']

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # 修正后的多前缀判断
    if message.content.startswith(('FindNumber2', '1', '3', '4')):
        time.sleep(2)
        # 拿到带权重的随机结果
        res = random.choices(list4, weights=(100, 30, 59, 40))[0]
        await message.channel.send(res)
        # 结果为2就停止机器人
        if res == '2':
            await client.close()

client.run('你的机器人Token')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:48:03