-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·190 lines (159 loc) · 4.71 KB
/
main.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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"time"
"main.go/pkg"
"github.com/coreos/pkg/flagutil"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"github.com/joho/godotenv"
)
func LoadDotEnv() {
err := godotenv.Load()
if err != nil && !os.IsNotExist(err) {
log.Fatal("Error loading .env file")
}
}
func Tweet(content string) error {
LoadDotEnv()
flags := flag.NewFlagSet("user-auth", flag.ExitOnError)
consumerKey := flags.String("consumer-key", os.Getenv("API_KEY"), "Twitter Consumer Key")
consumerSecret := flags.String("consumer-secret", os.Getenv("API_SECRET_KEY"), "Twitter Consumer Secret")
accessToken := flags.String("access-token", os.Getenv("ACCESS_TOKEN"), "Twitter Access Token")
accessSecret := flags.String("access-secret", os.Getenv("ACCESS_TOKEN_SECRET"), "Twitter Access Secret")
flags.Parse(os.Args[1:])
flagutil.SetFlagsFromEnv(flags, "TWITTER")
if *consumerKey == "" || *consumerSecret == "" || *accessToken == "" || *accessSecret == "" {
// log.Fatal("Consumer key/secret and Access token/secret required")
return errors.New("Bad credentials")
}
config := oauth1.NewConfig(*consumerKey, *consumerSecret)
token := oauth1.NewToken(*accessToken, *accessSecret)
// OAuth1 http.Client will automatically authorize Requests
httpClient := config.Client(oauth1.NoContext, token)
// Twitter client
client := twitter.NewClient(httpClient)
// Verify Credentials
verifyParams := &twitter.AccountVerifyParams{
SkipStatus: twitter.Bool(true),
IncludeEmail: twitter.Bool(true),
}
user, _, err1 := client.Accounts.VerifyCredentials(verifyParams)
fmt.Printf("User's ACCOUNT:\n%+v\n", user)
if err1 != nil {
return err1
}
tweet, _, err2 := client.Statuses.Update(content, nil)
fmt.Printf("Posted Tweet\n%v\n", tweet)
return err2
}
func ReadFile(file_name string) (string, error) {
file, err := os.Open(file_name)
if err != nil {
// log.Fatal(err)
return "", err
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
b, _ := ioutil.ReadAll(file)
return string(b), nil
}
// TODO: this is hard to test, should be refactored
// GetFilenameFromDate(date) string
// ReadTodaysFilename(string) string
func ScheduledTweet() (scheduled []pkg.FileContent, err error) {
LoadDotEnv()
path := os.Getenv("FILE_PATH")
fmt.Println(path)
filesInDirectory, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
dateRegex, err := regexp.Compile(`(\d{4}-\w{3}-\d{2}|\w+ \d{2}, \d{4})\.(md|txt)`)
if err != nil {
return nil, err
}
for _, fileInfo := range filesInDirectory {
if fileInfo.IsDir() {
continue
}
if dateRegex.MatchString(fileInfo.Name()) {
if result := pkg.ReadFileComplex(path, fileInfo.Name(), true); result != nil {
scheduled = append(scheduled, *result)
}
continue
}
if result := pkg.ReadFileComplex(path, fileInfo.Name(), false); result != nil {
scheduled = append(scheduled, *result)
}
}
if len(scheduled) == 0 {
return nil, errors.New("no tweet files found")
}
return scheduled, nil
}
// TODO: either fix or remove queue system:
func IsQueueNameFormat(filename string) bool {
// if name fits the format q-#, return true
if string(filename[0]) == "q" && string(filename[1]) == "-" {
return true
}
return false
}
// TODO: either fix or remove queue system:
func QueuedTweet() (string, string, error) {
LoadDotEnv()
path := os.Getenv("FILE_PATH")
files, dir_read_error := ioutil.ReadDir(path)
if dir_read_error != nil {
return "", "", dir_read_error
}
filenames := []string{}
for _, f := range files {
if IsQueueNameFormat(f.Name()) {
filenames = append(filenames, f.Name())
}
}
sort.Strings(filenames)
if len(filenames) == 0 {
return "", "", errors.New("No queued files found")
}
queued_file_name := filenames[0]
queued_file_path := path + queued_file_name
content, read_error := ReadFile(queued_file_path)
if read_error != nil {
return "", "", read_error
}
current_time := time.Now()
formatted_time := current_time.Format("2006-Jan-02")
new_filename_path := path + "attempted_" + formatted_time + "_" + queued_file_name
rename_error := os.Rename(queued_file_path, new_filename_path)
if rename_error != nil {
return "", "", rename_error
}
// return the content of the file
return content, new_filename_path, nil
}
func main() {
scheduled_list, scheduled_tweet_error := ScheduledTweet()
if scheduled_tweet_error != nil {
fmt.Println("Error scheduling files:", scheduled_list)
fmt.Println("Error:", scheduled_tweet_error)
return
}
fmt.Println(pkg.SprintFileList(scheduled_list))
for _, scheduled := range scheduled_list {
post_failure := Tweet(scheduled.Content)
fmt.Println("Error posting to Twitter:", post_failure)
}
}