Skip to content

Instantly share code, notes, and snippets.

@dtbaker
Created May 28, 2016 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtbaker/a89564a791920b67dd070416c01abe4a to your computer and use it in GitHub Desktop.
Save dtbaker/a89564a791920b67dd070416c01abe4a to your computer and use it in GitHub Desktop.
Run this PHP script and it will start a "bot" user on Slack that does Google Searches for you
<?php
require 'vendor/autoload.php';
use PhpSlackBot\Bot;
// Custom command
class MyCommand extends \PhpSlackBot\Command\BaseCommand {
protected function configure() {
$this->setName('bot');
}
protected function execute($message, $context) {
$text = substr($message['text'],7);
$query = 'https://www.googleapis.com/customsearch/v1?q='.urlencode( $text ).'&cx=CSECODEHERE&num=5&key=APIKEYHERE';
$ch = curl_init($query);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$results = json_decode( curl_exec( $ch ), true);
if($results && count($results['items'])){
$reply = 'What up yo! I found "'.$results['items'][0]['title'].'" over at '.$results['items'][0]['link']. " on the Google machine. It has something to do with: \n\n";
$reply .= $results['items'][0]['snippet'];
if(count($results['items']) > 1){
$reply .= "\n\n\nThere's also:";
for($x=1; $x<4; $x++){
if(isset($results['items'][$x])) {
$reply .= " " . ( $x != 1 ? "and " : "" ) . $results['items'][ $x ]['link'];
}
}
}
$this->send($this->getCurrentChannel(), null, $reply);
}else{
$this->send($this->getCurrentChannel(), null, "OH SHIT THE GOOGLE IS DOWN! NO RESULTS!");
}
}
}
$bot = new Bot();
$bot->setToken('SLACKTOKENHERE'); // Get your token here https://my.slack.com/services/new/bot
$bot->loadCommand(new MyCommand());
$bot->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment