Giter Site home page Giter Site logo

jlobos / instagram-web-api Goto Github PK

View Code? Open in Web Editor NEW
1.1K 38.0 188.0 592 KB

🤳 Instagram Private Web API client for Node

Home Page: https://npmjs.com/instagram-web-api

License: MIT License

JavaScript 100.00%
instagram api client private upload photo like comment node love

instagram-web-api's Introduction

NPM version Build Status XO code style

A Instagram Private Web API client 🤳✨❤️

Simple, easy and very complete implementation of the Instagram private web API.

  • Support for all the main functions of Instagram Web
  • Well tested, CI
  • All test runs daily

Install

npm install instagram-web-api

Usage

Intance Instagram and call login method; this stores the credentials in memory.

const Instagram = require('instagram-web-api')
const { username, password } = process.env

const client = new Instagram({ username, password })

client
  .login()
  .then(() => {
    client
      .getProfile()
      .then(console.log)
  })

Using async/await in Node >= 8

const Instagram = require('instagram-web-api')
const { username, password } = process.env

const client = new Instagram({ username, password })

;(async () => {
  await client.login()
  const profile = await client.getProfile()

  console.log(profile)
})()

Save cookies to disk by using a though-cookie store.

// Packages
const Instagram = require('instagram-web-api')
const FileCookieStore = require('tough-cookie-filestore2')

const { username, password } = process.env // Only required when no cookies are stored yet

const cookieStore = new FileCookieStore('./cookies.json')
const client = new Instagram({ username, password, cookieStore })

;(async () => {
  // URL or path of photo
  const photo =
    'https://scontent-scl1-1.cdninstagram.com/t51.2885-15/e35/22430378_307692683052790_5667315385519570944_n.jpg'

  await client.login()

  // Upload Photo to feed or story, just configure 'post' to 'feed' or 'story'
  const { media } = await client.uploadPhoto({ photo: photo, caption: 'testing', post: 'feed' })
  console.log(`https://www.instagram.com/p/${media.code}/`)
})()

API Reference

Instagram(credentials, opts)

const client = new Instagram({ username: '', password: '' }, { language: 'es-CL' })

Initializes the client.

  • credentials
    • username: The username of account
    • password: The password of account
    • cookieStore: An optional though-cookie cookie storage, which allows for persistent cookies. Default is undefined
  • opts
    • language: The language of response from API. Default is en-US
    • proxy: String of a proxy to tunnel all requests. Default is undefined

login(credentials)

const { username, password, cookies } = await client.login({ username: '', password: '' })
const { authenticated, user } = await client.login({ username: '', password: '' })

Login in the account, this method returns user (true when username is valid) and authenticated (true when login was successful)

  • credentials
    • username: The username of account
    • password: The password of account

logout()

await client.logout()

Logout in the account.

getHome()

const feed = await client.getHome('KGEAxpEdUwUrxxoJvxRoQeXFGooSlADHZ8UaDdSWbnOIxxoUUhyciJ7EGlxNlZjaYcUaXTgUM00qyBrgBhUsLezIGqVTlxqausga5W-fVax9xRryaBdN1EnIGvdQFgzxoMgaFoLO7v7xWQA=')

Get home feed timeline, media shared by the people you follow.

  • params
    • end_cursor (String) for pagination

getUserByUsername(params)

const instagram = await client.getUserByUsername({ username: 'instagram' })
const me = await client.getUserByUsername({ username: client.credentials.username })

Get user by username, this method not require authentication for public profiles.

  • params
    • username: The username of the profile

getFollowers(params)

const followers = await client.getFollowers({ userId: '1284161654' })

Get followers for given userId. Be aware that the response gets slightly altered for easier usage.

  • params
    • userId: The user id
    • first: Amount of followers to request. Default is 20
    • after: Optional end_cursor (String) for pagination.

getFollowings(params)

const followings = await client.getFollowings({ userId: '1284161654' })

Get followings for given userId. Be aware that the response gets slightly altered for easier usage.

  • params
    • userId: The user id
    • first: Amount of followings to request. Default is 20
    • after: Optional end_cursor (String) for pagination.

getActivity()

const activity = await client.getActivity()

Get activity of account, news following, liked, etc.

getProfile()

const profile = await client.getProfile()

Get profile the account first_name, last_name, email, username, phone_number, gender, birthday, biography, external_url and chaining_enabled.

updateProfile(params)

await client.updateProfile({ biography: '❤️', website: 'https://jlobos.com/', gender: 1 })

Update profile the account.

  • params
    • 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

changeProfilePhoto(params)

const fs = require('fs')

