-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
94 lines (71 loc) · 1.9 KB
/
bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package bot
import (
"fmt"
"jokey-discord-bot/config"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/icelain/jokeapi"
)
var BotId string
func Start() {
// Creating new bot session
goBot, err := discordgo.New("Bot " + config.Token)
// Handling error
if err != nil {
fmt.Println(err.Error())
return
}
// Making our bot a user using User function .
u, err := goBot.User("@me")
// Handling error
if err != nil {
fmt.Println(err.Error())
return
}
// Storing our id from u to BotId .
BotId = u.ID
/* Adding handler function to handle our messages using AddHandler from
discordgo package. We will declare messageHandler function later. */
goBot.AddHandler(messageHandler)
err = goBot.Open()
// Error handling
if err != nil {
fmt.Println(err.Error())
return
}
//If every thing works fine we will be printing this.
fmt.Println("Jokey is up and running!")
}
/* Definition of messageHandler function it takes two arguments first one is discordgo.Session which is s,
second one is discordgo.MessageCreate which is m. */
func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// Bot musn't reply to it's own messages, to confirm it we perform this check.
if m.Author.ID == BotId {
return
}
if strings.ToLower(m.Content) == "jokey help" {
helpMssg := "How can I help you today?"
_, _ = s.ChannelMessageSend(m.ChannelID, helpMssg)
}
if strings.ToLower(m.Content) == "joke" {
joke := getRandomJoke()
_, _ = s.ChannelMessageSend(m.ChannelID, joke)
}
}
func getRandomJoke() string {
ctgs := []string{"Programming", "Dark", "Miscellaneous", "Pun", "Spooky"}
api := jokeapi.New()
api.Set(jokeapi.Params{Categories: ctgs})
res, err := api.Fetch()
if err != nil {
fmt.Println(err.Error())
return ""
}
switch res.JokeType {
case "single":
return "- " + res.Joke[0]
case "twopart":
return "- " + res.Joke[0] + "\n- " + res.Joke[1]
}
return ""
}