You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lurk/main.go

137 lines
2.9 KiB

package main
import (
"flag"
"os"
"os/signal"
"strings"
"syscall"
"time"
"go.jolheiser.com/lurk/config"
"go.jolheiser.com/lurk/handler"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"github.com/peterbourgon/ff/v3"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/turnage/graw/reddit"
)
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.InfoLevel)
fs := flag.NewFlagSet("lurk", flag.ExitOnError)
configFlag := fs.String("config", "config.yaml", "path to config file")
debugFlag := fs.Bool("debug", false, "turn on debug mode")
if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix("LURK")); err != nil {
log.Fatal().Err(err).Msg("")
}
if *debugFlag {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
if len(os.Args) > 1 && strings.EqualFold(os.Args[1], "init") {
if err := config.Init(*configFlag); err != nil {
log.Err(err).Msg("")
return
}
log.Info().Msgf("created %q", *configFlag)
return
}
cfg, err := config.Load(*configFlag)
if err != nil {
log.Fatal().Err(err).Msg("")
}
// Reddit
go lurkReddit(cfg)
// Twitter
go lurkTwitter(cfg)
log.Info().Msg("Lurk is ready to start lurking!")
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
}
func lurkReddit(cfg *config.Config) {
if !cfg.Reddit.Enabled {
log.Info().Msg("reddit is disabled")
return
}
bot, err := reddit.NewBot(reddit.BotConfig{
Agent: cfg.Reddit.UserAgent(),
App: reddit.App{
ID: cfg.Reddit.ClientID,
Secret: cfg.Reddit.ClientSecret,
Username: cfg.Reddit.Username,
Password: cfg.Reddit.Password,
},
})
if err != nil {
log.Fatal().Err(err).Msg("")
return
}
lurker := &handler.Reddit{
Bot: bot,
Config: cfg,
}
for {
if err := lurker.Run(); err != nil {
log.Err(err).Msg("")
}
<-time.After(cfg.Backoff)
}
}
func lurkTwitter(cfg *config.Config) {
if !cfg.Twitter.Enabled {
log.Info().Msg("twitter is disabled")
return
}
twitterConfig := oauth1.NewConfig(cfg.Twitter.ConsumerKey, cfg.Twitter.ConsumerSecret)
token := oauth1.NewToken(cfg.Twitter.AccessToken, cfg.Twitter.AccessSecret)
httpClient := twitterConfig.Client(oauth1.NoContext, token)
client := twitter.NewClient(httpClient)
// Just to test if we have valid auth
_, _, err := client.Timelines.HomeTimeline(&twitter.HomeTimelineParams{
Count: 1,
})
if err != nil {
log.Fatal().Err(err).Msg("")
}
for _, filter := range cfg.Twitter.Filters {
stream, err := client.Streams.Filter(&twitter.StreamFilterParams{
Follow: filter.Follows,
Locations: filter.Locations,
StallWarnings: twitter.Bool(false),
Track: filter.Tracks,
})
if err != nil {
log.Fatal().Err(err).Msg("")
}
lurker := &handler.Twitter{
Filter: filter,
Stream: stream,
}
go func() {
for {
lurker.Run()
<-time.After(cfg.Backoff)
}
}()
}
}