public function getTweets($username, $howMany) { $tweets = $this->api->get('statuses/user_timeline', array('screen_name' => $username, 'exclude_replies' => 'true', 'include_rts' => 'false', 'count' => $howMany)); array_walk($tweets, function (&$tweet) { $tweet = new Tweet((array) $tweet); }); return $tweets; }
/** * @param string $search * * @return TweetStructure[] */ public function getPopularTweets($search = 'popular') { $tweetParams = ['q' => $search, 'count' => 10, 'result_type' => 'popular']; $tweet = new TwitterOAuth($this->tweetConfig); $twitterApiResponse = $tweet->get('search/tweets', $tweetParams); $parsedTweets = $this->parseTweetsData($twitterApiResponse); return $this->composeTweets($parsedTweets); }
public function __construct($term, $date = false) { $date or date('Y-m-d'); $auth = array('consumer_key' => 'KVkrn7uBUMip54GWMUL2gLGT0', 'consumer_secret' => 'VAX4Au52lyrfHk0NYa0qaKZtzEIoQsNjYXGTfv87LzYgTjBU2a', 'oauth_token' => '2361267441-osslrEhA6ZBYpa9h5CEPCJR3AI8UooGpwg0uhi4', 'oauth_token_secret' => 'gaIUmEhOWhkaAcYWScZwSSh28gMo6JeCkm4eeOT8dDMkN', 'output_format' => 'object'); $twitter = new TwitterOAuth($auth); $params = array('q' => $term, 'lang' => 'pt-BR', 'count' => 100); $this->response = $twitter->get('search/tweets', $params); return $this->response; }
public function saveAction() { if (null !== ($response = $this->checkAuth(AdminResources::MODULE, ['Twitter'], AccessManager::UPDATE))) { return $response; } $form = new ConfigurationForm($this->getRequest()); $configurationForm = $this->validateForm($form); $consumer_key = $configurationForm->get('consumer_key')->getData(); $consumer_secret = $configurationForm->get('consumer_secret')->getData(); $screen_name = $configurationForm->get('screen_name')->getData(); $count = $configurationForm->get('count')->getData(); $cache_lifetime = $configurationForm->get('cache_lifetime')->getData(); // $debug_mode = $configurationForm->get('debug_mode')->getData(); $errorMessage = null; $response = null; // Save config values ConfigQuery::write('twitter_consumer_key', $consumer_key, 1, 1); ConfigQuery::write('twitter_consumer_secret', $consumer_secret, 1, 1); ConfigQuery::write('twitter_screen_name', $screen_name, 1, 1); ConfigQuery::write('twitter_count', $count, 1, 1); ConfigQuery::write('twitter_cache_lifetime', $cache_lifetime * 60, 1, 1); // Minutes ConfigQuery::write('twitter_last_updated', 0, 1, 1); if ($screen_name && $consumer_key && $consumer_secret) { if (!extension_loaded('openssl')) { $sslError = $this->getTranslator()->trans("This module requires the PHP extension open_ssl to work.", [], Twitter::DOMAIN_NAME); } else { $config = array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'output_format' => 'array'); try { $connection = new TwitterOAuth($config); $bearer_token = $connection->getBearerToken(); } catch (\Exception $e) { $errorMessage = $e->getMessage(); } try { $params = array('screen_name' => $screen_name, 'count' => 1, 'exclude_replies' => true); $response = $connection->get('statuses/user_timeline', $params); if ($response['error']) { throw new TwitterException($response['error']); } } catch (\Exception $e) { $erroMessage = $this->getTranslator()->trans("Unrecognized screen name", [], Twitter::DOMAIN_NAME); } } } $response = RedirectResponse::create(URL::getInstance()->absoluteUrl('/admin/module/Twitter')); if (null !== $errorMessage) { $this->setupFormErrorContext($this->getTranslator()->trans("Twitter configuration failed.", [], Twitter::DOMAIN_NAME), $errorMessage, $form); $response = $this->render("module-configure", ['module_code' => 'Twitter']); } return $response; }
public function getFeed($options) { $since_time = empty($options['sa_since_time']) ? 1 : $options['sa_since_time']; $config = array('consumer_key' => $options['sa_tw_key'], 'consumer_secret' => $options['sa_tw_secret'], 'oauth_token' => $options['sa_tw_token'], 'oauth_token_secret' => $options['sa_tw_token_secret'], 'output_format' => 'object'); $tw = new TwitterOAuth($config); /** * Returns a collection of the most recent Tweets posted by the user * https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline */ $params = array('screen_name' => $options['sa_tw_screenname'], 'count' => 10, 'since_id' => $since_time, 'exclude_replies' => true); // $params = array( // 'q' => '#freefly', // 'count' => 20, // 'since_id' => $since_id // ); /** * Send a GET call with set parameters */ try { $response = $tw->get('statuses/user_timeline', $params); } catch (TwitterException $e) { return array('error' => 4, 'message' => 'Error fetching Twitter feed: <span class="social-feed-error">' . $e->getMessage() . '</span>'); } // return an array with success = false if $response is empty.. if (count($response) == 0) { return array('error' => 1, 'message' => 'No Twitter items found.'); } $data = array(); $date_added = time(); $since_ids = array(); foreach ($response as $post) { $p = array(); $p['id'] = $post->id; $p['message'] = $post->text; $p['link'] = 'https://www.twitter.com/' . $post->user->screen_name; $p['date_added'] = $date_added; $p['date_created'] = strtotime($post->created_at); $since_ids[] = $post->id; array_push($data, $p); } if (count($data) == 0) { return array('error' => 3, 'message' => 'No new Twitter items found.'); } $res = array('data' => $data, 'since_time' => max($since_ids)); return $res; }
public function getTweets() { $cache_path = realpath('.') . '/cache/tweets'; $last_updated = ConfigQuery::read('twitter_last_updated'); $tweets_file = $cache_path . '/' . Twitter::TWEETS_FILENAME; $tweets = []; // Is the cache stale ? // if( $last_updated + 0 < time() ) if ($last_updated + $this->cache_lifetime < time()) { if (!is_dir($cache_path)) { mkdir($cache_path); chmod($cache_path, 0755); } // Get the tweets $config = ['consumer_key' => $this->consumer_key, 'consumer_secret' => $this->consumer_secret]; try { $connection = new TwitterOAuth($config); $bearer_token = $connection->getBearerToken(); } catch (\Exception $e) { $errorMessage = $e->getMessage(); } try { $params = array('screen_name' => $this->screen_name, 'count' => $this->count, 'exclude_replies' => true); $tweets = $connection->get('statuses/user_timeline', $params); if ($tweets['error']) { throw new TwitterException($tweets['error']); } // Cache tweets unlink($tweets_file); $fh = fopen($tweets_file, 'w'); fwrite($fh, json_encode($tweets)); fclose($fh); // Update cache refresh timestamp ConfigQuery::write('twitter_last_updated', time(), 1, 1); } catch (\Exception $e) { $erroMessage = Translator::getInstance()->trans("Unrecognized screen name", [], Twitter::DOMAIN_NAME); } } else { // Get tweets from the cache $tweets = json_decode(file_get_contents($tweets_file)); } return $tweets; }
<?php use TwitterOAuth\TwitterOAuth; date_default_timezone_set('UTC'); require_once __DIR__ . '/vendor/autoload.php'; include "config/config.php"; $tw = new TwitterOAuth($config); $conf = new Lib\Conf(); //Last ID $lastid = $conf->getValue("lastid"); //Get Screenname if ($conf->getValue("screenName") === False) { echo "Get Screenname\r\n"; $response = $tw->get("account/settings"); $screenName = $response->screen_name; $conf->setValue("screenName", $screenName); } $lists = new Lib\Lists(); if ($lastid !== false) { $response = $tw->get('statuses/mentions_timeline', array("since_id" => $lastid)); } else { $response = $tw->get('statuses/mentions_timeline', array()); } # Loop Tweets foreach ($response as $tweet) { # Set lastid if tweet id is bigger if ($tweet->id_str > $lastid) { $lastid = $tweet->id_str; } #Tweet Pharsen list($listname, $entrys) = $lists->tweetPhrasen($tweet->text);
use TwitterOauth\TwitterOAuth; date_default_timezone_set('UTC'); $cache_filename = "state/twitter_trends"; $trends_json = ""; // If there is no recent cache file, try reading from twitter // (By recent we currently mean modification time < an hour ago) if (!(file_exists($cache_filename) && filemtime($cache_filename) > time() - 3600)) { // Read from Twitter and write to the cache file try { // Instantiate TwitterOAuth class with API tokens $connection = new TwitterOAuth($config['twitter_api_key']); // Get an application-only token $bearer_token = $connection->getBearerToken(); $params = array('id' => 1, 'exclude' => true); // Ask for the trends $trends_json = $connection->get('trends/place', $params); // json_encode in this context is not used to TURN IT INTO JSON, it already // is, but rather to encode any special characters so they won't cause any // trouble when being output $trends_json = json_encode($trends_json); // Write to the cache file file_put_contents($cache_filename, $trends_json); } catch (Exception $e) { // Fetch failed - fallback to file $trends_json = ""; } } if ($trends_json == "") { // Either recent cache file is available, OR the Twitter fetch failed and // we should fallback to file anyway. if (file_exists($cache_filename)) {
*/ /* Load required lib files. */ session_start(); require_once dirname(__DIR__) . '/TwitterOAuth.php'; require_once 'config.php'; use twitteroauth\TwitterOAuth; /* If access tokens are not available redirect to connect page. */ if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) { header('Location: ./clearsessions.php'); } /* Get user access tokens out of the session. */ $access_token = $_SESSION['access_token']; /* Create a TwitterOauth object with consumer/user tokens. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); /* If method is set change API call made. Test is called by default. */ $content = $connection->get('account/rate_limit_status'); echo "Current API hits remaining: {$content->remaining_hits}."; /* Get logged in user to help with tests. */ $user = $connection->get('account/verify_credentials'); $active = FALSE; if (empty($active) || empty($_GET['confirmed']) || $_GET['confirmed'] !== 'TRUE') { echo '<h1>Warning! This page will make many requests to Twitter.</h1>'; echo '<h3>Performing these test might max out your rate limit.</h3>'; echo '<h3>Statuses/DMs will be created and deleted. Accounts will be un/followed.</h3>'; echo '<h3>Profile information/design will be changed.</h3>'; echo '<h2>USE A DEV ACCOUNT!</h2>'; echo '<h4>Before use you must set $active = TRUE in test.php</h4>'; echo '<a href="./test.php?confirmed=TRUE">Continue</a> or <a href="./index.php">go back</a>.'; exit; } function twitteroauth_row($method, $response, $http_code, $parameters = '')
date_default_timezone_set('UTC'); /** * Array with the OAuth tokens provided by Twitter when you create application * * output_format - Optional - Values: text|json|array|object - Default: object */ $config = array('consumer_key' => '01b307acba4f54f55aafc33bb06bbbf6ca803e9a', 'consumer_secret' => '926ca39b94e44e5bdd4a8705604b994ca64e1f72', 'oauth_token' => 'e98c603b55646a6d22249d9b0096e9af29bafcc2', 'oauth_token_secret' => '07cfdf42835998375e71b46d96b4488a5c659c2f', 'output_format' => 'object'); /** * Instantiate TwitterOAuth class with set tokens */ $tw = new TwitterOAuth($config); /** * Returns a collection of the most recent Tweets posted by the user * https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline */ $params = array('screen_name' => 'ricard0per', 'count' => 5, 'exclude_replies' => true); /** * Send a GET call with set parameters */ $response = $tw->get('statuses/user_timeline', $params); var_dump($response); /** * Creates a new list for the authenticated user * https://dev.twitter.com/docs/api/1.1/post/lists/create */ $params = array('name' => 'TwOAuth', 'mode' => 'private', 'description' => 'Test List'); /** * Send a POST call with set parameters */ $response = $tw->post('lists/create', $params); var_dump($response);
<?php error_reporting(E_ALL); ini_set("display_errors", 1); use TwitterOAuth\TwitterOAuth; // Autoload the vendor require __DIR__ . '/vendor/autoload.php'; // Database $dbh = new PDO('sqlite:' . realpath(__DIR__ . '/data/lolspondent.db')); // Twitter $twitter = new TwitterOAuth(['consumer_key' => '[consumer_key]', 'consumer_secret' => '[consumer_secret]', 'oauth_token' => '[oauth_token]', 'oauth_token_secret' => '[oauth_token_secret]', 'output_format' => 'object']); // Params $params = ['q' => 'decorrespondent.nl-filter:retweets', 'lang' => 'nl', 'result_type' => 'recent', 'include_entities' => true, 'count' => 50]; // Get the tweets $response = $twitter->get('search/tweets', $params); // Foreach the tweets foreach ($response->statuses as $r) { foreach ($r->entities->urls as $url) { $exploded = explode("/", $url->expanded_url); if ($exploded[2] == "decorrespondent.nl" && isset($exploded[5])) { $check = $dbh->prepare("SELECT count(id) as count FROM posts WHERE decorrespondent_id = :cid AND hash = :hash"); $query = $check->execute(array(':cid' => $exploded[3], ':hash' => $exploded[5])); if ($check->fetch()['count'] < 1) { $sth = $dbh->prepare("INSERT INTO posts (decorrespondent_id, url, hash) VALUES (:cid, :url, :hash)"); $sth->execute(array(':cid' => $exploded[3], ':url' => $url->expanded_url, ':hash' => $exploded[5])); } } } }
<?php /** * @file * User has successfully authenticated with Twitter. Access tokens saved to session and DB. */ /* Load required lib files. */ session_start(); require_once dirname(__DIR__) . '/TwitterOAuth.php'; require_once __DIR__ . '/config.php'; use twitteroauth\TwitterOAuth; /* If access tokens are not available redirect to connect page. */ if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) { header('Location: ./clearsessions.php'); } /* Get user access tokens out of the session. */ $access_token = $_SESSION['access_token']; /* Create a TwitterOauth object with consumer/user tokens. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); /* If method is set change API call made. Test is called by default. */ $content = $connection->get('account/verify_credentials'); /* Some example calls */ //$connection->get('users/show', array('screen_name' => 'abraham'))); //$connection->post('statuses/update', array('status' => date(DATE_RFC822))); //$connection->post('statuses/destroy', array('id' => 5437877770)); //$connection->post('friendships/create', array('id' => 9436992))); //$connection->post('friendships/destroy', array('id' => 9436992))); /* Include HTML to display on the page */ include 'html.inc';