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 var name string
74 if user.UserName == "" {
75 name = user.FirstName + user.LastName
76 } else {
77 name = "@" + user.UserName
78 }
79 return fmt.Sprintf("[%s](tg://user?id=%d)", name, user.ID)
80}
81
82func handleLinks(bot *tgbotapi.BotAPI, message *tgbotapi.Message) {
83 links := []string{}
84
85 if message.Text != "" {
86 textLinks := parseText(message.Text)
87 links = append(links, textLinks...)
88 }
89
90 if message.Caption != "" {
91 captionLinks := parseText(message.Caption)
92 links = append(links, captionLinks...)
93 }
94
95 if len(links) == 0 {
96 return
97 }
98
99 user := getUserMention(*message.From)
100
101 for _, link := range links {
102 text := fmt.Sprintf(linkMessage, link, user)
103 msg := tgbotapi.NewMessage(message.Chat.ID, text)
104 msg.MessageThreadID = message.MessageThreadID
105 msg.ParseMode = parseMode
106 bot.Send(msg)
107 }
108
109}