const photo = fs.join(__dirname, 'photo.jpg')
await client.changeProfilePhoto({ photo })

Change the profile photo.

  • params
    • photo: A String of path file or URL

deleteMedia(params)

await client.deleteMedia({ mediaId: '1442533050805297981' })

Delete a media, photo, video, etc. by the id.

  • params
    • mediaId: The media id

uploadPhoto(params)

const photo = 'https://scontent-scl1-1.cdninstagram.com/t51.2885-15/e35/16465198_658888867648924_4042368904838774784_n.jpg'
await client.uploadPhoto({ photo, caption: '❤️', post: 'feed' })

Upload a photo to Instagram. Only jpeg images allowed.

  • params
    • photo: A String of path file or URL
    • caption: The caption of photo. Default is
    • post: The local post, feed or story

getMediaFeedByLocation(params)

const location = await client.getMediaFeedByLocation({ locationId: '26914683' })

Get latitude, longitude, top posts, last media, country, city, and more related to the location.

  • params
    • locationId: The location id

getMediaFeedByHashtag(params)

const tag = client.getMediaFeedByHashtag({ hashtag: 'unicorn' })

Explore last media and top posts feed related to a hashtag.

  • params
    • hashtag: A hashtag, not including the "#"

locationSearch(params)

const venues = client.locationSearch({ query: 'chile', latitude: -33.45, longitude: -70.6667 })

Search venues by latitude and longitude.

  • params
    • latitude: Latitude
    • longitude: Longitude
    • query: A optional location name. Default is

getMediaByShortcode(params)

const media = await client.getMediaByShortcode({ shortcode: 'BQE6Cq2AqM9' })

Get data of a media by the Instagram shortcode

  • params
    • shortcode: A shortcode

addComment(params)

await client.addComment({ mediaId: 1442533050805297981, text: 'awesome' })

Add comment to a media item.

  • params
    • mediaId: The media id
    • text: Comment text
    • replyToCommentId: Optional comment id to which to reply

deleteComment(params)

await client.deleteComment({ mediaId: '1442533050805297981', commentId: '17848908229146688' })

Delete a comment.

  • params
    • mediaId: The media id
    • commentId: The comment id

getChallenge(params)

await client.getChallenge({ challengeUrl: '/challenge/1284161654/a1B2c3d4E6/' })

Get information about a challenge.

  • params
    • challengeUrl: A String with a challenge path

updateChallenge(params)

const challengeUrl = '/challenge/1284161654/a1B2c3d4E6/'

await client.updateChallenge({ challengeUrl, choice: 0 })
await client.updateChallenge({ challengeUrl, securityCode: 123456  })

Request or submit a verification code for the given challenge.

  • params
    • challengeUrl: A String with a challenge path
    • choice: Number 0 for phone and 1 for email. Default is ``
    • securityCode: Number the received verification code for the challenge. Default is ``

resetChallenge(params)

await client.resetChallenge({ challengeUrl: '/challenge/1284161654/a1B2c3d4E6/' })

Reset a challenge to start over again.

  • params
    • challengeUrl: A String with a challenge path

replayChallenge(params)

await client.replayChallenge({ challengeUrl: '/challenge/1284161654/a1B2c3d4E6/' })

Request a new verification message.

  • params
    • challengeUrl: A String with a challenge path

approve(params)

await client.approve({ userId: '1284161654' })

Approve a friendship request.

  • params
    • userId: The user id

ignore(params)

await client.ignore({ userId: '1284161654' })

Reject a friendship request.

  • params
    • userId: The user id

follow(params)

await client.follow({ userId: '1284161654' })

Follow a user.

  • params
    • userId: The user id

unfollow(params)

await client.unfollow({ userId: '1284161654' })

Unfollow a user.

  • params
    • userId: The user id

block(params)

await client.block({ userId: '1284161654' })

Block a user.

  • params
    • userId: The user id

unblock(params)

await client.unblock({ userId: '1284161654' })

Unblock a user.

  • params
    • userId: The user id

like(params)

await client.like({ mediaId: '1442533050805297981' })

Like a media item.

  • params
    • mediaId: The media id

unlike(params)

await client.unlike({ mediaId: '1442533050805297981' })

Unlike a media item.

  • params
    • mediaId: The media id

save(params)

await client.save({ mediaId: '1442533050805297981' })

Save a media item.

  • params
    • mediaId: The media id

unsave(params)

await client.unsave({ mediaId: '1442533050805297981' })

Unsave a media item.

  • params
    • mediaId: The media id

search(params)

await client.search({ query: 'unicorn' })

