-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (72 loc) · 1.71 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/hpcloud/tail"
)
func main() {
var confFile string
var telegramBotToken string
flag.StringVar(&confFile, "conf", "./conf.json", "-conf=xxx.json")
flag.Parse()
telegramBotToken = os.Getenv("TG_TOKEN")
conf := parseConf(confFile)
bot, err := tgbotapi.NewBotAPI(telegramBotToken)
pe(err)
ctx := context.Background()
for _, fw := range conf.Files {
f := fw
go func() {
f.start(ctx, &conf, bot)
}()
}
c := make(chan struct{})
<-c
}
func parseConf(path string) Conf {
b, err := ioutil.ReadFile(path)
pe(err)
var conf Conf
err = json.Unmarshal(b, &conf)
pe(err)
return conf
}
type Conf struct {
ChatID int64 `json:"chat_id,omitempty"`
Files []*FileWatcher `json:"files,omitempty"`
}
func (c Conf) SendMessage(bot *tgbotapi.BotAPI, text string) {
_, err := bot.Send(tgbotapi.NewMessage(c.ChatID, text))
if err != nil {
fmt.Println("[ERR] send bot msg err", err)
}
}
type FileWatcher struct {
File string `json:"file,omitempty"`
Content string `json:"content,omitempty"` //content to watch in line
}
func pe(err error) {
if err != nil {
panic(err)
}
}
func (fw *FileWatcher) start(ctx context.Context, conf *Conf, bot *tgbotapi.BotAPI) {
t, err := tail.TailFile(fw.File, tail.Config{Follow: true, ReOpen: true, Location: &tail.SeekInfo{Whence: 2}})
pe(err)
for line := range t.Lines {
if line.Err != nil {
continue
}
if strings.Contains(line.Text, fw.Content) {
msg := fmt.Sprintf("find %s in %s, line: %s", fw.Content, fw.File, line.Text)
fmt.Println("[warn]", msg)
conf.SendMessage(bot, msg)
}
}
}