|
| 1 | +package agents |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/tech-thinker/chat/config" |
| 10 | +) |
| 11 | + |
| 12 | +type slackAgent struct { |
| 13 | + config *config.Config |
| 14 | +} |
| 15 | + |
| 16 | +func (agent *slackAgent) Post(message string) (interface{}, error) { |
| 17 | + url := "https://slack.com/api/chat.postMessage" |
| 18 | + |
| 19 | + payloadStr := fmt.Sprintf( |
| 20 | + `{"channel": "%s","text": "%s"}`, |
| 21 | + agent.config.SlackChannelId, message, |
| 22 | + ) |
| 23 | + |
| 24 | + payload := strings.NewReader(payloadStr) |
| 25 | + |
| 26 | + req, _ := http.NewRequest("POST", url, payload) |
| 27 | + |
| 28 | + req.Header.Add("Content-Type", "application/json") |
| 29 | + req.Header.Add("User-Agent", "tech-thinker/chat") |
| 30 | + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", agent.config.SlackToken)) |
| 31 | + |
| 32 | + res, err := http.DefaultClient.Do(req) |
| 33 | + if err!=nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + |
| 37 | + defer res.Body.Close() |
| 38 | + body, err := io.ReadAll(res.Body) |
| 39 | + return string(body), err |
| 40 | +} |
| 41 | + |
| 42 | +func (agent *slackAgent) Reply(threadId string, message string) (interface{}, error) { |
| 43 | + url := "https://slack.com/api/chat.postMessage" |
| 44 | + |
| 45 | + payloadStr := fmt.Sprintf( |
| 46 | + `{"channel": "%s", "text": "%s", "thread_ts": "%s"}`, |
| 47 | + agent.config.SlackChannelId, message, threadId, |
| 48 | + ) |
| 49 | + |
| 50 | + payload := strings.NewReader(payloadStr) |
| 51 | + |
| 52 | + req, _ := http.NewRequest("POST", url, payload) |
| 53 | + |
| 54 | + req.Header.Add("Content-Type", "application/json") |
| 55 | + req.Header.Add("User-Agent", "tech-thinker/chat") |
| 56 | + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", agent.config.SlackToken)) |
| 57 | + |
| 58 | + res, err := http.DefaultClient.Do(req) |
| 59 | + if err!=nil { |
| 60 | + return nil, err |
| 61 | + } |
| 62 | + |
| 63 | + defer res.Body.Close() |
| 64 | + body, err := io.ReadAll(res.Body) |
| 65 | + return string(body), err |
| 66 | +} |
| 67 | + |
| 68 | +func NewSlackAgent(config *config.Config) Agent { |
| 69 | + return &slackAgent{config: config} |
| 70 | +} |
0 commit comments