Examples

These are a few examples on how to use fbchat. Remember to swap out <email> and <password> for your email and password

Basic example

This will show basic usage of fbchat

# -*- coding: UTF-8 -*-

from fbchat import Client
from fbchat.models import *

client = Client("<email>", "<password>")

print("Own id: {}".format(client.uid))

client.send(Message(text="Hi me!"), thread_id=client.uid, thread_type=ThreadType.USER)

client.logout()

Interacting with Threads

This will interact with the thread in every way fbchat supports

# -*- coding: UTF-8 -*-

from fbchat import Client
from fbchat.models import *

client = Client("<email>", "<password>")

thread_id = "1234567890"
thread_type = ThreadType.GROUP

# Will send a message to the thread
client.send(Message(text="<message>"), thread_id=thread_id, thread_type=thread_type)

# Will send the default `like` emoji
client.send(
    Message(emoji_size=EmojiSize.LARGE), thread_id=thread_id, thread_type=thread_type
)

# Will send the emoji `👍`
client.send(
    Message(text="👍", emoji_size=EmojiSize.LARGE),
    thread_id=thread_id,
    thread_type=thread_type,
)

# Will send the sticker with ID `767334476626295`
client.send(
    Message(sticker=Sticker("767334476626295")),
    thread_id=thread_id,
    thread_type=thread_type,
)

# Will send a message with a mention
client.send(
    Message(
        text="This is a @mention", mentions=[Mention(thread_id, offset=10, length=8)]
    ),
    thread_id=thread_id,
    thread_type=thread_type,
)

# Will send the image located at `<image path>`
client.sendLocalImage(
    "<image path>",
    message=Message(text="This is a local image"),
    thread_id=thread_id,
    thread_type=thread_type,
)

# Will download the image at the URL `<image url>`, and then send it
client.sendRemoteImage(
    "<image url>",
    message=Message(text="This is a remote image"),
    thread_id=thread_id,
    thread_type=thread_type,
)


# Only do these actions if the thread is a group
if thread_type == ThreadType.GROUP:
    # Will remove the user with ID `<user id>` from the thread
    client.removeUserFromGroup("<user id>", thread_id=thread_id)

    # Will add the user with ID `<user id>` to the thread
    client.addUsersToGroup("<user id>", thread_id=thread_id)

    # Will add the users with IDs `<1st user id>`, `<2nd user id>` and `<3th user id>` to the thread
    client.addUsersToGroup(
        ["<1st user id>", "<2nd user id>", "<3rd user id>"], thread_id=thread_id
    )


# Will change the nickname of the user `<user_id>` to `<new nickname>`
client.changeNickname(
    "<new nickname>", "<user id>", thread_id=thread_id, thread_type=thread_type
)

# Will change the title of the thread to `<title>`
client.changeThreadTitle("<title>", thread_id=thread_id, thread_type=thread_type)

# Will set the typing status of the thread to `TYPING`
client.setTypingStatus(
    TypingStatus.TYPING, thread_id=thread_id, thread_type=thread_type
)

# Will change the thread color to `MESSENGER_BLUE`
client.changeThreadColor(ThreadColor.MESSENGER_BLUE, thread_id=thread_id)

# Will change the thread emoji to `👍`
client.changeThreadEmoji("👍", thread_id=thread_id)

# Will react to a message with a 😍 emoji
client.reactToMessage("<message id>", MessageReaction.LOVE)

Fetching Information

This will show the different ways of fetching information about users and threads

# -*- coding: UTF-8 -*-

from itertools import islice
from fbchat import Client
from fbchat.models import *

client = Client("<email>", "<password>")

# Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers()

print("users' IDs: {}".format([user.uid for user in users]))
print("users' names: {}".format([user.name for user in users]))


# If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
user = client.fetchUserInfo("<user id>")["<user id>"]
# We can also query both mutiple users together, which returns list of `User` objects
users = client.fetchUserInfo("<1st user id>", "<2nd user id>", "<3rd user id>")

print("user's name: {}".format(user.name))
print("users' names: {}".format([users[k].name for k in users]))


# `searchForUsers` searches for the user and gives us a list of the results,
# and then we just take the first one, aka. the most likely one:
user = client.searchForUsers("<name of user>")[0]

print("user ID: {}".format(user.uid))
print("user's name: {}".format(user.name))
print("user's photo: {}".format(user.photo))
print("Is user client's friend: {}".format(user.is_friend))


# Fetches a list of the 20 top threads you're currently chatting with
threads = client.fetchThreadList()
# Fetches the next 10 threads
threads += client.fetchThreadList(offset=20, limit=10)

print("Threads: {}".format(threads))


# Gets the last 10 messages sent to the thread
messages = client.fetchThreadMessages(thread_id="<thread id>", limit=10)
# Since the message come in reversed order, reverse them
messages.reverse()

