Featured image of post 使用Go制作Discord机器人

使用Go制作Discord机器人

前言

使用的依赖包Github

$ go get github.com/bwmarrin/discordgo

创建Discord Bot

  1. 访问 applications
  2. 右上角的 New Application
  3. 填写名字
  4. Bot -> Add Bot -> Yes, do it! -> 复制 TOKEN 待会会用
  5. General Information -> Client ID -> Copy
  6. 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")
}

后记

discordgo官方

Licensed under CC BY-NC-SA 4.0
最后更新于 2021 年 11 月 5 日 23:09 +0900