jQuery 设置 Twitter API,获取最近的几条推文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17049821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:19:45  来源:igfitidea点击:

Setting up Twitter API, getting the last few Tweets

javascriptjquerytwittertwitter-oauth

提问by AnchovyLegend

I am completely new to using Twitter in general and have never embedded "latest tweets" on any project. I am simply trying to embed the 3-4 newest tweets on the site footer with no additional features of functionality. I have been researching how to do this for quite some time now and having some trouble.

我对使用 Twitter 完全陌生,从未在任何项目中嵌入“最新推文”。我只是想在网站页脚上嵌入 3-4 条最新的推文,而没有其他功能特性。一段时间以来,我一直在研究如何做到这一点,但遇到了一些麻烦。

I added the following code snippet to the project, which works quite well, however, I am not sure how to update the snippet so it uses my Twitter account instead of the one it is set up with.

我将以下代码片段添加到项目中,效果很好,但是,我不确定如何更新片段,因此它使用我的 Twitter 帐户而不是它设置的帐户。

    <div id="twitter_update_list">
    </div>
    <script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stackoverflow&include_rts=true&count=4&callback=twitterCallback2">
    </script>

In addition, I keep reading that the most commonly used Twitter API will stop working soon because Twitter wants people to use their own, as opposed to third party.

此外,我一直在读到,最常用的 Twitter API 将很快停止工作,因为 Twitter 希望人们使用自己的 API,而不是第三方。

I am not sure how to proceed from here. I would greatly appreciate any suggestions in this regard. To recap, all I am trying to do is grab the 3-4 latest tweets from my account.

我不知道如何从这里开始。我将不胜感激在这方面的任何建议。回顾一下,我要做的就是从我的帐户中获取 3-4 条最新的推文。

many thanks in advance!

提前谢谢了!

回答by Starboy

So you REALLY don't want to do this client-side anymore. (Just went through numerous docs, and devs suggest to do all oAuth server-side)

所以你真的不想再做这个客户端了。(刚刚浏览了大量文档,开发人员建议在服务器端进行所有 oAuth)

What you need to do:

你需要做什么:

First: sign up on https://dev.twitter.com, and make a new application.

首先:在https://dev.twitter.com 上注册,并创建一个新的应用程序。

Second: NOTE: Your Consumer Key / Secret along with Access Token / Secret

第二:注意:您的消费者密钥/秘密以及访问令牌/秘密

