[index] [permalink] [comment]

lowb1rd.github.ioJuly 2016 Category: tech Blog Entry: 004

Create A Twitter Chat-Bot with PHP .. in 5 minutes

We want to set up a simple Twitter chatbot that just replies with whatever we say to it. The bot has to react in an instant so we will be using the Twitter Streaming API to stay permanently connected to Twitter. Since we do not have the time to fiddle with the connection details, we'll be using the very nice Phirehose PHP library for this task. For replying we are simply using Twitters REST API.

1. You need a Twitter Account with a confirmed phone number for your bot. Create a regular Twitter Account here real quick.

2. Login and go to apps.twitter.com, click the "Create New App" Button. Choose any Name, Description and Website URL - nobody will ever see this. Leave the Callback URL empty.

3. Get all the tokens needed for authentication: Click on the app created, then "Keys and Access Tokens", copy Consumer Key (API Key) (A) and Consumer Secret (API Secret) (B), change access level to include Direct Messages, scroll down to "Access Token" and create a new token there. Copy Access Token (C) and Access Token Secret (D).

4. Download/Clone Phirehose. We only need the three PHP files in the lib dir. Create a new php file that will be our bot entry "executable". Replace the four Tokens/Secrets collected above (A/B/C/D).

<?php require_once('UserstreamPhirehose.php');   class TwitterChatBot extends UserstreamPhirehose { public function enqueueStatus($status) { $data = json_decode($status, true); echo date("Y-m-d H:i:s (").strlen($status)."):".print_r($data,true)."\n"; } }   define('TWITTER_CONSUMER_KEY', 'A'); define('TWITTER_CONSUMER_SECRET', 'B'); define('OAUTH_TOKEN', 'C'); define('OAUTH_SECRET', 'D');   // Start streaming $sc = new TwitterChatBot(OAUTH_TOKEN, OAUTH_SECRET); $sc->consume();

5. Run this on the CLI. It should instantly print out the data whenever the bot receives a direct message. Send a message to the bot's Twitter account from another account. Do not forget to friend each other before or enable to receive direct messages from unknown people in the security settings of the bot's account.

6. We are using the oAuth procedure from Phirehose to craft our REST API call for the reply. Replace the TwitterChatBot class above with the following:

  1. class TwitterChatBot extends UserstreamPhirehose {
  2. public function enqueueStatus($status) {
  3. $data = json_decode($status, true);
  4. echo date("Y-m-d H:i:s (").strlen($status)."):".print_r($data,true)."\n";
  5.  
  6. if (isset($data['direct_message']) && $data['direct_message']['screen_name'] != '#BOT_SCREENNAME#') {
  7. $msg = $data['direct_message']['text'];
  8. $id = $data['direct_message']['sender_id'];
  9.  
  10. $this->msg($id, $msg . '!');
  11. }
  12. }
  13. public function msg($to, $text) {
  14. $url = 'https://api.twitter.com/1.1/direct_messages/new.json';
  15. $req = ['user_id' => $to, 'text' => $text];
  16. $auth = $this->getAuthorizationHeader($url, $req);
  17. $context = stream_context_create(array(
  18. 'http' => array(
  19. 'method' => 'POST',
  20. 'header' => "Authorization: " . $auth,
  21. 'content' => http_build_query($req)
  22. )
  23. ));
  24. $data = file_get_contents($url, false, $context);
  25. }
  26. }

Important: Replace #BOT_SCREENNAME# in line 6 with the screen name of your bot. Messages sent from the bot will also come in via the streaming API so we have to exclude these to prevent an infinite loop.

7. We're done!

Twitter bot