-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.go
190 lines (160 loc) · 4.47 KB
/
bot.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"bytes"
"encoding/json"
"flag"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/abadojack/whatlanggo"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TranslationRequest struct {
Text string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
}
type TranslationResponse struct {
Data string `json:"data"`
}
var (
allowedGroups map[int64]bool
allowedUsers map[int64]bool
ignoreLangs map[string]bool
targetLang string
botToken string
apiURL string
)
func main() {
// Parse command-line flags
flag.StringVar(&botToken, "token", "", "Telegram Bot Token")
flag.StringVar(&targetLang, "target", "ZH", "Target language for translation")
flag.StringVar(&apiURL, "api", "http://127.0.0.1:1188/translate", "API URL for translation service")
ignoreLangsFlag := flag.String("ignore", "ZH", "Comma-separated list of languages to ignore")
allowedGroupsFlag := flag.String("groups", "", "Comma-separated list of allowed group IDs")
allowedUsersFlag := flag.String("users", "", "Comma-separated list of allowed user IDs")
flag.Parse()
// Use environment variables if flags are not set
if botToken == "" {
botToken = os.Getenv("BOT_TOKEN")
}
if targetLang == "ZH" {
targetLang = getEnv("TARGET_LANG", "ZH")
}
if apiURL == "http://127.0.0.1:1188/translate" {
apiURL = getEnv("API_URL", "http://127.0.0.1:1188/translate")
}
if *ignoreLangsFlag == "ZH" {
*ignoreLangsFlag = getEnv("IGNORE_LANGS", "ZH")
}
if *allowedGroupsFlag == "" {
*allowedGroupsFlag = os.Getenv("ALLOWED_GROUPS")
}
if *allowedUsersFlag == "" {
*allowedUsersFlag = os.Getenv("ALLOWED_USERS")
}
// Initialize configuration
initConfig(*ignoreLangsFlag, *allowedGroupsFlag, *allowedUsersFlag)
bot, err := tgbotapi.NewBotAPI(botToken)
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
log.Printf("Using API URL: %s", apiURL)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
go handleMessage(bot, update.Message)
}
}
func initConfig(ignoreLangsStr, allowedGroupsStr, allowedUsersStr string) {
ignoreLangs = make(map[string]bool)
for _, lang := range strings.Split(ignoreLangsStr, ",") {
ignoreLangs[strings.TrimSpace(strings.ToUpper(lang))] = true
}
allowedGroups = make(map[int64]bool)
for _, groupID := range strings.Split(allowedGroupsStr, ",") {
if id, err := strconv.ParseInt(strings.TrimSpace(groupID), 10, 64); err == nil {
allowedGroups[id] = true
}
}
allowedUsers = make(map[int64]bool)
for _, userID := range strings.Split(allowedUsersStr, ",") {
if id, err := strconv.ParseInt(strings.TrimSpace(userID), 10, 64); err == nil {
allowedUsers[id] = true
}
}
}
func handleMessage(bot *tgbotapi.BotAPI, message *tgbotapi.Message) {
if !isAllowed(message) {
log.Printf("Message from non-whitelisted source: %d", message.Chat.ID)
return
}
if !shouldIgnore(message.Text) {
translatedText, err := translate(message.Text)
if err != nil {
log.Printf("Translation error: %v", err)
return
}
msg := tgbotapi.NewMessage(message.Chat.ID, translatedText)
msg.ReplyToMessageID = message.MessageID
_, err = bot.Send(msg)
if err != nil {
log.Printf("Error sending message: %v", err)
}
}
}
func isAllowed(message *tgbotapi.Message) bool {
if len(allowedGroups) == 0 && len(allowedUsers) == 0 {
return true
}
if message.Chat.Type == "private" {
return allowedUsers[message.From.ID]
} else {
return allowedGroups[message.Chat.ID]
}
}
func shouldIgnore(text string) bool {
lang := whatlanggo.DetectLang(text)
sourceLang := strings.ToUpper(lang.Iso6391())
return ignoreLangs[sourceLang]
}
func translate(text string) (string, error) {
requestBody, err := json.Marshal(TranslationRequest{
Text: text,
SourceLang: "auto",
TargetLang: targetLang,
})
if err != nil {
return "", err
}
resp, err := http.Post(apiURL, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var translationResp TranslationResponse
err = json.Unmarshal(body, &translationResp)
if err != nil {
return "", err
}
return translationResp.Data, nil
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}