forked from furtidev/the-farting-whale
90 lines
2.4 KiB
Go
90 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"strings"
|
|
"regexp"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
func main() {
|
|
vpr := viper.GetViper()
|
|
vpr.SetConfigFile(".env")
|
|
var token string = ""
|
|
if err := vpr.ReadInConfig(); err != nil {
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
|
|
log.Fatalln("Config file (.env) not found!")
|
|
} else {
|
|
log.Println("Failed to parse config!")
|
|
}
|
|
}
|
|
|
|
if vpr.GetString("DISCORD_BOT_TOKEN") == "" {
|
|
token = os.Getenv("DISCORD_BOT_TOKEN")
|
|
if token == "" {
|
|
log.Fatalln("Couldn't fetch bot token!")
|
|
}
|
|
} else {
|
|
token = vpr.GetString("DISCORD_BOT_TOKEN")
|
|
}
|
|
|
|
dg, err := discordgo.New("Bot " + token)
|
|
if err != nil {
|
|
log.Fatalf("Error creating Discord session: %s\n", err)
|
|
}
|
|
|
|
dg.AddHandler(messageCreate)
|
|
dg.Identify.Intents = discordgo.IntentsGuildMessages
|
|
|
|
// connect to discord
|
|
err = dg.Open()
|
|
if err != nil {
|
|
log.Fatalf("Couldn't connect to DIscord: %s\n", err)
|
|
}
|
|
|
|
// wait until ctrl+c or other term signal is received
|
|
fmt.Println("The Farting Whale is online!")
|
|
sc := make(chan os.Signal, 1)
|
|
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
|
|
<-sc
|
|
|
|
// graceful shutdown
|
|
dg.Close()
|
|
}
|
|
|
|
// incoming message handler
|
|
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
|
|
// ignore messages sent by the bot.
|
|
if m.Author.ID == s.State.User.ID {
|
|
return
|
|
}
|
|
|
|
if strings.HasPrefix(m.Content, "!fart") {
|
|
c := strings.Fields(m.Content)
|
|
if len(c) == 1 {
|
|
s.ChannelMessageSend(m.ChannelID, ":whale2: :dash:")
|
|
} else if len(c) == 2 {
|
|
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(":whale2: :dash: %s", c[1]))
|
|
}
|
|
return
|
|
}
|
|
|
|
// check for reddit/twitter links and replace them with open source frontends
|
|
re := regexp.MustCompile(`(?i)((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)`)
|
|
result := re.FindStringSubmatch(m.Content)
|
|
// hard coded, group 2 contains the base url
|
|
if len(result) >= 3 {
|
|
if result[2] == "https://www.reddit.com" || result[2] == "https://reddit.com"{
|
|
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("<https://tedd.it%s>", result[4]))
|
|
} else if result[2] == "https://www.twitter.com" || result[2] == "https://twitter.com" {
|
|
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("<https://nitter.lacontrevoie.fr/%s>", result[4]))
|
|
}
|
|
}
|
|
}
|