/** * @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 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; }
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; }
function reply_tweet($tweetID, $message) { $connection = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET, TWITTER_TOKEN, TWITTER_TOKEN_SECRET); $response = $connection->post("statuses/update", array("in_reply_to_status_id" => $tweetID, "status" => $message)); if (isset($response->errors)) { var_dump($response->errors); return false; } else { return $response->id; } }
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; }
* read from cache file provided it exists */ require_once "lib/TwitterOAuth/TwitterOAuth.php"; require_once "lib/TwitterOAuth/Exception/TwitterException.php"; require_once "conf/config.php"; 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 = ""; }
/* friends/ids */ $method = 'friends/ids'; twitteroauth_row($method, $connection->get($method), $connection->http_code); /* friends/ids */ $method = 'friends/ids'; twitteroauth_row($method, $connection->get($method), $connection->http_code); /** * Account Methods. */ twitteroauth_header('Account Methods'); /* account/verify_credentials */ $method = 'account/verify_credentials'; twitteroauth_row($method, $connection->get($method), $connection->http_code); /* account/rate_limit_status */ $method = 'account/rate_limit_status'; twitteroauth_row($method, $connection->get($method), $connection->http_code); /* account/update_profile_colors */ $parameters = array('profile_background_color' => 'fff'); $method = 'account/update_profile_colors'; twitteroauth_row($method, $connection->post($method, $parameters), $connection->http_code, $parameters); /* account/update_profile */ $parameters = array('location' => 'Teh internets'); $method = 'account/update_profile'; twitteroauth_row($method, $connection->post($method, $parameters), $connection->http_code, $parameters); /** * OAuth Methods. */ twitteroauth_header('OAuth Methods'); /* oauth/request_token */ $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); twitteroauth_row('oauth/reqeust_token', $oauth->getRequestToken(), $oauth->http_code);
<?php require_once __DIR__ . '/TwitterOAuth/TwitterOAuth.php'; require_once __DIR__ . '/TwitterOAuth/Exception/TwitterException.php'; use TwitterOAuth\TwitterOAuth; 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');
<?php /* Start session and load library. */ session_start(); require_once dirname(__DIR__) . '/TwitterOAuth.php'; require_once __DIR__ . '/config.php'; use twitteroauth\TwitterOAuth; /* Build TwitterOAuth object with client credentials. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); $connection->enableDebug(); // uncomment to collect additional debug info /* Get temporary credentials. */ try { $request_token = $connection->getRequestToken(OAUTH_CALLBACK); /* Save temporary credentials to session. */ $_SESSION['oauth_token'] = $token = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; /* Build authorize URL and redirect user to Twitter. */ $url = $connection->getAuthorizeURL($token); header('Location: ' . $url); } catch (\OAuthException $e) { $responseInfo = $connection->getLastResponseInfo(); echo "Could not connect to Twitter ({$e->getMessage()}). Refresh the page or try again later."; ///* uncomment for some additional debug info echo "<pre>Response:\n" . print_r($responseInfo, true) . "\n\nSESSION:\n" . print_r($_SESSION, true) . "\n" . print_r($connection->getDebugInfo(), true) . "\n</pre>\n"; //*/ }
* @file * Take the user when they return from Twitter. Get access tokens. * Verify credentials and redirect to based on response from Twitter. */ /* Start session and load lib */ session_start(); require_once dirname(__DIR__) . '/TwitterOAuth.php'; require_once 'config.php'; use twitteroauth\TwitterOAuth; /* If the oauth_token is old redirect to the connect page. */ if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) { $_SESSION['oauth_status'] = 'oldtoken'; header('Location: ./clearsessions.php'); } /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); /* Request access tokens from twitter */ $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']); /* Save the access tokens. Normally these would be saved in a database for future use. */ $_SESSION['access_token'] = $access_token; /* Remove no longer needed request tokens */ unset($_SESSION['oauth_token']); unset($_SESSION['oauth_token_secret']); $response_info = $connection->getLastResponseInfo(); /* If HTTP response is 200 continue otherwise send to connect page to retry */ if (200 == $response_info['http_code']) { /* The user has been verified and the access tokens can be saved for future use */ $_SESSION['status'] = 'verified'; header('Location: ./index.php'); } else { /* Save HTTP status for error dialog on connnect page.*/
<?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 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"); $lists = new Lib\Lists(); $entrys = $lists->getShortKeys(); foreach ($entrys as $entry) { #$user = $tw->get("users/lookup", array("user_id"=>$entry["userid"])); #$username = $user[0]->screen_name; $tw->post("direct_messages/new", array("user_id" => $entry["userid"], "text" => "Dein Key ist " . $entry["shortkey"] . "")); $lists->createLongKey($entry["userid"]); #var_dump($user); }
<?php require_once "conn.php"; require_once "db_handler.php"; require_once "twitteroauth/autoload.php"; use TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET, TWITTER_TOKEN, TWITTER_TOKEN_SECRET); /* $ret = db_query("Twitter_Follower", array("UserID"), "screen_name = '' LIMIT 150"); //var_dump($ret); if (!$ret->{'Status'}) { foreach ($ret->{'Results'} as $item) { $response = $connection->get("users/show", array("user_id" => $item->{'UserID'})); if (isset($response->errors)) { var_dump($response->errors); //return false; } else { if ($response->followers_count > 20 && $response->statuses_count > 50 && strtotime('-10 days') < strtotime($response->status->created_at)) { $friend = $connection->post("friendships/create", array("user_id" => $item->{'UserID'})); if (isset($friend->errors)) { var_dump($friend->errors); } else {
<?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);
<?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';