1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoogleAppsScriptでSlackにGoogle急上昇ワードを送信する(番外編でTeamsも追加)

Last updated at Posted at 2020-09-27

やりたいこと

image.png

Googleトレンドの急上昇ワードを、SlackBotに投稿する。
目的は、仕事の息抜き。

ゴールはGoogle急上昇ワードの内容をSlackに送ること!

image.png

image.png

手順

  1. SlackAPIトークンキー取得
  2. GoogleAppsScript作成
  3. GoogleAppsScriptトリガー設定

SlackAPIトークンキー取得

  1. SlackAppsを作成する。
    https://api.slack.com/apps

  2. SlackAPIページにアクセスして、「Create New App」を実行する。
    image.png
    image.png

  3. 「Basic Information - Display Information」でApp名称やアイコンを設定する。
    image.png

  4. SlackAppsのBotを作成する。

  5. 「App Home - Your App’s Presence in Slack」でBot名称を設定する。
    image.png

  6. 「OAuth & Permissions - Scopes」で権限を設定する。

    • channels:read
    • chat:write
      image.png
      image.png
  7. 「OAuth & Permissions - OAuth Tokens & Redirect URLs」で「Install App to Workspace」を実行する。
    image.png

  8. 「OAuth & Permissions - OAuth Tokens & Redirect URLs」に作成された[Bot User OAuth Access Token]が表示される。
    image.png

  9. Botをチャンネルに設定する。
    image.png
    image.png

GoogleAppsScript作成

  1. プロジェクトを作成する。
    https://script.google.com/home
  2. 「新しいプロジェクト」を実行する。
    image.png
  3. プロジェクト名を変更する。
    image.png
  4. コード.gsを変更する。
コード.gs
const GOOGLE_TRENDS_URL = 'https://trends.google.com/trends/api/dailytrends?geo=JP'
const SLACK_URL = 'https://slack.com/api/chat.postMessage'
/* SlackAPIトークンキーを設定!!!! */
const SLACK_TOKEN = 'xoxb-13848890xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
/* SlackAPIを設定したチャンネル名を設定!!!! */
const SLACK_CANNEL = '急上昇ワード'


/**
 * function name : notifySlackOfTrend.
 * Overview : Notify Slack of trend information.
 */
function notifySlackOfTrend() {
  // Get trend information from Google.
  const response = UrlFetchApp.fetch(GOOGLE_TRENDS_URL, {
    'method' : 'get',
  });
  const trends = JSON.parse(response.getContentText().replace(/^\)\]\}\'\,/g, ''))
  
  if (trends.default.trendingSearchesDays.length === 0) return 

  // Create a Slack message from trend information.
  const trendingSearches = trends.default.trendingSearchesDays[0].trendingSearches
  let trendMessages = ['*Google急上昇ワード*']
  for (const trendingSearchesDay of trends.default.trendingSearchesDays) {
    trendMessages.push('*' + trendingSearchesDay. formattedDate + '*')
    let ranking = 1
    for (const trendingSearche of trendingSearchesDay.trendingSearches) {
      const message = ranking++ + '. ' + '<https://trends.google.com' + trendingSearche.title.exploreLink + '|' + trendingSearche.title.query + '> '
        + '_' + trendingSearche.formattedTraffic + '_'
        + (trendingSearche.relatedQueries.length ?
          '\n```\n関連ワード:' + trendingSearche.relatedQueries.map(relatedQuerie => {
            return '<https://trends.google.com' + relatedQuerie.exploreLink + '|' + relatedQuerie.query + '>'
          }).join(',')
          + '\n```' 
          : '')
      console.log(message)
      trendMessages.push(message)
    }
    // Send a message to Slack.
    sendSlackBot(SLACK_CANNEL, trendMessages.join('\n'))
    trendMessages = []
  }
}

/**
 * function name : sendSlackBot.
 * Overview : If an channel is specified, an slack message will be sent.
 */
function sendSlackBot(channel, message) {
  if (!channel) return
  // Send message to bot.
  UrlFetchApp.fetch(SLACK_URL, {
    method: 'post',
    payload: {
      token: SLACK_TOKEN,
      channel: channel,
      text: message
    }
  })
}
  1. 動作確認
  2. 実行メソッドを「notifySlackOfTrend」に変更後、実行ボタンを押下。
    image.png
    権限確認が来るので、許可する。
    image.png
  3. Slackのチャンネルに通知が来ていることを確認する
    image.png
    リンクもついているので、クリックで情報をみることもできます。
    image.png
    image.png

GoogleAppsScriptトリガー設定

Slackに急上昇ワードのBot送信ができたので、定期的に実行するようにトリガーを設定します。
image.png

  1. 「トリガーを追加」からトリガー情報を設定する。
    今回は、ネタBotなので、お昼時間帯に1日1回送信する。
    image.png

最後に

今回は、毎日お昼になると急上昇ワードが送信されるようなネタBotを作成しました。
仕事で煮詰まっている人や、話す話題に困っている人に見てもらえると、チーム生産性やコミュニケーションが向上するかも!?

あまり、真面目にGASを触っていなかったのですが、手軽に使えるので今後もいろいろ試してみたいと思います。

番外編 Teamsに送信する場合

GASスクリプト

notifyTeamsOfTrend.gs
const GOOGLE_TRENDS_URL = 'https://trends.google.com/trends/api/dailytrends?geo=JP'
/* Teams Incoming WebhookのURLを設定!!!! */
const TEAMS_WEBHOOK = 'https://outlook.office.com/webhook/xxxxx'

/**
 * function name : notifyTeamsOfTrend.
 * Overview : Notify Teams of trend information.
 */
function notifyTeamsOfTrend() {
  // Get trend information from Google.
  const response = UrlFetchApp.fetch(GOOGLE_TRENDS_URL, {
    'method' : 'get',
  });
  const trends = JSON.parse(response.getContentText().replace(/^\)\]\}\'\,/g, ''))
  
  if (trends.default.trendingSearchesDays.length === 0) return 

  // Create a Teams message from trend information.
  const trendingSearches = trends.default.trendingSearchesDays[0].trendingSearches
  let trendMessages = ['# Google急上昇ワード']
  for (const trendingSearchesDay of trends.default.trendingSearchesDays) {
    trendMessages.push('## ' + trendingSearchesDay. formattedDate)
    let ranking = 1
    for (const trendingSearche of trendingSearchesDay.trendingSearches) {
      const message = ranking++ + '. [' + trendingSearche.title.query + '](https://trends.google.com' + trendingSearche.title.exploreLink + ') '
        + '_' + trendingSearche.formattedTraffic + '_'
        + (trendingSearche.relatedQueries.length ?
          '\n\n  - 関連ワード:' + trendingSearche.relatedQueries.map(relatedQuerie => {
            return '[' + relatedQuerie.query + '](https://trends.google.com' + relatedQuerie.exploreLink + ')'
          }).join(',')
          + '\n\n' 
          : '\n')
      console.log(message)
      trendMessages.push(message)
    }
  }
  // Send a message to Teams.
  sendTeamsBot({text:trendMessages.join('\n')})
}

/**
 * function name : sendTeamsBot.
 * Overview : Teams message will be sent.
 */
function sendTeamsBot(message) {
  // Send message to bot.
  UrlFetchApp.fetch(TEAMS_WEBHOOK, {
    method: 'post',
    payload: JSON.stringify(message)
  })
}

Teamsの送信結果

image.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?