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)
Tools convert cookies facebook menjadi token facebook.

Tools convert cookies facebook menjadi token facebook.

Muhammad Latif Harkat 2 Jul 17, 2022
This repo contains a simple library for work with Eitaa messenger's api

Eitaa PyKit This repo contains a simple library for work with Eitaa messenger's api PyPI Page : https://pypi.org/project/Eitaa-PyKit Install via pip p

Bistcuite 20 Sep 16, 2022
Python SDK for Facebook's Graph API

Facebook Python SDK This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical

Mobolic 2.7k Jan 7, 2023
Facebook open graph api implementation using the Django web framework in python

Django Facebook by Thierry Schellenbach (mellowmorning.com) Status Django and Facebook are both rapidly changing at the moment. Meanwhile, I'm caught

Thierry Schellenbach 1.4k Dec 29, 2022
A simple Facebook Account generator, written in python (needs different Email so Accounts do not get banned)

FacebookAccountGenerator FAB is a Facebook-Account generating script, written in python Installation Use the package manager pip to install selenium p

MrOverload 7 Jan 5, 2023
Facebook fishing on telegram bot

Facebook-fishing Facebook fishing on telegram bot تثبيت الاداة pkg update -y pkg upgrade -y pkg install git -y pkg install python -y git clone https:/

sadamalsharabi 7 Oct 18, 2022
Brute Force Attack On Facebook Accounts

Brute Force Attack On Facebook Accounts For Install: pkg install update && pkg upgrade -y pkg install python pip install requests pip install mechani

MK X Shaon 1 Oct 30, 2021
Bot facebook

botfb Bot facebook Login via cookies cara install $pkg update && pkg upgrade $pkg install git python $git clone https://github.com/Ainx-BOT/botfb $cd

Fahmi Dev 12 Dec 18, 2022
Auto like & auto followers facebook

Auto like & auto followers facebook

Fahmi Dev 23 Dec 8, 2022
Script Crack Facebook, and Instagram 🚶‍♂

in-mbf Script Crack Facebook, and Instagram ??‍♂ Bukti Install Script $ pkg update && pkg upgrade $ pkg install git $ pkg install python2 $ pip2 insta

Yumasaa 5 Dec 27, 2021
📖 GitHub action schedular (cron) that posts a Hadith every hour on Twitter & Facebook.

Hadith Every Hour ?? A bot that posts a Hadith every hour on Twitter & Facebook (Every 3 hours for now to avoid spamming) Follow on Twitter @HadithEve

Ananto 13 Dec 14, 2022
A multi-password‌ cracking tool that can help you hack facebook accounts very quickly

FbCracker This is a multi-password‌ cracking tool that can help you hack facebook accounts very quickly. Facebook Hacking Tool Installation On Termux

ReD H4CkeR 9 Nov 16, 2022
SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

SEBUAH TOOLS CRACK FACEBOOK & INSTAGRAM DENGAN FITUR YANGMENDUKUNG

Jeeck X Nano 1 Dec 27, 2021
Facebook Clooning Tool BD...

Facebook Clooning Tool BD...

Ariyan Ahmed Mamun 2 Feb 16, 2022
A bot to share Facebook posts.

bot_share_facebook a bot to share Facebook posts. install & clone untuk menjalankan anda bisa melalui terminal contohnya termux, cmd, dan terminal lai

Muhammad Latif Harkat 7 Dec 7, 2022
Official Python client for the MonkeyLearn API. Build and consume machine learning models for language processing from your Python apps.

MonkeyLearn API for Python Official Python client for the MonkeyLearn API. Build and run machine learning models for language processing from your Pyt

MonkeyLearn 157 Nov 22, 2022
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

Python Reddit API Wrapper Development 3k Dec 29, 2022