Discord.py 实现支持多单位组合时长的Tempmute临时禁言命令咨询
解决方案
你可以通过正则表达式提取时长字符串中所有的「数值+单位」组合,分别转换为秒数累加即可支持多单位组合的输入格式,同时还修复了原代码中存在的几处逻辑错误。
核心改动说明
- 引入正则匹配逻辑替换原有单单位提取逻辑,支持任意顺序/数量的d/h/m/s单位组合
- 修复原代码中字符串未转整数直接计算、角色变量名不匹配、创建角色时的缩进错误问题
- 新增全格式校验,避免输入含非法字符的时长参数
完整修改后代码
import re import asyncio import discord from discord.ext import commands @bot.command(aliases=['tempmute']) @commands.has_permissions(manage_messages=True) async def mute(ctx, member: discord.Member=None, time=None, *, reason=None): if not member: await ctx.send("You must mention a member to mute!") return if not time: await ctx.send("You must mention a time!") return if not reason: reason = "No reason given" # 多单位时长转换逻辑 try: total_seconds = 0 # 匹配所有数字加s/m/h/d单位的组合 matches = re.findall(r'(\d+)([smhd])', time.lower()) if not matches: await ctx.send("Invalid duration input") return # 校验整个输入字符串是否全部为合法时长格式 parsed_str = ''.join([f"{num}{unit}" for num, unit in matches]) if parsed_str != time.lower(): await ctx.send("Invalid duration input") return # 累加计算总秒数 for num_str, unit in matches: num = int(num_str) if unit == "s": total_seconds += num elif unit == "m": total_seconds += num * 60 elif unit == "h": total_seconds += num * 3600 elif unit == "d": total_seconds += num * 86400 except Exception as e: print(e) await ctx.send("Invalid time input") return # 禁言角色处理逻辑 guild = ctx.guild Muted = discord.utils.get(guild.roles, name="Muted") if not Muted: Muted = await guild.create_role(name="Muted") for channel in guild.channels: await channel.set_permissions(Muted, speak=False, send_messages=False, read_message_history=True, read_messages=False) # 执行禁言 await member.add_roles(Muted, reason=reason) muted_embed = discord.Embed(title="Muted a user", description=f"{member.mention} Was muted by {ctx.author.mention} for {reason} to {time}") await ctx.send(embed=muted_embed) # 定时解除禁言 await asyncio.sleep(total_seconds) await member.remove_roles(Muted) unmute_embed = discord.Embed(title="Mute over!", description=f'{ctx.author.mention} muted to {member.mention} for {reason} is over after {time}') await ctx.send(embed=unmute_embed)
修改后即可支持!tempmute @user 1d3h10m1s这类多单位组合的输入格式,也兼容原来的单单位输入用法。
内容的提问来源于stack exchange,提问作者CodingLion
相关产品推荐
相关产品推荐

