Skip to content

Commit

Permalink
Add method to post message on a media (refs to #243)
Browse files Browse the repository at this point in the history
  • Loading branch information
pgrimaud committed Sep 20, 2021
1 parent f5250bd commit 4859cc0
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 8 deletions.
28 changes: 28 additions & 0 deletions examples/post-comment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

use Instagram\Api;
use Instagram\Exception\InstagramException;

use Psr\Cache\CacheException;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

require realpath(dirname(__FILE__)) . '/../vendor/autoload.php';
$credentials = include_once realpath(dirname(__FILE__)) . '/credentials.php';

$cachePool = new FilesystemAdapter('Instagram', 0, __DIR__ . '/../cache');

try {
$api = new Api($cachePool);
$api->login($credentials->getLogin(), $credentials->getPassword());

// 2657627124756968810 is id of https://www.instagram.com/p/CThycoMlPVq/
$postId = 2657627124756968810;

$api->commentPost($postId, 'Awesome!');
} catch (InstagramException $e) {
print_r($e->getMessage());
} catch (CacheException $e) {
print_r($e->getMessage());
}
18 changes: 17 additions & 1 deletion src/Instagram/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
Live,
TaggedMediasFeed
};
use Instagram\Transport\{HtmlProfileDataFeed,
use Instagram\Transport\{CommentPost,
HtmlProfileDataFeed,
JsonMediaDetailedDataFeed,
JsonMediasDataFeed,
JsonMediaCommentsFeed,
Expand Down Expand Up @@ -697,4 +698,19 @@ public function getProfileAlternative(int $userId): Profile

return $hydrator->getProfile();
}

/**
* @param int $postId
* @param string $message
*
* @return string
*
* @throws Exception\InstagramAuthException
* @throws Exception\InstagramFetchException
*/
public function commentPost(int $postId, string $message): string
{
$request = new CommentPost($this->client, $this->session);
return $request->comment($postId, $message);
}
}
20 changes: 13 additions & 7 deletions src/Instagram/Transport/AbstractDataFeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ abstract class AbstractDataFeed

/**
* @param ClientInterface $client
* @param Session|null $session
* @param Session|null $session
*
* @throws InstagramAuthException
*/
Expand Down Expand Up @@ -54,7 +54,7 @@ protected function fetchJsonDataFeed(string $endpoint): \StdClass

$res = $this->client->request('GET', $endpoint, $headers);

$data = (string)$res->getBody();
$data = (string) $res->getBody();
$data = json_decode($data);

