telegram/replace.go (view raw)
1package telegram
2
3import (
4 "fmt"
5 "regexp"
6
7 tgbotapi "github.com/BiRabittoh/telegram-bot-api/v5"
8)
9
10type Replacer struct {
11 Regex *regexp.Regexp
12 Format string
13}
14
15const (
16 parseMode = "markdown"
17 linkMessage = "[🔗](%s) Da %s."
18 regexFlags = "(?i)(?m)"
19)
20
21var replacers = []Replacer{
22 {
23 Regex: regexp.MustCompile(regexFlags + `(?:(?:https?:)?\/\/)?(?:(?:www|m)\.)?(?:(?:youtube(?:-nocookie)?\.com|youtu.be))(?:\/(?:[\w\-]+\?v=|embed\/|live\/|v\/|shorts\/)?)([\w\-]+)`),
24 Format: "https://y.outube.duckdns.org/%s",
25 },
26 {
27 Regex: regexp.MustCompile(regexFlags + `https?:\/\/(?:www\.)?twitter\.com\/(?:#!\/)?(.*)\/status(?:es)?\/([^\/\?\s]+)`),
28 Format: "https://fxtwitter.com/%s/status/%s",
29 },
30 {
31 Regex: regexp.MustCompile(regexFlags + `(?:https?:\/\/)?(?:www\.)?x\.com\/(?:#!\/)?(.*)\/status(?:es)?\/([^\/\?\s]+)`),
32 Format: "https://fixupx.com/%s/status/%s",
33 },
34 {
35 Regex: regexp.MustCompile(regexFlags + `(?:https?:\/\/)?(?:www\.)?instagram\.com\/(reels?|p)\/([\w\-]{11})[\/\?\w=&]*`),
36 Format: "https://ddinstagram.com/%s/%s",
37 },
38 {
39 Regex: regexp.MustCompile(regexFlags + `https?:\/\/(?:(?:www)|(?:vm))?\.?tiktok\.com\/@([\w.]+)\/(?:video)\/(\d{19,})`),
40 Format: "https://www.tnktok.com/@%s/video/%s",
41 },
42 {
43 Regex: regexp.MustCompile(regexFlags + `(?:https?:\/\/)?(?:(?:www)|(?:vm))?\.?tiktok\.com\/(?:t\/)?([\w]{9})\/?`),
44 Format: "https://vm.tnktok.com/%s/",
45 },
46}
47
48func parseText(message string) []string {
49 links := []string{}
50
51 for _, replacer := range replacers {
52 foundMatches := replacer.Regex.FindStringSubmatch(message)
53
54 if len(foundMatches) == 0 {
55 continue
56 }
57 captureGroups := foundMatches[1:]
58
59 var formatArgs []interface{}
60 for _, match := range captureGroups {
61 if match != "" {
62 formatArgs = append(formatArgs, match)
63 }
64 }
65
66 formatted := fmt.Sprintf(replacer.Format, formatArgs...)
67 links = append(links, formatted)
68 }
69 return links
70}
71
72func getUserMention(user tgbotapi.User) string {
73 return fmt.Sprintf("[@%s](tg://user?id=%d)", user.UserName, user.ID)
74}
75
76func handleLinks(bot *tgbotapi.BotAPI, message *tgbotapi.Message) {
77 links := []string{}
78
79 if message.Text != "" {
80 textLinks := parseText(message.Text)
81 links = append(links, textLinks...)
82 }
83
84 if message.Caption != "" {
85 captionLinks := parseText(message.Caption)
86 links = append(links, captionLinks...)
87 }
88
89 if len(links) == 0 {
90 return
91 }
92
93 user := getUserMention(*message.From)
94
95 for _, link := range links {
96 text := fmt.Sprintf(linkMessage, link, user)
97 msg := tgbotapi.NewMessage(message.Chat.ID, text)
98 msg.MessageThreadID = message.MessageThreadID
99 msg.ParseMode = parseMode
100 bot.Send(msg)
101 }
102
103}