How I Created A PHP Instagram Bot To Automate My Instagram Activities!

Photo by Solen Feyissa on Unsplash

How I Created A PHP Instagram Bot To Automate My Instagram Activities!

Bhawani Garg's photo
Bhawani Garg
·Jun 27, 2022·

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Do you use Instagram? Do you want to know how to build an Instagram Bot?

This tutorial will teach you how to automate Instagram activities with the help of an Instagram bot.

Let's get started!

Prerequisites for making one (Bot)

Linux server

That's it. Now let's dive straight into the code.

First file (instagram.class.php)

<?php
set_time_limit(0);
Class Instagram
{
public $username;
public $password;
private $guid;
private $my_uid;
private $userAgent = 'Instagram 6.21.2 Android (19/4.4.2; 480dpi; 1152x1920; Meizu; MX4; mx4; mt6595; en_US)';
private $instaSignature ='25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5';
private $instagramUrl = 'https://i.instagram.com/api/v1/';

function __construct()    {    
    if (!extension_loaded('curl')) trigger_error('php_curl extension is not loaded', E_USER_ERROR);    
}

function __destruct()    {

}    

private function Request($url, $post, $post_data, $cookies) {    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->instagramUrl . $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
        }         
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE,   dirname(__FILE__). '/cookies.txt');            
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR,  dirname(__FILE__). '/cookies.txt');
    }
    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);    
    curl_close($ch);    
    return array($http, $response);
}

private function GenerateGuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(16384, 20479), 
            mt_rand(32768, 49151), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535), 
            mt_rand(0, 65535));
}

private function GenerateSignature($data) {
    return hash_hmac('sha256', $data, $this->instaSignature); 
}

public function Login($username, $password) {
    $this->username = $username;
    $this->password = $password;    
    $this->guid = $this->GenerateGuid();
    $device_id = "android-" . $this->guid;    
    $data = '{"device_id":"'.$device_id.'","guid":"'.$this->guid.'","username":"'. $this->username.'","password":"'.$this->password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
    $sig = $this->GenerateSignature($data);
    $data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';    
    $myid = $this->Request('accounts/login/', true, $data, false);    
    $decode = json_decode($myid[1], true); 
    $this->my_uid = $decode['logged_in_user']['pk'];
    print_r($this->my_uid);    
    return $myid;
}

public function IsFriend($user_id) {
    $device_id = "android-".$this->guid;
    $data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
    $sig = $this->GenerateSignature($data);
    $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
    return $this->Request('friendships/show/'.$user_id.'/', true, $new_data, true);    
}        

public function PostComment($caption, $media_id) {
    $caption = preg_replace("/\r|\n/", "", $caption);
    $device_id = "android-".$this->guid;
    $data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","comment_text":"'.trim($caption).'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
    $sig = $this->GenerateSignature($data);
    $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
    return $this->Request('media/'.$media_id.'/comment/', true, $new_data, true);    
} 

public function PostLike($media_id) {
    $device_id = "android-".$this->guid;
    $data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","d":"0","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
    $sig = $this->GenerateSignature($data);
    $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
    return $this->Request('media/'.$media_id.'/like/', true, $new_data, true);        
} 

public function PostFollow($user_id) {
    $device_id = "android-".$this->guid;
    $data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
    $sig = $this->GenerateSignature($data);
    $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
    return $this->Request('friendships/create/'.$user_id.'/', true, $new_data, true);    
}

public function SearchTag($tag) {
    $device_id = "android-".$this->guid;
    $data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","timezone_offset":"43200","uid":"'.$this->my_uid.'","q":"'.$tag.'","count":"50","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';   
    $sig = $this->GenerateSignature($data);
    $new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';    
    return $this->Request('feed/tag/'.$tag.'/', true, $new_data, true);        
}


}
?>

2nd file (instagram_config.php)

You need to edit the details with yours.

<?php
set_time_limit(0);
$searchtag = array('hashtag1', 'hashtag2', 'hashtag3');
$hello = array('Before-Tag-Msg', 'Before-Tag-Msg-2');
$praise = array('After-Tag-Msg', ' After-Tag-Msg', ' After-Tag-Msg');
?>

So your comment will look like this:

Before-Tag-Msg @Username After-Tag-Msg

3rd file and the final one:

You need to replace your instagram username and password here

<?php
set_time_limit(0);
include 'instagram.class.php';
include 'instagram_config.php';

$username = 'USERNAME';   // your instagram username
$password = 'PASSWORD';  // your instagram password 

$insta = new instagram();
$response = $insta->Login($username, $password);


if(strpos($response[1], "Sorry")) {
    echo "Request failed, there's a chance that this proxy/ip is blocked";
    print_r($response);
    exit();
}         
if(empty($response[1])) {
    echo "Empty response received from the server while trying to login";
    print_r($response);    
    exit();    
}

$search = $searchtag[array_rand($searchtag)];
$res = $insta->SearchTag($search);

$decode = json_decode($res[1], true); 
$i=0;

foreach($decode['items'] as $data)  {
    $i++;
    $d = explode("_", $data['id']);
    $media_id = $d[0];
    $user_id = $d[1];
    $like_count = $data['like_count'];
    $comment_count = $data['comment_count'];
    $username = $data['user']['username'];
    $haslike = $data['has_liked'];

    if ($i<40)  {
        if ($like_count < 20 )  {
            $fakecomment = $hello[array_rand($hello)].' '.'@'. $username . ' ' . $praise[array_rand($praise)];
            $fres=$insta->IsFriend($user_id);
            $friend = json_decode($fres[1], true); 

                // auto follow, like and comment
            if (!$friend['following'] && !$friend['is_private'] && !$friend['outgoing_request'])  {
                $res=$insta->PostFollow($user_id);
                echo "<br> after follow";
                if (!$haslike) {
                    echo "<br> All auto comment, post, Like";
                    sleep(rand(3,10));
                    $res=$insta->PostLike($media_id);
                    sleep(rand(3,10));
                    $res=$insta->PostComment($fakecomment, $media_id);    
                    sleep(rand(3,10));    
                }                
            } else {
                //only like
                    if (!$haslike) {
                    echo "<br> Like only";
                    sleep(rand(3,10));
                    $res=$insta->PostLike($media_id);    
                    }
            }
        }
    }
    unset($res);    
}

exit();
?>

Upload all the files in your linux server after editing and add a cron to the file "instagram_follow.php" for every 3Hours (Preferred).

For the first time when you will run this bot your instagram account may ask to confirm the location. I personally use this script for my account @MarwadiWriter

You can download all the files from here

PS: I don't take any responsibilities of your instagram accounts. Use at your own risk!

 
Share this