在本地將機器人上線
Golang 版本: 1.17.5
使用套件: https://github.com/bwmarrin/discordgo
- 建立資料夾 discordbot,並使用編輯器開啟
- 在終端機輸入指令來建立 go.mod
go mod init disocrdbot
- 建立 .exv 檔案,輸入上一章節取得的機器人 token
DCToken=你的機器人token
建立 main.go
package main import ( "fmt" "os" "os/signal" "syscall" "github.com/bwmarrin/discordgo" _ "github.com/joho/godotenv/autoload" ) func main() { token := os.Getenv("DCToken") // creates a new Discord session dg, err := discordgo.New("Bot " + token) if err != nil { fmt.Println("error creating Discord session,", err) return } // Register the messageCreate func as a callback for MessageCreate events. dg.AddHandler(messageCreate) // 只監聽訊息 dg.Identify.Intents = discordgo.IntentsGuildMessages // 開啟連線 err = dg.Open() if err != nil { fmt.Println("error opening connection,", err) return } // 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) <-sc // Cleanly close down the Discord session. dg.Close() } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { // Ignore all messages created by the bot itself // This isn't required in this specific example but it's a good practice. if m.Author.ID == s.State.User.ID { return } // If the message is "ping" reply with "Pong!" if m.Content == "ping" { s.ChannelMessageSend(m.ChannelID, "Pong!") } // If the message is "pong" reply with "Ping!" if m.Content == "pong" { s.ChannelMessageSend(m.ChannelID, "Ping!") } }
在終端機執行 go mod tidy 來下載套件
go mod tidy
目前資料夾的檔案
執行 go run main.go 執行檔案
go run main.go
有看到以下文字出現在終端機就代表成功將機器人上線了
Bot is now running. Press CTRL-C to exit.
回到 Discord 有機器人的伺服器,輸入 ping 或 pong 就可以看到機器人回應你了