Codeigniter - Botman - Conversations method not replying - php

I'm using Botman 2.0 and Codeigniter 3.1.6
Ngrok & FB Webhook setup successfully..
Did a simple hears & reply method, working good :
$this->botman->hears('foo','HelloWorld#handleFoo');
$this->botman->hears('hello',function($bot){
$bot->reply('bye~');
});
But when using Botman's conversation method, then Bot is not replying...my conversation code as below:
$this->load->library('BotConversations/OnboardingConversation');
$this->botman->hears('sup', function($bot) {
$bot->startConversation(OnboardingConversation);
});
// Listen
$this->botman->listen();
anyhow, I've follow Botman's Cache conf's guide to setup Cache via Codeigniter method
Below are some of my test files:
Controller
Class
appreciate your help! thanks....

Everything works fine right now, I overlook on a simple syntax issue...
updated my code as below :
$this->botman->hears('sup', function($bot) {
$bot->startConversation(New OnboardingConversation);
});

Related

Laravel 7 - Use REST API instead of a database

I am using a rest api to store/retrieve my data which is stored in a postgres database. The api is not laravel, its an external service!
Now i want to create a website with laravel (framework version 7.3.0) and i'm stuck on how to implement the api calls correctly.
For example: i want to have a custom user provider with which users can log-in on the website. But the validation of the provided credentials is done by the api not by laravel.
How do i do that?
Just make a Registration controller and a Login Controller by "php artisan make:controller ControllerName" and write Authentication logics there.
In previous versions of Laravel you had a command like "php artisan make:auth" that will make everything needed to do these operations. But in Laravel 7.0 you need to install a package called laravel/ui.
Run "composer required laravel/ui" to install that package
Then run "php artisan ui bootstrap --auth"
and now, you are able to run "php artisan make:auth"
This command will make whole Registration (Signup) and Login system for you.
and in orer to work with REST, you may need to know REST (Http) verbs. Learn about GET, POST, PUT, PATH, DELETE requests and how to make those request with PHP and Laravel collection methods. Learn about JSON parsing, encoding, and decoding. Then you can work with REST easily. and work without any template codes from other packages.
Thank you so much. I hope this answer give you some new information/thought. Thanks again.
Edit:
This might not be the best way. But this is what I did at that time. I tried curl and guzzle to build the request with session cookie and everything in the header to make it look like a request from a web browser. Couldn't make it work.
I used the web socket's channel id for the browser I want the changes to happen and concatenated it with the other things, then encrypted it with encrypt($string). After that, I used the encrypted string to generate a QR code.
Mobile app (which was already logged in as an authenticated used) scanned it and made a post request with that QR string and other data. Passport took care of the authentication part of this request. After decrypting the QR string I had the web socket's channel id.
Then I broadcasted in that channel with proper event and data. Caught that broadcast in the browser and reloaded that page with JavaScript.
/*... processing other data ...*/
$broadcastService = new BroadcastService();
$broadcastService->trigger($channelId, $eventName, encrypt($$data));
/*... returned response to the mobile app...*/
My BroadcastService :
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Pusher\Pusher;
use Pusher\PusherException;
class BroadcastService {
public $broadcast = null;
public function __construct() {
$config = config('broadcasting.connections.pusher');
try {
$this->broadcast = new Pusher($config['key'], $config['secret'], $config['app_id'], $config['options']);
} catch (PusherException $e) {
Log::info($e->getMessage());
}
}
public function trigger($channel, $event, $data) {
$this->broadcast->trigger($channel, $event, $data);
}
}
In my view :
<script src="{{asset('assets/js/pusher.js')}}"></script>
<script src="{{asset('assets/js/app.js')}}" ></script>
<script>
<?php
use Illuminate\Support\Facades\Cookie;
$channel = 'Channel id';
?>
Echo.channel('{{$channel}}')
.listen('.myEvent' , data => {
// processing data
window.location.reload();
});
</script>
I used Laravel Echo for this.
Again this is not the best way to do it. This is something that just worked for me for that particular feature.
There may be a lot of better ways to do it. If someone knows a better approach, please let me know.
As of my understanding, you are want to implement user creation and authentication over REST. And then retrieve data from the database. Correct me if I'm wrong.
And I'm guessing you already know how to communicate over API using token. You are just stuck with how to implement it with laravel.
You can use Laravel Passport for the authentication part. It has really good documentation.
Also, make use of this medium article. It will help you to go over the step by step process.

Problem with CORS loading data from cakephp restapi implementation into angular app

