summaryrefslogtreecommitdiff
path: root/main.go
blob: e3d2228dd43b5a8e1baafffe9f1f91f525047451 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/labstack/echo"
	"io/ioutil"
	"log"
	"net/http"
)

type event struct {
	Payload string `form:"payload"`
}

type payload struct {
	Type     string `json:"type" form:"type"`
	Token    string `json:"token"`
	ActionTS string `json:"action_ts"`

	Team struct {
		ID     string `json:"id"`
		Domain string `json:"domain"`
	}
	User struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"user"`
	Channel struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"channel"`
	CallbackID string `json:"callback_id"`
	TriggerID  string `json:"trigger_id"`
	MessageTS  string `json:"message_ts"`
	Message    struct {
		ClientMsgID string `json:"client_msg_id"`
		Type        string `json:"type"`
		Text        string `json:"text"`
		User        string `json:"user"`
		TS          string `json:"ts"`
	} `json:"message"`
	ResponseUrl string `json:"response_url"`
}

type message struct {
	Text         string       `json:"text"`
	ResponseType string       `json:"response_type"`
	Attachments  []Attachment `json:"attachments"`
}
type Attachment struct {
	Color string `json:"color"`
	Text  string `json:"text"`
}

func main() {
	e := echo.New()
	e.POST("/events-endpoint", func(c echo.Context) error {
		ev := &event{}
		c.Bind(ev)
		pl := &payload{}
		if err := json.Unmarshal([]byte(ev.Payload), pl); err != nil {
			log.Println(err)
			return err
		}

		member := getRandomMember()
		text := "Назначен: " + member
		jm := message{
			Text:         pl.Message.Text,
			ResponseType: "in_channel",
			Attachments:  []Attachment{{Text: text, Color: "#36a64f"}},
		}
		b, _ := json.Marshal(jm)
		resp, err := http.DefaultClient.Post(pl.ResponseUrl, "application/json", bytes.NewReader(b))
		if err != nil {
			return err
		}
		if resp.StatusCode >= 300 || resp.StatusCode < 200 {
			return errors.New("unexpected status " + resp.Status)
		}
		defer resp.Body.Close()
		s, _ := ioutil.ReadAll(resp.Body)
		log.Println(string(s))

		return nil
	})
	if err := e.Start(":3000"); err != nil {
		log.Fatalln(err)
	}
}