Slack API、webhook使い方
#### API TOKEN 取得方法
https://api.slack.com/docs/oauth-test-tokens
でトークンを取得する。
#### Webhook TOKEN 取得方法
https://api.slack.com/incoming-webhooks
でトークンを取得する
curl でsend message できる
curl -XPOST "https://slack.com/api/chat.postMessage?token=<TOKEN>&channel=%23general&text=Hello%20@bot_server&username=test_bot"
curl -XPOST -d "token=<TOKEN>" -d "channel=#general" -d "text=Hello @bot_server" -d "username=test_bot" "https://slack.com/api/chat.postMessage"
いろんなAPI
https://api.slack.com/methods
使いきれない。。。
golangで試す
- API
slack_api.go
package main
import (
"bytes"
"net/http"
"net/url"
"fmt"
"os"
)
var(
token string = "tokenxxxx-xxxxxxxxxxxx" // change token
apiUrl string = "https://slack.com/api/chat.postMessage"
)
func main() {
arg := os.Args[1:]
data := url.Values{}
data.Set("token",token)
data.Add("channel","#general") // change channel
data.Add("username","testBot")
data.Add("text", fmt.Sprintf("%s",arg))
client := &http.Client{}
r, _ := http.NewRequest("POST", fmt.Sprintf("%s",apiUrl), bytes.NewBufferString(data.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
実行
./slack_api this is test!
200
slack_webhook.go
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"fmt"
)
var(
// change token
IncomingUrl string = "https://hooks.slack.com/services/xxxxxxxxxxxx/xxxxxxxxxxxx/xxxxxxxxx"
)
type Slack struct {
Text string `json:"text"`
Username string `json:"username"`
Icon_emoji string `json:"icon_emoji"`
Icon_url string `json:"icon_url"`
Channel string `json:"channel"`
}
func main() {
arg := os.Args[1:]
params, _ := json.Marshal(Slack{
fmt.Sprintf("%s",arg),
"MyBot",
"",
"http://www.icons101.com/icons/66/NuoveXT_by_Alexandre_Moore/128/slackware.png",
"#general"})
resp, _ := http.PostForm(
IncomingUrl,
url.Values{"payload": {string(params)}},
)
body, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
println(string(body))
}
実行
./slack_webhook this is test!
200 ok