I'm trying to comunicate with an already working RestAPI server developed in PHP (CakePHP framework); i'm trying to make a simple login action in Angular 7 application and if success i will proceed with the implementations.
This is the Angular App call code:
constructor(protected cli: HttpClient) {
this.tablet_couple = new TabletCoupleModule();
}
ngOnInit() {
this.cli.get('http://work.local/grai/api-angular/api/v1/tablet_couples/1.json')
.subscribe(
data => { console.log(data) }
)
this.cli.post('http://work.local/grai/api-angular/api/v1/tablet_couples/login.json',{
username: 'xxxxxxxx',
passoword: '123456789',
})
.subscribe(
data => { console.log(data) }
)
}
The actual problem is that the GET call work fine, but the POST call still no working.
I'm sure the REST API is working correctly because if i use tool like Insomnia the response is correct for both calls.
I try to find why but the problem is every time the CORS implementation:
I have try to force headers in Cakephp as you can see above but still not working.
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
if($this->request->is('OPTIONS')) {
$this->response->header('Access-Control-Allow-Origin','*');
$this->response->header('Access-Control-Allow-Methods','*');
$this->response->header('Access-Control-Allow-Headers','Content-Type, Authorization');
}
else {
$this->response = $this->response->withHeader("Access-Control-Allow-Origin","*");
$this->response = $this->response->withHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
$this->response = $this->response->withHeader("Access-Control-Allow-Methods","*");
}
}
UPDATE 1
I had find a library to integrate CORS with cakephp : cakephp-cors
This help but i still have a problem: i can't use Rest API if they are not on the same domain (ok is CORS) but i need.
IF i deploy the application and put my Angular App on the same domain it works; but i want deploy app that can access remote REST API.
Any suggestion?
Ok, i had a "solution" tanks to the #JensV.
1th :: cakephp 3.1.x is too old
I'm using an OLD version of CakePHP (3.1.14); the 3.1.x is simply too old to manager correctly an OPTIONS Method Call.
Using CakePHP 3.7.* with the plugin cakephp-cors it works correctly and now i can make remote call from localhost:4200 .
2nd :: the Method OPTIONS
This is a method that give me so much pain; this method is called by browsers before a POST method call.
The correct response at this method is a HTTP Code 200 from the server.
If you don't manage this call correctly the browser truncate the POST call.
Again i post some reference about this call and how to find a solution:
CakePHP, preflight & CORS
Handling “XMLHttpRequest” OPTIONS Pre-flight Request in Laravel
I hope it helps someone.

Chatbot - Botman functions not working

I am using Botman 2.0 to build a Facebook Messenger chatbot.
Everything is fine with webhook verification and the hear() and reply() methods work well.
But, it looks like other methods don't work.
i.e.
Whenever I use the say() method, it never works. My server receives the request from Messenger, but it does not respond with the message response.
I have test with Botman's main example:
$botman->hears('Hello BotMan!', function($bot) {
$bot->reply('Hello!');
$bot->ask('Whats your name?', function($answer, $bot) {
$bot->say('Welcome '.$answer->getText()); //this never works
});
});
Additionally, when I try to use ButtonTemplate it raises an exception:
PHP Fatal error: Uncaught Error: Class 'ButtonTemplate' not found
Even though Botman's Facebook Driver is loaded:
DriverManager::loadDriver(\BotMan\Drivers\Facebook\FacebookDriver::class);
And my composer.json file looks right:
"require": {
"botman/driver-facebook": "^1.7"
}
What am I missing here?
You need add in your header the following classes:
use BotMan\Drivers\Facebook\Commands\AddStartButtonPayload;
use BotMan\Drivers\Facebook\Commands\AddGreetingText;
use BotMan\Drivers\Facebook\Extensions\ButtonTemplate;
use BotMan\Drivers\Facebook\Extensions\ElementButton;
This works for me. I added the below Facebook extensions immediately after the controller class
use BotMan\Drivers\Facebook\Extensions\Element as Element;
use BotMan\Drivers\Facebook\Extensions\ElementButton as ElementButton;
use BotMan\Drivers\Facebook\Extensions\ButtonTemplate as ButtonTemplate;
use BotMan\Drivers\Facebook\Extensions\GenericTemplate as GenericTemplate;
use BotMan\Drivers\Facebook\Extensions\ListTemplate as ListTemplate;
$botman = resolve('botman');
$botman->hears('Hello BotMan!', function($bot) {
$bot->reply('Hello!');
$bot->ask('Whats your name?', function($answer, $bot) {
$bot->say('Welcome '.$answer->getText()); //this works
});
});
You can check from this link as well https://www.gitmemory.com/issue/botman/botman/1055/522233149

Params missing when POSTed to Fat Free Framework

I've got an Angular front end calling a REST service to authenticate a user provided by a Fat Free server.
When I use postman I can see the parameters passed in the POST in the f3 route, so:
function authenticate(\Base $f3) {
$logger = new \Log('app-events.log');
$logger->write('authenticate called.');
$logger->write('username:' . $f3->get('POST.username'));
$logger->write('username:' . $f3->get('PARAM.username'));
will log the username.
But when I call the same service from my angular front end the parameters are empty.
My server is running version 5.6.17 and I've set always_populate_raw_post_data=-1.
I am stumped and would appreciate any insights.
Thanks
Matt

laravel how to debug a RESTful controller

I have this controller
class APIV1CustomerController extends BaseController{
public function getIndex(){
return "super new look";
}
public function postRegister(){
return "you have entered "+Input::get('fullName')+" as fullName parameter and "+Input::get('mobileNumber')+" as mobileNumber parameter";
}
}
I am trying to call the register function from IOS, I have some problems with the returing data. Thus, I need to debug that function.
when I return just simple test like return "test", it works well from IOS. but when I return the code I showed to you, some problem accrues, I can solve the problem myself from the IOS side but I need to debug the postRegister to check some issues.
when I was using J2EE web service, I can simple print some data to the console in my eClipse that is why I am asking if there is any way to do that in laravel.
Thanks
I am using php storm IDE
This might be useful: https://github.com/mlanin/laravel-api-debugger
It's a laravel package specifically built for assisting with APIs.
this might be irrelevant, but i learned a lot from this article when debugging api and jquery back then. http://www.openlogic.com/wazi/bid/188084/jQuery-and-Ajax-Error-Detection-and-Handling.
the first step is to see if there's any functions in your IOS which will notify you when you have an error after the http call, so that you know you actually are getting an error, ex. 404, 500 etc. Because if you are getting 200, most likely you don't need more advanced debug tool other than print.
server log is another friend which is very helpful in these white screen case, it'll tell you the exact error when 500 error happens. Ex. last error I got on my server was telling me a class name is not found, although it runs fine in my local.

Categories