12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package discourse
- import (
- "encoding/json"
- "fmt"
- "strings"
- )
- type pmPayload struct {
- Body string `json:"raw"`
- TargetUsernames string `json:"target_usernames"`
- Title string `json:"title"`
- ArchType string `json:"archetype"`
- }
- type errorResponse struct {
- Action string `json:"action"`
- Errors []string `json:"errors"`
- }
- type newPMResponse struct {
- ID int `json:"topic_id"`
- }
- const pmArchtype = "private_message"
- // SendPM - Send a PM on the discouse forum
- func SendPM(apiConfig APIConfig, recipients []string, title, body string) (int, error) {
- newPm := pmPayload{
- ArchType: pmArchtype,
- TargetUsernames: strings.Join(recipients, ","),
- Title: title,
- Body: body,
- }
- payload, _ := json.Marshal(newPm)
- url := fmt.Sprintf("%s/posts.json", apiConfig.Endpoint)
- req, _ := newPostRequest(apiConfig, url, payload)
- client := getClient(rl)
- response, err := client.Do(req)
- if err != nil {
- return 0, err
- }
- if response.StatusCode != 200 {
- var errorResult errorResponse
- json.NewDecoder(response.Body).Decode(&errorResult)
- return 0, fmt.Errorf("Failed to send PM. %s", strings.Join(errorResult.Errors, "; "))
- }
- var result newPMResponse
- json.NewDecoder(response.Body).Decode(&result)
- return result.ID, nil
- }
|