session.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package discourse
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. )
  10. type Session struct {
  11. apiKey string
  12. apiUser string
  13. apiEndpoint string
  14. }
  15. func (session Session) SendPM(usernames []string, title string, body string) (string, error) {
  16. targetUsernames := strings.Join(usernames, ",")
  17. messageJSON := map[string]interface{}{
  18. "title": title,
  19. "target_usernames": targetUsernames,
  20. "archetype": "private_message",
  21. "raw": body,
  22. }
  23. payload, err := json.Marshal(messageJSON)
  24. if err != nil {
  25. return "", err
  26. }
  27. url := fmt.Sprintf("%s/posts.json?api_key=%s&api_username=%s", session.apiEndpoint, session.apiKey, session.apiUser)
  28. response, err := http.Post(url, "application/json", bytes.NewBuffer(payload))
  29. if err != nil {
  30. return "", err
  31. }
  32. var result map[string]interface{}
  33. json.NewDecoder(response.Body).Decode(&result)
  34. topicIDDigit := result["topic_id"].(float64)
  35. topicID := strconv.FormatFloat(topicIDDigit, 'f', -1, 64)
  36. return topicID, nil
  37. }