/
telegram.go
93 lines (85 loc) · 2.12 KB
/
telegram.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
package bootstrap
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/ijijni/wechat-gpt/config"
"github.com/ijijni/wechat-gpt/handler/telegram"
"github.com/ijijni/wechat-gpt/utils"
log "github.com/sirupsen/logrus"
"strings"
"time"
)
func StartTelegramBot() {
telegramKey := config.GetTelegram()
if telegramKey == nil {
log.Info("未找到tg token,不启动tg tot")
return
}
bot, err := tgbotapi.NewBotAPI(*telegramKey)
if err != nil {
log.Error("tg bot 启动失败:", err.Error())
return
}
bot.Debug = false
log.Info("Authorized on account: ", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
updates := bot.GetUpdatesChan(u)
time.Sleep(time.Millisecond * 500)
for len(updates) != 0 {
<-updates
}
for update := range updates {
if update.Message == nil {
continue
}
text := update.Message.Text
chatID := update.Message.Chat.ID
chatUserName := update.Message.Chat.UserName
tgUserNameStr := config.GetTelegramWhitelist()
if tgUserNameStr != nil {
tgUserNames := strings.Split(*tgUserNameStr, ",")
if len(tgUserNames) > 0 {
found := false
for _, name := range tgUserNames {
if name == chatUserName {
found = true
break
}
}
if !found {
log.Error("用户设置了私人私用,白名单以外的人不生效: ", chatUserName)
continue
}
}
}
tgKeyWord := config.GetTelegramKeyword()
var reply *string
// 如果设置了关键字就以关键字为准,没设置就所有消息都监听
if tgKeyWord != nil {
content, key := utils.ContainsI(text, *tgKeyWord)
if len(key) == 0 {
continue
}
splitItems := strings.Split(content, key)
if len(splitItems) < 2 {
continue
}
requestText := strings.TrimSpace(splitItems[1])
log.Println("问题:", requestText)
reply = telegram.Handle(requestText)
} else {
reply = telegram.Handle(text)
}
if reply == nil {
continue
}
msg := tgbotapi.NewMessage(chatID, *reply)
send, err := bot.Send(msg)
if err != nil {
log.Errorf("发送消息出错:%s", err.Error())
continue
}
fmt.Println(send.Text)
}
select {}
}