Third: Download Twitter OAuth Library (In this case I used the PHP Library https://github.com/abraham/twitteroauth, additional libraries located here: https://dev.twitter.com/docs/twitter-libraries)

第三:下载 Twitter OAuth 库(在这种情况下,我使用了 PHP 库https://github.com/abraham/twitteroauth,其他库位于:https: //dev.twitter.com/docs/twitter-libraries

Fourth: (If using PHP) Make sure cURL is enabled if your running on a LAMP here's the command you need:

第四:(如果使用 PHP)如果您在 LAMP 上运行,请确保启用了 cURL,这是您需要的命令:

sudo apt-get install php5-curl

Fifth: Make a new PHP file and insert the following: Thanks to Tom Elliot http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/

第五:创建一个新的 PHP 文件并插入以下内容:感谢 Tom Elliot http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/

<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3

$twitteruser = "twitterusername"; //user name you want to reference
$notweets = 30; //how many tweets you want to retrieve
$consumerkey = "12345"; //Noted keys from step 2
$consumersecret = "123456789"; //Noted keys from step 2
$accesstoken = "123456789"; //Noted keys from step 2
$accesstokensecret = "12345"; //Noted keys from step 2

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

echo json_encode($tweets);
echo $tweets; //testing remove for production   
?>

And boom, you're done. I know this isn't a pure js solution but again reading through the new Twitter API 1.1 docs they REALLY don't want you to do this client-side. Hope thishelps!

繁荣,你完成了。我知道这不是纯 js 解决方案,但再次阅读新的 Twitter API 1.1 文档,他们真的不希望您在客户端执行此操作。希望这有帮助!

回答by Rauli Rajande

How to get last few tweets of user with core PHP functionality only (no CURL or Twitter oAuth library needed):

如何仅使用核心 PHP 功能获取用户的最后几条推文(不需要 CURL 或 Twitter oAuth 库):

  1. Register your app/webpage https://apps.twitter.com(You may need to verify your personal account mobile number too)

  2. Note Consumer Key and Consumer Secret

  3. PHP Code:

    // auth parameters
    $api_key = urlencode('REPLACEWITHAPPAPIKEY'); // Consumer Key (API Key)
    $api_secret = urlencode('REPLACEWITHAPPAPISECRET'); // Consumer Secret (API Secret)
    $auth_url = 'https://api.twitter.com/oauth2/token'; 
    
    // what we want?
    $data_username = 'Independent'; // username
    $data_count = 10; // number of tweets
    $data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';
    
    // get api access token
    $api_credentials = base64_encode($api_key.':'.$api_secret);
    
    $auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
                    'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";
    
    $auth_context = stream_context_create(
        array(
            'http' => array(
                'header' => $auth_headers,
                'method' => 'POST',
                'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
            )
        )
    );
    
    $auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
    $auth_token = $auth_response['access_token'];
    
    // get tweets
    $data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );
    
    $data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);
    
    // result - do what you want
    print('<pre>');
    print_r($data);
    
  1. 注册您的应用程序/网页https://apps.twitter.com(您可能还需要验证您的个人帐户手机号码)

  2. 注意消费者密钥和消费者秘密

  3. PHP代码:

    // auth parameters
    $api_key = urlencode('REPLACEWITHAPPAPIKEY'); // Consumer Key (API Key)
    $api_secret = urlencode('REPLACEWITHAPPAPISECRET'); // Consumer Secret (API Secret)
    $auth_url = 'https://api.twitter.com/oauth2/token'; 
    
    // what we want?
    $data_username = 'Independent'; // username
    $data_count = 10; // number of tweets
    $data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';
    
    // get api access token
    $api_credentials = base64_encode($api_key.':'.$api_secret);
    
    $auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
                    'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";
    
    $auth_context = stream_context_create(
        array(
            'http' => array(
                'header' => $auth_headers,
                'method' => 'POST',
                'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
            )
        )
    );
    
    $auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
    $auth_token = $auth_response['access_token'];
    
    // get tweets
    $data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );
    
    $data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);
    
    // result - do what you want
    print('<pre>');
    print_r($data);
    

Tested with XAMPP for Windows and Centos6 default installation (PHP 5.3)

使用 XAMPP for Windows 和 Centos6 默认安装(PHP 5.3)测试

Most probable problem with this might be that openssl is not enabled in php.ini

最可能的问题可能是 php.ini 中未启用 openssl

To fix check if extension=php_openssl.dll or extension=php_openssl.so line is present and uncommented in php.ini

修复检查 extension=php_openssl.dll 或 extension=php_openssl.so 行是否存在且在 php.ini 中未注释

回答by Hakes

Actually twitter has many restrictions, as there is lot of contest from companies like Nike and others. The reading of tweet is limited in the sense that if you are reading through the latest API its actually a bit behind time.

实际上推特有很多限制,因为有很多来自耐克等公司的竞争。从某种意义上说,推文的阅读是有限的,如果你正在阅读最新的 API,它实际上有点落后。

They have also controlled the DM delay which means you cannot DM instantly even if you do, the other party will only receive after X amount of time. If you do through script, and even if you try to DM a lot from one single ip twitter will simply BLOCK you.

他们还控制了DM延迟,这意味着即使您这样做也无法立即进行DM,对方只能在X时间后才能收到。如果您通过脚本进行操作,即使您尝试从一个单一的 ip 进行大量 DM,twitter 也会简单地阻止您。