Help us understand the problem. What is going on with this article?

【GoogleAppsScript】【Slack】電車遅延情報post

More than 1 year has passed since last update.

GoogleAppScriptと連携し、
Slackに遅延情報を投稿するbotを作成してみました。

やりたいこと

GoogleAppsScriptで、
関東の電車遅延情報を毎朝Slackに投稿させる

完成系

slack.PNG

Slack設定

1.channelの作成

2.Incoming WebHooksで、Webhook URLを作成する

Browse Apps -> Custom Integrations -> Incoming WebHooks -> Edit configuration

設定例:
slack-post-train.PNG

  • Post to Channelにて投稿したいchannelを指定する
  • WebhookURLをメモする
  • Customize Nameにbotの名前を記述する
  • Customize Iconでbotのアイコンを選択する

GoogleAppScript

指定したURLのタグの要素を取得し、整形しSlackにpostさせる処理

function slackpost() {
try{

// 日付取得、フォーマット整形
var currentDate = new Date();
var weekday = currentDate.getDay();
var date = Utilities.formatDate( currentDate, 'Asia/Tokyo', 'M月d日 HH時mm分');

// 祝日は実行させない
if (weekday == 0 || weekday == 6) {
  return;
}
var calendar = CalendarApp.getCalendarById('ja.japanese#holiday@group.v.calendar.google.com');
if (calendar.getEventsForDay(currentDate, {max: 1}).length > 0) {
  return;
}

// URLから要素を指定し、タグ要素を取得する
var yahoo = "https://transit.yahoo.co.jp/traininfo/area/4/";
var response = UrlFetchApp.fetch(yahoo);
var myRegexp_line = /<div class="elmTblLstLine trouble">([\s\S]*?)<\/div>/i;
var line_html = myRegexp_line.exec(response.getContentText());
var line_list = line_html[1];

// 文字の整形
// replaceでline_listをゴリゴリ整形し変数、lineに...(もっと綺麗に書きたかった。。) 
var line_base = line_list.replace(/\n|(運転状況|列車遅延|路線|詳細)|<td><span.*<\/td>|<.?th>|<tr>|<.?table>/g, "");
var line_top_del = line_base.replace("状況", "");
var line_td_del_1 = line_top_del.replace(/<td>/g, "\n");
var line_span_del = line_td_del_1.replace(/<\/span>|<\/a>/g, "");
var line_a_del = line_span_del.replace(/<a href=".*\/">/g,"");
var line_td_del_2 = line_a_del.replace(/<\/td>/g, "\n" );
var line = line_td_del_2.replace(/<\/tr>/g, "━─━─━─━─━─━─━─━");

if(line !== '事故・遅延情報はありません'){

  // slackに投稿
  function postMessage(message, hookPoint){
    var payload = {
      "text": message,
      "channelId": '#information',
      "userName": 'train-info',
      "icon_emoji": ':train:'
    }
    var options = {
      "method": "POST",
      "payload": JSON.stringify(payload),
      "headers": {
      "Content-type": "application/json",
      }
    }
    var response = UrlFetchApp.fetch(hookPoint, options);

    if (response.getResponseCode() == 200) {
      return response;
    }
      return false;
  }
    postMessage("\n" + "◆関東遅延情報 " + date + "\n" + yahoo + "\n" + line,'メモしたWebhookURL');
}else{
    postMessage("\n" + "◆関東遅延情報 " + date + "\n" + "○ 事故・遅延情報はありません。" + "\n"+ yahoo,'メモしたWebhookURL');
}
}catch(e){
  result = "エラーの内容:" + e;
    Logger.log(result);
    postMessage("◆Script実行エラーです。");
 }
}

トリガーのセット

post.PNG

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした