mst/main.go

108 lines
2.4 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/mattn/go-mastodon"
"github.com/sirupsen/logrus"
cli "github.com/urfave/cli/v2" // imports as package "cli"
_ "golang.org/x/tools/blog/atom"
)
func init() {
logrus.SetOutput(os.Stderr)
}
func main() {
app := &cli.App{
Name: "mst",
Usage: "simple mastodon toy",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "default config file (for keys and tokens)",
Value: "./config.json",
},
&cli.BoolFlag{
Name: "timeline",
Usage: "output the users timeline feed",
},
&cli.StringFlag{
Name: "hash",
Usage: "stream the search of the provided hashtag",
},
},
Action: func(ctx *cli.Context) error {
config := mastodon.Config{
Server: "https://mastodon.social",
ClientID: "asdfasdfafd",
ClientSecret: "asfdasdfasfd",
AccessToken: "asdfasdfadfasfd",
}
buf, err := os.ReadFile(ctx.String("config"))
if err == nil {
tmpconfig := mastodon.Config{}
err := json.Unmarshal(buf, &tmpconfig)
if err != nil {
logrus.Fatal(err)
}
config = tmpconfig
} else {
logrus.Warn(err)
}
// https://pkg.go.dev/github.com/mattn/go-mastodon#Config
c := mastodon.NewClient(&config)
if ctx.Bool("timeline") {
timeline, err := c.GetTimelineHome(context.Background(), nil)
if err != nil {
logrus.Fatal(err)
}
for i := len(timeline) - 1; i >= 0; i-- {
fmt.Println(timeline[i])
}
}
if ctx.String("hash") != "" {
// https://pkg.go.dev/github.com/mattn/go-mastodon#Client.StreamingHashtag
evnt, err := c.StreamingHashtag(context.Background(), ctx.String("hash"), false)
if err != nil {
logrus.Fatal(err)
}
for {
select {
case e := <-evnt:
switch v := e.(type) {
case nil:
logrus.Info("event is nil")
case *mastodon.UpdateEvent:
// https://pkg.go.dev/github.com/mattn/go-mastodon#Status
buf, err := json.MarshalIndent(v.Status, "", " ")
if err != nil {
logrus.Error(err)
}
fmt.Println(string(buf))
case *mastodon.ErrorEvent:
logrus.Errorf("event was error: %#v", v.Error())
default:
logrus.Warnf("not sure what to do with %T: %s", v, v)
// just saw a *mastodon.DeleteEvent
}
}
}
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
logrus.Fatal(err)
}
}