How to make a bot for the Facebook chat with python, very fast and easy.
Tags: python, coding, programming, codenewbie
Published: 2020-09-27 08:21:19

I'm sorry if I don't explain myself very well, you know, even I don't understand myself...lol

Ok I want to do the most fast and simple possible, so for do this bot we will use the module of python `fbchat`, it can be installed with the command `pip` so if you use **GnuLinux** like me and your package manager is apt the next command should work:

```bash
sudo apt install python-pip; sudo pip install fbchat
```

Ok the next is import all the stuff necessary for built our bot, so the first is import the modules [Client](https://fbchat.readthedocs.io/en/v1.3.9/_modules/fbchat/client.html) and **log** of fbchat and the [models](https://fbchat.readthedocs.io/en/v1.3.9/_modules/fbchat/models.html), then the module [getpass](https://docs.python.org/2/library/getpass.html) we need this module because we need to login on FaceBook with the bot,Yeah with the account which we login, in the chat of that account gonna be run the bot and the `getpass` module will give us an easy and secure way to put the password of our account:

```python
from fbchat import Client, log
from fbchat.models import *
from getpass import getpass
```
Ok the class Client of fbchat have some cool methods like `listen()` and `onMessage()`:

`listen()`
> This method initializes and runs the listening loop continually, this loop start to listen for events, we can define what should be executed or do the bot when certain events happen.


`onMessage()`
> This method is called when the client is listening, and somebody sends a message, cool right?


The event actions can be changed by sub classing the `Client()`, and then overwriting the event methods.

This is the code of `onMessage()` method:

```python

  def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        """
        Called when the client is listening, and somebody sends a message

        :param author_id: The ID of the author
        :param message_object: The message (As a `Message` object)
        :param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
        :param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
        :type message_object: models.Message
        :type thread_type: models.ThreadType
        """
        log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
 ```

Yeah for now this method doesn't do anything, so let's to modify this method with some instructions, of course making a sub class that works exactly like the Client() method, only overwriting the `onMessage()` method adding some extra instructions that will be run depend the text of message receive:

```python

from fbchat import log, Client
from fbchat.models import *
from getpass import getpass

class testBot(Client):

    def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        """
        Called when the client is listening, and somebody sends a message   
        :param author_id: The ID of the author
        :param message_object: The message (As a `Message` object)
        :param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
        :param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
        :type message_object: models.Message
        :type thread_type: models.ThreadType
        """
        log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
        msgText=message_object.text
        msgText.lower()
        if msgText == 'hi' or msgText == "hello":
            self.send(Message(text="Hi my friend"), thread_id=thread_id,thread_type=thread_type )
        elif msgText == 'love':
            self.reactToMessage(message_object.uid, MessageReaction.LOVE)
        elif msgText == 'peace':
            self.reactToMessage(message_object.uid, MessageReaction.HEART)
            self.send(Message(text="First you must have peace in your heart, to give peace to anyone"), thread_id=thread_id, thread_type=thread_type )

client=testBot(raw_input("Insert the email of facebook account"), getpass())
client.listen()
 ```

In above code we're creating a new class that inherent all the functionalities of `Client()` method but overwriting the `onMessage()` which is called when the client is listening and a message is receive.

Let's explain the main points in the above code, the **message_object** is the proper message receive in the chat see like a object, yeah due to every message send or receive in faceBook have a few [atributes](https://fbchat.readthedocs.io/en/v1.3.9/api.html#fbchat.models.Message), yeah isn't only the text, the message have this attributes:

```python
#: The actual message
text = None
#: A list of :class:`Mention` objects
mentions = None
#: A :class:`EmojiSize`. Size of a sent emoji
emoji_size = None
#: The message ID
uid = None
#: ID of the sender
author = None
#: Timestamp of when the message was sent
timestamp = None
#: Whether the message is read
is_read = None
#: A dict with user's IDs as keys, and their :class:`MessageReaction` as values
reactions = None
#: A :class:`Sticker`
sticker = None
#: A list of attachments
attachments = None
```
So in this part our code we're saving the text of received message in the variable **msgText** and then we use the method `lower()` to convert all the text in lowercase, this to avoid problems at hour of comparing strings:

```python 
msgText=message_object.text
msgText.lower()
```
The next is our conditionals that do something based in the text receive:

```python
if msgText == 'hi' or msgText == "hello":
    self.send(Message(text="Hi my friend"), thread_id=thread_id,thread_type=thread_type )
elif msgText == 'love':
    self.reactToMessage(message_object.uid, MessageReaction.LOVE)
elif msgText == 'peace':
    self.reactToMessage(message_object.uid, MessageReaction.HEART)
    self.send(Message(text="First you must have peace in your heart, to give peace to anyone"), thread_id=thread_id, thread_type=thread_type )

```

How you see in our `if` statement if the text of msg receive is "hi" or "hello" the bot will return the message "Hi my friend" usin the method `send()` this method at least needs a value and it's the thread_id, a thread can refer to two things: A Messenger group chat or a single Facebook user, in facebook every user have their own uid that is the same that thread_id because that in this part:
```python
self.send(Message(text="Hi my friend"), thread_id=thread_id,thread_type=thread_type )
```
I use variable **thread_id** to set the value of thread_id, because when we receive any message the variable thread_id is set with the thread_id of who send the msg, with this the bot always gonna answer the msg to who send the msg.

The next is this:
```python
elif msgText == 'love':
    self.reactToMessage(message_object.uid, MessageReaction.LOVE)
```
In the above code if the msg text is "love", our bot gonna react to that msg giving it the love reaction, using the `reactToMessage()` method , every message object have its own id, so **message_object.uid** is the id of receive msg, so our bot gonna react with love reaction to any msg if the msg text is "love", so let's continue with this next code part:

```python
elif msgText == 'peace':
    self.reactToMessage(message_object.uid, MessageReaction.HEART)
    self.send(Message(text="First you must have peace in your heart, to give peace to anyone"), thread_id=thread_id, thread_type=thread_type )
```
The above code our bot respond to any receive msg with the text "First you must have peace in your heart, to give peace to anyone" also it gonna react with a heart to the receive message if the text in the receive message is "peace".

And finally this:

```python
client=testBot(raw_input("Insert the email of facebook account"), getpass())
client.listen()
```
The above code login into faceBook, and put the bot to listen for events.
 
And here is the bot working....lol...cool don't you think?
 ![image](https://raw.githubusercontent.com/TitanHero/GNU-Addiction/master/images/testBot.png)

So this is all of my part, goodbye, animus, never give up, keep trying.