Instagram Action Script

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
boomboom
Posts: 3
Joined: 04 Dec 2017, 07:04
Contact:

Instagram Action Script

04 Dec 2017, 07:11

I don't know if this is the right place to put this, but I created an Instagram script that goes through a list of hashtags and does actions on those posts, such as liking and following. This was my first time using AutoHotKey, so it might show in the code that I am new.

But, I do plan on extending the functionality to include commenting, scheduling posts and a myriad of other actions. But, as it stands now, it just likes and follows.

Let me know what you think. :)

Here is the link to the repo where I have the code hosted.

https://github.com/talymo/instaAutomate
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: Instagram Action Script

04 Dec 2017, 07:53

I might be ignorant, but what is it good for? Why "like" or "follow" randomly? Is it to get likes and followers back?
If yes, what is the usual conversion rate? Can you monetize this? Is Instagram (and other sites) one big pyramid scheme? Well, perhaps not pyramid, but scheme...
User avatar
boomboom
Posts: 3
Joined: 04 Dec 2017, 07:04
Contact:

Re: Instagram Action Script

04 Dec 2017, 12:09

I started an online store on Shopify selling dropshipping fashion items. I set up an Instagram account to market this store. I post photos every once in a while (planning on scripting that out too in the future), and I run this script on that Instagram account using hashtags that are relevant to my store. Sure, the script gets me a lot of random likes but I am seeing an increase in traffic from Instagram to my online store. I started out this morning with 80 followers, ran the script while I went to class, checked when I got out 2 hours later and I have 109 followers and 5 more visits on my online store.
No conversions yet (online sales from the Instagram attention, that is), but I literally just started doing this. I did this as sort of an experiment to see what the results would be.
guest3456
Posts: 3454
Joined: 09 Oct 2013, 10:31

Re: Instagram Action Script

04 Dec 2017, 12:21

nice work

User avatar
boomboom
Posts: 3
Joined: 04 Dec 2017, 07:04
Contact:

Re: Instagram Action Script

04 Dec 2017, 12:32

guest3456 wrote:nice work
Thanks!
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: Instagram Action Script

04 Dec 2017, 14:19

boomboom wrote:I started an online store on Shopify selling dropshipping fashion items. I set up an Instagram account to market this store. I post photos every once in a while (planning on scripting that out too in the future), and I run this script on that Instagram account using hashtags that are relevant to my store. Sure, the script gets me a lot of random likes but I am seeing an increase in traffic from Instagram to my online store. I started out this morning with 80 followers, ran the script while I went to class, checked when I got out 2 hours later and I have 109 followers and 5 more visits on my online store.
No conversions yet (online sales from the Instagram attention, that is), but I literally just started doing this. I did this as sort of an experiment to see what the results would be.
I see, thank you for the info, despite my provocative question. Now I understand what its goal is.
(I used to work in online marketing in the early days of internet - before "Likes" were invented, I guess)
User avatar
Mutinii
Posts: 2
Joined: 08 Dec 2017, 06:56
Contact:

Re: Instagram Action Script

08 Dec 2017, 07:29

boomboom wrote:I don't know if this is the right place to put this, but I created an Instagram script that goes through a list of hashtags and does actions on those posts, such as liking and following. This was my first time using AutoHotKey, so it might show in the code that I am new.

But, I do plan on extending the functionality to include commenting, scheduling posts and a myriad of other actions. But, as it stands now, it just likes and follows.

Let me know what you think. :)

Here is the link to the repo where I have the code hosted.

https://github.com/talymo/instaAutomate
Very very good work. Please keep us updated on new features to your script!

And what's the link to your Shopify site and its associated Instagram? I'd love to take a look at both of them. I may possibly purchase a thing or two!
Guest

Re: Instagram Action Script

11 Jan 2018, 04:27

Be careful with buying followers. You might easily get shadowbanned. Here's the resource needed https://www.fast-unfollow.com/
User avatar
adegard
Posts: 90
Joined: 24 Nov 2017, 05:58
Contact:

Re: Instagram Action Script

26 Nov 2018, 15:15

Hi, I found this post idea interesting ! Follow people based on your target (Hashtag) is usefull to increase people back following you... So I decide to reproduce this script (above by @boomboom) with the use of TagIE_Editor&Functions, to simply it a bit. ;)

Here's my revisited code, I hope it could be usefull for someone:
Spoiler
r2997790
Posts: 71
Joined: 02 Feb 2017, 02:46

Re: Instagram Action Script

27 Nov 2018, 03:20

Great job. Thank you.

Would love to see something that can post stories too. Be great to have this added as well.

It's also annoying the Instagram doesn't allow you to search by location, combining location and hashtag would really be awesome.

