如何为Discord机器人gstart抽奖命令添加多单位时间转换器?
为Discord抽奖命令添加时间转换器功能
要让gstart命令支持多种时间单位(如1s=1秒、1day=86400秒),可以通过自定义时间解析函数实现,具体修改步骤如下:
1. 编写时间解析函数
添加一个函数来解析带单位的时间字符串,将其转换为总秒数:
import re def parse_time(time_str): # 匹配数字+单位的格式,支持s/m/h/d/day等单位 match = re.match(r'^(\d+)(s|m|h|d|day)$', time_str.lower()) if not match: raise ValueError("无效的时间格式!请使用如1s/5m/2h/1d的格式") amount = int(match.group(1)) unit = match.group(2) # 单位转秒数映射 unit_map = { 's': 1, 'm': 60, 'h': 3600, 'd': 86400, 'day': 86400 } return amount * unit_map[unit]
2. 修改抽奖命令代码
将原命令的mins: int参数改为duration: str,并替换时间相关逻辑:
@client.command(description="Starts a giveaway.") @has_permissions(manage_messages=True) async def gstart(ctx, duration: str, *, prize: str): global users, new_msg try: await ctx.message.delete() # 解析时间为总秒数 total_seconds = parse_time(duration) em = discord.Embed( title=f"<a:fun:1052215771738165269> {prize} <a:fun:1052215771738165269>", color=discord.Colour.random() ) timestamp = time.time() + total_seconds em.set_footer(text=f"Started by {ctx.author}") em.add_field( name=f"** **", value=f"**Ends at**: <t:{int(timestamp)}:f> or <t:{int(timestamp)}:R> \n **Prize**: {prize} \n **Hosted by**: {ctx.author.mention}", inline=False ) my_msg = await ctx.send(embed=em) await my_msg.add_reaction("🎉") # 等待抽奖结束 await asyncio.sleep(total_seconds) new_msg = await ctx.channel.fetch_message(my_msg.id) users = [user async for user in new_msg.reactions[0].users()] users.pop(users.index(client.user)) if not users: await ctx.send(f"抽奖**{prize}**没有参与者,取消开奖!") return winner = random.choice(users) await ctx.send(f'Congratulations {winner.mention} won **{prize}**! Hosted by {ctx.author.mention}') except ValueError as ve: await ctx.send(ve) except Exception as er: await ctx.send(f"出错了:{er}")
关键修改点说明
- 参数类型替换:将原有的
mins: int改为duration: str,支持接收带单位的时间输入 - 时间解析逻辑:通过
parse_time函数将字符串转换为总秒数,兼容s(秒)、m(分钟)、h(小时)、d/day(天)多种单位 - 等待逻辑调整:
asyncio.sleep直接使用解析后的总秒数,无需再做单位转换 - 异常处理优化:针对无效时间格式抛出明确提示,同时新增无参与者的边界情况处理
内容的提问来源于stack exchange,提问作者I am goku
相关产品推荐
相关产品推荐

