Twitter bot using Oauth - twitter

I have a twitter bot, where it searches for an #mention and replies to the user depending on what the user says.
It was working fine until this week, when I started getting this error:
Warning: Invalid argument supplied for foreach() in /home/reportax/public_html/reportaxi/twitterbot/config.php on line 14
I stripped down the code to the most basic form, which is the searching for the #mention and then tweeting something when it finds it, but I'm still getting this error. Any ideas?
As I mentioned before, this was working fine until this week, so I know the consumer key, secret, and all that is OK.
here's the code:
<?php
require_once('twitteroauth.php');
define('CONSUMER_KEY', 'MYKEY');
define('CONSUMER_SECRET', 'MYSECRET');
define('ACCESS_TOKEN', 'MYTOKEN');
define('ACCESS_TOKEN_SECRET', 'MYTOKENSECRET');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$twitter->host = "http://search.twitter.com/";
$search = $twitter->get('search', array('q' => '#repor_taxi', 'rpp' => 15));
$twitter->host = "https://api.twitter.com/1/";
foreach($search->results as $tweet) {
$status = 'RT #'.$tweet->from_user.' '.$tweet->text;
if(strlen($status) > 140) $status = substr($status, 0, 139);
$twitter->post('statuses/update', array('status' => $status));
}
?
any ideas?

