This repository has been archived by the owner on May 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load_tweets.php
79 lines (60 loc) · 2.12 KB
/
load_tweets.php
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
<?php
require_once __DIR__ . '/vendor/autoload.php';
$settings = require_once(__DIR__ . '/.settings.php');
$tweets = new TweetReader();
$tweets->load($settings);
class TweetReader
{
private $tweets;
public function load($settings)
{
$filename = __DIR__ . '/storage/tweets.json';
// Use a cache file if it exists and is recent.
if (file_exists($filename) && ! $this->fileUpdatedSince($filename, 2)) {
$tweets_json = file_get_contents($filename);
} else {
$tweets_json = $this->downloadFreshTweets($settings);
file_put_contents($filename, $tweets_json);
}
$tweets_data = json_decode($tweets_json);
$this->tweets = array();
$seen_texts = array();
foreach ($tweets_data->statuses as $status) {
if ($status->lang == "en" && !in_array($status->text, $seen_texts)) {
$seen_texts[] = $status->text;
$tweet = new stdClass();
$tweet->text = $status->text;
$tweet->by = $status->user->screen_name;
if (isset($status->entities->media[0]->media_url)) {
$tweet->img = $status->entities->media[0]->media_url;
}
$this->tweets[] = $tweet;
}
}
}
public function readTweets($number = null)
{
if (is_null($number)) {
return $this->tweets;
}
if ($number == 1) {
return $this->tweets[0];
}
return array_slice($this->tweets, 0, $number);
}
private function downloadFreshTweets($settings)
{
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?count=100&q=%23openaccess%20-RT';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$tweets_json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
return $tweets_json;
}
private function fileUpdatedSince($filename, $minutes)
{
return time() - filemtime($filename) > $minutes * 60;
}
}