Skip to content
Docs

Recipes

Alerts on new calls

Each new call on your tickers as a message in Slack, Discord or Telegram, from task to running code, with its errors handled.

On this page
  1. Gather the parts
  2. Copy this file into your backend
  3. Start it from your server code
  4. What it handles
  1. Gather the parts

    A Partner API key with access to /v1/feed, Node 18 or later, feed-client.mjs copied from the API quickstart, and where the alerts go: a Slack incoming webhook URL, a Discord webhook URL or a Telegram bot token and the chat ID.

  2. Copy this file into your backend

    Save it as alerts.mjs next to feed-client.mjs. To send elsewhere, such as email, pass your own notify; it must throw only when nothing went out.

    alerts.mjs
    // Alert bot: sends each new call on your tickers to Slack, Discord, Telegram or your own notifier.
    // Copy it into your backend next to feed-client.mjs (Node 18 or later, no packages).
    import { readFileSync, writeFileSync } from 'node:fs';
    import { followFeed } from './feed-client.mjs';
    
    const PER_ROUND = 20;   // at most this many alerts per complete read; the rest wait for the next
    const MAX_TRIES = 3;
    const WEEK = 7 * 24 * 3600 * 1000;   // a post leaves the feed seven days after it was published
    const KEEP = WEEK + 24 * 3600 * 1000;
    
    // The wait a notifier names, in whole seconds: 60 when it names none (or zero, a negative or not a
    // number), at most one day.
    const waitFor = (seconds) => {
      const value = Number(seconds);
      return Number.isNaN(value) || value <= 0 ? 60 : Math.min(86400, Math.ceil(value));
    };
    
    // Calls notify(post) for each call the feed brings after the first read, at least once: a call can
    // arrive twice when the process stops between a send and the state write. notify must throw only
    // when nothing went out; an error with `retryAfter` (seconds) pauses sending without counting a try.
    // A state file that cannot be written stops the bot: onError gets the error.
    export function startAlerts({ key, tickers, notify, stateFile = 'alerts-state.json', onError = console.error }) {
      // seen: post id -> when it was alerted or found on a first read. tickers: the set the last read had.
      // tries: failed sends per post id. pausedUntil: the end of a notifier's Retry-After. mark: the cursor.
      // readAt: when the last complete read came.
      let state = null;
      try {
        state = JSON.parse(readFileSync(stateFile, 'utf8'));
      } catch (error) {
        if (error.code !== 'ENOENT') throw error;   // an unreadable state file stops the bot
      }
      let busy = false, halted = false, feed = null;
      const save = () => {
        try {
          writeFileSync(stateFile, JSON.stringify(state));
        } catch (error) {   // a bot that cannot remember must not send
          // Halt first, then report: an onError that throws still leaves the bot stopped. A round still
          // sending when the bot stopped records the call it just sent: if that write fails too, it is the
          // same stop, reported once.
          const first = !halted;
          halted = true;
          feed?.stop();
          if (first) onError(error);
          throw error;
        }
      };
    
      async function round(posts, current, mark, reset) {
        if (halted) return;
        const now = Date.now();
        // What a read says about the past is recorded on every read, also while sending waits (a notifier's
        // pause, a round still sending): a later read no longer carries the reset.
        const away = state?.readAt && now - state.readAt > WEEK;
        if (!state || away || reset === 'mark_expired' || reset === 'invalid_mark') {
          // First read ever, a cursor that no longer resumes, or more than seven days since the last read
          // (a long stop, also one with calls left unsent and no cursor saved): what the feed holds now is
          // not new. A new ticker set (mark_mismatch) keeps the seen calls below.
          state = { seen: state?.seen || {}, tries: state?.tries || {}, pausedUntil: state?.pausedUntil || 0,
                    tickers: current, mark: null };
          for (const id of posts.keys()) state.seen[id] = now;
        }
        state.readAt = now;
        // A ticker added since the last read: its calls already in the feed are not new either.
        const added = new Set(current.filter((ticker) => !state.tickers.includes(ticker)));
        for (const [id, post] of posts) if (added.has(post.ticker) && !state.seen[id]) state.seen[id] = now;
        state.tickers = current;
        state.tries = state.tries || {};
        if (busy || now < (state.pausedUntil || 0)) {   // the next read sends what is left
          save();
          return;
        }
        busy = true;
        try {
          const fresh = [...posts.values()]
            .filter((post) => post.call && !state.seen[post.id])
            .sort((a, b) => a.published_at.localeCompare(b.published_at))
            .slice(0, PER_ROUND)
            .map((post) => post.id);
          for (const id of fresh) {
            if (halted) return;   // a write failed meanwhile (another read): send nothing more
            const post = posts.get(id);   // as the feed holds it now: a post removed meanwhile is not sent
            if (!post || !post.call || state.seen[id]) continue;
            try {
              await notify(post);
              state.seen[post.id] = Date.now();
            } catch (error) {
              if (error.retryAfter !== undefined) {   // the notifier asked to wait: stop this round, count no try
                state.pausedUntil = Date.now() + waitFor(error.retryAfter) * 1000;
                save();
                break;
              }
              // A timeout may have delivered the message: record it rather than send it again.
              const timedOut = error.name === 'TimeoutError' || error.name === 'AbortError';
              state.tries[post.id] = (state.tries[post.id] || 0) + 1;
              if (timedOut || state.tries[post.id] >= MAX_TRIES) state.seen[post.id] = Date.now();
              console.error(`Alert for ${post.id} failed: ${error.message}`);
            }
            if (state.seen[post.id]) delete state.tries[post.id];
            save();
          }
          if (halted) return;
          // A restart resumes from the saved cursor (it lives seven days). It moves on only when every call
          // read so far was sent, so calls read but not yet sent come back after a restart.
          if (![...posts.values()].some((post) => post.call && !state.seen[post.id])) state.mark = mark;
          for (const [id, at] of Object.entries(state.seen)) if (at < now - KEEP) delete state.seen[id];
          save();
        } finally {
          busy = false;
        }
      }
    
      feed = followFeed({
        key, tickers, mark: state?.mark ?? null,
        onChange: (posts, current, mark, reset) => {
          round(posts, current, mark, reset).catch((error) => { if (!halted) onError(error); });
        },
        onProblem: (error) => console.error(error.message),
      });
      return feed;
    }
    
    // Text from a post cannot hide a link behind other words, and in Slack and Discord it cannot ping anyone:
    // Slack's & < > and Discord's Markdown are escaped (Discord also allows no mentions). Telegram gets plain
    // text, where an @handle works as in any message. The alert's own link stays a link.
    const CHANNELS = {
      slack: { escape: (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'),
               link: (url) => `<${url.replace(/&/g, '&amp;').replace(/[<>|]/g, encodeURIComponent)}>` },
      discord: { escape: (text) => text.replace(/[\\*_~`|<>[\]#-]/g, '\\$&'), link: (url) => url },
      telegram: { escape: (text) => text, link: (url) => url },
    };
    
    // Text cut to `limit` characters once escaped, by code points (never half a character), with "…".
    const fit = (text, limit, escape) => {
      if (escape(text).length <= limit) return escape(text);
      if (limit <= 0) return '';
      const chars = Array.from(text).slice(0, limit - 1);
      while (chars.length && escape(chars.join('')).length > limit - 1) chars.pop();
      return `${escape(chars.join(''))}…`;
    };
    
    // The alert: author, call, ticker, thesis and link, within Discord's 2,000 characters: a long thesis, or an
    // author name past 200 characters, is cut; the link stays whole.
    export function alertText(post, channel = 'telegram', max = 2000) {
      const { escape, link } = CHANNELS[channel];
      const url = link(post.source.url);
      const rest = ` (${escape(post.author.platform)}): ${post.call.toUpperCase()} ${escape(post.ticker)}`;
      const head = fit(post.author.name, Math.min(200, max - url.length - 2 - rest.length), escape) + rest;
      return `${head}\n${fit(post.summary, max - head.length - url.length - 2, escape)}\n${url}`;
    }
    
    // The notifiers. Each throws only when the service refused the message; a 429 carries the wait it names.
    // A network error, or a malformed address, can quote the address, which holds the webhook secret or the bot
    // token: it is replaced by one that names only the service, keeping a timeout's name (it may have arrived).
    const send = async (service, url, body) => {
      try {
        return await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(15000),
        });
      } catch (error) {
        const failure = new Error(`${service} could not be reached`);
        if (error?.name === 'TimeoutError' || error?.name === 'AbortError') failure.name = error.name;
        throw failure;
      }
    };
    const refused = (service, res, seconds) => {
      const error = new Error(`${service} answered ${res.status}`);
      if (res.status === 429) error.retryAfter = waitFor(seconds);
      return error;
    };
    const answer = async (res) => { try { return JSON.parse(await res.text()); } catch { return {}; } };
    
    // A Slack incoming webhook. A 429 names the wait in its Retry-After header.
    export async function slack(post, url = process.env.SLACK_WEBHOOK_URL) {
      const res = await send('Slack', url, { text: alertText(post, 'slack') });
      if (!res.ok) throw refused('Slack', res, res.headers.get('retry-after'));
    }
    
    // A Discord channel webhook, asked to wait until the message is saved, so success means it was. A 429 names
    // the wait in retry_after, in seconds; no mention pings anyone.
    export async function discord(post, url = process.env.DISCORD_WEBHOOK_URL) {
      let target;
      try {
        target = new URL(url);
      } catch {
        throw new Error('Discord could not be reached');   // the message of a bad URL quotes it
      }
      target.searchParams.set('wait', 'true');
      const res = await send('Discord', target.href,
        { content: alertText(post, 'discord'), allowed_mentions: { parse: [] } });
      if (!res.ok) throw refused('Discord', res, (await answer(res)).retry_after ?? res.headers.get('retry-after'));
    }
    
    // A Telegram bot writing to one chat; the preview is the alert's own link, not one in the thesis. A 429
    // names the wait in parameters.retry_after.
    export async function telegram(post, token = process.env.TELEGRAM_BOT_TOKEN, chatId = process.env.TELEGRAM_CHAT_ID) {
      const res = await send('Telegram', `https://api.telegram.org/bot${token}/sendMessage`, {
        chat_id: chatId, text: alertText(post, 'telegram'),
        link_preview_options: { url: post.source.url, prefer_small_media: true },
      });
      if (!res.ok) throw refused('Telegram', res, (await answer(res)).parameters?.retry_after);
    }
    
  3. Start it from your server code

    Your server
    import { startAlerts, slack } from './alerts.mjs';
    
    startAlerts({
      key: process.env.BUZZBERG_API_KEY,
      tickers: ['BTC', 'ETH', 'NVDA'],
      notify: (post) => slack(post, process.env.SLACK_WEBHOOK_URL),
    });
    
    import { startAlerts, discord } from './alerts.mjs';
    
    startAlerts({
      key: process.env.BUZZBERG_API_KEY,
      tickers: ['BTC', 'ETH', 'NVDA'],
      notify: (post) => discord(post, process.env.DISCORD_WEBHOOK_URL),
    });
    
    import { startAlerts, telegram } from './alerts.mjs';
    
    startAlerts({
      key: process.env.BUZZBERG_API_KEY,
      tickers: ['BTC', 'ETH', 'NVDA'],
      notify: (post) => telegram(post, process.env.TELEGRAM_BOT_TOKEN,
        process.env.TELEGRAM_CHAT_ID),
    });
    

    Start one per state file. It writes alerts-state.json in the working directory; pass stateFile to put it elsewhere. Delivery is at least once: a call can arrive twice when the process stops between a send and the state write, so a receiver that must not repeat can drop a post ID it has seen.

What it handles

First startThe calls already in the feed are not sent; every call that arrives after is.
Late callsA call saved hours after it was published is sent when it arrives.
Backlog20 alerts a round; the rest go out in the next rounds.
Revised or removed postA revised post is not sent again; a post removed before its alert is not sent.
RestartResumes from the saved cursor and sends what arrived while it was stopped, and what was read but not yet sent, 20 a round. After more than seven days without a read, the bot starts as on a first start: calls published while it was stopped are not sent.
New tickerIts calls already in the feed are not sent as new.
Notifier errorTried again on the next round, at most 3 times, restarts included. A send that times out is recorded as sent, since it may have arrived. Discord is asked to answer once the message is saved, so a success means it was. An error names only the service, never the webhook address or bot token. A 429 pauses sending for the wait the service names (Slack's Retry-After header, Discord's retry_after, Telegram's parameters.retry_after), across a restart, without counting a try.
Text from a postIt cannot hide a link behind other words, and in Slack and Discord it cannot ping anyone: Slack's & < > and Discord's Markdown are escaped. Telegram gets plain text, where an @handle works as in any message, and its preview is the alert's own link.
Untracked ticker, 429, rejected keyThe feed client leaves the untracked ticker out, waits Retry-After, or stops polling (feed client).
State fileUnreadable at start: startAlerts throws instead of sending everything again. Not writable: the bot stops sending and passes the error to onError, since a bot that cannot remember what it sent must not send.