Compare commits

...

118 Commits

Author SHA1 Message Date
Mads Marquart
e6bc5bbab3 Version up, thanks to @kapi2289 and @2FWAH 2019-01-31 20:20:17 +01:00
Mads Marquart
de5f3a9d9e Merge branch 'pr/300' 2019-01-31 20:13:27 +01:00
Mads Marquart
7f0da012c2 Few nitpicky fixes 2019-01-31 20:12:59 +01:00
Mads Marquart
76ecbf5eb0 Merge branch 'pr/325' 2019-01-31 19:57:22 +01:00
Mads Marquart
06881a4c70 Add formatMentions docstring 2019-01-31 19:56:35 +01:00
Mads Marquart
c14fdd82db Merge branch 'pr/338' 2019-01-31 19:29:54 +01:00
Mads Marquart
b1a02ad930 Merge pull request #342 from kapi2289/quick_replies
[Feature] Quick replies
2019-01-31 19:26:03 +01:00
Mads Marquart
2b580c60e9 Readd deprecated markAlive parameter 2019-01-31 19:23:46 +01:00
Mads Marquart
27ffba3b14 Fix a few isinstance checks 2019-01-31 19:21:52 +01:00
Mads Marquart
fb7bf437ba Merge pull request #384 from carpedm20/github-releases-ci
Automatic GitHub Releases
2019-01-25 20:01:37 +01:00
Mads Marquart
d8baf0b9e7 Put automatic GitHub releases in the draft state
This is done so that I can edit the description as needed, before publishing
2019-01-25 19:35:20 +01:00
Mads Marquart
a6945fe880 Merge branch 'disable-online-tests' 2019-01-25 19:18:03 +01:00
Mads Marquart
6ff77dd8c7 Merge pull request #382 from carpedm20/flit
Use `flit` as our build system
2019-01-25 19:14:04 +01:00
Mads Marquart
1d925a608b Update pypy version to 3.5 2019-01-25 18:53:14 +01:00
Mads Marquart
646669ca75 Add Github Releases deployment 2019-01-25 18:49:56 +01:00
Mads Marquart
0ec2baaa83 Add Python 3.7 testing 2019-01-25 18:49:35 +01:00
Mads Marquart
5abaaefd1c Disable Travis online tests 2019-01-25 18:49:08 +01:00
Mads Marquart
687afea0f2 Pin minimum pytest version to fix tests 2019-01-25 17:45:15 +01:00
Mads Marquart
7398d4fa2b Use --python option to properly install the package under Python 2.7 2019-01-25 17:14:14 +01:00
Mads Marquart
d73c8c3627 Fix travis setup for running flit under Python 2.7 2019-01-25 17:05:35 +01:00
Mads Marquart
f921b91c5b Make travis use flit 2019-01-25 16:43:22 +01:00
Mads Marquart
8ed3c1b159 Use flit instead of setuptools
Mostly just a simple move from `setup.cfg` -> `pyproject.toml`. Had to reformat the description in `__init__` a little though.
2019-01-25 16:36:09 +01:00
Mads Marquart
4f947cdbb5 Version up, thanks to @kapi2289 and @kaushalvivek 2019-01-25 16:01:47 +01:00
Mads Marquart
ec6c29052a Merge pull request #371 from carpedm20/fix-enums
Fix `ThreadColor` and `MessageReaction` enums
2019-01-24 22:42:41 +01:00
Mads Marquart
6b117502f3 Merge branch 'master' into fix-enums 2019-01-24 22:40:44 +01:00
Kacper Ziubryniewicz
a367aa0b31 Replying on location quick replies 2019-01-05 20:40:45 +01:00
Kacper Ziubryniewicz
7f6843df55 Better quick reply types 2019-01-05 20:06:28 +01:00
Kacper Ziubryniewicz
4b485d54b6 Merge remote-tracking branch 'origin/master' into quick_replies 2019-01-05 19:29:32 +01:00
Kacper Ziubryniewicz
e80a040db4 Deprecate markAlive parameter in doOneListen and _pullMessage 2019-01-05 18:48:40 +01:00
Kacper Ziubryniewicz
c357fd085b Better listening for buddylist overlay and chatbox presence 2019-01-05 18:36:48 +01:00
Kacper Ziubryniewicz
d0c5f29b0a Fixed getting active status 2019-01-05 18:24:23 +01:00
Mads Marquart
3e7b20c379 Merge pull request #377 from kapi2289/fix-fbchatexception
Fixed typos in FBchatException
2019-01-05 18:20:38 +01:00
Kacper Ziubryniewicz
f4a997c0ef Fixed typos in FBchatException 2019-01-05 17:55:54 +01:00
Kacper Ziubryniewicz
102e74bb63 Merge remote-tracking branch 'origin/master' into active_status 2019-01-05 17:46:27 +01:00
Mads Marquart
84fa15e44c Merge pull request #333 from kapi2289/extensible_attachments
[Feature] Extensible attachments
2019-01-04 21:06:11 +01:00
Kacper Ziubryniewicz
7b8ecf8fe3 Changed deleted to unsent 2019-01-04 20:02:00 +01:00
Kacper Ziubryniewicz
79ebf920ea More on responding to quick replies 2019-01-03 23:28:23 +01:00
Kacper Ziubryniewicz
0d05d42f70 getPhoneNumbers and getEmails methods 2019-01-03 22:54:47 +01:00
Kacper Ziubryniewicz
95989b6da7 Merge branch 'master' into extensible_attachments 2018-12-23 14:58:03 +01:00
Kacper Ziubryniewicz
22e57f99a1 deleted attribute of Message
and batter handling of deleted (unsended) messages
2018-12-23 14:56:27 +01:00
Kacper Ziubryniewicz
b9d29c0417 Removed addReaction, removeReaction, _react
(and undeprecated `reactToMessage`)
2018-12-23 14:45:17 +01:00
Kacper Ziubryniewicz
edc33db9e8 Few fixes in quick replies 2018-12-23 14:36:26 +01:00
Mads Marquart
45d8b45d96 Fix enum_extend_if_invalid warning 2018-12-12 23:22:08 +01:00
Mads Marquart
b6a6d7dc68 Move enum_extend_if_invalid to utils.py 2018-12-12 23:06:16 +01:00
Mads Marquart
c57b84cd0b Refactor enum extending 2018-12-12 23:04:26 +01:00
Mads Marquart
78e7841b5e Extend MessageReaction when encountering unknown values 2018-12-12 22:53:23 +01:00
Mads Marquart
e41d981449 Extend ThreadColor when encountering unknown values 2018-12-12 22:44:19 +01:00
Mads Marquart
381227af66 Make use aenum instead of the default enum 2018-12-12 22:39:31 +01:00
Mads Marquart
2f8d0728ba Merge pull request #366 from kaushalvivek/master
Fix for issue #365
2018-12-10 21:16:57 +01:00
kaushalvivek
13bfc5f2f9 Fix for search limit 2018-12-10 14:46:04 +05:30
Mads Marquart
f8d3b571ba Version up, thanks to @ekohilas and @kapi2289 2018-12-09 21:21:00 +01:00
Mads Marquart
64b1e52d4c Merge pull request #357 from carpedm20/fixed-listening
Fixed listening
2018-12-09 19:23:33 +01:00
Mads Marquart
b650f7ee9a Merge pull request #367 from carpedm20/fix-pytest-deprecation
Fix pytest "Applying marks directly to parameters" deprecation
2018-12-09 19:23:20 +01:00
Kacper Ziubryniewicz
d4446280c7 Detecting when someone unsends a message 2018-12-09 15:27:01 +01:00
Mads Marquart
3443a233f4 Fix pytest "Applying marks directly to parameters" deprecation 2018-12-09 15:02:48 +01:00
Kacper Ziubryniewicz
861f17bc4d Added DeletedMessage attachment 2018-12-09 14:55:10 +01:00
Kacper Ziubryniewicz
41bbe18e3d Unsending messages 2018-12-09 14:36:23 +01:00
Kacper Ziubryniewicz
5f9c357a15 Fixed graphql and added method for replying on quick replies 2018-12-09 01:07:33 +01:00
Kacper Ziubryniewicz
c089298f46 Sending new quick replies 2018-12-09 00:57:58 +01:00
Kacper Ziubryniewicz
be968e0caa New models for quick replies 2018-12-09 00:32:44 +01:00
Vivek Kaushal
d32b7b612a Fix for issue #365 2018-12-07 21:26:48 +05:30
Mads Marquart
160386be62 Added support for request_batch parsing in _parseMessage 2018-11-09 20:08:26 +01:00
Mads Marquart
64bdde8f33 Sticky and pool parameters can be set after the inital _fetchSticky 2018-11-07 20:06:10 +01:00
Kacper Ziubryniewicz
8739318101 Sending voice clips 2018-10-30 22:24:47 +01:00
Kacper Ziubryniewicz
1ac569badd Sending pinned or current location 2018-10-30 22:21:05 +01:00
Kacper Ziubryniewicz
e38f891693 Active status fixes 2018-10-30 21:48:55 +01:00
Mads Marquart
89a277c354 Merge pull request #354 from ekohilas/master
separate spellchecked docs
2018-10-28 12:46:48 +01:00
Mads Marquart
8238387c7d Merge pull request #353 from ekohilas/docstrings
completed todo for graphql_requests
2018-10-28 12:45:37 +01:00
ekohilas
6c829581af completed todo for graphql_requests 2018-10-27 02:02:15 +11:00
ekohilas
d180650c1b spellchecked docs 2018-10-25 18:18:19 +11:00
Mads Marquart
772bf5518f Merge pull request #346 from kapi2289/remove_unnecessary
Remove unnecessary code
2018-10-07 16:50:31 +02:00
Kacper Ziubryniewicz
153dc0bdad Remove unnecessary code 2018-10-07 16:27:19 +02:00
Kacper Ziubryniewicz
b7ea8e6001 New sendLocation method 2018-09-29 13:48:08 +02:00
Kacper Ziubryniewicz
b0bf5ba8e0 Update graphql.py 2018-09-29 13:42:11 +02:00
Kacper Ziubryniewicz
8169a5f776 Changed LocationAttachment 2018-09-29 13:40:38 +02:00
Mads Marquart
b4b8914448 Version up, thanks to @kapi2289 2018-09-27 21:53:12 +02:00
Mads Marquart
2ea2c89b4a Fixed markAsRead and markAsUnread, fixes #336 2018-09-27 21:44:04 +02:00
Mads Marquart
479ca59a6a Merge pull request #341 from kapi2289/read_by
[Feature] New `read_by` attribute of `Message`
2018-09-27 20:56:13 +02:00
Mads Marquart
343f987a78 Merge pull request #340 from kapi2289/fix_fetch_thread_list
[Fix] `fetchThreadList` fix
2018-09-27 20:27:03 +02:00
Kacper Ziubryniewicz
492465a525 Update graphql.py 2018-09-25 18:00:44 +02:00
Kacper Ziubryniewicz
f185e44f93 Update models.py 2018-09-25 17:59:16 +02:00
Kacper Ziubryniewicz
5f2c318baf Sending quick replies 2018-09-24 21:04:21 +02:00
Kacper Ziubryniewicz
531a5b77d0 GraphQL method for quick replies 2018-09-24 20:57:19 +02:00
Kacper Ziubryniewicz
f9245cdfed New model and Message attribute
New `QuickReply` model and `quick_replies` attribute of `Message` model.
2018-09-24 20:54:25 +02:00
Kacper Ziubryniewicz
bad9c7a4b9 read_by handling 2018-09-24 20:33:43 +02:00
Kacper Ziubryniewicz
576e0949e0 New read_by attribute in Message 2018-09-24 20:32:04 +02:00
Kacper Ziubryniewicz
d807648d2b fetchThreadList fix 2018-09-24 16:50:15 +02:00
Kacper Ziubryniewicz
47ea88e025 Read commit description
- Fixed `onImageChange` documentation and added missing `msg` parameter
- Moved `on` methods to the right place
- Added changing client active status while listening
- Added fetching friends' active status
2018-09-22 21:52:40 +02:00
Kacper Ziubryniewicz
345a473ee0 ActiveStatus model 2018-09-22 21:34:44 +02:00
Kacper Ziubryniewicz
c6dc432d06 Move on methods to the right place 2018-09-22 20:39:41 +02:00
2FWAH
af3bd55535 Add basic test for fetchThreads 2018-09-21 19:43:39 +02:00
2FWAH
5fa1d86191 Add before, after and limit parameters to fetchThreads 2018-09-21 19:12:46 +02:00
2FWAH
d4859b675a Fix ident for _forcedFetch 2018-09-21 17:36:16 +02:00
2FWAH
9aa427031e Merge from upstream and solve conflict in fbchat/client.py 2018-09-21 17:29:58 +02:00
Kacper Ziubryniewicz
9e8fe7bc1e Fix Python 2.7 compability 2018-09-15 11:34:16 +02:00
Kacper Ziubryniewicz
90813c959d Added get_url_parameters util method 2018-09-15 11:21:35 +02:00
Kacper Ziubryniewicz
940a65954c Read commit description
Added:
- Detecting extensible attachments
- Fetching live user location
- New methods for message reacting
- New `on` methods: `onReactionAdded`, `onReactionRemoved`, `onBlock`, `onUnblock`, `onLiveLocation`
- Fixed `size` of attachments
2018-09-12 17:52:38 +02:00
Kacper Ziubryniewicz
9b4e753a79 Added graphql methods for extensible attachments 2018-09-12 17:48:35 +02:00
Kacper Ziubryniewicz
e0be9029e4 Added extensible attachments models 2018-09-12 17:48:00 +02:00
Kacper Ziubryniewicz
0ae213c240 Merge pull request #1 from carpedm20/master
Merge `master`
2018-09-12 17:41:53 +02:00
Mads Marquart
08117e7a54 Fixed examples, see #332
The examples were using generator expressions instead of list comprehensions
2018-09-09 14:24:20 +02:00
Mads Marquart
51c3226070 Merge pull request #326 from kapi2289/merge_rooms
Merge `Room` with `Group`
2018-09-09 14:09:36 +02:00
Mads Marquart
5396d19d7d Merge pull request #327 from kapi2289/fix_active
`markAlive` fix
2018-09-09 14:07:48 +02:00
Kacper Ziubryniewicz
11501e6899 Fix Room model initialization 2018-09-03 15:05:11 +02:00
Kacper Ziubryniewicz
4eb49b9119 Backwards compability for Rooms 2018-08-31 13:25:37 +02:00
Kacper Ziubryniewicz
4c2da22750 markAlive fix 2018-08-30 20:28:32 +02:00
Kacper Ziubryniewicz
753b9cbae2 Merge Room with Group methods 2018-08-30 19:57:47 +02:00
Kacper Ziubryniewicz
2c73cabe22 Merge Room with Group graphql methods 2018-08-30 19:57:12 +02:00
Kacper Ziubryniewicz
d6ca091b7b Merge Room with Group model 2018-08-30 19:56:18 +02:00
Kacper Ziubryniewicz
aa3faca246 Added formatMentions method 2018-08-30 15:57:16 +02:00
2FWAH
2edb95dfdd Fetch missing users in a single request 2018-06-12 08:38:02 +02:00
2FWAH
e0bb9960fb Check if list is empty with if instead of len() 2018-06-12 08:15:53 +02:00
2FWAH
71608845c0 Use snake case convention 2018-06-12 07:55:16 +02:00
2FWAH
0048e82151 Fix typo in fetchAllUsersFromThreads 2018-06-07 21:58:00 +02:00
2FWAH
0767ef4902 Add fetchAllUsersFromThreads
Add a method to get all users involved in threads (given as a parameter)
2018-06-01 23:27:34 +02:00
2FWAH
abe3357e67 Explicit parameter thread_location 2018-06-01 23:08:03 +02:00
2FWAH
19457efe9b Fix call to fetchThreadList
Use "self" instead of "client"
2018-06-01 23:06:02 +02:00
2FWAH
487a2eb3e3 Add fetchThreads method
Add a method to get all threads in Location (INBOX, ARCHIVED...)
2018-06-01 22:59:56 +02:00
27 changed files with 1139 additions and 389 deletions

