discord.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package discord
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. )
  8. // Discord is an instance of the Discord service.
  9. type Discord struct {
  10. name string
  11. avatar string
  12. webhookURL string
  13. }
  14. // New will create a new instance of the Discord service.
  15. func New(name, avatar, webhook string) (*Discord, error) {
  16. return &Discord{
  17. name: name,
  18. avatar: avatar,
  19. webhookURL: webhook,
  20. }, nil
  21. }
  22. // Send will send a message to a Discord channel via a webhook.
  23. func (t *Discord) Send(content string) error {
  24. type message struct {
  25. Username string `json:"username"`
  26. Content string `json:"content"`
  27. Avatar string `json:"avatar_url"`
  28. }
  29. msg := message{
  30. Username: t.name,
  31. Content: content,
  32. Avatar: t.avatar,
  33. }
  34. jsonText, err := json.Marshal(msg)
  35. if err != nil {
  36. return errors.Wrap(err, "error marshalling discord message to json")
  37. }
  38. req, err := http.NewRequest("POST", t.webhookURL, bytes.NewReader(jsonText))
  39. if err != nil {
  40. return errors.Wrap(err, "error creating discord webhook request")
  41. }
  42. req.Header.Set("Content-Type", "application/json")
  43. client := &http.Client{}
  44. resp, err := client.Do(req)
  45. if err != nil {
  46. return errors.Wrap(err, "error executing discord webhook")
  47. }
  48. return resp.Body.Close()
  49. }