-
Notifications
You must be signed in to change notification settings - Fork 2
/
instabot.go
187 lines (154 loc) · 4.2 KB
/
instabot.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
package main
import (
"encoding/json"
"fmt"
"github.com/imroc/req/v3"
"github.com/jmoiron/jsonq"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"time"
)
const (
PHOTO = 1
VIDEO = 2
)
var baseUrl = "https://www.instagram.com"
var client *req.Client = req.C()
func runBot(watchlist map[string]string) {
fmt.Println("\n[*] Bot Started!\n")
// get ids from usernames
for username := range watchlist {
id := getIdFromUser(username)
if id == "" {
fmt.Printf("\n[-] Unable to find the ID for user: " + username)
continue
}
watchlist[username] = id
}
for {
// start monitoring
scanUsers(watchlist)
time.Sleep(60 * time.Second)
}
}
func scanUsers(watchlist map[string]string) {
for username := range watchlist {
time.Sleep(30 * time.Second)
mediaUrl, mediaType := getLastReel(username, watchlist[username])
if mediaUrl == "" {
continue
}
if mediaType == PHOTO {
sendPhoto(mediaUrl, username)
} else {
sendVideo(mediaUrl, username)
}
fmt.Printf("[+] [%s] New instagam story sent!\n", username)
}
}
func getIdFromUser(user string) string {
// Realizar la solicitud HTTP para obtener los datos del usuario
resp, err := client.R().
Get("/web/search/topsearch/?context=blended&query=" + user + "&rank_token=0.3953592318270893&count=1")
if err != nil {
log.Fatalf("Error al realizar la solicitud HTTP: %v", err)
}
defer resp.Body.Close()
// Leer y decodificar la respuesta JSON
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatalf("Error al decodificar la respuesta JSON: %v", err)
}
// Verificar si la respuesta contiene la estructura esperada
users, ok := data["users"].([]interface{})
if !ok || len(users) == 0 {
log.Fatalf("No se encontró el campo 'users' en la respuesta JSON")
}
userObj, ok := users[0].(map[string]interface{})
if !ok {
log.Fatalf("No se pudo convertir 'users[0]' a un objeto map[string]interface{}")
}
userNode, ok := userObj["user"].(map[string]interface{})
if !ok {
log.Fatalf("No se pudo convertir 'user' a un objeto map[string]interface{}")
}
id, ok := userNode["pk"].(string)
if !ok {
log.Fatalf("No se encontró la clave 'pk' o no es una cadena")
}
return id
}
func parseJson(jsonStr string, username string) (mediaUrl string, mediaType int) {
data := map[string]interface{}{}
dec := json.NewDecoder(strings.NewReader(jsonStr))
dec.Decode(&data)
jq := jsonq.NewQuery(data)
// get last stories
lastReel, err := jq.Int("reels_media", "0", "latest_reel_media")
if err != nil {
return "", 0
}
// check if I have already downloaded it
if !IsStoryNew(username, int64(lastReel)) {
return "", 0
}
items, _ := jq.Array("reels_media", "0", "items")
itemsCount := len(items)
lastItem := fmt.Sprintf("%v", items[itemsCount-1])
// check if it's a video or a photo
if strings.Contains(lastItem, "media_type:1") {
mediaType = PHOTO
mediaUrl = strings.Split(lastItem, "image_versions2")[1]
} else {
mediaType = VIDEO
mediaUrl = strings.Split(lastItem, "video_versions")[1]
}
mediaUrl = strings.Split(mediaUrl, "url:")[1]
mediaUrl = strings.Split(mediaUrl, " width")[0]
mediaUrl = strings.ReplaceAll(mediaUrl, "\\u0026", "&")
return mediaUrl, mediaType
}
func getLastReel(username string, id string) (string, int) {
resp, err := client.R().Get("/api/v1/feed/reels_media/?reel_ids=" + id)
if err != nil {
log.Fatal(err)
}
content, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
return parseJson(string(content), username)
}
func setupHttpClient(sessionID string, appID string, userAgent string) {
// make cookieJar
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatalf("Got error while creating cookie jar %s", err.Error())
}
// set cookie in cookieJar
urlObj, _ := url.Parse(baseUrl)
jar.SetCookies(urlObj, []*http.Cookie{
{
Name: "sessionid",
Value: sessionID,
Path: "/",
Domain: "www.instagram.com",
},
{
Name: "ds_user_id",
Value: strings.Split(sessionID, "%")[0],
Path: "/",
Domain: "www.instagram.com",
},
})
// make client http
client = req.C().
SetCommonHeaderNonCanonical("x-ig-app-id", appID).
SetUserAgent(userAgent).
SetCookieJar(jar).
SetBaseURL(baseUrl)
}