Twitter API V2 使用 PHP 创建带媒体的推文

huangapple go评论112阅读模式
英文:

Twitter API V2 create tweet with media PHP

问题

经过一段时间的研究,我找到了如何使用新的 API V2 创建推文的方法,但是新版本不支持在文本中发送媒体。这是我的发送纯文本的代码,但我真的需要能够附带一张图片。

require '../vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;


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

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

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

var_dump($content);

我正在使用 twitteroauth.com 进行安装,只需执行以下命令:

composer require abraham/twitteroauth
英文:

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 Abraham\TwitterOAuth\TwitterOAuth;


$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

答案1

得分: 3

我找到了一个解决方案...以下是用于创建带媒体的推文的代码...需要使用 API V1 上传媒体,然后使用 ID 创建 V2 推文...

require '../vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

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

下面是您需要使用的令牌的图片,只有这些:

Twitter API V2 使用 PHP 创建带媒体的推文

英文:

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 Abraham\TwitterOAuth\TwitterOAuth;


$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:

Twitter API V2 使用 PHP 创建带媒体的推文

huangapple
  • 本文由 发表于 2023年6月19日 16:08:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定