Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add mastodon service #297

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ require (
require (
github.com/appleboy/go-fcm v0.1.5
github.com/google/go-cmp v0.5.8
github.com/mattn/go-mastodon v0.0.4
)

require (
Expand Down Expand Up @@ -77,6 +78,7 @@ require (
github.com/tidwall/gjson v1.14.1 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80 //indirect
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
Expand Down
66 changes: 66 additions & 0 deletions service/mastodon/mastodon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package mastodon

import (
"context"
"fmt"

"github.com/mattn/go-mastodon"
"github.com/pkg/errors"
)

type Mastodon struct {
client *mastodon.Client
mastodonIDs []string
}

type Credentials struct {
Server string
ClientID string
ClientSecret string
AccessToken string
}

func New(credentials Credentials) (*Mastodon, error) {
config := mastodon.Config(credentials)
client := mastodon.NewClient(&config)

// Verify Credentials
_, err := client.GetAccountCurrentUser(context.Background())
if err != nil {
return nil, err
}

t := &Mastodon{
client: client,
mastodonIDs: []string{},
}

return t, nil
}

func (t *Mastodon) AddReceivers(mastodonIDs ...string) {
t.mastodonIDs = append(t.mastodonIDs, mastodonIDs...)
}

func (t Mastodon) Send(ctx context.Context, subject, message string) error {

for _, mastodonID := range t.mastodonIDs {
select {
case <-ctx.Done():
return ctx.Err()
default:
directMessage := &mastodon.Toot{
Status: fmt.Sprintf("@%s, %s: %s", mastodonID, subject, message),
Visibility: "direct",
}

_, err := t.client.PostStatus(ctx, directMessage)
if err != nil {
return errors.Wrapf(err, "failed to send direct message to mastodon ID '%s'", mastodonID)
}

}
}

return nil
}