View File

@@ -1,90 +1,50 @@
sudo: false sudo: false
language: python language: python
conditions: v1 python: 3.6
# There are two accounts made specifically for Travis, and the passwords are really only encrypted for obscurity cache: pip
# The global env variables `client1_email`, `client1_password`, `client2_email`, `client2_password` and `group_id`
# are set on the Travis Settings page
# The tests are run with `Limit concurrent jobs = 1`, since the tests can't use the clients simultaneously before_install: pip install flit
install: flit install --deps production --extras test
install: script: pytest -m offline
- pip install -U -r requirements.txt
- pip install -U -r dev-requirements.txt
cache:
pip: true
# Pytest caching is disabled, since TravisCI instances have different public IPs. Facebook doesn't like that,
# and redirects you to the url `/checkpoint/block`, where you have to change the account's password
# directories:
# - .pytest_cache
jobs: jobs:
include: include:
# The tests are split into online and offline versions. - python: 2.7
# The online tests are only run against the master branch. before_install:
# Because: - sudo apt-get -y install python3-pip python3-setuptools
# Travis caching is per-branch and per-job, so even though we cache the Facebook sessions via. `.pytest_cache` - sudo pip3 install flit
# and in `tests.utils.load_client`, we need 6 new sessions per branch. This is usually the point where Facebook install: flit install --python python --deps production --extras test
# starts complaining, and we have to manually fix it - python: 3.4
- python: 3.5
- python: 3.6
- python: 3.7
dist: xenial
sudo: required
- python: pypy3.5
- &test-online - stage: deploy
if: (branch = master OR tag IS present) AND type != pull_request name: Github Releases
stage: online tests if: tag IS present
script: scripts/travis-online
# Run online tests in all the supported python versions
python: 2.7
- <<: *test-online
python: 3.4
- <<: *test-online
python: 3.5
- <<: *test-online
python: 3.6
- <<: *test-online
python: pypy
# Run the expensive tests, with the python version most likely to break, aka. 2
- <<: *test-online
# Only run if the commit message includes [ci all] or [all ci]
if: commit_message =~ /\[ci\s+all\]|\[all\s+ci\]/
python: 2.7
env: PYTEST_ADDOPTS='-m expensive'
- &test-offline
# Ideally, it'd be nice to run the offline tests in every build, but since we can't run jobs concurrently (yet),
# we'll disable them when they're not needed, and include them inside the online tests instead
if: not ((branch = master OR tag IS present) AND type != pull_request)
stage: offline tests
script: scripts/travis-offline
# Run offline tests in all the supported python versions
python: 2.7
- <<: *test-offline
python: 3.4
- <<: *test-offline
python: 3.5
- <<: *test-offline
python: 3.6
- <<: *test-offline
python: 3.6
- <<: *test-offline
python: pypy
# Deploy to PyPI
- &deploy
stage: deploy
if: branch = master AND tag IS present
install: skip install: skip
script: flit build
deploy: deploy:
provider: pypi provider: releases
user: madsmtm api_key: $GITHUB_OAUTH_TOKEN
password: file_glob: true
secure: "VA0MLSrwIW/T2KjMwjLZCzrLHw8pJT6tAvb48t7qpBdm8x192hax61pz1TaBZoJvlzyBPFKvluftuclTc7yEFwzXe7Gjqgd/ODKZl/wXDr36hQ7BBOLPZujdwmWLvTzMh3eJZlvkgcLCzrvK3j2oW8cM/+FZeVi/5/FhVuJ4ofs=" file: dist/*
distributions: sdist bdist_wheel skip_cleanup: true
skip_existing: true draft: true
on:
tags: true
# We need the bdist_wheels from both Python 2 and 3 - stage: deploy
python: 3.6 name: PyPI
- <<: *deploy if: tag IS present
python: 2.7 install: skip
script: skip
deploy:
provider: script
script: flit publish
on:
tags: true

View File

@@ -1,3 +0,0 @@
include LICENSE
include CONTRIBUTING.rst
include README.rst

View File

@@ -5,9 +5,9 @@ fbchat: Facebook Chat (Messenger) for Python
:target: https://github.com/carpedm20/fbchat/tree/master/LICENSE :target: https://github.com/carpedm20/fbchat/tree/master/LICENSE
:alt: License: BSD 3-Clause :alt: License: BSD 3-Clause
.. image:: https://img.shields.io/badge/python-2.7%2C%203.4%2C%203.5%2C%203.6%20pypy-blue.svg .. image:: https://img.shields.io/badge/python-2.7%2C%203.4%2C%203.5%2C%203.6%203.7%20pypy-blue.svg
:target: https://pypi.python.org/pypi/fbchat :target: https://pypi.python.org/pypi/fbchat
:alt: Supported python versions: 2.7, 3.4, 3.5, 3.6 and pypy :alt: Supported python versions: 2.7, 3.4, 3.5, 3.6, 3.7 and pypy
.. image:: https://readthedocs.org/projects/fbchat/badge/?version=master .. image:: https://readthedocs.org/projects/fbchat/badge/?version=master
:target: https://fbchat.readthedocs.io :target: https://fbchat.readthedocs.io
@@ -27,17 +27,18 @@ or jump right into the code by viewing the `examples <https://github.com/carpedm
Installation: Installation:
.. code-block:: console .. code-block::
$ pip install fbchat $ pip install fbchat
You can also install from source, by using `setuptools` (You need at least version 30.3.0): You can also install from source, by using `flit`:
.. code-block:: console .. code-block::
$ pip install flit
$ git clone https://github.com/carpedm20/fbchat.git $ git clone https://github.com/carpedm20/fbchat.git
$ cd fbchat $ cd fbchat
$ python setup.py install $ flit install
Maintainer Maintainer

View File

@@ -1,2 +0,0 @@
pytest
six

View File

@@ -13,7 +13,7 @@ If you are looking for information on a specific function, class, or method, thi
Client Client
------ ------
This is the main class of `fbchat`, which contains all the methods you use to interract with Facebook. This is the main class of `fbchat`, which contains all the methods you use to interact with Facebook.
You can extend this class, and overwrite the events, to provide custom event handling (mainly used while listening) You can extend this class, and overwrite the events, to provide custom event handling (mainly used while listening)
.. autoclass:: Client(email, password, user_agent=None, max_tries=5, session_cookies=None, logging_level=logging.INFO) .. autoclass:: Client(email, password, user_agent=None, max_tries=5, session_cookies=None, logging_level=logging.INFO)

View File

@@ -18,7 +18,7 @@ This will show basic usage of `fbchat`
Interacting with Threads Interacting with Threads
------------------------ ------------------------
This will interract with the thread in every way `fbchat` supports This will interact with the thread in every way `fbchat` supports
.. literalinclude:: ../examples/interract.py .. literalinclude:: ../examples/interract.py

View File

@@ -8,7 +8,7 @@ FAQ
Version X broke my installation Version X broke my installation
------------------------------- -------------------------------
We try to provide backwards compatability where possible, but since we're not part of Facebook, We try to provide backwards compatibility where possible, but since we're not part of Facebook,
most of the things may be broken at any point in time most of the things may be broken at any point in time
Downgrade to an earlier version of fbchat, run this command Downgrade to an earlier version of fbchat, run this command

View File

@@ -6,7 +6,7 @@ Introduction
============ ============
`fbchat` uses your email and password to communicate with the Facebook server. `fbchat` uses your email and password to communicate with the Facebook server.
That means that you should always store your password in a seperate file, in case e.g. someone looks over your shoulder while you're writing code. That means that you should always store your password in a separate file, in case e.g. someone looks over your shoulder while you're writing code.
You should also make sure that the file's access control is appropriately restrictive You should also make sure that the file's access control is appropriately restrictive
@@ -16,7 +16,7 @@ Logging In
---------- ----------
Simply create an instance of :class:`Client`. If you have two factor authentication enabled, type the code in the terminal prompt Simply create an instance of :class:`Client`. If you have two factor authentication enabled, type the code in the terminal prompt
(If you want to supply the code in another fasion, overwrite :func:`Client.on2FACode`):: (If you want to supply the code in another fashion, overwrite :func:`Client.on2FACode`)::
from fbchat import Client from fbchat import Client
from fbchat.models import * from fbchat.models import *
@@ -50,7 +50,7 @@ A thread can refer to two things: A Messenger group chat or a single Facebook us
:class:`models.ThreadType` is an enumerator with two values: ``USER`` and ``GROUP``. :class:`models.ThreadType` is an enumerator with two values: ``USER`` and ``GROUP``.
These will specify whether the thread is a single user chat or a group chat. These will specify whether the thread is a single user chat or a group chat.
This is required for many of `fbchat`'s functions, since Facebook differetiates between these two internally This is required for many of `fbchat`'s functions, since Facebook differentiates between these two internally
Searching for group chats and finding their ID can be done via. :func:`Client.searchForGroups`, Searching for group chats and finding their ID can be done via. :func:`Client.searchForGroups`,
and searching for users is possible via. :func:`Client.searchForUsers`. See :ref:`intro_fetching` and searching for users is possible via. :func:`Client.searchForUsers`. See :ref:`intro_fetching`
@@ -141,7 +141,7 @@ Sessions
-------- --------
`fbchat` provides functions to retrieve and set the session cookies. `fbchat` provides functions to retrieve and set the session cookies.
This will enable you to store the session cookies in a seperate file, so that you don't have to login each time you start your script. This will enable you to store the session cookies in a separate file, so that you don't have to login each time you start your script.
Use :func:`Client.getSession` to retrieve the cookies:: Use :func:`Client.getSession` to retrieve the cookies::
session_cookies = client.getSession() session_cookies = client.getSession()

View File

@@ -8,8 +8,8 @@ client = Client('<email>', '<password>')
# Fetches a list of all users you're currently chatting with, as `User` objects # Fetches a list of all users you're currently chatting with, as `User` objects
users = client.fetchAllUsers() users = client.fetchAllUsers()
print("users' IDs: {}".format(user.uid for user in users)) print("users' IDs: {}".format([user.uid for user in users]))
print("users' names: {}".format(user.name for user in users)) print("users' names: {}".format([user.name for user in users]))
# If we have a user id, we can use `fetchUserInfo` to fetch a `User` object # If we have a user id, we can use `fetchUserInfo` to fetch a `User` object
@@ -18,7 +18,7 @@ user = client.fetchUserInfo('<user id>')['<user id>']
users = client.fetchUserInfo('<1st user id>', '<2nd user id>', '<3rd user id>') users = client.fetchUserInfo('<1st user id>', '<2nd user id>', '<3rd user id>')
print("user's name: {}".format(user.name)) print("user's name: {}".format(user.name))
print("users' names: {}".format(users[k].name for k in users)) print("users' names: {}".format([users[k].name for k in users]))
# `searchForUsers` searches for the user and gives us a list of the results, # `searchForUsers` searches for the user and gives us a list of the results,

View File

@@ -1,12 +1,7 @@
# -*- coding: UTF-8 -*- # -*- coding: UTF-8 -*-
"""Facebook Chat (Messenger) for Python
""" :copyright: (c) 2015 - 2019 by Taehoon Kim
fbchat
~~~~~~
Facebook Chat (Messenger) for Python
:copyright: (c) 2015 - 2018 by Taehoon Kim
:license: BSD 3-Clause, see LICENSE for more details. :license: BSD 3-Clause, see LICENSE for more details.
""" """
@@ -15,10 +10,10 @@ from __future__ import unicode_literals
from .client import * from .client import *
__title__ = 'fbchat' __title__ = 'fbchat'
__version__ = '1.4.0' __version__ = '1.6.0'
__description__ = 'Facebook Chat (Messenger) for Python' __description__ = 'Facebook Chat (Messenger) for Python'
__copyright__ = 'Copyright 2015 - 2018 by Taehoon Kim' __copyright__ = 'Copyright 2015 - 2019 by Taehoon Kim'
__license__ = 'BSD 3-Clause' __license__ = 'BSD 3-Clause'
__author__ = 'Taehoon Kim; Moreels Pieter-Jan; Mads Marquart' __author__ = 'Taehoon Kim; Moreels Pieter-Jan; Mads Marquart'

File diff suppressed because it is too large Load Diff

View File

@@ -26,12 +26,11 @@ class ConcatJSONDecoder(json.JSONDecoder):
def graphql_color_to_enum(color): def graphql_color_to_enum(color):
if color is None: if color is None:
return None return None
if len(color) == 0: if not color:
return ThreadColor.MESSENGER_BLUE return ThreadColor.MESSENGER_BLUE
try: color = color[2:] # Strip the alpha value
return ThreadColor('#{}'.format(color[2:].lower())) color_value = '#{}'.format(color.lower())
except ValueError: return enum_extend_if_invalid(ThreadColor, color_value)
raise FBchatException('Could not get ThreadColor from color: {}'.format(color))
def get_customization_info(thread): def get_customization_info(thread):
if thread is None or thread.get('customization_info') is None: if thread is None or thread.get('customization_info') is None:
@@ -42,7 +41,7 @@ def get_customization_info(thread):
'emoji': info.get('emoji'), 'emoji': info.get('emoji'),
'color': graphql_color_to_enum(info.get('outgoing_bubble_color')) 'color': graphql_color_to_enum(info.get('outgoing_bubble_color'))
} }
if thread.get('thread_type') in ('GROUP', 'ROOM') or thread.get('is_group_thread') or thread.get('thread_key', {}).get('thread_fbid'): if thread.get('thread_type') == 'GROUP' or thread.get('is_group_thread') or thread.get('thread_key', {}).get('thread_fbid'):
rtn['nicknames'] = {} rtn['nicknames'] = {}
for k in info.get('participant_customizations', []): for k in info.get('participant_customizations', []):
rtn['nicknames'][k['participant_id']] = k.get('nickname') rtn['nicknames'][k['participant_id']] = k.get('nickname')
@@ -128,9 +127,84 @@ def graphql_to_attachment(a):
uid=a.get('legacy_attachment_id') uid=a.get('legacy_attachment_id')
) )
def graphql_to_extensible_attachment(a):
story = a.get('story_attachment')
if story:
target = story.get('target')
if target:
_type = target['__typename']
if _type == 'MessageLocation':
latitude, longitude = get_url_parameter(get_url_parameter(story['url'], 'u'), 'where1').split(", ")
rtn = LocationAttachment(
uid=int(story['deduplication_key']),
latitude=float(latitude),
longitude=float(longitude),
)
if story['media']:
rtn.image_url = story['media']['image']['uri']
rtn.image_width = story['media']['image']['width']
rtn.image_height = story['media']['image']['height']
rtn.url = story['url']
return rtn
elif _type == 'MessageLiveLocation':
rtn = LiveLocationAttachment(
uid=int(story['target']['live_location_id']),
latitude=story['target']['coordinate']['latitude'] if story['target'].get('coordinate') else None,
longitude=story['target']['coordinate']['longitude'] if story['target'].get('coordinate') else None,
name=story['title_with_entities']['text'],
expiration_time=story['target']['expiration_time'] if story['target'].get('expiration_time') else None,
is_expired=story['target']['is_expired'],
)
if story['media']:
rtn.image_url = story['media']['image']['uri']
rtn.image_width = story['media']['image']['width']
rtn.image_height = story['media']['image']['height']
rtn.url = story['url']
return rtn
elif _type in ['ExternalUrl', 'Story']:
return ShareAttachment(
uid=a.get('legacy_attachment_id'),
author=story['target']['actors'][0]['id'] if story['target'].get('actors') else None,
url=story['url'],
original_url=get_url_parameter(story['url'], 'u') if "/l.php?u=" in story['url'] else story['url'],
title=story['title_with_entities'].get('text'),
description=story['description'].get('text'),
source=story['source']['text'],
image_url=story['media']['image']['uri'] if story.get('media') else None,
original_image_url=(get_url_parameter(story['media']['image']['uri'], 'url') if "/safe_image.php" in story['media']['image']['uri'] else story['media']['image']['uri']) if story.get('media') else None,
image_width=story['media']['image']['width'] if story.get('media') else None,
image_height=story['media']['image']['height'] if story.get('media') else None,
attachments=[graphql_to_subattachment(attachment) for attachment in story.get('subattachments')],
)
else:
return UnsentMessage(
uid=a.get('legacy_attachment_id'),
)
def graphql_to_subattachment(a):
_type = a['target']['__typename']
if _type == 'Video':
return VideoAttachment(
duration=a['media'].get('playable_duration_in_ms'),
preview_url=a['media'].get('playable_url'),
medium_image=a['media'].get('image'),
uid=a['target'].get('video_id'),
)
def graphql_to_live_location(a):
return LiveLocationAttachment(
uid=a['id'],
latitude=a['coordinate']['latitude'] / (10 ** 8) if not a.get('stopReason') else None,
longitude=a['coordinate']['longitude'] / (10 ** 8) if not a.get('stopReason') else None,
name=a.get('locationTitle'),
expiration_time=a['expirationTime'],
is_expired=bool(a.get('stopReason')),
)
def graphql_to_poll(a): def graphql_to_poll(a):
rtn = Poll( rtn = Poll(
title=a.get('title') if a.get('title') else a.get("text"), title=a.get('title') if a.get('title') else a.get('text'),
options=[graphql_to_poll_option(m) for m in a.get('options')] options=[graphql_to_poll_option(m) for m in a.get('options')]
) )
rtn.uid = int(a["id"]) rtn.uid = int(a["id"])
@@ -193,6 +267,24 @@ def graphql_to_plan(a):
rtn.invited = [m.get('node').get('id') for m in guests if m.get('guest_list_state') == "INVITED"] rtn.invited = [m.get('node').get('id') for m in guests if m.get('guest_list_state') == "INVITED"]
return rtn return rtn
def graphql_to_quick_reply(q, is_response=False):
data = dict()
_type = q.get('content_type').lower()
if q.get('payload'): data["payload"] = q["payload"]
if q.get('data'): data["data"] = q["data"]
if q.get('image_url') and _type is not QuickReplyLocation._type: data["image_url"] = q["image_url"]
data["is_response"] = is_response
if _type == QuickReplyText._type:
if q.get('title') is not None: data["title"] = q["title"]
rtn = QuickReplyText(**data)
elif _type == QuickReplyLocation._type:
rtn = QuickReplyLocation(**data)
elif _type == QuickReplyPhoneNumber._type:
rtn = QuickReplyPhoneNumber(**data)
elif _type == QuickReplyEmail._type:
rtn = QuickReplyEmail(**data)
return rtn
def graphql_to_message(message): def graphql_to_message(message):
if message.get('message_sender') is None: if message.get('message_sender') is None:
message['message_sender'] = {} message['message_sender'] = {}
@@ -207,20 +299,36 @@ def graphql_to_message(message):
rtn.uid = str(message.get('message_id')) rtn.uid = str(message.get('message_id'))
rtn.author = str(message.get('message_sender').get('id')) rtn.author = str(message.get('message_sender').get('id'))
rtn.timestamp = message.get('timestamp_precise') rtn.timestamp = message.get('timestamp_precise')
rtn.unsent = False
if message.get('unread') is not None: if message.get('unread') is not None:
rtn.is_read = not message['unread'] rtn.is_read = not message['unread']
rtn.reactions = {str(r['user']['id']):MessageReaction(r['reaction']) for r in message.get('message_reactions')} rtn.reactions = {
str(r['user']['id']): enum_extend_if_invalid(MessageReaction, r['reaction'])
for r in message.get('message_reactions')
}
if message.get('blob_attachments') is not None: if message.get('blob_attachments') is not None:
rtn.attachments = [graphql_to_attachment(attachment) for attachment in message['blob_attachments']] rtn.attachments = [graphql_to_attachment(attachment) for attachment in message['blob_attachments']]
# TODO: This is still missing parsing: if message.get('platform_xmd_encoded'):
# message.get('extensible_attachment') quick_replies = json.loads(message['platform_xmd_encoded']).get('quick_replies')
if isinstance(quick_replies, list):
rtn.quick_replies = [graphql_to_quick_reply(q) for q in quick_replies]
elif isinstance(quick_replies, dict):
rtn.quick_replies = [graphql_to_quick_reply(quick_replies, is_response=True)]
if message.get('extensible_attachment') is not None:
attachment = graphql_to_extensible_attachment(message['extensible_attachment'])
if isinstance(attachment, UnsentMessage):
rtn.unsent = True
elif attachment:
rtn.attachments.append(attachment)
return rtn return rtn
def graphql_to_user(user): def graphql_to_user(user):
if user.get('profile_picture') is None: if user.get('profile_picture') is None:
user['profile_picture'] = {} user['profile_picture'] = {}
c_info = get_customization_info(user) c_info = get_customization_info(user)
plan = graphql_to_plan(user['event_reminders']['nodes'][0]) if user.get('event_reminders', dict()).get('nodes') else None plan = None
if user.get('event_reminders'):
plan = graphql_to_plan(user['event_reminders']['nodes'][0]) if user['event_reminders'].get('nodes') else None
return User( return User(
user['id'], user['id'],
url=user.get('url'), url=user.get('url'),
@@ -258,7 +366,9 @@ def graphql_to_thread(thread):
else: else:
last_name = user.get('name').split(first_name, 1).pop().strip() last_name = user.get('name').split(first_name, 1).pop().strip()
plan = graphql_to_plan(thread['event_reminders']['nodes'][0]) if thread.get('event_reminders', dict()).get('nodes') else None plan = None
if thread.get('event_reminders'):
plan = graphql_to_plan(thread['event_reminders']['nodes'][0]) if thread['event_reminders'].get('nodes') else None
return User( return User(
user['id'], user['id'],
@@ -288,13 +398,19 @@ def graphql_to_group(group):
last_message_timestamp = None last_message_timestamp = None
if 'last_message' in group: if 'last_message' in group:
last_message_timestamp = group['last_message']['nodes'][0]['timestamp_precise'] last_message_timestamp = group['last_message']['nodes'][0]['timestamp_precise']
plan = graphql_to_plan(group['event_reminders']['nodes'][0]) if group.get('event_reminders', dict()).get('nodes') else None plan = None
if group.get('event_reminders'):
plan = graphql_to_plan(group['event_reminders']['nodes'][0]) if group['event_reminders'].get('nodes') else None
return Group( return Group(
group['thread_key']['thread_fbid'], group['thread_key']['thread_fbid'],
participants=set([node['messaging_actor']['id'] for node in group['all_participants']['nodes']]), participants=set([node['messaging_actor']['id'] for node in group['all_participants']['nodes']]),
nicknames=c_info.get('nicknames'), nicknames=c_info.get('nicknames'),
color=c_info.get('color'), color=c_info.get('color'),
emoji=c_info.get('emoji'), emoji=c_info.get('emoji'),
admins = set([node.get('id') for node in group.get('thread_admins')]),
approval_mode = bool(group.get('approval_mode')) if group.get('approval_mode') is not None else None,
approval_requests = set(node["requester"]['id'] for node in group['group_approval_queue']['nodes']) if group.get('group_approval_queue') else None,
join_link = group['joinable_mode'].get('link'),
photo=group['image'].get('uri'), photo=group['image'].get('uri'),
name=group.get('name'), name=group.get('name'),
message_count=group.get('messages_count'), message_count=group.get('messages_count'),
@@ -302,34 +418,14 @@ def graphql_to_group(group):
plan=plan, plan=plan,
) )
def graphql_to_room(room):
if room.get('image') is None:
room['image'] = {}
c_info = get_customization_info(room)
plan = graphql_to_plan(room['event_reminders']['nodes'][0]) if room.get('event_reminders', dict()).get('nodes') else None
return Room(
room['thread_key']['thread_fbid'],
participants=set([node['messaging_actor']['id'] for node in room['all_participants']['nodes']]),
nicknames=c_info.get('nicknames'),
color=c_info.get('color'),
emoji=c_info.get('emoji'),
photo=room['image'].get('uri'),
name=room.get('name'),
message_count=room.get('messages_count'),
admins = set([node.get('id') for node in room.get('thread_admins')]),
approval_mode = bool(room.get('approval_mode')),
approval_requests = set(node.get('id') for node in room['thread_queue_metadata'].get('approval_requests', {}).get('nodes')),
join_link = room['joinable_mode'].get('link'),
privacy_mode = bool(room.get('privacy_mode')),
plan=plan,
)
def graphql_to_page(page): def graphql_to_page(page):
if page.get('profile_picture') is None: if page.get('profile_picture') is None:
page['profile_picture'] = {} page['profile_picture'] = {}
if page.get('city') is None: if page.get('city') is None:
page['city'] = {} page['city'] = {}
plan = graphql_to_plan(page['event_reminders']['nodes'][0]) if page.get('event_reminders', dict()).get('nodes') else None plan = None
if page.get('event_reminders'):
plan = graphql_to_plan(page['event_reminders']['nodes'][0]) if page['event_reminders'].get('nodes') else None
return Page( return Page(
page['id'], page['id'],
url=page.get('url'), url=page.get('url'),
@@ -433,6 +529,40 @@ class GraphQL(object):
}, },
outgoing_bubble_color, outgoing_bubble_color,
emoji emoji
},
thread_admins {
id
},
group_approval_queue {
nodes {
requester {
id
}
}
},
approval_mode,
joinable_mode {
mode,
link
},
event_reminders {
nodes {
id,
lightweight_event_creator {
id
},
time,
location_name,
event_title,
event_reminder_members {
edges {
node {
id
},
guest_list_state
}
}
}
} }
} }
""" """
@@ -453,7 +583,7 @@ class GraphQL(object):
""" """
SEARCH_USER = """ SEARCH_USER = """
Query SearchUser(<search> = '', <limit> = 1) { Query SearchUser(<search> = '', <limit> = 10) {
entities_named(<search>) { entities_named(<search>) {
search_results.of_type(user).first(<limit>) as users { search_results.of_type(user).first(<limit>) as users {
nodes { nodes {
@@ -465,7 +595,7 @@ class GraphQL(object):
""" + FRAGMENT_USER """ + FRAGMENT_USER
SEARCH_GROUP = """ SEARCH_GROUP = """
Query SearchGroup(<search> = '', <limit> = 1, <pic_size> = 32) { Query SearchGroup(<search> = '', <limit> = 10, <pic_size> = 32) {
viewer() { viewer() {
message_threads.with_thread_name(<search>).last(<limit>) as groups { message_threads.with_thread_name(<search>).last(<limit>) as groups {
nodes { nodes {
@@ -477,7 +607,7 @@ class GraphQL(object):
""" + FRAGMENT_GROUP """ + FRAGMENT_GROUP
SEARCH_PAGE = """ SEARCH_PAGE = """
Query SearchPage(<search> = '', <limit> = 1) { Query SearchPage(<search> = '', <limit> = 10) {
entities_named(<search>) { entities_named(<search>) {
search_results.of_type(page).first(<limit>) as pages { search_results.of_type(page).first(<limit>) as pages {
nodes { nodes {
@@ -489,7 +619,7 @@ class GraphQL(object):
""" + FRAGMENT_PAGE """ + FRAGMENT_PAGE
SEARCH_THREAD = """ SEARCH_THREAD = """
Query SearchThread(<search> = '', <limit> = 1) { Query SearchThread(<search> = '', <limit> = 10) {
entities_named(<search>) { entities_named(<search>) {
search_results.first(<limit>) as threads { search_results.first(<limit>) as threads {
nodes { nodes {

View File

@@ -1,7 +1,8 @@
# -*- coding: UTF-8 -*- # -*- coding: UTF-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import enum import aenum
from string import Formatter
class FBchatException(Exception): class FBchatException(Exception):
@@ -102,8 +103,16 @@ class Group(Thread):
color = None color = None
#: The groups's default emoji #: The groups's default emoji
emoji = None emoji = None
# Set containing user IDs of thread admins
admins = None
# True if users need approval to join
approval_mode = None
# Set containing user IDs requesting to join
approval_requests = None
# Link for joining group
join_link = None
def __init__(self, uid, participants=None, nicknames=None, color=None, emoji=None, **kwargs): def __init__(self, uid, participants=None, nicknames=None, color=None, emoji=None, admins=None, approval_mode=None, approval_requests=None, join_link=None, privacy_mode=None, **kwargs):
"""Represents a Facebook group. Inherits `Thread`""" """Represents a Facebook group. Inherits `Thread`"""
super(Group, self).__init__(ThreadType.GROUP, uid, **kwargs) super(Group, self).__init__(ThreadType.GROUP, uid, **kwargs)
if participants is None: if participants is None:
@@ -114,24 +123,6 @@ class Group(Thread):
self.nicknames = nicknames self.nicknames = nicknames
self.color = color self.color = color
self.emoji = emoji self.emoji = emoji
class Room(Group):
# Set containing user IDs of thread admins
admins = None
# True if users need approval to join
approval_mode = None
# Set containing user IDs requesting to join
approval_requests = None
# Link for joining room
join_link = None
# True is room is not discoverable
privacy_mode = None
def __init__(self, uid, admins=None, approval_mode=None, approval_requests=None, join_link=None, privacy_mode=None, **kwargs):
"""Represents a Facebook room. Inherits `Group`"""
super(Room, self).__init__(uid, **kwargs)
self.type = ThreadType.ROOM
if admins is None: if admins is None:
admins = set() admins = set()
self.admins = admins self.admins = admins
@@ -140,6 +131,16 @@ class Room(Group):
approval_requests = set() approval_requests = set()
self.approval_requests = approval_requests self.approval_requests = approval_requests
self.join_link = join_link self.join_link = join_link
class Room(Group):
# True is room is not discoverable
privacy_mode = None
def __init__(self, uid, privacy_mode=None, **kwargs):
"""Deprecated. Use :class:`Group` instead"""
super(Room, self).__init__(uid, **kwargs)
self.type = ThreadType.ROOM
self.privacy_mode = privacy_mode self.privacy_mode = privacy_mode
@@ -180,6 +181,8 @@ class Message(object):
timestamp = None timestamp = None
#: Whether the message is read #: Whether the message is read
is_read = None is_read = None
#: A list of pepole IDs who read the message, works only with :func:`fbchat.Client.fetchThreadMessages`
read_by = None
#: A dict with user's IDs as keys, and their :class:`MessageReaction` as values #: A dict with user's IDs as keys, and their :class:`MessageReaction` as values
reactions = None reactions = None
#: The actual message #: The actual message
@@ -188,8 +191,12 @@ class Message(object):
sticker = None sticker = None
#: A list of attachments #: A list of attachments
attachments = None attachments = None
#: A list of :class:`QuickReply`
quick_replies = None
#: Whether the message is unsent (deleted for everyone)
unsent = None
def __init__(self, text=None, mentions=None, emoji_size=None, sticker=None, attachments=None): def __init__(self, text=None, mentions=None, emoji_size=None, sticker=None, attachments=None, quick_replies=None):
"""Represents a Facebook message""" """Represents a Facebook message"""
self.text = text self.text = text
if mentions is None: if mentions is None:
@@ -200,7 +207,12 @@ class Message(object):
if attachments is None: if attachments is None:
attachments = [] attachments = []
self.attachments = attachments self.attachments = attachments
if quick_replies is None:
quick_replies = []
self.quick_replies = quick_replies
self.reactions = {} self.reactions = {}
self.read_by = []
self.deleted = False
def __repr__(self): def __repr__(self):
return self.__unicode__() return self.__unicode__()
@@ -208,6 +220,52 @@ class Message(object):
def __unicode__(self): def __unicode__(self):
return '<Message ({}): {}, mentions={} emoji_size={} attachments={}>'.format(self.uid, repr(self.text), self.mentions, self.emoji_size, self.attachments) return '<Message ({}): {}, mentions={} emoji_size={} attachments={}>'.format(self.uid, repr(self.text), self.mentions, self.emoji_size, self.attachments)
@classmethod
def formatMentions(cls, text, *args, **kwargs):
"""Like `str.format`, but takes tuples with a thread id and text instead.
Returns a `Message` object, with the formatted string and relevant mentions.
```
>>> Message.formatMentions("Hey {!r}! My name is {}", ("1234", "Peter"), ("4321", "Michael"))
<Message (None): "Hey 'Peter'! My name is Michael", mentions=[<Mention 1234: offset=4 length=7>, <Mention 4321: offset=24 length=7>] emoji_size=None attachments=[]>
>>> Message.formatMentions("Hey {p}! My name is {}", ("1234", "Michael"), p=("4321", "Peter"))
<Message (None): 'Hey Peter! My name is Michael', mentions=[<Mention 4321: offset=4 length=5>, <Mention 1234: offset=22 length=7>] emoji_size=None attachments=[]>
```
"""
result = ""
mentions = list()
offset = 0
f = Formatter()
field_names = [field_name[1] for field_name in f.parse(text)]
automatic = '' in field_names
i = 0
for (literal_text, field_name, format_spec, conversion) in f.parse(text):
offset += len(literal_text)
result += literal_text
if field_name is None: continue
if field_name == '':
field_name = str(i)
i += 1
elif automatic and field_name.isdigit():
raise ValueError("cannot switch from automatic field numbering to manual field specification")
thread_id, name = f.get_field(field_name, args, kwargs)[0]
if format_spec: name = f.format_field(name, format_spec)
if conversion: name = f.convert_field(name, conversion)
result += name
mentions.append(Mention(thread_id=thread_id, offset=offset, length=len(name)))
offset += len(name)
message = cls(text=result, mentions=mentions)
return message
class Attachment(object): class Attachment(object):
#: The attachment ID #: The attachment ID
uid = None uid = None
@@ -216,6 +274,12 @@ class Attachment(object):
"""Represents a Facebook attachment""" """Represents a Facebook attachment"""
self.uid = uid self.uid = uid
class UnsentMessage(Attachment):
def __init__(self, *args, **kwargs):
"""Represents an unsent message attachment"""
super(UnsentMessage, self).__init__(*args, **kwargs)
class Sticker(Attachment): class Sticker(Attachment):
#: The sticker-pack's ID #: The sticker-pack's ID
pack = None pack = None
@@ -248,9 +312,79 @@ class Sticker(Attachment):
super(Sticker, self).__init__(*args, **kwargs) super(Sticker, self).__init__(*args, **kwargs)
class ShareAttachment(Attachment): class ShareAttachment(Attachment):
def __init__(self, **kwargs): #: ID of the author of the shared post
"""Represents a shared item (eg. URL) that has been sent as a Facebook attachment - *Currently Incomplete!*""" author = None
#: Target URL
url = None
#: Original URL if Facebook redirects the URL
original_url = None
#: Title of the attachment
title = None
#: Description of the attachment
description = None
#: Name of the source
source = None
#: URL of the attachment image
image_url = None
#: URL of the original image if Facebook uses `safe_image`
original_image_url = None
#: Width of the image
image_width = None
#: Height of the image
image_height = None
#: List of additional attachments
attachments = None
def __init__(self, author=None, url=None, original_url=None, title=None, description=None, source=None, image_url=None, original_image_url=None, image_width=None, image_height=None, attachments=None, **kwargs):
"""Represents a shared item (eg. URL) that has been sent as a Facebook attachment"""
super(ShareAttachment, self).__init__(**kwargs) super(ShareAttachment, self).__init__(**kwargs)
self.author = author
self.url = url
self.original_url = original_url
self.title = title
self.description = description
self.source = source
self.image_url = image_url
self.original_image_url = original_image_url
self.image_width = image_width
self.image_height = image_height
if attachments is None:
attachments = []
self.attachments = attachments
class LocationAttachment(Attachment):
#: Latidute of the location
latitude = None
#: Longitude of the location
longitude = None
#: URL of image showing the map of the location
image_url = None
#: Width of the image
image_width = None
#: Height of the image
image_height = None
#: URL to Bing maps with the location
url = None
def __init__(self, latitude=None, longitude=None, **kwargs):
"""Represents a user location"""
super(LocationAttachment, self).__init__(**kwargs)
self.latitude = latitude
self.longitude = longitude
class LiveLocationAttachment(LocationAttachment):
#: Name of the location
name = None
#: Timestamp when live location expires
expiration_time = None
#: True if live location is expired
is_expired = None
def __init__(self, name=None, expiration_time=None, is_expired=None, **kwargs):
"""Represents a live user location"""
super(LiveLocationAttachment, self).__init__(**kwargs)
self.expiration_time = expiration_time
self.is_expired = is_expired
class FileAttachment(Attachment): class FileAttachment(Attachment):
#: Url where you can download the file #: Url where you can download the file
@@ -439,6 +573,73 @@ class Mention(object):
def __unicode__(self): def __unicode__(self):
return '<Mention {}: offset={} length={}>'.format(self.thread_id, self.offset, self.length) return '<Mention {}: offset={} length={}>'.format(self.thread_id, self.offset, self.length)
class QuickReply(object):
#: Payload of the quick reply
payload = None
#: External payload for responses
external_payload = None
#: Additional data
data = None
#: Whether it's a response for a quick reply
is_response = None
def __init__(self, payload=None, data=None, is_response=False):
"""Represents a quick reply"""
self.payload = payload
self.data = data
self.is_response = is_response
def __repr__(self):
return self.__unicode__()
def __unicode__(self):
return '<{}: payload={!r}>'.format(self.__class__.__name__, self.payload)
class QuickReplyText(QuickReply):
#: Title of the quick reply
title = None
#: URL of the quick reply image (optional)
image_url = None
#: Type of the quick reply
_type = "text"
def __init__(self, title=None, image_url=None, **kwargs):
"""Represents a text quick reply"""
super(QuickReplyText, self).__init__(**kwargs)
self.title = title
self.image_url = image_url
class QuickReplyLocation(QuickReply):
#: Type of the quick reply
_type = "location"
def __init__(self, **kwargs):
"""Represents a location quick reply (Doesn't work on mobile)"""
super(QuickReplyLocation, self).__init__(**kwargs)
self.is_response = False
class QuickReplyPhoneNumber(QuickReply):
#: URL of the quick reply image (optional)
image_url = None
#: Type of the quick reply
_type = "user_phone_number"
def __init__(self, image_url=None, **kwargs):
"""Represents a phone number quick reply (Doesn't work on mobile)"""
super(QuickReplyPhoneNumber, self).__init__(**kwargs)
self.image_url = image_url
class QuickReplyEmail(QuickReply):
#: URL of the quick reply image (optional)
image_url = None
#: Type of the quick reply
_type = "user_email"
def __init__(self, image_url=None, **kwargs):
"""Represents an email quick reply (Doesn't work on mobile)"""
super(QuickReplyEmail, self).__init__(**kwargs)
self.image_url = image_url
class Poll(object): class Poll(object):
#: ID of the poll #: ID of the poll
uid = None uid = None
@@ -520,7 +721,26 @@ class Plan(object):
def __unicode__(self): def __unicode__(self):
return '<Plan ({}): {} time={}, location={}, location_id={}>'.format(self.uid, repr(self.title), self.time, repr(self.location), repr(self.location_id)) return '<Plan ({}): {} time={}, location={}, location_id={}>'.format(self.uid, repr(self.title), self.time, repr(self.location), repr(self.location_id))
class Enum(enum.Enum): class ActiveStatus(object):
#: Whether the user is active now
active = None
#: Timestamp when the user was last active
last_active = None
#: Whether the user is playing Messenger game now
in_game = None
def __init__(self, active=None, last_active=None, in_game=None):
self.active = active
self.last_active = last_active
self.in_game = in_game
def __repr__(self):
return self.__unicode__()
def __unicode__(self):
return '<ActiveStatus: active={} last_active={} in_game={}>'.format(self.active, self.last_active, self.in_game)
class Enum(aenum.Enum):
"""Used internally by fbchat to support enumerations""" """Used internally by fbchat to support enumerations"""
def __repr__(self): def __repr__(self):
# For documentation: # For documentation:
@@ -530,8 +750,8 @@ class ThreadType(Enum):
"""Used to specify what type of Facebook thread is being used. See :ref:`intro_threads` for more info""" """Used to specify what type of Facebook thread is being used. See :ref:`intro_threads` for more info"""
USER = 1 USER = 1
GROUP = 2 GROUP = 2
ROOM = 2
PAGE = 3 PAGE = 3
ROOM = 4
class ThreadLocation(Enum): class ThreadLocation(Enum):
"""Used to specify where a thread is located (inbox, pending, archived, other).""" """Used to specify where a thread is located (inbox, pending, archived, other)."""

View File

@@ -11,13 +11,15 @@ from os.path import basename
import warnings import warnings
import logging import logging
import requests import requests
import aenum
from .models import * from .models import *
try: try:
from urllib.parse import urlencode from urllib.parse import urlencode, parse_qs, urlparse
basestring = (str, bytes) basestring = (str, bytes)
except ImportError: except ImportError:
from urllib import urlencode from urllib import urlencode
from urlparse import parse_qs, urlparse
basestring = basestring basestring = basestring
# Python 2's `input` executes the input, whereas `raw_input` just returns the input # Python 2's `input` executes the input, whereas `raw_input` just returns the input
@@ -140,6 +142,7 @@ class ReqUrl(object):
GET_POLL_OPTIONS = "https://www.facebook.com/ajax/mercury/get_poll_options" GET_POLL_OPTIONS = "https://www.facebook.com/ajax/mercury/get_poll_options"
SEARCH_MESSAGES = "https://www.facebook.com/ajax/mercury/search_snippets.php?dpr=1" SEARCH_MESSAGES = "https://www.facebook.com/ajax/mercury/search_snippets.php?dpr=1"
MARK_SPAM = "https://www.facebook.com/ajax/mercury/mark_spam.php?dpr=1" MARK_SPAM = "https://www.facebook.com/ajax/mercury/mark_spam.php?dpr=1"
UNSEND = "https://www.facebook.com/messaging/unsend_message/?dpr=1"
pull_channel = 0 pull_channel = 0
@@ -297,3 +300,18 @@ def get_files_from_paths(filenames):
yield files yield files
for fn, fp, ft in files: for fn, fp, ft in files:
fp.close() fp.close()
def enum_extend_if_invalid(enumeration, value):
try:
return enumeration(value)
except ValueError:
log.warning("Failed parsing {.__name__}({!r}). Extending enum.".format(enumeration, value))
aenum.extend_enum(enumeration, "UNKNOWN_{}".format(value).upper(), value)
return enumeration(value)
def get_url_parameters(url, *args):
params = parse_qs(urlparse(url).query)
return [params[arg][0] for arg in args if params.get(arg)]
def get_url_parameter(url, param):
return get_url_parameters(url, param)[0]

52
pyproject.toml Normal file
View File

@@ -0,0 +1,52 @@
[build-system]
requires = ["flit"]
build-backend = "flit.buildapi"
[tool.flit.metadata]
module = "fbchat"
author = "Taehoon Kim"
author-email = "carpedm20@gmail.com"
maintainer = "Mads Marquart"
maintainer-email = "madsmtm@gmail.com"
home-page = "https://github.com/carpedm20/fbchat/"
requires = [
"aenum",
"requests",
"beautifulsoup4",
]
description-file = "README.rst"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Communications :: Chat",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
requires-python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4.0"
keywords = "Facebook FB Messenger Library Chat Api Bot"
license = "BSD 3-Clause"
[tool.flit.metadata.urls]
Documentation = "https://fbchat.readthedocs.io/"
Repository = "https://github.com/carpedm20/fbchat/"
[tool.flit.metadata.requires-extra]
test = [
"pytest~=4.0",
"six",
]

View File

@@ -1,3 +0,0 @@
requests
beautifulsoup4
enum34; python_version < '3.4'

View File

@@ -1,5 +0,0 @@
#!/bin/bash
set -ex
python -m pytest -m offline --color=yes

View File

@@ -1,18 +0,0 @@
#!/bin/bash
set -ex
if ! python -m pytest --color=yes; then
echo << EOF
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
Some tests failed! Rerunning them, since they can be kinda flaky.
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
EOF
python -m pytest --last-failed --color=yes
fi

View File

@@ -1,51 +0,0 @@
[metadata]
name = fbchat
version = attr: fbchat.__version__
license = BSD 3-Clause
license_file = LICENSE
author = Taehoon Kim
author_email = carpedm20@gmail.com
maintainer = Mads Marquart
maintainer_email = madsmtm@gmail.com
description = Facebook Chat (Messenger) for Python
long_description = file: README.rst
long_description_content_type = text/x-rst
keywords = Facebook FB Messenger Chat Api Bot
classifiers =
Development Status :: 3 - Alpha
Intended Audience :: Developers
Intended Audience :: Information Technology
License :: OSI Approved :: BSD License
Operating System :: OS Independent
Natural Language :: English
Programming Language :: Python
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: Implementation :: PyPy
Topic :: Communications :: Chat
Topic :: Internet :: WWW/HTTP :: Dynamic Content
Topic :: Software Development :: Libraries :: Python Modules
url = https://github.com/carpedm20/fbchat/
project_urls =
Documentation = https://fbchat.readthedocs.io/
Repository = https://github.com/carpedm20/fbchat/
[options]
zip_safe = True
include_package_data = True
packages = find:
python_requires = >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4.0
install_requires =
requests
beautifulsoup4
# May not work in pip with bdist_wheel
# See https://wheel.readthedocs.io/en/latest/#defining-conditional-dependencies
# It is therefore defined in setup.py
# enum34; python_version < '3.4'

View File

@@ -1,8 +0,0 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from setuptools import setup
setup(extras_require={':python_version < "3.4"': ['enum34']})

View File

@@ -20,7 +20,9 @@ def group(pytestconfig):
return {"id": load_variable("group_id", pytestconfig.cache), "type": ThreadType.GROUP} return {"id": load_variable("group_id", pytestconfig.cache), "type": ThreadType.GROUP}
@pytest.fixture(scope="session", params=["user", "group", pytest.mark.xfail("none")]) @pytest.fixture(scope="session", params=[
"user", "group", pytest.param("none", marks=[pytest.mark.xfail()])
])
def thread(request, user, group): def thread(request, user, group):
return { return {
"user": user, "user": user,

View File

@@ -19,6 +19,11 @@ def test_fetch_thread_list(client1):
assert len(threads) == 2 assert len(threads) == 2
def test_fetch_threads(client1):
threads = client1.fetchThreads(limit=2)
assert len(threads) == 2
@pytest.mark.parametrize("emoji, emoji_size", EMOJI_LIST) @pytest.mark.parametrize("emoji, emoji_size", EMOJI_LIST)
def test_fetch_message_emoji(client, emoji, emoji_size): def test_fetch_message_emoji(client, emoji, emoji_size):
mid = client.sendEmoji(emoji, emoji_size) mid = client.sendEmoji(emoji, emoji_size)

View File

@@ -11,8 +11,14 @@ from time import time
@pytest.fixture(scope="module", params=[ @pytest.fixture(scope="module", params=[
Plan(int(time()) + 100, random_hex()), Plan(int(time()) + 100, random_hex()),
pytest.mark.xfail(Plan(int(time()), random_hex()), raises=FBchatFacebookError), pytest.param(
pytest.mark.xfail(Plan(0, None)), Plan(int(time()), random_hex()),
marks=[pytest.mark.xfail(raises=FBchatFacebookError)]
),
pytest.param(
Plan(0, None),
marks=[pytest.mark.xfail()],
),
]) ])
def plan_data(request, client, user, thread, catch_event, compare): def plan_data(request, client, user, thread, catch_event, compare):
with catch_event("onPlanCreated") as x: with catch_event("onPlanCreated") as x:

View File

@@ -26,7 +26,9 @@ from utils import random_hex, subset
PollOption(random_hex()), PollOption(random_hex()),
PollOption(random_hex()), PollOption(random_hex()),
]), ]),
pytest.mark.xfail(Poll(title=None, options=[]), raises=ValueError), pytest.param(
Poll(title=None, options=[]), marks=[pytest.mark.xfail(raises=ValueError)]
),
]) ])
def poll_data(request, client1, group, catch_event): def poll_data(request, client1, group, catch_event):
with catch_event("onPollCreated") as x: with catch_event("onPollCreated") as x:

View File

@@ -72,8 +72,8 @@ def test_change_nickname(client, client_all, catch_event, compare):
"😂", "😂",
"😕", "😕",
"😍", "😍",
pytest.mark.xfail("🙃", raises=FBchatFacebookError), pytest.param("🙃", marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
pytest.mark.xfail("not an emoji", raises=FBchatFacebookError) pytest.param("not an emoji", marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
]) ])
def test_change_emoji(client, catch_event, compare, emoji): def test_change_emoji(client, catch_event, compare, emoji):
with catch_event("onEmojiChange") as x: with catch_event("onEmojiChange") as x:
@@ -101,7 +101,7 @@ def test_change_image_remote(client1, group, catch_event):
[ [
x x
if x in [ThreadColor.MESSENGER_BLUE, ThreadColor.PUMPKIN] if x in [ThreadColor.MESSENGER_BLUE, ThreadColor.PUMPKIN]
else pytest.mark.expensive(x) else pytest.param(x, marks=[pytest.mark.expensive()])
for x in ThreadColor for x in ThreadColor
], ],
) )

View File

@@ -23,15 +23,15 @@ EMOJI_LIST = [
("😆", EmojiSize.LARGE), ("😆", EmojiSize.LARGE),
# These fail in `catch_event` because the emoji is made into a sticker # These fail in `catch_event` because the emoji is made into a sticker
# This should be fixed # This should be fixed
pytest.mark.xfail((None, EmojiSize.SMALL)), pytest.param(None, EmojiSize.SMALL, marks=[pytest.mark.xfail()]),
pytest.mark.xfail((None, EmojiSize.MEDIUM)), pytest.param(None, EmojiSize.MEDIUM, marks=[pytest.mark.xfail()]),
pytest.mark.xfail((None, EmojiSize.LARGE)), pytest.param(None, EmojiSize.LARGE, marks=[pytest.mark.xfail()]),
] ]
STICKER_LIST = [ STICKER_LIST = [
Sticker("767334476626295"), Sticker("767334476626295"),
pytest.mark.xfail(Sticker("0"), raises=FBchatFacebookError), pytest.param(Sticker("0"), marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
pytest.mark.xfail(Sticker(None), raises=FBchatFacebookError), pytest.param(Sticker(None), marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
] ]
TEXT_LIST = [ TEXT_LIST = [
@@ -40,8 +40,8 @@ TEXT_LIST = [
"\\\n\t%?&'\"", "\\\n\t%?&'\"",
"ˁҭʚ¹Ʋջوװ՞ޱɣࠚԹБɑȑңКએ֭ʗыԈٌʼőԈ×௴nચϚࠖణٔє܅Ԇޑط", "ˁҭʚ¹Ʋջوװ՞ޱɣࠚԹБɑȑңКએ֭ʗыԈٌʼőԈ×௴nચϚࠖణٔє܅Ԇޑط",
"a" * 20000, # Maximum amount of characters you can send "a" * 20000, # Maximum amount of characters you can send
pytest.mark.xfail("a" * 20001, raises=FBchatFacebookError), pytest.param("a" * 20001, marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
pytest.mark.xfail(None, raises=FBchatFacebookError), pytest.param(None, marks=[pytest.mark.xfail(raises=FBchatFacebookError)]),
] ]