subscribe-bot/discord/bot.go

322 lines
7.3 KiB
Go
Raw Normal View History

2020-10-12 13:47:28 +00:00
package discord
2020-10-11 19:32:58 +00:00
import (
"errors"
"fmt"
2020-10-12 08:50:18 +00:00
"io/ioutil"
2020-10-11 19:32:58 +00:00
"log"
2020-10-12 08:50:18 +00:00
"os"
"path"
2020-10-11 19:32:58 +00:00
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/bwmarrin/discordgo"
2020-10-12 08:50:18 +00:00
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
2020-10-12 13:47:28 +00:00
"subscribe-bot/config"
"subscribe-bot/db"
"subscribe-bot/osuapi"
2020-10-11 19:32:58 +00:00
)
type Bot struct {
*discordgo.Session
mentionRe *regexp.Regexp
2020-10-12 13:47:28 +00:00
db *db.Db
api *osuapi.Osuapi
config *config.Config
2020-10-11 19:32:58 +00:00
}
2020-10-12 13:47:28 +00:00
func NewBot(config *config.Config, db *db.Db, api *osuapi.Osuapi) (bot *Bot, err error) {
2020-10-12 08:50:18 +00:00
s, err := discordgo.New("Bot " + config.BotToken)
2020-10-11 19:32:58 +00:00
if err != nil {
return
}
err = s.Open()
if err != nil {
return
}
log.Println("connected to discord")
re, err := regexp.Compile("\\s*<@\\!?" + s.State.User.ID + ">\\s*")
if err != nil {
return
}
2020-10-12 13:47:28 +00:00
bot = &Bot{s, re, db, api, config}
2020-10-11 19:32:58 +00:00
s.AddHandler(bot.errWrap(bot.newMessageHandler))
return
}
2020-10-17 23:05:12 +00:00
func (bot *Bot) NotifyError(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
channel, _ := bot.UserChannelCreate("100443064228646912")
bot.ChannelMessageSend(channel.ID, msg)
}
2020-10-11 19:32:58 +00:00
func (bot *Bot) errWrap(fn interface{}) interface{} {
val := reflect.ValueOf(fn)
origType := reflect.TypeOf(fn)
origTypeIn := make([]reflect.Type, origType.NumIn())
for i := 0; i < origType.NumIn(); i++ {
origTypeIn[i] = origType.In(i)
}
newType := reflect.FuncOf(origTypeIn, []reflect.Type{}, false)
newFunc := reflect.MakeFunc(newType, func(args []reflect.Value) (result []reflect.Value) {
res := val.Call(args)
if len(res) > 0 && !res[0].IsNil() {
err := res[0].Interface().(error)
if err != nil {
2020-10-17 23:05:12 +00:00
bot.NotifyError("error: %s", err)
2020-10-11 19:32:58 +00:00
}
}
return []reflect.Value{}
})
return newFunc.Interface()
}
2020-10-12 13:47:28 +00:00
func (bot *Bot) NotifyNewBeatmap(channels []string, newMaps []osuapi.Beatmapset) (err error) {
2020-10-12 13:14:56 +00:00
for _, beatmapSet := range newMaps {
2020-10-12 08:50:18 +00:00
var eventTime time.Time
eventTime, err = time.Parse(time.RFC3339, beatmapSet.LastUpdated)
2020-10-12 08:50:18 +00:00
if err != nil {
return
}
2020-10-12 04:22:47 +00:00
var (
gotDownloadedBeatmap = false
downloadedBeatmap BeatmapsetDownloaded
2020-10-12 08:50:18 +00:00
// status git.Status
2020-10-12 08:56:27 +00:00
commit *object.Commit
parent *object.Commit
patch *object.Patch
foundPatch = false
2020-10-12 08:50:18 +00:00
// commitFiles *object.FileIter
2020-10-12 04:22:47 +00:00
)
// beatmapSet, err = bot.getBeatmapsetInfo(beatmap)
2020-10-12 08:50:18 +00:00
// try to open a repo for this beatmap
var repo *git.Repository
repoDir := path.Join(bot.config.Repos, strconv.Itoa(beatmapSet.UserID), strconv.Itoa(beatmapSet.ID))
if _, err := os.Stat(repoDir); os.IsNotExist(err) {
os.MkdirAll(repoDir, 0777)
}
repo, err = git.PlainOpen(repoDir)
if err == git.ErrRepositoryNotExists {
// create a new repo
repo, err = git.PlainInit(repoDir, false)
}
if err != nil {
return
}
2020-10-12 08:50:18 +00:00
// download latest updates to the map
err = bot.downloadBeatmapTo(&beatmapSet, repo, repoDir)
if err != nil {
log.Println("failed to download beatmap:", err)
} else {
gotDownloadedBeatmap = true
}
2020-10-12 08:50:18 +00:00
// create a commit
var (
worktree *git.Worktree
files []os.FileInfo
hash plumbing.Hash
)
worktree, err = repo.Worktree()
if err != nil {
return
}
files, err = ioutil.ReadDir(repoDir)
if err != nil {
return
}
for _, f := range files {
if f.Name() == ".git" {
continue
2020-10-12 08:50:18 +00:00
}
worktree.Add(f.Name())
}
hash, err = worktree.Commit(
fmt.Sprintf("update: %d", beatmapSet.ID),
&git.CommitOptions{
Author: &object.Signature{
Name: beatmapSet.Creator,
Email: "nobody@localhost",
When: eventTime,
2020-10-12 08:50:18 +00:00
},
},
)
if err != nil {
err = fmt.Errorf("couldn't create commit for %d: %w", beatmapSet.ID, err)
return
}
2020-10-12 08:50:18 +00:00
commit, err = repo.CommitObject(hash)
if err != nil {
2020-10-12 13:14:56 +00:00
err = fmt.Errorf("couldn't find commit with hash %s: %w", hash, err)
return
}
parent, err = commit.Parent(0)
2020-10-12 13:14:56 +00:00
if errors.Is(err, object.ErrParentNotFound) {
err = nil
} else if err != nil {
2020-10-12 13:14:56 +00:00
err = fmt.Errorf("couldn't retrieve commit parent: %w", err)
return
} else {
2020-10-14 21:57:15 +00:00
patch, err = parent.Patch(commit)
if err != nil {
2020-10-12 13:14:56 +00:00
err = fmt.Errorf("couldn't retrieve patch: %w", err)
2020-10-12 08:50:18 +00:00
return
}
foundPatch = true
2020-10-12 04:22:47 +00:00
}
embed := &discordgo.MessageEmbed{
2020-10-14 22:45:21 +00:00
URL: fmt.Sprintf("%s/map/%d/%d/versions", bot.config.Web.ServedAt, beatmapSet.UserID, beatmapSet.ID),
Title: fmt.Sprintf("Update: %s - %s", beatmapSet.Artist, beatmapSet.Title),
2020-10-12 13:14:56 +00:00
Timestamp: eventTime.Format(time.RFC3339),
Author: &discordgo.MessageEmbedAuthor{
URL: "https://osu.ppy.sh/u/" + strconv.Itoa(beatmapSet.UserID),
2020-10-12 04:22:47 +00:00
Name: beatmapSet.Creator,
IconURL: fmt.Sprintf(
"https://a.ppy.sh/%d?%d.png",
beatmapSet.UserID,
2020-10-12 09:52:19 +00:00
time.Now().Unix(),
2020-10-12 04:22:47 +00:00
),
},
Thumbnail: &discordgo.MessageEmbedThumbnail{
2020-10-12 04:22:47 +00:00
URL: beatmapSet.Covers.SlimCover2x,
},
}
2020-10-12 04:22:47 +00:00
if gotDownloadedBeatmap {
log.Println(downloadedBeatmap)
if foundPatch {
2020-10-12 13:14:56 +00:00
embed.Description = fmt.Sprintf(
"Latest revision: %s\n%s",
hash,
patch.Stats().String(),
)
} else {
embed.Description = "Newly tracked map; diff information will be reported upon next update!"
2020-10-12 04:22:47 +00:00
}
}
2020-10-12 08:50:18 +00:00
for _, channelId := range channels {
2020-10-12 13:14:56 +00:00
_, err = bot.ChannelMessageSendEmbed(channelId, embed)
if err != nil {
err = fmt.Errorf("failed to send to %s: %w", channelId, err)
}
2020-10-12 08:50:18 +00:00
}
2020-10-12 04:22:47 +00:00
}
return
}
type BeatmapsetDownloaded struct {
Path string
}
2020-10-12 13:47:28 +00:00
func (bot *Bot) downloadBeatmapTo(beatmapSet *osuapi.Beatmapset, repo *git.Repository, repoDir string) (err error) {
2020-10-12 08:50:18 +00:00
// clear all OSU files
files, err := ioutil.ReadDir(repoDir)
2020-10-12 04:22:47 +00:00
if err != nil {
return
}
2020-10-12 08:50:18 +00:00
for _, f := range files {
if !strings.HasSuffix(f.Name(), ".osu") {
continue
}
os.Remove(f.Name())
}
2020-10-12 04:22:47 +00:00
2020-10-12 08:50:18 +00:00
for _, beatmap := range beatmapSet.Beatmaps {
path := path.Join(repoDir, fmt.Sprintf("%d.osu", beatmap.ID))
err = bot.api.DownloadSingleBeatmap(beatmap.ID, path)
if err != nil {
return
}
}
2020-10-12 04:22:47 +00:00
return
}
2020-10-12 13:47:28 +00:00
func (bot *Bot) getBeatmapsetInfo(event osuapi.Event) (beatmapSet osuapi.Beatmapset, err error) {
2020-10-12 04:22:47 +00:00
beatmapSetId, err := strconv.Atoi(strings.TrimPrefix(event.Beatmapset.URL, "/s/"))
if err != nil {
return
}
log.Println("beatmap set id", beatmapSetId)
beatmapSet, err = bot.api.GetBeatmapSet(beatmapSetId)
if err != nil {
return
}
return
}
2020-10-11 19:32:58 +00:00
func (bot *Bot) newMessageHandler(s *discordgo.Session, m *discordgo.MessageCreate) (err error) {
mentionsMe := false
for _, user := range m.Mentions {
if user.ID == s.State.User.ID {
mentionsMe = true
break
}
}
if !mentionsMe {
return
}
msg := bot.mentionRe.ReplaceAllString(m.Content, " ")
msg = strings.Trim(msg, " ")
parts := strings.Split(msg, " ")
switch strings.ToLower(parts[0]) {
case "track":
if len(parts) < 2 {
err = errors.New("fucked up")
return
}
2020-10-12 13:47:28 +00:00
var mapper osuapi.User
2020-10-12 04:30:04 +00:00
mapperName := strings.Join(parts[1:], " ")
mapper, err = bot.api.GetUser(mapperName)
2020-10-11 19:32:58 +00:00
if err != nil {
return
}
2020-10-12 07:32:03 +00:00
mapperId := mapper.ID
2020-10-11 19:32:58 +00:00
err = bot.db.ChannelTrackMapper(m.ChannelID, mapperId, 3)
if err != nil {
return
}
2020-10-12 04:30:04 +00:00
bot.ChannelMessageSend(m.ChannelID, fmt.Sprintf("subscribed to %+v", mapper))
2020-10-14 19:33:23 +00:00
case "list":
mappers := make([]string, 0)
2021-07-21 22:09:06 +00:00
bot.db.IterChannelTrackedMappers(m.ChannelID, func(mapper db.User) error {
2020-10-14 19:33:23 +00:00
mappers = append(mappers, mapper.Username)
return nil
})
bot.ChannelMessageSend(m.ChannelID, "tracking: "+strings.Join(mappers, ", "))
2020-10-11 19:32:58 +00:00
}
return
}
func (bot *Bot) Close() {
bot.Session.Close()
}