grim/wasdead

9c111fecaf67
Make the bot only look at messages that mention it
package discord
import (
"fmt"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize"
log "github.com/sirupsen/logrus"
"bitbucket.org/TheToyz/nowdead/presence"
)
type commandHandler func(c *DiscordClient, m *discordgo.MessageCreate) error
var commands map[string]commandHandler
func init() {
commands = map[string]commandHandler{
"!uptime": uptimeCommand,
"!setchannel": setChannelCommand,
"!islive": isLiveCommand,
}
}
func (c *DiscordClient) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// ignore messages for ourselves
if m.Author.ID == s.State.User.ID {
return
}
if !strings.HasPrefix(m.Content, c.mentionString) {
return
}
log.Debugf("message contents: '%s'", m.Content)
log.Debugf("our user id: %s", c.userID)
parts := strings.Split(m.Content, " ")
command := strings.ToLower(parts[1])
if handler, found := commands[command]; found {
err := handler(c, m)
if err != nil {
log.Warnf("failed to send response: %v", err)
c.sendChannel(m.ChannelID, fmt.Sprintf("error: %#v", err))
}
}
}
func uptimeCommand(c *DiscordClient, m *discordgo.MessageCreate) error {
return c.sendChannel(
m.ChannelID,
fmt.Sprintf("Started %s", humanize.Time(c.started)),
)
}
func setChannelCommand(c *DiscordClient, m *discordgo.MessageCreate) error {
c.db.SetChannel(m.GuildID, m.ChannelID)
return c.sendChannel(
m.ChannelID,
fmt.Sprintf("Set <#%s> as the announcement channel", m.ChannelID),
)
}
func isLiveCommand(c *DiscordClient, m *discordgo.MessageCreate) error {
args := strings.Split(m.Content, " ")
if len(args) != 3 {
return fmt.Errorf("invalid arguments")
}
uri := ""
user := args[2]
if len(m.Mentions) > 1 {
member := m.Mentions[0]
log.Debugf("getting presence on %s for %s", m.GuildID, member.ID)
p := c.getPresence(m.GuildID, member.ID)
log.Debugf("presences: %#v", p)
if p == nil {
return fmt.Errorf("no presence data found")
}
if p.Game.Type == discordgo.GameTypeStreaming {
uri = p.Game.URL
}
} else {
uri = "https://twitch.tv/" + user
}
presence, err := presence.GetPresence(uri)
if err != nil {
return err
}
return c.sendPresence(m.GuildID, presence)
}