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)
A simple Discord bot written in Python

Acolyte A small and simple little Discord bot written in Python that utilizes the discord.py library. Dependencies The bot depends on Python 3.9 and u

0 Jul 17, 2021
Rocks vc Userbot: A Telegram Bot Project That's Allow You To Play Audio And Video Music On Telegram Voice Chat Group

⭐️ Rocks VC Userbot ⭐️ Telegram Userbot To Play Audio And Video Song On VC Chat

Dr Asad Ali 10 Jul 18, 2022
Quot-a-lecture - Lecture transcript question extraction

Setup virtualenv venv source venv/bin/activate pip install -r requirements.txt

Pratyaksh Sharma 5 Sep 12, 2022
Cloud-native, data onboarding architecture for the Google Cloud Public Datasets program

Public Datasets Pipelines Cloud-native, data pipeline architecture for onboarding datasets to the Google Cloud Public Datasets Program. Overview Requi

Google Cloud Platform 109 Dec 30, 2022
Python binding for Microsoft LightGBM

pyLightGBM: python binding for Microsoft LightGBM Features: Regression, Classification (binary, multi class) Feature importance (clf.feature_importanc

Ardalan 330 Nov 18, 2022
A Powerful, Smart And Simple Userbot In Telethon.

Owner: Masterolic 🇮🇳 BLACK LIGHTNING A Powerful, Smart And Simple Userbot In Telethon. Credits This is A Remix Bot Of Many UserBot. DARKCOBRA Friday

Masterolic 1 Nov 28, 2021
Wakatime Response In javascript and python

Project Title Wakatime Response In javascript and python Description just for refrence Getting Started Dependencies For Python: requests json For Java

Gjenius20 1 Dec 31, 2021
Automated crypto trading bot as adapted from Algovibes.

crypto-trading-bot Automated crypto trading bot as adapted from Algovibes. Pre-requisites Ensure that you have created a Binance API key before procee

Kai Koh 33 Nov 01, 2022
A bot for Large Fry Larrys

GroupMe Bot Driver This driver is written entirely in Python, and with easy configuration in mind. Using this driver, you'll be able to monitor multip

1 Oct 25, 2021
Represents a Lavalink client used to manage nodes and connections.

lavaplayer Represents a Lavalink client used to manage nodes and connections. setup pip install lavaplayer setup lavalink you need to java 11* LTS or

HazemMeqdad 37 Nov 21, 2022
Telegram bot for searching videos in your PDisk account by @AbirHasan2005

PDisk-Videos-Search A Telegram bot for searching videos in your PDisk account by @AbirHasan2005. Configs API_ID - Get from @TeleORG_Bot API_HASH - Get

Abir Hasan 39 Oct 21, 2022
A Telegram Music Bot with proper functions written in Python with Pyrogram and Py-Tgcalls.

⭐️ Yukki Music Bot ⭐️ A Telegram Music Bot written in Python using Pyrogram and Py-Tgcalls Ready to use method A Support Group and ready-to-use runnin

Shikhar Kumar 1000 Jan 03, 2023
A taskbar clock for secondary taskbars on Windows 11

ElevenClock A taskbar clock for secondary taskbars on Windows 11. When microsoft's engineers were creating Windows 11, they forgot to add a clock on t

Martí Climent 1.7k Jan 07, 2023
Telegram bot/scraper to get the latest NUS vacancy reports.

Telegram bot/scraper to get the latest NUS vacancy reports. Stay ahead of the curve and don't get modrekt.

Chee Hong 1 Jan 08, 2022
Contrastive Language-Audio Pretraining

CLAP Contrastive Language-Audio Pretraining In due time this repo will be full of lovely things, I hope. Feel free to check out the Issues if you're i

Charles Foster 83 Dec 01, 2022
An advanced QR Code telegram bot with more features.

QR Code Bot A telegram qr code encode and decode bot Advanced Features 1. Database ( MongoDB ) Support 2. Broadcast Support 3. Status Command 4. Setti

Fayas Noushad 16 Nov 12, 2022
QuickStart specific rules for cfn-python-lint

AWS Quick Start cfn-lint rules This repo provides CloudFormation linting rules specific to AWS Quick Start guidelines, for more information see the Co

AWS Quick Start 12 Jul 30, 2022
Scheduled Block Checker for Cardano Stakepool Operators

ScheduledBlocks Scheduled Block Checker for Cardano Stakepool Operators Lightweight and Portable Scheduled Blocks Checker for Current Epoch. No cardan

SNAKE (Cardano Stakepool) 4 Oct 18, 2022
Discord Bot for League of Legends live match tracker

SABot Dicord Bot for League of Legends match auto tracker Features: Search Summoners statistics in League of Legends. Auto-notifications provide when

Jungyu Choi 4 Sep 27, 2022
Simple web-based hcaptcha bypass

Hcaptcha-Bypass !!! If you found this useful, please click the STAR button !!! Simple web-based hcaptcha bypass Just a demonstration right now, and yo

Kieronia 4 Oct 06, 2021