forked from tducasse/go-instabot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
252 lines (205 loc) · 6.81 KB
/
util.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"flag"
"fmt"
"io"
"log"
"math/rand"
"net/smtp"
"os"
"strings"
"time"
"github.com/spf13/viper"
)
// Whether we are in development mode or not
var dev *bool
// Whether we want an email to be sent when the script ends / crashes
var startmail *bool
// Whether we want an email to be sent when the script ends / crashes
var nomail *bool
// Whether we want to launch the unfollow mode
var unfollow *bool
// Acut
var run *bool
// An image will be liked if the poster has more followers than likeLowerLimit, and less than likeUpperLimit
var likeLowerLimit int
var likeUpperLimit int
// A user will be followed if he has more followers than followLowerLimit, and less than followUpperLimit
// Needs to be a subset of the like interval
var followLowerLimit int
var followUpperLimit int
// An image will be commented if the poster has more followers than commentLowerLimit, and less than commentUpperLimit
// Needs to be a subset of the like interval
var commentLowerLimit int
var commentUpperLimit int
// Hashtags list. Do not put the '#' in the config file
var tagsList map[string]interface{}
// Limits for the current hashtag
var limits map[string]int
// Comments list
var commentsList []string
// Line is a struct to store one line of the report
type line struct {
Tag, Action string
}
// Report that will be sent at the end of the script
var report map[line]int
// Counters that will be incremented while we like, comment, and follow
var numFollowed int
var numLiked int
var numAlreadyLiked int
var numCommented int
// Will hold the tag value
var tag string
// check will log.Fatal if err is an error
func check(err error) {
if err != nil {
send(fmt.Sprintf("A fatal error occurred:\n%s", err), false)
log.Fatal("ERROR:", err)
}
}
// Parses the options given to the script
func parseOptions() {
run = flag.Bool("run", false, "Use this option to follow, like and comment")
unfollow = flag.Bool("sync", false, "Use this option to unfollow those who are not following back")
startmail = flag.Bool("startmail", false, "Use this option to enable an email notifciation when script begins : seful when in crontab")
nomail = flag.Bool("nomail", false, "Use this option to disable the email notifications")
dev = flag.Bool("dev", false, "Use this option to use the script in development mode : nothing will be done for real")
logs := flag.Bool("logs", false, "Use this option to enable the logfile")
flag.Parse()
// -logs enables the log file
if *logs {
// Opens a log file
t := time.Now()
logFile, err := os.OpenFile("instabot-"+t.Format("2006-01-02-15-04-05")+".log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
check(err)
defer logFile.Close()
// Duplicates the writer to stdout and logFile
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)
}
}
// Gets the conf in the config file
func getConfig() {
gopath := os.Getenv("GOPATH")
dir := gopath + "/src/github.com/mcrwfrd/go-instabot"
folder := dir + "/config"
if *dev {
folder = dir + "/local"
}
viper.SetConfigFile(folder + "/config.json")
// Reads the config file
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file, %s", err)
}
// Check enviroment
viper.SetEnvPrefix("instabot")
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv()
// Confirms which config file is used
log.Printf("Using config: %s\n\n", viper.ConfigFileUsed())
likeLowerLimit = viper.GetInt("limits.like.min")
likeUpperLimit = viper.GetInt("limits.like.max")
followLowerLimit = viper.GetInt("limits.follow.min")
followUpperLimit = viper.GetInt("limits.follow.max")
commentLowerLimit = viper.GetInt("limits.comment.min")
commentUpperLimit = viper.GetInt("limits.comment.max")
tagsList = viper.GetStringMap("tags")
commentsList = viper.GetStringSlice("comments")
type Report struct {
Tag, Action string
}
report = make(map[line]int)
}
// Sends an email. Check out the "mail" section of the "config.json" file.
func send(body string, success bool) {
if !*nomail {
from := viper.GetString("user.mail.from")
pass := viper.GetString("user.mail.password")
to := viper.GetString("user.mail.to")
status := func() string {
if success {
return "Success!"
}
return "Failure!"
}()
msg := "From: " + from + "\n" +
"To: " + to + "\n" +
"Subject:" + status + " go-instabot\n\n" +
body
err := smtp.SendMail(viper.GetString("user.mail.smtp"),
smtp.PlainAuth("", from, pass, viper.GetString("user.mail.server")),
from, []string{to}, []byte(msg))
if err != nil {
log.Printf("smtp error: %s", err)
return
}
log.Print("sent")
}
}
// Sends an email at the beginning of the script to notify that it has begun. Used when job is in crontab
func sendStartMail() {
if *startmail {
log.Print("sending script initialization")
send("The instabot is now running", true)
}
}
// Retries the same function [function], a certain number of times (maxAttempts).
// It is exponential : the 1st time it will be (sleep), the 2nd time, (sleep) x 2, the 3rd time, (sleep) x 3, etc.
// If this function fails to recover after an error, it will send an email to the address in the config file.
func retry(maxAttempts int, sleep time.Duration, function func() error) (err error) {
for currentAttempt := 0; currentAttempt < maxAttempts; currentAttempt++ {
err = function()
if err == nil {
return
}
for i := 0; i <= currentAttempt; i++ {
time.Sleep(sleep)
}
log.Println("Retrying after error:", err)
}
send(fmt.Sprintf("The script has stopped due to an unrecoverable error :\n%s", err), false)
return fmt.Errorf("After %d attempts, last error: %s", maxAttempts, err)
}
// Builds the line for the report and prints it
func buildLine() {
reportTag := ""
for index, element := range report {
if index.Tag == tag {
reportTag += fmt.Sprintf("%s %d/%d - ", index.Action, element, limits[index.Action])
}
}
// Prints the report line on the screen / in the log file
if reportTag != "" {
log.Println(strings.TrimSuffix(reportTag, " - "))
}
}
// Builds the report prints it and sends it
func buildReport() {
reportAsString := ""
for index, element := range report {
var times string
if element == 1 {
times = "time"
} else {
times = "times"
}
if index.Action == "like" {
reportAsString += fmt.Sprintf("#%s has been liked %d %s\n", index.Tag, element, times)
} else {
reportAsString += fmt.Sprintf("#%s has been %sed %d %s\n", index.Tag, index.Action, element, times)
}
}
// Displays the report on the screen / log file
fmt.Println(reportAsString)
// Sends the report to the email in the config file, if the option is enabled
send(reportAsString, true)
}
func waitRandomInterval(min int, max int) {
rand.Seed(time.Now().Unix())
wait := rand.Intn(max-min) + min
log.Printf("Waiting %d seconds...\n\n", wait)
time.Sleep(time.Duration(wait) * time.Second)
return
}