前言
使用的依赖包Github
$ go get github.com/bwmarrin/discordgo
创建Discord Bot
- 访问 applications
- 右上角的
New Application
- 填写名字
- Bot -> Add Bot -> Yes, do it! -> 复制
TOKEN
待会会用 - General Information -> Client ID -> Copy
- https://discord.com/api/oauth2/authorize?client_id={{Clinet ID}}&permissions=0&scope=bot -> 添加到服务器
代码
// main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/bwmarrin/discordgo"
)
func main() {
// Bot 后面不加空格会出错
discord, err := discordgo.New("Bot " + "{{TOKEN}}")
if err != nil {
log.Printf("Create discord bot failed: %v\n", err)
}
// event list https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events
discord.AddHandler(handlers.Ready)
discord.AddHandler(handlers.MessageCreate)
err = discord.Open()
if err != nil {
log.Printf("Open bot failed: %v\n", err)
}
// Wait here until CTRL-C or other term signal is received.
fmt.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// Cleanly close down the Discord session.
dg.Close()
}
handler 的构成
func MessageCreate(s *discordgo.Session, m *discordgo.<event name>)
简单的处理
// handlers/handlers.go
package handlers
import (
"fmt"
"time"
"github.com/bwmarrin/discordgo"
)
func MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
fmt.Printf("%20s %20s %20s > %s\n", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)
switch m.Content {
// 如果文本是hello 返回 @author hello
case "hello":
s.ChannelMessageSend(m.ChannelID, "<@!"+m.Author.ID+"> hello")
}
}
func Ready(s *discordgo.Session, m *discordgo.Ready) {
// 如果Bot上线更改游戏状态
s.UpdateGameStatus(0, "Minecraft")
}