How to Make Facebook Messenger Bot in Python

Making a facebook messenger chat bot in python using fbchat library, you can make customized auto messages and bots, get user information, and much more handy tools.
  · 3 min read · Updated jul 2022 · Web Scraping · Application Programming Interfaces

Unlock the secrets of your code with our AI-powered Code Explainer. Take a look!

Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

Being able to automate stuff and make useful bots in Facebook messenger appears to be interesting and cool, in this tutorial, we will see how we can connect in Facebook messenger in Python and do various of different cool things!

We gonna be using fbchat library, it works by emulating the browser. This means doing the exact same GET/POST requests and tricking Facebook into thinking it's accessing the website normally. Therefore, this API isn't official and it doesn't require any API key, instead, it requires the credentials of your Facebook account.

Related: How to Make a Telegram Bot in Python.

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 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.

We also have a tutorial on building a Telegram bot, check it out!

Finally, if you're a beginner and want to learn Python, I suggest you take the Python For Everybody Coursera course, in which you'll learn a lot about Python. You can also check our resources and courses page to see the Python resources I recommend on various topics!

Learn Also: How to Extract All Website Links in Python.

Happy Coding ♥

Found the article interesting? You'll love our Python Code Generator! Give AI a chance to do the heavy lifting for you. Check it out!

View Full Code Explain My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!