topics.go 1.3 KB

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