121 lines
2.3 KiB
Go
121 lines
2.3 KiB
Go
package discord
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
)
|
|
|
|
// DiscordClient -
|
|
type DiscordClient struct {
|
|
Session *discordgo.Session
|
|
ID string
|
|
connected bool
|
|
}
|
|
|
|
// Errors
|
|
var (
|
|
ErrTokenEmpty = errors.New("token is empty")
|
|
ErrGuildIDEmpty = errors.New("guild id is empty")
|
|
)
|
|
|
|
var client *DiscordClient
|
|
|
|
// NewClient -
|
|
func NewClient(token string) (*DiscordClient, error) {
|
|
if len(token) == 0 {
|
|
return nil, ErrTokenEmpty
|
|
}
|
|
var err error
|
|
|
|
client = &DiscordClient{}
|
|
client.Session, err = discordgo.New(fmt.Sprintf("Bot %s", token))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// register event
|
|
client.Session.AddHandler(messageCreateEvt)
|
|
client.Session.AddHandler(guildMemberAddEvt)
|
|
client.Session.AddHandler(guildMemberRemoveEvt)
|
|
client.Session.AddHandler(rateLimitEvt)
|
|
client.Session.AddHandler(connectEvt)
|
|
client.Session.AddHandler(disconnectEvt)
|
|
|
|
botInfo, err := client.Session.User("@me")
|
|
if err != nil {
|
|
return client, err
|
|
}
|
|
client.ID = botInfo.ID
|
|
|
|
return client, nil
|
|
}
|
|
|
|
// GetClient -
|
|
func GetClient() *DiscordClient { return client }
|
|
|
|
// Connect to discord websocket
|
|
func (p *DiscordClient) Connect() error {
|
|
if p.connected == true {
|
|
return nil
|
|
}
|
|
return p.Session.Open()
|
|
}
|
|
|
|
// Close discord websocket connection
|
|
func (p *DiscordClient) Close() error {
|
|
if p.connected == false {
|
|
return nil
|
|
}
|
|
return p.Session.Close()
|
|
}
|
|
|
|
// GetGuildOwner -
|
|
func (p *DiscordClient) GetGuildOwner(guild string) (ownerID string, err error) {
|
|
if len(guild) == 0 {
|
|
return "", ErrGuildIDEmpty
|
|
}
|
|
guildInfo, err := p.Session.Guild(guild)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
ownerID = guildInfo.OwnerID
|
|
return
|
|
}
|
|
|
|
// GuildRole -
|
|
type GuildRole struct {
|
|
Name string
|
|
ID string
|
|
}
|
|
|
|
// GetGuildRoles -
|
|
func (p *DiscordClient) GetGuildRoles(guild string) (roles []GuildRole, err error) {
|
|
if len(guild) == 0 {
|
|
return nil, ErrGuildIDEmpty
|
|
}
|
|
|
|
roleInfos, err := p.Session.GuildRoles(guild)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
roles = make([]GuildRole, 0, len(roleInfos))
|
|
for _, role := range roleInfos {
|
|
r := GuildRole{
|
|
ID: role.ID,
|
|
Name: role.Name,
|
|
}
|
|
roles = append(roles, r)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// SendMessage -
|
|
func (p *DiscordClient) SendMessage(channel, message string) error {
|
|
var err error
|
|
_, err = p.Session.ChannelMessageSend(channel, message)
|
|
return err
|
|
}
|