需要帮助更新Abraham Twitteroauth v2的GET Feed。

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

Need help updating Abraham Twitteroauth v2 GET Feed

问题

我使用Abraham TwitterOAuth v1.1创建了一个WordPress插件,现在我正在尝试将其更新到v2,但在文档中如何实现对TwitterOAuth的更改方面感到困惑。以下是我的v1.1代码,其中有一些更改以隐藏我的凭据:

function my_twitter_feed_shortcode() {  
    
    // Twitter API凭据
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';

    // 创建TwitterOAuth实例
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);  

    // 使用API获取推文
    $tweets = $connection->get('statuses/user_timeline', ['screen_name' => 'XXXXXX', 'count' => 10]);
   
    // 为推文生成HTML标记
    $html = '<ul>';
    foreach ($tweets as $tweet) {
        $html .= '<li>' . $tweet->text . '</li>';
    }
    $html .= '</ul>';

    // 返回生成的HTML
    return $html;
}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');

因此,在更新为v2后,$connection->setApiVersion('2'); 获取推文不再起作用。我还更新了代码以尝试使用演示v2代码并测试我的结果:$tweets = $connection->get('users', ['ids' => ######]);,所以更新后的代码现在是:

function stride_twitter_feed_shortcode() {  
    
    // Twitter API凭据
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';

    // 创建TwitterOAuth实例
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

    // 设置API版本为2
    $connection->setApiVersion('2');

    // 使用API获取推文
    $tweets = $connection->get('users', ['ids' => ######]);    
    
    // 为推文生成HTML标记
    $html = '<ul>';
    foreach ($tweets as $tweet) {
        $html .= '<li>' . $tweet->text . '</li>';
    }
    $html .= '</ul>';

    // 返回生成的HTML
    return $html;
}
add_shortcode('stride_twitter_feed', 'stride_twitter_feed_shortcode');

虽然在调试时返回了ID、名称和用户名(不会在屏幕上返回任何内容,所以仍然需要弄清楚这一部分),但我不确定如何像v1.1中那样显示时间线。文档中更新的时间线终点说v2是:/2/users/:id/tweets,但如何在TwitterOAuth中使其工作我尝试了一些不同的方法,但都没有成功,所以任何帮助都会很好。

更新: 感谢@andytela的代码更新,我还添加了一些内容。添加了让Twitter生成我的ID的功能,只需更新twitter_name。我还过滤了回复,显示了带有其名称、句柄、头像的转推。此外,我只需要3个结果,所以我使用了foreach ($tweets->data as $index => $tweet) { 来获取每个推文的索引,然后在最后使用了这个来在达到第3个之后停止(数组索引2):

if ($index === 2) {
    break;
}

以下是我的完整插件代码:

require_once( plugin_dir_path( __FILE__ ) . 'vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;

function my_twitter_feed_shortcode() {     
    
    // Twitter API凭据
    $consumer_key = 'XXXXXX';
    $consumer_secret = 'XXXXXX';
    $access_token = 'XXXXXX';
    $access_token_secret = 'XXXXXX';
    $bearer_token = 'XXXXXX';

    // 创建TwitterOAuth实例
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret, $bearer_token);

    $connection->setApiVersion('2');

    // 使用API获取推文   
    $response = $connection->get('users/by/username/twitter_name');
    $user_id = $response->data->id;
    
    $tweets = $connection->get(
        "users/$user_id/tweets",
        [
            'max_results' => 5,
            'tweet.fields' => 'created_at,author_id,public_metrics,referenced_tweets',
            'expansions' => 'attachments.media_keys,author_id,referenced_tweets.id,referenced_tweets.id.author_id',
            'media.fields' => 'url,public_metrics,organic_metrics',
            'user.fields' => 'public_metrics,profile_image_url,verified',
            'exclude' => 'replies',
        ]
    );

    // 为推文生成HTML标记
    $html = '<div class="twitter_wrap">';
    foreach ($tweets->data as $index => $tweet) {        
        $tweetText = urlencode($tweet->text);
        $shareUrl = 'https://twitter.com/intent/tweet?text=' . $tweetText;
        $tweetDate = date('M j, Y', strtotime($tweet->created_at));
        $tweetTime = date('h:i A', strtotime($tweet->created_at));
        $authorId = $tweet->author_id;
        
        $author = $tweets->includes->users[array_search($authorId, array_column($tweets->includes->users, 'id'))];
        $authorName = $author->name;
        $authorHandle = $author->username;        
        $authorAvatar = $author->profile_image_url;
        $authorVerified = $author->verified;

        
        // 检查推文是否为转推
        if (isset($tweet->referenced_tweets) && !empty($tweet->referenced_tweets)) {
            $retweetedTweetId = $tweet->referenced_tweets[0]->id;
            foreach ($tweets->includes->tweets as $retweetedTweet) {
                if ($retweetedTweet->id === $retweetedTweetId) {
                    $retweetedAuthorId = $retweetedTweet->author_id;
                    foreach ($tweets->includes->users as $retweetedAuthor) {
                        if ($retweetedAuthor->id === $retweetedAuthorId) {
                            // 分配转推作者信息
                            $authorName = $retweetedAuthor->name;
                            $authorHandle = $retweetedAuthor->username;
                            $authorAvatar = $retweetedAuthor

<details>
<summary>英文:</summary>

I created a WordPress plugin using [Abraham TwitterOAuth](https://github.com/abraham/twitteroauth) v1.1 and now I am trying to update it to v2 but getting lost in the Docs on how to implement the changes for TwitterOAuth. Here is my v1.1 code with a few changes to hide my credentials:

function my_twitter_feed_shortcode() {

// Twitter API credentials
$consumer_key = &#39;XXXXXX&#39;;
$consumer_secret = &#39;XXXXXX&#39;;
$access_token = &#39;XXXXXX&#39;;
$access_token_secret = &#39;XXXXXX&#39;;
// Create a TwitterOAuth instance
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);  
// Fetch tweets using the API
$tweets = $connection-&gt;get(&#39;statuses/user_timeline&#39;, [&#39;screen_name&#39; =&gt; &#39;XXXXXX&#39;, &#39;count&#39; =&gt; 10]);
// Generate HTML markup for the tweets
$html = &#39;&lt;ul&gt;&#39;;
foreach ($tweets as $tweet) {
$html .= &#39;&lt;li&gt;&#39; . $tweet-&gt;text . &#39;&lt;/li&gt;&#39;;
}
$html .= &#39;&lt;/ul&gt;&#39;;
// Return the generated HTML
return $html;

}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');

So after updating for v2 `$connection-&gt;setApiVersion(&#39;2&#39;);` fetching the tweets no longer works. I also updated the code to try and use the demo v2 code and test my results: `$tweets = $connection-&gt;get(&#39;users&#39;, [&#39;ids&#39; =&gt; ######]);` so the updated code is now:

function stride_twitter_feed_shortcode() {

// Twitter API credentials
$consumer_key = &#39;XXXXXX&#39;;
$consumer_secret = &#39;XXXXXX&#39;;
$access_token = &#39;XXXXXX&#39;;
$access_token_secret = &#39;XXXXXX&#39;;
// Create a TwitterOAuth instance
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
// Set API Version 2
$connection-&gt;setApiVersion(&#39;2&#39;);
// Fetch tweets using the API
$tweets = $connection-&gt;get(&#39;users&#39;, [&#39;ids&#39; =&gt; ######]);    
// Generate HTML markup for the tweets
$html = &#39;&lt;ul&gt;&#39;;
foreach ($tweets as $tweet) {
$html .= &#39;&lt;li&gt;&#39; . $tweet-&gt;text . &#39;&lt;/li&gt;&#39;;
}
$html .= &#39;&lt;/ul&gt;&#39;;
// Return the generated HTML
return $html;

}
add_shortcode('stride_twitter_feed', 'stride_twitter_feed_shortcode');


While this returns the ID, Name, &amp; Username when debugging (doesn&#39;t return anything to the screen so still have to figure that part out) I am not sure how to show the timeline like in v1.1. The updated Timeline endpoint in the Docs say v2 is: `/2/users/:id/tweets` but how do I get that working in TwitterOAuth? Tried a few different things with no luck, so any help would be great.
**UPDATE:** Updated code thanks to @andytela, I also added a few things. Added the ability to let twitter generate my ID instead, just update `twitter_name`. I also am filtering out replies, showing retweets with their name, handle, avatar. Also I only need 3 results so I used `foreach ($tweets-&gt;data as $index =&gt; $tweet) {` to get the index of each tweet and then at the end I used this to stop once it reached the 3rd one (array index 2):

if ($index === 2) {
break;
}


Here is my full plugin code:

require_once( plugin_dir_path( FILE ) . 'vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;

function my_twitter_feed_shortcode() {

// Twitter API credentials
$consumer_key = &#39;XXXXXX&#39;;
$consumer_secret = &#39;XXXXXX&#39;;
$access_token = &#39;XXXXXX&#39;;
$access_token_secret = &#39;XXXXXX&#39;;
$bearer_token = &#39;XXXXXX&#39;;
// Create a TwitterOAuth instance
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret, $bearer_token);
$connection-&gt;setApiVersion(&#39;2&#39;);
// Fetch tweets using the API   
$response = $connection-&gt;get(&#39;users/by/username/twitter_name&#39;);
$user_id = $response-&gt;data-&gt;id;
$tweets = $connection-&gt;get(
&quot;users/$user_id/tweets&quot;,
[
&#39;max_results&#39; =&gt; 5,
&#39;tweet.fields&#39; =&gt; &#39;created_at,author_id,public_metrics,referenced_tweets&#39;,
&#39;expansions&#39; =&gt; &#39;attachments.media_keys,author_id,referenced_tweets.id,referenced_tweets.id.author_id&#39;,
&#39;media.fields&#39; =&gt; &#39;url,public_metrics,organic_metrics&#39;,
&#39;user.fields&#39; =&gt; &#39;public_metrics,profile_image_url,verified&#39;,
&#39;exclude&#39; =&gt; &#39;replies&#39;,
]
);
// Generate HTML markup for the tweets
$html = &#39;&lt;div class=&quot;twitter_wrap&quot;&gt;&#39;;
foreach ($tweets-&gt;data as $index =&gt; $tweet) {        
$tweetText = urlencode($tweet-&gt;text);
$shareUrl = &#39;https://twitter.com/intent/tweet?text=&#39; . $tweetText;
$tweetDate = date(&#39;M j, Y&#39;, strtotime($tweet-&gt;created_at));
$tweetTime = date(&#39;h:i A&#39;, strtotime($tweet-&gt;created_at));
$authorId = $tweet-&gt;author_id;
$author = $tweets-&gt;includes-&gt;users[array_search($authorId, array_column($tweets-&gt;includes-&gt;users, &#39;id&#39;))];
$authorName = $author-&gt;name;
$authorHandle = $author-&gt;username;        
$authorAvatar = $author-&gt;profile_image_url;
$authorVerified = $author-&gt;verified;
// Check if the tweet is a retweet
if (isset($tweet-&gt;referenced_tweets) &amp;&amp; !empty($tweet-&gt;referenced_tweets)) {
$retweetedTweetId = $tweet-&gt;referenced_tweets[0]-&gt;id;
foreach ($tweets-&gt;includes-&gt;tweets as $retweetedTweet) {
if ($retweetedTweet-&gt;id === $retweetedTweetId) {
$retweetedAuthorId = $retweetedTweet-&gt;author_id;
foreach ($tweets-&gt;includes-&gt;users as $retweetedAuthor) {
if ($retweetedAuthor-&gt;id === $retweetedAuthorId) {
// Assign retweeted author information
$authorName = $retweetedAuthor-&gt;name;
$authorHandle = $retweetedAuthor-&gt;username;
$authorAvatar = $retweetedAuthor-&gt;profile_image_url;
$authorVerified  = $retweetedAuthor-&gt;verified;
// Use retweeted tweet&#39;s date and time
$tweetDate = date(&#39;M j, Y&#39;, strtotime($retweetedTweet-&gt;created_at));
$tweetTime = date(&#39;h:i A&#39;, strtotime($retweetedTweet-&gt;created_at));
// Update the current tweet to the retweeted tweet
$tweet = $retweetedTweet;
break;
}
}
break;
}
}
}
$html .= &#39;
&lt;div class=&quot;twitter_item_wrap&quot;&gt;
&lt;div class=&quot;user_row&quot;&gt;
&lt;div class=&quot;user_avatar_wrap&quot;&gt;
&lt;div class=&quot;avatar&quot;&gt;&lt;img src=&quot;&#39; . $authorAvatar . &#39;&quot; alt=&quot;Avatar&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;user_wrap&quot;&gt; 
&lt;div class=&quot;name&quot;&gt;&#39; . $authorName . &#39; &#39; . ( $authorVerified ? &#39;&lt;i class=&quot;verified_icon&quot;&gt;&lt;/i&gt;&#39; : &#39;&#39; ) . &#39;&lt;/div&gt;
&lt;div class=&quot;handle&quot;&gt;@&#39; . $authorHandle . &#39;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;i class=&quot;twitter_icon&quot;&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;div class=&quot;text&quot;&gt;&#39; . $tweet-&gt;text . &#39;&lt;/div&gt;
&lt;div class=&quot;time_date&quot;&gt;&#39; . $tweetTime . &#39; &amp;bull; &#39; . $tweetDate . &#39;&lt;/div&gt;
&lt;div class=&quot;links_wrap&quot;&gt;
&lt;div class=&quot;reply&quot;&gt;
&lt;a href=&quot;https://twitter.com/intent/tweet?in_reply_to=&#39; . $tweet-&gt;id . &#39;&quot;&gt;
&lt;i&gt;&lt;/i&gt;
&#39; . $tweet-&gt;public_metrics-&gt;reply_count . &#39;
&lt;span class=&quot;tooltip&quot;&gt;Reply&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;retweet&quot;&gt;
&lt;a href=&quot;https://twitter.com/intent/retweet?tweet_id=&#39; . $tweet-&gt;id . &#39;&quot;&gt;
&lt;i&gt;&lt;/i&gt;
&#39; . $tweet-&gt;public_metrics-&gt;retweet_count . &#39;
&lt;span class=&quot;tooltip&quot;&gt;Retweet&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;favorite&quot;&gt;
&lt;a href=&quot;https://twitter.com/intent/like?tweet_id=&#39; . $tweet-&gt;id . &#39;&quot;&gt;
&lt;i&gt;&lt;/i&gt;
&#39; . $tweet-&gt;public_metrics-&gt;like_count . &#39;
&lt;span class=&quot;tooltip&quot;&gt;Like&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;share&quot;&gt;
&lt;a href=&quot;&#39; . $shareUrl . &#39;&quot;&gt;
&lt;i&gt;&lt;/i&gt;
&lt;span class=&quot;tooltip&quot;&gt;Share&lt;/span&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;&#39;;
if ($index === 2) {
break;
}       
}
$html .= &#39;&lt;/div&gt;&#39;;    
// Return the generated HTML
return $html;

}
add_shortcode('my_twitter_feed', 'my_twitter_feed_shortcode');


</details>
# 答案1
**得分**: 1
将这一行更改为:
```php
$tweets = $connection-&gt;get(&quot;users/######/tweets&quot; );

然后只需将循环更改为:

foreach ($tweets-&gt;data as $tweet) {

以获取推文。

英文:

Change this line

$tweets = $connection-&gt;get(&#39;users&#39;, [&#39;ids&#39; =&gt; ######]); 

To this

$tweets = $connection-&gt;get(&quot;users/######/tweets&quot; );

Worked for me

Then just change the loop to this

 foreach ($tweets-&gt;data as $tweet) {

To get the tweets out

huangapple
  • 本文由 发表于 2023年6月9日 03:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434963.html
匿名

发表评论

匿名网友

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

确定