You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
3 years ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"io"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/bwmarrin/discordgo"
|
||
|
)
|
||
|
|
||
|
var client = &http.Client{}
|
||
|
|
||
|
type CommandFunction func(s *discordgo.Session, m *discordgo.MessageCreate)
|
||
|
|
||
|
func InitCommands(s *discordgo.Session) {
|
||
|
s.AddHandler(commandHandler("greet", greetCommand))
|
||
|
s.AddHandler(commandHandler("dadjoke", dadJokeCommand))
|
||
|
}
|
||
|
|
||
|
func commandHandler(commandName string, handler CommandFunction) func(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||
|
return func(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||
|
if m.Content != "!"+commandName {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
handler(s, m)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func greetCommand(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||
|
greeting := `Hello! I'm Bub! I am a bot created for the Hubbub.
|
||
|
I was created by RageCage. Ask him for more info if you're interested in looking at my source code!`
|
||
|
s.ChannelMessageSend(m.ChannelID, greeting)
|
||
|
}
|
||
|
|
||
|
func dadJokeCommand(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||
|
errorMessage := "I couldn't get a dad joke! Tell RageCage to check on me. :)"
|
||
|
req, err := http.NewRequest("GET", "https://icanhazdadjoke.com/", nil)
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
s.ChannelMessageSend(m.ChannelID, errorMessage)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
req.Header.Add("Accept", "text/plain")
|
||
|
jokeResponse, err := client.Do(req)
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
s.ChannelMessageSend(m.ChannelID, errorMessage)
|
||
|
return
|
||
|
}
|
||
|
defer jokeResponse.Body.Close()
|
||
|
|
||
|
jokeBytes, err := io.ReadAll(jokeResponse.Body)
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
s.ChannelMessageSend(m.ChannelID, errorMessage)
|
||
|
return
|
||
|
}
|
||
|
joke := string(jokeBytes)
|
||
|
log.Println(joke)
|
||
|
s.ChannelMessageSend(m.ChannelID, joke)
|
||
|
}
|