new message

This commit is contained in:
Chris kerr 2024-04-26 22:30:28 -04:00
parent 22d05c4807
commit 50513cf3cd

241
main.go
View File

@ -15,80 +15,82 @@ import (
) )
type Config struct { type Config struct {
DiscordBotToken string `json:"discord_bot_token"` DiscordBotToken string `json:"discord_bot_token"`
DiscordChannelID string `json:"discord_channel_id"` // Add more configuration fields here DiscordChannelID string `json:"discord_channel_id"` // Add more configuration fields here
} }
func main() { func main() {
// Open and read the configuration file // Open and read the configuration file
configFile, err := os.Open("config.json") configFile, err := os.Open("config.json")
if err != nil { if err != nil {
fmt.Println("Error opening config file:", err) fmt.Println("Error opening config file:", err)
return return
} }
defer configFile.Close() defer configFile.Close()
// Parse the configuration from JSON // Parse the configuration from JSON
var config Config var config Config
err = json.NewDecoder(configFile).Decode(&config) err = json.NewDecoder(configFile).Decode(&config)
if err != nil { if err != nil {
fmt.Println("Error decoding config JSON:", err) fmt.Println("Error decoding config JSON:", err)
return return
} }
// Access the Discord bot token from the configuration // Access the Discord bot token from the configuration
token := config.DiscordBotToken token := config.DiscordBotToken
if token == "" { if token == "" {
fmt.Println("Discord bot token is not set in config file") fmt.Println("Discord bot token is not set in config file")
return return
} }
// //
channelID := config.DiscordChannelID channelID := config.DiscordChannelID
if channelID == "" { if channelID == "" {
fmt.Println("Discord channel ID is not set in config file") fmt.Println("Discord channel ID is not set in config file")
} }
// Create a new Discord session using the provided bot token // Create a new Discord session using the provided bot token
dg, err := discordgo.New("Bot " + token) dg, err := discordgo.New("Bot " + token)
if err != nil { if err != nil {
fmt.Println("Error creating Discord session:", err) fmt.Println("Error creating Discord session:", err)
return return
} }
// Register messageCreate as a callback for the messageCreate events // Register messageCreate as a callback for the messageCreate events
dg.AddHandler(messageCreate) dg.AddHandler(messageCreate)
// Open a websocket connection to Discord and begin listening dg.AddHandler(message2Create)
err = dg.Open()
if err != nil {
fmt.Println("Error opening Discord connection:", err)
return
}
// Run the scraping and message sending function once at the specified time // Open a websocket connection to Discord and begin listening
err = dg.Open()
if err != nil {
fmt.Println("Error opening Discord connection:", err)
return
}
// Run the scraping and message sending function once at the specified time
sendNotifications(dg, channelID, scrapeNews()) sendNotifications(dg, channelID, scrapeNews())
// Schedule the scraping and message sending function to run once a day // Schedule the scraping and message sending function to run once a day
ticker := time.NewTicker(24 * time.Hour) ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop() defer ticker.Stop()
// Run the scraping and message sending function when the ticker ticks // Run the scraping and message sending function when the ticker ticks
go func() { go func() {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
sendNotifications(dg, channelID, scrapeNews()) sendNotifications(dg, channelID, scrapeNews())
} }
} }
}() }()
//test() //test()
// 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.")
<-make(chan struct{}) <-make(chan struct{})
} }
func scrapeNews() string { func scrapeNews() string {
@ -116,74 +118,85 @@ func scrapeNews() string {
// Add a function to extract relevant tags from the HTML content // Add a function to extract relevant tags from the HTML content
func extractTags(html string) []string { func extractTags(html string) []string {
var tags []string var tags []string
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil { if err != nil {
fmt.Println("Error parsing HTML:", err) fmt.Println("Error parsing HTML:", err)
return tags return tags
} }
// Find and extract tags with class name "news-module-feed-item-details-tag" // Find and extract tags with class name "news-module-feed-item-details-tag"
doc.Find("span.news-module-feed-item-details-tag").Each(func(i int, s *goquery.Selection) { doc.Find("span.news-module-feed-item-details-tag").Each(func(i int, s *goquery.Selection) {
tag := strings.TrimSpace(s.Text()) tag := strings.TrimSpace(s.Text())
tags = append(tags, tag) tags = append(tags, tag)
}) })
return tags return tags
} }
// Define a map to associate each desired tag with its corresponding Discord channel ID // Define a map to associate each desired tag with its corresponding Discord channel ID
var tagChannelMap = map[string]string{ var tagChannelMap = map[string]string{
"Patch Notes": "556093419341086749", "Patch Notes": "556093419341086749",
"Atomic Shop": "590581442392621067", "Atomic Shop": "590581442392621067",
"News": "558335339018846228", "News": "558335339018846228",
// Add more tags and corresponding channel IDs as needed // Add more tags and corresponding channel IDs as needed
} }
func sendNotifications(session *discordgo.Session, channelID string, html string) { func sendNotifications(session *discordgo.Session, channelID string, html string) {
// Extract tags from the HTML content // Extract tags from the HTML content
tags := extractTags(html) tags := extractTags(html)
// Define today's date string // Define today's date string
today := time.Now().Format("January 2, 2006") today := time.Now().Format("January 2, 2006")
// Iterate over extracted tags // Iterate over extracted tags
for _, tag := range tags { for _, tag := range tags {
// Check if the tag is in the desired tags list // Check if the tag is in the desired tags list
if tagChannelID, ok := tagChannelMap[tag]; ok { if tagChannelID, ok := tagChannelMap[tag]; ok {
// Check if today's date matches the tag // Check if today's date matches the tag
if tag == today { if tag == today {
// Send a message to the corresponding Discord channel // Send a message to the corresponding Discord channel
message := fmt.Sprintf("Today's date matches the tag '%s' on the Fallout news page!", tag) message := fmt.Sprintf("Today's date matches the tag '%s' on the Fallout news page!", tag)
_, err := session.ChannelMessageSend(tagChannelID, message) _, err := session.ChannelMessageSend(tagChannelID, message)
if err != nil { if err != nil {
fmt.Printf("Error sending message to Discord channel %s: %s\n", tagChannelID, err) fmt.Printf("Error sending message to Discord channel %s: %s\n", tagChannelID, err)
continue continue
} }
fmt.Println("Message sent to Discord channel:", tagChannelID) fmt.Println("Message sent to Discord channel:", tagChannelID)
} else { } else {
// Send a different message indicating the tag was found // Send a different message indicating the tag was found
message := fmt.Sprintf("Tag '%s' found on the Fallout news page, but it's not today's date.", tag) message := fmt.Sprintf("Tag '%s' found on the Fallout news page, but it's not today's date.", tag)
_, err := session.ChannelMessageSend(tagChannelID, message) _, err := session.ChannelMessageSend(tagChannelID, message)
if err != nil { if err != nil {
fmt.Printf("Error sending message to Discord channel %s: %s\n", tagChannelID, err) fmt.Printf("Error sending message to Discord channel %s: %s\n", tagChannelID, err)
continue continue
} }
fmt.Println("Message sent to Discord channel:", tagChannelID) fmt.Println("Message sent to Discord channel:", tagChannelID)
} }
} }
} }
} }
// This function will be called whenever a new message is created // This function will be called whenever a new message is created
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore messages created by the bot itself // Ignore messages created by the bot itself
if m.Author.ID == s.State.User.ID { if m.Author.ID == s.State.User.ID {
return return
} }
// If the message content is "!hello", respond with "Hello!" // If the message content is "!hello", respond with "Hello!"
if m.Content == "!hello" { if m.Content == "!hello1" {
_, _ = s.ChannelMessageSend(m.ChannelID, "Hello!") _, _ = s.ChannelMessageSend(m.ChannelID, "Hello!")
} }
}
// This function will be called whenever a new message is created
func message2Create(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore messages created by the bot itself
if m.Author.ID == s.State.User.ID {
return
}
// If the message content is "!hello", respond with "Hello!"
if m.Content == "!hello" {
_, _ = s.ChannelMessageSend(m.ChannelID, "You are SUCH a NERD")
}
} }