Session

class fbchat.Session(*, user_id, fb_dtsg, revision, session=NOTHING, counter=0, client_id=NOTHING)[source]

Stores and manages state required for most Facebook requests.

This is the main class, which is used to login to Facebook.

property user

The logged in user.

classmethod login(email, password, on_2fa_callback=None)[source]

Login the user, using email and password.

Parameters
  • email (str) – Facebook email, id or phone number

  • password (str) – Facebook account password

  • on_2fa_callback (Optional[Callable[[], int]]) –

    Function that will be called, in case a two factor authentication code is needed. This should return the requested code.

    Only tested with SMS codes, might not work with authentication apps.

    Note: Facebook limits the amount of codes they will give you, so if you don’t receive a code, be patient, and try again later!

Example

>>> import fbchat
>>> import getpass
>>> session = fbchat.Session.login(
...     input("Email: "),
...     getpass.getpass(),
...     on_2fa_callback=lambda: input("2FA Code: ")
... )
Email: abc@gmail.com
Password: ****
2FA Code: 123456
>>> session.user.id
"1234"
is_logged_in()[source]

Send a request to Facebook to check the login status.

Return type

bool

Returns

Whether the user is still logged in

Example

>>> assert session.is_logged_in()
logout()[source]

Safely log out the user.

The session object must not be used after this action has been performed!

Example

>>> session.logout()
Return type

None

get_cookies()[source]

Retrieve session cookies, that can later be used in from_cookies.

Return type

Mapping[str, str]

Returns

A dictionary containing session cookies

Example

>>> cookies = session.get_cookies()
classmethod from_cookies(cookies)[source]

Load a session from session cookies.

Parameters

cookies (Mapping[str, str]) – A dictionary containing session cookies

Example

>>> cookies = session.get_cookies()
>>> # Store cookies somewhere, and then subsequently
>>> session = fbchat.Session.from_cookies(cookies)