1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

PIONEERS Facebook Messenger Webhooks

Discussion in 'Developers' Corner' started by ABSGINC, Sep 16, 2017.

?

DO YOU HAVE FACEBOOK MESSENGER INSTALLED ON YOUR MOBILE DEVICE?

  1. YES

  2. NO

Results are only viewable after voting.
  1. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    Want PROOF of CONCEPT? Here it is.

    We've got SMS alerts, EMAIL alerts, but what about Facebook Messenger alerts?

    Better yet, WHY Facebook Messenger alerts?

    ALMOST everyone communicates with Facebook Messenger, secondly with their well documented API you can send nice buttons, lists, and all kinds of usefulness and build an awesome BOT for your communications platform.

    In this example i'm using this to only communicate with me and other staff members, if you build a thorough application and submit for review you can communicate with FB users who aren't admins or moderators to the page you created.

    One benefit to this, you can send a Facebook message to a phone number and Facebook will attempt to deliver it to a Facebook account registered at that phone #.

    Why would you want to do that? -- how about after a call leaves your system, maybe you have an app setup to ask for a customer service review, after hanging up your caller could receive a facebook message from your company thanking them for their call and asking for their feedback. Your customer might not have known you even had a facebook page, and you might not have known your customer did either! -

    In moving forward I imagine my voip server communicating with me through my Facebook Messenger Bot, listing me my voicemail in a visual list, listing me my missed calls, passing me the audio, yes this is all possible as I look through the documentation, and if I had enough caffeine and adrenaline, I could probably finish it all this year ;-) I'm serious, take a look at the API reference and how simple it is to make these requests with some simply json formatting and a CURL PUSH.

    I want to share with you what I have so far, IT WORKS

    You'll probably need to get your feet wet with this Facebook API python bot example I checked out here first, this is where I gained some momentum. GO HERE: django ngrok facebook bot example on python

    The example explains how to register your FB page, application and webhooks. Facebook only will pass these webhooks via https and if your wazo is behind a firewall as well no need to worry, ngrok is a great solution and it is used in the linked example to create a tunnel to your localhost via a defined DNS A record supplied by ngrok. The example also uses django to host the server and handle the requests between facebook and our app.

    I have a few windows open here to show you what happens when I call into my application. In the TOP IMAGE; the top right window is the asterisk console, the top left is the django server console for the webhook callbacks that come in, this is necessary to handle responses down the road, right now the example simply echos back "I think you said XXX"

    The call comes in and I execute a file similar to how wolfram alpha executes 4747
    Except I execute 52637 (also located in the asterisk agi-bin)

    It sends a CURL POST and as the call comes in I get a Desktop Notification from Facebook immediately, also my tablet and mobile phone alerted of Facebook messages

    [​IMG]

    And take a look at this custom formatted message shown on my mobile!

    I can press ANSWER or IGNORE and send this payload back to my wazo server!


    [​IMG]

    I receive a message that said a call entered the 52637 application but have not passed the caller ID yet. The message is also sent with 2 quick reply buttons that allow a payload to be sent back to the bot on wazo

    Later in development that choice which could simply update a flat text file, a variable, and throughout the dialplan application progress that status can be checked to see if the call should be forwarded to the individual who pressed answer.. ----pretty neat?

    Let me show you how I sent this button,

    here is the code for 52637
    Code:
    curl -X POST -H "Content-Type: application/json" -d '{
      "recipient":{
        "id":"<This is the facebook id i want this alert sent to i found it in the logs when i messaged myself>"
      },
      "message":{
        "text": "A call just entered the 52637 application the caller ID is: I havent got that far in code yet!",
        "quick_replies":[
          {
            "content_type":"text",
            "title":"ANSWER",
            "payload":"ANSWER CALL",
          },
          {
            "content_type":"text",
            "title":"IGNORE CALL",
            "payload":"IGNORE CALL"
          }
        ]
      }
    }' "https://graph.facebook.com/v2.6/me/messages?access_token=<this is my huge access token that i wont be sharing here>"
    
    and when I route a call to start this process, this is what it looks like
    Code:
    
    [call-landron] ; Give Landron a call
    exten => s,1,Answer
    exten => s,n,Wait(1)
    exten => s,n,System(/var/lib/asterisk/agi-bin/52637) ; THIS IS WHERE THE ABOVE CODE EXECUTES
    ;exten => s,n,Set(CURLOPT(ssl_verifypeer)=0) ; i couldnt get the curl to work from here
    ;exten => s,n,Set(CURL_RESULT=${CURL(https://graph.facebook.com/v2.6/me/messages?access_token=<get_your_own_access_token>,/var/lib/asterisk/agi-bin/alertfb.json)}) ; I tried the json in a file
    ;exten => s,Set(result=${JSONELEMENT(CURL_RESULT,error/message)})
    ;exten => s,Verbose(${result)
    exten => s,n,Playback(custom/qualitytrain)
    exten => s,n,Dial(Local/52637@default)
    
    So as you can see in the dialplan code, i commented out some lines of trying CURL right from the dialplan, couldnt get the post right, so I ran it in command line style shown above, and as i showed you in the images, it works. When I call in my application I get a Facebook Message from the page I created telling me there is a caller in the system. Just at that I'm thrilled.

    There are other python files created and edited as I followed the tutorial for basically building a bot, these files basically setup the url and tokens for registering the application with facebook and for handling the events.

    main file being views.py - This guy echos back when i type to it from my facebook account, he could easily do other actions on these hooks like update variables that could effect the dialplan, or do other actions and reply back with fetched data like responding to commands like last 10 calls, voicemail, call recordings, etc. But for now, lets echo.
    Code:
    import json, requests, random, re
    from pprint import pprint
    from django.views import generic
    from django.http.response import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from django.utils.decorators import method_decorator
    
    def post_facebook_message(fbid, recevied_message):          
        post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<put-your-token-here>' 
        response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":recevied_message}})
        status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
        pprint(status.json())
    
    
    # Create your views here.
    class AlertFBView(generic.View):
        def get(self, request, *args, **kwargs):
            if self.request.GET['hub.verify_token'] == '<yourowncodeheretoo>':
                return HttpResponse(self.request.GET['hub.challenge'])
            else:
                return HttpResponse('Error, invalid token')
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return generic.View.dispatch(self, request, *args, **kwargs)
    
        # Post function to handle Facebook messages
        def post(self, request, *args, **kwargs):
            # Converts the text payload into a python dictionary
            incoming_message = json.loads(self.request.body.decode('utf-8'))
            # Facebook recommends going through every entry since they might send
            # multiple messages in a single call during high load
            for entry in incoming_message['entry']:
                for message in entry['messaging']:
                    # Check to make sure the received call is a message call
                    # This might be delivery, optin, postback for other events 
                    if 'message' in message:
                        # Print the message to the terminal
                        pprint(message)    
               sendthis =  "I think you said " +  message['message']['text']
                       pprint('this is what i sent')
               pprint(sendthis)
                 post_facebook_message(message['sender']['id'], sendthis)
            return HttpResponse()
    

    I'm really really tired. This wasn't all exactly smooth sailing for me, and I've learned a lot, just today.

    But I don't want to stop there, so I need to get better at this asterisk fun stuff.

    Who can offer me some tips on making this really WORK.
    What I mean is I set this up on a virtual environment, this will never survive a reboot. But with this PROOF OF CONCEPT IN PLACE, who here got excited with me?

    I'd like a put something together on gitbuh that could be cloned to include all of the madness above and survive a reboot.. There is a lot of directions we could go from here. But here we are.

    SUCCESSFUL FACEBOOK MESSENGER COMMUNICATION!
    Comments, Questions, Tips, Tricks, I need some feedback please!
     
  2. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    I've even been able in further testing activate the "TYPING" toggle in Facebook messenger,

    Code:
    !This command toggles TYPING ON
    curl -X POST -H "Content-Type: application/json" -d '{
      "recipient":{
        "id":"<your sender rid here>"
      },
      "sender_action":"typing_on"
    }' "https://graph.facebook.com/v2.6/me/messages?access_token=<put yours here>"
    
    The typing status remains on for only 20 seconds unless you post it again before 20 seconds is up.
    Also if you want it off before the 20 seconds you can send the same command with sender_action as typing_off

    This could indicate a caller is still holding in the queue unanswered, a lack of typing after the receive of a call alert could mean the caller hung up or was answered, all of such final result could also be relayed in another message.

    In anther application waiting in general, and using the speech and tts APIs we can potentially send back to facebook the responses of desired application results and respond to influence how our AiBot should interact next with our caller.

    Recall above in my original post that we can send formatted lists that generate response buttons that can be clicked easily sending a payload back to trigger next dial plan behavior. I've shown in my most above how far I've got, working, and now I need to clean it up and do something real with it. Those of you who read it, please let me know what you see, what needs to be done, and help guide me in possibly building a plugin for the wazo admin gui like the ngrok, one. I'm lost and need some help making something like this come to life..

    CHANCES ARE, IM MISSING SOMETHING HUGE,
    I've followed an example that inspired me to do this and managed to get it to work on asterisk, but maybe i could accomplish most of this using the ngnix already there instead of firing up a virtual environment with django. with a rewrite rule for the urls, in the same manner of the example i used can we use the http servers already running to serve the request to facebook? I dont mind using nkrok to handle the https passthrough to the localhost for now, but whats everyones thoughts on this?
     
    #2 ABSGINC, Sep 16, 2017
    Last edited: Sep 16, 2017
    Sylvain Boily likes this.
  3. Sylvain Boily

    Sylvain Boily Active Member

    Joined:
    Apr 30, 2016
    Messages:
    255
    Likes Received:
    139
    Hello,

    If you need help, let me know. Your project is interesting ;-)

    Sylvain
     
    wardmundy and ABSGINC like this.
  4. wardmundy

    wardmundy Nerd Uno

    Joined:
    Oct 12, 2007
    Messages:
    13,825
    Likes Received:
    2,293
    The screenpop we've all been waiting for. With database integration, this could be something really special. Thanks, @ABSGINC and I hope you'll take advantage of the @Sylvain Boily offer. He's a great tutor. :smartass:
     
    ABSGINC likes this.
  5. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    This is going to be FUN Guys!

    For those following and wanting to contribute here is Facebook documentation on the Messenger Platform
    https://developers.facebook.com/docs/messenger-platform

    If you haven't fired up your Facebook Developers Account head over to facebook and get started
    https://developers.facebook.com/apps/

    You'll need to create a new app, and then add the messenger platform. You'll also need to SUBSCRIBE your application to a Facebook page, so if you haven't created a Facebook page (not your personal profile, a business, a cause, a place), you should create one now for the purpose of identifying your bot.

    The tutorial that inspired me to throw together the conceptional clunkster is here
    https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok
    ---but in moving forward with this on WAZO for permanent joy, I'd like to see how we can get away from some of these methods. Can't we use some rewrite rules and run an instance of Apache or ngnix on a specific port to handle the requests that the django server does in the example , or a rewrite rule to listen on the already running http server?, or is there something I am missing to what else is going on there. I understand there is python, but looking through the Facebook docs, and having some understanding of php, I think I am on the right track. But I don't know enough yet. Just enough to get me in trouble. So with you guys help I want to make sure that this is being done as efficiently as possible. I appreciate the offer @Sylvain Boily , and I take you up on it ! Just tell me where to go next with this.

    I'd like to start keeping it simple, yet its all confusing for me because I've not tried this yet,
    But, in the new GUI in wazo, https://host/admin, I'm going to use the ngrok plugin for example.
    It takes some varibles like token code, and settings extries for individual tunnels.

    [​IMG]

    With this Facebook Concept, anyone should be able to deploy the basic feature of receiving call notifications simply by following steps to create a Facebook Page and App, much similar to the processes necessary for Google, Amazon, or other familiar services with API's, and then applying these values to a setup page after installing the to be developed Facebook Connector in Wazo.

    So how do I make a plugin (like the ngrok configure utility )that will store the necessary variables as well as install the necessary service sand dependencies? I'll have to take a look at some examples if any on github, but i'm lost here for now ---but hold up, I don't even know what services I'm going to be running or all prerequisites required over a base wazo, and where I am going to be injecting these variables yet, so some brainstorming with you guys @Sylvain Boily @wardmundy, on the feature possibilities and the ease of setup and deploy for the average user, hopefully we can work together and see what we should do next.

    example of ngrok setting values..
    [​IMG]

    In ease of use, the Facebook Messenger Bot app should probably GENERATE a 25 character random sequence to use as part of the callback URL that will need to be entered into Facebook. Also there is another challenge answer that Facebook sends to you that you declare in the Facebook settings called verify token. It's good thinking to have our application serving up the 200's to check for this code that Facebook sends with all transmissions to be certain that it's really Facebook talking to us. Obviously in deploying this I want it to be as secure as possible. Does anyone think using ngrok is a security problem? We can easily lock this host down to only facebbooks servers too I believe, which I think rules out a lot of room for vulnerability, but actually when using ngrok I think you need to whitelist your ngrok host server, so making that callback URL with the unique 25 character in the URL will add much security, deny all requests not including the correct url. This is The URL that YOU specify to Facebook. its not the token they give you. We don't tell Facebook come find us on me.voipfreecallshere.com we specify our ngrok/some.crazy.string so I believe security is looking OK here so far.

    So in OUR apps settings we need to save / display;
    1) save the facebook Page Access Token received from Facebook when selecting out Page to act as Messenger.
    2) declare and save the verify token we told facebook we'd check for when settings up the webhooks.
    3) display a URL to enter into facebook to use as the callback url. This url should be generated using possibly the ngrok tunnel and generated url token to whatever port we have running that will dish up the 200 requests for facebook.
    4) default recipient ID, to receive system messages, not extension user specific

    With these settings in place we need to FIRST authenticate and subscribe our application with that page token before too long or it may very well expire. Once this is done we listen for events, but also using the basic curl push's json formatted we can send right from the dialplan the alerts very quickly. So I imagine on this setup page with the feature variables would also have a field for default recipient, for alerts without a prior recipient specified, or for system wide alerts (hard drives getting full, lost trunk connectivity), to also have a button next to that recipient ID to send a test message. That's the plugin page. But what about all the stuff we need running on the backend.

    ...Continued on next post, getting long winded here
     
    wardmundy and Twilight Sparkle like this.
  6. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    Continuation from long-winded post above ,

    Facebook wants your webhooks to be https only, and on a public server like most secure pbx's this is a pain. As I mentioned in the initial post this is pretty solvable with a ngrok solution, and we can choose any internal local host port we choose to catch, while ngrok serves us up on 443 viable to facebook. -- I first tried to use the ngrok plugin in the Wazo gui admin, for some reason when setting up a port forward in there the result is giving a random port # on their host to match up to, but facebook doesnt like sending the webooks to a host and abnormal port #. I notice if you just run ngrok from the command line "./ngrok http 8000" it would give you a randomsubname.theirhost.io (no abnormal port), facebook likes this. Perhaps when the ngrok plugin was setup it was done to use the port numbers to be more secure? asking @Sylvain Boily I'm not sure, but maybe an update on that beta plugin could have a toggle when setting up a ngrok tunnel to use subdomain link instead of a port number link method. Maybe its there already, I just know how to do it from the command line and wasn't able to get it to work using ngrok tunnels made in the gui. Speaking of the ngrok command, I don't know how to get back to my shell without opening another shell, as I haven't dug as deep to see ngrok run as a service and persistent. I've ran in to these same issues when deploying the django server, I have to open another shell as starting the server from what i learned in the tutorials leave the status and conole up, and breaking out stops the server, both ngrok and the django webserver. In fairness I haven't been to the documentation on django or ngrok, I'm first finding out what pieces to this puzzle are actually necessary and which ones are the hardway. But moving forward with a solid plugin i'm looking at a better option for handling the http requests. Maybe something already here?

    This is where I need some help as I step back and take a big look at Wazo as a full Asterisk solution. I haven't found Facebook integration, period, in another pbx setup. @wardmundy You Were right, This is the Screen Popup We've all truly been waiting for. I've been reading your blog for the past 6 or 7 years and I've always ran one of the monsters with the Incredible Freepbx feature sets, so i wanted to personally thank you for your time in expanding open source telecommunication. :cheers2: I've been following the wazo journey for the last year. This is the type of features people are looking for. Already using Facebook Messenger most likely, relieves the need of an extra android or ios app installed for end user, Facebooks messenger.com works on any browser too. Screen popups on any device, literally. having a conversation tab that easily plays your voicemails, etc. All this can be capable for all, starting as simple as entering in some tokens and web call back addresses users can begin getting alerts from their pbx.

    I believe there is an extra (optional) variable that should / could be stored with a pbx user, and that is the Facebook ID number. If you add each user in the pbx as a tester or a moderator to the Facebook page/app, they can communicate without having to have you sending in an app review to Facebook, This also prevents any other facebook user obviously unauthorized, from trying to communicate with your app, so its a benefit for security not to approve your app for the public, just add your pbx users as moderators or app testers.. But if each USER has an optional Facebook user attached to their user record, they are instantly authenticated as the correct user when communicating to the bot and can ask for their voicemail and calls, this will be important I believe. Voicemail flowing through messenger by passing the audio through the api, this actually eliminates the need for 90% of the asterisk voicemail already existing (for retrieval methods)

    I'm visioning a total open source solution featuring an out of office field agent call center that;
    1. optionally with caller ID and CRM values if caller is recognized send to assigned field agent rep only, new callers get answered no matter what, and quickly

    2. Call gets answered on dialplan and either plays normal ring or plays intro and MOH

    3. Before the intro is even done speaking or before the second ring all field agents received a FB call alert or optionally only the specified agent if the caller is recognized and they are assigned to an agent already.

    4. the FIRST agent that presses that ANSWER button is the winner. He can sit tight with his phone in his hand because it's about to ring any second to bridge that caller. Optionally other agents could receive a FB message alerting of call completion to the answering agent.

    Why do I think this is so cool? By alerting the queue agents FIRST by messenger bot you eliminate dialing out on multiple outbound channels, eughhumm, and the cost of this outbound termination. How about instead we send this alert in a way that could potentially allow you to have 100x more agents logged in that can potentiality grab a call. If you needed to RINGALL a group of 10 real estate agents that are working in the field, do we want to make 10 outbound calls through our SIP trunk, (a chain makes our caller wait too long and a ring all uses too many channels at once) Instead lets send FB alerts to our 10 agents and wait for replies on the http server. I'm going to be very honest when i tell you that at time of execution, a Facebook Message is received and alerted on my phone faster, much faster then the same time the call to go over the POTS and ring my cell phone. Just being alerted of the call sooner allows me to prepare to answer and be ready for my caller with minimal wait time for them.

    Look at this a little deeper. The FB message goes to 10 agents, each seeing the alert and other details possibly passed, they are presented with buttons, probably answer or ignore, maybe other choices, but also they see the indicator that our bot is currently TYPING to him. It's not. This indicator could stay on while no other agent has yet said they would "ANSWER". So as you open the message and see the available call and also see the typing is happening too, that means the call is still available for answer. if your typing indicator suddenly stops then that means one of the other agents pressed answer, a confirmation message of that could come through in a moment alerting all other agents once the call was actually successfully connected as well as which other agent answered telephone # whatever. Heck optionally we can send a message to all agents after the call saying the duration with a button that allows the call to be listened to through facebook messenger. don't believe me ;-) ? well it gets better, the call will be available to all 10 users from what i gather by sharing the attachment previously uploaded to one agent, So after uploading the attachment to the first user, we can simply call an attachment ID to the next 9 users to prevent uploading the recorded call 10 times once to each user. Fantastic! A team of consultants or agents working in the field together efficiently, each call LOGGED through Facebook messenger, optionally throwing up call recordings, actually being STORED in messenger. Are you guys getting excited yet? Do you realize it looks like you can use this Facebook bot to create even a simple call logger that spits out attachments in messenger with your call recordings or voicemail? How much space is Facebook giving us, and how long will they store it for? I haven't dug deep enough to lean to the limits of the API, but in high scale use I'm sure they respond with threes a price for everything. It's fun to be first though, isn't it?

    Open source features like this are what progression is about. You can't find a Google calendar API plugin on a website (that writes to your calendar) that doesn't want to charge monthly because they wrote an interface to Googles API.

    For Guys on the road that want to dial out with their office phone number without having to expose a DISA, our Facebook Messenger app could easily achieve a dial command and call the users mobile with the call ID they wanted to dial out from, and optionally achieving the call recording and accounting necessary for your crm. :punk:

    I'm not sure where to start next, as I mentioned, conceptional and clunky I have some things working, So I need some mentoring, timeline, and a lot of help. Before I dig deep I'd love to hear what you guys think about what I mentioned in these basic features and how we can together move forward accomplishing to putting a great add on together.

    - Scott
     
    wardmundy likes this.
  7. wardmundy

    wardmundy Nerd Uno

    Joined:
    Oct 12, 2007
    Messages:
    13,825
    Likes Received:
    2,293
    Fantastic job, Scott. Now we need a little @Sylvain Boily magic to help put the pieces in place with Wazo.

    :party::party::party:
     
    ABSGINC likes this.
  8. Sylvain Boily

    Sylvain Boily Active Member

    Joined:
    Apr 30, 2016
    Messages:
    255
    Likes Received:
    139
    Hello,

    I'm in business travel for the moment, but I'll check soon to help you. Are you coming at the AstriCon ?

    Sylvain
     
  9. krzykat

    krzykat Guru

    Joined:
    Aug 2, 2008
    Messages:
    1,258
    Likes Received:
    300
    How about us IncrediblePBX folks and Isabell? :(
     
    Twilight Sparkle likes this.
  10. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    stay tuned.
     
    krzykat likes this.
  11. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    ...but at this point, with the concepts shown in my original post, and extra services required, it could be achieved their too just as I did here, the main ingredient here is in my dialplan I call a script that executes a CURL post event, I do this modifying the extra congif files in wazo, but it can surely be done on FreePbx with the right effort..
     
    #11 ABSGINC, Sep 18, 2017
    Last edited: Sep 18, 2017
  12. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    I am putting large consideration on being in Orlando in a few weeks. I probably can't do all 3 day's of AstriCon, but I am particularly interested in a hearing this developer speak on Wednesday morning about this great Wazo platform. Anyone heard of this guy? ;) ...Especially interested seeing it promises to talk about working with 3rd party applications using the API, which is exactly what I am asking here. Wazo to the rescue to make it easier.

    Question, besides a general expo admission of $75, what else would I need to be able to attend your event? I haven't the purse necessary to drop $700+, nor the time to go to the entire event. But, I'd like to be able to meet up at AstriCon, and hopefully we have some time to talk before hand. I think this would be one hell of an example to showcase, and I'd love to be part of the magic.

    - Scott
     
  13. wardmundy

    wardmundy Nerd Uno

    Joined:
    Oct 12, 2007
    Messages:
    13,825
    Likes Received:
    2,293
    I'm working on it as we speak. Got my first Facebook message in Debian a few minutes ago... independent of Wazo. That's the hard part (I think). The rest is just connecting the dots for incoming or outgoing calls, much as we did with Twitter years ago.
     
    Twilight Sparkle, krzykat and ABSGINC like this.
  14. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    LOL moment for me when I read "independent of Wazo", It's a tricky recipe at first. My above example while I went ahead and fired it all up with processes running on the Wazo machine, Wazo only knows in my example to execute a file that executes a CURL push json formatted, I haven't even passed variables to it in the example. Simple, in dialplan I was calling a script that executes a CURL push. -- and I know how long that took me, but once you figure it out things start clicking and making more sense, and lets just say, this is going to be big.

    The big fun gets complicated on handling return messages sent to your Facebook bot, that's where we need a whole seperate module running handling event messages received. It's EASY to send a curl push to send a static message. And in the example so far it echos. It leaves a lot of flexibility for others to develop on. Things I wonder now is how to write a a connector that we can send arguments to that could be used on any asterisk platform, though its a little more complicated with the extra prerequisites needed to install the Facebook bot handling, so far anyway. We're actually moving pretty fast on the initial development right now.

    I'm happy to see I've inspired the community! :rockon:
     
    krzykat and wardmundy like this.
  15. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    It's getting pretty fabulous as I was mentioning, the possibilities are damn right cool in Messenger.

    [​IMG]
     
    wardmundy likes this.
  16. krzykat

    krzykat Guru

    Joined:
    Aug 2, 2008
    Messages:
    1,258
    Likes Received:
    300
    Yeah, I'm just imagining using it in conjunction with Asterisk SMS Messaging !!!! Can you imagine someone sends you a text message on your business phone number, it pops up on your facebook messenger, and then you just type back a reply? Very cool :)
     
  17. ABSGINC

    ABSGINC You can call me Scott.

    Joined:
    Oct 1, 2014
    Messages:
    47
    Likes Received:
    21
    Heck's yea. Keep the imaginations coming, SMS relaying is Very do-able. When a product comes a long with a great API well documented, it''s great to see what all we can accomplish.

    ..>Which brings me to possible eventual limits. Excessive calls to the API reported will most likely trigger an 'automatic' review process, where it looks like they will can set a limit to your daily calls, not yet seeing where you can pay for over the limit, such as Google, Amazon IBM Blumix, etc. As Facebooks dream is for you to build a BOT that can reach a lot of people, (basically make you both famous).

    ..But clearly Facebook can imagine the power, I just missed it, but there is a closed beta, it looked like for a one time for of $99 they gave you access to make calls against a phone number database (of registered phone numbers registered for messenger) , you could send a message by calling it directly to the phone number, (if you didn't know their facebook ID), so if this moves out of beta and back open this might soon be an option again, and this call screams i come best from a telecommunications server. - They called it "Customer Matching" - https://developers.facebook.com/docs/messenger-platform/customer-matching/

    Facebook is one of the top dogs that I will be keeping an eye on their APIs. I've been long watching facebook and their graph api for years, the second release of the messenger platform brought more and more attention to the API when they released several updates to messenger that the big fortune guys were immediately releasing bot apps that could send you updates to their content, or provide you with artificial intelligence based services. Definitely got my attention as I watched many other APIs startup just to allow you to callback your facebook webhooks for messenger to their servers, many offering a promise to simplify artificial intelligence


    I'm looking forward for the opportunity to work with Mr. @Sylvain Boily if he can find some time before AstriCon. It speaks volumes for the open source community when we can bring things together first.
     
    krzykat and wardmundy like this.
  18. wardmundy

    wardmundy Nerd Uno

    Joined:
    Oct 12, 2007
    Messages:
    13,825
    Likes Received:
    2,293
    Anything that runs overnight and still works the next morning is my kind of app. Fun times!
     
  19. krzykat

    krzykat Guru

    Joined:
    Aug 2, 2008
    Messages:
    1,258
    Likes Received:
    300
    "You've got a new fax from 555-555-1212 All State Insurance - 5 pages on 9/19/17 at 10:02AM" needs to be added to this beast.
     
    wardmundy likes this.
  20. wardmundy

    wardmundy Nerd Uno

    Joined:
    Oct 12, 2007
    Messages:
    13,825
    Likes Received:
    2,293
    Here's my sample views.py which embellishes @ABSGINC code a bit and handles incoming FB messages on the Debian box. Prints the message on the console, sends confirmation message back to FB, emails it somewhere else, and then forwards it as an SMS message using VoIP.ms. But it could do other things easily... if I only knew Python. For example, it could place a call to an extension and then use TTS to play the message to the callee. Thus far, this is all incoming stuff from Facebook Messenger. But it also could be used from your PBX to push calls and messages out through FB Messenger.

    Perhaps @ABSGINC can look this over. In particular, just need to be sure an invalid token kills the rest of the script. Like I said, I don't know Python much better than the monkey in the pet store.

    Code:
    # yomamabot/fb_yomamabot/views.py
    import json, requests, random, re
    from pprint import pprint
    from django.views import generic
    from django.http.response import HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from django.utils.decorators import method_decorator
    from subprocess import call
    
    def post_facebook_message(fbid, received_message): 
        post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=YOUR-PAGE-ACCESS-TOKEN'
        response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":received_message}})
        status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
        #pprint(status.json())
    
    
    # Create your views here.
    class YoMamaBotView(generic.View):
        def get(self, request, *args, **kwargs):
            if self.request.GET['hub.verify_token'] == 'YOUR-VERIFY_TOKEN':
                return HttpResponse(self.request.GET['hub.challenge'])
            else:
                return HttpResponse('Error, invalid token')
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return generic.View.dispatch(self, request, *args, **kwargs)
    
        # Post function to handle Facebook messages
        def post(self, request, *args, **kwargs):
            # Converts the text payload into a python dictionary
            incoming_message = json.loads(self.request.body.decode('utf-8'))
            # Facebook recommends going through every entry since they might send
            # multiple messages in a single call during high load
            for entry in incoming_message['entry']:
                for message in entry['messaging']:
                    # Check to make sure the received call is a message call
                    # This might be delivery, optin, postback for other events
                    if 'message' in message:
                        # Print the message to the terminal
                        print(" ")
                        print(" ")
                        print("NEW MESSAGE: " + message["message"]["text"])
                        #print(message["message"]["text"])
                        #pprint(message)
                        sendthis =  "RECEIVED: " +  message['message']['text']
                        post_facebook_message(message['sender']['id'], sendthis)
                        print(" ")
                        # you need the next line if you're doing other stuff where quotes would cause problems
                        msg = json.dumps(message["message"]["text"])
                        # next line forwards the FB message as an email message
                        return_code = call(["echo %s | mail -s 'IncrediblePBX Msg' -a'From:Important <admin@YOUR-FQDN>' YOUR-RECIPIENT@gmail.com" % (msg)], shell=True)
                        # next line forwards the FB message as an SMS message thru VoIP.ms
                        return_code = call(["/root/sms-voip.ms/voipms-sms.php 8431234567 %s" % (msg)], shell=True)
            return HttpResponse()
    
    By the way, there are some missing packages in our Wazo platform. This should get your server squared away:
    Code:
    apt-get update
    apt-get -y install python-pip python-dev
    pip install mkvirtualenv virtualenvwrapper simplejson pprint requests
    
    Must-read tutorial: https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok

    Facebook's Webhook Tutorial: https://developers.facebook.com/docs/messenger-platform/webhook
     
    #20 wardmundy, Sep 19, 2017
    Last edited: Sep 19, 2017

Share This Page