Skip to content

Commit

Permalink
feat: update discord-webhook-publisher
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasgouveia committed Apr 25, 2023
1 parent 4a1d46f commit e638984
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions discord-webhook-publisher/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module handler/function

go 1.19
53 changes: 53 additions & 0 deletions discord-webhook-publisher/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package function

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)

const (
webhookUrl = "https://discord.com/api/webhooks/1089563947423764550/LuUfqOQMwscSZlS9gOboRraau0J-rJw9YCMKJ03RA2P5q1GKOGQUUB8Ezqlr1G4T3EIz"
)

// Data Transfer Object for the request
type PublishMessageRequest struct {
Message string `json:"message"`
}

func Handler(w http.ResponseWriter, r *http.Request) {
// If the incoming request is not POST,
// we return a HTTP 405 Method Not Allowed
if r.Method != http.MethodPost {
http.Error(w, "This function accept only POST requests.", http.StatusMethodNotAllowed)
return
}

// Decode the request body, and if an error occurs,
// return a HTTP 400 Bad Request error
dto := &PublishMessageRequest{}
if err := json.NewDecoder(r.Body).Decode(dto); err != nil {
http.Error(w, fmt.Sprintf("Unable to decode request body: %v", err), http.StatusBadRequest)
return
}

// Create a valid JSON request body for the webhook.
// https://discord.com/developers/docs/resources/webhook#execute-webhook
data, _ := json.Marshal(map[string]interface{}{
"user": "Morty",
"content": dto.Message,
})

// Create the request and execute it
req, _ := http.NewRequest(http.MethodPost, webhookUrl, bytes.NewReader(data))
req.Header.Add("Content-Type", "application/json")

if _, err := http.DefaultClient.Do(req); err != nil {
http.Error(w, fmt.Sprintf("failed to send data to webhook: %v", err), http.StatusInternalServerError)
return
}

// Send the HTTP 204 No Content
w.WriteHeader(http.StatusNoContent)
}
2 changes: 2 additions & 0 deletions discord-webhook-publisher/morty.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
name: discord-webhook-publisher
runtime: go-1.19

0 comments on commit e638984

Please sign in to comment.