jlobos / instagram-web-api Goto Github PK
View Code? Open in Web Editor NEW🤳 Instagram Private Web API client for Node
Home Page: https://npmjs.com/instagram-web-api
License: MIT License
🤳 Instagram Private Web API client for Node
Home Page: https://npmjs.com/instagram-web-api
License: MIT License
node -v 8.11.3
Code:
const Instagram = require('instagram-web-api')
const client = new Instagram({ username: '', password: '' })
;(async () => {
await client.login()
const profile = await client.getProfile()
console.log(profile)
})()
Error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined
at request.then.res (/Users/user/Desktop/prjct/htdocs/app/node_modules/instagram-web-api/lib/index.js:55:46)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:9012) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9012) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This api send DM ??? there is an exemple ? thxxx
Hey there. Thanks a ton for this straightforward API. Just a heads up. I'm getting a 500 error on the profile update endpoint.
Example:
const testLocationId = '234604984'
const feed = await client.getMediaFeedByLocation({ locationId: testLocationId })
feed is undefined
I'm using v1.1.0, this was working a couple of days ago, maybe this was a change on Instagram?
The URL https://www.instagram.com/explore/locations/234604984/
is also valid
New header of authentication
Would love to know!
When attempting to use the updateProfile method, I get the following error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): StatusCodeError: 400 - {"message":{"errors":["You need an email or confirmed phone number."]},"status":"fail"}
Anybody know how to fix?
the old
getHome() { return this.request('/?__a=1').then(data => data.graphql.user) }
the new
getHome(variables) { return this.request('/graphql/query/', { qs: { query_hash: 'your_query_id', variables: JSON.stringify(variables) } }) .then(data => data) }
Hi
Can i get ??
comments: Total number of comments
description: User description
email: User email
engagement: (((comments + likes) / posts) / followers)
followers: Total number of followers
following: Total number of following
frequency: Returns a ms-to object with a post frequency between the first and last one
fullName: User full name
id: User id
likes: Total number of likes
posts: Total number of posts
url: User Instagram url
username: Same username as supplied
website: User website
there is an exemple ?
client.getProfile() only returns
name: The full name. Default is
email: The email of account. Default is
username: The username of account. Default is client.credentials.username
phoneNumber: The Phone Number. Default is
gender: Number 1 male, 2 female and 3 not specified
biography: The Bio. Default is
website: The Website. Default is
similarAccountSuggestions: Boolean Include your account when recommending similar accounts people might want to follow. Default is true
(node:2635) UnhandledPromiseRejectionWarning: StatusCodeError: 400 - {"message":"checkpoint_required","checkpoint_url":"/challenge/8364541766/xYkNMOwdsP/","lock":false,"status":"fail"}
I got this error when I try to login. Did you get this error before ?
Would love to know!
Hi
I use getUserByUsername method, But this method and anothers methods cant pagination posts.
const instagram = await client.getUserByUsername({ username: 'instagram' })
Is there a way to read other pages?
node -v 8.11.3
Code:
const Instagram = require('instagram-web-api')
const client = new Instagram({ username: '', password: '' })
;(async () => {
await client.login()
const profile = await client.getProfile()
console.log(profile)
})()
Error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined
at request.then.res (/Users/user/Desktop/prjct/htdocs/app/node_modules/instagram-web-api/lib/index.js:55:46)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:9012) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9012) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Thank you very much your api is super!
I would very much like to see support getting subscribers
But not only their own but also any other person like
let followers = getFollowers (userId);
console.log (followers);
output:
[
Lucas123,
anotherPerson,
MeganFox,
Lena23
]
Hi
How can I get stories highlights ?
It looks like async functions are used without await, for example:
https://github.com/jlobos/instagram-web-api/blob/master/lib/index.js#L358
async getMediaFeedByHashtag({ hashtag }) {
return this.request(`/explore/tags/${hashtag}/?__a=1`).then(
data => data.graphql.hashtag
)
}
This means that if this.request
throws an error, it will not be caught.
I suggest proper use of async functions for all methods:
async getMediaFeedByHashtag({ hashtag }) {
const data = await this.request(`/explore/tags/${hashtag}/?__a=1`)
return data.graphql.hashtag
}
There should be support to be able to access the feed/reels_tray/
GET endpoint in the Instagram API
web browser is sending a 12 character string for
X-Instagram-AJAX instead of a constant 1 to
follow requests. anyone know how this string is built?
:authority: www.instagram.com
:method: POST
:path: /web/friendships/1313258832/follow/
:scheme: https
accept: /
accept-encoding: gzip, deflate, br
accept-language: ja,en-US;q=0.9,en;q=0.8
cache-control: no-cache
content-length: 0
content-type: application/x-www-form-urlencoded
cookie: ****
origin: https://www.instagram.com
pragma: no-cache
referer: https://www.instagram.com/p/BjDyf5DB6wo/?tagged=%E6%97%85%E8%A1%8C
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
x-csrftoken: lImObEnNSMYXK06xqtSoP2MZ1O7QsFqz
x-instagram-ajax: 555a07dee140
x-requested-with: XMLHttpRequest
I can't fetch user's media feed by specifing user id (pk)?
[edit: delete]
Hi,
When I try to add a comment, no matter which mediaId I use, I always get an error with following content: "StatusCodeError: 400 - {"message":"Sorry, this media has been deleted.","status":"fail"}". What can be the issue? Did anybody else experienced same error?
Thanks.
I Use getPhotosByUsername by a single Js,it's ok. but when i use it in the express,it returns 403.why?
this is my express code
app.get('/api/ins/morepic', async(req, res) => {
let username = req.query.username
let client = new Instagram({}, { proxy: "http://127.0.0.1:1080" })
let photos = await client.getPhotosByUsername(username)
res.json(photos)
})
comment not deleting, when I use
let result = await client.deleteComment({ mediaId: media.graphql.shortcode_media.id, commentId: "17910681670083819" })
console.log(result)
response is { status: 'ok' }
, but comment is on it's place
When I try to delete not my comment response is {"message":"You cannot delete this comment","status":"fail"}
, as expected
Proposed by @ibrunotome in https://docs.google.com/spreadsheets/d/1c5NITqvgL-4At54iL5k-KKx22BnBKUVF-wiN6FJDpHk/edit?disco=AAAABioFlso
Hi, would be nice the mapping of logging_client_events too, this events are REALLY necessary to prevent that Instagram flag the account.
https://graph.instagram.com/logging_client_events
I try to simply log in as
const Instagram = require('instagram-web-api');
const client = new Instagram({ username: 'XX', password: 'YY' });
(async () => {
await client.login();
const profile = await client.getProfile();
})();
but it returns the error:
TypeError: Cannot read property 'map' of undefined
at request.then.res (/home/kimia/node_modules/instagram-web-api/lib/index.js:55:46)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
Did someone found how to take all followers/followings with new limits to request?(first=50)
the getUserByUsername
endpoint still seems to require authentication for public profiles.
The following code should work but instead I get StatusCodeError: 403 - undefined
:
const Instagram = require('instagram-web-api');
const client = new Instagram({ username: 'instagram', password: '' });
(async () => {
// await client.login();
// const profile = await client.getProfile();
try {
const p39 = await client.getUserByUsername({ username: 'instagram' });
console.log(p39);
} catch(e){
console.error(e);
}
})();
Has anyone actually got this to work without authenticating?
I have problem with updateChallenge
My code:
static async login(username, password) {
const cookieStore = new FileCookieStore(`/path_here/${username}.json`);
const client = new Instagram({ username, password, cookieStore });
try {
await client.login();
const profile = await client.getProfile();
console.log(profile);
}
catch (e) {
this.challenges[username] = e.error.checkpoint_url;
let challengeUrl = e.error.checkpoint_url;
await client.updateChallenge({challengeUrl, choice: 1}); // 1 is email
return {result: false};
}
}
After login(username, password)
I get an email with code
Now i can try update challenge:
static async challenge(username, password, code){
const cookieStore = new FileCookieStore(`/path_here/${username}.json`);
const client = new Instagram({ username, password, cookieStore });
try {
let challengeUrl = this.challenges[username];
console.log(challengeUrl); // here link like /challenge/1623843519/Sz6xLG84Th/
console.log("code " + code); // here code from email like 604861
await client.updateChallenge({ challengeUrl, securityCode: code });
} catch(e){
console.log(e.error);
}
}
When i call challenge(username, password, code)
i getting error with HTML:
<title>
Page Not Found • Instagram
</title>
(looks like default 404 page)
Also i can open link "instagram.com" + challengeUrl and it its valid page with code form
What i doing wrong?
P.S. Sorry for bad English
Most endpoints don't return the needed data directly, but in a nested way.
For example:
const response = await client.getProfile()
const data = response.form_data
const response = await client.getMediaFeedByHashtag({
hashtag: 'instagram'
})
const data = response.graphql.hashtag
Should the module deconstruct those responses, so it yields the desired result directly?
This is a design choice which leads to breaking changes, but I think for most use cases this would be a welcome change.
When trying to login using client.login()
I get an http 403 error with an html page saying:
This page could not be loaded. If you have cookies disabled in your browser, or you are browsing in Private Mode, please try enabling cookies or turning off Private Mode, and then retrying your action.
My code was working fine until yesterday.
It seems this has happened with the official API before https://stackoverflow.com/questions/50530404/bug-with-instagram-api-login-this-page-could-not-be-loaded
I think it isn't the best idea to use the same User Agent for every instance.
We could improve this behaviour by generating a custom userAgent based on the username.
Support for all the main functions of Instagram Web
but there is no reporting function and instagram web has reporting function
Request:
client.login().then(console.log)
Response from instagram:
{ authenticated: false, user: true, status: 'ok' }
But not signed in
Why?
The Instagram website requires users to close a warning banner before any cookies are set. This policy means that the CSRF cookie is not set on the initial http request.
Closing the cookie banner creates a cookie ig_cb=1
and the server will only send CSRF cookie(s) if this is present.
To fix this, the constructor for the Instagram
class should add this cookie to whatever cookie store is being used, so that it is included in all requests, particularly the one to get the CSRF cookie.
cookies.json:
{
"www.instagram.com" : {
"/" : {
"" : {
"hostOnly" : true,
"domain" : "www.instagram.com",
"value" : "ig_cb=1",
"pathIsDefault" : true,
"path" : "/"
}
}
}
}
client.login()
errors on the first run, however it still saves the cookies, and runs fine on the second attempt
try {
await client.login()
} catch(e) {
await client.login()
}
Hi ! Now is limite 50, how get more ?
When I want to log in, this err is always display. some code:
import React, {Fragment} from 'react';
import ReactDOM from 'react-dom';
const Instagram = require('instagram-web-api');
class Login extends React.Component{
constructor(props){
super(props);
this.login = this.login.bind(this);
}
login(){
const userName = document.getElementById('name').value;
const userPassword = document.getElementById('pass').value;
const client = new Instagram({username: 'big_2rch', password: 'mrx1337'});
client
.login()
.then(() => {
client
.getProfile()
.then(console.log)
})
}
render(){
return (
<Fragment>
<input type='text' id='name' />
<input type='password' id='pass' />
<button onClick={this.login}>Log in</button>
</Fragment>
);
}
}
ReactDOM.render(
<Login/>,
document.getElementById('root')
);
I just noticed Instagram made some changes to the graphql availability.
It seems that followers/following "endpoints" return error on any requests with "first" parameter greater than 50. So by now we should make (followersCount+followingCount)/50 requests to get the whole lists.
When attempting to do so, IG responds with:
{"message":"execution failure","errors":[{"message":"Something is wrong. Please check your input and try again.","locations":[]}],"data":{"user":null},"status":"fail"}
Currently it is only possible to supply a static cookie at initialization. Support for though-cookie
stores would enable more possibilities:
const client = new Instagram({
username: 'some-user',
password: 'some-pass '
});
client
.login()
.then(async () => {
let media = await client.getMediaByShortcode({
shortcode: 'BN8DTVJg1kS'
})
console.log(JSON.stringify(media.edge_media_preview_like));
/* output
{
"count": 67,
"edges": [{
"node": {
"id": "1230362723",
"profile_pic_url": "https://scontent-mrs1-1.cdninstagram.com/vp/9f8e99e506c766b0267135f467c7d390/5BDFB13E/t51.2885-19/11189695_432232966950576_2123846447_a.jpg",
"username": "monta_snuggles"
}
}, {
"node": {
"id": "4261111824",
"profile_pic_url": "https://scontent-mrs1-1.cdninstagram.com/vp/84ee6d4cb727ad8189aff1e62fd4f3a4/5BE5C194/t51.2885-19/s150x150/31556620_175666989761266_2349846087327547392_n.jpg",
"username": "funny_vids_54"
}
}, {
"node": {
"id": "3036650979",
"profile_pic_url": "https://scontent-mrs1-1.cdninstagram.com/vp/81147c56fde08d0dac759a696022e9d9/5BD0BADB/t51.2885-19/s150x150/28152590_149544409043434_3151792815944499200_n.jpg",
"username": "aungaungalverechanel"
}
}]
} */
})
the media has 67 likes but I only get the first 3 of them any idea how get all of them
I encounter a 405 - undefined
error when calling client.logout
:
{ StatusCodeError: 405 - undefined
at new StatusCodeError (/Users/chunheisiu/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/Users/chunheisiu/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/Users/chunheisiu/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/Users/chunheisiu/node_modules/request/request.js:185:22)
at Request.emit (events.js:189:13)
at Request.<anonymous> (/Users/chunheisiu/node_modules/request/request.js:1161:10)
at Request.emit (events.js:189:13)
at IncomingMessage.<anonymous> (/Users/chunheisiu/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:277:13)
at IncomingMessage.emit (events.js:194:15)
name: 'StatusCodeError',
statusCode: 405,
message: '405 - undefined',
error: undefined,
options: { ... },
response: { ... }
}
Am I calling the method wrong?
Hi! I'm trying to wrap my head around the challenge but can't seem to figure it out.
When trying to login, I'm getting
StatusCodeError: 400 - {"message":"checkpoint_required","checkpoint_url":"/challenge/ABCABC/123123/","lock":false,"status":"fail"}
which means that a challenge needs a response.
I've tried browsing to instagram.com/challenge/ABCABC/123123
(in my normal web browser) and completing the challenge, but on the next attempt to login programmatically, I'm getting a new challenge, and so it continues.
I've also tried
getChallenge
, which responds with{ challengeType: 'SelectVerificationMethodForm',
errors: [],
experiments: {},
extraData:
{ __typename: 'GraphChallengePage',
content: [ [Object], [Object], [Object], [Object] ] },
fields:
{ choice: '1',
fb_access_token: 'None',
big_blue_token: 'None',
google_oauth_token: 'None',
email: '*********@gmail.com',
phone_number: '+** ** *** ** **' },
navigation:
{ forward: '/challenge/ABCABC/123123/',
replay: '/challenge/replay/ABCABC/123123/',
dismiss: 'https://www.instagram.com/' },
privacyPolicyUrl: '/about/legal/privacy/',
type: 'CHALLENGE' }
client.updateChallenge({ challengeUrl: "/challenge/ABCABC/123123/", choice: 1 })
But that updateChallenge
is returning HTML content(!), which says
This page could not be loaded. If you have cookies disabled in your browser, or you are browsing in Private Mode, please try enabling cookies or turning off Private Mode, and then retrying your action
So how is the challenge-response flow supposed to work?
It seems like Instagram ist testing a new endpoint instead of /?__a=1
. My personal account returns the expected result, my test account on the other hand returns { "graphql": null }
.
After some investigation I think they are switching to the GraphQL endpoint for this task.
Not sure what to do at this point since it isn't really consistent yet. I will just put this out here for now.
I don't find method to take id from logged user, so i can't user a half of methods without this
Package from npm fails on the requests changed after publishing but fixed in master
List of web API Endpoints and state of development ✨
https://docs.google.com/spreadsheets/d/1c5NITqvgL-4At54iL5k-KKx22BnBKUVF-wiN6FJDpHk/edit?usp=sharing
I need to pull links to IG content while the browser is minimized. If I minimize the window and reload the page, it won't load image URL's into the srcset of each div container UNTIL I bring the instagram tab back to front. This is why I want to try this library.
I used browserify to solve imports and added the following:
(function (process){
const Instagram = require('..')
const { username, password } = process.env
const client = new Instagram({ username:'username123', password: 'password123' })
console.log(client)
client
.login()
.then(() => {
client
.getProfile()
.then(console.log)
})
}).call(this,require('_process'))
I've added prints and it seems to get called properly as, after browserifying, adding the resulting 2.3mb file as a Chrome Snippet and running it prints:
credentials
. . .
password
:
"password123"
username
:
"username123"
However, just after that, I get an exception:
index4:56 Uncaught (in promise) TypeError: Cannot read property 'map' of undefined
at request.then.res (<anonymous>:56:46)
async login({ username, password } = {}) {
username = username || this.credentials.username
password = password || this.credentials.password
// Get CSRFToken from cookie before login
const { value } = await this.request('/', { resolveWithFullResponse: true })
.then(res => res.headers['set-cookie'].map(Cookie.parse)) //THIS IS WHERE THE ERROR POINTS AT
.then(res => res.find(cookie => cookie.key === 'csrftoken'))
.then(res => res.toJSON())
Am I doing something wrong? Also, if you happen to know about any JavaScript object or something similar where all the image URL's get saved to, that would already solve the case for me personally. Having a browser session running isn't an issue for my project but I need to be able to pull the links to the media when the browser window is minimized.
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.