Slack: チャット投稿 (Bots) (Slack: Post Chat (Bots))
この工程は、Bots 機能を使って Slack にメッセージを投稿します。
Configs:共通設定
  • 工程名
  • メモ
Configs
  • C1-deprecated: OAuth2 設定 (スコープ変更のため)
  • C1: OAuth2 設定 *
  • C2: 投稿するチャンネルの名前 *
  • C3: 送信するテキスト#{EL}
  • C4: メンション(ユーザ もしくは メールアドレス)
  • C5: Attachment の要約 (送信テキストが空の場合に、通知で使用される)#{EL}
  • C6: Attachment の色
  • C7: Attachment のタイトル#{EL}
  • C8: Attachment のタイトルリンク#{EL}
  • C9: Attachment のテキスト#{EL}

Notes

  • 廃止予定(C1-deprecated)が設定されている場合、C1: OAuth2 設定 を設定してください。
  • 複数の投稿チャネルを指定することはできません。
  • 指定する投稿チャンネルでは、事前に「questetra_bot」をチャンネルに招待しておいてください。
  • C4: メンションを指定した場合、本文の最後に自動的に追加されます。

Capture

See also

Script (click to open)
  • 下記のスクリプトを記述した XML ファイルをダウンロードできます
    • slack-chat-post-bots.xml (C) Questetra, Inc. (MIT License)
    • Professional をご利用であればファイルの内容を改変することでオリジナルのアドオンとして活用できます


main();

function main() {
    const oauth2 = decideOAuth2Setting();
    let text = "";
    if (configs.get("Text") !== "" && configs.get("Text") !== null) {
        text = configs.get("Text");
    }
    const channel = configs.get("ChannelName");

    let attachment = {};

    attachAdd(attachment, "Fallback", "fallback");
    attachAdd(attachment, "Color", "color");
    attachAdd(attachment, "Title", "title");
    if (attachment["title"] !== undefined) {
        attachAdd(attachment, "TitleLink", "title_link");
    }
    attachAdd(attachment, "AttachText", "text");

    const slackIdNum = decideSlackIdNum(oauth2);

    if (slackIdNum !== "") {
        text = `${text}\n\n<@${slackIdNum}>`;
        engine.log('Slack Id:' + slackIdNum);
    }

    if (attachment["title"] === undefined && attachment["text"] === undefined && text === "") {
        throw "Message to send isn't set.";
    }

    sendMessage(oauth2, channel, text, attachment);
}

/**
 * @return 使用する OAuth2 設定
 */
function decideOAuth2Setting() {
    const v1 = configs.get("conf_OAuth2");
    if (v1 !== null && v1 !== "") {
        return v1;
    }
    return configs.get("conf_OAuth2_V2");
}

/**
 * メンション相手のメールアドレス(Slack アカウント)をconfigから読み出す
 * メールアドレスから Slack ID を取得する関数を呼ぶ
 * @return {String} slackIdNum  Slack ID
 */
function decideSlackIdNum(oauth2) {
    let mailAddress = "";
    let slackIdNum = '';
    mailAddressDef = configs.getObject("conf_Mention");

    if (mailAddressDef === null) { //固定値
        mailAddress = configs.get("conf_Mention");
    } else {
        const user = engine.findData(mailAddressDef);
        if (mailAddressDef.matchDataType("QUSER")) { //ユーザ型
            if (user !== null) {
                mailAddress = user.getEmail();
            }
        } else { //文字型
            mailAddress = user;
        }
    }

    if (mailAddress !== "" && mailAddress !== null) {
        engine.log("email: " + mailAddress);
        slackIdNum = usersLookupByEmail(oauth2, mailAddress);
    }

    return slackIdNum;
}


/**
 * メールアドレスから Slack ID を取得する
 * users.lookupByEmail https://api.slack.com/methods/users.lookupByEmail
 * @param {String} oauth2
 * @param {String} email
 * @return {String} responseJson.user.id  Slack ID
 */
function usersLookupByEmail(oauth2, email) {

    const url = 'https://slack.com/api/users.lookupByEmail';
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam("email", email)
        .post(url);
    const status = response.getStatusCode();
    const responseTxt = response.getResponseAsString();

    let responseJson;
    try {
        responseJson = JSON.parse(responseTxt);
    } catch (e) {
        engine.log("failed to parse as json");
        engine.log(`status: ${status}`);
        engine.log(responseTxt);
        throw `Failed to users lookup By email. status: ${status}`;
    }

    if (responseJson.ok !== true) {
        const error = `Failed to send`;
        engine.log(`status: ${status}`);
        engine.log(responseTxt);
        throw error;
    }
    return responseJson.user.id;
}


/**
 * Send Message with Bots  チャット投稿
 * @param {String} oauth2
 * @param {String} channel
 * @param {String} text
 * @param {String} attachment
 */
function sendMessage(oauth2, channel, text, attachment) {
    let jsonReq = {};
    jsonReq["text"] = text;
    jsonReq["channel"] = channel;
    jsonReq["as_user"] = "true";

    let attachArray = [];
    if (Object.keys(attachment).length !== 0) {
        attachArray.push(attachment);
    }

    jsonReq["attachments"] = attachArray;

    const url = 'https://slack.com/api/chat.postMessage';
    const response = httpClient.begin()
        .authSetting(oauth2)
        .body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
        .post(url);
    const status = response.getStatusCode();
    const responseTxt = response.getResponseAsString();

    let responseJson;
    try {
        responseJson = JSON.parse(responseTxt);
    } catch (e) {
        engine.log("failed to parse as json");
        engine.log(`status: ${status}`);
        engine.log(responseTxt);
        throw `Failed to send. status: ${status}`;
    }

    if (responseJson.ok !== true) {
        const error = `Failed to send`;
        engine.log(`status: ${status}`);
        engine.log(responseTxt);
        throw error;
    }
}

function attachAdd(attachment, config, attachName) {
    const value = configs.get(config);
    if (value !== "" && value !== null) {
        attachment[attachName] = value;
    }
}

%d