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

为何Slack机器人中count与counter变量显示undefined?求修复

Slack机器人count/counter变量undefined问题修复

我正在开发一款Slack机器人,需求是:当指定频道收到新消息时,自动在另一频道发送通知,且该功能每日仅触发一次。但运行代码后控制台输出报错:

No new hits! undefined messages and undefined in "counter".

不清楚为何count和counter变量显示为undefined,以下是我的代码:

const web = new WebClient(process.env.SLACK_TOKEN);
const currentTime = new Date().toTimeString();
let channelId = "C02FHG0K0SY";
let conversationHistory, message, count, stop;
let counter;

async function fetchMessages() {
  const result = await web.conversations.history({
    channel: channelId,
    limit: 11000,
  });

  conversationHistory = result.messages;

  count = conversationHistory.length;
}

setInterval(function () {
  if (counter === null) {
    fetchMessages();
    var count = fetchMessages.count;
    counter === count;
    console.log("Counter has been setup!");
  }

  if (counter === count) {
    fetchMessages();
    if (count > counter) {
      web.chat.postMessage({
        token: process.env.SLACK_TOKEN,
        channel: "C02FB9QHW10",
        text: "Hits have arrived, let's get started with them! Woo-hoo! This is just a test by the way, no hits have actually arrived.",
      });
      stop === true;
      console.log("Hits arrived! Posted.")
    } else {
      console.log(`No new hits! ${count} messages and ${counter} in "counter".`);
    }
  }
}, 5000);

setInterval(function () {
  if (currentTime == "23:59:59 GMT+0000 (Coordinated Universal Time)") {
    if (stop === true) {
      stop === false;
    }
  }
}, 1000);

问题原因及修复步骤

1. 异步函数未正确等待结果

fetchMessages是异步函数,调用时必须用await,否则代码会跳过等待直接执行后续逻辑,此时count还未被赋值,导致undefined。

2. 变量赋值与比较混淆

代码中多处错误使用===(比较运算符)代替=(赋值运算符):

  • counter === count 应改为 counter = count
  • stop === true 应改为 stop = true
  • stop === false 应改为 stop = false

另外,var count = fetchMessages.count完全错误,fetchMessages函数没有count属性,直接使用全局声明的count即可。

3. 变量初始化判断错误

counter初始值是undefined,判断counter === null永远不会成立,应改为if (counter === undefined),或者初始化counter为null。

4. 时间变量未实时更新

currentTime是初始化时的固定值,不会随时间变化。需要在定时器内部重新获取当前时间,才能正确判断每日重置时机。

5. 重复调用API优化

原代码在定时器内多次调用fetchMessages,会重复请求Slack API,建议调用一次后复用结果,减少不必要的请求。

修复后的完整代码

const web = new WebClient(process.env.SLACK_TOKEN);
let channelId = "C02FHG0K0SY";
let conversationHistory, count, stop = false;
let counter;

async function fetchMessages() {
  const result = await web.conversations.history({
    channel: channelId,
    limit: 11000,
  });

  conversationHistory = result.messages;
  count = conversationHistory.length;
  return count;
}

// 主检查定时器
setInterval(async function () {
  if (stop) return; // 每日触发后停止检查

  // 初始化计数器
  if (counter === undefined) {
    counter = await fetchMessages();
    console.log("Counter has been setup!");
    return;
  }

  // 获取最新消息数量
  const latestCount = await fetchMessages();
  
  if (latestCount > counter) {
    await web.chat.postMessage({
      token: process.env.SLACK_TOKEN,
      channel: "C02FB9QHW10",
      text: "Hits have arrived, let's get started with them! Woo-hoo! This is just a test by the way, no hits have actually arrived.",
    });
    stop = true;
    console.log("Hits arrived! Posted.");
    counter = latestCount; // 更新计数器
  } else {
    console.log(`No new hits! ${latestCount} messages and ${counter} in "counter".`);
  }
}, 5000);

// 每日重置定时器
setInterval(function () {
  const currentTime = new Date().toTimeString();
  if (currentTime.startsWith("23:59:59")) { // 简化时间判断,避免时区精确匹配问题
    stop = false;
    console.log("Daily reset completed.");
  }
}, 1000);

内容的提问来源于stack exchange,提问作者Jose Moran Urena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:25:04