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

如何为Discord机器人的/coinflip斜杠命令设置两种选项?

解决Discord斜杠命令/coinflip添加选项的问题

你的代码目前有两个核心问题:一是没给用户提供选择“Kopf”或“Zahl”的交互入口,二是胜负判断逻辑完全错误——if choices == botchoice是拿整个列表和随机生成的字符串比较,永远不会成立,导致用户永远无法获胜。

以下是修复后的完整代码,同时实现了用户选择功能:

import random
import os
import discord
from discord import app_commands

@bot.tree.command(name="coinflip", description="Wirf eine Münze und schau was passiert!")
@app_commands.choices(choice=[
    app_commands.Choice(name="Kopf", value="kopf"),
    app_commands.Choice(name="Zahl", value="zahl")
])
async def coinflip(interaction: discord.Interaction, choice: app_commands.Choice[str]):
    userid = str(interaction.user.id)
    bot_choice = random.choice(["kopf", "zahl"])
    filename = f"database/{userid}.txt"
    
    # 判断用户是否猜对结果
    if choice.value == bot_choice:
        # 读取现有金币或初始化新用户金币
        if os.path.isfile(filename):
            with open(filename, "r") as file:
                coins = int(file.read())
            coins += 25
        else:
            coins = 25
        
        # 保存更新后的金币数
        with open(filename, "w") as file:
            file.write(str(coins))
        
        await interaction.response.send_message(f"Du gewinnst 25 Münzen! Das Ergebnis war {bot_choice}.", ephemeral=True)
    else:
        await interaction.response.send_message(f"Leider verloren! Das Ergebnis war {bot_choice}.", ephemeral=True)

关键改动说明:

  • 添加了@app_commands.choices装饰器,定义了“Kopf”和“Zahl”两个可选选项,用户调用斜杠命令时会看到对应的选择项。
  • 函数新增choice参数,用于接收用户的选择,choice.value会对应到我们定义的kopf或zahl字符串。
  • 修正胜负判断逻辑:将choices == botchoice改为choice.value == bot_choice,正确对比用户选择和机器人随机结果。
  • 优化金币读写逻辑,减少重复代码,先统一计算出最终金币数,再一次性写入文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:42:12