discord_bots/main.go

110 lines
2.6 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"math/rand/v2"
"os"
"os/signal"
"strconv"
"time"
"github.com/bwmarrin/discordgo"
"github.com/joho/godotenv"
)
var botToken string
var announceChannelName string
var cleanDelay = 30
var confFile string
func init() {
flag.StringVar(&confFile, "conf", ".env", ".env file w/ config variables")
flag.Parse()
}
var joinMessages = []string{
"<@%s> has joined <#%s>",
"<@%s> has joined <#%s>; Join in for some nerd talk",
"<#%[2]s> is the place to be! <@%[1]s> just joined",
"<#%[2]s> just go a bit cooler, <@%[1]s> is now in",
"<@%s> is hanging out in <#%s>",
}
func main() {
envs, err := godotenv.Read(confFile)
if err != nil {
log.Fatalf("Unable to get environment variables: %v", err)
}
// set values from env
botToken = envs["BOT_TOKEN"]
announceChannelName = envs["ANNOUNCE_CHANNEL"]
if delay, ok := envs["CLEAN_DELAY"]; ok {
if d2, err := strconv.Atoi(delay); err == nil {
cleanDelay = d2
}
}
s, err := discordgo.New("Bot " + botToken)
if err != nil {
log.Fatal(err)
}
// Log all of the servers tht this bot is installed in.
s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
for _, g := range r.Guilds {
g2, _ := s.Guild(g.ID)
log.Printf("Bot is connected to %q.", g2.Name)
}
})
// Add different capability handlers:
s.AddHandler(voiceStatus)
err = s.Open()
if err != nil {
log.Fatalf("Cannot open the session: %v", err)
}
defer s.Close()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
}
// Handle for when someone joins a voice channel - send notification about them joining.
func voiceStatus(s *discordgo.Session, m *discordgo.VoiceStateUpdate) {
if m.BeforeUpdate != nil || m.VoiceState == nil {
return
}
channels, err := s.GuildChannels(m.VoiceState.GuildID)
if err != nil {
log.Printf("Unable to get channels for Guild: %s", m.VoiceState.GuildID)
return
}
var announceChannel *discordgo.Channel
for _, c := range channels {
if c.Name == announceChannelName {
announceChannel = c
}
}
if announceChannel == nil {
log.Printf("Unable to get announce channel for Guild: %s", m.VoiceState.GuildID)
return
}
msg := joinMessages[rand.IntN(len(joinMessages))]
sent, err := s.ChannelMessageSend(announceChannel.ID, fmt.Sprintf(msg, m.VoiceState.UserID, m.VoiceState.ChannelID))
g, _ := s.Guild(m.VoiceState.GuildID)
log.Default().Printf("%q has joined %q in %s", m.VoiceState.Member.DisplayName(), m.VoiceState.ChannelID, g.Name)
if err != nil {
log.Printf("unable to send message: %s", err)
}
time.AfterFunc(time.Second*time.Duration(cleanDelay), func() {
s.ChannelMessageDelete(sent.ChannelID, sent.ID)
})
}