package discourse import ( "bytes" "encoding/json" "fmt" "net/http" "strings" ) type topic 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:"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 := topic{ ArchType: pmArchtype, TargetUsernames: strings.Join(recipients, ","), Title: title, Body: body, } payload, _ := json.Marshal(newPm) fmt.Println(string(payload)) url := fmt.Sprintf("%s/posts.json?api_key=%s&api_username=%s", apiConfig.Endpoint, apiConfig.APIKey, apiConfig.APIUsername) response, err := http.Post(url, "application/json", bytes.NewBuffer(payload)) 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 }