| 1 | package zulip |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "net/url" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // CreatePayload builds a form-encoded payload for the Zulip messages API. |
| 11 | func CreatePayload(config *Config, message string) url.Values { |
| 12 | form := url.Values{} |
| 13 | |
| 14 | msgType := config.Type |
| 15 | if msgType == "" { |
| 16 | msgType = MessageTypeChannel |
| 17 | } |
| 18 | |
| 19 | form.Set("type", string(msgType)) |
| 20 | |
| 21 | if msgType == MessageTypeDirect { |
| 22 | recipients := config.To |
| 23 | if recipients == "" && config.Stream != "" { |
| 24 | recipients = config.Stream |
| 25 | } |
| 26 | |
| 27 | recipientList := parseRecipients(recipients) |
| 28 | |
| 29 | b, err := json.Marshal(recipientList) |
| 30 | if err != nil { |
| 31 | form.Set("to", recipients) |
| 32 | } else { |
| 33 | form.Set("to", string(b)) |
| 34 | } |
| 35 | } else { |
| 36 | form.Set("to", config.Stream) |
| 37 | } |
| 38 | |
| 39 | form.Set("content", message) |
| 40 | |
| 41 | if config.Topic != "" && msgType != MessageTypeDirect { |
| 42 | form.Set("topic", config.Topic) |
| 43 | } |
| 44 | |
| 45 | if config.ReadBySender { |
| 46 | form.Set("read_by_sender", "true") |
| 47 | } |
| 48 | |
| 49 | return form |
| 50 | } |
| 51 | |
| 52 | // parseRecipients splits a comma-separated list of user IDs or email addresses. |
| 53 | func parseRecipients(s string) []string { |
| 54 | parts := strings.Split(s, ",") |
| 55 | |
| 56 | result := make([]string, 0, len(parts)) |
| 57 | for _, p := range parts { |
| 58 | trimmed := strings.TrimSpace(p) |
| 59 | if trimmed != "" { |
| 60 | result = append(result, trimmed) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return result |
| 65 | } |
| 66 | |
| 67 | // ValidateMessageType returns an error if the message type is not supported. |
| 68 | func ValidateMessageType(t MessageType) error { |
| 69 | switch t { |
| 70 | case MessageTypeChannel, MessageTypeDirect, "": |
| 71 | return nil |
| 72 | default: |
| 73 | return fmt.Errorf("%w: %q", ErrInvalidMessageType, t) |
| 74 | } |
| 75 | } |