与Jira通信的WhatsApp创建一个机器人
#node #bot #whatsapp #jira

该项目利用以下节点职责:

1- whatsapp-web.js
2 -axiosaxios-cookiejar-support e tough-cookie
3- node-cron
4- qrcode-terminal

obs :创建一个项目节点,并在上方添加downs

项目结构

project
├── services
│   └── api.js
├── utils
│   └── jiraUtils.js
├── index.js
├── jiraClient.js
└── package.json

项目代码

// api.js

const axios = require("axios");
const { wrapper } = require("axios-cookiejar-support");
const { CookieJar } = require("tough-cookie");

const cookieJar = new CookieJar();

axios.defaults.withCredentials = true;
axios.defaults.jar = cookieJar;

const instance = wrapper(
  axios.create({
    baseURL: process.env.JIRA_REST_API_URL,
  })
);

module.exports = instance;

转移 axios-cookiejar-suport Tough-cookie 帮助治疗和manipualrr cookie。

// jiraClient.js

const instance = require("./services/api");

const loginJira = async () => {
  try {
    const result = await instance.post("/rest/auth/1/session", {
      username: process.env.JIRA_USERNAME;,
      password: process.env.JIRA_PASSWORD,
    });
    if (result.status === 200) {
      console.log("Login realizado com sucesso");
      return true;
    }
  } catch (error) {
    console.log("Erro ao realizar o login:", error.message);
  }
  return false;
};

const getIssue = async (id) => {
  const result = await instance.get(`/rest/api/2/issue/${id}`);
  return result;
};

const jiraClient = async (numberIssue) => {
  try {
    const result = await instance.get("/rest/auth/1/session");
    if (result) {
      console.log("Sessão ativa");
      const issue = await getIssue(numberIssue);
      return issue;
    }
  } catch (error) {
    if (error.response.status === 401) {
      console.log("Não autorizado");
      const loginResult = await loginJira();
      if (loginResult) {
        return jiraClient(numberIssue);
      } else {
        throw error;
      }
    } else {
      console.log("Erro ao obter a sessão:", error);
      throw error;
    }
  }
};

module.exports = jiraClient;
// jiraUtils.js

const jiraClient = require(".././jiraClient");

const JIRA_REMINDER_MESSAGE = "Não esquecer de logar as horas no Jira!";

const makeResponseJira = async (id) => {
  try {
    const jiraIssue = await jiraClient(id);
    return `Issue: ${jiraIssue?.data?.key}\nLabel: ${jiraIssue?.data?.fields?.labels[0]}\nAssignee: ${jiraIssue?.data?.fields?.assignee?.name}\nDescription: ${jiraIssue?.data?.fields?.description}`;
  } catch (error) {
    if (error.response.status === 404) {
      return `Issue ${id} não encontrada!`;
    }
    if (error.response.status === 401) {
      return `Verifique suas credenciais!`;
    }
  }
};

const processMsgReceived = async (msg) => {
  let response;
  if (msg.body.startsWith("DEV-")) {
    response = await makeResponseJira(msg.body);
  } else if (msg.body.startsWith("!lembrete")) {
    response = JIRA_REMINDER_MESSAGE;
  } else {
    return null;
  }
  return response;
};

module.exports = processMsgReceived;

obs dev 是指问题 命名模式。
示例性问题: dev-100

// index.js 

const qrcode = require("qrcode-terminal");
const { Client, MessageMedia, LocalAuth } = require("whatsapp-web.js");
const cron = require("node-cron");
const processMsgReceived = require("./utils/jiraUtils");

const GROUP_ID = process.env.WPP_GROUP_ID;
const JIRA_LOGO_URL =
  "https://visuresolutions.com/wp-content/uploads/2022/07/Logo-Jira.png";
const JIRA_REMINDER_MESSAGE = "Não esquecer de logar as horas no Jira!";

const newBotClient = async () => {
  const client = new Client({ authStrategy: new LocalAuth() });
  return client;
};

const botJira = async (client) => {
  client.initialize();

  client.on("qr", (qr) => {
    qrcode.generate(qr, { small: true });
  });

  client.on("authenticated", () => {
    console.log("AUTHENTICATED");
  });

  client.on("ready", async () => {
    console.log("Client is ready!");
    cron.schedule(
      "0 17 * * *",
      async () => {
        // running a task every day 17 hrs
        const media = await MessageMedia.fromUrl(JIRA_LOGO_URL);
        let message = JIRA_REMINDER_MESSAGE;
        client.sendMessage(GROUP_ID, media, {
          caption: message,
        });
      },
      {
        scheduled: true,
        timezone: process.env.TIMEZONE || "America/Sao_Paulo",
      }
    );
    client.on("message", async (message) => {
      const processedMsg = await processMsgReceived(message);
      console.log("processedMsg MSG: ", processedMsg);
      if (processedMsg !== null) {
        const media = await MessageMedia.fromUrl(JIRA_LOGO_URL);
        const response = client.sendMessage(message.from, media, {
          caption: processedMsg,
        });

        return response;
      }
    });
  });
};

const startBot = async () => {
  try {
    const client = await newBotClient();
    botJira(client);
    console.log("Bot started!");
  } catch (error) {
    console.log("ERROR INIT BOT: ", error);
  }
};

startBot();

一些要解释的要点:

1-在 startar 该项目,将显示终端上的 QR码。您应该使用将是机器人的 whatsapp 帐户读取相同的内容。
2 - group_id 是指 whatsapp 组,将添加机器人以响应。
3- Chron.schedule 每天在17小时

每天发射提醒

在projeto上 lstrong>链接:https://github.com/mensonones/bot-jira-tutorial

时间是这个!我希望它会和任何生活都会发表评论或与我联系。在下一个:)