DEV Community

Cover image for Facebook Unofficial API + Chatterbot Bot Part 3: Scratching the Chatterbot + Integration
Takunda Madechangu
Takunda Madechangu

Posted on

Facebook Unofficial API + Chatterbot Bot Part 3: Scratching the Chatterbot + Integration

Hello everyone in this tutorial we will just pass by chatterbot's place and say hi

First things first: Import libraries

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
Enter fullscreen mode Exit fullscreen mode

This lines will import the Chatbot class and ListTrainer which will be used to train the bot.

Create a bot

chatbot = ChatBot("Adam")
Enter fullscreen mode Exit fullscreen mode

Get a response

response = chatbot.get_response("Good morning!")
Enter fullscreen mode Exit fullscreen mode

Whole code

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot("Adam")
response = chatbot.get_response("Good morning!")
Enter fullscreen mode Exit fullscreen mode

I showed you guys some very simple snippets of fbchat and chatterbot. Its time to
integrate the two

Chatterbot + FBChat

Thanos joining two stones

So every-time someone sends us a message we want to send it to chatbot then send then then response back to the user. So how we do that?

Import libraries

from fbchat import log, Client
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from fb_creds import user_name, user_pass
import pickle
Enter fullscreen mode Exit fullscreen mode

fb_creds is file where are creds are being stored. The pickle library will be used to store and retrieve session cookies.

Creating the bot

chatbot = ChatBot("Adam")
Enter fullscreen mode Exit fullscreen mode

Behold the new onMessage

def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        self.markAsDelivered(thread_id, message_object.uid)
        self.markAsRead(thread_id)

        # If you're not the author, echo
        if author_id != self.uid:
            # LINES FOR ECHOING 
            response = chatbot.get_response(message_object.text)
            message_object.text = response
            self.send(message_object, thread_id=thread_id, thread_type=thread_type)   
Enter fullscreen mode Exit fullscreen mode

So now we are now making use of message_object to get the text message, then pass it to our chatbot. From there we change message_object text property to whatever is returned by the chatbot then we send it back to the sender.

WE ARE SMART RIGHT?

Nuh your bot is still dum. Your bot cant get you any new girlfriends while you sleep.πŸ˜”πŸ˜”πŸ˜”

Bye Bye

Top comments (0)