skip to Main Content

After some time I figure out how to create tweet with the new API V2, but with the new version doesn’t have the possibility to send media with the text. This is my code to send simple text, but I really needs to create with an image.

require '../vendor/autoload.php';
use AbrahamTwitterOAuthTwitterOAuth;


$connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

$data =  [
   'text' => 'Hello world'
];

$connection->setApiVersion('2');
$content = $connection->post("tweets", $data, true);

var_dump($content);

I am using the twitteroauth.com to install just use:

composer require abraham/twitteroauth

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution... here is the code for create a tweet with media... it's necessary to upload the media using the API V1 and after with the id create the tweet with V2...

    require '../vendor/autoload.php';
    use AbrahamTwitterOAuthTwitterOAuth;
    
    
    $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
    
    
    $image = [];
    
    $media = $connection->upload('media/upload', ['media' => 'image/test.jpg']);
    array_push($image, $media->media_id_string);
    
    $data =  [
        'text' => 'Hello world',
        'media'=> ['media_ids' => $image]
    ];
    
    
    $connection->setApiVersion('2');
    $content = $connection->post("tweets", $data, true);
    
    var_dump($content);
    

    Below got a pic with the tokens you need to use, only this:

    enter image description here


  2. using $connection->setApiVersion('2'); getting error as 
    PHP Fatal error:  Uncaught Error: Call to undefined method AbrahamTwitterOAuthTwitterOAuth::setApiVersion() in D:xampphtdocstwitterPHPinit.php:26      
    Stack trace:
    #0 {main}
      thrown in D:xampphtdocstwitterPHPinit.php on line 26
    
    how to solve it 
    <?php
    
    require "vendor/autoload.php";
    
    use AbrahamTwitterOAuthTwitterOAuth;
    
    $consumerKey = 'x';
    $consumerSecret = 'x';
    $accessToken = 'x';
    $accessTokenSecret = 'x';
    
    $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
    $info = $connection->get("account/verify_credentials");
    // var_dump($info);
    
    
    $image = [];
    
    $media = $connection->upload('media/upload', ['media' => './Screenshot 2024-04-30 122819.png']);
    array_push($image, $media->media_id_string);
    
    $data =  [
        'text' => 'Hello world',
        'media'=> ['media_ids' => $image]
    ];
    $connection->setApiVersion('2');
    $content = $connection->post("tweets", $data, true);
    
    // var_dump($content);
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search