我最终使用了codebird而不是TwitterAPIExchange.php。请看我的回答。
TwitterAPIExchange.php
我正在绞尽脑汁试图弄清楚为什么我的代码不起作用。我可以在推特上发布状态更新,但是当我尝试添加图像时,它似乎永远不会发布带有状态的状态。
在我读过的许多关于此的帖子中,我已经尝试了所有应用媒体示例的帖子,但似乎没有一个有效。
一件事是,其中许多帖子都提到了正在https://api.twitter.com/1.1/statuses/update_with_media.json
的 API 调用 url,根据本文,该 url 已贬值。
新的网址"我认为"只是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,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');