Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
231 lines (186 sloc) 8.7 KB
<?php
namespace App\Http\Controllers;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Middleware\ApiAi;
use BotMan\Drivers\Telegram\TelegramDriver;
use Illuminate\Support\Facades\Cache;
use BotMan\BotMan\Messages\Attachments\Location;
use Illuminate\Support\Facades\DB;
class BotManController extends Controller
{
/**
* Dailystoic logic here.
*/
public function handle()
{
$botman = app('botman');
//create a dialogflow agent
$dialogflow = ApiAi::create(env('DIALOGFLOW_API'))->listenForAction();
//set dialogflow as a middleware between each message and the output to the user
$botman->middleware->received($dialogflow);
//get all the messages and filter them, if not saved to DB save it then check if reply is a whentime
$botman->hears('.*', function (BotMan $bot) {
$id = $bot->getUser()->getId();
if(DB::table('users')->select('id')->where('id', '=',$id)->get()->count() != 1){
DB::table('users')->insert( ['id' => $id]);
$bot->reply("inserted you");
}
$extras = $bot->getMessage()->getExtras();
$apiReply = $extras['apiReply'];
$apiAction = $extras['apiAction'];
$apiIntent = $extras['apiIntent'];
//if reply is about setting time of daily questions save it to cache and DB
if ($apiReply !== "" && $apiAction === "alarm.set" && $apiIntent === "whentime") {
$parts = explode(":", $apiReply); //if you know its safe
$bot->reply("✅ Perfect you'll get questions at ". $parts[0].":00");
//save to cache in the section time with assocative key equal to user Id
$time = Cache::get('time', collect());
$time->put($bot->getUser()->getId(),$parts[0]);
//save the info in the db to send daily messages easily
DB::table('users')->where( ['id' => $id])->update(['time' => $parts[0]]);
Cache::forever('time', $time);
}
})->middleware($dialogflow);
//bot description to the user when starting the chat for the first time
$botman->hears('/start', function ($bot) {
$firstName = $bot->getUser()->getFirstName();
$bot->reply('Hi '.$firstName.' 👋 ');
$bot->reply('Welcome to DailyStoic!');
$bot->reply(' I’m your personal stoic buddy, we’ll be able to challenge our minds and became more happy with Stoicism.
I’ll ask you one simple question every day to help you reflect about your day, life, routine and happiness.');
$bot->reply('To start click this /begin !');
$bot->reply('To change timezone send me your location!');
$bot->reply('And to change the time of the day to receive the questions send me your preferred time !');
});
//begin == enable daily questions
$botman->hears('/begin', function ($bot) {
$id = $bot->getUser()->getId();
$users = Cache::get('users', collect());
if ($users->has($id)) {
$bot->reply('✅ You are already subscribed');
} else {
$users->put($id, 'enabled');
Cache::forever('users', $users);
$bot->reply('✅ Subscribed, you will now receive daily questions!');
DB::table('users')->where( ['id' => $id])->update(['enabled' => 1]);
}
});
//stop == disable daily questions
$botman->hears('/stop', function ($bot) {
$users = Cache::get('users', collect());
$id = $bot->getUser()->getId();
if ($users->has($id)) {
$users->forget($id);
Cache::forever('users', $users);
$firstName = $bot->getUser()->getFirstName();
$bot->reply('See you soon ' . $firstName . ' 👋 ');
$bot->reply('❌ I won\'t send you more daily questions... 😢');
DB::table('users')->where( ['id' => $id])->update(['enabled' => 0]);
} else {
$bot->reply('You are not subscribed to daily questions.');
}
$bot->reply('To resume send me /begin ');
});
$botman->hears('/whoareyou', function ($bot) {
$bot->reply('I\'m StoicBot , I live in the web. My creator is Riccardo Giorato.');
$bot->reply('https://twitter.com/RiccardoGiorato');
});
//send to the user his current active preferences
$botman->hears('/pref', function($bot){
$users = Cache::get('users', collect());
$id = $bot->getUser()->getId();
if ($users->has($id)) {
$bot->reply("✅ You have daily questions enabled");
}else{
$bot->reply("❌ You have daily questions disabled send me /begin to enable");
}
//Location preference
$location = Cache::get('locations', collect());
$tmz = $location->get($bot->getUser()->getId());
if ($tmz) {
date_default_timezone_set($tmz);
}
$bot->reply("✅ Your current time: ".date("H:i"));
$bot->reply('To change it, send me your new location');
//Time preference
$when = Cache::get('time', collect());
$time = $when->get($bot->getUser()->getId());
if(!$time){
$time = 20;
}
$bot->reply('✅ Daily time to reflect: '.$time.":00");
$bot->reply('To change it, send me the right time of the day');
});
//list all the possible commands to the user
$botman->hears('/help', function ($bot) {
$bot->reply('Here\'s all the commands you can send me:
/begin enable daily questions ✅
/pref to know your current preferences 🌍 location and time
/whoareyou know me a little more 🗞
/feedback to send us some feedback about this bot 📩
/stop disable daily questions ❌
');
});
///if the user send a location the bot will save it as the specific timezone in that part of a country
$botman->receivesLocation(function($bot, Location $location) {
$lat = $location->getLatitude();
$lng = $location->getLongitude();
$tmz = TimezoneMapper::latLngToTimezoneString($lat,$lng,$bot->getUser()->getLanguageCode());
$id = $bot->getUser()->getId();
$location = Cache::get('locations', collect());
$location->put($id,$tmz);
Cache::forever('locations', $location);
DB::table('users')->where( ['id' => $id])->update(['timezone' => $tmz]);
$bot->reply("✅ Your new location has been saved!");
});
$botman->hears('/feedback', function ($bot) {
$bot->reply('📩 Use this simple form to help us:');
$bot->reply('https://goo.gl/ZP95Ee');//google form
});
//botman has to listen to user messages
$botman->listen();
}
/**
* @return mixed return a string containing one of the possible daily question
*/
private function question(){
$questions [0]= "What do you spend a silly amount of money on today?";
$questions [1]= "What's the worst things that happened today?";
$questions [2]= "What would make today great?";
$questions [3]= "What would make tomorrow great?";
$questions [4]= "What are you grateful for today?";
$questions [5]= "How could I have made today better?";
return $questions[mt_rand(0,count($questions)-1)];
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function tinker()
{
return view('tinker');
}
/**
* @return string html of send questions page
*/
public function sendquestions()
{
$botman = app('botman');
//get all the users with enabled questions
$users = DB::table('users')->select('*')->where('enabled', '=',1)->get();
//for each one of them check if it's currently the right time to send the questions to them
foreach ($users as $user) {
//if empty will use the default timezone GMT+0
if($user->timezone !== '') {
date_default_timezone_set($user->timezone);
}
if(date("H") === $user->time){
echo "User time:".$user->time." I can send him questions<br/>";
$botman->say($this->question(), $user->id, TelegramDriver::class);
}
}
return "Sent questions!<br/>";
}
}