Writing your first facebook chat bot in PHP using Jaxl library

Standard

Today facebook officially announced availability of it’s chat through jabber/xmpp clients. This is a big win for XMPP, with almost 400 million new probable users adding into XMPP club. In this post, I will demonstrate how to connect to facebook chat servers using Jaxl client library in PHP. It can further be used to make custom chat bots for facebook.

Creating your first facebook chat bot:
Follow the steps to successfully run a facebook chat bot:

  1. Download Jaxl or checkout latest from trunk
    svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only
  2. Edit the configuration file config.ini.php as follows:
      // Set an enviornment
      $env = "prod";
    
      $key = array("prod"=>array("user"=>"facebook_username",
                                 "pass"=>"facebook_password",
                                 "host"=>"chat.facebook.com",
                                 "port"=>5222,
                                 "domain"=>"chat.facebook.com"
                                ),
  3. Run from command line:
    abhinavsingh@abhinavsingh-desktop:/jaxl$ sudo php index.php
    OSType: Linux, Registering shutdown for SIGINT and SIGTERM
    OpenSSL: Enabled for CLI
    Attempting DIGEST-MD5 Authentication...
    Starting Session...
    Requesting Feature List...
    Requesting Roster List...
    Setting Status...
    Done
    

Try to send a message to your running chat bot and you shall receive a default message back from the bot saying “Hi, Thanks for your message”.

See further sample codes and explaination on how to build a full fledged gaming chat bots under xmpp category.

  • jak

    Wow, worked in first go. But are we allowed to run such chat bots on fb?

  • Pingback: Abhinav Singh’s Blog: Writing your first facebook chat bot in PHP using Jaxl library | Development Blog With Code Updates : Developercast.com

  • Pingback: Abhinav Singh’s Blog: Writing your first facebook chat bot in PHP using Jaxl library | Webs Developer

  • Phil

    Doesn’t work for me – I fill out the email and password I login to facebook with, and the bot hangs on attempting the digest-md5 auth – I can see when I sniff the traffic that I see a challenge come from facebook and that the bot sends a response, but then after that – nothing.

    Any ideas?

  • Phil

    Oh. I’ve read the developer information for Facebook chat and DIGEST-MD5 authentication requires that you have created a facebook ‘username’. You cannot login with your email address.

    • http://abhinavsingh.com Abhinav Singh

      Right why I wrote for the config file: ‘facebook_username’ :D Enjoy!

    • Phil

      Abhinav: yeah, but as far as I am concerned, an email address often is considered to be a ‘username’… I’ll confess to being annoyed by facebook’s ‘username’ function in the first place, but I suppose in this instance you don’t have a lot of choice in the matter (I wonder if you could logon using your FB u ID if you were able to otherwise work it out)

    • http://abhinavsingh.com Abhinav Singh

      Right I agree, there is and will be a lot of confusion on this for many developers. And yeah there is not a lot of error checks in Jaxl, else library should have told you about the invalid username.

      Nevertheless, glad that you brought this up, will also update the blog post.

    • Phil

      Well, the thing is – if you try to authenticate with your email address, you don’t get an error back from facebook! It just does not respond at all, so it’s a timeout that has to be handled with a “(Bad username?)” subtext.

      Have you written anything that extends the roster list to track presence updates so that I can do actions on all users in the roster that are not offline, for example?

    • http://abhinavsingh.com Abhinav Singh

      There are a lot of methods available. You can find them listed at top of jaxl.class.php file.

      * eventMessage(), eventPresence()
      * sendMessage($jid,$message), sendStatus($status)
      * subscribe($jid)
      * roster(‘get’)
      * roster(‘add’,$jid)
      * roster(‘remove’,$jid)
      * roster(‘update’,$jid,$name,$groups)

      Also check this post of mine “How to broadcast a message to your Gtalk friends using JAXL?” which was intended for gtalk but the methodology will be same for facebook. http://bit.ly/Aecv3

  • Phil

    Hi Abhinav,

    Yeah – I saw the functions in the class, but the roster in of itself only tracks what contacts you have when you sign in, it does not process the Presence status of the contacts.

    The reason I’m looking at it is because of the broadcast script, and I don’t want it to message people who are currently offline.

    The thing that’s confusing me is that I have updated eventPresence in the broadcast class to print out $fromJid.” is “.$status every time it receives presence updates and it’s not printing anything when it receives the burst of presence events at sign-on…

    • Phil

      Gah sorry for starting a new thread, wrong button :/

    • http://abhinavsingh.com Abhinav Singh

      Try calling $this->roster(‘get’) after “Done\n” and see if you still don’t get anything….

    • Phil

      Still nothing, sadly.. I can see in the traffic sniffing that after logging on and sending the message it is coded to send that it receives a full roster and nothing is printed.

      Subsequent presence updates (such as <presence from="@chat.facebook.com” to=”@chat.facebook.com/jaxl_5e991852_47F7F32FA6A83″ type=”unavailable”/> ) also result in no output? :/

    • http://abhinavsingh.com Abhinav Singh

      I don’t think eventPresence() is currently called when someone goes offline. This was done intentionally while building gtalkbots and thats why it is like this.

      Good thing is, as I plan to make progress on Jaxl I am also changing the architecture a bit so that users can bind event handlers for various kind of events. It will be more like wordpress plugin framework. Also there will be some documentation done.

      I am currently not at my workstation, will checkin the required changes if required. Otherwise will update you with the code required to get this info.

  • Phil

    Hi Abhinav,

    Thanks for your input on this. I would expect eventPresence to be called when I receive the initial burst of users who are online, though?

    Phil

    • Phil

      Crikey, I did it again :/

  • Pingback: uberVU - social comments

  • Pingback: Writing your first facebook chat bot in PHP using Jaxl library | Dev Loom

  • jpod

    D:\html\jaxl2>php index.php
    OSType: Windows, Unable to register shutdown functions, try moving to a linux bo
    x
    OpenSSL: Enabled for CLI
    Attempting DIGEST-MD5 Authentication…

    ^^ prosess just stop there.. can u explain more? is problem cause by my OSType?

    • http://abhinavsingh.com Abhinav Singh

      I think your username/password is wrong. Your username should not be your email id with which u register. OS shd not be a problem.

  • Pankaj

    Hi Abhi,

    Thanks for sharing your work.
    I have tried this example.
    I have uploaded the example on the server & the script is running fine.
    I want to know after running the script, what are the steps to follow?

    Should i send an invite to facebookuser@chat.facebook.com because right now there is no reply from the user if i send an invitation.

    Please guide me.

    Regards,
    Pankaj

    • http://abhinavsingh.com Abhinav Singh

      Hi Pankaj,

      I haven’t dug enough to find this out. I guess better place will be to ask on facebook developer forums.

    • http://abhinavsingh.com Abhinav Singh

      I just tested if Jaxl works with facebook chat server or not, and it did :D

    • Pankaj

      No problem, thanks abhi for your prompt reply.

  • http://www.rebeccasaforia.com Rebecca

    Hi Abhinav

    Any update on it not messaging offline users please?

    Thanks

    Rebecca

  • http://mashedlife.com Paul

    It hangs forever when trying to connect to the FB chat server:

    C:\jabber> php index.php
    Attempting DIGEST-MD5 Authentication…

    Thanks for comments

    • http://abhinavsingh.com Abhinav Singh

      Hi Paul,

      Jaxl doesn’t handle all error cases yet and seems like it missed here.

      However from the error i can predict you have a wrong username and password set in the config.ini.php file.

      Kindly check and lemme know. Also see above example of what actual facebook username looks like. It’s not your gmail or yahoo mail id, but your facebook username.

    • http://mashedlife.com Paul

      Thanks, made some progress by correcting the ‘user’ name. And I’m pretty sure the pass is right. Still got an auth error:

      Sending XML>>

      Received XML<<

    • http://mashedlife.com Paul

      failure xmlns=”urn:ietf:params:xml:ns:xmpp-sasl” .. not-authorized …

    • http://abhinavsingh.com Abhinav Singh

      Yup ‘not-authorized’ means u have wrong username/password combination in your config.ini.php file. Try to connect to that account using any of the IM’s and see if you can connect through. If you are able to connect via IM with same user/pass, do let me know.

  • http://none king serolf

    hello sir.. IM King im planning to do this but i dont know… it didnt work for me im still 14 years old and i want to konw how… all i know is AIML but im not so good on it.

    QUESTIONS:

    1) can i use notepad to edit an any configuration file?

    2) (im not demanding) but do you have video for this? if so… can you give me a lin please thanks…

    3)thats all hope youll answer my questions.. thanks

  • http://www.litera.com Word Comparison

    Wow… very valuable information to developers to develope facebook chat program.

  • Lo

    i don’t get it…

    where should i place these?

    view plaincopy to clipboardprint?

    1. svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only

    view plaincopy to clipboardprint?

    1. abhinavsingh@abhinavsingh-desktop:/jaxl$ sudo php index.php
    2. OSType: Linux, Registering shutdown for SIGINT and SIGTERM
    3. OpenSSL: Enabled for CLI
    4. Attempting DIGEST-MD5 Authentication…
    5. Starting Session…
    6. Requesting Feature List…
    7. Requesting Roster List…
    8. Setting Status…
    9. Done

  • Lo

    it would be easier if there’s a video

  • http://weblist.me Jumolea Marius

    I am now testing JAXL with facebook chat server but I have a small issue sending a message. I cam successfully authenticate but when I try to send a message $this->jid is null.

    Am I missing something?

  • Tom

    I found the Authentication hangs when you have the domain set incorrectly in the config.ini.php.

    You have it correctly in your example, but I think the jaxl defaults are misdirecting people. The default is server: talk.google.com domain: gmail.com. This makes it looks like one needs to omit the subdomain which is incorrect.

    Ok so my problem now is I’m not receive any roster response. It just hangs on Sending XML>>

    No response. Any ideas? Cheers.

  • Hitesh

    Abhinav,

    facebook supports, ” facebook connect authentication with xmpp” , http://wiki.developers.facebook.com/index.php/Integrating_with_Facebook_Chat#Authenticating_with_Facebook_Connect

    can you tell me.

    is there a way , if I dont want user to enter username password. Just a single facebook login button. and the user can use facebook chat??

    thanks in advance

  • Nitish

    When i type php inex.php in cmd:
    it displays an error: ‘php’ is not recognised as an internal or external command,operable program or batch file

    pls pls help ne

  • http://abhinavsingh.com Abhinav Singh

    Hi Nitish, you simply need to add php binary to your $PATH… else execute by typing /full/path/to/php index.php

  • Compare Excel Columns

    Very Quite interesting Post on Face book Chat Program.

  • http://abhinavsingh.com Abhinav Singh

    Hi Hitesh,

    Kindly checkout Jaxl v 2.x which now supports X-FACEBOOK-PLATFORM oauth mechanism inside chat bots. http://github.com/abhinavsingh/JAXL

  • aka

    can I install it on a Linux server? and how?

    ’cause I tried and it didn’t worked…

    • http://abhinavsingh.com Abhinav Singh

      Hi Aka,

      Yes Jaxl was developed, tested and now running on production boxes (all linux servers). Can you kindly pass on the details e.g. jaxl.log and other info which can help us debug your env problem :)

  • met

    it is stange but, svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only

    those files are missing from the general trunk of your files. anyway, i have tried the code above but i wasnt able to make it work. it is get stucked in the “Attempting DIGEST-MD5 Authentication…” step. I am sure that the userid is correct, and the password also. I have also tried myemailtologin@facebookcom, 100012*** and my username “mydemo.lastname” but that all didnt work. Would you please upload a demo “php file” that is working with the library here: http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only
    which i can work with facebook?

    Thanks

    • http://abhinavsingh.com Abhinav Singh

      Hi Met,

      Google SVN repo (jaxl 1.x) has been deprecated and replaced by http://github.com/abhinavsingh/JAXL (jaxl 2.x)
      This example was written using jaxl 1.x library but same thing is quite possible with 2.x and i recommend you to use the same.
      2.x library contains an /app folder which have 7 sample examples to help you out.

  • met

    i was able to connect to :) one last problem i am getting is, how i can list the online users in both ajaxl 1.x and 2.x ? i couldnt find a way to list them..

  • met

    I have seen that you have answered in stackoverflow about jabber, thanks for it. But i really couldnt find a proper way to understand if a user is online or not (or list all users online).

    What i got is i can only list online users for a channel (which not all jabber clients doesnt support, like in facebook;i am not an admin of any channel)

    secondly, what i see that someone recommend to subscribe to someone and i can learn if he/she is online or not. But thisi s again limited with facebook servers.

    • http://abhinavsingh.com Abhinav Singh

      Hi Met,

      Your connected Jaxl application can only know about presence status of users to which it has previously subscribed successfully. In short, you can only get info about your roster items. Jaxl internally cache this for you, try print_r($jaxl->roster) in your code.

      I didn’t quite understand what you meant by channel? Also what restriction do u face with fb servers?

  • met

    Met , i have fixed the problems i had. Two problems i have is (which you have explained in stackoverflow too but incomplete)
    1) the photos are binval. how i can convert them to image ?

    2) the vcard doesnt get response from fbook. i want to export the username to names from the vcard info. however when i try to get a info i get that error.

  • Vikas

    Hi Abhinav,

    I am trying to update the name of a buddy of the bot. Its updating also but while getting the roster list, its not shown there. What could be wrong there?

    Vikas

  • Andrew

    Hi, Abhinav and All!
    Did anybody faced error like this?

    PHP Warning: fwrite(): SSL operation failed with code 1. OpenSSL Error messages:
    error:140D00CF:SSL routines:SSL_write:protocol is shutdown in /home/andrew/Dropbox/Sites/tests/jaxl-read-only/xmpp.class.php on line 219
    PHP Stack trace:
    PHP 1. {main}() /home/andrew/Dropbox/Sites/tests/jaxl-read-only/index.php:0
    PHP 2. XMPP->getXML() /home/andrew/Dropbox/Sites/tests/jaxl-read-only/index.php:18
    PHP 3. XMPP->ping() /home/andrew/Dropbox/Sites/tests/jaxl-read-only/xmpp.class.php:258
    PHP 4. XMPP->sendXML() /home/andrew/Dropbox/Sites/tests/jaxl-read-only/xmpp.class.php:869
    PHP 5. fwrite() /home/andrew/Dropbox/Sites/tests/jaxl-read-only/xmpp.class.php:219

    Any ideas are welcome :) Help me please

  • http://asimabinash.info Asm Abnash

    Cool , very helpful. needed a chat bot very badly :P

  • http://abaywashere.com abay

    this for linux?
    i am use windows xp
    do you want teach me about bot chat for windows xp

  • jojchi

    Hi! You can easily make your own chatbot at http://www.chatbot4u.com

  • http://www.desi-date.com/ DD

    I don’t quite understand how the chat bots work, but I will play around with it and see. Thanks for this tutorial.

  • http://anilmathewm.blogspot.com Anil Mathew

    Nice helped me a lot thanks

  • http://abhinavsingh.com Abhinav Singh

    Announcing Jaxl v3.x – asynchronous, non-blocking I/O, event based PHP client/server library – http://abhinavsingh.com/blog/2012/07/announcing-jaxl-v3-x-asynchronous-non-blocking-io-event-based-php-clientserver-library/