topics.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package discourse
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. )
  9. type topic struct {
  10. Body string `json:"raw"`
  11. TargetUsernames string `json:"target_usernames"`
  12. Title string `json:"title"`
  13. ArchType string `json:"archetype"`
  14. }
  15. type errorResponse struct {
  16. Action string `json:"action"`
  17. Errors []string `json:"errors"`
  18. }
  19. type newPMResponse struct {
  20. ID int `json:"id"`
  21. }
  22. const pmArchtype = "private_message"
  23. // SendPM - Send a PM on the discouse forum
  24. func SendPM(apiConfig APIConfig, recipients []string, title, body string) (int, error) {
  25. newPm := topic{
  26. ArchType: pmArchtype,
  27. TargetUsernames: strings.Join(recipients, ","),
  28. Title: title,
  29. Body: body,
  30. }
  31. payload, _ := json.Marshal(newPm)
  32. fmt.Println(string(payload))
  33. url := fmt.Sprintf("%s/posts.json?api_key=%s&api_username=%s",
  34. apiConfig.Endpoint, apiConfig.APIKey, apiConfig.APIUsername)
  35. response, err := http.Post(url, "application/json", bytes.NewBuffer(payload))
  36. if err != nil {
  37. return 0, err
  38. }
  39. if response.StatusCode != 200 {
  40. var errorResult errorResponse
  41. json.NewDecoder(response.Body).Decode(&errorResult)
  42. return 0, fmt.Errorf("Failed to send PM. %s", strings.Join(errorResult.Errors, "; "))
  43. }
  44. var result newPMResponse
  45. json.NewDecoder(response.Body).Decode(&result)
  46. return result.ID, nil
  47. }