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 telegram bot script for generating session string using pyrogram and telethon on Telegram bot

String-session-Bot Telegram Bot to generate Pyrogram and Telethon String Session. A star ⭐ from you means a lot to us! Usage Deploy to Heroku Tap on a

Wahyusaputra 8 Oct 28, 2022
A web app via which users can buy and sell stocks using virtual money

finance Virtual Stock Trader. A web app via which users can buy and sell stocks using virtual money. All stock prices are real and provided by IEX. Fe

Kiron Deb 0 Jan 15, 2022
Updater for PGCG (Paradox Game Converters Group) converters written in Python.

Updater Updater for PGCG (Paradox Game Converters Group) converters written in Python. Needs to be put inside an "Updater" directory in the root conve

Paradox Game Converters 2 Jan 10, 2022
Converts a text file of songs to a playlist on your Spotify account.

Playlist Converter Convert a text file of songs to a playlist on your Spotify account. Create your playlists faster instead of manually searching for

Priya Aggarwal 18 Dec 21, 2022
This is a simple Python bot to identify sentiments in tweets

Twitter-Sentiment 👋 Hi There! 📱 This is a simple Python bot to identify sentiments in tweets 👨‍💻 This project was made for study, and pratice. You

Guilherme Silva 1 Oct 28, 2021
Discord Rich Presence for Team Fortress 2

TF2 Rich Presence Discord Rich Presence for Team Fortress 2 Detects current game state, queue info, playtime, and more Configurable, reliable, and per

Kataiser 33 Dec 31, 2022
Um bot simples para seguir as pessoas

Um bot simples para seguir pessoas no instagram, criado apeanas para testes. Utilizando o framework "Selenium", criei um bot para entrar em uma conta

Mobben 1 Nov 05, 2021
Repositório para meu Discord Bot pessoal

BassetinhoBot Escrevi o código usando o Python 3.8.3 e até agora não tive problemas rodando nas versões mais recentes. Repositório para o Discord Bot

Vinícius Bassete 1 Jan 04, 2022
Alcarin Tengwar - a Tengwar typeface designed to pair well with the Brill typeface

Alcarin Tengwar Alcarin Tengwar is a Tengwar typeface designed to pair well with

Toshi Omagari 23 Nov 02, 2022
A simple worker for OpenClubhouse to sync data.

OpenClubhouse-Worker This is a simple worker for OpenClubhouse to sync CH channel data.

100 Dec 17, 2022
Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar seu próprio token, e lembrando, é um bot básico, não se utiliza Cogs nem slash commands nele!

BotDiscordPython Aqui está disponível GRATUITAMENTE, um bot de discord feito em python, saiba que, terá que criar seu bot como aplicação, e utilizar s

Matheus Muguet 4 Feb 05, 2022
Asyncevents: a small library to help developers perform asynchronous event handling in Python

asyncevents - Asynchronous event handling for modern Python asyncevents is a small library to help developers perform asynchronous event handling in m

Mattia 5 Aug 07, 2022
Marketplace for self published books

Nile API API for the imaginary Nile marketplace for self published books. This is a project created to try out FastAPI as the post promising ASGI serv

Matt de Young 1 Jan 31, 2022
Análise de dados abertos do programa Taxigov.

Análise de dados do Taxigov Este repositório contém os cadernos Jupyter usados no projeto de análise de dados do Taxigov. Conjunto de dados O conjunto

Augusto Herrmann 1 Jan 10, 2022
Send OpenWeatherMap alerts (One Call API) to telegram users.

OpenWeatherMap Telegram Alert Send OpenWeatherMap alerts (One Call API) to telegram users. Installation Requirements: $ apt install python3-yaml pytho

Michael Hacker 1 Jun 04, 2022
OpenSea Python Bot coded purely in Python3.

OpenSea Python Bot coded purely in Python3. It utilises everything from OpenSea API to continuously monitor NFT's. It can be used to snipe or monitor if something falls below floor value.

OpenSea Elite Sniper 20 Dec 29, 2021
:lock: Python 2.7/3.X client for HashiCorp Vault

hvac HashiCorp Vault API client for Python 3.x Tested against the latest release, HEAD ref, and 3 previous minor versions (counting back from the late

hvac 1k Dec 29, 2022
Python API Client for Twitter API v2

🐍 Python Client For Twitter API v2 🚀 Why Twitter Stream ? Twitter-Stream.py a python API client for Twitter API v2 now supports FilteredStream, Samp

Twitivity 31 Nov 19, 2022
It's a simple python script to take backup of directories (compressing) then the same to move your mentioned S3 bucket with the help of AWS IAM User.

Directory Backup Moved to S3 (Pyscript) Description Here it's a python script that needs to use this script simply create a directory backup and moved

Yousaf K Hamza 3 Mar 04, 2022
DeleteAllBot - Telegram bot to delete all messages in a group

Delete All Bot A star ⭐ from you means a lot to me ! Telegram bot to delete all

Stark Bots 15 Dec 26, 2022