send messages on a schedule

This commit is contained in:
Khinshan Khan
2025-03-08 19:52:42 -05:00
parent 4a11a52969
commit c3d7e97468
+16 -23
View File
@@ -5,6 +5,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"time"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/joho/godotenv" "github.com/joho/godotenv"
@@ -18,8 +19,9 @@ func main() {
} }
botToken := os.Getenv("DISCORD_BOT_TOKEN") botToken := os.Getenv("DISCORD_BOT_TOKEN")
if botToken == "" { channelID := os.Getenv("DISCORD_CHANNEL_ID")
fmt.Println("Missing variable in .env") if botToken == "" || channelID == "" {
fmt.Println("Missing DISCORD_BOT_TOKEN or DISCORD_CHANNEL_ID in .env")
return return
} }
@@ -32,13 +34,15 @@ func main() {
// open WebSocket connection // open WebSocket connection
dg.AddHandler(readyHandler) dg.AddHandler(readyHandler)
dg.AddHandler(messageCreate)
err = dg.Open() err = dg.Open()
if err != nil { if err != nil {
fmt.Println("Error opening connection,", err) fmt.Println("Error opening connection,", err)
return return
} }
// start the scheduled messages
go sendScheduledMessages(dg, channelID)
// wait here until CTRL-C or other term signal is received. // wait here until CTRL-C or other term signal is received.
fmt.Println("Bot is now running. Press CTRL-C to exit.") fmt.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1) sc := make(chan os.Signal, 1)
@@ -53,26 +57,15 @@ func readyHandler(s *discordgo.Session, r *discordgo.Ready) {
fmt.Println("Ready to rumble!") fmt.Println("Ready to rumble!")
} }
// This function will be called (due to AddHandler above) every time a new func sendScheduledMessages(s *discordgo.Session, channelID string) {
// message is created on any channel that the authenticated bot has access to. ticker := time.NewTicker(30 * time.Second)
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { defer ticker.Stop()
// Ignore all messages created by the bot itself for range ticker.C {
// This isn't required in this specific example but it's a good practice. message := "Good"
if m.Author.ID == s.State.User.ID { _, err := s.ChannelMessageSend(channelID, message)
return if err != nil {
} fmt.Printf("Error sending message: %v\n", err)
}
// Ugh message is blank, must be some weird intents thing?
fmt.Println(m.Author.Username + " sent: " + m.Content)
// If the message is "ping" reply with "Pong!"
if m.Content == "ping" {
s.ChannelMessageSend(m.ChannelID, "Pong!")
}
// If the message is "pong" reply with "Ping!"
if m.Content == "pong" {
s.ChannelMessageSend(m.ChannelID, "Ping!")
} }
} }