-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTwitterBot.php
More file actions
590 lines (482 loc) · 17.9 KB
/
TwitterBot.php
File metadata and controls
590 lines (482 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
//Need to include this PHP library
require_once('TwitterAPIExchange.php');
class TwitterBot
{
private $settings;
public function __construct()
{
$this->settings = array
(
'oauth_access_token' => "TwitterAccessToken",
'oauth_access_token_secret' => "TwitterAccessTokenSecret",
'consumer_key' => "TwitterConsumerKey",
'consumer_secret' => "TwitterConsumerSecret"
);
}
//Reusable function to Send a Twitter Get request, pass in request URL and array of parameters
function SendTwitterGetRequest($url, $getfield)
{
$twitter = new TwitterAPIExchange($this->settings);
$fullResponse = $twitter->setGetfield($getfield)
->buildOauth($url, 'GET')
->performRequest();
$json = json_decode($fullResponse);
return $json;
}
//Reusable function to Send a Twitter Get request, pass in request URL and array of parameters
//Unlike 'SendTwitterGetRequest' method, which returns JSON, this returns an associative array,
//ie, similar to a C# dictionary:
//myList['ids'] = ['123', '456', '789];
function SendTwitterGetRequestAssociativeArray($url, $getfield)
{
$twitter = new TwitterAPIExchange($this->settings);
$fullResponse = $twitter->setGetfield($getfield)
->buildOauth($url, 'GET')
->performRequest();
$json = json_decode($fullResponse, true);
return $json;
}
//Reusable function to Send a Twitter Post request, pass in request URL and array of parameters
function SendTwitterPostRequest($url, $postfields)
{
$twitter = new TwitterAPIExchange($this->settings);
$fullResponse = $twitter->buildOauth($url, 'POST')
->setPostfields($postfields)
->performRequest();
return $fullResponse;
}
//Old method kept for now for backup
/*
function GetFollowers()
{
//Get the lists of Followers from Twitter
//Add Pagination and Concatenation of Arrays...
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '';
return $this->SendTwitterGetRequest($url, $getfield);
}
*/
//Function to get a JSON list of Twitter 'Followers'
//Each "GetFollowers" API request can only return a maximum of 5000 UserIds at once, so pagination
//is needed to get the next batch of 5000, add it to the first array and then return the whole lot
//Currently works for 0-10000 UserIds - while loop needed for more than 10000
//After that, as the API can only be used 15 times in 15 minutes, offline storage will be needed once
//the method has to paginate more than 15 times (15 * 5 = 75000 UserIds)
function GetFollowers()
{
//Get the lists of Followers from Twitter
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '';
$followersJSON = $this->SendTwitterGetRequest($url, $getfield);
$jsonAssociativeArray = json_decode(json_encode($followersJSON), true);
if($followersJSON->next_cursor_str != "0")
{
$nextFollowersJSON = $this->GetFollowersByCursor($followersJSON->next_cursor_str);
foreach($nextFollowersJSON['ids'] as $followerUserID)
{
array_push($jsonAssociativeArray['ids'], $followerUserID);
}
//Odd because you need to convert from JSON to associative array to push more Ids into the array
//But the method that calls this expects it back as JSON
return json_decode(json_encode($jsonAssociativeArray));
}
else
{
return $followersJSON;
}
}
//Function to get an associative array of the next batch of Twitter Followers, ready to be added
//to the first array of Followers
function GetFollowersByCursor($cursorString)
{
//Get the lists of Followers from Twitter
//Add Pagination and Concatenation of Arrays...
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = "cursor=$cursorString";
return $this->SendTwitterGetRequestAssociativeArray($url, $getfield);
}
//Old method kept for now for backup
/*
function GetFollowing()
{
//Get the lists of Following from Twitter
//Add Pagination and Concatenation of Arrays...
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = '';
return $this->SendTwitterGetRequest($url, $getfield);
}
*/
//Function to get a JSON list of Twitter 'Following' users
//Each "GetFriends" API request can only return a maximum of 5000 UserIds at once, so pagination
//is needed to get the next batch of 5000, add it to the first array and then return the whole lot
//Currently works for 0-10000 UserIds - while loop needed for more than 10000
//After that, as the API can only be used 15 times in 15 minutes, offline storage will be needed once
//the method has to paginate more than 15 times (15 * 5 = 75000 UserIds)
function GetFollowing()
{
//Get the lists of Following from Twitter
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = '';
$followingJSON = $this->SendTwitterGetRequest($url, $getfield);
$jsonAssociativeArray = json_decode(json_encode($followingJSON), true);
if($followingJSON->next_cursor_str != "0")
{
$nextFollowingJSON = $this->GetFollowingByCursor($followingJSON->next_cursor_str);
foreach($nextFollowingJSON['ids'] as $followerUserID)
{
array_push($jsonAssociativeArray['ids'], $followerUserID);
}
//Odd because you need to convert from JSON to associative array to push more Ids into the array
//But the method that calls this expects it back as JSON
return json_decode(json_encode($jsonAssociativeArray));
}
else
{
return $followingJSON;
}
}
//Function to get an associative array of the next batch of Twitter 'Following', ready to be added
//to the first array of 'Following'
function GetFollowingByCursor($cursorString)
{
//Get the lists of Followers from Twitter
//Add Pagination and Concatenation of Arrays...
$url = 'https://api.twitter.com/1.1/friends/ids.json';
$getfield = "cursor=$cursorString";
return $this->SendTwitterGetRequestAssociativeArray($url, $getfield);
}
//Follow a user
function FollowUser($userID, $screenName)
{
$url = 'https://api.twitter.com/1.1/friendships/create.json';
$postfields = array(
'user_id' => "$userID",
'screen_name' => "$screenName",
);
return $this->SendTwitterPostRequest($url, $postfields);
}
//Unfollow a user
function UnfollowUser($userID, $screenName)
{
$url = 'https://api.twitter.com/1.1/friendships/destroy.json';
$postfields = array(
'user_id' => "$userID",
'screen_name' => "$screenName"
);
return $this->SendTwitterPostRequest($url, $postfields);
}
//Function to favourite a Tweet by ID
function FavouriteTweet($tweetID)
{
//Let's favourite!
// $url = 'https://api.twitter.com/1.1/favorites/create.json';
// $url = "https://api.twitter.com/1.1/favorites/create.json?id=$tweetID";
$url = "https://api.twitter.com/1.1/favorites/create.json";
$postfields = array (
'id' => "$tweetID"
);
return $this->SendTwitterPostRequest($url, $postfields);
}
//Function to Retweet a Tweet by ID
function RetweetTweet($tweetID)
{
$url = "https://api.twitter.com/1.1/statuses/retweet/$tweetID.json";
$postfields = array(
'trim_user' => "1"
);
return $this->SendTwitterPostRequest($url, $postfields);
}
//Returns the JSON for your account
function GetSelfLookup()
{
//Your Twitter User ID:
$getfield = 'user_id=123456789123456789';
return $this->GetTwitterUserLookup($getfield);
}
//Return the JSON about a specific user, pass in 'user_id=123456789123456789'
function GetTwitterUserLookup($getfield)
{
$url = 'https://api.twitter.com/1.1/users/lookup.json';
$lookupUserJSON = $this->SendTwitterGetRequest($url, $getfield);
return $lookupUserJSON;
}
function GetSearchResults($searchWord)
{
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = "q=$searchWord";
$json = $this->SendTwitterGetRequest($url, $getfield);
return $json;
}
//Reusable function to send Tweets, just pass in an array of parameters
function SendTweet($postfields)
{
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$this->SendTwitterPostRequest($url, $postfields);
}
//Pass in a string array of "interests" that the bot will search for and Retweet
function RetweetInterests($searchWords)
{
//The big foreach loop now to Retween a number of Tweets for each subject in the passed-in string array
foreach($searchWords as $searchWord)
{
$json = $this->GetSearchResults($searchWord)
//Retweet $numberOfTweetsToRetweet tweets about each subject
$numberOfTweetsToRetweet = 2;
for($count = 0; $count < $numberOfTweetsToRetweet; $count++)
{
$tweetId = $json->statuses[$count]->id_str;
$this->RetweetTweet($tweetId);
}
}
return "Sent some tweets...";
}
//Pass in a string array of "interests" that the bot will search for and Like
function LikeTweets($searchWords)
{
//The big foreach loop now to Like a number of Tweets for each subject in the passed-in string array
foreach($searchWords as $searchWord)
{
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = "q=$searchWord";
$json = $this->SendTwitterGetRequest($url, $getfield);
//Like $numberOfTweetsToLike tweets about each subject?
$numberOfTweetsToLike = 2;
for($count = 0; $count < $numberOfTweetsToLike; $count++)
{
$tweetID = $json->statuses[$count]->id_str;
$temp = $this->FavouriteTweet($tweetID);
}
}
echo "Favourited some Tweets...";
}
//Likes any Tweets send to the Twitter bot (and in some cases, replies to the Tweets)
//You need to pass in the ID of a Tweet sent to the bot so you can check if any more Tweets have been sent to it SINCE that one
//The method returns the new latest Tweet ID, ready to be saved so it can be passed back in next time
function ManageMentions($oldestMentionID)
{
//id_str was used to Retweet, so let's go with that!
$url = 'https://api.twitter.com/1.1/statuses/mentions_timeline.json';
$getfield = "since_id=$oldestMentionID";
$json = $this->SendTwitterGetRequest($url, $getfield);
$mentionCount = count($json);
//If there are no mentions, no need to go any further!
if($mentionCount == 0)
{
return 0;
}
//The "since_id" for next time will be the mention in $json[0] this time
$newSinceID = $json[0]->id_str;
//for each mention, Favourite that Tweet!
for($tweetIndex = 0; $tweetIndex < $mentionCount; $tweetIndex++)
{
$tweetID = $json[$tweetIndex]->id_str;
$temp = $this->FavouriteTweet($tweetID);
$this->ReplyToTweet($json[$tweetIndex]);
}
return $newSinceID;
}
//Reply to Tweets sent to the bot in certain cases...
function ReplyToTweet($tweetJSON)
{
$screenName = $tweetJSON->user->screen_name;
$mentionText = strtoupper($tweetJSON->text);
$status = "";
//Only reply in certain conditions
//Most Tweets to the bot are:
/*
- Thanks for the Retweet
- Thanks for the Follow
- Thanks for the RT
- Or a combination of all of these
*/
if((strpos($mentionText, "THANKS") !== false
|| strpos($mentionText, "THANK YOU") !== false
|| strpos($mentionText, "THANKYOU") !== false
|| strpos($mentionText, "THX") !== false)
&& (strpos($mentionText, "FOR") !== false
|| strpos($mentionText, "TO") !== false))
{
if(strpos($mentionText, "RETWEET") !== false
|| strpos($mentionText, " RT") !== false)
{
$status = "No problem @$screenName :)";
}
else if(strpos($mentionText, "FOLLOW") !== false
|| strpos($mentionText, "FOLLOWING") !== false
|| strpos($mentionText, "FOLLOWERS") !== false)
{
$status = "Good to connect @$screenName :)";
}
else if(strpos($mentionText, "LIKES") !== false
|| strpos($mentionText, "LIKE") !== false
|| strpos($mentionText, "LIKING") !== false)
{
$status = "No worries @$screenName :)";
}
else
{
$status = "Thanks @$screenName :)";
}
$inReplyTo = $tweetJSON->id;
$postfields = array(
'status' => "$status",
'in_reply_to_status_id' => "$inReplyTo"
);
$this->SendTweet($postfields);
}
else
{
return;
}
}
//Reusable function to prepare a JPG image from a URL ready to be Tweeted
function GetJPGMediaID($path)
{
//Need to do the INIT first to get a Media ID
//https://dev.twitter.com/rest/reference/post/media/upload-init
// $url = "https://api.twitter.com/1.1/statuses/retweet/$tweetId.json";
$url = 'https://upload.twitter.com/1.1/media/upload.json';
$postfields = array(
'media_type' => "image/jpeg",
'command' => "INIT",
'total_bytes' => strlen(file_get_contents($path))
);
$fullResponse = $this->SendTwitterPostRequest($url, $postfields);
$json = json_decode($fullResponse);
$mediaID = $json->media_id_string;
//Next need to convert the media data
//http://stackoverflow.com/questions/3967515/how-to-convert-image-to-base64-encoding
//$path = "http://openweathermap.org/img/w/10n.png";
$type = "jpg";
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$mediaData = base64_encode($data);
//Need to do the APPEND next to send the data. Sort of
//https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=123&segment_index=2&media_data=123
$url = 'https://upload.twitter.com/1.1/media/upload.json';
$postfields = array(
'command' => "APPEND",
'media_id' => "$mediaID",
'segment_index' => "0",
'media_data' => "$mediaData"
);
$this->SendTwitterPostRequest($url, $postfields);
//Lastly, need to FINALIZE
//https://dev.twitter.com/rest/reference/post/media/upload-finalize
//https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id=710511363345354753
$url = 'https://upload.twitter.com/1.1/media/upload.json';
$postfields = array(
'command' => "FINALIZE",
'media_id' => "$mediaID",
);
$this->SendTwitterPostRequest($url, $postfields);
//Finally, return the $mediaID ready to be Tweeted
return $mediaID;
}
//Tweet the NASA Image Of The Day
//Pass in the 'NASA Image Of The Day' JSON, obtained from the NASA API
function TweetNASAIOTD()
{
//Harvest NASA IOTD properties
$nasaHelper = new NASAHelper();
$copyright = $nasaHelper->copyright;
$date = $nasaHelper->date;
$explanation = $nasaHelper->explanation;
$title = $nasaHelper->title;
$path = $nasaHelper->image;
$mediaType = $nasaHelper->mediaType;
//If the media_type flag on the NASA JSON is "video",
//then simply Tweet the link to that video.
//Otherwise, process and Tweet the NASA IOTD
if($mediaType == "video")
{
//Tweet the NASA IOTD...video
$output = "$title\r#NASA #ImageOfTheDay #Space\r $path";
$postfields = array(
'status' => "$output",
);
echo $this->SendTweet($postfields);
//echo "Tweeted NASA IOTD...";
}
else
{
//Tweet the image-to-base64-encoding
$mediaID = $this->GetJPGMediaID($path);
//Tweet the image-to-base64-encoding
$output = "$title\r#NASA #ImageOfTheDay #Space";
$postfields = array(
'status' => "$output",
'media_ids' => "$mediaID"
);
echo $this->SendTweet($postfields);
//echo "Tweeted NASA IOTD...";
}
}
//Tweet a Weather forecast
//Weather forecast obtained using the OpenWeatherMap API
function TweetWeather()
{
$apiKey = "OpenWeatherAPIKey";
$location = "Liverpool,uk";
//http://www.openweathermap.org
$url = "http://api.openweathermap.org/data/2.5/weather?q=$location&appid=$apiKey&units=metric";
$response = file_get_contents($url);
$json = json_decode($response);
//Temperature: Celsius
//Wind Speed: metres/second
$weatherMain = $json->weather[0]->main;
$weatherDescription = $json->weather[0]->description;
$tempNow = round($json->main->temp);
$tempMin = round($json->main->temp_min);
$tempMax = round($json->main->temp_max);
$windSpeedMPS = $json->wind->speed;
$windSpeedMPH = round(2.237 * $windSpeedMPS);
$stringReplacement = "#Liverpool #Weather:\r%s, %s.\r%dC.\rMinimum Temperature: %dC\rMaximum Temperature: %dC.\rWind Speed: %gmph";
$output = sprintf($stringReplacement, $weatherMain, $weatherDescription, $tempNow, $tempMin, $tempMax, $windSpeedMPH);
//Some alternative formats in case any of the "description" fields are particularly long
$maxTweetLength = 140;
$tweetLength = strlen($output);
if($tweetLength > $maxTweetLength){
$stringReplacement = "#Liverpool #Weather:\r%s, %s.\r%dC.\rMin Temperature: %dC\rMax Temperature: %dC.\rWind Speed: %gmph";
$output = sprintf($stringReplacement, $weatherMain, $weatherDescription, $tempNow, $tempMin, $tempMax, $windSpeedMPH);
}
$tweetLength = strlen($output);
if($tweetLength > $maxTweetLength){
$stringReplacement = "#Liverpool #Weather:\r%s, %s.\r%dC.\rMin Temp: %dC\rMax Temp: %dC.\rWind Speed: %gmph";
$output = sprintf($stringReplacement, $weatherMain, $weatherDescription, $tempNow, $tempMin, $tempMax, $windSpeedMPH);
}
$tweetLength = strlen($output);
if($tweetLength > $maxTweetLength){
$stringReplacement = "#Weather:\r%s, %s.\r%dC.\rMin Temp: %dC\rMax Temp: %dC.\rWind Speed: %gmph";
$output = sprintf($stringReplacement, $weatherMain, $weatherDescription, $tempNow, $tempMin, $tempMax, $windSpeedMPH);
}
$tweetLength = strlen($output);
if($tweetLength > $maxTweetLength){
$stringReplacement = "#Weather:\r%s, %s.\r%dC.\rMin Temp: %dC\rMax Temp: %dC.\rWind Spd: %gmph";
$output = sprintf($stringReplacement, $weatherMain, $weatherDescription, $tempNow, $tempMin, $tempMax, $windSpeedMPH);
}
$tweetLength = strlen($output);
if($tweetLength > $maxTweetLength){
//Well, we tried! The overall format of the Tweet will need adjusting - this weather forecast is just too long!
echo $output;
return;
}
$postfields = array(
'status' => "$output"
);
$this->SendTweet($postfields);
echo "Tweeted Weather...";
}
//Retweet the most recent quote Tweeted by the account 'qu0te_b0t'
function TweetQuote()
{
//Username: qu0te_b0t
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = "screen_name=qu0te_b0t";
$json = $this->SendTwitterGetRequest($url, $getfield);
$tweetID = $json[0]->id_str;
echo $this->RetweetTweet($tweetID);
}
}
?>