How to Make Facebook Messenger Bot in Python

Abdou Rockikz · 14 aug 2019

Abdou Rockikz · 3 min read · Updated oct 2019 · General Python Topics

In this tutorial, we will see how we can connect in facebook messenger in python and do various of different cool things!

First, you gonna need to install fbchat library:

pip3 install fbchat

Now to get started, make an empty python file or open up an interactive shell or jupyter notebook and follow along, let's import fbchat:

from fbchat import Client
from fbchat.models import Message

Let's first login:

# facebook user credentials
username = "username.or.email"
password = "password"
# login
client = Client(username, password)

Note: You need to enter correct facebook credentials, otherwise it won't make any sense following with this tutorial.

We have now the client object, there are a lot of useful methods in it, try to dir() it.

For instance, let's get the users you most recently talked to:

# get 20 users you most recently talked to
users = client.fetchThreadList()
print(users)

This will result in a list of threads, a thread can be a user or a group.

Let's search for our best friend, let's get all the information we can get about these users:

# get the detailed informations about these users
detailed_users = [ list(client.fetchThreadInfo(user.uid).values())[0] for user in users ]

Luckily for us, a thread object have a message_count attribute that counts number of messages between you and that thread, we can sort by this attribute:

# sort by number of messages
sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True)

We have now a list of 20 users sorted by message_count, let's get the best friend easily by:

# print the best friend!
best_friend = sorted_detailed_users[0]
print("Best friend:", best_friend.name, "with a message count of", best_friend.message_count)

Let's congratulate this friend by sending a message:

# message the best friend!
client.send(Message(text=f"Congratulations {best_friend.name}, you are my best friend with {best_friend.message_count} messages!"),
            thread_id=best_friend.uid)

Let me take a look at messages:

Message sent by PythonAwesome, right ?

If you want to get all the users you talked to in messenger, you can by:

# get all users you talked to in messenger in your account
all_users = client.fetchAllUsers()
print("You talked with a total of", len(all_users), "users!")

Finally, when you finish, make sure you logout:

# let's logout
client.logout()

As you can see, there are endless of possibilities you can do with this library, you can make automatic reply messages, a chatbot, echobot and many more cool functionalities.

Please check their official documentation.

Happy Coding ♥

View Full Code
Sharing is caring!


Read Also





Comment panel

   
Comment system is still in Beta, if you find any bug, please consider contacting us here.