HybridAuth отправить твит с изображением

Я использую библиотеку HybridAuth. Я хотел бы иметь возможность публиковать сообщения в моем профиле Twitter, прошедшем проверку подлинности, с изображениями.

Метод setUserStatus хорошо работает для автоматической отправки твита.

Я написал следующий метод:

function setUserStatus( $status, $image )
{
    //$parameters = array( 'status' => $status, 'media[]' => "@{$image}" );
    $parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
    $response  = $this->api->post( 'statuses/update_with_media.json', $parameters );

    // check the last HTTP status code returned
    if ( $this->api->http_code != 200 ){
        throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
    }
 }

Сообщение, которое я получаю из твиттера:

Ой, мы получили ошибку: Не удалось обновить статус пользователя! Твиттер вернул ошибку. 403 Forbidden: Запрос понят, но отклонен.

Как я могу получить более точную информацию об ошибке? Кому-нибудь уже удалось отправить картинку, прикрепленную к твиту?

Спасибо !

Хьюго


person hugsbrugs    schedule 21.11.2013    source источник
comment
эй, ты исправил это?   -  person Junaid Atique    schedule 08.05.2014
comment
нет ! когда я буду над этим работать, я буду напрямую использовать twitter API...   -  person hugsbrugs    schedule 09.05.2014


Ответы (2)


Спасибо @Heena за то, что заставила себя проснуться от этого вопроса, я ЭТО СДЕЛАЛА ;)

function setUserStatus( $status )
{
    if(is_array($status))
    {
        $message = $status["message"];
        $image_path = $status["image_path"];
    }
    else
    {
        $message = $status;
        $image_path = null;
    }

    $media_id = null;

    # https://dev.twitter.com/rest/reference/get/help/configuration
    $twitter_photo_size_limit = 3145728;

    if($image_path!==null)
    {
        if(file_exists($image_path))
        {
            if(filesize($image_path) < $twitter_photo_size_limit)
            {
                # Backup base_url
                $original_base_url = $this->api->api_base_url;

                # Need to change base_url for uploading media
                $this->api->api_base_url = "https://upload.twitter.com/1.1/";

                # Call Twitter API media/upload.json
                $parameters = array('media' => base64_encode(file_get_contents($image_path)) );
                $response  = $this->api->post( 'media/upload.json', $parameters ); 
                error_log("Twitter upload response : ".print_r($response, true));

                # Restore base_url
                $this->api->api_base_url = $original_base_url;

                # Retrieve media_id from response
                if(isset($response->media_id))
                {
                    $media_id = $response->media_id;
                    error_log("Twitter media_id : ".$media_id);
                }

            }
            else
            {
                error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
            }
        }
        else
        {
            error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
        }
    }

    if($media_id!==null)
    {
        $parameters = array( 'status' => $message, 'media_ids' => $media_id );
    }
    else
    {
        $parameters = array( 'status' => $message); 
    }
    $response  = $this->api->post( 'statuses/update.json', $parameters );

    // check the last HTTP status code returned
    if ( $this->api->http_code != 200 ){
        throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
    }
}

Чтобы заставить его работать, вы должны сделать следующее:

$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );

$twitter_status = array(
    "message" => "Hi there! this is just a random update to test some stuff",
    "image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );

Наслаждаться !

person hugsbrugs    schedule 16.11.2014

Я не понял это для гибридной аутентификации, тогда я использовал эту библиотеку https://github.com/J7mbo/twitter-api-php/archive/master.zip

Затем мне удалось использовать код ниже: (появляется в другом месте в стеке)

    <?php
    require_once('TwitterAPIExchange.php');
    $settings= array(
    'oauth_access_token' => '';
    'oauth_access_secret' => '';
    'consumer_key' => '';
    'consumer_secret' => '';
    // paste your keys above properly
    )

    $url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
    $requestMethod = "POST";

    $tweetmsg = $_POST['post_description'];   //POST data from upload form
    $twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload

    $postfields = array(
        'status' => $tweetmsg,
        'media[]' => '@' . $twimg
    );
    try {
        $twitter = new TwitterAPIExchange($settings);
        $twitter->buildOauth($url_media, $requestMethod)
                ->setPostfields($postfields)
                ->performRequest();

        echo "You just tweeted with an image";
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
?>
person Heena Shah    schedule 09.11.2014
comment
чтобы жестко закодировать сообщение и изображение, сделайте так: $tweetmsg=Посмотрите мое новое фото; $twimg=кошачий бой.jpg; - person Heena Shah; 09.11.2014
comment
Привет, update_with_media.json устарел, Twitter API, вам следует рассмотреть возможность использования нового подход с media/upload.json, затем statuses/update.json - person hugsbrugs; 16.11.2014