src/globals/utils.go (view raw)
1package globals
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7 "time"
8
9 "github.com/birabittoh/myks"
10 "github.com/birabittoh/rabbitpipe"
11 "github.com/bwmarrin/discordgo"
12)
13
14var (
15 searchPattern = regexp.MustCompile(`watch\?v\x3d([a-zA-Z0-9_-]{11})`)
16 searchKS = myks.New[string](12 * time.Hour)
17)
18
19func GetVoiceChannelID(s *discordgo.Session, m *discordgo.MessageCreate) (response string, g *discordgo.Guild, voiceChannelID string) {
20 if m.Member == nil {
21 response = "Please, use this inside a server."
22 return
23 }
24
25 g, err := s.State.Guild(m.GuildID)
26 if err != nil {
27 logger.Errorf("could not get guild: %s", err)
28 response = MsgError
29 return
30 }
31
32 for _, vs := range g.VoiceStates {
33 if vs.UserID == m.Author.ID {
34 voiceChannelID = vs.ChannelID
35 break
36 }
37 }
38
39 if voiceChannelID == "" {
40 response = "You need to be in a voice channel to use this command."
41 }
42 return
43}
44
45func (bc BotCommand) FormatHelp(command, guildID string) string {
46 var shortCodeStr string
47 if bc.ShortCode != "" {
48 shortCodeStr = fmt.Sprintf(" (%s)", FormatCommand(bc.ShortCode, guildID))
49 }
50 return fmt.Sprintf(MsgHelpFmt, FormatCommand(command, guildID)+shortCodeStr, bc.Help)
51}
52
53func FormatCommand(command, guildID string) string {
54 return fmt.Sprintf("`%s%s`", GetPrefix(guildID), command)
55}
56
57func FormatVideo(v *rabbitpipe.Video) string {
58 duration := time.Duration(v.LengthSeconds) * time.Second
59 return fmt.Sprintf("**%s** (`%s`)", v.Title, duration.String())
60}
61
62func ParseUserMessage(messageContent, guildID string) (command string, args []string, ok bool) {
63 after, found := strings.CutPrefix(messageContent, GetPrefix(guildID))
64 if !found {
65 return
66 }
67
68 userInput := strings.Split(after, " ")
69 command = strings.ToLower(userInput[0])
70 return command, userInput[1:], len(command) > 0
71}
72
73func GetPrefix(guildID string) string {
74 for _, prefix := range Config.Values.Prefixes {
75 if prefix.Name == guildID {
76 return prefix.Value
77 }
78 }
79
80 Config.Values.Prefixes = append(Config.Values.Prefixes, KeyValuePair{Name: guildID, Value: defaultPrefix})
81 err := Config.Save()
82 if err != nil {
83 logger.Errorf("could not save config: %s", err)
84 }
85 return defaultPrefix
86}
87
88func SetPrefix(guildID, prefixValue string) string {
89 var found bool
90 for i, prefix := range Config.Values.Prefixes {
91 if prefix.Name == guildID {
92 Config.Values.Prefixes[i].Value = prefixValue
93 found = true
94 break
95 }
96 }
97
98 if !found {
99 Config.Values.Prefixes = append(Config.Values.Prefixes, KeyValuePair{Name: guildID, Value: prefixValue})
100 }
101
102 err := Config.Save()
103 if err != nil {
104 logger.Errorf("could not save config: %s", err)
105 }
106 return defaultPrefix
107}