Skip to content

Instantly share code, notes, and snippets.

@alcalyn
Created August 31, 2017 13:11
Show Gist options
  • Save alcalyn/6963659e09dbbae82b6e7737fb0e76eb to your computer and use it in GitHub Desktop.
Save alcalyn/6963659e09dbbae82b6e7737fb0e76eb to your computer and use it in GitHub Desktop.
drop twitter test
HASHTAG=#droprobot
MASTER_API=http://0.0.0.0:8480/index-dev.php/api/
MASTER_API_KEY=ChangeMeImFamous
ACCESS_TOKEN=
ACCESS_TOKEN_SECRET=
CONSUMER_KEY=
CONSUMER_SECRET=
{
"require": {
"spatie/twitter-streaming-api": "^1.2",
"guzzlehttp/guzzle": "^6.3",
"vlucas/phpdotenv": "^2.4"
}
}
<?php
require_once 'vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$masterApi = new GuzzleHttp\Client([
'base_uri' => getenv('MASTER_API'),
]);
Spatie\TwitterStreamingApi\PublicStream::create(
getenv('ACCESS_TOKEN'),
getenv('ACCESS_TOKEN_SECRET'),
getenv('CONSUMER_KEY'),
getenv('CONSUMER_SECRET')
)->whenHears(getenv('HASHTAG'), function(array $tweet) {
echo "====== {$tweet['user']['screen_name']}\n{$tweet['text']}\n\n";
$orders = parseTweet($tweet['text']);
sendOrders($tweet['user']['screen_name'], $orders);
})->startListening();
function parseTweet($tweet) {
preg_match_all('/(team|move):([a-z]+)/', $tweet, $matches);
$orders = [];
foreach ($matches[1] as $key => $type) {
$orders []= [
'type' => $type,
'order' => $matches[2][$key],
];
}
return $orders;
}
function sendOrders($pseudo, $orders) {
global $masterApi;
if (0 === count($orders)) {
echo 'Nothing to send.', PHP_EOL;
return;
}
$message = [];
foreach ($orders as $order) {
$message []= [
'pseudo' => $pseudo,
$order['type'] => $order['order'],
];
}
echo 'send to master ', json_encode($message), PHP_EOL;
$masterApi->request('POST', 'orders?api_key='.getenv('MASTER_API_KEY'), ['json' => $message]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment