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

如何在discord.py slash commands中要求用户输入预定义时间格式

时间格式提示示例

预定义时间格式输入的Slash Command实现方案

1. 前端输入引导配置

  • 前往对应平台(Discord/Slack/飞书等)的开发者后台,找到对应slash command的参数配置项,给时间参数的描述字段明确标注格式要求,示例描述:时间长度,格式为「数字+单位」,支持单位:s(秒)、m(分钟)、h(小时)、d(天)、w(周),示例:1m、3w
  • 如果平台支持参数自动补全(如Discord),可以绑定autocomplete回调,用户输入时实时校验格式、推送合法示例:
// Discord.js 自动补全回调示例
client.on('interactionCreate', async interaction => {
  if (!interaction.isAutocomplete()) return;
  if (interaction.commandName === '你的目标命令名') {
    const inputVal = interaction.options.getFocused();
    const timeReg = /^\d+[smhdw]$/i;
    const options = [];
    if (timeReg.test(inputVal)) {
      options.push({ name: inputVal, value: inputVal });
    } else {
      // 推送默认参考示例
      ['1m', '15m', '1h', '1d', '3w'].forEach(item => options.push({ name: item, value: item }));
    }
    await interaction.respond(options);
  }
});

2. 后台强制校验

用户提交命令后,后台先对时间参数做格式校验,不匹配则直接返回清晰的错误提示,引导用户重新输入:

错误提示示例:您输入的时间格式不合法,请按照「数字+单位」格式输入,支持单位:s(秒)、m(分钟)、h(小时)、d(天)、w(周),例如输入3w代表3周。

3. 合法时间格式解析

校验通过后,用正则拆分数字和单位,转换为你需要的时间格式(如时间戳、秒数)即可:

  • 匹配正则:/^(\d+)([smhdw])$/i
  • 单位对应换算系数(转毫秒):
    • s: 1000
    • m: 60 * 1000
    • h: 60 * 60 * 1000
    • d: 24 * 60 * 60 * 1000
    • w: 7 * 24 * 60 * 60 * 1000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:45:00