Milen/util/magic.go

58 lines
1.8 KiB
Go

package util
import (
"errors"
"strings"
)
var (
//Errors for ParseRole
ErrInvalidRole = errors.New("Invalid role has been provided.")
//Errors for ParseEmoji
ErrInvalidEmoji = errors.New("Invalid emoji has been provided.")
//Errors for ParseMessageLink
ErrNotValidURL = errors.New("Invalid URL has been provided (expecting message link).")
ErrNotDiscordURL = errors.New("Invalid Discord URL has been provided (expecting message link).")
ErrNotMessageURL = errors.New("Invalid Discord message link has been provided.")
)
type ParsedMessageLink struct {
GuildID string
ChannelID string
MessageID string
}
func ParseRole(roleString string) (string, error) {
if !strings.HasPrefix(roleString, "<@&") || !strings.HasSuffix(roleString, ">") {
return "", ErrInvalidRole
}
return roleString[3 : len(roleString)-1], nil
}
func ParseEmoji(emojiString string) (string, error) {
if strings.HasPrefix(emojiString, "<:") && strings.HasSuffix(emojiString, ">") {
return emojiString[2 : len(emojiString)-1], nil
}
//TODO: We assume people aren't ill-intended and everything are actually emoji for now.
//The alternative would be to keep a list of all possible emoji which is overkill.
return emojiString, nil
}
func ParseMessageLink(messageLink string) (ParsedMessageLink, error) {
if !strings.HasPrefix(messageLink, "https://") {
return ParsedMessageLink{}, ErrNotValidURL
}
split := strings.Split(messageLink, "/")
if split[2] != "discordapp.com" && split[2] != "canary.discordapp.com" && split[2] != "ptb.discordapp.com" {
return ParsedMessageLink{}, ErrNotDiscordURL
}
if len(split) < 7 || split[3] != "channels" {
return ParsedMessageLink{}, ErrNotMessageURL
}
return ParsedMessageLink{
GuildID: split[4],
ChannelID: split[5],
MessageID: split[6],
}, nil
}