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

如何修改Discord Ping定时器代码实现UTC-3定时@角色

修改Discord定时推送脚本以支持UTC-3时区的定时消息与角色提及

核心修改思路

  1. 替换固定间隔轮询为基于UTC-3时区的时间点判断,避免固定间隔导致的时间偏移
  2. 配置多组时间-消息-角色映射,实现不同时间发送不同内容并@指定角色
  3. 修正Discord Webhook的角色提及格式与权限配置,确保@角色生效

完整修改后的代码

// 配置项:替换为你的Webhook信息、时区时间点与对应内容
const CONFIG = {
    webhookId: "你的Webhook ID",
    webhookToken: "你的Webhook Token",
    // UTC-3时区的时间点配置:时间格式为HH:mm,支持多组
    scheduledTasks: [
        {
            time: "09:00",
            content: "早上好!<@&123456789012345678> 请查看今日任务清单",
            roleId: "123456789012345678" // 要提及的角色ID
        },
        {
            time: "18:00",
            content: "下班提醒!<@&987654321098765432> 请提交今日工作汇报",
            roleId: "987654321098765432"
        }
    ]
};

// 每分钟检查一次时间(避免过于频繁请求)
setInterval(checkAndSend, 60000);

function checkAndSend() {
    // 获取当前UTC-3时间
    const now = new Date();
    const utc3Time = new Date(now.getTime() - 3 * 3600 * 1000); // UTC转UTC-3
    const currentTime = `${String(utc3Time.getHours()).padStart(2, '0')}:${String(utc3Time.getMinutes()).padStart(2, '0')}`;

    // 匹配当前时间对应的任务
    const matchedTask = CONFIG.scheduledTasks.find(task => task.time === currentTime);
    if (!matchedTask) return;

    // 执行推送
    sendWebhookMessage(matchedTask);
}

function sendWebhookMessage(task) {
    const https = require("https");
    const req = https.request({
        hostname: "discord.com", // 使用Discord最新域名
        port: 443,
        path: `/api/webhooks/${CONFIG.webhookId}/${CONFIG.webhookToken}`,
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        }
    }, res => {
        res.setEncoding("utf8");
        res.on("data", ch => console.log("Webhook响应:", ch));
    });

    req.on("error", e => console.error("推送失败:", e));
    req.write(JSON.stringify({
        allowed_mentions: {
            roles: [task.roleId], // 明确允许提及的角色ID,避免Discord拦截
            parse: [] // 关闭默认提及解析,仅允许指定角色
        },
        content: task.content
    }));
    req.end();
}

关键说明

  • 时区处理:通过new Date(now.getTime() - 3 * 3600 * 1000)将当前UTC时间转换为UTC-3,彻底规避系统本地时区的影响
  • 角色提及规则:Discord中@角色必须使用<@&角色ID>格式,同时在allowed_mentions中指定对应角色ID,否则会被Discord自动屏蔽提及
  • 时间匹配逻辑:每分钟检查一次当前UTC-3时间的小时和分钟,仅在匹配到预设时间点时执行推送,避免固定间隔轮询导致的时间漂移
  • 多任务扩展:在CONFIG.scheduledTasks数组中添加更多对象,即可快速实现不同时间发送不同消息、@不同角色的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:33:09