Edits history of script submission #22519 for ' Schedule error handler (slack)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { WebClient } from "@slack/web-api";
    import dayjs from "dayjs";
    
    type Slack = {
      token: string;
    };
    
    function formatError(error: any) {
      if (error.stack && error.name && error.message) {
        return `*${error.name}: ${error.message}*\`\`\`\n${error.stack}\n\`\`\``;
      } else {
        return `\`\`\`\n${JSON.stringify(error, null, 2)}\n\`\`\``;
      }
    }
    
    export async function main(
      path: string, // The path of the script or flow that errored
      is_flow: boolean, // Whether the runnable is a flow
      schedule_path: string, // The path of the schedule
      error: object, // The error details
      started_at: string, // The start datetime of the latest job that failed
      failed_times: number, // Minimum number of times the schedule failed before calling the error handler
      slack: Slack,
      channel: string,
    ) {
      const baseUrl = Bun.env.WM_BASE_URL;
      const scheduleUrl = baseUrl + "/runs?schedule_path=" +
        encodeURIComponent(schedule_path);
      const runnableUrl = baseUrl + (is_flow ? "/flows/get/" : "/scripts/get/") +
        path;
      const web = new WebClient(slack.token);
    
      await web.chat.postMessage({
        channel,
        text: `Schedule ${schedule_path} failed ${
          failed_times > 1 ? (failed_times + " times in a row") : ""
        }`,
        blocks: [
          {
            "type": "section",
            "text": {
              "type": "mrkdwn",
              "text": `*Schedule <${scheduleUrl}|${schedule_path}> failed*${
                failed_times > 1 ? (" " + failed_times + " times in a row") : ""
              }:\n- ${is_flow ? "Flow" : "Script"}: <${runnableUrl}|${path}>`,
            },
          },
        ],
        attachments: [
          {
            color: "#ff0000",
            "blocks": [{
              "type": "section",
              "text": {
                "type": "mrkdwn",
                "text": `Last failure at: ${
                  dayjs(started_at).format("DD.MM.YYYY HH:mm (Z)")
                }\n${formatError(error)}`,
              },
            }],
          },
        ],
      });
    }
    

    Submitted by hugo989 6 days ago