aboutsummaryrefslogtreecommitdiff
path: root/internal/integration/matrixbot/matrixbot.go
blob: 7b3198ed5bd5d6ee4ccf8fbeaad68c4879c3be55 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package matrixbot // import "miniflux.app/v2/internal/integration/matrixbot"

import (
	"fmt"

	"miniflux.app/v2/internal/logger"
	"miniflux.app/v2/internal/model"

	"github.com/matrix-org/gomatrix"
)

// PushEntry pushes entries to matrix chat using integration settings provided
func PushEntries(entries model.Entries, serverURL, botLogin, botPassword, chatID string) error {
	bot, err := gomatrix.NewClient(serverURL, "", "")
	if err != nil {
		return fmt.Errorf("matrixbot: bot creation failed: %w", err)
	}

	resp, err := bot.Login(&gomatrix.ReqLogin{
		Type:     "m.login.password",
		User:     botLogin,
		Password: botPassword,
	})

	if err != nil {
		logger.Debug("matrixbot: login failed: %w", err)
		return fmt.Errorf("matrixbot: login failed, please check your credentials or turn on debug mode")
	}

	bot.SetCredentials(resp.UserID, resp.AccessToken)
	defer func() {
		bot.Logout()
		bot.ClearCredentials()
	}()

	message := ""
	for _, entry := range entries {
		message = message + entry.Title + " " + entry.URL + "\n"
	}

	if _, err = bot.SendText(chatID, message); err != nil {
		logger.Debug("matrixbot: sending message failed: %w", err)
		return fmt.Errorf("matrixbot: sending message failed, turn on debug mode for more informations")
	}

	return nil
}