forked from tducasse/go-instabot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsta.go
320 lines (272 loc) · 7.66 KB
/
insta.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package main
import (
"bufio"
"crypto/md5"
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"strings"
"time"
"github.com/spf13/viper"
"github.com/tducasse/goinsta"
"github.com/tducasse/goinsta/response"
"github.com/tducasse/goinsta/store"
)
// Insta is a goinsta.Instagram instance
var insta *goinsta.Instagram
// login will try to reload a previous session, and will create a new one if it can't
func login() {
err := reloadSession()
if err != nil {
createAndSaveSession()
}
}
func syncFollowers() {
following, err := insta.SelfTotalUserFollowing()
check(err)
followers, err := insta.SelfTotalUserFollowers()
check(err)
var users []response.User
for _, user := range following.Users {
if !contains(followers.Users, user) {
users = append(users, user)
}
}
fmt.Printf("\n%d users are not following you back!\n", len(users))
answer := getInput("Do you want to unfollow these users? [yN]")
if answer != "y" {
fmt.Println("Not unfollowing.")
os.Exit(0)
}
for _, user := range users {
fmt.Printf("Unfollowing %s\n", user.Username)
if !*dev {
insta.UnFollow(user.ID)
}
time.Sleep(7 * time.Second)
}
}
func getInput(text string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Printf(text)
input, err := reader.ReadString('\n')
check(err)
return strings.TrimSpace(input)
}
// Checks if the user is in the slice
func contains(slice []response.User, user response.User) bool {
for _, currentUser := range slice {
if currentUser == user {
return true
}
}
return false
}
var sessionFileName string
func getSessionFile(username string) string {
if sessionFileName == "" {
sessionFileName = "sessions/" + genSessionKey([]byte(username))
}
return sessionFileName
}
var keyFileName string
func getKeyFile(username string) string {
if keyFileName == "" {
keyFileName = "keys/" + genSessionKey([]byte(username))
}
return keyFileName
}
// Logins and saves the session
func createAndSaveSession() {
username := viper.GetString("user.instagram.username")
insta = goinsta.New(username, viper.GetString("user.instagram.password"))
err := insta.Login()
check(err)
key := createKey()
bytes, err := store.Export(insta, key)
check(err)
err = ioutil.WriteFile(getSessionFile(username), bytes, 0644)
check(err)
log.Println("Created and saved the session")
}
// Generate the session key
func genSessionKey(data []byte) string {
return fmt.Sprintf("%x", md5.Sum(data))
}
// reloadSession will attempt to recover a previous session
func reloadSession() error {
username := viper.GetString("user.instagram.username")
sessionFile := getSessionFile(username)
if _, err := os.Stat(sessionFile); os.IsNotExist(err) {
return errors.New("no session found")
}
session, err := ioutil.ReadFile(sessionFile)
check(err)
log.Println("A session file exists")
key, err := ioutil.ReadFile(getKeyFile(username))
check(err)
insta, err = store.Import(session, key)
if err != nil {
return errors.New("couldn't recover the session")
}
log.Println("Successfully logged in")
return nil
}
// createKey creates a key and saves it to file
func createKey() []byte {
key := make([]byte, 32)
_, err := rand.Read(key)
check(err)
err = ioutil.WriteFile(getKeyFile(viper.GetString("user.instagram.username")), key, 0644)
check(err)
log.Println("Created and saved the key")
return key
}
// Go through all the tags in the list
func loopTags() {
for tag = range tagsList {
limitsConf := viper.GetStringMap("tags." + tag)
// Some converting
limits = map[string]int{
"follow": int(limitsConf["follow"].(float64)),
"like": int(limitsConf["like"].(float64)),
"comment": int(limitsConf["comment"].(float64)),
}
// What we did so far
numFollowed = 0
numLiked = 0
numCommented = 0
browse()
}
buildReport()
}
// Browses the page for a certain tag, until we reach the limits
func browse() {
var i = 0
for numFollowed < limits["follow"] || numLiked < limits["like"] || numCommented < limits["comment"] {
log.Println("Fetching the list of images for #" + tag + "\n")
i++
// Getting all the pictures we can on the first page
// Instagram will return a 500 sometimes, so we will retry 10 times.
// Check retry() for more info.
var images response.TagFeedsResponse
err := retry(10, 30*time.Second, func() (err error) {
images, err = insta.TagFeed(tag)
return
})
check(err)
goThrough(images)
if viper.IsSet("limits.maxRetry") && i > viper.GetInt("limits.maxRetry") {
log.Println("Currently not enough images for this tag to achieve goals")
break
}
}
}
// Goes through all the images for a certain tag
func goThrough(images response.TagFeedsResponse) {
var i = 1
for _, image := range images.FeedsResponse.Items {
// Exiting the loop if there is nothing left to do
if numFollowed >= limits["follow"] && numLiked >= limits["like"] && numCommented >= limits["comment"] {
break
}
// Skip our own images
if image.User.Username == viper.GetString("user.instagram.username") {
continue
}
// Check if we should fetch new images for tag
if i >= limits["follow"] && i >= limits["like"] && i >= limits["comment"] {
break
}
// Getting the user info
// Instagram will return a 500 sometimes, so we will retry 10 times.
// Check retry() for more info.
var posterInfo response.GetUsernameResponse
err := retry(10, 30*time.Second, func() (err error) {
posterInfo, err = insta.GetUserByUsername(image.User.Username)
return
})
check(err)
poster := posterInfo.User
followerCount := poster.FollowerCount
buildLine()
log.Println("Checking followers for " + poster.Username + " - for #" + tag)
log.Printf("%s has %d followers\n", poster.Username, followerCount)
i++
// Will only follow and comment if we like the picture
like := followerCount > likeLowerLimit && followerCount < likeUpperLimit && numLiked < limits["like"]
follow := followerCount > followLowerLimit && followerCount < followUpperLimit && numFollowed < limits["follow"] && like
comment := followerCount > commentLowerLimit && followerCount < commentUpperLimit && numCommented < limits["comment"] && like
// Checking if we are already following current user and skipping if we do
skip := false
following, err := insta.SelfTotalUserFollowing()
check(err)
for _, user := range following.Users {
if user.Username == poster.Username {
skip = true
break
}
}
// Like, then comment/follow
if !skip {
if like {
likeImage(image)
if follow {
followUser(posterInfo)
}
if comment {
commentImage(image)
}
}
}
log.Printf("%s done\n\n", poster.Username)
// This is to avoid the temporary ban by Instagram
time.Sleep(25 * time.Second)
}
}
// Likes an image, if not liked already
func likeImage(image response.MediaItemResponse) {
log.Println("Liking the picture")
if !image.HasLiked {
if !*dev {
insta.Like(image.ID)
}
log.Println("Liked")
numLiked++
report[line{tag, "like"}]++
} else {
log.Println("Image already liked")
}
}
// Comments an image
func commentImage(image response.MediaItemResponse) {
rand.Seed(time.Now().Unix())
text := commentsList[rand.Intn(len(commentsList))]
if !*dev {
insta.Comment(image.ID, text)
}
log.Println("Commented " + text)
numCommented++
report[line{tag, "comment"}]++
}
// Follows a user, if not following already
func followUser(userInfo response.GetUsernameResponse) {
user := userInfo.User
log.Printf("Following %s\n", user.Username)
userFriendShip, err := insta.UserFriendShip(user.ID)
check(err)
// If not following already
if !userFriendShip.Following {
if !*dev {
insta.Follow(user.ID)
}
log.Println("Followed")
numFollowed++
report[line{tag, "follow"}]++
} else {
log.Println("Already following " + user.Username)
}
}