Advertisement
Guest User

Post instagram

a guest
Apr 27th, 2017
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.34 KB | None | 0 0
  1. /*Лень - самое главное качество программиста. Если программист не ленивый - он плохой программист.
  2. Да, да. Все именно так. Ведь только очень ленивый человек делает огромную работу единовременно, чтобы в будущем не делать практически ничего.
  3.  
  4. Загружать фотографии в инстаграм мне было лень, но для моего проекта это было бы очень полезно, и я стал искать.
  5.  
  6. В API самого инстаграма нет ничего интересного - поиск по фотографиям, изменение профиля, и все в этом духе. И ни слова как автоматически загрузить фотографию с комментарием.
  7. Это меня очень раздосадовало, и я обратился к своему самому главному помощнику - интернету.
  8.  
  9. После нескольких часов поиска я нашел скрипт который более менее подходил под мои нужды, и немного подправил его.
  10.  
  11. Ну и собственно, хочу поделиться им с вами.
  12. Для того чтобы запостить в инстаграм фотографию и текст нужна следующая функция
  13.  
  14. sendInstagramm($image, $text);
  15. $image - Полный путь до изображения (отправляется с помощью cURL). Изображение должно быть квадратным, и должно быть локальным!
  16. загрузка по ссылке невозможна!
  17. $text - ваш текст. Для вставки переносов применяется "\n", с поддержкой хэштэгов (#тэг)
  18. Как видите - все достаточно просто. В ответ приходит статус, или ошибка (string)
  19.  
  20. Если вам лень пользоваться скриптом, то узнав, что статья пользуется неплохой популярностью, я решил написать сервис IPosting для автоматической публикации изображений в instagram
  21.  
  22. А вот собственно и сам код который все это делает*/
  23.  
  24. <?php
  25.  
  26. function SendRequest($url, $post, $post_data, $user_agent, $cookies) {
  27.     $ch = curl_init();
  28.     curl_setopt($ch, CURLOPT_URL, 'https://instagram.com/api/v1/'.$url);
  29.     curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  30.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  31.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  32.  
  33.     if($post) {
  34.         curl_setopt($ch, CURLOPT_POST, true);
  35.         curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  36.     }
  37.  
  38.     if($cookies) {
  39.         curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
  40.     } else {
  41.         curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
  42.     }
  43.  
  44.     $response = curl_exec($ch);
  45.     $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  46.     curl_close($ch);
  47.  
  48.     return array($http, $response);
  49. }
  50.  
  51. function GenerateGuid() {
  52.     return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  53.         mt_rand(0, 65535),
  54.         mt_rand(0, 65535),
  55.         mt_rand(0, 65535),
  56.         mt_rand(16384, 20479),
  57.         mt_rand(32768, 49151),
  58.         mt_rand(0, 65535),
  59.         mt_rand(0, 65535),
  60.         mt_rand(0, 65535));
  61. }
  62.  
  63. function GenerateUserAgent() {
  64.     $resolutions = array('720x1280', '320x480', '480x800', '1024x768', '1280x720', '768x1024', '480x320');
  65.     $versions = array('GT-N7000', 'SM-N9000', 'GT-I9220', 'GT-I9100');
  66.     $dpis = array('120', '160', '320', '240');
  67.  
  68.     $ver = $versions[array_rand($versions)];
  69.     $dpi = $dpis[array_rand($dpis)];
  70.     $res = $resolutions[array_rand($resolutions)];
  71.  
  72.     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)';
  73. }
  74.  
  75. function GenerateSignature($data) {
  76.     return hash_hmac('sha256', $data, 'b4a23f5e39b5929e0666ac5de94c89d1618a2916');
  77. }
  78.  
  79. function GetPostData($filename) {
  80.     if(!$filename) {
  81.         echo "The image doesn't exist ".$filename;
  82.     } else {
  83.         $post_data = array('device_timestamp' => time(),
  84.             'photo' => '@'.$filename);
  85.         return $post_data;
  86.     }
  87. }
  88.  
  89.  
  90. function sendInstagramm($filename, $caption)
  91. {
  92.     $username = _ВАШ_ЛОГИН_;
  93.     $password = _ВАШ_ПАРОЛЬ_;
  94.  
  95.     $agent = GenerateUserAgent();
  96.     $guid = GenerateGuid();
  97.     $device_id = "android-" . $guid;
  98.     $data = '{"device_id":"' . $device_id . '","guid":"' . $guid . '","username":"' . $username . '","password":"' . $password . '","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
  99.     $sig = GenerateSignature($data);
  100.     $data = 'signed_body=' . $sig . '.' . urlencode($data) . '&ig_sig_key_version=4';
  101.     $login = SendRequest('accounts/login/', true, $data, $agent, false);
  102.     $text = '';
  103.  
  104.     if (strpos($login[1], "Sorry, an error occurred while processing this request.")) {
  105.         $text .= "Request failed, there's a chance that this proxy/ip is blocked";
  106.         return $text;
  107.     }
  108.  
  109.     if (empty($login[1])) {
  110.         $text .= "Empty response received from the server while trying to login";
  111.         return $text;
  112.     }
  113.     $obj = @json_decode($login[1], true);
  114.  
  115.     if (empty($obj)) {
  116.         $text .= "Could not decode the response" ;
  117.         return $text;
  118.     }
  119.     $data = GetPostData($filename);
  120.     $post = SendRequest('media/upload/', true, $data, $agent, true);
  121.  
  122.     if (empty($post[1])) {
  123.         $text .= "Empty response received from the server while trying to post the image";
  124.         return $text;
  125.     }
  126.     $obj = @json_decode($post[1], true);
  127.  
  128.     if (empty($obj)) {
  129.         $text .= "Could not decode the response";
  130.         return $text;
  131.     }
  132.     $status = $obj['status'];
  133.  
  134.     if ($status != 'ok') {
  135.         $text .= "Status isn't okay";
  136.         return $text;
  137.     }
  138.  
  139.     $media_id = $obj['media_id'];
  140.     $device_id = "android-" . $guid;
  141.  
  142.     $data = (object)array(
  143.         'device_id' => $device_id,
  144.         'guid' => $guid,
  145.         'media_id' => $media_id,
  146.         'caption' => trim($caption),
  147.         'device_timestamp' => time(),
  148.         'source_type' => '5',
  149.         'filter_type' => '0',
  150.         'extra' => '{}',
  151.         'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
  152.     );
  153.     $data = json_encode($data);
  154.     $sig = GenerateSignature($data);
  155.     $new_data = 'signed_body=' . $sig . '.' . urlencode($data) . '&ig_sig_key_version=4';
  156.  
  157.     $conf = SendRequest('media/configure/', true, $new_data, $agent, true);
  158.  
  159.     if (empty($conf[1])) {
  160.         $text .= "Empty response received from the server while trying to configure the image";
  161.     } else {
  162.         if (strpos($conf[1], "login_required")) {
  163.             $text .= "You are not logged in. There's a chance that the account is banned";
  164.         } else {
  165.             $obj = @json_decode($conf[1], true);
  166.             $status = $obj['status'];
  167.             if ($status != 'fail') {
  168.                 $text .= "Success";
  169.             } else {
  170.                 $text .= 'Fail';
  171.             }
  172.         }
  173.     }
  174.     return $text;
  175. }
  176. //Вам остается только заменить строки 75 - 76
  177.  
  178. $username = _ВАШ_ЛОГИН_;
  179. $password = _ВАШ_ПАРОЛЬ_;
  180. /*Все - теперь с помощью этого удобного скрипта можно автоматизировать еще один рутинный процесс.
  181. Всем спасибо за внимание.
  182.  
  183. PS
  184.  
  185. Изображение должно быть квадратным
  186. Изображение должно быть локальынм - лежать на машине со скриптом. По ссылке НЕ РАБОТАЕТ.
  187. Не забудьте установить необходимые права на файлы для никсов
  188. Сервис IPosting - для тех кто не умеет, у кого не получается, или кому просто лень ;)*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement