-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
503 lines (425 loc) · 12.9 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"gopkg.in/yaml.v2"
)
type Config struct {
TelegramBotToken string `yaml:"telegram_bot_token"`
}
var awaitingInput = make(map[int64]string)
var userSettings = make(map[int64]UserSettings)
var messageBuffers = make(map[int64]*bytes.Buffer)
type UserSettings struct {
Token string
Domain string
}
func main() {
config := Config{}
configFile, err := os.ReadFile("secrets.yml")
if err != nil {
log.Panic(err)
}
err = yaml.Unmarshal(configFile, &config)
if err != nil {
log.Panic(err)
}
bot, err := tgbotapi.NewBotAPI(config.TelegramBotToken)
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Panic(err)
}
loadUserSettingsFromFile("tokens.txt", "token")
loadUserSettingsFromFile("domains.txt", "domain")
checkTicker := time.NewTicker(5 * time.Minute)
go func() {
for range checkTicker.C {
checkAndSendOldestPosts(bot)
}
}()
for update := range updates {
if update.Message == nil {
continue
}
chatID := update.Message.Chat.ID
if update.Message.IsCommand() {
if update.Message.Command() == "send" {
handleSendCommand(chatID, bot)
continue
}
handleCommand(update.Message, bot)
} else if inputType, ok := awaitingInput[chatID]; ok {
handleUserInput(chatID, inputType, update.Message.Text)
} else {
bufferMessage(chatID, update.Message.Text)
}
}
}
func checkAndSendOldestPosts(bot *tgbotapi.BotAPI) {
for userID, settings := range userSettings {
if shouldSendPost(settings) {
sendOldestPost(bot, userID, settings)
}
}
}
func shouldSendPost(settings UserSettings) bool {
lastPostTime, err := getLastPostTime(settings.Domain, settings.Token)
if err != nil {
log.Printf("Error fetching last post time: %v", err)
return false
}
fmt.Printf("Last post time: %v\n", lastPostTime)
return time.Since(lastPostTime) >= 4*time.Hour
}
func getLastPostTime(domain, token string) (time.Time, error) {
userID, err := getUserID(domain, token)
if err != nil {
return time.Time{}, fmt.Errorf("error getting user ID: %w", err)
}
apiUrl := fmt.Sprintf("https://%s/api/v1/accounts/%d/statuses", domain, userID)
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
return time.Time{}, fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return time.Time{}, fmt.Errorf("error fetching user statuses: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return time.Time{}, fmt.Errorf("received non-success status code %d", resp.StatusCode)
}
var posts []map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&posts); err != nil {
return time.Time{}, fmt.Errorf("error decoding response: %w", err)
}
for _, post := range posts {
if inReplyToID, exists := post["in_reply_to_id"]; (!exists || inReplyToID == nil) && (post["reblog"] == false || post["reblog"] == nil) {
createdAt, ok := post["created_at"].(string)
if !ok {
continue
}
postTime, err := time.Parse(time.RFC3339, createdAt)
if err != nil {
log.Printf("Error parsing time: %v", err)
continue
}
return postTime, nil
}
}
return time.Time{}, errors.New("no valid posts found")
}
func getUserID(domain, token string) (int64, error) {
apiUrl := fmt.Sprintf("https://%s/api/v1/accounts/verify_credentials", domain)
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
return 0, fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return 0, fmt.Errorf("error fetching user credentials: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return 0, fmt.Errorf("received non-success status code %d", resp.StatusCode)
}
var userData map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&userData); err != nil {
return 0, fmt.Errorf("error decoding response: %w", err)
}
id, ok := userData["id"].(string)
if !ok {
return 0, errors.New("user ID not found in response")
}
userID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return 0, fmt.Errorf("error parsing user ID: %w", err)
}
return userID, nil
}
func sendOldestPost(bot *tgbotapi.BotAPI, userID int64, settings UserSettings) {
dirPath := fmt.Sprintf("posts/%d", userID)
files, err := ioutil.ReadDir(dirPath)
if err != nil {
log.Printf("Error reading directory for user %d: %v", userID, err)
return
}
if len(files) == 0 {
return // No posts to send for this user
}
// Assuming files are named with Unix timestamps, the oldest will be the first
oldestFile := files[0]
for _, file := range files {
if file.ModTime().Before(oldestFile.ModTime()) {
oldestFile = file
}
}
filePath := filepath.Join(dirPath, oldestFile.Name())
content, err := ioutil.ReadFile(filePath)
if err != nil {
log.Printf("Error reading file for user %d: %v", userID, err)
return
}
// Post content to Mastodon
postLink, err := postToMastodon(settings.Domain, settings.Token, string(content))
if err != nil {
log.Printf("Error posting to Mastodon for user %d: %v", userID, err)
return
}
// Delete the file after successful post
if err := os.Remove(filePath); err != nil {
log.Printf("Error deleting file for user %d: %v", userID, err)
return
}
// Notify the user about the successful post
message := fmt.Sprintf("Post sent: %s", postLink)
msg := tgbotapi.NewMessage(userID, message)
bot.Send(msg)
}
func handleSendCommand(chatID int64, bot *tgbotapi.BotAPI) {
if buffer, ok := messageBuffers[chatID]; ok && buffer.Len() > 0 {
err := savePostToFile(chatID, buffer.String())
if err != nil {
bot.Send(tgbotapi.NewMessage(chatID, fmt.Sprintf("Error saving post: %v", err)))
} else {
bot.Send(tgbotapi.NewMessage(chatID, "Messages saved to file."))
}
buffer.Reset()
} else {
bot.Send(tgbotapi.NewMessage(chatID, "No messages to save."))
}
}
func savePostToFile(userID int64, content string) error {
dirPath := fmt.Sprintf("posts/%d", userID)
if err := os.MkdirAll(dirPath, 0755); err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
filePath := fmt.Sprintf("%s/%d.txt", dirPath, time.Now().Unix())
return ioutil.WriteFile(filePath, []byte(content), 0644)
}
func bufferMessage(chatID int64, message string) {
if _, ok := messageBuffers[chatID]; !ok {
messageBuffers[chatID] = new(bytes.Buffer)
}
buffer := messageBuffers[chatID]
if buffer.Len() > 0 {
buffer.WriteString("\n\n")
}
buffer.WriteString(message)
}
func handleCommand(message *tgbotapi.Message, bot *tgbotapi.BotAPI) {
chatID := message.Chat.ID
switch message.Command() {
case "token":
awaitingInput[chatID] = "token"
bot.Send(tgbotapi.NewMessage(chatID, "Please send your Mastodon access token."))
case "domain":
awaitingInput[chatID] = "domain"
bot.Send(tgbotapi.NewMessage(chatID, "Please send your Mastodon instance domain."))
case "list":
handleListCommand(chatID, bot)
case "count":
handleCountCommand(chatID, bot)
case "help":
commands := `Commands:
/token - Set your Mastodon access token
/domain - Set your Mastodon instance domain
/list - List all outstanding posts
/count - Count all outstanding posts
/help - Show this help message`
bot.Send(tgbotapi.NewMessage(chatID, commands))
default:
bot.Send(tgbotapi.NewMessage(chatID, "I don't know that command"))
}
}
func handleCountCommand(chatID int64, bot *tgbotapi.BotAPI) {
dirPath := fmt.Sprintf("posts/%d", chatID)
files, err := ioutil.ReadDir(dirPath)
if err != nil {
if os.IsNotExist(err) {
bot.Send(tgbotapi.NewMessage(chatID, "No outstanding posts."))
} else {
bot.Send(tgbotapi.NewMessage(chatID, "Error reading post directory."))
}
return
}
count := len(files)
if count == 0 {
bot.Send(tgbotapi.NewMessage(chatID, "No outstanding posts."))
} else {
bot.Send(tgbotapi.NewMessage(chatID, fmt.Sprintf("You have %d outstanding post(s).", count)))
}
}
func handleListCommand(chatID int64, bot *tgbotapi.BotAPI) {
dirPath := fmt.Sprintf("posts/%d", chatID)
files, err := ioutil.ReadDir(dirPath)
if err != nil {
bot.Send(tgbotapi.NewMessage(chatID, "Error reading post directory."))
return
}
if len(files) == 0 {
bot.Send(tgbotapi.NewMessage(chatID, "No outstanding posts."))
return
}
// Sort files by modification time in ascending order (oldest first)
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime().Before(files[j].ModTime())
})
var response strings.Builder
response.WriteString("List of outstanding posts:\n")
for _, file := range files {
filePath := filepath.Join(dirPath, file.Name())
content, err := ioutil.ReadFile(filePath)
if err != nil {
log.Printf("Error reading file %s: %v", filePath, err)
continue
}
formattedTime := file.ModTime().Format("Mon, 02 Jan 2006 15:04:05 MST")
response.WriteString(fmt.Sprintf("\n------------\n*Post Time: %s*\n\n%s\n", formattedTime, string(content)))
// Check if the message is getting too long
if response.Len() > 4000 { // Telegram's limit is 4096 characters
break
}
}
if response.Len() == 0 {
response.WriteString("Error reading post contents.")
}
msg := tgbotapi.NewMessage(chatID, response.String())
msg.ParseMode = tgbotapi.ModeMarkdown
bot.Send(msg)
}
func handleUserInput(chatID int64, inputType, input string) {
sanitizedInput := sanitizeInput(input)
settings, _ := userSettings[chatID]
switch inputType {
case "token":
settings.Token = sanitizedInput
saveToFile("tokens.txt", chatID, sanitizedInput)
case "domain":
settings.Domain = sanitizedInput
saveToFile("domains.txt", chatID, sanitizedInput)
}
userSettings[chatID] = settings
}
func defaultResponse(chatID int64, bot *tgbotapi.BotAPI) {
bot.Send(tgbotapi.NewMessage(chatID, "Welcome! Please use a command to get started. Type /help for a list of commands."))
}
func postToMastodon(domain, token, content string) (string, error) {
apiUrl := fmt.Sprintf("https://%s/api/v1/statuses", domain)
data := url.Values{"status": {content}}
req, err := http.NewRequest("POST", apiUrl, strings.NewReader(data.Encode()))
if err != nil {
return "", fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("error posting to Mastodon: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return "", fmt.Errorf("received non-success status code %d", resp.StatusCode)
}
// Parse the response to extract the link to the post
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("error decoding response: %w", err)
}
// Assuming 'url' field in response contains the post link
postLink, ok := result["url"].(string)
if !ok {
return "", errors.New("post link not found in response")
}
return postLink, nil
}
func saveToFile(filename string, userID int64, data string) {
filePath := filename
content, err := os.ReadFile(filePath)
if err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
lines := strings.Split(string(content), "\n")
newLine := fmt.Sprintf("%d: %s", userID, data)
updated := false
for i, line := range lines {
if strings.HasPrefix(line, fmt.Sprintf("%d:", userID)) {
lines[i] = newLine
updated = true
break
}
}
if !updated {
lines = append(lines, newLine)
}
err = ioutil.WriteFile(filePath, []byte(strings.Join(lines, "\n")), 0644)
if err != nil {
log.Fatal(err)
}
}
func sanitizeInput(input string) string {
return strings.TrimSpace(strings.Split(input, "\n")[0])
}
func loadUserSettingsFromFile(filename, settingType string) {
file, err := os.Open(filename)
if err != nil {
if !os.IsNotExist(err) {
log.Fatal(err)
}
return // File does not exist, so nothing to load
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ": ")
if len(parts) != 2 {
continue // Invalid line format
}
userID, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
if err != nil {
log.Printf("Error parsing user ID from file: %v", err)
continue
}
setting := strings.TrimSpace(parts[1])
if settingType == "token" {
userSettings[userID] = UserSettings{
Token: setting,
Domain: userSettings[userID].Domain,
}
} else if settingType == "domain" {
userSettings[userID] = UserSettings{
Token: userSettings[userID].Token,
Domain: setting,
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}