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はすごいです。