user13286
user13286

Reputation: 3075

Possible to leverage Twitter 1.1 API to pull in tweets with a certain hashtag from one specific user?

I am trying to display tweets from one specific user, but only the tweets which contain a specific hashtag. I've been able to get it working one way or the other, but cannot figure out how to get it from both(if it's even possible).

Here is my code so far which pulls all the tweets from a specific user:

<?php
require_once("twitteroauth.php");

$twitteruser = "xxxxxxxx";
$notweets = 5;
$consumerkey = "xxxxxxxxxxx";
$consumersecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstoken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstokensecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

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

Is there any way to modify this code in order to only pull tweets from this single user which have a specific hashtag?

Upvotes: 0

Views: 118

Answers (1)

APAD1
APAD1

Reputation: 13666

Instead of using the user_timeline API url, you can use the "search tweets" URL and just place the Twitter user's handle into the search query along with the hashtag. Something like this:

<?php
require_once("twitteroauth.php");

$twitteruser = "xxxxxxxx";
$hashtag = "xxxx"; //put the hashtag you want to search for here
$notweets = 5;
$consumerkey = "xxxxxxxxxxx";
$consumersecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstoken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstokensecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

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/search/tweets.json?q=%40".$twitteruser."%20%23".$hashtag."&count=".$notweets);

echo json_encode($tweets);
?>

Upvotes: 1

Related Questions