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

Discord抽奖机器人剩余时间显示单位修改咨询

你只需要新增一个秒数转易读格式的工具函数,再修改原有 embed 里的剩余时间显示逻辑即可,具体调整如下:

第一步:新增秒数格式化函数

在原有代码的convert函数下方新增如下函数:

def format_seconds(total_seconds):
    # 定义时间单位和对应的秒数
    time_units = [
        ("天", 86400),
        ("小时", 3600),
        ("分钟", 60),
        ("秒", 1)
    ]
    result = []
    remaining = int(total_seconds)
    for unit, sec_count in time_units:
        if remaining >= sec_count:
            unit_val = remaining // sec_count
            result.append(f"{unit_val}{unit}")
            remaining = remaining % sec_count
        # 可选配置:最多显示2级单位,比如5天2小时就不再显示分钟秒,要完整显示可以删掉这两行
        if len(result) >= 2:
            break
    return "".join(result) if result else "0秒"

如果偏好带单位后缀的英文简写格式(比如5d 2h),可以把上面time_units里的中文换成s/m/h/d即可。

第二步:修改抽奖创建逻辑里的显示部分

找到gcreate函数里创建Embed的代码,把原来的剩余时间显示替换成调用新的格式化函数:

# 原来的写法
# description=f"Hosted by - {ctx.author.mention} React with :tada: to enter! Time Remaining: **{time}** seconds",
# 修改为
description=f"Hosted by - {ctx.author.mention} React with :tada: to enter! Time Remaining: **{format_seconds(time)}**",

可选补充:实现剩余时间实时更新

你当前的代码创建完Embed之后就不会再修改了,如果需要让剩余时间动态刷新,可以在发送完抽奖消息后加一个定时循环,每隔固定时间(比如1分钟)编辑一次Embed的剩余时间字段即可。

调整后的完整可运行代码如下:

import discord
import asyncio
import random
from discord.ext import commands

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())

def convert(time):
    pos = ["s", "m", "h", "d"]
    time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
    unit = time[-1]
    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2
    return val * time_dict[unit]

def format_seconds(total_seconds):
    time_units = [
        ("天", 86400),
        ("小时", 3600),
        ("分钟", 60),
        ("秒", 1)
    ]
    result = []
    remaining = int(total_seconds)
    for unit, sec_count in time_units:
        if remaining >= sec_count:
            unit_val = remaining // sec_count
            result.append(f"{unit_val}{unit}")
            remaining = remaining % sec_count
        if len(result) >= 2:
            break
    return "".join(result) if result else "0秒"

@client.command()
@commands.has_permissions(manage_messages=True)
async def gcreate(ctx, time: str, *, prize: str):
    total_sec = convert(time)
    if total_sec < 0:
        await ctx.send("时间格式错误,请使用类似 5d/12h/30m/60s 的格式")
        return

    embed = discord.Embed(title=prize,
                          description=f"Hosted by - {ctx.author.mention} React with :tada: to enter! Time Remaining: **{format_seconds(total_sec)}**",
                          colour = discord.Colour.purple())

    msg = await ctx.channel.send(content=":tada: **GIVEAWAY** :tada:", embed=embed)
    await msg.add_reaction("🎉")

    await asyncio.sleep(total_sec)

    new_msg = await ctx.channel.fetch_message(msg.id)
    user_list = [user for user in await new_msg.reactions[0].users().flatten() if user != client.user]  
    if len(user_list) == 0:
        await ctx.send("No one reacted.")
    else:
        winner = random.choice(user_list)
        await ctx.send(f"{winner.mention} You have won the {prize}!")

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:09:03