I had the same problem. You need update your code for twitter API 1.1.
<?php
require_once('twitteroauth.php');
define('CONSUMER_KEY', 'MYKEY');
define('CONSUMER_SECRET', 'MYSECRET');
define('ACCESS_TOKEN', 'MYTOKEN');
define('ACCESS_TOKEN_SECRET', 'MYTOKENSECRET');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
/*The search has change a little bit */
/* Remove this 2 lines */
/* $twitter->host = "http://search.twitter.com/"; */
/* $search = $twitter->get('search', array('q' => '#repor_taxi', 'rpp' => 15)); */
/* Put this new line */
$search = $twitter->get("https://api.twitter.com/1.1/search/tweets.json?q=#repor_taxi&count=15");
/* The Search URL is https://api.twitter.com/1.1/search/tweets.json?q= */
/* Everything after is parameter */
/* You can check parameters list here: https://dev.twitter.com/docs/using-search */
/* Twitter host updated too */
$twitter->host = "https://api.twitter.com/1.1/";
foreach($search as $tweet) {
...
?>
I hope this may help you. Good luck.

Related

Google API login failed always: back to needing to authorize

I'd like to change my tags of a YouTube video using the YouTube Data API. But I'm already stuck on login:
My page shows the message: You need to authorize access before proceeding. I click on authorize access and select my Google account and then my YouTube channel, I select allow and get redirected to the login message.
The code is directly from the sample files on Github:
<?php
/**
* This sample adds new tags to a YouTube video by:
*
* 1. Retrieving the video resource by calling the "youtube.videos.list" method
* and setting the "id" parameter
* 2. Appending new tags to the video resource's snippet.tags[] list
* 3. Updating the video resource by calling the youtube.videos.update method.
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'myID';
$OAUTH2_CLIENT_SECRET = 'mySec';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE this value with the video ID of the video being updated.
$videoId = "Zqt-NvuMKYU";
// Call the API's videos.list method to retrieve the video resource.
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
// If $listResponse is empty, the specified video was not found.
if (empty($listResponse)) {
$htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
} else {
// Since the request specified a video ID, the response only
// contains one video resource.
$video = $listResponse[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// Preserve any tags already associated with the video. If the video does
// not have any tags, create a new list. Replace the values "tag1" and
// "tag2" with the new tags you want to associate with the video.
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Set the tags array for the video snippet
$videoSnippet['tags'] = $tags;
// Update the video resource by calling the videos.update() method.
$updateResponse = $youtube->videos->update("snippet", $video);
$responseTags = $updateResponse['snippet']['tags'];
$htmlBody .= "<h3>Video Updated</h3><ul>";
$htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
array_pop($responseTags), array_pop($responseTags),
$videoId, $video['snippet']['title']);
$htmlBody .= '</ul>';
}
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Would be great if someone has a tip for me.
Fixed... was a space key inside secret

Auto Post on Twitter after authentication : getting Invalid access token error

Here I need to automatically post on Twitter after authentication.
My code
<?php
session_start();
include("twitteroauth.php");
define('CONSUMER_KEY','zubLdCze6Erz9SVNIgG3w');
define('CONSUMER_SECRET','ZnZQ77bNnpBER2aSxTQGEXToAQODz9qEBSAXIdeYw');
define('OAUTH_CALLBACK','http://dev.pubs.positive-dedicated.net/Licensee/addPubEventWeekly.php');
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$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'];
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
?>
and
ksort($_SESSION);
$tweet = new TwitterOAuth('zubLdCze6Erz9SVNIgG3w','ZnZQ77bNnpBER2aSxTQGEXToAQODz9qEBSAXIdeYw',$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
print_r($tweet);
$account = $tweet->get('account/verify_credentials');
$message = "This is an example twitter post using PHP";
$postVal = $tweet->post('statuses/update', array('status' => $message));
But here I am getting "Invalid/Expired access token" Error.
I have changed twittreauth.php library file also from 1.0 to 1.1 from here
public $host = "https://api.twitter.com/1.1/";
Please suggest how to fix this

twitter bot not showing as retweeted on twitter feed

rather than using the RT prefix to a tweet, Twitter now provides a retweeted sign on retweeted tweets. I would like this to show up on my retweeted tweets on my twitter bot... i.e. the original user information is embedded on the feed in twitter.com/user
this is the code i have so far (using API 1.1):
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$twitter->host = "http://search.twitter.com/";
$search = $twitter->get('search', array('q' => '-escort -RT -ADRTBot #abudhabi', 'count' => 5));
$twitter->host = "https://api.twitter.com/1.1/";
foreach($search->results as $tweet) {
$status = $tweet->text;
if(strlen($status) > 140) $status = substr($status, 0, 139);
$twitter->post('statuses/retweet/$tweet->id', array('status' => $status));
print "STATUS: $tweet->id $status<br>";
}
Any ideas would be gratefully received!!
The above doesn't work... and i'm still struggling to retweet using the new api 1.1.
Here is the revised code i have so far:
<?php
require_once('twitteroauth/twitteroauth.php');
define('CONSUMER_KEY', 'xxxxx');
define('CONSUMER_SECRET', 'xxxxx');
define('ACCESS_TOKEN', 'xxxxx');
define('ACCESS_TOKEN_SECRET', 'xxxxx');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $twitter->get("https://api.twitter.com/1.1/search/tweets.json?q=-escort%20-RT%20-ADRTBot%20abudhabi&count=5");
$twitter->host = "https://api.twitter.com/1.1/";
foreach($tweets as $tweet) {
foreach($tweet as $chirp) {
$id = $chirp->id_str;
//testing that data coming through... and it is
echo "<br>THIS IS THE ID: $id<br>";
echo "statuses/retweet/$id.json<br>";
echo "$chirp->text<br>";
$twitter->post('https://api.twitter.com/1.1/statuses/retweet/$id.json');
}
}
echo json_encode($tweets);
?>
However, it is not posting to twitter... what am i missing?
Many thanks,
R
you should have left the code alone from the original coder. Up until 2 days ago this bot actually worked but due to twitter updates on API 1.1 the bot has stopped functioning and I think it's down to the properties of search.twitter.com though to answer your question
[code]
require_once('twitteroauth.php');
define('CONSUMER_KEY', '\\');
define('CONSUMER_SECRET', '\\');
define('ACCESS_TOKEN', '\\');
define('ACCESS_TOKEN_SECRET', '\\');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$twitter->host = "http://search.twitter.com/";
$search = $twitter->get('search',array('q' => '#abudhabi', 'another hashtag here', 'another keyword here', 'rrp' => 4));
$twitter->host = "https://api.twitter.com/1.1/";
foreach($search->results as $tweet) {
$status = 'RT #'.$tweet->from_user.' '.$tweet->text;
if(strlen($status) > 140) $status = substr($status, 0, 139);
$twitter->post('statuses/update', array('status' => $status));
}
echo "Success! Check your twitter bot for retweets!";
[/code]

Retweet and destroy tweet using twitter API

I am developing an application which can send tweets to my twitter profile.
Now I need to implement retweet and delete tweet function. I implement those like following but no success. can any one help me!!
/* Delete tweet function */
$twitteroauthPost = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$token = $twitteroauthPost->getRequestToken();
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$token['oauth_token'], $token['oauth_token_secret']);
$result = $connection->post('statuses/destroy', array('id' => $postId));
/* Retweet function */
$twitteroauthPost = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$token = $twitteroauthPost->getRequestToken();
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$token['oauth_token'], $token['oauth_token_secret']);
$result = $connection->post('statuses/retweet', array('id' => $postId));
Then it return this
(
[request] => /1/statuses/retweet.json
[error] => Could not authenticate you.
)
This error means that the authorization header that gets sent to twitter is not correct. Since you are using a library that's been tested and is widely used I'm guessing that you have got your CONSUMER_KEY or CONSUMER_SECRET wrong. I'd just double check these.

