matrixbot.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2021 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package matrixbot // import "miniflux.app/integration/matrixbot"
  5. import (
  6. "fmt"
  7. "miniflux.app/logger"
  8. "miniflux.app/model"
  9. "github.com/matrix-org/gomatrix"
  10. )
  11. // PushEntry pushes entries to matrix chat using integration settings provided
  12. func PushEntries(entries model.Entries, serverURL, botLogin, botPassword, chatID string) error {
  13. bot, err := gomatrix.NewClient(serverURL, "", "")
  14. if err != nil {
  15. return fmt.Errorf("matrixbot: bot creation failed: %w", err)
  16. }
  17. resp, err := bot.Login(&gomatrix.ReqLogin{
  18. Type: "m.login.password",
  19. User: botLogin,
  20. Password: botPassword,
  21. })
  22. if err != nil {
  23. logger.Debug("matrixbot: login failed: %w", err)
  24. return fmt.Errorf("matrixbot: login failed, please check your credentials or turn on debug mode")
  25. }
  26. bot.SetCredentials(resp.UserID, resp.AccessToken)
  27. defer func() {
  28. bot.Logout()
  29. bot.ClearCredentials()
  30. }()
  31. message := ""
  32. for _, entry := range entries {
  33. message = message + entry.Title + " " + entry.URL + "\n"
  34. }
  35. if _, err = bot.SendText(chatID, message); err != nil {
  36. logger.Debug("matrixbot: sending message failed: %w", err)
  37. return fmt.Errorf("matrixbot: sending message failed, turn on debug mode for more informations")
  38. }
  39. return nil
  40. }