diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..18be56d --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "env": {}, + "args": [] + } + ] +} \ No newline at end of file diff --git a/.yourbase.yml b/.yourbase.yml new file mode 100644 index 0000000..acc6eee --- /dev/null +++ b/.yourbase.yml @@ -0,0 +1,13 @@ +dependencies: + build: + - go:1.14.2 + +build_targets: + - name: default + commands: + - go run main.go + +ci: + builds: + - name: default + build_target: default \ No newline at end of file diff --git a/coldbrewcrew/iworkout/discord.go b/coldbrewcrew/iworkout/discord.go new file mode 100644 index 0000000..4fb0d78 --- /dev/null +++ b/coldbrewcrew/iworkout/discord.go @@ -0,0 +1,189 @@ +// Package iworkout joins Cold Brew Crew's Discord server and listens for emoji reactions in the #iworkout channel. +// Use this link to make the bot join your server: https://discord.com/api/oauth2/authorize?client_id=709797518032240751&scope=bot +// Optionally add a &permissions=ABC parameter, where ABC is a bitwise flag as so: https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags +package iworkout + +import ( + "fmt" + "log" + "time" + + "github.com/bwmarrin/discordgo" +) + +const startMsg = "Starting Discord handlers..." +const logPrefix = "Discord:" +const botToken = "NzA5Nzk3NTE4MDMyMjQwNzUx.XryNQQ.vx4n9mcdsJr8bFCz8pOgrr2YD0A" + +const iworkoutChannelID = "492391546411417620" + +// In-memory caches of data retrieved through the API. +var ( + // users is a map of user ID to user. + users = map[string]discordgo.User{} + + // messages is a two-dimensional map of channel ID to message ID to message. + messages = map[string]map[string]discordgo.Message{} + + // reactions is a map of message ID to a "set" of users who reacted to that message (with any reaction). + reactions = map[string]map[string]struct{}{} +) + +// init is called automatically on boot. +func init() { + discord, err := discordgo.New(fmt.Sprintf("Bot %s", botToken)) + if err != nil { + log.Fatalf("%s can't start: %s.\n", startMsg, err) + return + } + + discord.AddHandler(handleReactionAdd) + discord.AddHandler(handleReactionRemove) + + if err := discord.Open(); err != nil { + log.Fatalf("%s can't open: %s.\n", startMsg, err) + return + } + + fmt.Printf("%s ready.\n", startMsg) + + go buildMessagesState(discord, iworkoutChannelID) +} + +// handleReactionAdd is called by discordgo when an emoji reaction is added to a message. +func handleReactionAdd(s *discordgo.Session, r *discordgo.MessageReactionAdd) { + u := fetchUser(s, r.UserID) + m := fetchMessage(s, r.ChannelID, r.MessageID) + + reactions[m.ID][u.ID] = struct{}{} + + fmt.Printf("%s reaction added: \"%s\" had a %s added by %v\n", logPrefix, m.Content, r.Emoji.Name, u) +} + +// handleReactionRemove is called by discordgo when an emoji reaction is removed from a message. +func handleReactionRemove(s *discordgo.Session, r *discordgo.MessageReactionRemove) { + u := fetchUser(s, r.UserID) + m := fetchMessage(s, r.ChannelID, r.MessageID) + + delete(reactions[m.ID], u.ID) + + fmt.Printf("%s reaction removed: \"%s\" had a %s removed by %v\n", logPrefix, m.Content, r.Emoji.Name, u) +} + +// fetchUser gets a user through the Discord API by ID and caches it, if it is not already stored in the local cache. +func fetchUser(s *discordgo.Session, id string) discordgo.User { + if u, ok := users[id]; ok { + return u + } + + u, err := s.User(id) + if err != nil { + log.Printf("Couldn't fetch user %s: %s", id, err) + return discordgo.User{} + } + + users[id] = *u + + return *u +} + +// fetchMessage gets a message through the Discord API by ID and caches it, if it is not already stored in the local cache. +func fetchMessage(s *discordgo.Session, channelID, messageID string) discordgo.Message { + if m, ok := messages[channelID][messageID]; ok { + return m + } + + m, err := s.ChannelMessage(channelID, messageID) + if err != nil { + log.Printf("Couldn't fetch message %s/%s: %s", channelID, messageID, err) + return discordgo.Message{} + } + + if messages[channelID] == nil { + messages[channelID] = map[string]discordgo.Message{} + } + messages[channelID][messageID] = *m + + return *m +} + +func buildMessagesState(s *discordgo.Session, channelID string) { + const limit = 100 + var earliest, latest discordgo.Message + fmt.Println("Building message state...") + + for { + time.Sleep(600 * time.Millisecond) + m, err := s.ChannelMessages(channelID, limit, earliest.ID, "", "") + if err != nil { + log.Printf("Couldn't fetch messages: %s", err) + } + + if len(m) == 0 { + fmt.Printf("Done cataloguing messages.\n\tEarliest: %s by %v\n\tLatest: %s by %v\n", earliest.Content, earliest.Author, latest.Content, latest.Author) + break + } + + for _, msg := range m { + if messages[msg.ChannelID] == nil { + messages[msg.ChannelID] = map[string]discordgo.Message{} + } + + messages[msg.ChannelID][msg.ID] = *msg + + if earliest.ID == "" { + earliest = *msg + } + if latest.ID == "" { + latest = *msg + } + + t, err := msg.Timestamp.Parse() + if err != nil { + log.Printf("Can't parse returned message timestamp: %s", err) + } + + et, err := earliest.Timestamp.Parse() + if err != nil { + log.Printf("Can't parse earliest message timestamp: %s", err) + } + + if t.Before(et) { + earliest = *msg + } + if t.After(et) { + latest = *msg + } + } + fmt.Printf("Catalogued %d messages (to %s)\n", len(m), earliest.Timestamp) + } + + buildReactionsState(s) +} + +func buildReactionsState(s *discordgo.Session) { + const limit = 100 + fmt.Println("Building reaction state...") + + for channelID, msgs := range messages { + for _, msg := range msgs { + for _, reaction := range msg.Reactions { + time.Sleep(600 * time.Millisecond) + users, err := s.MessageReactions(channelID, msg.ID, reaction.Emoji.APIName(), limit) + if err != nil { + log.Printf("Can't get users who reacted with %s to %s: %s\n", reaction.Emoji.Name, msg.Content, err) + } + + for _, user := range users { + if reactions[msg.ID] == nil { + reactions[msg.ID] = map[string]struct{}{} + } + reactions[msg.ID][user.ID] = struct{}{} + } + fmt.Printf("Catalogued %d reactions spanning %d emoji to %s by %s\n", len(users), len(msg.Reactions), msg.Content, msg.Author) + } + } + } + + fmt.Printf("Done cataloguing reactions.\n") +} diff --git a/db/db.go b/db/db.go new file mode 100644 index 0000000..2c230f8 --- /dev/null +++ b/db/db.go @@ -0,0 +1,58 @@ +// Package db is a simple file-based key-value store. It implictly trusts its consumers not to be malicious to the filesystem, such as using ../ to navigate out of the database directory. +package db + +import ( + "fmt" + "io/ioutil" + "os" + "time" +) + +const prefix = "db/store" + +// GetStr retrieves a string value from the store and returns it. +func GetStr(key string) (string, error) { + val, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", prefix, key)) + if err != nil { + return "", fmt.Errorf("Can't get value %s from db: %s", key, err) + } + + return string(val), nil +} + +// SetStr places a key in the store with string value val. +func SetStr(key, val string) error { + if err := ioutil.WriteFile(fmt.Sprintf("%s/%s", prefix, key), []byte(val), os.ModePerm); err != nil { + return fmt.Errorf("Can't set value %s=%s in db: %s", key, val, err) + } + + return nil +} + +// GetTime retrieves a time.Time value from the store and returns it. +func GetTime(key string) (time.Time, error) { + val, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", prefix, key)) + if err != nil { + return time.Time{}, fmt.Errorf("Can't get time.Time value %s from db: %s", key, err) + } + + var t time.Time + + t.UnmarshalText([]byte(val)) + + return t, nil +} +func SetTime(key string, val time.Time) error { + t, err := val.MarshalText() + if err != nil { + return fmt.Errorf("Can't marshal time.Time %v into text: %s", val, err) + } + + if err := ioutil.WriteFile(fmt.Sprintf("%s/%s", prefix, key), t, os.ModePerm); err != nil { + return fmt.Errorf("Can't set time.Time value %s=%v in db: %s", key, val, err) + } + + return nil +} + +// SetStr places a key in the store with time.Time value val. diff --git a/db/store/discord_bot_access_token b/db/store/discord_bot_access_token new file mode 100644 index 0000000..dd0f6b5 --- /dev/null +++ b/db/store/discord_bot_access_token @@ -0,0 +1 @@ +NzA5Nzk3NTE4MDMyMjQwNzUx.XryNQQ.vx4n9mcdsJr8bFCz8pOgrr2YD0A \ No newline at end of file diff --git a/db/store/discord_bot_access_token_expiry b/db/store/discord_bot_access_token_expiry new file mode 100644 index 0000000..e69de29 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5d9c9fd --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/glacials/mainframe + +go 1.14 + +require github.com/bwmarrin/discordgo v0.20.3 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7123e3e --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/bwmarrin/discordgo v0.20.3 h1:AxjcHGbyBFSC0a3Zx5nDQwbOjU7xai5dXjRnZ0YB7nU= +github.com/bwmarrin/discordgo v0.20.3/go.mod h1:O9S4p+ofTFwB02em7jkpkV8M3R0/PUVOwN61zSZ0r4Q= +github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16 h1:y6ce7gCWtnH+m3dCjzQ1PCuwl28DDIc3VNnvY29DlIA= +golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= diff --git a/main.go b/main.go index f06368b..30647c6 100644 --- a/main.go +++ b/main.go @@ -6,14 +6,15 @@ import ( "log" "net/http" "time" + + _ "github.com/glacials/mainframe/coldbrewcrew/iworkout" ) +const startMsg = "Starting mainframe..." const port = 9000 const refreshInterval = 2 * time.Second func main() { - fmt.Println("Starting mainframe...") - var ( index []byte err error @@ -25,6 +26,7 @@ func main() { log.Fatalf("Cannot read html/index.html: %s", err) return } + time.Sleep(refreshInterval) } }() @@ -33,6 +35,6 @@ func main() { w.Write(index) }) - fmt.Println("Mainframe listening on port 8080...") + fmt.Printf("%s listening on %s:%d.\n", startMsg, "localhost", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil)) }