mtfosbot/module/background/twitch.go

84 lines
1.6 KiB
Go
Raw Normal View History

2018-09-11 16:29:38 +00:00
package background
import (
"fmt"
2019-06-25 09:02:03 +00:00
"log"
2018-09-12 04:03:44 +00:00
"strings"
2018-11-29 06:19:23 +00:00
"time"
2018-09-11 16:29:38 +00:00
"git.trj.tw/golang/mtfosbot/model"
2018-09-12 04:03:44 +00:00
"git.trj.tw/golang/mtfosbot/module/apis/line"
2018-09-11 16:29:38 +00:00
"git.trj.tw/golang/mtfosbot/module/apis/twitch"
)
func getStreamStatus() {
2018-09-12 04:03:44 +00:00
channels, err := model.GetAllTwitchChannel()
2018-09-11 16:29:38 +00:00
if err != nil {
return
}
var ids []string
for _, v := range channels {
ids = append(ids, v.ID)
}
info := twitch.GetUserStreamStatus(ids)
2018-09-12 04:03:44 +00:00
if len(info) == 0 {
return
}
2018-09-11 16:29:38 +00:00
for _, v := range info {
2018-09-12 04:03:44 +00:00
for _, ch := range channels {
if v.UserID == ch.ID {
go checkStream(ch, v)
}
}
2018-09-11 16:29:38 +00:00
}
}
2018-09-12 04:03:44 +00:00
func checkStream(ch *model.TwitchChannel, info *twitch.StreamInfo) {
if info.ID == ch.LastStream {
return
}
err := ch.GetGroups()
if err != nil {
return
}
err = ch.UpdateStream(info.ID)
if err != nil {
return
}
2018-09-11 16:29:38 +00:00
2018-11-29 06:19:23 +00:00
// 開台間隔小於10分鐘不通知
if time.Now().Unix()-ch.Mtime.Unix() < 600 {
return
}
2018-12-13 08:56:48 +00:00
chData := twitch.GetUserDataByID(ch.ID)
if chData != nil {
if chData.Login != ch.Name {
ch.UpdateName(chData.Login)
}
}
2018-09-12 04:03:44 +00:00
link := fmt.Sprintf("https://twitch.tv/%s", ch.Name)
for _, v := range ch.Groups {
if v.Notify {
2019-06-25 09:02:03 +00:00
bot, err := v.GetBot()
if err != nil || bot == nil {
log.Println("get group binding bot fail :: ", err)
continue
}
2018-09-12 04:03:44 +00:00
tmpl := v.Tmpl
if len(tmpl) > 0 {
tmpl = strings.Replace(tmpl, "{txt}", info.Title, -1)
tmpl = strings.Replace(tmpl, "{link}", link, -1)
} else {
tmpl = fmt.Sprintf("%s\n%s", info.Title, link)
}
msg := line.TextMessage{
Text: tmpl,
}
2019-06-25 09:02:03 +00:00
line.PushMessage(bot.AccessToken, v.ID, msg)
2018-09-12 04:03:44 +00:00
}
}
2018-09-11 16:29:38 +00:00
}