LoginSignup
12
11

More than 5 years have passed since last update.

Yoで月曜をお知らせ

Posted at

Yoで何かやってみたい

Yo APIを試してみたを見て何か作れないかと考えた結果、月曜日をお知らせするbotを作ってみました。
GETSUYOにYoを送ると月曜のお知らせを受け取れます。

GETSUYOのソース

Goで作ってherokuにデプロイしたかったのでGetting Started with Go on Herokuの手順通りに進めます。
ただし、botはWebアプリではないのでProcfileのprocess typeをclock(web以外の任意の単語)にします。

getsuyo/Procfile
clock: getsuyo

タイムゾーンはherokuでタイムゾーン設定のようにコンソールから設定できますが、コードで設定してみました。
またSIGTERMでプロセス停止なのできちんと処理しています。

getsuyo/main.go
package main

import (
    "fmt"
    "net/http"
    "net/url"
    "os"
    "os/signal"
    "syscall"
    "time"
)

const (
    api_key            = "ここにAPI_KEYを設定する"
    location           = "Asia/Tokyo"
    offsetLoc          = 9 * 60 * 60
    offsetDayOfWeekday = time.Monday
)

func init() {
    loc, err := time.LoadLocation(location)
    if err != nil {
        loc = time.FixedZone(location, offsetLoc)
    }
    time.Local = loc
}

func main() {
    fmt.Println("starting getsuyo")
    s := make(chan os.Signal)
    signal.Notify(s, syscall.SIGTERM)

end:
    for {
        select {
        case <-time.After(nextTickTime()):
            if time.Now().Weekday() == offsetDayOfWeekday {
                yoall()
            }
        case <-s:
            break end
        }
    }
    fmt.Println("stopping getsuyo")
}

func nextTickTime() time.Duration {
    now := time.Now()
    nextDay := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
    return nextDay.Sub(now)
}

func yoall() {
    values := url.Values{}
    values.Add("api_token", api_key)
    _, err := http.PostForm("http://api.justyo.co/yoall/", values)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Send yoall")
    }
}

まとめ

ここまでやっておいて何ですが、cronとcurlだけでほぼ同じ事ができるんですよね。
とは言え、標準ライブラリだけでこんなに簡単に作れるGoはすごいです。

12
11
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
12
11