Telegram - . ? :)

Merion Networks

Recently one idea came up into our minds if its possible to integrate Asterisk and Instagram with following scenario when any call goes to PBX, Asterisk is looking in PHP script via AGI with CallerID, and, simultaneously script is drawing the picture according to preconfigured draft. On this picture you can see CallerID and call date and then send it through API to Instagram and we decided to try this a bit insane concept.

We are sure, that we both have one question in our heads how it can help you and how it might be used in your infrastructure, so we decided not to spend our resources on this possibly useless idea. But one of our engineers decided to give it a chance so please read it and hopefully you will enjoy it!

So this article serves for only educational purpose and cant be used in daily basis in your office Asterisk system.

Creation of AGI PHP script

There will be three files:

  1. instagram.php - script, where we will get CallerID from AGI CallerID, referring to image generation script which will send the data to Instagram;
  2. generate_pic.php - script,which generates picture with applied CallerID and call date;
  3. pic.jpg - draft picture, which will be completed with call date and CallerID;

Just for information, example of picture pic.jpg is below:

Picture for  Asterisk and Instagram integration
One very important moment the picture should be in square format for example, 600x600.

So, lets look on some code. Main points will be commented in following fashion with \:

#!/usr/bin/php -q
$agi = new AGI(); 
$cid = $agi->request['agi_callerid']; \ parsing CallerID from AGI and writing it to $cid variable;
copy(dirname( __FILE__ )."/pic.jpg", dirname( __FILE__ )."/picc.jpg"); \ copying our picture draft to the same one, but with the name picc.jpg. It would be deleted after post creation in Instagram;
$input = "$cid&pic=../../home/admin/instagram/pic.jpg"; \referring to script generate_pic.php, while transmitting there via variable num CallerID, and in variable pic = picture, on which well put our data. Script will return us a picture with overlaid text. Pay an attention on  filesystem way /home/admin/instagram/pic.jpg  there will be uploaded draft picture;
$output = dirname( __FILE__ )."/picc.jpg";
file_put_contents($output, file_get_contents($input)); \ putting call date and CallerID to file picc.jpg, which was created earlier;
$image = dirname( __FILE__ )."/picc.jpg"; 
$date = date("Y-m-d H:i:s"); \ generating call date - as AGI is referring to script during phone call, it will be very precise;
$text = "Incoming call from $date from number $cid"; \ generating data for  Instagram;
function SendRequest($url, $post, $post_data, $user_agent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ''.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return array($http, $response);

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

function GenerateUserAgent() {
    $resolutions = array('720x1280', '320x480', '480x800', '1024x768', '1280x720', '768x1024', '480x320');
    $versions = array('GT-N7000', 'SM-N9000', 'GT-I9220', 'GT-I9100');
    $dpis = array('120', '160', '320', '240');

    $ver = $versions[array_rand($versions)];
    $dpi = $dpis[array_rand($dpis)];
    $res = $resolutions[array_rand($resolutions)];

    return 'Instagram 4.'.mt_rand(1,2).'.'.mt_rand(0,2).' Android ('.mt_rand(10,11).'/'.mt_rand(1,3).'.'.mt_rand(3,5).'.'.mt_rand(0,5).'; '.$dpi.'; '.$res.'; samsung; '.$ver.'; '.$ver.'; smdkc210; en_US)';

function GenerateSignature($data) {
    return hash_hmac('sha256', $data, 'b4a23f5e39b5929e0666ac5de94c89d1618a2916');

function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $post_data = array('device_timestamp' => time(),
            'photo' => '@'.$filename);
        return $post_data;

function sendInstagramm($filename, $caption) // creating the function with two input parameters  file and text, which will create the post in Instagram;
    $username = 'your_instagram_login'; // please state there login from your Instagram account;
    $password = 'your_instagram password'; // please state there password from your Instagram account;

$agent = GenerateUserAgent();
    $guid = GenerateGuid();
    $device_id = "android-" . $guid;
    $data = '{"device_id":"' . $device_id . '","guid":"' . $guid . '","username":"' . $username . '","password":"' . $password . '","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
    $sig = GenerateSignature($data);
    $data = 'signed_body=' . $sig . '.' . urlencode($data) . '&ig_sig_key_version=4';
    $login = SendRequest('accounts/login/', true, $data, $agent, false);
    $text = '';

    if (strpos($login[1], "Sorry, an error occurred while processing this request.")) {
        $text .= "Request failed, there's a chance that this proxy/ip is blocked";
        return $text;

    if (empty($login[1])) {
        $text .= "Empty response received from the server while trying to login";
        return $text;
    $obj = @json_decode($login[1], true);

    if (empty($obj)) {
        $text .= "Could not decode the response" ;
        return $text;
    $data = GetPostData($filename);
    $post = SendRequest('media/upload/', true, $data, $agent, true);

    if (empty($post[1])) {
        $text .= "Empty response received from the server while trying to post the image";
        return $text;
    $obj = @json_decode($post[1], true);

    if (empty($obj)) {
        $text .= "Could not decode the response";
        return $text;
    $status = $obj['status'];

    if ($status != 'ok') {
        $text .= "Status isn't okay";
        return $text;

    $media_id = $obj['media_id'];
    $device_id = "android-" . $guid;

    $data = (object)array(
        'device_id' => $device_id,
        'guid' => $guid,
        'media_id' => $media_id,
        'caption' => trim($caption),
        'device_timestamp' => time(),
        'source_type' => '5',
        'filter_type' => '0',
        'extra' => '{}',
        'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
    $data = json_encode($data);
    $sig = GenerateSignature($data);
    $new_data = 'signed_body=' . $sig . '.' . urlencode($data) . '&ig_sig_key_version=4';

    $conf = SendRequest('media/configure/', true, $new_data, $agent, true);
	print_r ($conf);

    if (empty($conf[1])) {
        $text .= "Empty response received from the server while trying to configure the image";
    } else {
        if (strpos($conf[1], "login_required")) {
            $text .= "You are not logged in. There's a chance that the account is banned";
        } else {
            $obj = @json_decode($conf[1], true);
            $status = $obj['status'];
            if ($status != 'fail') {
                $text .= "Success";
            } else {
                $text .= 'Fail';
    return $text;
sendInstagramm($image, $text); \ calling posting function;
unlink(dirname( __FILE__ )."/picc.jpg"); \ deleting created earlier image file picc.jpg as it wont be required anymore;
Download AGI - script
If you will download it, please change file extension from .txt to .php

Ok, weve completed the hardest part. Now save this script as Instagram.php and put it to following folder: /var/lib/asterisk/agi-bin. For this purpose you can use WinSCP, for example. Then it should be followed by for a few commands via SSH session to your Asterisk server:

dos2unix /var/lib/asterisk/agi-bin/instagram.php
chown asterisk:asterisk /var/lib/asterisk/agi-bin/instagram.php
chmod 775 /var/lib/asterisk/agi-bin/instagram.php

Now we need to put our draft picture on our Asterisk server for following path: /home/admin/instagram/pic.jpg the same as it is described in script and providing equal permissions for this file. Now we starting to prepare picture generation PHP script.

Picture generation in PHP

Now we will generate picture on PHP language. First step is to create a file generate_pic.php and add code above, which is also commented:

function writeTextOnImage($filename, $text)  \ function with two input parameters -  picture and text which will be overlaid on initial picture;
    $size_img = getimagesize($filename);  
    if ($size_img[2]==2)       $src_img = imagecreatefromjpeg($filename);  
    else if ($size_img[2]==1)  $src_img = imagecreatefromgif($filename);  
    else if ($size_img[2]==3)  $src_img = imagecreatefrompng($filename);    
    $color = imagecolorallocatealpha($src_img, 0, 0, 0, 0);  
    $font_file = "2211.ttf";  //.ttf file with required font;
    $img_x = imagesx($src_img); 
    $img_y = imagesy($src_img);     
    $height_font = 28;
    $angle = 0;
    $box = imagettftext($src_img, $height_font, $angle, $img_x - 500, $img_y - 350, $color, $font_file, $text);  \ here you can adjust picture position  on X and Y axis (shofted for  $img_x - 500, $img_y - 350);
    if ($size_img[2]==2)  
        header ("Content-type: image/jpeg");  
    else if ($size_img[2]==1)  
        header ("Content-type: image/gif");  
    else if ($size_img[2]==3)  
        header ("Content-type: image/png");  
    return true;  
$pic = $_GET['pic']; \ getting path to picture;
$num = $_GET['num']; \ getting CallerID;
$img = "../../$pic"; \ relative path to picture;
$date = date("Y-m-d H:i:s"); \ generating call date;
writeTextOnImage($img, "CallFrom: $num\n  CallDate&Time:\n  $date\n\n\n\n");  \ function calling;
Download generation script

Now you need to create a following directory on your Asterisk server /var/www/html/insta. Here you need to put generated script generate_pic.php and font file 2211.ttf, and then set required file permissions:

You can call the files anyway you want, but it is mandatory to change it in scripts also.
dos2unix /var/www/html/insta/generate_pic.php
chown asterisk:asterisk /var/www/html/insta/generate_pic.php
chown asterisk:asterisk /var/www/html/insta/2211.ttf
chmod 775 /var/www/html/insta/generate_pic.php
chmod 775 /var/www/html/insta/2211.ttf

How to call the script from dialplan

So now we need to perform the easiest operation call script instagram.php from Asterisk dial plan. It can be performed with following code:

exten => _.,n,AGI(instagram.php)

Thats all our script located on our incoming trunk in testing circuit. Now we are making phone call from our mobile and checking Instagram account:

Asterisk and Instagram integrations

Lets take a closer look on our post we need to check the signature:

picture in Instagram from Asterisk