fbchat - Facebook Messenger for Python

Overview

This project is unmaintained

This project is officially marked as unmaintained, since my life is somewhere where I just do not have the time and energy to lead this project.

If there is someone out there willing to take the lead, please get in contact, but even if there is, I can't get in contact with the original author @carpedm20 and get the ability to add others as maintainers, see issue 390. So a fork might be preferable.

I have opened for further discussion in issue 613.

Thanks for serving you all these years.

- Mads Marquart / @madsmtm.

Original project description below

fbchat - Facebook Messenger for Python

Project version Supported python versions: 3.5, 3.6, 3.7, 3.8 and pypy License: BSD 3-Clause Documentation Travis CI Code style

A powerful and efficient library to interact with Facebook's Messenger, using just your email and password.

This is not an official API, Facebook has that over here for chat bots. This library differs by using a normal Facebook account instead.

fbchat currently support:

  • Sending many types of messages, with files, stickers, mentions, etc.
  • Fetching all messages, threads and images in threads.
  • Searching for messages and threads.
  • Creating groups, setting the group emoji, changing nicknames, creating polls, etc.
  • Listening for, an reacting to messages and other events in real-time.
  • Type hints, and it has a modern codebase (e.g. only Python 3.5 and upwards).
  • async/await (COMING).

Essentially, everything you need to make an amazing Facebook bot!

Version Warning

v2 is currently being developed at the master branch and it's highly unstable. If you want to view the old v1, go here.

Additionally, you can view the project's progress here.

Caveats

fbchat works by imitating what the browser does, and thereby tricking Facebook into thinking it's accessing the website normally.

However, there's a catch! Using this library may not comply with Facebook's Terms Of Service!, so be responsible Facebook citizens! We are not responsible if your account gets banned!

Additionally, the APIs the library is calling is undocumented! In theory, this means that your code could break tomorrow, without the slightest warning! If this happens to you, please report it, so that we can fix it as soon as possible!

With that out of the way, you may go to Read The Docs to see the full documentation!

Installation

$ pip install fbchat

If you don't have pip, this guide can guide you through the process.

You can also install directly from source, provided you have pip>=19.0:

$ pip install git+https://github.com/carpedm20/fbchat.git

Example Usage

import getpass
import fbchat
session = fbchat.Session.login("", getpass.getpass())
user = fbchat.User(session=session, id=session.user_id)
user.send_text("Test message!")

More examples are available here.

Maintainer

No one, see notice at the top.

Acknowledgements

This project was originally inspired by facebook-chat-api.

