-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathmain.go
268 lines (235 loc) · 6.82 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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"strconv"
"sync"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/spf13/viper"
"golang.org/x/net/proxy"
tb "gopkg.in/tucnak/telebot.v2"
)
// Config struct for toml config file
type Config struct {
ButtonText string `mapstructure:"button_text"`
WelcomeMessage string `mapstructure:"welcome_message"`
AfterSuccessMessage string `mapstructure:"after_success_message"`
AfterFailMessage string `mapstructure:"after_fail_message"`
PrintSuccessAndFail string `mapstructure:"print_success_and_fail_messages_strategy"`
WelcomeTimeout string `mapstructure:"welcome_timeout"`
BanDurations string `mapstructure:"ban_duration"`
UseSocks5Proxy string `mapstructure:"use_socks5_proxy"`
Socks5Address string `mapstructure:"socks5_address"`
Socks5Port string `mapstructure:"socks5_port"`
Socks5Login string `mapstructure:"socks5_login"`
Socks5Password string `mapstructure:"socks5_password"`
}
var config Config
var passedUsers = sync.Map{}
var bot *tb.Bot
var tgtoken = "TGTOKEN"
var configPath = "CONFIG_PATH"
func init() {
err := readConfig()
if err != nil {
log.Fatalf("Cannot read config file. Error: %v", err)
}
}
func main() {
token, err := getToken(tgtoken)
if err != nil {
log.Fatalln(err)
}
log.Printf("Telegram Bot Token [%v] successfully obtained from env variable $TGTOKEN\n", token)
var httpClient *http.Client
if config.UseSocks5Proxy == "yes" {
var err error
httpClient, err = initSocks5Client()
if err != nil {
log.Fatalln(err)
}
}
bot, err = tb.NewBot(tb.Settings{
Token: token,
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
Client: httpClient,
})
if err != nil {
log.Fatalf("Cannot start bot. Error: %v\n", err)
}
bot.Handle(tb.OnUserJoined, challengeUser)
bot.Handle(tb.OnCallback, passChallenge)
bot.Handle("/healthz", func(m *tb.Message) {
msg := "I'm OK"
if _, err := bot.Send(m.Chat, msg); err != nil {
log.Println(err)
}
log.Printf("Healthz request from user: %v\n in chat: %v", m.Sender, m.Chat)
})
log.Println("Bot started!")
go func() {
bot.Start()
}()
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
<-signalChan
log.Println("Shutdown signal received, exiting...")
}
func challengeUser(m *tb.Message) {
if m.UserJoined.ID != m.Sender.ID {
return
}
log.Printf("User: %v joined the chat: %v", m.UserJoined, m.Chat)
if member, err := bot.ChatMemberOf(m.Chat, m.UserJoined); err == nil {
if member.Role == tb.Restricted {
log.Printf("User: %v already restricted in chat: %v", m.UserJoined, m.Chat)
return
}
}
newChatMember := tb.ChatMember{User: m.UserJoined, RestrictedUntil: tb.Forever(), Rights: tb.Rights{CanSendMessages: false}}
err := bot.Restrict(m.Chat, &newChatMember)
if err != nil {
log.Println(err)
}
inlineKeys := [][]tb.InlineButton{{tb.InlineButton{
Unique: "challenge_btn",
Text: config.ButtonText,
}}}
challengeMsg, err := bot.Reply(m, config.WelcomeMessage, &tb.ReplyMarkup{InlineKeyboard: inlineKeys})
if err != nil {
log.Printf("Can't send challenge msg: %v", err)
return
}
n, err := strconv.ParseInt(config.WelcomeTimeout, 10, 64)
if err != nil {
log.Println(err)
}
time.AfterFunc(time.Duration(n)*time.Second, func() {
_, passed := passedUsers.Load(m.UserJoined.ID)
if !passed {
banDuration, e := getBanDuration()
if e != nil {
log.Println(e)
}
chatMember := tb.ChatMember{User: m.UserJoined, RestrictedUntil: banDuration}
err := bot.Ban(m.Chat, &chatMember)
if err != nil {
log.Println(err)
}
if config.PrintSuccessAndFail == "show" {
_, err := bot.Edit(challengeMsg, config.AfterFailMessage)
if err != nil {
log.Println(err)
}
} else if config.PrintSuccessAndFail == "del" {
err := bot.Delete(m)
if err != nil {
log.Println(err)
}
err = bot.Delete(challengeMsg)
if err != nil {
log.Println(err)
}
}
log.Printf("User: %v was banned in chat: %v for: %v minutes", m.UserJoined, m.Chat, config.BanDurations)
}
passedUsers.Delete(m.UserJoined.ID)
})
}
// passChallenge is used when user passed the validation
func passChallenge(c *tb.Callback) {
if c.Message.ReplyTo.Sender.ID != c.Sender.ID {
err := bot.Respond(c, &tb.CallbackResponse{Text: "This button isn't for you"})
if err != nil {
log.Println(err)
}
return
}
passedUsers.Store(c.Sender.ID, struct{}{})
if config.PrintSuccessAndFail == "show" {
_, err := bot.Edit(c.Message, config.AfterSuccessMessage)
if err != nil {
log.Println(err)
}
} else if config.PrintSuccessAndFail == "del" {
err := bot.Delete(c.Message)
if err != nil {
log.Println(err)
}
}
log.Printf("User: %v passed the challenge in chat: %v", c.Sender, c.Message.Chat)
newChatMember := tb.ChatMember{User: c.Sender, RestrictedUntil: tb.Forever(), Rights: tb.Rights{CanSendMessages: true}}
err := bot.Promote(c.Message.Chat, &newChatMember)
if err != nil {
log.Println(err)
}
err = bot.Respond(c, &tb.CallbackResponse{Text: "Validation passed!"})
if err != nil {
log.Println(err)
}
}
func readConfig() (err error) {
v := viper.New()
path, ok := os.LookupEnv(configPath)
if ok {
v.SetConfigName("config")
v.AddConfigPath(path)
}
v.SetConfigName("config")
v.AddConfigPath(".")
if err = v.ReadInConfig(); err != nil {
return err
}
if err = v.Unmarshal(&config); err != nil {
return err
}
return
}
func getToken(key string) (string, error) {
token, ok := os.LookupEnv(key)
if !ok {
err := errors.Errorf("Env variable %v isn't set!", key)
return "", err
}
match, err := regexp.MatchString(`^[0-9]+:.*$`, token)
if err != nil {
return "", err
}
if !match {
err := errors.Errorf("Telegram Bot Token [%v] is incorrect. Token doesn't comply with regexp: `^[0-9]+:.*$`. Please, provide a correct Telegram Bot Token through env variable TGTOKEN", token)
return "", err
}
return token, nil
}
func getBanDuration() (int64, error) {
if config.BanDurations == "forever" {
return tb.Forever(), nil
}
n, err := strconv.ParseInt(config.BanDurations, 10, 64)
if err != nil {
return 0, err
}
return time.Now().Add(time.Duration(n) * time.Minute).Unix(), nil
}
func initSocks5Client() (*http.Client, error) {
addr := fmt.Sprintf("%s:%s", config.Socks5Address, config.Socks5Port)
dialer, err := proxy.SOCKS5("tcp", addr, &proxy.Auth{User: config.Socks5Login, Password: config.Socks5Password}, proxy.Direct)
if err != nil {
return nil, fmt.Errorf("cannot init socks5 proxy client dialer: %w", err)
}
httpTransport := &http.Transport{}
httpClient := &http.Client{Transport: httpTransport}
dialContext := func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.Dial(network, address)
}
httpTransport.DialContext = dialContext
return httpClient, nil
}