if ($data === null) {
Expand All @@ -69,9 +69,9 @@ protected function fetchJsonDataFeed(string $endpoint): \StdClass
*
* @throws InstagramFetchException
*/
protected function postJsonDataFeed(string $endpoint): \StdClass
protected function postJsonDataFeed(string $endpoint, array $formParameters = []): \StdClass
{
$headers = [
$options = [
'headers' => [
'user-agent' => UserAgentHelper::AGENT_DEFAULT,
'x-requested-with' => 'XMLHttpRequest',
Expand All @@ -81,9 +81,15 @@ protected function postJsonDataFeed(string $endpoint): \StdClass
'cookies' => $this->session->getCookies(),
];

$res = $this->client->request('POST', $endpoint, $headers);
if (count($formParameters) > 0) {
$options = array_merge($options, [
'form_params' => $formParameters,
]);
}

$res = $this->client->request('POST', $endpoint, $options);

$data = (string)$res->getBody();
$data = (string) $res->getBody();
$data = json_decode($data);

if ($data === null) {
Expand All @@ -108,7 +114,7 @@ private function getRolloutHash(): string
],
]);

$html = (string)$baseRequest->getBody();
$html = (string) $baseRequest->getBody();

preg_match('/<script type="text\/javascript">window\._sharedData\s?=(.+);<\/script>/', $html, $matches);

Expand Down
47 changes: 47 additions & 0 deletions src/Instagram/Transport/CommentPost.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

namespace Instagram\Transport;

use Instagram\Exception\InstagramFetchException;
use Instagram\Utils\Endpoints;

class CommentPost extends AbstractDataFeed
{
/**
* @param int $postId
* @param string $message
*
* @return string
*
* @throws InstagramFetchException
*/
public function comment(int $postId, string $message): string
{
$endpoint = Endpoints::getCommentUrl($postId);
return $this->fetchData($endpoint, $message);
}

/**
* @param string $endpoint
* @param string $message
*
* @return string
*
* @throws InstagramFetchException
*/
private function fetchData(string $endpoint, string $message): string
{
$data = $this->postJsonDataFeed($endpoint, [
'comment_text' => $message,
'replied_to_comment_id' => '',
]);

if (!$data->status) {
throw new InstagramFetchException('Whoops, looks like something went wrong!');
}

return $data->status;
}
}
12 changes: 12 additions & 0 deletions src/Instagram/Utils/Endpoints.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class Endpoints

const PROFILE_URL = 'https://i.instagram.com/api/v1/users/{{userId}}/info/';

const COMMENT_URL = 'https://www.instagram.com/web/comments/{{postId}}/add/';

/**
* @param int $accountId
*
Expand Down Expand Up @@ -89,4 +91,14 @@ public static function getProfileUrl(int $userId): string
{
return str_replace('{{userId}}', (string) $userId, static::PROFILE_URL);
}

/**
* @param int $postId
*
* @return string
*/
public static function getCommentUrl(int $postId): string
{
return str_replace('{{postId}}', (string) $postId, static::COMMENT_URL);
}
}
61 changes: 61 additions & 0 deletions tests/PostCommentTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Instagram\Tests;

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Instagram\Api;
use Instagram\Exception\InstagramFetchException;
use PHPUnit\Framework\TestCase;

class PostCommentTest extends TestCase
{
use GenerateCookiesTrait;

public function testPostComment()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'cookie'], file_get_contents(__DIR__ . '/fixtures/home.html')),
new Response(200, [], file_get_contents(__DIR__ . '/fixtures/login-success.json')),
new Response(200, ['Set-Cookie' => 'cookie'], file_get_contents(__DIR__ . '/fixtures/home.html')),
new Response(200, [], file_get_contents(__DIR__ . '/fixtures/comment-post.json')),
]);

$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);

$api = new Api($this->generateCookiesForFollow(), $client);

$api->login('username', 'password');

$result = $api->commentPost(123455, 'Awesome!');
$this->assertSame('ok', $result);

$api->logout('username');
}

public function testPostCommentWithError()
{
$this->expectException(InstagramFetchException::class);

$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'cookie'], file_get_contents(__DIR__ . '/fixtures/home.html')),
new Response(200, [], file_get_contents(__DIR__ . '/fixtures/login-success.json')),
new Response(200, ['Set-Cookie' => 'cookie'], file_get_contents(__DIR__ . '/fixtures/home.html')),
new Response(200, [], '{"status":""}'),
]);

$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);

$api = new Api($this->generateCookiesForFollow(), $client);

$api->login('username', 'password');

$api->commentPost(123455, 'Awesome!');

$api->logout('username');
}
}
1 change: 1 addition & 0 deletions tests/fixtures/comment-post.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"18091595578284217","from":{"id":"35781928511","username":"rudigerempira","full_name":"Rudiger E.","profile_picture":"https://scontent-arn2-1.cdninstagram.com/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=scontent-arn2-1.cdninstagram.com\u0026_nc_ohc=lcvyX5vEjaAAX8Nk11U\u0026edm=ABmJApABAAAA\u0026ccb=7-4\u0026oh=76314cdf5c3265fe625c55b6865364b7\u0026oe=614F2ECF\u0026_nc_sid=6136e7\u0026ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4"},"text":"Awesome!","created_time":1632144927,"status":"ok"}

0 comments on commit 4859cc0

Please sign in to comment.