forked from nikoksr/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviber.go
61 lines (50 loc) · 1.79 KB
/
viber.go
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
51
52
53
54
55
56
57
58
59
60
61
package viber
import (
"context"
vb "github.com/mileusna/viber"
"github.com/pkg/errors"
)
//go:generate mockery --name=viberClient --output=. --case=underscore --inpackage
type viberClient interface {
SetWebhook(url string, eventTypes []string) (vb.WebhookResp, error)
SendTextMessage(receiver, msg string) (uint64, error)
}
// Compile-time check to ensure that vb.Viber implements the viberClient interface.
var _ viberClient = new(vb.Viber)
// Viber struct holds necessary fields to communicate with Viber API
type Viber struct {
Client viberClient
SubscribedUserIDs []string
}
// New returns a new instance of Viber notification service
func New(appKey, senderName, senderAvatar string) *Viber {
return &Viber{
Client: vb.New(appKey, senderName, senderAvatar),
SubscribedUserIDs: []string{},
}
}
// AddReceivers receives subscribed user IDs then add them to internal receivers list
func (v *Viber) AddReceivers(subscribedUserIDs ...string) {
v.SubscribedUserIDs = append(v.SubscribedUserIDs, subscribedUserIDs...)
}
// SetWebhook receives a URL that will we used as a webhook URL for Viber
func (v *Viber) SetWebhook(webhookURL string) error {
_, err := v.Client.SetWebhook(webhookURL, []string{})
return err
}
// Send takes a message subject and a message body and sends them to all previously set userIds
func (v *Viber) Send(ctx context.Context, subject, message string) error {
fullMessage := subject + "\n" + message // Treating subject as message title
for _, subscribedUserID := range v.SubscribedUserIDs {
select {
case <-ctx.Done():
return ctx.Err()
default:
_, err := v.Client.SendTextMessage(subscribedUserID, fullMessage)
if err != nil {
return errors.Wrapf(err, "failed to send message to User ID '%s'", subscribedUserID)
}
}
}
return nil
}