chatbot_replier.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package chatbot
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "time"
  10. )
  11. type ChatbotReplier struct {
  12. }
  13. func NewChatbotReplier() *ChatbotReplier {
  14. return &ChatbotReplier{}
  15. }
  16. func (r *ChatbotReplier) SimpleReplyText(ctx context.Context, sessionWebhook string, content []byte) error {
  17. requestBody := map[string]interface{}{
  18. "msgtype": "text",
  19. "text": map[string]interface{}{
  20. "content": string(content),
  21. },
  22. }
  23. return r.ReplyMessage(ctx, sessionWebhook, requestBody)
  24. }
  25. func (r *ChatbotReplier) SimpleReplyMarkdown(ctx context.Context, sessionWebhook string, title, content []byte) error {
  26. requestBody := map[string]interface{}{
  27. "msgtype": "markdown",
  28. "markdown": map[string]interface{}{
  29. "title": string(title),
  30. "text": string(content),
  31. },
  32. }
  33. return r.ReplyMessage(ctx, sessionWebhook, requestBody)
  34. }
  35. func (r *ChatbotReplier) ReplyMessage(ctx context.Context, sessionWebhook string, requestBody map[string]interface{}) error {
  36. requestJsonBody, _ := json.Marshal(requestBody)
  37. req, err := http.NewRequestWithContext(ctx, http.MethodPost, sessionWebhook, bytes.NewReader(requestJsonBody))
  38. if err != nil {
  39. return err
  40. }
  41. req.Header.Set("Content-Type", "application/json")
  42. req.Header.Set("Accept", "*/*")
  43. httpClient := &http.Client{
  44. Transport: http.DefaultTransport,
  45. Timeout: 5 * time.Second,
  46. }
  47. resp, err := httpClient.Do(req)
  48. if err != nil {
  49. return err
  50. }
  51. if resp.StatusCode != 200 {
  52. defer resp.Body.Close()
  53. responseJsonBody, err := io.ReadAll(resp.Body)
  54. if err != nil {
  55. return err
  56. }
  57. return fmt.Errorf(string(responseJsonBody))
  58. }
  59. return nil
  60. }