-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram.go
More file actions
196 lines (177 loc) · 5.02 KB
/
Copy pathtelegram.go
File metadata and controls
196 lines (177 loc) · 5.02 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
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
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2025 Aaron LI
//
// Telegram bot to post messages.
//
// Telegram setup:
// 1. Search "@BotFather" and open a chat;
// 2. Send "/newbot" to create the bot;
// 3. Send "/mybots" and choose the created bot to edit it;
// 4. Choose "Edit Bot" and then "Edit Commands";
// 5. Send "start - Get the ChatID to start using the bot";
// 6. Search and find the created bot, or add the bot to the group;
// 7. Send "/start" to the bot to get the ChatID;
// 8. Update the config file of this program and restart.
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
const (
// Shorten the poll timeout to get rid of the error (unharmful) logs:
// "error get update, error do request for method getUpdates ...
// unexpected EOF".
pollTimeout = 30 * time.Second
)
type TgBot struct {
bot *bot.Bot
chats []int64
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewTgBot(token string, chats []int64) (*TgBot, error) {
b, err := bot.New(token,
bot.WithHTTPClient(pollTimeout, &http.Client{
Timeout: 2 * pollTimeout,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
// Disable keepalive allows the TG bot to
// quickly reconnect after a network
// disconnection (e.g., laptop suspend+resume);
// otherwise, there would be multiple errors
// logs: "context deadline exceeded
// (Client.Timeout exceeded while awaiting
// headers)"; which might lasts >30 minutes.
DisableKeepAlives: true,
},
}),
bot.WithMiddlewares(func(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
if m := update.Message; m != nil {
slog.Debug("TG bot received message",
"from", m.From.Username, "text", m.Text)
} else {
slog.Debug("TG bot received update", "id", update.ID)
}
next(ctx, b, update)
}
}),
)
if err != nil {
slog.Error("TG bot creation failed", "error", err)
return nil, err
}
tgbot := &TgBot{
bot: b,
chats: chats,
}
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact,
func(ctx context.Context, _ *bot.Bot, update *models.Update) {
chat := update.Message.Chat.ID
tgbot.send(ctx, &bot.SendMessageParams{
ChatID: chat,
Text: fmt.Sprintf("The Chat ID is <code>%d</code>.", chat),
ParseMode: models.ParseModeHTML,
})
})
b.RegisterHandler(bot.HandlerTypeMessageText, "/whoami", bot.MatchTypeExact,
func(ctx context.Context, _ *bot.Bot, update *models.Update) {
chat := update.Message.Chat.ID
tgbot.send(ctx, &bot.SendMessageParams{
ChatID: chat,
Text: fmt.Sprintf("You are in Chat ID: <code>%d</code>.", chat),
ParseMode: models.ParseModeHTML,
})
})
b.RegisterHandler(bot.HandlerTypeMessageText, "", bot.MatchTypePrefix,
func(ctx context.Context, _ *bot.Bot, update *models.Update) {
m := update.Message
if !strings.HasPrefix(m.Text, "/") {
slog.Debug("TG bot received non-command message",
"from", m.From.Username, "text", m.Text)
return
}
tgbot.send(ctx, &bot.SendMessageParams{
ChatID: m.Chat.ID,
Text: "Sorry, I don't know that command.",
ReplyParameters: &models.ReplyParameters{
MessageID: m.ID,
},
})
})
return tgbot, nil
}
func (b *TgBot) send(ctx context.Context, msg *bot.SendMessageParams) {
if _, err := b.bot.SendMessage(ctx, msg); err != nil {
slog.Error("TG bot sending failed",
"to", msg.ChatID, "text", msg.Text, "error", err)
}
}
func (b *TgBot) Start() {
b.ctx, b.cancel = context.WithCancel(context.Background())
if me, err := b.bot.GetMe(b.ctx); err != nil {
slog.Error("TG bot GetMe failed", "error", err)
return
} else {
slog.Info("TG bot started", "id", me.ID, "username", me.Username)
}
b.wg.Add(1)
b.bot.Start(b.ctx)
slog.Info("TG bot polling stopped")
b.wg.Done()
}
func (b *TgBot) Stop() {
if b.cancel != nil {
b.cancel()
b.cancel = nil
b.ctx = nil
}
b.wg.Wait()
slog.Info("TG bot stopped")
}
func (b *TgBot) Post(msg Message) {
if !strings.HasPrefix(msg.Target, "#") {
return // Ignore private messages.
}
if b.ctx == nil {
slog.Error("TG bot called but not started")
return
}
var text string
switch msg.Source {
case SourceIRC:
text = fmt.Sprintf("<b>[IRC %s]</b> ", msg.Target)
if msg.Event == "ACTION" {
text += fmt.Sprintf("👉 <code>%s</code> ", msg.From)
} else {
text += fmt.Sprintf("<code>%s</code>💬 ", msg.From)
}
case SourceWebhook:
text = fmt.Sprintf("<b>[Webhook %s]</b> ", msg.Target)
text += fmt.Sprintf("<code>%s</code>📢 ", msg.From)
default:
text = fmt.Sprintf("<b>[❓ %s]</b> ", msg.Target)
text += fmt.Sprintf("<code>%s</code> ", msg.From)
}
text += strings.NewReplacer(
"&", "&",
"<", "<",
">", ">",
).Replace(msg.Text)
for _, chatID := range b.chats {
b.send(b.ctx, &bot.SendMessageParams{
ChatID: chatID,
Text: text,
ParseMode: models.ParseModeHTML,
})
}
}