· 6 years ago · Jan 18, 2020, 07:46 PM
1/*
2Instagram API: send direct messages from a web browser
3
4For browser setup, see script instagram-api_direct_messages_backup.js
5Instagram web version sessionid cookie does not allow sending messages so we need to log in manually
6
7Signature should match signed_body data (using HMAC-SHA256 with private key) but using random value may work also
8https://eliasbagley.github.io/reverseengineering/2016/12/02/reverse-engineering-instagram-api.html
9http://www.will3942.com/reverse-engineering-instagram
10*/
11
12/* Usage */
13//InstagramDMlogin("username", "password"); // this function should be called only once to log in (page needs to refreshed after logging in)
14//InstagramDMsend("username", "Hi!");
15
16function InstagramDMlogin(username, password)
17{
18 var formData = new FormData();
19 formData.append("signed_body", 'XXX.{"_csrftoken":"XXX","device_id":"XXX","username":"' + username+ '","password":"' + password + '","guid":"XXX","phone_id":"XXX","login_attempt_count":0}');
20 formData.append("ig_sig_key_version", "4");
21
22 var xhr = new XMLHttpRequest();
23 xhr.open("POST", "https://i.instagram.com/api/v1/accounts/login/");
24 xhr.withCredentials = true;
25 xhr.send(formData);
26}
27
28async function InstagramDMsend(username, message)
29{
30 var userid = await getUserId(username);
31 var timestamp = Date.now();
32 var formData = new FormData();
33
34 formData.append("csrftoken", "XXX"); // should be the same as instagram.com cookie or match the value used to log in
35 formData.append("device_id", "android-XXX"); // taken from IG:dm HTTP request (random md5 hash should be fine), should match the value used to log in
36 formData.append("_uuid", timestamp); // can be generated with Linux uuid command (don't need to be renewed, timestamp can be used instead)
37 formData.append("recipient_users", "[[" + userid + "]]"); // user id can be found on https://www.instagram.com/username/?__a=1
38 formData.append("client_context", timestamp); // can be generated with Linux uuid command (timestamp can be used instead)
39 formData.append("text", message); // message to customize
40
41 var xhr = new XMLHttpRequest();
42 xhr.open("POST", "https://i.instagram.com/api/v1/direct_v2/threads/broadcast/text/");
43 xhr.withCredentials = true;
44 xhr.send(formData);
45}
46
47function getUserId(username)
48{
49 return new Promise(function(resolve) {
50 var xhr = new XMLHttpRequest();
51 xhr.open("GET", "https://www.instagram.com/" + username + "/?__a=1");
52 xhr.withCredentials = true;
53 xhr.addEventListener("load", function() {
54 var response = JSON.parse(xhr.responseText);
55 resolve(response.graphql.user.id);
56 });
57 xhr.send();
58 });
59}