【问题标题】:discord.py reminder command time conversiondiscord.py 提醒命令时间转换
【发布时间】:2021-07-11 12:56:41
【问题描述】:

我想知道如何为提醒命令进行时间转换,因此 1s 转换为 1 秒 1m 转换为 1 分钟,1h 转换为 1 小时

@client.command(aliases=["reminder"])
async def remind(ctx, remindertime, *, msg):
  seconds=seconds % (24 * 3600)
  hour=seconds // 3600
  seconds %= 3600
  minutes=seconds // 60
  seconds %= 60
  s=seconds
  h=hour
  m=minutes

  await asyncio.sleep(remindertime)
  await ctx.send(f"{ctx.author.mention} You were going to: {msg} and asked me to remind you.")

【问题讨论】:

  • 将所有内容转换为秒,在应该使用datetime 执行时将其添加到数据库中,然后如果时间少于 30 分钟,请在同一命令上等待它,然后如果它更长然后每分钟做一个任务,检查时间是否会执行。
  • @FluxedScript,我相信问题是解析参数并将其转换为时间
  • @Ceres 我知道,但我只是给出建议,为什么它是评论而不是答案

标签: discord discord.py


【解决方案1】:

您可以使用正则表达式来检查字符串是否为时间字符串:

import re

TIME_REGEX = re.compile("([0-9]+)(d|h|m|s)?")
MULTIPLER = {
  "d": 86400,
  "h": 3600,
  "m": 60,
  "s": 1,
  "None": 1 #if they type "30", this will be 30 seconds"
}
match = TIME_REGEX.match(time_string)

if not match:
  return await ctx.send("Please enter a valid time.")

seconds = int(match.groups()[0]) * MULTIPLER.get(str(match.groups()[1]))

【讨论】:

    【解决方案2】:

    你在这里尝试做的方式很困难。这只会浪费时间并让您感到困惑。

    它的完成方式通常非常简单。

    您创建一个字典,然后在其中添加时间转换值。然后创建一个根据要求转换时间的变量。别担心,我刚才会解释它。它会清除你的疑问。 :)

    第 1 步:创建函数。

    这就是提醒功能。

    @client.command(aliases=["reminder"])
    async def remind(ctx, time, *, msg):
    

    第 2 步:创建时间字典。

    这本词典将在执行时间的转换中起主要作用。该字典的 KEYS 将是时间单位,VALUES 将以秒为单位。

    time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
    

    这将用于将我们的时间转换为秒并在 sleep() 函数中使用。

    第 3 步:创建时间转换变量。

    此变量将根据在命令中输入的值以秒为单位。

    remindertime = int(time[0]) * time_conversion[time[-1]]
    

    这首先获取附加到时间输入的数值并将其与字典中的整数 VALUE 相乘。

    第四步:在命令中使用这个时间。

    现在当我们使用这个时间时,我们的命令看起来像:

    @client.command(aliases=["reminder"])
    async def remind(ctx, time, *, msg):
        time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
        remindertime = int(time[0]) * time_conversion[time[-1]]
        await asyncio.sleep(remindertime)
        await ctx.send(f"{ctx.author.mention} You were going to: {msg} and asked me to remind you.")
    

    所以,这是您可以在命令中实际使用时间的方式。

    我很高兴能提供帮助。如果您对我解释的任何内容仍有任何困难,请随时在 cmets 中问我。 :)

    谢谢! :D

    【讨论】:

    • 如果您认为我的回答有效,请接受此回答,以免其他人再浪费时间和精力回答。 :D
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2020-12-18
    • 2021-09-06
    • 2021-02-09
    • 2021-06-02
    • 2021-03-06
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多