Search users, places, or hashtags.

  • params
    • query: Query
    • context: The context of search, hashtag, place, user or blended. Default is blended

getPhotosByHashtag(params)

await client.getPhotosByHashtag({ hashtag: 'unicorn' })

Get photos for hashtag.

  • params
    • hashtag: A String with a hashtag
    • first: A number of records to return
    • after: The query cursor String for pagination

getPhotosByUsername(params)

await client.getPhotosByUsername({ username: 'unicorn' })

Gets user photos.

  • params
    • username: A String with a hashtag
    • first: A number of records to return
    • after: The query cursor String for pagination

getPrivateProfilesFollowRequests

await client.getPrivateProfilesFollowRequests(cursor)

getChainsData

await client.getChainsData({ userId })

This will return the similar accounts, that you see, when you click on the ARROW in a profile.

  • params
    • userId: The user id

getMediaLikes(params)

await client.getMediaLikes({ shortcode: 'B-0000000', first: '49', after: '' })

This will return the media likes.

  • params
    • shortcode: The shortcode media like this: https://www.instagram.com/p/B-00000000/, only put shortcode like this : B-000000000
    • first: A number of records to return max is 49
    • after: The query cursor String for pagination

getMediaComments(params)

await client.getMediaComments({ shortcode: 'B-0000000', first: '12', after: '' }).catch((error) => {
  console.log(error);
})
.then((response) => {
  console.log(response);
});

//The query cursor 'after' maybe return an array, if array you need to convert like this: 
let pointer = response.page_info.end_cursor;
// this will try to convert array to json stringify
  try{
  		pointer = JSON.parse(pointer);
  		pointer = JSON.stringify(pointer);
  }catch(e){
  		console.log('Pointer is not array!, don't need to be converted!');
  }

This will return the media comments.

  • params
    • shortcode: The shortcode media like this: https://www.instagram.com/p/B-00000000/, only put shortcode like this : B-000000000
    • first: A number of records to return max is 49
    • after: The query cursor String for pagination

License

MIT © Jesús Lobos

instagram-web-api's People

Contributors

aldinp16 avatar anakis avatar bence04 avatar codexjoin avatar dependabot[bot] avatar doguhanokumus avatar ivkos avatar jkdrangel avatar jlobos avatar jzarca01 avatar k-miras avatar morris avatar revall avatar samholmes avatar sdkayy avatar sebnun avatar stiveknx avatar tarun7singh avatar timolins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

instagram-web-api's Issues

UnhandledPromiseRejectionWarning: StatusCodeError: 400

(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 ?

getPhotosByUsername cannot use in express?

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)
})

Instagram new limits

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"}

Problem in simple login

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)

unhandledPromiseRejectionWarning

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.

X-Instagram-AJAX

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

analytics ? exemple

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

Support to get stories

There should be support to be able to access the feed/reels_tray/ GET endpoint in the Instagram API

Login fails due to CSRF cookies not being set because of cookie confirmation banner

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.
image

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.

Workaround

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()
}

getMediaFeedByLocation returns undefined with valid locationId

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

addComment method returns 400

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.

Can not delete comment

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

Use await in order to avoid UnhandledPromiseRejectionWarning

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
  }

Pagination getUserByUsername

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?

Deconstruct response data

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.

500 Error on profile edit

Hey there. Thanks a ton for this straightforward API. Just a heads up. I'm getting a 500 error on the profile update endpoint.

X-requests-header

image
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')
);

Get followers and followings

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
]

During login: Uncaught (in promise) TypeError: Cannot read property 'map' of undefined

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

Add cookie store support

Currently it is only possible to supply a static cookie at initialization. Support for though-cookie stores would enable more possibilities:

  • Automatically store cookie changes
  • Easily store cookies in a remote place (a database fore example)
  • Load old sessions with ease (No need to manually pass the cookie)

Problem with login

Request:
client.login().then(console.log)

Response from instagram:
{ authenticated: false, user: true, status: 'ok' }

But not signed in
Why?

403 error when trying to login

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

Error: Cannot read property 'map' of undefined

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.

Get user's feed

I can't fetch user's media feed by specifing user id (pk)?

updateProfile method returns error

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?

How update challenge?

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 &bull; 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

How is challenge/response supposed to work?

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

  1. logging in (and getting the challenge error)
  2. requesting 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' }
  1. Updating the 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?

getUserByUsername requires authentication for public profiles (valid username & password)

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?

client.logout returns 405

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?

Edge limit of media likes

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

Reporting a User

Support for all the main functions of Instagram Web

but there is no reporting function and instagram web has reporting function

New `client.getHome` endpoint

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.

Randomize `userAgent`

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.