-
Notifications
You must be signed in to change notification settings - Fork 0
/
Twitter.php
69 lines (60 loc) · 2.11 KB
/
Twitter.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
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
use Dotenv\Dotenv;
Dotenv::createUnsafeImmutable(__DIR__)->safeLoad();
class Twitter {
private string $apiKey;
private string $apiSecret;
private string $accessToken;
private string $accessTokenSecret;
public function __construct() {
$this->apiKey = $_ENV['API_KEY'];
$this->apiSecret = $_ENV['API_SECRET_KEY'];
$this->accessToken = $_ENV['ACCESS_TOKEN'];
$this->accessTokenSecret = $_ENV['ACCESS_TOKEN_SECRET'];
}
public function get_api(): TwitterOAuth {
$connection = new TwitterOAuth($this->apiKey, $this->apiSecret, $this->accessToken, $this->accessTokenSecret);
$connection->setApiVersion('2');
return $connection;
}
public function post_tweet(string $payload): string {
$api = $this->get_api();
$response = $api->post("tweets", ["text" => $payload], true);
$response = json_encode($response);
$response = json_decode($response, true);
if ($response) {
$data = [
'success' => true,
'message' => 'tweet posted',
'tweet_id' => $response['data']['id']
];
} else {
$data = [
'success' => false,
'message' => 'Failed to post'
];
}
return json_encode($data);
}
public function post_reply(string $payload, string $id_string): string {
$api = $this->get_api();
$response = $api->post("tweets", ["text" => $payload, "reply" => ["in_reply_to_tweet_id" => $id_string]], true);
$response = json_encode($response);
$response = json_decode($response, true);
if ($response) {
$data = [
'success' => true,
'message' => 'reply posted',
'tweet_id' => $response['data']['id']
];
} else {
$data = [
'success' => false,
'message' => 'Failed to post reply'
];
}
return json_encode($data);
}
}