Thanks for making this cool script example.
User avatar
adegard
Posts: 90
Joined: 24 Nov 2017, 05:58
Contact:

Re: Instagram Action Script

30 Nov 2018, 10:25

Would love to see something that can post stories too. Be great to have this added as well.
To add stories on Instagram, You need to "rotate your phone" then from computer, no way...
r2997790
Posts: 71
Joined: 02 Feb 2017, 02:46

Re: Instagram Action Script

01 Dec 2018, 02:56

No, if you view the browser using the mobile viewport via developer options you can use it as a 'mobile' and click your profile photo to add a story.

So far from impossible! Just need to open IE and switch to a mobile render of the page so you load a mobile view of Instagram...
User avatar
adegard
Posts: 90
Joined: 24 Nov 2017, 05:58
Contact:

Re: Instagram Action Script

03 Dec 2018, 14:51

I found this code to change the IE user agent, but I was not able to reproduce it in instagram...

Code: Select all

;https://autohotkey.com/board/topic/98489-setuseragent-change-ie-com-session-user-agent/
wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := True
;wb.Navigate("https://www.instagram.com/")
wb.Navigate("http://whatsmyuseragent.com",0,0,0,"User-Agent: Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537")
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Instagram Action Script

03 Dec 2018, 16:34

Login to instagram with this API:
https://github.com/LevPasha/Instagram-API-python

Code: Select all

username := "[email protected]"
password := "password"

API_URL := "https://i.instagram.com/api/v1/"
DEVICE_SETTINTS := {manufacturer: "Xiaomi", model: "HM 1SW", android_version: 18, android_release: 4.3}
USER_AGENT := "Instagram 10.26.0 Android (" DEVICE_SETTINTS["android_version"] "/" DEVICE_SETTINTS["android_release"] "; 320dpi; 720x1280; " DEVICE_SETTINTS["manufacturer"] "; " DEVICE_SETTINTS["model"] "; armani; qcom; en_US)"
IG_SIG_KEY := "4f8732eb9ba7d1c8e8897a75d6474d4eb3f5279137431b2aafb71fafe2abe178"
SIG_KEY_VERSION := 4

