This repository has been archived on 2024-01-17. You can view files and clone it, but cannot push or open issues or pull requests.
dlbot4/instagram/instagram.go

73 lines
1.8 KiB
Go
Raw Normal View History

2023-01-04 16:21:00 +00:00
package instagram
2023-01-03 02:30:01 +00:00
import (
"encoding/json"
2023-01-03 02:45:13 +00:00
"errors"
2023-01-03 02:30:01 +00:00
"io"
"net/http"
"net/url"
"path"
)
2023-01-04 16:21:00 +00:00
type queryResponse struct {
2023-01-03 02:30:01 +00:00
Data struct {
2023-01-03 02:45:13 +00:00
ShortcodeMedia *struct {
Type string `json:"__typename"`
2023-01-03 02:30:01 +00:00
VideoUrl string `json:"video_url"`
Owner struct {
Username string `json:"username"`
} `json:"owner"`
EdgeMediaToCaption struct {
Edges []struct {
Node struct {
2023-01-03 02:45:25 +00:00
Text string `json:"text"`
2023-01-03 02:30:01 +00:00
} `json:"node"`
} `json:"edges"`
} `json:"edge_media_to_caption"`
} `json:"shortcode_media"`
} `json:"data"`
}
2023-01-04 16:21:00 +00:00
type lookupResponse struct {
2023-01-03 02:30:01 +00:00
VideoUrl string
Author string
Text string
}
2023-01-04 16:21:00 +00:00
func lookup(urlSrc string) (lookupResponse, error) {
2023-01-03 02:45:13 +00:00
urlSrcParsed, err := url.Parse(urlSrc)
if err != nil {
2023-01-04 16:21:00 +00:00
return lookupResponse{}, err
2023-01-03 02:45:13 +00:00
}
2023-01-03 02:30:01 +00:00
url, _ := url.Parse("https://www.instagram.com/graphql/query/?query_hash=b3055c01b4b222b8a47dc12b090e4e64")
query := url.Query()
2023-01-03 02:45:13 +00:00
query.Add("variables", "{\"shortcode\":\""+path.Base(urlSrcParsed.Path)+"\",\"child_comment_count\":3,\"fetch_comment_count\":40,\"parent_comment_count\":24,\"has_threaded_comments\":true}")
2023-01-03 02:30:01 +00:00
url.RawQuery = query.Encode()
resp, err := http.Get(url.String())
if err != nil {
2023-01-04 16:21:00 +00:00
return lookupResponse{}, err
2023-01-03 02:30:01 +00:00
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
2023-01-04 16:21:00 +00:00
var response queryResponse
2023-01-03 02:30:01 +00:00
err = json.Unmarshal(body, &response)
if err != nil {
2023-01-04 16:21:00 +00:00
return lookupResponse{}, err
2023-01-03 02:30:01 +00:00
}
2023-01-03 02:45:13 +00:00
if response.Data.ShortcodeMedia == nil {
2023-01-04 16:21:00 +00:00
return lookupResponse{}, errors.New("No encontré el video.")
2023-01-03 02:45:13 +00:00
}
if response.Data.ShortcodeMedia.Type != "GraphVideo" {
2023-01-04 16:21:00 +00:00
return lookupResponse{}, errors.New("Esto no es un video.")
2023-01-03 02:45:13 +00:00
}
2023-01-04 16:21:00 +00:00
return lookupResponse{
2023-01-03 02:30:01 +00:00
VideoUrl: response.Data.ShortcodeMedia.VideoUrl,
Author: response.Data.ShortcodeMedia.Owner.Username,
Text: response.Data.ShortcodeMedia.EdgeMediaToCaption.Edges[0].Node.Text,
}, nil
}