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