|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | +) |
| 10 | + |
| 11 | +func SendSlackMessage(airtableAPIKey string, userID string, message string, blocksJSON string) error { |
| 12 | + record := map[string]interface{}{ |
| 13 | + "fields": map[string]interface{}{ |
| 14 | + "requester_identifier": "Hackatime Reset Password", |
| 15 | + "target_slack_id": userID, |
| 16 | + "message_text": message, |
| 17 | + "message_blocks": blocksJSON, |
| 18 | + "unfurl_links": true, |
| 19 | + "unfurl_media": true, |
| 20 | + "send_success": false, |
| 21 | + }, |
| 22 | + } |
| 23 | + |
| 24 | + payload := map[string]interface{}{ |
| 25 | + "records": []interface{}{record}, |
| 26 | + } |
| 27 | + |
| 28 | + jsonPayload, err := json.Marshal(payload) |
| 29 | + if err != nil { |
| 30 | + return fmt.Errorf("error marshaling payload: %v", err) |
| 31 | + } |
| 32 | + |
| 33 | + req, err := http.NewRequest("POST", "https://middleman.hackclub.com/airtable/v0/appTeNFYcUiYfGcR6/arrpheus_message_requests", bytes.NewBuffer(jsonPayload)) |
| 34 | + if err != nil { |
| 35 | + return fmt.Errorf("error creating request: %v", err) |
| 36 | + } |
| 37 | + |
| 38 | + req.Header.Set("Content-Type", "application/json") |
| 39 | + req.Header.Set("Accept", "application/json") |
| 40 | + req.Header.Set("Authorization", "Bearer "+airtableAPIKey) |
| 41 | + req.Header.Set("User-Agent", "waka.hackclub.com (reset password)") |
| 42 | + |
| 43 | + client := &http.Client{} |
| 44 | + resp, err := client.Do(req) |
| 45 | + if err != nil { |
| 46 | + return fmt.Errorf("error sending request: %v", err) |
| 47 | + } |
| 48 | + defer resp.Body.Close() |
| 49 | + |
| 50 | + body, err := io.ReadAll(resp.Body) |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("error reading response body: %v", err) |
| 53 | + } |
| 54 | + |
| 55 | + var result struct { |
| 56 | + Records []struct{} `json:"records"` |
| 57 | + Error struct { |
| 58 | + Type string `json:"type"` |
| 59 | + Message string `json:"message"` |
| 60 | + } `json:"error,omitempty"` |
| 61 | + } |
| 62 | + |
| 63 | + if err := json.Unmarshal(body, &result); err != nil { |
| 64 | + return fmt.Errorf("error parsing response: %v", err) |
| 65 | + } |
| 66 | + |
| 67 | + if result.Error.Type != "" { |
| 68 | + return fmt.Errorf("Airtable error: %s - %s", result.Error.Type, result.Error.Message) |
| 69 | + } |
| 70 | + |
| 71 | + return nil |
| 72 | +} |
0 commit comments