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)
Sukoshi is a proof-of-concept Python implant that leverages the MQTT protocol for C2 and uses AWS IoT Core as infrastructure.

Sukoshi | 少し Overview Sukoshi is a proof-of-concept Python implant that leverages the MQTT protocol for C2 and uses AWS IoT Core as infrastructure. It

Steven Patterson 37 Oct 29, 2022
API Basica per a synologys Active Backup For Buissiness

Synology Active Backup for Business API-NPP Informació Per executar el programa

Nil Pujol 0 May 13, 2022
un outil pour bypasser les code d'états HTTP négatif coté client ( 4xx )

4xxBypasser un outil pour bypasser les code d'états HTTP négatif coté client ( 4xx ) Liscence : MIT license Creator Installation : git clone https://g

21 Dec 25, 2022
Some python code to make twitter bots ;)

How to set up a twitter bot using python's tweepy library Create a twitter developer account and project Make sure you are logged into your twitter ac

Wael 2 Jan 10, 2022
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

OpenAPI Generator Master (5.3.1): 5.4.x (5.4.x): 6.0.x (6.0.x): ⭐ ⭐ ⭐ If you would like to contribute, please refer to guidelines and a list of open t

OpenAPI Tools 14.8k Jan 04, 2023
Discord bot template.py

discord_bot_template.py A minimal and open-source discord.py boilerplate for kick-starting bot projects. I spend a lot of time developing bots for dif

Tarran Prior 1 Feb 24, 2022
Wonderful Phoenix-Bot

Phoenix Bot Discord Phoenix Bot is inspired by Natewong1313's Bird Bot project yet due to lack of activity by their team. We have decided to revive th

Senior Developer 0 Aug 12, 2021
Telegram Bot to learn English by words and more.. ( in Arabic )

Get the mp3 files Extract the mp3.rar on the same file that bot.py on install requirements pip install -r requirements.txt #Then enter you bot token

Plugin 10 Feb 19, 2022
A secure and customizable bot for controlling cross-server announcements and interactions within Discord

DiscordBot A secure and customizable bot for controlling cross-server announcements and interactions within Discord. Within the code of the bot, you c

Jacob Dorfmeister 1 Jan 22, 2022
Discord bot for user notes.

Noter A discord bot for handling notes for users. Want to keep track of things about your discord users? Then this bot is for you! Links DB Browser fo

Ori 2 Jun 05, 2022
A Telegram bot to index Chinese and Japanese group contents, works with @lilydjwg/luoxu.

luoxu-bot luoxu-bot 是类似于 luoxu-web 的 CJK 友好的 Telegram Bot,依赖于 luoxu 所创建的后端。 测试环境 Python 3.7.9 pip 21.1.2 开发中使用到的 Telethon 需要 Python 3+ 配置 前往 luoxu 根据相

TigerBeanst 10 Nov 18, 2022
Search twitter by address.

Twitter Geolocate Twitter Geolocation is a console app that generates twitter search querries for a certain geolocation and opens them in your standar

David J. Kowalk 28 Dec 06, 2022
Total servers you're in!

Discord-Servercount With this script you can check the amount of servers you are in, along with statistics of how many servers you are owner in and in

Nickyux 1 Feb 12, 2022
Pincer-ext-commands - A simple, lightweight package for pincer prefixed commands

pincer.ext.commands A reimagining of pincer's command system and bot system. Ins

Vincent 2 Jan 11, 2022
This is a simple unofficial async Api-wrapper for tio.run

Async-Tio This is a simple unofficial async Api-wrapper for tio.run

Tom-the-Bomb 7 Oct 28, 2022
Simulación con el método de Montecarlo para verificar ganancias con márgenes negativos.

Apliación del método Monte Carlo a un ejemplo que incluye márgenes negativos. Por Marco A. de la Cruz Importante La información contenida en este ejem

1 Jan 17, 2022
LOL-banner - A discord bot that bans anybody playing league of legends

LOL-banner A discord bot that bans anybody playing league of legends This bot ha

bsd_witch 46 Dec 17, 2022
Discord Selfbot, 90+ commands

Setting the bot up. STEP 1: copy the directory yook.club selfbot was downloaded and extracted into, open cmd and type "cd " then paste. STEP 2: python

yook 1 Dec 12, 2021
Aws-cidr-finder - A Python CLI tool for finding unused CIDR blocks in AWS VPCs

aws-cidr-finder Overview An Example Installation Configuration Contributing Over

Cooper Walbrun 18 Jul 31, 2022