使用 php 通过 Twitter API 发布图像 + 状态

问题描述 投票:0回答:2

我最终使用了 codebird 而不是 TwitterAPIExchange.php。请看我的回答。

TwitterAPIExchange.php

我正在绞尽脑汁试图找出为什么我的代码不起作用。我可以在 Twitter 上发布状态更新,但当我尝试添加图像时,它似乎永远不会与状态一起发布。

我读过很多关于此的帖子,我已经尝试过将它们全部应用到媒体示例中,但似乎都不起作用。

有一件事是,这些帖子中的许多都提到 API 调用 url 是

https://api.twitter.com/1.1/statuses/update_with_media.json
,根据 本文 已被贬值。

新网址“我认为”只是

https://api.twitter.com/1.1/statuses/update.json

此时状态上传正常,但图像从未上传。任何人都可以帮我解决我的代码吗?

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "***",
    'oauth_access_token_secret' => "***",
    'consumer_key' => "***",
    'consumer_secret' => "***"
);
$url = "https://api.twitter.com/1.1/statuses/update.json";

$requestMethod = 'POST'; 

$twimage = '60001276.jpg';

$postfields = array(
    'media[]' => "@{$twimage}",
    'status' => 'Testing Twitter app'
);

$twitter = new TwitterAPIExchange($settings);

$response = $twitter->buildOauth($url, $requestMethod)
                   ->setPostfields($postfields)
                   ->performRequest();

print_r($response);
php twitter oauth
2个回答
13
投票

我最终无法使用此方法并找到了更新的解决方案。我学到的关于使用 php 通过消息发送图像的一件事是,你必须首先将图像加载到 twitter,其中 API 将返回一个

media_id
给你。该
media_id
与图像相关联。获得
media_id
后,即可将该 ID 与您的消息关联起来,并使用
media_id
发送消息。当我了解到这一点后,代码就变得更有意义了。

我使用 codebird 来用 php 实现推文。

您所要做的就是创建一个像这样的函数

function tweet($message,$image) {

// add the codebird library
require_once('codebird/src/codebird.php');

// note: consumerKey, consumerSecret, accessToken, and accessTokenSecret all come from your twitter app at https://apps.twitter.com/
\Codebird\Codebird::setConsumerKey("Consumer-Key", "Consumer-Secret");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("Access-Token", "Access-Token-Secret");

//build an array of images to send to twitter
$reply = $cb->media_upload(array(
    'media' => $image
));
//upload the file to your twitter account
$mediaID = $reply->media_id_string;

//build the data needed to send to twitter, including the tweet and the image id
$params = array(
    'status' => $message,
    'media_ids' => $mediaID
);
//post the tweet with codebird
$reply = $cb->statuses_update($params);

}

下载 API 时,请确保

cacert.pem
与下载时附带的
codebird.php
位于同一目录中,这一点很重要。 不要只是下载
codebird.php

另外请记住 Twitter 有关尺寸和参数的图像和视频指南。

确保您的服务器至少有 php 5.3 版本并启用了curl。如果您不确定自己拥有什么,您可以创建任何

.php
文件并添加
phpinfo();
,这将告诉您 php 配置的所有信息。

一旦一切就绪,那么使用 codebird 发送推文所需要做的就是

tweet('This is my sample tweet message','http://www.example.com/image.jpg');

0
投票

从 2023 年 7 月 19 日开始,1.1 端点已被弃用 根据本文,并且 codebird 库(最后更新于 2018 年 8 月)不再工作。寻找简单的替代方案,如果您有任何想法,请发布。

© www.soinside.com 2019 - 2024. All rights reserved.