-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetchtelegram.go
85 lines (77 loc) · 2.48 KB
/
fetchtelegram.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
package main
import (
"fmt"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
var tgbot *tgbotapi.BotAPI
func setupTelegram() {
var settings globalSettings
database.First(&settings)
if settings.APIKey != "" {
var err error
tgbot, err = tgbotapi.NewBotAPI(settings.APIKey)
output(func(print printer) {
if err != nil {
print("unable to connect to telegram")
} else {
print(fmt.Sprintf("Telegram Identity: %s", tgbot.Self.UserName))
}
})
u := tgbotapi.NewUpdate(settings.APIOffset)
u.Timeout = 60
var botupdates tgbotapi.UpdatesChannel
botupdates, err = tgbot.GetUpdatesChan(u)
output(func(print printer) {
if err != nil {
print("unable to establish updates connection")
}
})
go telegramFetcher(botupdates)
} else {
output(func(print printer) {
print("No Telegram API key set. SEt one and restart in order to start operations.")
})
}
}
func telegramFetcher(updates tgbotapi.UpdatesChannel) {
for update := range updates {
var settings globalSettings
database.First(&settings)
settings.APIOffset = update.UpdateID + 1
database.Save(&settings)
incomingmessage := update.Message
userID := incomingmessage.From.ID
storeduser := chat{TelegramID: userID}
database.Where(&storeduser).First(&storeduser)
if database.NewRecord(storeduser) {
//this is a new record, so we have to fill in the details.
storeduser.TelegramFirstName = incomingmessage.From.FirstName
storeduser.TelegramLastName = incomingmessage.From.LastName
storeduser.TelegramUserName = incomingmessage.From.UserName
if storeduser.TelegramUserName == "" {
storeduser.TelegramUserName = storeduser.TelegramFirstName
}
if storeduser.TelegramUserName == "" {
storeduser.TelegramUserName = storeduser.TelegramLastName
}
storeduser.TelegramChatID = incomingmessage.Chat.ID
database.Create(&storeduser)
}
storedmessage := message{Inbound: true, Text: incomingmessage.Text, Date: int(time.Now().Unix()), ChatID: storeduser.ID, Read: false}
database.Create(&storedmessage)
if activeChatID == storeduser.ID {
output(func(print printer) { print(storedmessage.toString()) })
} else {
updateSidebar()
}
automationqueue <- automationitem{Chat: storeduser, Message: storedmessage}
var chats []chat
database.Where(&chat{Admin: true}).Find(&chats)
for _, admin := range chats {
if admin.ID != storeduser.ID {
admin.sendMessage(fmt.Sprintf("[I] <%s> %s", storeduser.TelegramUserName, incomingmessage.Text))
}
}
}
}