LoginSignup
1
0

More than 1 year has passed since last update.

discordのwebhookを使用してgoから通知を送ってみた

Last updated at Posted at 2022-09-10

無料版slackだとデータが消えていってしまうということでslackに飛ばしていた通知をdiscordに飛ばせないかと思い実装をしてみました!

参考文献: https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks

1. webhook_url取得

まずはここからですね。

  1. 通知したいチャンネルの設定を開きます
    スクリーンショット 2022-09-10 13.27.46.png

  2. 連帯サービス > ウェブフックURLコピーをクリックして取得します
    スクリーンショット 2022-09-10 13.29.09.png

ここでチャンネルの変更とか可能です。

2. 実装

main.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

type Discord struct {
	Username  string `json:"username"`
	AvatarUrl string `json:"avatar_url"`
	Content   string `json:"content"`
}

func main() {
	var discord Discord
	discord.Username = "Mr. Hogehoge"
	discord.AvatarUrl = "https://github.com/qiita.png"
	discord.Content = "Hello World!"

	// encode json
	discord_json, _ := json.Marshal(discord)
	fmt.Println(string(discord_json))

	// discord webhook_url
	webhook_url := "取得したURL"
	res, _ := http.Post(
		webhook_url,
		"application/json",
		bytes.NewBuffer(discord_json),
	)
	defer res.Body.Close()
}

はい!これで

go run main.go
を実行すると以下のように通知ができます。
スクリーンショット 2022-09-10 14.04.43.png

3. 解説編

最終的にjsonでdiscrodに対しPOSTリクエストしたいので

res, _ := http.Post(
    webhook_url,
    "application/json",
    bytes.NewBuffer(discord_json),
)

これに当てはめる必要があります。

http.Post関数は以下のように定義されているので

func http.Post(url string, contentType string, body io.Reader) (resp *http.Response, err error)

各々の変数には

  • 変数1 > リクエスト先URL(今回は取得したURL)
  • 変数2 > contentType(今回はjson形式なので"application/json")
  • 変数3 > リクエストボディ(json)

を入れる必要があります。

変数1, 2は単純ですが3に関しては工夫が必要で、今回はstructを用意しそれをjsonに変換して代入する手段を取りました。以下の部分ですね。

// encode json
discord_json, _ := json.Marshal(discord)
fmt.Println(string(discord_json))

とこのような感じで実装することができます。

4. まとめ

slackの代わりにdiscordでいけそうなので個人的にはdiscordを使うことが多くなりそうです!
他にもメンションの設定とか色々できるので公式ドキュメント見てみると楽しいと思いますよ!

以上です!お疲れ様でした!!

今回実装したソースコードは以下です。
https://github.com/taiki-nd/go_discord

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0