forked from ildus/jabber_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
366 lines (320 loc) · 7.74 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package main
import (
"./telegrambot"
"./xmpp"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"path"
"strconv"
"strings"
"time"
)
type UserAccounts map[string]*Account
var (
config = flag.String("config", "settings.json", "configuration file")
conf Configuration
bot *telegrambot.Bot
accountsTable string = "accounts"
rostersTable string = "rosters"
accounts map[int]UserAccounts
currentUpdateId = 0
)
const (
MAX_ACCOUNTS = 500
)
const (
CMD_CONNECT = iota
CMD_CHECK = iota
CMD_DISCONNECT = iota
CMD_BOT_MESSAGE = iota
CMD_MESSAGE = iota
)
/* Account represents connection on this level,
UserId - id of telegram user
Jid, Host, Port - connection params
For security reasons we do not keep password here
messageJids - used for messages reply, when we get some message we keep
its id and sender, and when user wants to reply, we can determine receiver
of reply
client - xmpp connection
*/
type Account struct {
UserId int
Jid string
Host string
Port uint16
messageJids map[int]string
client *xmpp.Client
}
/* Configuration, filled from settings file */
type Configuration struct {
Listen int `json:"listen"`
Token string `json:"token"`
BaseDomain string `json:"base_domain"`
HookPath string `json:"hook_path"`
AdminUserId int `json:"admin_user_id"`
}
/* Messages to bot parsed to this struct if they has some meaning */
type Command struct {
Cmd int
Jid string
Password string
Host string
Port uint16
UserId int
Message string
}
/* Load configuration from specified file and connect to database */
func loadConfiguration() {
confData, err := ioutil.ReadFile(*config)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(confData, &conf)
if err != nil {
log.Fatal("Configuration decoding error: ", err)
}
xmpp.Init()
}
/* Creates bot, checks it and shows in console hook path */
func setupBot() {
bot = &telegrambot.Bot{Token: conf.Token}
ok, info := bot.GetMe()
if !ok {
log.Fatal("Bot setup error")
}
log.Printf("Bot username is: %s", info["username"].(string))
hookPath := path.Join("https://", conf.BaseDomain, conf.HookPath)
log.Println("Hook expected on: ", hookPath)
}
/* Creates xmpp connection
User can have more than one connection, it all is keeped in `accounts`
First key is user_id, second - jid
It creates client, start client listening, and start own goroutine
that listens messages from client channel
*/
func Connect(user_id int, jid string, password string,
host string, port uint16) error {
if accounts == nil {
accounts = make(map[int]UserAccounts)
}
/* adding to accounts table */
if _, ok := accounts[user_id]; !ok {
accounts[user_id] = make(UserAccounts)
}
if _, ok := accounts[user_id][jid]; ok {
return errors.New("Account already connected")
}
if len(accounts) >= MAX_ACCOUNTS {
return errors.New("Accounts limit exceeded")
}
client := &xmpp.Client{Jid: jid}
err := client.Connect(password, host, port)
if err != nil {
log.Println("Connection error: ", err)
return errors.New("Connection error")
}
user_accounts := accounts[user_id]
account := &Account{
Jid: jid,
Host: host,
Port: port,
client: client,
}
user_accounts[jid] = account
client.Listen()
// start listening messages from jabber
go func() {
defer func() {
if err := recover(); err != nil {
log.Println("Messages listening error: ", err)
}
}()
defer delete(user_accounts, jid)
messageJids := make(map[int]string)
user_accounts[jid].messageJids = messageJids
for msg := range client.Channel {
msg_jid := strings.Split(msg.From, "/")[0]
text := fmt.Sprintf("%s %s", msg_jid, msg.Text)
message_id := SendMessage(user_id, text)
if message_id > 0 {
messageJids[message_id] = msg_jid
}
}
}()
return nil
}
func Disconnect(user_id int) {
if user_accounts, ok := accounts[user_id]; ok {
for jid, account := range user_accounts {
log.Println("%s disconnected", jid)
account.client.Disconnect()
}
}
}
func SendMessage(user_id int, text string) int {
return bot.SendMessage(user_id, text)
}
func parseCommand(message *telegrambot.Message) (*Command, error) {
defer func() {
if err := recover(); err != nil {
log.Println("Command parse error", message.Text)
}
}()
text := message.Text
if len(text) > 5000 {
return nil, errors.New("Too long command")
}
var err error
parts := strings.Split(strings.Trim(text, " "), " ")
cmd := parts[0]
if cmd == "/connect" {
if len(parts) < 3 {
return nil, errors.New("Need more args")
}
jid, pass := parts[1], parts[2]
if !EmailIsValid(jid) {
return nil, errors.New("Enter valid jid")
}
host, port := "", 0
if len(parts) == 4 {
host = parts[3]
}
if len(parts) == 5 {
port, err = strconv.Atoi(parts[4])
if err != nil {
return nil, errors.New("Port format error")
}
}
command := &Command{
Cmd: CMD_CONNECT,
Jid: jid,
Password: pass,
Host: host,
Port: uint16(port),
}
return command, nil
} else if cmd == "/check" || cmd == "/ch" {
return &Command{Cmd: CMD_CHECK}, nil
} else if cmd == "/disconnect" || cmd == "/d" {
return &Command{Cmd: CMD_DISCONNECT}, nil
} else if cmd == "/bot_message" && conf.AdminUserId > 0 {
user_id, err := strconv.Atoi(parts[1])
if err == nil {
msg := strings.Join(parts[2:], " ")
return &Command{
Cmd: CMD_BOT_MESSAGE,
Message: msg,
UserId: user_id,
}, nil
}
} else if cmd == "/message" {
receiver := parts[1]
if !EmailIsValid(receiver) {
return nil, errors.New("Enter valid recipient")
}
msg := strings.Join(parts[2:], "")
return &Command{
Cmd: CMD_MESSAGE,
Message: msg,
Jid: receiver,
}, nil
}
if conf.AdminUserId > 0 {
text := fmt.Sprintf("%d %s %s %s",
message.From.Id,
message.From.FirstName,
message.From.Username,
message.Text)
SendMessage(conf.AdminUserId, text)
}
return nil, errors.New("Unknown command")
}
func onUpdate(update *telegrambot.Update) {
defer func() {
if err := recover(); err != nil {
log.Println("Update handling error: ", err)
}
}()
if currentUpdateId > 0 && update.Id < currentUpdateId {
return
}
currentUpdateId = update.Id
message := &update.Msg
user_id := message.From.Id
// there is no message
if user_id == 0 {
return
}
// only private chat
if user_id != message.Chat.Id {
return
}
// skip forwared messages
if message.ForwardDate > 0 {
return
}
reply_to_id := message.ReplyTo.MessageId
if reply_to_id > 0 {
// is reply
user_accounts, ok := accounts[user_id]
if !ok {
SendMessage(user_id, "You are not connected")
}
for _, account := range user_accounts {
if jid, ok := account.messageJids[reply_to_id]; ok {
account.client.SendMessage(jid, message.Text)
break
}
}
return
}
command, err := parseCommand(message)
if err != nil {
SendMessage(message.From.Id, err.Error())
return
}
switch command.Cmd {
case CMD_CONNECT:
{
err = Connect(message.From.Id, command.Jid, command.Password,
command.Host, command.Port)
if err != nil {
SendMessage(message.From.Id, err.Error())
}
}
case CMD_DISCONNECT:
Disconnect(message.From.Id)
case CMD_BOT_MESSAGE:
{
if conf.AdminUserId == user_id {
SendMessage(command.UserId, command.Message)
}
}
}
}
func listen() {
routes := mux.NewRouter()
bot.OnUpdate = onUpdate
routes.HandleFunc(conf.HookPath, bot.Hook)
s := &http.Server{
Addr: fmt.Sprintf(":%d", conf.Listen),
Handler: routes,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}
func main() {
log.Println("Server started")
loadConfiguration()
setupBot()
listen()
}