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

discord.py Giveaway命令回答完3个问题后不显示完整抽奖Embed

问题修复方案

根因定位

  • 代码存在缩进错误,负责解析频道ID的return语句位置错误,无论频道ID是否解析成功,函数都会直接提前退出,后续生成抽奖Embed、推送抽奖消息的逻辑完全不会执行。
  • 原有代码中错误的片段如下:
try:
        c_id = int(answers[0][2:-1])
except:
    await ctx.send(f"你没有正确提及频道,格式应该是 {ctx.channel.mention},请重试")
return # 这里缩进错误,和except同级,不管try是否成功都会执行return

修复后完整代码

import discord
import asyncio
import random
# 注意要确保你自己写的convert时间转换函数存在且可用

@bot.command() # 确保加上命令装饰器注册该命令
async def giveaway(ctx):
    await ctx.send("🎉 我们来创建新的抽奖!请在15秒内回答以下问题")
    questions = ["抽奖应该在哪个频道举办?", "抽奖时长设置为多少?(单位:S秒|M分|H小时|D天)", "抽奖的奖品是什么?"]
    answers = []
    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel

    for i, question in enumerate(questions):
            embed = discord.Embed(title=f"问题 {i+1}", description=question)
            await ctx.send(embed=embed)
            try:
                msg = await bot.wait_for('message', timeout=15.0, check=check)
            except asyncio.TimeoutError:
                await ctx.send("你没有及时回答,已取消操作")
                return
            answers.append(msg.content)
  
    try:
            c_id = int(answers[0][2:-1])
    except:
        await ctx.send(f"你没有正确提及频道,格式应该是 {ctx.channel.mention},请重试")
        return # 把return缩进放到except块里面,只有解析失败才会提前退出
  
    channel = bot.get_channel(c_id)

    time = convert(answers[1]) # 请确保你的convert函数已正确定义
    if time == -1:
            await ctx.send("你输入的时间单位不正确,请使用(S|M|H|D)")
            return
    elif time == -2:
            await ctx.send("时间数值必须为整数")
            return

    prize = answers[2]

    await ctx.send(f"抽奖将在 {channel.mention} 举办,时长为 {answers[1]}")

    embed = discord.Embed(title=":tada: 免费抽奖活动开始啦!:tada:", description=f"**奖品:**{prize}\n**主办方:** {ctx.author.mention}\n")

    embed.add_field(name = "主办方", value = ctx.author.mention)
    embed.set_footer(text = f"{answers[1]} 后结束抽奖")

    my_msg = await channel.send(embed=embed)

    await my_msg.add_reaction("🎉")

    await asyncio.sleep(time)

    new_msg = await channel.fetch_message(my_msg.id)

    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))

    winner = random.choice(users)

    await channel.send(f"恭喜 {winner.mention} 获得了奖品 {prize}!")

其他注意事项

  • 请确保已经正确导入了discord、asyncio、random依赖
  • 请确保你自己实现的convert时间转换函数逻辑正确,返回值符合预期
  • 请确保机器人有目标频道的发消息、添加反应权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:15:02