Comments
  • onMessage stopped working.

    onMessage stopped working.

    Description of the problem

    I have created a messenger chatbot, and suddenly all of it's functions stopped working today since they are based on the 'onMessage' function.

    Even the most basic setup containing "onMessage" doesn't work:

    Code to reproduce

    from fbchat import Client
    from fbchat.models import *
    import pickle
    import time
    
    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    with open('/home/pi/Documents/FBBotV4/data/pass.txt', 'rt') as pass_txt:
        passwd = pass_txt
    
    class Client(Client):
        def onMessage(self, message_object, **kwargs):
            print(message_object)
    
    client = Client('[...]', passwd)
    client.listen()
    

    However, this works and sends messages normally:

    Working Code

    from fbchat import Client
    from fbchat.models import *
    import pickle
    import time
    
    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    with open('/home/pi/Documents/FBBotV4/data/pass.txt', 'rt') as pass_txt:
        passwd = pass_txt
    
    client = Client('[...]', passwd)
    
    client.send(Message(text='$> test'), thread_id='[...]', thread_type=ThreadType.GROUP)
    

    Environment information

    • Python version: Python 3.7.3
    • fbchat version: 1.8.3
    bug help wanted 
    opened by Nikas36 25
  • new facebook api - FIXED !!!

    new facebook api - FIXED !!!

    Hey guys, I use fbchat for a couple of weeks now and everything worked fine.

    But since 23h I can't send any msg :/

    import fbchat client = fbchat.Client("....", ".....") sent = client.send(100001986531748, "test123") if sent: print("Message sent successfully!") print("nope! test")

    In cmd:

    D:\Spiele\TEST>python test.py Logging in... nope! test

    When loggin in the fbacc, I can msg everyone without a problem. Furthermore I can get the last messages sent without a problem

    Any ideas ? Sorry I am new to python

    thx in advance <3

    opened by Kobito123 23
  • listen to messages (fb bot)

    listen to messages (fb bot)

    Hi guys! Is it possible to make a fb bot alike with this code? I need something that will listen constanly to messages and on type of message send it to client. Something like jarvis fb bot, but without using heroku etc.

    Thanks!

    opened by milo123milo 22
  • client.send() method is returning a False response

    client.send() method is returning a False response

    I can't send messages to anyone since today (it was sending messages normally until yesterday). In the send method r.ok is False. Is it happening with anyone else?

    opened by afonsocarlos 21
  • Error in getThreadList()

    Error in getThreadList()

    getThreadList() gives me an error in python 3.4. It was fixed by changing

    https://github.com/carpedm20/fbchat/blob/master/fbchat/client.py#L224

     t = Thread(thread)
    

    to

     t = Thread(**thread)
    

    (I can fork and fix it if needed, unless you guys have already fixed it)

    opened by xcorat 18
  • IndexError: list index out of range

    IndexError: list index out of range

    Traceback (most recent call last): File "/home/sulav/.local/share/virtualenvs/facbook-autoreply-bot-Rb9hz_6h/lib/python3.8/site-packages/fbchat/_client.py", line 205, in login self._state = State.login( File "/home/sulav/.local/share/virtualenvs/facbook-autoreply-bot-Rb9hz_6h/lib/python3.8/site-packages/fbchat/_state.py", line 151, in login return cls.from_session(session=session) File "/home/sulav/.local/share/virtualenvs/facbook-autoreply-bot-Rb9hz_6h/lib/python3.8/site-packages/fbchat/_state.py", line 190, in from_session revision = int(r.text.split('"client_revision":', 1)[1].split(",", 1)[0])

    opened by sulavmhrzn 16
  • TravisCI integration and updated test suite

    TravisCI integration and updated test suite

    I've changed the test suite from using unittest to using pytest, and reworked it, so that we can test when onX events were successfully executed. Though I haven't reworked all parts, just adding these extra tests lead me to the discovery of several bugs and unexpected behaviour.

    There's admittedly great part of the test code that still has redundancy, but it's getting closer to an acceptable state.

    I've tinkered with TravisCI configuration, and I think it's now at a point where it's pretty stable. The main reason for using TravisCI is primarily to detect python 2/3 issues, and changes on Facebook's side.

    So, @carpedm20, I need you to setup a Travis project and add either a Github integration or a webhook, and then set the following settings:

    Build only if .travis.yml is present -> true
    Limit concurrent jobs -> true, set to 1 (This one is the most important, since the clients can't be used by two jobs at once)
    Build pushed branches -> true
    Build pushed pull requests -> true
    Auto Cancellation (Both) -> true
    Cron job: master, daily, "Do not run if there has been a build in the last 24h"
    

    I'd also like you to setup a RTFD Webhook with Github, so the docs are automatically built, just something I never got around to asking you to do. You should have access to the project on RTFD

    Lastly you can, if you want to, set some branch protections on master, preventing force pushes definitely should be enabled, but you can choose to require status checks and such.

    Note: I initally set this off to v2.0.0, but I decided against that, and made it now, so that the jump to v2.0.0 is smaller

    enhancement 
    opened by madsmtm 14
  • thread_id

    thread_id

    Is there any possibility to get the thread_id out of the JSON? Would be useful for writing a bot that can interact with multiple users in a single group conversation.

    opened by azziplekkus 14
  • How long can bot be running without logging out?

    How long can bot be running without logging out?

    Please mark it as question.

    How long I can leave my bot logged in and running on VPS? I know that you can’t tell me exact number of hours/days but I want to know if I have to log out, once per day for example, to not get banned by Facebook.

    Should I use some method to log out and log in once per X or maybe log in with cookies to make it more like real person, instead of a bot that is running 24/7?

    question 
    opened by kubapilch 13
  • sendLocalImage() Error

    sendLocalImage() Error

    Hi,

    getting error while uploading local png image. PS : I am using Python 2.7.x

    Exception in parsing of {u'queue': <removed>L, u'ofd_ts': <removed>L,
    u'iseq': 138295, u'type': u'delta', u'delta': {u'body': u'screenshot-a', u'irisS
    eqId': u'138295', u'class': u'NewMessage', u'attachments': [], u'messageMetadata
    ': {u'tags': [u'source:titan:m_basic'], u'actorFbId': u'<removed>', u'mess
    ageId': u'mid.$<removed>', u'offlineThreadingId': u'<removed>
    <removed>', u'timestamp': u'<removed>', u'threadKey': {u'otherUserFbId': u
    '<removed>'}}}}
    Traceback (most recent call last):
      File "C:\Python27\lib\site-packages\fbchat\client.py", line 1520, in _parseMes
    sage
        thread_id=thread_id, thread_type=thread_type, ts=ts, metadata=metadata, msg=
    m)
      File "C:\Other\tp\Research\Python\FB_Terminal\FBTerminal.py", line 31, in onMe
    ssage
        self.sendLocalImage(image_path, Message(text='screenshot'), thread_id=thread
    _id, thread_type=thread_type)
      File "C:\Python27\lib\site-packages\fbchat\client.py", line 1038, in sendLocal
    Image
        image_id = self._uploadImage(image_path, open(image_path, 'rb'), mimetype)
      File "C:\Python27\lib\site-packages\fbchat\client.py", line 981, in _uploadIma
    ge
        return j['payload']['metadata'][0]['image_id']
    IndexError: list index out of range
    
    bug 
    opened by HiteshPatel0101 13
  • markAsRead is not marking thread as read

    markAsRead is not marking thread as read

    i tried to compare payload with facebook messenger running in a browser and payload seems to be the same except of the missing __dyn argument. can it be related?

    opened by actionless 13
  • Update _session.py 01-06-23 19:01

    Update _session.py 01-06-23 19:01

    I used this package, and there's a bug on it. So I try to debug it first, and It's working now. r.text.split('"client_revision":', 1)[1].split(",", 1)[0] ArrayIndexOutOfBoundsException on ('"client_revision":', 1)[1]

    opened by RyannKim327 4
  • Module not found Error!

    Module not found Error!

    Code

    from fbchat import Client
    from fbchat.models import *
    client = Client('<user>', '<password>')
    

    Error

     Exception has occurred: ModuleNotFoundError
     No module named 'fbchat.models'
       File "C:\Users\User\Desktop\Facebook\main.py", line 2, in <module>
         from fbchat.models import *
    

    Environment information

    • Python 3.10
    • fbchat 1.9.7
    opened by errorsensei 0
  • Can't Log in

    Can't Log in

    I'm trying to log in, but I can't The code is: from fbchat import Client from fbchat.models import * if not client.isLoggedIn(): client = Client('PHONE', 'PASS')

    The Traceback: Logging in PHONE NUMBER... Attempt #1 failed, retrying Traceback (most recent call last): File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_client.py", line 205, in login self._state = State.login( File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_state.py", line 151, in login return cls.from_session(session=session) File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_state.py", line 190, in from_session revision = int(r.text.split('"client_revision":', 1)[1].split(",", 1)[0]) IndexError: list index out of range ( then it retries 3 more times ) IndexError: list index out of range Traceback (most recent call last): File "O:\P\Messenger_script.py", line 3, in client = Client('PHONENUMBER', 'PASSWORD') File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_client.py", line 103, in init self.login(email, password, max_tries, user_agent=user_agent) File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_client.py", line 205, in login self._state = State.login( File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_state.py", line 151, in login return cls.from_session(session=session) File "C:\Users\MemeB\AppData\Local\Programs\Python\Python310\lib\site-packages\fbchat_state.py", line 190, in from_session revision = int(r.text.split('"client_revision":', 1)[1].split(",", 1)[0]) IndexError: list index out of range

    Python 3.10.0 Fbchat 1.9.7

    opened by CaptainCaramel 7
  • Trouble Logging in Error and info included

    Trouble Logging in Error and info included

    Hello, I am trying to use the module, first with python 3.10 for windows and now downgraded to 3.7, but the error was unaffected.

    Please see details below, I have verified username and password for facebook, and tried two accounts. Passwords do not contain %

    Logging in [email protected]... Traceback (most recent call last): File "main.py", line 501, in login_logout() File "main.py", line 57, in login_logout client = CustomClient(email, password, max_tries=1, logging_level=logging.DEBUG) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\fbchat_client.py", line 103, in init self.login(email, password, max_tries, user_agent=user_agent) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\fbchat_client.py", line 209, in login user_agent=user_agent, File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\fbchat_state.py", line 155, in login "(Failed on url: {})".format(r.url) fbchat._exception.FBchatUserError: Login failed. Check email/password. (Failed on url: https://m.facebook.com/login.php?login_attempt=1)

    opened by aksuited 0
  • Sending AudioAttachments doesn't work

    Sending AudioAttachments doesn't work

    I know this project is unmaintained, but maybe someone figured out how to sent these. Basically sending every other media by url works (images, videoclips), but when it's trying to send AudioAttachments, it just hangs forever.

    opened by MyNameIsArko 3