OAuth H9 Google Health

I am attempting to gain three-legged Oauth access, but I can't get the first step to work. My code so far:
include("OAuth.php");
$consumer_key = "anonymous";
$consumer_secret = "anonymous";
define("URI", "http://www.google.com");
$request_token_url = URI.'/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fh9%2Ffeeds%2F';
$parsed = parse_url($request_token_url);
$params = array();
$oauth_consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);
$req_req = OAuthRequest::from_consumer_and_token($oauth_consumer, NULL, "GET", $request_token_url, $params);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req->sign_request($sig_method, $oauth_consumer, NULL);
$request = $req_req->to_url();
$session = curl_init($request);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
// Make the request
$response = curl_exec($session);
//Error Handling:
// there is an error while executing the request,
if (!$response) {
$response = curl_error($curl);
}
curl_close($session);
parse_str($response, $params);
$oauth_token = $params['oauth_token'];
$oauth_token_secret = $params['oauth_token_secret'];
$_SESSION['CONSUMER_KEY'] = $consumer_key;
$_SESSION['CONSUMER_SECRET'] = $consumer_secret;
$_SESSION['REQUEST_TOKEN'] = $oauth_token;
$_SESSION['REQUEST_TOKEN_SECRET'] = $oauth_token_secret;
print_r($_SESSION);
I'm using OAuth.php.
The returning array does not give me anything:
Array (
[CONSUMER_KEY] => googlecodesamples.com
[CONSUMER_SECRET] => [REQUEST_TOKEN] => [REQUEST_TOKEN_SECRET] =>
)
I found this on the Google Oauth Reference
If your application is not registered, select HMAC-SHA1 and use the following key and secret:
consumer key: "anonymous" consumer
secret: "anonymous"
I have altered the consumer_key and consumer_secret variables but the returning array remains empty.
I'm not sure what I'm doing wrong this is a basic H9 sandbox development procedure; any advice would help.
Well I have figured this one out,
When I printed the response of the curl I got a message which said:
This URL has moved here:
https://www.google.com/accounts/OAuthGetRequestToken?oauth_consumer_key=anonymous%20%20%20%20[amp;oauth_nonce]%20=%3E%20828f80d4cec64b5b6fcca5010e2aa952%20%20%20%20[amp;oauth_signature]%20=%3E%20H+WrK1WIhyFEkrHRBvjpzcVLFvs=%20%20%20%20[amp;oauth_signature_method]%20=%3E%20HMAC-SHA1%20%20%20%20[amp;oauth_timestamp]%20=%3E%201282773417%20%20%20%20[amp;oauth_version]%20=%3E%201.0%20%20%20%20[amp;scope]%20=%3E%20https://www.google.com/h9/feeds/
So once I changed the $request_token_url to this, it worked like a charm and I finally have one-leg!! two left :)

Resources