Slack: チャット投稿(Bots)

Slack: チャット投稿 (Bots)

Slack: Post Chat (Bots)

この工程は、Bots 機能を使って Slack にメッセージを投稿します。

Auto Step icon
Basic Configs
工程名
メモ
Configs for this Auto Step
conf_OAuth2_V2
C1: OAuth2 設定 *
ChannelName
C2: 投稿するチャンネルの名前 *
Text
C3: 送信するテキスト#{EL}
conf_Mention
C4: メンション(ユーザ もしくは メールアドレス)
Fallback
C5: Attachment の要約 (送信テキストが空の場合に、通知で使用される)#{EL}
Color
C6: Attachment の色
Title
C7: Attachment のタイトル#{EL}
TitleLink
C8: Attachment のタイトルリンク#{EL}
AttachText
C9: Attachment のテキスト#{EL}

Notes

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

Capture

See also

Script (click to open)
  • 次のスクリプトが記述されている XML ファイルをダウンロードできます
    • slack-chat-post-bots.xml (C) Questetra, Inc. (MIT License)
    • Professional のワークフロー基盤では、ファイル内容を改変しオリジナルのアドオン自動工程として活用できます


function main() {
    const oauth2 = configs.getObject("conf_OAuth2_V2");
    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);
}


/**
 * メンション相手のメールアドレス(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 {AuthSettingWrapper} oauth2  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 {AuthSettingWrapper} oauth2  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;
    }
}
上部へスクロール

Questetra Supportをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む