-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathtgbot.go
109 lines (90 loc) · 2.37 KB
/
tgbot.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
tb "gopkg.in/tucnak/telebot.v2"
)
var (
sharingURL = os.Getenv("SHARE_BOT_URL")
notifyURL = os.Getenv("NOTIFY_URL")
notifyToken = os.Getenv("NOTIFY_TOKEN")
botAdminUserID = os.Getenv("BOT_ADMIN_USER_ID")
)
// sendNotifyToApp 往推送发一个通知
func sendNotifyToApp(brief string) {
body := map[string]string{"token": notifyToken, "title": "发布了一篇新的博客", "brief": brief, "route": "https://jiajunhuang.com"}
jsonBytes, err := json.Marshal(body)
if err != nil {
log.Printf("failed to marshal json %+v: %s", body, err)
return
}
resp, err := http.Post(notifyURL, "application/json", bytes.NewReader(jsonBytes))
if err != nil {
log.Printf("failed to notify system: %s", err)
return
}
defer resp.Body.Close()
log.Printf("successfully notify the system")
}
func startSharingBot() {
b, err := tb.NewBot(tb.Settings{
Token: os.Getenv("SHARE_TGBOT_TOKEN"),
URL: "https://api.telegram.org",
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatalf("failed to start telegram bot: %s", err)
return
}
b.Handle("/comment", func(m *tb.Message) {
if !(m.Private() && fmt.Sprintf("%d", m.Sender.ID) == botAdminUserID) {
return
}
if err := dao.CommentLatestSharing(m.Payload); err != nil {
b.Send(m.Sender, fmt.Sprintf("failed to comment: %s", err))
return
}
b.Send(m.Sender, "commented")
})
b.Handle(tb.OnChannelPost, func(m *tb.Message) {
log.Printf("received channel message %+v", m)
if m.FromChannel() {
log.Printf("gonna send request to notify system")
sendNotifyToApp(m.Text)
return
}
})
b.Handle(tb.OnText, func(m *tb.Message) {
log.Printf("received text message %+v", m)
if !(m.Private() && fmt.Sprintf("%d", m.Sender.ID) == botAdminUserID) {
return
}
dao.AddSharing(m.Text)
b.Send(m.Sender, "saved")
})
b.Start()
}
func startNoteBot() {
b, err := tb.NewBot(tb.Settings{
Token: os.Getenv("NOTE_TGBOT_TOKEN"),
URL: "https://api.telegram.org",
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatalf("failed to start telegram bot: %s", err)
return
}
b.Handle(tb.OnText, func(m *tb.Message) {
if !(m.Private() && fmt.Sprintf("%d", m.Sender.ID) == botAdminUserID) {
return
}
dao.AddNote(m.Text)
b.Send(m.Sender, "saved")
})
b.Start()
}