~alexwennerberg/twitterbots-go

twitterbots-go/main.go -rw-r--r-- 2.1 KiB
58d07a1aalex wennerberg merge commit a month ago
                                                                                
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main

import (
	"encoding/json"
	"flag"
	"github.com/dghubble/go-twitter/twitter"
	"github.com/dghubble/oauth1"
	"log"
	"math/rand"
	"os"
	"time"
)

func main() {
	rand.Seed(time.Now().Unix())
	fileName := flag.String("config", "", "config filepath")
	mode := flag.String("mode", "", "mode, either souls or lacroix")
	noop := flag.Bool("noop", false, "don't post tweet, just echo")
	flag.Parse()
	config, err := loadConfig(fileName)
	if err != nil {
		panic(err)
	}
	client, err := getTwitterClient(config)
	var tweet string
	if *mode == "souls" {
		tweet = generateSoulsTweet()
	} else if *mode == "lacroix" {
		tweet = generateLacroixTweet()
	} else {
		panic("Invalid mode")
		// do nothing
	}
	if err != nil {
		panic(err)
	}
	if *noop {
		log.Println(tweet)
		return
	}
	postedTweet, _, err := client.Statuses.Update(tweet, nil)
	if err != nil {
		panic(err)
	}
	log.Printf("@%s posted update \"%s\"\n", postedTweet.User.ScreenName, tweet)
}

func generateLacroixTweet() string {
	allFlavors := flavors()
	result := allFlavors[rand.Intn(len(allFlavors))] + " flavored La Croix"
	if rand.Intn(5) == 1 {
		// sometimes add naturally essenced
		result = "Naturally Essenced " + result
	}
	return result
}

func generateSoulsTweet() string {
	phrases := allPhrases()
	result := phrases[rand.Intn(len(phrases))]
	return result
}

type TwitterCreds struct {
	ConsumerKey    string
	ConsumerSecret string
	AccessToken    string
	AccessSecret   string
}

func loadConfig(configFilename *string) (*TwitterCreds, error) {
	file, err := os.Open(*configFilename)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	configuration := TwitterCreds{}
	err = decoder.Decode(&configuration)
	if err != nil {
		return nil, err
	}
	return &configuration, nil
}

func getTwitterClient(configuration *TwitterCreds) (*twitter.Client, error) {
	config := oauth1.NewConfig(configuration.ConsumerKey, configuration.ConsumerSecret)
	token := oauth1.NewToken(configuration.AccessToken, configuration.AccessSecret)
	httpClient := config.Client(oauth1.NoContext, token)
	twitterClient := twitter.NewClient(httpClient)
	return twitterClient, nil
}