-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtelegram.go
More file actions
84 lines (72 loc) · 2.15 KB
/
Copy pathtelegram.go
File metadata and controls
84 lines (72 loc) · 2.15 KB
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
// Package telegram handles all Telegram-side logic.
package telegram
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/ritlug/teleirc/internal"
)
/*
Client contains information for the Telegram bridge, including
the TelegramSettings needed to run the bot
*/
type Client struct {
api *tgbotapi.BotAPI
Settings *internal.TelegramSettings
IRCSettings *internal.IRCSettings
ImgurSettings *internal.ImgurSettings
logger internal.DebugLogger
sendToIrc func(string)
}
/*
NewClient creates a new Telegram bot client
*/
func NewClient(settings *internal.TelegramSettings, ircsettings *internal.IRCSettings, imgur *internal.ImgurSettings, tgapi *tgbotapi.BotAPI, logger internal.DebugLogger) *Client {
logger.LogInfo("Creating new Telegram bot client...")
return &Client{api: tgapi, Settings: settings, IRCSettings: ircsettings, ImgurSettings: imgur, logger: logger}
}
/*
SendMessage sends a message to the Telegram channel specified in the settings
*/
func (tg *Client) SendMessage(msg string) {
newMsg := tgbotapi.NewMessage(tg.Settings.ChatID, "")
newMsg.Text = msg
if tg.Settings.QuoteNick {
newMsg.ParseMode = "HTML"
}
if _, err := tg.api.Send(newMsg); err != nil {
var attempts int = 0
// Try resending 3 times if the message is successfully sent
for err != nil && attempts < 3 {
tg.logger.LogError(err)
attempts++
_, err = tg.api.Send(newMsg)
}
}
}
/*
StartBot adds necessary handlers to the client and then connects,
returning any errors that occur
*/
func (tg *Client) StartBot(errChan chan<- error, sendMessage func(string)) {
tg.logger.LogInfo("Starting up Telegram bot...")
var err error
tg.api, err = tgbotapi.NewBotAPI(tg.Settings.Token)
if err != nil {
tg.logger.LogError(err)
errChan <- err
}
if tg.api == nil {
tg.logger.LogError("Failed to authenticate to Telegram")
errChan <- err
}
tg.logger.LogInfo("Authorized on account", tg.api.Self.UserName)
tg.sendToIrc = sendMessage
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := tg.api.GetUpdatesChan(u)
if err != nil {
errChan <- err
tg.logger.LogError(err)
}
updateHandler(tg, updates)
errChan <- nil
}