Releases(v2.0.0a5)
RequestTrackerBot - Request Tracker Bot With Python

Request Tracker Bot This is a Request Tracker Bot repo, It is for those who uplo

Prince Jaiswal 1 Dec 30, 2021
A Git Alert Bot - Github Integration for Pyrogram & Telethon

Yet Another GitAlertBot Inspired From @Pokurt's GitGram Run Bot: Local Host Git Clone Repo : For Telethon Version : git clone https://github.com/DevsE

DevsExpo 23 Oct 21, 2022
A discord bot providing notifications of player activity on a minecraft server.

tos-alert A discord bot providing notifications of player activity on a minecraft server. Setup By default the app does not launch and will crash with

1 Jul 22, 2022
Stinky ID - A stable pluggable Telegram userbot + Voice & Video Call music bot, based on Telethon

Ultroid - UserBot A stable pluggable Telegram userbot + Voice & Video Call music

Riyan.rz 1 Jan 03, 2022
Automatic login to Microsoft Teams conferences

Automatic login to Microsoft Teams conferences

Xhos 1 Jan 24, 2022
This library is for simplified work with the sms-man.com API

SMSMAN Public API Python This is a lightweight library that works as a connector to Sms-Man public API Installation pip install smsman Documentation h

13 Nov 19, 2022
A Discord webhook spammer made in Python

