all repos — disgord @ 4594fc1f9738dd7c5e7d9ec50660b347f0d3a6d2

A simple Discord bot in Go.

src/globals/utils.go (view raw)

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