go-flat-finder/internal/flatfinder/discord.go

91 lines
2.5 KiB
Go
Raw Permalink Normal View History

2022-09-13 07:31:25 +00:00
package flatfinder
import (
"fmt"
"log"
"strconv"
"strings"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/webhook"
"github.com/disgoorg/snowflake/v2"
)
// Load discord client
func (c *LocalConfig) initDiscord() {
// Webhook URL splitting
webhookString := strings.ReplaceAll(c.DiscordWebhook, "https://discord.com/api/webhooks/", "")
webhookParts := strings.Split(webhookString, "/")
if len(webhookParts) != 2 {
log.Fatal("Invalid DISCORD_WEBHOOK")
}
// Convert snowflakeID to uint64
i, err := strconv.ParseInt(webhookParts[0], 10, 64)
if err != nil {
log.Fatal(err)
}
// Start client!
client := webhook.New(snowflake.ID(i), webhookParts[1])
c.DiscordClient = client
log.Print("Discord client loaded succesfully")
}
// sendEmbeddedMessage - Build an embedded message from listing data
func (c *LocalConfig) sendEmbeddedMessage(listing TradeMeListing) {
log.Printf("New listing: %s", listing.Title)
2022-09-13 10:44:53 +00:00
hasFibre, currentConn := getAvailableSpeeds(
2022-09-13 09:56:18 +00:00
fmt.Sprintf(
"%s, %s, %s",
strings.TrimSpace(listing.Address),
strings.TrimSpace(listing.Suburb),
strings.TrimSpace(listing.Region),
),
)
2022-09-13 07:31:25 +00:00
embed := discord.NewEmbedBuilder().
SetTitle(listing.Title).
SetURL(fmt.Sprintf("https://trademe.co.nz/%d", listing.ListingID)).
SetColor(1127128).
SetImage(listing.PictureHref).
2022-09-13 09:56:18 +00:00
AddField(
"Location",
fmt.Sprintf(
"[%s](https://maps.google.com/maps?z=12&t=m&q=loc:%f+%f)",
listing.Address,
listing.GeographicLocation.Latitude,
listing.GeographicLocation.Longitude,
),
true,
).
AddField("Bedrooms", fmt.Sprintf("%d", listing.Bedrooms), true).
2022-09-13 10:44:53 +00:00
AddField("Fibre Avail", hasFibre, false).
AddField("Current Connection", currentConn, false)
2022-09-13 07:31:25 +00:00
2022-09-13 11:25:11 +00:00
// Tag if required
if c.DiscordTag != "" {
embed.SetDescription(c.DiscordTag)
}
2022-09-13 07:39:44 +00:00
// Only add address if token set
if c.GoogleApiToken != "" && c.GoogleLocation1 != "" {
2022-09-13 11:25:11 +00:00
distance := c.getDistanceFromAddress(c.GoogleLocation1, listing.GeographicLocation.Latitude, listing.GeographicLocation.Longitude)
embed = embed.AddField(fmt.Sprintf("Walking distance to %s", c.GoogleLocation1), distance, false)
}
if c.GoogleApiToken != "" && c.GoogleLocation2 != "" {
distance := c.getDistanceFromAddress(c.GoogleLocation2, listing.GeographicLocation.Latitude, listing.GeographicLocation.Longitude)
embed = embed.AddField(fmt.Sprintf("Walking distance to %s", c.GoogleLocation2), distance, false)
2022-09-13 07:39:44 +00:00
}
2022-09-13 07:31:25 +00:00
embeds := []discord.Embed{}
embeds = append(embeds, embed.Build())
_, err := c.DiscordClient.CreateEmbeds(embeds)
if err != nil {
log.Print(err)
}
}