A Python made Discord webhook spammer usually used for token loggers to spam them/delete them original by cattyn changes listed below.

2 Jan 12, 2022
With this simple app you can customize your presence in Discord.

Discord Rich Presence This a simple console app which can customize your Discord Presence easily, with only one config file! Setup Go to Discord Devel

Mai 1 Jan 06, 2022
Gets instagram public username and returns usefull informations like profilepic(b64), video_urls etc.

InstaSucker Gets instagram public username and returns usefull informations like profilepic(b64), video_urls etc. Information this project contains a

Armin Amiri 5 Apr 30, 2022
Easy & powerful bot to check if your all Telegram bots are working or not. This bot status bot updates every 45 minutes & runs for 24x7 hours.

PowerfulBotStatus-IDN-C-X Easy & powerful bot to check if your all Telegram bots are working or not. This bot status bot updates every 45 minutes & ru

IDNCoderX 5 Oct 06, 2022
Droplink URL Shortener Bot, deployable to Heroku and Railway.

Droplink-bot Make short link by using Droplink API key. Made by @dakshy. Installation The Easy Way Required Variables BOT_TOKEN: Create a bot using @B

ToonsHub 5 Jun 25, 2022
Github Workflows üzerinde Çalışan A101 Aktüel Telegam Bot

A101AktuelRobot Github Workflows üzerinde Çalışan A101 Aktüel Telegam Bot @A101AktuelRobot 💸 Bağış Yap ☕️ Kahve Ismarla 🌐 Telif Hakkı ve Lisans Copy

Ömer Faruk Sancak 10 Nov 02, 2022
A clean, easy to scale discord bot template

A clean, easy to scale discord bot template. Develope using nextcord library and can be use with any other discord.py forked library.

めがねこ 3 Mar 03, 2022
Tiktok 2 Instagram With Python

Tiktok2Instagram 📸 About The Project What it does: Download the source video from a user inputted Tiktok URL. 📙 Add audio to the Tiktok video from a

Carter Belisle 4 Feb 06, 2022
Raid ToolBox (RTB) is a big toolkit of Spamming/Raiding/Token management tools for discord.

This code is very out of date and not very good, feel free to make it into something better. (we check the github page every 5 years to pulls your PRs

2 Oct 03, 2021
DISCORD script to automate sending messages to a particular server

discord discord script This script sends random quotes to an discord server and tags random users on the server in the process MADE WITH LOVE BY SACS

Solomon ogu 1 Nov 06, 2021
Feedback-TelegramBot is a resemblance bot which can be deployed on server

Feedback-TelegramBot Feedback-TelegramBot is a resemblance bot which can be deployed on server This work is based on Telegram library, thanks to their

2 Jan 03, 2022
Python On WhatsApp - Run your python codes on whatsapp along with talking to a chatbot

Python On WhatsApp Run your python codes on whatsapp along with talking to a chatbot This is a small python project to run python on whatsapp. and i c

Prajjwal Pathak 32 Dec 30, 2022
Python wrapper for Revolt API

defectio is a direct implementation of the entire Revolt API and provides a way to authenticate and start communicating with Revolt servers. Similar interface to discord.py

Leon Bowie 26 Sep 18, 2022
M3U Playlist for free TV channels

Free TV This is an M3U playlist for free TV channels around the World. Either free locally (over the air): Or free on the Internet: Plex TV Pluto TV P

Free TV 964 Jan 08, 2023