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

Node.js开发Discord机器人时间转Unix戳遇表情转换问题求助

解决Discord机器人斜杠命令中时间字符串被表情替换的问题

问题根源

你的服务器存在名为18的自定义表情,当用户输入包含:18:的时间字符串(如12:18:30)时,Discord会自动将:18:替换为该表情的结构化ID格式(例如<:18:123456>),且这个替换过程是在请求到达机器人之前完成的——所以你在代码里用反引号包裹的操作完全无效,因为拿到的已经是被篡改后的内容。

解决方案

在机器人获取到时间参数后,先将Discord替换的表情格式还原为原始的冒号文本,再进行时间解析:

  1. 添加表情还原逻辑
    使用正则表达式匹配Discord自定义表情的格式,将其替换回原始的:emoji_name:形式:

    const timeString = options.getString("time");
    // 还原被替换的表情为原始冒号格式
    const cleanedTimeString = timeString.replace(/<:([^:]+):\d+>/g, ":$1:");
    
  2. 修正时间格式的潜在问题
    你的代码中currentMonth直接使用了currentDate.getMonth(),而这个方法返回的是0-11的数字(0代表1月),但后续拼接YYYY-MM-DD格式需要的是1-12的月份,会导致moment解析失败。需要修正为:

    const currentMonth = month || (currentDate.getMonth() + 1);
    
  3. 修改后的完整核心代码

    const timeString = options.getString("time");
    // 还原表情格式
    const cleanedTimeString = timeString.replace(/<:([^:]+):\d+>/g, ":$1:");
    const timezone = options.getString("timezone");
    const date = options.getInteger("date");
    const month = options.getString("month");
    const year = options.getInteger("year");
    
    const currentDate = new Date();
    const currentYear = year || currentDate.getFullYear();
    // 修正月份为1-12的格式
    const currentMonth = month || (currentDate.getMonth() + 1);
    const currentDateValue = date || currentDate.getDate();
    
    let timestamp;
    if (date && month) {
      timestamp = moment.tz(`${date} ${month} ${year} ${cleanedTimeString}`, "DD MM YYYY HH:mm:ss", timezone).valueOf();
    } else {
      timestamp = moment.tz(`${currentYear}-${currentMonth}-${currentDateValue} ${cleanedTimeString}`, "YYYY-MM-DD HH:mm:ss", timezone).valueOf();
    }
    

额外建议

如果服务器中还有其他可能和时间格式冲突的表情(比如:00:、:30:),这个正则表达式也能统一处理,无需单独修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:20:06