# Prints the content of all the messages
for message in messages:
    print(message.text)


# If we have a thread id, we can use `fetchThreadInfo` to fetch a `Thread` object
thread = client.fetchThreadInfo("<thread id>")["<thread id>"]
print("thread's name: {}".format(thread.name))
print("thread's type: {}".format(thread.type))


# `searchForThreads` searches works like `searchForUsers`, but gives us a list of threads instead
thread = client.searchForThreads("<name of thread>")[0]
print("thread's name: {}".format(thread.name))
print("thread's type: {}".format(thread.type))


# Here should be an example of `getUnread`


# Print image url for 20 last images from thread.
images = client.fetchThreadImages("<thread id>")
for image in islice(image, 20):
    print(image.large_preview_url)

Echobot

This will reply to any message with the same message

# -*- coding: UTF-8 -*-

from fbchat import log, Client

# Subclass fbchat.Client and override required methods
class EchoBot(Client):
    def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        self.markAsDelivered(thread_id, message_object.uid)
        self.markAsRead(thread_id)

        log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))

        # If you're not the author, echo
        if author_id != self.uid:
            self.send(message_object, thread_id=thread_id, thread_type=thread_type)


client = EchoBot("<email>", "<password>")
client.listen()

Remove Bot

This will remove a user from a group if they write the message Remove me!

# -*- coding: UTF-8 -*-

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


class RemoveBot(Client):
    def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        # We can only kick people from group chats, so no need to try if it's a user chat
        if message_object.text == "Remove me!" and thread_type == ThreadType.GROUP:
            log.info("{} will be removed from {}".format(author_id, thread_id))
            self.removeUserFromGroup(author_id, thread_id=thread_id)
        else:
            # Sends the data to the inherited onMessage, so that we can still see when a message is recieved
            super(RemoveBot, self).onMessage(
                author_id=author_id,
                message_object=message_object,
                thread_id=thread_id,
                thread_type=thread_type,
                **kwargs
            )


client = RemoveBot("<email>", "<password>")
client.listen()

“Prevent changes”-Bot

This will prevent chat color, emoji, nicknames and chat name from being changed. It will also prevent people from being added and removed

# -*- coding: UTF-8 -*-

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

# Change this to your group id
old_thread_id = "1234567890"

# Change these to match your liking
old_color = ThreadColor.MESSENGER_BLUE
old_emoji = "👍"
old_title = "Old group chat name"
old_nicknames = {
    "12345678901": "User nr. 1's nickname",
    "12345678902": "User nr. 2's nickname",
    "12345678903": "User nr. 3's nickname",
    "12345678904": "User nr. 4's nickname",
}


class KeepBot(Client):
    def onColorChange(self, author_id, new_color, thread_id, thread_type, **kwargs):
        if old_thread_id == thread_id and old_color != new_color:
            log.info(
                "{} changed the thread color. It will be changed back".format(author_id)
            )
            self.changeThreadColor(old_color, thread_id=thread_id)

    def onEmojiChange(self, author_id, new_emoji, thread_id, thread_type, **kwargs):
        if old_thread_id == thread_id and new_emoji != old_emoji:
            log.info(
                "{} changed the thread emoji. It will be changed back".format(author_id)
            )
            self.changeThreadEmoji(old_emoji, thread_id=thread_id)

    def onPeopleAdded(self, added_ids, author_id, thread_id, **kwargs):
        if old_thread_id == thread_id and author_id != self.uid:
            log.info("{} got added. They will be removed".format(added_ids))
            for added_id in added_ids:
                self.removeUserFromGroup(added_id, thread_id=thread_id)

    def onPersonRemoved(self, removed_id, author_id, thread_id, **kwargs):
        # No point in trying to add ourself
        if (
            old_thread_id == thread_id
            and removed_id != self.uid
            and author_id != self.uid
        ):
            log.info("{} got removed. They will be re-added".format(removed_id))
            self.addUsersToGroup(removed_id, thread_id=thread_id)

    def onTitleChange(self, author_id, new_title, thread_id, thread_type, **kwargs):
        if old_thread_id == thread_id and old_title != new_title:
            log.info(
                "{} changed the thread title. It will be changed back".format(author_id)
            )
            self.changeThreadTitle(
                old_title, thread_id=thread_id, thread_type=thread_type
            )

    def onNicknameChange(
        self, author_id, changed_for, new_nickname, thread_id, thread_type, **kwargs
    ):
        if (
            old_thread_id == thread_id
            and changed_for in old_nicknames
            and old_nicknames[changed_for] != new_nickname
        ):
            log.info(
                "{} changed {}'s' nickname. It will be changed back".format(
                    author_id, changed_for
                )
            )
            self.changeNickname(
                old_nicknames[changed_for],
                changed_for,
                thread_id=thread_id,
                thread_type=thread_type,
            )


client = KeepBot("<email>", "<password>")
client.listen()