如何将字符串解析为毫秒?

电脑极客12

我在 StackOverflow 上寻找其他答案但没有运气。

我在 discord.py 中有一个静音命令,如下所示:

@client.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, time: typing.Optional[str], *, reason = None):
    guild = ctx.guild
    for role in guild.roles:
        if role.name == "Muted":
            await member.add_roles(role)
            await ctx.send("{} has has been muted because {}!" .format(member.username + "#" + member.discriminator, reason))

如何将时间参数设为毫秒?类似于msnode.js 中模块。

例如,我希望将 的持续时间>mute @user 1h some reason解析为 3600000 毫秒。

迈克尔·比安科尼

我将假设格式是1h, 1m and 1s.

我们从字符串中提取第三个项目(这不会执行错误检查以确保它有 3 个项目)

raw_time = command.split()[2]  # Assuming the command is ">mute @user 1h..."
value = int(raw_time[0:-1])  # All but the last character
time_type = raw_time[-1]   # The last character

然后,我们评估它是小时、分钟还是秒:

if time_type == 'h':
    return value * 3600000
elif time_type == 'm':
    return value * 60000
else:
    return value * 1000

您可以将其扩展为包括任何时间段(例如毫秒)。但是,它不执行任何错误检查。要仔细检查给定的命令是否适用于此,您可以通过以下正则表达式运行它:

if re.match('(\S+\s+){2}\d+(h|m|s).*', command) is not None:

    raw_time = command.split()[2]  # Assuming the command is ">mute @user 1h..."
    value = int(raw_time[0:-1])  # All but the last character
    time_type = raw_time[-1]   # The last character
    if time_type == 'h':
        return value * 3600000
    elif time_type == 'm':
        return value * 60000
    else:
        return value * 1000
else:
    # ...

        

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章