feat: add where command

This commit is contained in:
Jack 2023-09-07 13:39:57 -04:00
parent 1c6162962f
commit 1cfe8247c4
No known key found for this signature in database
GPG Key ID: AFD9F14834097B8E
5 changed files with 376 additions and 7 deletions

5
go.mod
View File

@ -2,6 +2,8 @@ module github.com/jackmerrill/hampbot
go 1.19
require github.com/paulmach/go.geojson v1.5.0
require (
github.com/PuerkitoBio/goquery v1.8.1 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
@ -18,7 +20,9 @@ require (
github.com/go-redis/redis/v8 v8.11.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/geo v0.0.0-20230421003525-6adc56603217 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/jackmerrill/go-mapbox v0.4.5 // indirect
github.com/jackmerrill/hamp-api v0.0.0-20230818235104-8d222c9674c9 // indirect
github.com/jackmerrill/pvta-go v0.0.0-20220912020258-36dee8883b6e // indirect
github.com/klauspost/compress v1.10.3 // indirect
@ -43,5 +47,6 @@ require (
golang.org/x/net v0.14.0 // indirect
golang.org/x/sys v0.11.0 // indirect
golang.org/x/text v0.12.0 // indirect
gopkg.in/ryankurte/go-mapbox.v0 v0.4.2 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)

11
go.sum
View File

@ -59,6 +59,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
@ -67,6 +69,8 @@ github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jackmerrill/go-mapbox v0.4.5 h1:Lz59MY8N2xJIAjrrKS5EkUNYxFIizRvg1Fnef5dOlkA=
github.com/jackmerrill/go-mapbox v0.4.5/go.mod h1:aG1kJtaYV36I/3wD06rgdDyn5wEheSHZeXPXZW1dfvs=
github.com/jackmerrill/hamp-api v0.0.0-20230818235104-8d222c9674c9 h1:ZP4cMycNDHXMk5LQ+VbDq7So0e7gbYPetPpvqbD2XLo=
github.com/jackmerrill/hamp-api v0.0.0-20230818235104-8d222c9674c9/go.mod h1:KS8EBP1su7OHA4Kq5+wZkx162SEVDbIbUV9yo0MMRac=
github.com/jackmerrill/pvta-go v0.0.0-20220912020258-36dee8883b6e h1:Mo9/4mW8hbak/VKFZt3Xp7Vuq7mKpUQO4d7AwR5CqZA=
@ -109,10 +113,14 @@ github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISq
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
github.com/paulmach/go.geojson v1.5.0 h1:7mhpMK89SQdHFcEGomT7/LuJhwhEgfmpWYVlVmLEdQw=
github.com/paulmach/go.geojson v1.5.0/go.mod h1:DgdUy2rRVDDVgKqrjMe2vZAHMfhDTrjVKt3LmHIXGbU=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/ryankurte/go-mapbox v0.4.4 h1:wZV6MJ+wzROfK2JgahYuA89N0Fw7wTio/F7G3Ta0gZc=
github.com/ryankurte/go-mapbox v0.4.4/go.mod h1:DD9ifJ/Yf8Ov1o33bHT/8Nsumxq6RavU85EShdi9AkY=
github.com/sarulabs/di/v2 v2.4.2 h1:A/PDVU41gHYeUbZZKco8dOwPAB2rrFfiwWLJrZsi+h8=
github.com/sarulabs/di/v2 v2.4.2/go.mod h1:trZu4KPwNLE623mBIIsljn1LLkNE6ee/Pk24b7yzSf8=
github.com/sashabaranov/go-openai v1.14.2 h1:5DPTtR9JBjKPJS008/A409I5ntFhUPPGCmaAihcPRyo=
@ -121,6 +129,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tkrajina/gpxgo v1.1.2/go.mod h1:795sjVRFo5wWyN6oOZp0RYienGGBJjpAlgOz2nCngA0=
github.com/tkrajina/gpxgo v1.3.0 h1:rXqIey0Mc6wOvEoKHEnhZG6Kgxq/vQsOUs7/AME128Q=
@ -245,6 +254,8 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/ryankurte/go-mapbox.v0 v0.4.2 h1:i3wBfUnTxI7NNg4BiatUAzSAzfA9Cxpc0WWhOHBCMQg=
gopkg.in/ryankurte/go-mapbox.v0 v0.4.2/go.mod h1:HxwTAU0Ia8hfMMhlohUGyCbjSJwSzQYaZ4dmJSCEuiE=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -0,0 +1,276 @@
package studentlife
import (
"bytes"
"fmt"
"image/color"
"image/png"
"os"
"regexp"
"strings"
"github.com/bwmarrin/discordgo"
sm "github.com/flopp/go-staticmaps"
"github.com/golang/geo/s2"
mapbox "github.com/jackmerrill/go-mapbox/lib"
"github.com/jackmerrill/go-mapbox/lib/base"
"github.com/jackmerrill/go-mapbox/lib/directions"
"github.com/jackmerrill/hampbot/internal/utils/config"
"github.com/jackmerrill/hampbot/internal/utils/embed"
"github.com/zekroTJA/shireikan"
)
// string is the name of the building in regex, []float64 is the lat/long
type Location map[string][]float64
var LOCATIONS = Location{
"^(kern|kern kafe|kern cafe|kern center|r\\.w\\. kern center|rw kern center|admissions|financial aid|finaid)$": []float64{42.325490, -72.530425},
"^(bridge|bridge cafe|the bridge)$": []float64{42.32560055268511, -72.53171782489403},
"^(rcc|robert crown center|gym)$": []float64{42.3259021736783, -72.53138568980566},
"^(library|harold f. johnson library center|mail room|post office|hampstore|hamp store|campus store|duplications|it|art gallery|hampshire college art gallery|sparc)$": []float64{42.325503815980404, -72.53234665636477},
"^(cole|the cole|cole science center|csc)$": []float64{42.325005132910455, -72.53264274547023},
"^(mixed nuts)$": []float64{42.32438520935449, -72.53314741618625},
"^(prescott)$": []float64{42.32370121438042, -72.53400755941487},
"^(prescott tavern)$": []float64{42.32330551141666, -72.53410313088433},
"^(c4d|center for design|lemelson building)$": []float64{42.323653164859145, -72.53277277596145},
"^(central records|casa)$": []float64{42.32400565840685, -72.53267685200223},
"^(arts barn|art barn|art)$": []float64{42.323484930985096, -72.53270230871183},
"^(jlc|jerome liebling center)$": []float64{42.32343637951593, -72.53186281901529},
"^(solar canopy)$": []float64{42.3231160046793, -72.5323111913881},
"^(music and dance building|mdb|music|dance)$": []float64{42.32296880488658, -72.53257385728799},
"^(ash|adele simmons hall)$": []float64{42.32286199484466, -72.53189407069387},
"^(carle|the carle|the eric carle museum|the eric carle museum of picture book art)$": []float64{42.32109682435725, -72.53332586596198},
"^(elc|early learning center)$": []float64{42.32130800774271, -72.53485513102083},
"^(multisport center|multisport|weight room|msc)$": []float64{42.32138500151223, -72.53614340300827},
"^(dakin student life center|dslc)$": []float64{42.32313128927387, -72.53022445236283},
"^(merrill student life center|mslc)$": []float64{42.32347857352905, -72.53034306624653},
"^(merrill pavillion|pavillion)$": []float64{42.323322471247494, -72.53030510980373},
"^(dakin|hell|dakin house)$": []float64{42.322597743840625, -72.53027825479788},
"^(merrill|merrill house)$": []float64{42.323732718386175, -72.52977892147766},
"^(dining commons|dc|saga)$": []float64{42.32319356233955, -72.52917576638322},
"^(yiddish book center|ybc)$": []float64{42.32175452980474, -72.5276151025249},
"^(franklin patterson hall|fph)$": []float64{42.324221538083805, -72.5306271019939},
"^(the yurt|yurt|radio)$": []float64{42.324071744881785, -72.53136719263956},
"^(enfield|enfield mods|enfield house)$": []float64{42.32646094303269, -72.52929170510444},
"^(wellness center)$": []float64{42.32709812095117, -72.5291661607627},
"^(spiritual life center|slc)$": []float64{42.32705614551552, -72.52973716786117},
"^(edh|emily dickinson hall|theatre|theater)$": []float64{42.327652942240896, -72.53062317253445},
"^(writing center)$": []float64{42.32780110830725, -72.53112929268784},
"^(greenwich|greenwich mods|greenwich house)$": []float64{42.32748781455265, -72.53192281696715},
"^(soccer|soccer field|hampshire college soccer field)$": []float64{42.32651025401564, -72.53454675256307},
"^(cultural center|cc|lebron-wiggins-pran cultural center|Lebrón-Wiggins-Pran Cultural Center)$": []float64{42.32487763771362, -72.5339769868106},
"^(basketball|basketball courts|basketball court|tennis courts|tennis court)$": []float64{42.32557748709811, -72.53720546848393},
"^(red barn|the red barn|barn)$": []float64{42.32642633315529, -72.52551730246282},
"^(the hitchcock center|hitchcock center|hitchcock center for the environment)$": []float64{42.32771760017527, -72.52570886249646},
"^(csa|farm|hampshire college farm center|hampshire college farm)$": []float64{42.32903799744424, -72.52573139895138},
"^(health services|hampshire college health services)$": []float64{42.32666929509394, -72.52524995366625},
"^(atkins|atkins farms country market)$": []float64{42.319355104827295, -72.52927125654328},
"^(res|the res|the reservoir|reservoir)$": []float64{42.317285834368995, -72.5406219720153},
}
type Where struct {
}
var mapboxToken = os.Getenv("MAPBOX_TOKEN")
var mapBox, _ = mapbox.NewMapbox(mapboxToken)
func (c *Where) GetInvokes() []string {
return []string{"where"}
}
func (c *Where) GetDescription() string {
return "Where is this building?"
}
func (c *Where) GetHelp() string {
return "`where <building>` - Where is this building?"
}
func (c *Where) GetGroup() string {
return config.GroupStudentLife
}
func (c *Where) GetDomainName() string {
return "hamp.studentlife.where"
}
func (c *Where) GetSubPermissionRules() []shireikan.SubPermission {
return nil
}
func (c *Where) IsExecutableInDMChannels() bool {
return true
}
func (c *Where) Exec(ctx shireikan.Context) error {
if len(ctx.GetArgs()) < 1 {
ctx.GetSession().ChannelMessageSend(ctx.GetChannel().ID, "Please specify a building.")
return nil
}
to := strings.ToLower(ctx.GetArgs().Get(0).AsString())
from := strings.ToLower(ctx.GetArgs().Get(1).AsString())
e := embed.NewSuccessEmbed(ctx)
e.SetTitle("Where is " + to + "?")
if from != "" {
e.SetTitle("Directions from " + to + " to " + from)
}
e.SetDescription("It's right here!")
mapCtx := sm.NewContext()
mapCtx.SetSize(600, 600)
mapCtx.SetTileProvider(sm.NewTileProviderOpenStreetMaps())
if from == "" {
mapCtx.SetZoom(17)
}
var toCoord []float64
var fromCoord []float64
for regex, coords := range LOCATIONS {
toMatch, err := regexp.MatchString(regex, to)
if err != nil {
return err
}
fromMatch, err := regexp.MatchString(regex, from)
if err != nil {
return err
}
if toMatch || fromMatch {
lat := coords[0]
long := coords[1]
if toMatch {
toCoord = coords
mapCtx.AddObject(
sm.NewMarker(
s2.LatLngFromDegrees(lat, long),
color.RGBA{R: 0, G: 255, B: 0, A: 255},
16.0,
),
)
} else if fromMatch {
fromCoord = coords
mapCtx.AddObject(
sm.NewMarker(
s2.LatLngFromDegrees(lat, long),
color.RGBA{R: 255, G: 0, B: 0, A: 255},
16.0,
),
)
}
}
}
if len(toCoord) == 0 {
errorEmbed := embed.NewErrorEmbed(ctx)
errorEmbed.SetTitle("Error")
errorEmbed.SetDescription(fmt.Sprintf("Building `%s` not found.", to))
_, err := ctx.GetSession().ChannelMessageSendComplex(ctx.GetChannel().ID, &discordgo.MessageSend{
Embed: errorEmbed.MessageEmbed,
Reference: ctx.GetMessage().Reference(),
})
return err
}
if len(fromCoord) == 0 && from != "" {
errorEmbed := embed.NewErrorEmbed(ctx)
errorEmbed.SetTitle("Error")
errorEmbed.SetDescription(fmt.Sprintf("Building `%s` not found.", from))
_, err := ctx.GetSession().ChannelMessageSendComplex(ctx.GetChannel().ID, &discordgo.MessageSend{
Embed: errorEmbed.MessageEmbed,
Reference: ctx.GetMessage().Reference(),
})
return err
}
if from != "" {
// get mapbox directions
dir, err := mapBox.Directions.GetDirections([]base.Location{
{
Latitude: toCoord[0],
Longitude: toCoord[1],
},
{
Latitude: fromCoord[0],
Longitude: fromCoord[1],
},
}, directions.RoutingWalking, &directions.RequestOpts{
Steps: false,
Alternatives: false,
})
if err != nil {
return err
}
var latLngs []s2.LatLng
// add route to map
for _, coord := range dir.Routes[0].Geometry.Coordinates {
latLngs = append(latLngs, s2.LatLngFromDegrees(coord[1], coord[0]))
}
mapCtx.AddObject(
sm.NewPath(
latLngs,
color.RGBA{R: 0, G: 0, B: 255, A: 255},
3.0,
),
)
// set the zoom accordingly to the route length
if dir.Routes[0].Distance > 1000 {
mapCtx.SetZoom(15)
}
}
img, err := mapCtx.Render()
if err != nil {
return err
}
buf := new(bytes.Buffer)
// convert to base64
err = png.Encode(buf, img)
if err != nil {
return err
}
e.SetImage("attachment://map.png")
if err != nil {
return err
}
_, err = ctx.GetSession().ChannelMessageSendComplex(ctx.GetChannel().ID, &discordgo.MessageSend{
Embed: e.MessageEmbed,
Reference: ctx.GetMessage().Reference(),
Files: []*discordgo.File{
{
Name: "map.png",
ContentType: "image/png",
Reader: buf,
},
},
})
return err
}

View File

@ -2,10 +2,12 @@ package config
import (
"fmt"
"math"
"strconv"
"time"
"github.com/bwmarrin/discordgo"
geojson "github.com/paulmach/go.geojson"
)
var (
@ -15,7 +17,7 @@ var (
var (
// BotPrefix is the prefix used for bot commands.
BotPrefix = "!"
BotPrefix = ">>"
// BotGuild is the ID of the guild the bot is running on.
BotGuild = "936651575684915201"
@ -102,3 +104,73 @@ func Hex2RGB(hex Hex) (RGB, error) {
return rgb, nil
}
func long2tile(lon float64, zoom int) int {
return int(math.Floor((lon + 180.0) / 360.0 * math.Pow(2.0, float64(zoom))))
}
func lat2tile(lat float64, zoom int) int {
return int(math.Floor((1.0 - math.Log(math.Tan(lat*math.Pi/180.0)+1.0/math.Cos(lat*math.Pi/180.0))/math.Pi) / 2.0 * math.Pow(2.0, float64(zoom))))
}
func GetTileNumbers(lat, long float64, zoom int) (uint64, uint64) {
return uint64(long2tile(long, zoom)), uint64(lat2tile(lat, zoom))
}
func decodeToken(bytes []byte) (pos int, value float64) {
var token int64 = 0
var shift uint = 0
var result float64
var factor float64 = 1e5
for i, v := range bytes {
current := int64(v) - 63
token |= (current & 0x1f) << uint(shift)
shift += 5
if current&0x20 == 0 {
pos = i + 1
if token&1 != 0 {
result = float64(^(token >> 1))
} else {
result = float64(token >> 1)
}
value = result / factor
return
}
}
pos = 0
return
}
func DecodePolyline(bytes []byte) []byte {
fc := geojson.NewFeatureCollection()
coords := make([][]float64, 0)
var pos int = 0
var lat, lng float64
for pos < len(bytes) {
current, current_lat := decodeToken(bytes[pos:len(bytes)])
pos += current
lat += current_lat
current, current_lng := decodeToken(bytes[pos:len(bytes)])
pos += current
lng += current_lng
coord := []float64{lng, lat}
coords = append(coords, coord)
}
line := geojson.NewLineStringFeature(coords)
fc.AddFeature(line)
json, _ := fc.MarshalJSON()
return json
}

17
main.go
View File

@ -47,11 +47,13 @@ func main() {
InvokeToLower: true,
UseDefaultHelpCommand: true,
OnError: func(ctx shireikan.Context, typ shireikan.ErrorType, err error) {
ctx.GetSession().ChannelMessageSendComplex(ctx.GetChannel().ID, &discordgo.MessageSend{
Embed: embed.NewErrorEmbed(ctx).SetTitle("Error").SetDescription(err.Error()).MessageEmbed,
Reference: ctx.GetMessage().Reference(),
})
log.Error(err)
if typ != shireikan.ErrTypCommandNotFound {
ctx.GetSession().ChannelMessageSendComplex(ctx.GetChannel().ID, &discordgo.MessageSend{
Embed: embed.NewErrorEmbed(ctx).SetTitle("Error").SetDescription(err.Error()).MessageEmbed,
Reference: ctx.GetMessage().Reference(),
})
log.Error(err)
}
},
})
@ -89,10 +91,13 @@ func main() {
log.Error("Failed to initialize laundry notify- skipping.")
} else {
handler.Register(&studentlife.LaundryNotify{})
}
log.Debug("Registered laundry notify command")
handler.Register(&studentlife.Where{})
log.Debug("Registered where command")
log.Info("Registered all commands")
log.Info("Setting up activities...")