device_id := "android-" SubStr(bcrypt_md5(bcrypt_md5(username password) 12345), 1, 16)
uuid := generateUUID(true)
HTTP := ComObjCreate("WinHTTP.WinHTTPRequest.5.1")
HTTP.Open("GET", API_URL "si/fetch_headers/?challenge_type=signup&guid=" generateUUID(False), true)
HTTP.SetRequestHeader("Connection", "close")
HTTP.SetRequestHeader("Accept", "*/*")
HTTP.SetRequestHeader("Cookie2", "$Version=1")
HTTP.SetRequestHeader("Accept-Language", "en-US")
HTTP.SetRequestHeader("User-Agent", USER_AGENT)
HTTP.Send()
HTTP.WaitForResponse()
csrftoken := RegexReplace(HTTP.getAllResponseHeaders, "s)^.*Set-Cookie: csrftoken=(.+?);.*$", "$1")   ; given for 1 year
data := "{""phone_id"": """ generateUUID(true) """, ""_csrftoken"": """ csrftoken """, ""username"": """ username """, ""guid"": """ uuid """, ""device_id"": """ device_id """, ""password"": """ password """, ""login_attempt_count"": ""0""}"
Signature := "ig_sig_key_version=" SIG_KEY_VERSION "&signed_body=" HMAC(IG_SIG_KEY, data, "SHA256") "." UriEncode(data)

HTTP.Open("POST", API_URL "accounts/login/", true)
HTTP.SetRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
HTTP.SetRequestHeader("Connection", "close")
HTTP.SetRequestHeader("Accept", "*/*")
HTTP.SetRequestHeader("Cookie2", "$Version=1")
HTTP.SetRequestHeader("Accept-Language", "en-US")
HTTP.SetRequestHeader("User-Agent", USER_AGENT)
HTTP.Send(Signature)
HTTP.WaitForResponse()
msgbox % HTTP.responsetext
return



generateUUID(type)
{
   VarSetCapacity(puuid, 16, 0)
   if !(DllCall("rpcrt4.dll\UuidCreate", "ptr", &puuid))
   {
      if !(DllCall("rpcrt4.dll\UuidToString", "ptr", &puuid, "uint*", suuid))
      {
         if type
            return StrGet(suuid), DllCall("rpcrt4.dll\RpcStringFree", "uint*", suuid)
         else
            return StrReplace(StrGet(suuid), "-"), DllCall("rpcrt4.dll\RpcStringFree", "uint*", suuid)
      }
   }
   return ""
}



UriEncode(Uri, RE="[0-9A-Za-z]")
{
   VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
   While Code := NumGet(Var, A_Index - 1, "UChar")
      Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
   Return, Res
}



bcrypt_md5(string)
{
    static BCRYPT_MD5_ALGORITHM := "MD5"
    static BCRYPT_OBJECT_LENGTH := "ObjectLength"
    static BCRYPT_HASH_LENGTH   := "HashDigestLength"

    if !(hBCRYPT := DllCall("LoadLibrary", "str", "bcrypt.dll", "ptr"))
        throw Exception("Failed to load bcrypt.dll", -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptOpenAlgorithmProvider", "ptr*", hAlgo, "ptr", &BCRYPT_MD5_ALGORITHM, "ptr", 0, "uint", 0) != 0)
        throw Exception("BCryptOpenAlgorithmProvider: " NT_STATUS, -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptGetProperty", "ptr", hAlgo, "ptr", &BCRYPT_OBJECT_LENGTH, "uint*", cbHashObject, "uint", 4, "uint*", cbResult, "uint", 0) != 0)
        throw Exception("BCryptGetProperty: " NT_STATUS, -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptGetProperty", "ptr", hAlgo, "ptr", &BCRYPT_HASH_LENGTH, "uint*", cbHash, "uint", 4, "uint*", cbResult, "uint", 0) != 0)
        throw Exception("BCryptGetProperty: " NT_STATUS, -1)

    VarSetCapacity(pbHashObject, cbHashObject, 0)
    if (NT_STATUS := DllCall("bcrypt\BCryptCreateHash", "ptr", hAlgo, "ptr*", hHash, "ptr", &pbHashObject, "uint", cbHashObject, "ptr", 0, "uint", 0, "uint", 0) != 0)
        throw Exception("BCryptCreateHash: " NT_STATUS, -1)

    VarSetCapacity(pbInput, StrPut(string, "UTF-8"), 0) && cbInput := StrPut(string, &pbInput, "UTF-8") - 1
    if (NT_STATUS := DllCall("bcrypt\BCryptHashData", "ptr", hHash, "ptr", &pbInput, "uint", cbInput, "uint", 0) != 0)
        throw Exception("BCryptHashData: " NT_STATUS, -1)

    VarSetCapacity(pbHash, cbHash, 0)
    if (NT_STATUS := DllCall("bcrypt\BCryptFinishHash", "ptr", hHash, "ptr", &pbHash, "uint", cbHash, "uint", 0) != 0)
        throw Exception("BCryptFinishHash: " NT_STATUS, -1)

    loop % cbHash
        hash .= Format("{:02x}", NumGet(pbHash, A_Index - 1, "uchar"))

    DllCall("bcrypt\BCryptDestroyHash", "ptr", hHash)
    DllCall("bcrypt\BCryptCloseAlgorithmProvider", "ptr", hAlgo, "uint", 0)
    DllCall("FreeLibrary", "ptr", hBCRYPT)

    return hash
}




HMAC(Key, Message, Algo := "MD5")
{
   static Algorithms := {MD2:    {ID: 0x8001, Size:  64}
                                   , MD4:    {ID: 0x8002, Size:  64}
                                   , MD5:    {ID: 0x8003, Size:  64}
                                   , SHA:    {ID: 0x8004, Size:  64}
                                   , SHA256: {ID: 0x800C, Size:  64}
                                   , SHA384: {ID: 0x800D, Size: 128}
                                   , SHA512: {ID: 0x800E, Size: 128}}
   static iconst := 0x36
   static oconst := 0x5C
   if (!(Algorithms.HasKey(Algo)))
   {
      return ""
   }
   Hash := KeyHashLen := InnerHashLen := ""
   HashLen := 0
   AlgID := Algorithms[Algo].ID
   BlockSize := Algorithms[Algo].Size
   MsgLen := StrPut(Message, "UTF-8") - 1
   KeyLen := StrPut(Key, "UTF-8") - 1
   VarSetCapacity(K, KeyLen + 1, 0)
   StrPut(Key, &K, KeyLen, "UTF-8")
   if (KeyLen > BlockSize)
   {
      LC_CalcAddrHash(&K, KeyLen, AlgID, KeyHash, KeyHashLen)
   }

   VarSetCapacity(ipad, BlockSize + MsgLen, iconst)
   Addr := KeyLen > BlockSize ? &KeyHash : &K
   Length := KeyLen > BlockSize ? KeyHashLen : KeyLen
   i := 0
   while (i < Length)
   {
      NumPut(NumGet(Addr + 0, i, "UChar") ^ iconst, ipad, i, "UChar")
      i++
   }
   if (MsgLen)
   {
      StrPut(Message, &ipad + BlockSize, MsgLen, "UTF-8")
   }
   LC_CalcAddrHash(&ipad, BlockSize + MsgLen, AlgID, InnerHash, InnerHashLen)

   VarSetCapacity(opad, BlockSize + InnerHashLen, oconst)
   Addr := KeyLen > BlockSize ? &KeyHash : &K
   Length := KeyLen > BlockSize ? KeyHashLen : KeyLen
   i := 0
   while (i < Length)
   {
      NumPut(NumGet(Addr + 0, i, "UChar") ^ oconst, opad, i, "UChar")
      i++
   }
   Addr := &opad + BlockSize
   i := 0
   while (i < InnerHashLen)
   {
      NumPut(NumGet(InnerHash, i, "UChar"), Addr + i, 0, "UChar")
      i++
   }
   return LC_CalcAddrHash(&opad, BlockSize + InnerHashLen, AlgID)
}



LC_CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0)
{
   static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"]
   static b := h.minIndex()
   hProv := hHash := o := ""
   if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xf0000000))
   {
      if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash))
      {
         if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0))
         {
            if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0))
            {
               VarSetCapacity(hash, hashlength, 0)
               if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0))
               {
                  loop % hashlength
                  {
                     v := NumGet(hash, A_Index - 1, "UChar")
                     o .= h[(v >> 4) + b] h[(v & 0xf) + b]
                  }
               }
            }
         }
         DllCall("advapi32\CryptDestroyHash", "Ptr", hHash)
      }
      DllCall("advapi32\CryptReleaseContext", "Ptr", hProv, "UInt", 0)
   }
   return o
}
User avatar
adegard
Posts: 90
Joined: 24 Nov 2017, 05:58
Contact:

Re: Instagram Action Script

05 Dec 2018, 09:15

Login to instagram with this API:
Thanks you so much @malcev ! login is working :D . Now to upload some photos, I need the "uploadphoto" function, as describe in your link? it's in python. Could you please also adapt uploadPhoto function for autohotkey?

Code: Select all

uploadPhoto(self, photo, caption=None, upload_id=None, is_sidecar=None)
from this.

I'd like to use it as a little ahk app, button to upload photo
Spoiler
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Instagram Action Script

06 Dec 2018, 00:15

Sorry, but now it is not interesting for me because I do not use instagram.
I have written this code about a half year ago.
And basically it was interesting for me to try to understand how this python code works.
But You can do it by Yourself, as I see You have to convert Your photo to binary data and send with multipart/form-data.
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Instagram Action Script

04 Mar 2019, 23:06

adegard, if it still interesting to You here is code:

Code: Select all

username := "[email protected]"
password := "password"

API_URL := "https://i.instagram.com/api/v1/"
DEVICE_SETTINTS := {manufacturer: "Xiaomi", model: "HM 1SW", android_version: 18, android_release: 4.3}
USER_AGENT := "Instagram 10.26.0 Android (" DEVICE_SETTINTS["android_version"] "/" DEVICE_SETTINTS["android_release"] "; 320dpi; 720x1280; " DEVICE_SETTINTS["manufacturer"] "; " DEVICE_SETTINTS["model"] "; armani; qcom; en_US)"
IG_SIG_KEY := "4f8732eb9ba7d1c8e8897a75d6474d4eb3f5279137431b2aafb71fafe2abe178"
SIG_KEY_VERSION := 4

device_id := "android-" SubStr(bcrypt_md5(bcrypt_md5(username password) 12345), 1, 16)
uuid := generateUUID(true)
HTTP := ComObjCreate("WinHTTP.WinHTTPRequest.5.1")

; 1 time in 90 days
HTTP.Open("GET", API_URL "si/fetch_headers/?challenge_type=signup&guid=" generateUUID(False), true)
HTTP.SetRequestHeader("Connection", "close")
HTTP.SetRequestHeader("Accept", "*/*")
HTTP.SetRequestHeader("Cookie2", "$Version=1")
HTTP.SetRequestHeader("Accept-Language", "en-US")
HTTP.SetRequestHeader("User-Agent", USER_AGENT)
HTTP.Send()
HTTP.WaitForResponse()
csrftoken := RegexReplace(HTTP.getAllResponseHeaders, "s)^.*Set-Cookie: csrftoken=(.+?);.*$", "$1")   ;  giving for 1 year
data := "{""phone_id"": """ generateUUID(true) """, ""_csrftoken"": """ csrftoken """, ""username"": """ username """, ""guid"": """ uuid """, ""device_id"": """ device_id """, ""password"": """ password """, ""login_attempt_count"": ""0""}"
Signature := "ig_sig_key_version=" SIG_KEY_VERSION "&signed_body=" HMAC(IG_SIG_KEY, data, "SHA256") "." UriEncode(data)

HTTP.Open("POST", API_URL "accounts/login/", true)
HTTP.SetRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
HTTP.SetRequestHeader("Connection", "close")
HTTP.SetRequestHeader("Accept", "*/*")
HTTP.SetRequestHeader("Cookie2", "$Version=1")
HTTP.SetRequestHeader("Accept-Language", "en-US")
HTTP.SetRequestHeader("User-Agent", USER_AGENT)
HTTP.Send(Signature)
HTTP.WaitForResponse()
username_id := RegexReplace(HTTP.getAllResponseHeaders, "s)^.*Set-Cookie: ds_user_id=(.+?);.*$", "$1")
token := RegexReplace(HTTP.getAllResponseHeaders, "s)^.*Set-Cookie: csrftoken=(.+?);.*$", "$1")
match := "", Pos := 1
While Pos := regexmatch(HTTP.getAllResponseHeaders, "s)Set-Cookie: (.+?)\R", match, pos+StrLen(match))
   cookie .= match1 "; "
msgbox % clipboard := "username_id := " username_id "`r`ntoken := """ token """`r`ncookie := """ StrReplace(cookie, """", """""") """"

photo := "C:\001.jpg"
caption := "test"
disable_comments := false

pToken := Gdip_StartUp()
pBitmap := Gdip_CreateBitmapFromFile(photo)
Gdip_GetImageDimensions(pBitmap, width, height)
Gdip_DisposeImage(pBitmap)
Gdip_ShutDown(pToken)
upload_id := A_NowUTC
EnvSub, upload_id, 1970, seconds
upload_id .= A_MSec
data := {photo: [photo], upload_id: upload_id,  _csrftoken: csrftoken, image_compression: "{""lib_name"":""jt"",""lib_version"":""1.3.0"",""quality"":""87""}"}

CreateFormData(PostData, hdr_ContentType, data)
HTTP.Open("POST", API_URL "upload/photo/", true)
HTTP.SetRequestHeader("Content-Type", hdr_ContentType)
HTTP.SetRequestHeader("X-IG-Capabilities", "3Q4=")
HTTP.SetRequestHeader("X-IG-Connection-Type", "WIFI")
HTTP.SetRequestHeader("Cookie2", "$Version=1")
HTTP.SetRequestHeader("Accept-Language", "en-US")
HTTP.SetRequestHeader("Accept-Encoding", "gzip, deflate")
HTTP.SetRequestHeader("Connection", "close")
HTTP.SetRequestHeader("User-Agent", USER_AGENT)
HTTP.SetRequestHeader("Cookie", cookie)
HTTP.Send(PostData)
HTTP.WaitForResponse()
if (HTTP.Status = 200)
{
   data := "{""_csrftoken"": """ token """, ""media_folder"": ""Instagram"", ""source_type"": 4, ""_uid"": " username_id ", ""_uuid"": """ uuid """, ""caption"": """ caption """, ""upload_id"": """ upload_id """, ""device"": {""manufacturer"": """ DEVICE_SETTINTS["manufacturer"] """, ""model"": """ DEVICE_SETTINTS["model"] """, ""android_version"": " DEVICE_SETTINTS["android_version"] ", ""android_release"": """ DEVICE_SETTINTS["android_release"] """}, ""edits"": {""crop_original_size"": [" width ".0 , " height ".0], ""crop_center"": [0.0, 0.0], ""crop_zoom"": 1.0}, ""extra"": {""source_width"": " width ", ""source_height"": " height "}}"
   if disable_comments
      data := SubStr(data, 1, -1) ", ""disable_comments"": 1}"
   Signature := "ig_sig_key_version=" SIG_KEY_VERSION "&signed_body=" HMAC(IG_SIG_KEY, data, "SHA256") "." UriEncode(data)
   HTTP.Open("POST", API_URL "media/configure/?", true)
   HTTP.SetRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
   HTTP.SetRequestHeader("Connection", "close")
   HTTP.SetRequestHeader("Accept", "*/*")
   HTTP.SetRequestHeader("Cookie2", "$Version=1")
   HTTP.SetRequestHeader("Accept-Language", "en-US")
   HTTP.SetRequestHeader("User-Agent", USER_AGENT)
   HTTP.SetRequestHeader("Cookie", cookie)
   HTTP.Send(Signature)
   HTTP.WaitForResponse()
   if (HTTP.Status = 200)
   {
      data := "{""_uuid"": """ uuid """, ""_uid"": " username_id ", ""id"": " username_id ", ""_csrftoken"": """ token """, ""experiment"": ""ig_android_profile_contextual_feed""}"
      Signature := "ig_sig_key_version=" SIG_KEY_VERSION "&signed_body=" HMAC(IG_SIG_KEY, data, "SHA256") "." UriEncode(data)
      HTTP.Open("POST", API_URL "qe/expose/", true)
      HTTP.SetRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
      HTTP.SetRequestHeader("Connection", "close")
      HTTP.SetRequestHeader("Accept", "*/*")
      HTTP.SetRequestHeader("Cookie2", "$Version=1")
      HTTP.SetRequestHeader("Accept-Language", "en-US")
      HTTP.SetRequestHeader("User-Agent", USER_AGENT)
      HTTP.SetRequestHeader("Cookie", cookie)
      HTTP.Send(Signature)
      HTTP.WaitForResponse()
      msgbox done
   }
   else
   {
      msgbox % HTTP.ResponseText
      return
   }
}
else
{
   msgbox % HTTP.ResponseText
   return
}






generateUUID(type)
{
   VarSetCapacity(puuid, 16, 0)
   if !(DllCall("rpcrt4.dll\UuidCreate", "ptr", &puuid))
   {
      if !(DllCall("rpcrt4.dll\UuidToString", "ptr", &puuid, "uint*", suuid))
      {
         if type
            return StrGet(suuid), DllCall("rpcrt4.dll\RpcStringFree", "uint*", suuid)
         else
            return StrReplace(StrGet(suuid), "-"), DllCall("rpcrt4.dll\RpcStringFree", "uint*", suuid)
      }
   }
   return ""
}



UriEncode(Uri, RE="[0-9A-Za-z]")
{
   VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
   While Code := NumGet(Var, A_Index - 1, "UChar")
      Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
   Return, Res
}



bcrypt_md5(string)
{
    static BCRYPT_MD5_ALGORITHM := "MD5"
    static BCRYPT_OBJECT_LENGTH := "ObjectLength"
    static BCRYPT_HASH_LENGTH   := "HashDigestLength"

    if !(hBCRYPT := DllCall("LoadLibrary", "str", "bcrypt.dll", "ptr"))
        throw Exception("Failed to load bcrypt.dll", -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptOpenAlgorithmProvider", "ptr*", hAlgo, "ptr", &BCRYPT_MD5_ALGORITHM, "ptr", 0, "uint", 0) != 0)
        throw Exception("BCryptOpenAlgorithmProvider: " NT_STATUS, -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptGetProperty", "ptr", hAlgo, "ptr", &BCRYPT_OBJECT_LENGTH, "uint*", cbHashObject, "uint", 4, "uint*", cbResult, "uint", 0) != 0)
        throw Exception("BCryptGetProperty: " NT_STATUS, -1)

    if (NT_STATUS := DllCall("bcrypt\BCryptGetProperty", "ptr", hAlgo, "ptr", &BCRYPT_HASH_LENGTH, "uint*", cbHash, "uint", 4, "uint*", cbResult, "uint", 0) != 0)
        throw Exception("BCryptGetProperty: " NT_STATUS, -1)

    VarSetCapacity(pbHashObject, cbHashObject, 0)
    if (NT_STATUS := DllCall("bcrypt\BCryptCreateHash", "ptr", hAlgo, "ptr*", hHash, "ptr", &pbHashObject, "uint", cbHashObject, "ptr", 0, "uint", 0, "uint", 0) != 0)
        throw Exception("BCryptCreateHash: " NT_STATUS, -1)

    VarSetCapacity(pbInput, StrPut(string, "UTF-8"), 0) && cbInput := StrPut(string, &pbInput, "UTF-8") - 1
    if (NT_STATUS := DllCall("bcrypt\BCryptHashData", "ptr", hHash, "ptr", &pbInput, "uint", cbInput, "uint", 0) != 0)
        throw Exception("BCryptHashData: " NT_STATUS, -1)

    VarSetCapacity(pbHash, cbHash, 0)
    if (NT_STATUS := DllCall("bcrypt\BCryptFinishHash", "ptr", hHash, "ptr", &pbHash, "uint", cbHash, "uint", 0) != 0)
        throw Exception("BCryptFinishHash: " NT_STATUS, -1)

    loop % cbHash
        hash .= Format("{:02x}", NumGet(pbHash, A_Index - 1, "uchar"))

    DllCall("bcrypt\BCryptDestroyHash", "ptr", hHash)
    DllCall("bcrypt\BCryptCloseAlgorithmProvider", "ptr", hAlgo, "uint", 0)
    DllCall("FreeLibrary", "ptr", hBCRYPT)

    return hash
}




HMAC(Key, Message, Algo := "MD5")
{
   static Algorithms := {MD2:    {ID: 0x8001, Size:  64}
                                   , MD4:    {ID: 0x8002, Size:  64}
                                   , MD5:    {ID: 0x8003, Size:  64}
                                   , SHA:    {ID: 0x8004, Size:  64}
                                   , SHA256: {ID: 0x800C, Size:  64}
                                   , SHA384: {ID: 0x800D, Size: 128}
                                   , SHA512: {ID: 0x800E, Size: 128}}
   static iconst := 0x36
   static oconst := 0x5C
   if (!(Algorithms.HasKey(Algo)))
   {
      return ""
   }
   Hash := KeyHashLen := InnerHashLen := ""
   HashLen := 0
   AlgID := Algorithms[Algo].ID
   BlockSize := Algorithms[Algo].Size
   MsgLen := StrPut(Message, "UTF-8") - 1
   KeyLen := StrPut(Key, "UTF-8") - 1
   VarSetCapacity(K, KeyLen + 1, 0)
   StrPut(Key, &K, KeyLen, "UTF-8")
   if (KeyLen > BlockSize)
   {
      LC_CalcAddrHash(&K, KeyLen, AlgID, KeyHash, KeyHashLen)
   }

   VarSetCapacity(ipad, BlockSize + MsgLen, iconst)
   Addr := KeyLen > BlockSize ? &KeyHash : &K
   Length := KeyLen > BlockSize ? KeyHashLen : KeyLen
   i := 0
   while (i < Length)
   {
      NumPut(NumGet(Addr + 0, i, "UChar") ^ iconst, ipad, i, "UChar")
      i++
   }
   if (MsgLen)
   {
      StrPut(Message, &ipad + BlockSize, MsgLen, "UTF-8")
   }
   LC_CalcAddrHash(&ipad, BlockSize + MsgLen, AlgID, InnerHash, InnerHashLen)

   VarSetCapacity(opad, BlockSize + InnerHashLen, oconst)
   Addr := KeyLen > BlockSize ? &KeyHash : &K
   Length := KeyLen > BlockSize ? KeyHashLen : KeyLen
   i := 0
   while (i < Length)
   {
      NumPut(NumGet(Addr + 0, i, "UChar") ^ oconst, opad, i, "UChar")
      i++
   }
   Addr := &opad + BlockSize
   i := 0
   while (i < InnerHashLen)
   {
      NumPut(NumGet(InnerHash, i, "UChar"), Addr + i, 0, "UChar")
      i++
   }
   return LC_CalcAddrHash(&opad, BlockSize + InnerHashLen, AlgID)
}



LC_CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0)
{
   static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"]
   static b := h.minIndex()
   hProv := hHash := o := ""
   if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xf0000000))
   {
      if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash))
      {
         if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0))
         {
            if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0))
            {
               VarSetCapacity(hash, hashlength, 0)
               if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0))
               {
                  loop % hashlength
                  {
                     v := NumGet(hash, A_Index - 1, "UChar")
                     o .= h[(v >> 4) + b] h[(v & 0xf) + b]
                  }
               }
            }
         }
         DllCall("advapi32\CryptDestroyHash", "Ptr", hHash)
      }
      DllCall("advapi32\CryptReleaseContext", "Ptr", hProv, "UInt", 0)
   }
   return o
}



Gdip_Startup()
{
   Ptr := A_PtrSize ? "UPtr" : "UInt"
   if !DllCall("GetModuleHandle", "str", "gdiplus", Ptr)
      DllCall("LoadLibrary", "str", "gdiplus")
   VarSetCapacity(si, A_PtrSize = 8 ? 24 : 16, 0), si := Chr(1)
   DllCall("gdiplus\GdiplusStartup", A_PtrSize ? "UPtr*" : "uint*", pToken, Ptr, &si, Ptr, 0)
   return pToken
}

Gdip_Shutdown(pToken)
{
   Ptr := A_PtrSize ? "UPtr" : "UInt"
   DllCall("gdiplus\GdiplusShutdown", Ptr, pToken)
   if hModule := DllCall("GetModuleHandle", "str", "gdiplus", Ptr)
      DllCall("FreeLibrary", Ptr, hModule)
   return 0
}

Gdip_CreateBitmapFromFile(sFile, IconNumber=1, IconSize="")
{
   Ptr := A_PtrSize ? "UPtr" : "UInt"
   , PtrA := A_PtrSize ? "UPtr*" : "UInt*"
   if (!A_IsUnicode)
   {
      VarSetCapacity(wFile, 1024)
      DllCall("kernel32\MultiByteToWideChar", "uint", 0, "uint", 0, Ptr, &sFile, "int", -1, Ptr, &wFile, "int", 512)
      DllCall("gdiplus\GdipCreateBitmapFromFile", Ptr, &wFile, PtrA, pBitmap)
   }
   else
      DllCall("gdiplus\GdipCreateBitmapFromFile", Ptr, &sFile, PtrA, pBitmap)
   return pBitmap
}

Gdip_GetImageDimensions(pBitmap, ByRef Width, ByRef Height)
{
   Ptr := A_PtrSize ? "UPtr" : "UInt"
   DllCall("gdiplus\GdipGetImageWidth", Ptr, pBitmap, "uint*", Width)
   DllCall("gdiplus\GdipGetImageHeight", Ptr, pBitmap, "uint*", Height)
}

Gdip_DisposeImage(pBitmap)
{
   return DllCall("gdiplus\GdipDisposeImage", A_PtrSize ? "UPtr" : "UInt", pBitmap)
}



; CreateFormData() by tmplinshi, AHK Topic: https://autohotkey.com/boards/viewtopic.php?t=7647
; Thanks to Coco: https://autohotkey.com/boards/viewtopic.php?p=41731#p41731
; Modified version by SKAN, 09/May/2016

CreateFormData(ByRef retData, ByRef retHeader, objParam) {
	New CreateFormData(retData, retHeader, objParam)
}

Class CreateFormData {

	__New(ByRef retData, ByRef retHeader, objParam) {

		Local CRLF := "`r`n", i, k, v, str, pvData
		; Create a random Boundary
		Local Boundary := this.RandomBoundary()
		Local BoundaryLine := "------------------------------" . Boundary

    this.Len := 0 ; GMEM_ZEROINIT|GMEM_FIXED = 0x40
    this.Ptr := DllCall( "GlobalAlloc", "UInt",0x40, "UInt",1, "Ptr"  )          ; allocate global memory

		; Loop input paramters
		For k, v in objParam
		{
			If IsObject(v) {
				For i, FileName in v
				{
					str := BoundaryLine . CRLF
					     . "Content-Disposition: form-data; name=""" . k . """; filename=""" . FileName . """" . CRLF
					     . "Content-Type: " . this.MimeType(FileName) . CRLF . CRLF
          this.StrPutUTF8( str )
          this.LoadFromFile( Filename )
          this.StrPutUTF8( CRLF )
				}
			} Else {
				str := BoundaryLine . CRLF
				     . "Content-Disposition: form-data; name=""" . k """" . CRLF . CRLF
				     . v . CRLF
        this.StrPutUTF8( str )
			}
		}

		this.StrPutUTF8( BoundaryLine . "--" . CRLF )

    ; Create a bytearray and copy data in to it.
    retData := ComObjArray( 0x11, this.Len ) ; Create SAFEARRAY = VT_ARRAY|VT_UI1
    pvData  := NumGet( ComObjValue( retData ) + 8 + A_PtrSize )
    DllCall( "RtlMoveMemory", "Ptr",pvData, "Ptr",this.Ptr, "Ptr",this.Len )

    this.Ptr := DllCall( "GlobalFree", "Ptr",this.Ptr, "Ptr" )                   ; free global memory 

    retHeader := "multipart/form-data; boundary=----------------------------" . Boundary
	}

  StrPutUTF8( str ) {
    Local ReqSz := StrPut( str, "utf-8" ) - 1
    this.Len += ReqSz                                  ; GMEM_ZEROINIT|GMEM_MOVEABLE = 0x42
    this.Ptr := DllCall( "GlobalReAlloc", "Ptr",this.Ptr, "UInt",this.len + 1, "UInt", 0x42 )   
    StrPut( str, this.Ptr + this.len - ReqSz, ReqSz, "utf-8" )
  }
  
  LoadFromFile( Filename ) {
    Local objFile := FileOpen( FileName, "r" )
    this.Len += objFile.Length                     ; GMEM_ZEROINIT|GMEM_MOVEABLE = 0x42 
    this.Ptr := DllCall( "GlobalReAlloc", "Ptr",this.Ptr, "UInt",this.len, "UInt", 0x42 )
    objFile.RawRead( this.Ptr + this.Len - objFile.length, objFile.length )
    objFile.Close()       
  }

	RandomBoundary() {
		str := "0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z"
		Sort, str, D| Random
		str := StrReplace(str, "|")
		Return SubStr(str, 1, 12)
	}

	MimeType(FileName) {
		n := FileOpen(FileName, "r").ReadUInt()
		Return (n        = 0x474E5089) ? "image/png"
		     : (n        = 0x38464947) ? "image/gif"
		     : (n&0xFFFF = 0x4D42    ) ? "image/bmp"
		     : (n&0xFFFF = 0xD8FF    ) ? "image/jpeg"
		     : (n&0xFFFF = 0x4949    ) ? "image/tiff"
		     : (n&0xFFFF = 0x4D4D    ) ? "image/tiff"
		     : "application/octet-stream"
	}

}
After succesfull login You have to save all cookies, username_id and token.
And then You have to send cookies with every http request because:
You are advised to persist/cache the auth cookie details to avoid logging in every time you make an api call. Excessive logins is a surefire way to get your account flagged for removal. It's also advisable to cache the client details such as user agent, etc together with the auth details.
The saved auth cookie can be reused for up to 90 days.

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: tony01 and 113 guests