🔖

SlackAPIを使って自動でチャンネルにブックマークをつける方法

2023/06/19に公開

以下のbookmarks.addのAPIを使って、Flutter大学のユーザーの皆さんのtimesチャンネルにマイページへのbookmarkをつけてみました。

使ったAPI

https://api.slack.com/methods/bookmarks.add

本来は自分でbookmarkをつけなければいけないところを、APIで自動でつけれるので便利です。

tsのコード

コードは以下みたいなのをfirebaseのfunctionsに用意して、管理画面から叩きました。

SLACK_TOKENの取得やaxiosの導入などは本記事では割愛します。

export async function addUserPageBookmark(channelId: string, userId: string): Promise<void> {
    const baseURL = `https://flutteruniv.com`;
    const userPageURL = `${baseURL}/users/${userId}`;
    return addBookmark(channelId, 'マイページ', userPageURL, ':flutter_univ_logo:');
}

export async function addBookmark(channelId: string, title: string, url: string, emoji: string): Promise<void> {
    const config = {
        headers: {
            Authorization: `Bearer ${SLACK_TOKEN}`,
            'Content-Type': `application/x-www-form-urlencoded`,
        },
    };

    const encodedTitle = encodeURIComponent(title);
    const bookmarksAddURL = `https://slack.com/api/bookmarks.add?channel_id=${channelId}&title=${encodedTitle}&type=link&link=${url}&emoji=${emoji}`;
    const response = await axios.get(bookmarksAddURL, config);
    const data = response.data;
    const ok: boolean = data.ok;

    if (ok) {
        console.log(`Succeeded to added bookmark to ${channelId}`);
    } else {
        console.log('Failed to added bookmark: response.error=%s', data.error);
        console.log(`error channel id: ${channelId}`);
    }
}

結果

このような感じでAPIでbookmarkをつけることができました!

Flutter大学

Discussion