fbchat-dev / fbchat Goto Github PK
View Code? Open in Web Editor NEWFacebook Chat (Messenger) for Python
Home Page: https://fbchat.readthedocs.io
License: BSD 3-Clause "New" or "Revised" License
Facebook Chat (Messenger) for Python
Home Page: https://fbchat.readthedocs.io
License: BSD 3-Clause "New" or "Revised" License
Every time i am trying to login ,this error occurs.
client = fbchat.Client("User****Name", "password")
File "~/VirtualEnvironments/PythonApi/lib/python2.7/site-packages/fbchat/client.py", line 68, in init
self.data = data
NameError: global name 'data' is not defined
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.
can initial and send message to friend, but sending local image returns follow error:
send = client.sendLocalImage(friend[0].uid, message="<hi>", image="c:/image.jpg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python27\lib\site-packages\fbchat\client.py", line 317, in sendLocalImage
image_id = self.uploadImage({'file': (image, open(image), mimetype)})
File "c:\Python27\lib\site-packages\fbchat\client.py", line 327, in uploadImage
return json.loads(r._content[9:])['payload']['metadata'][0]['image_id']
TypeError: 'NoneType' object has no attribute '__getitem__'
OS: Windows Server 2012R2
Python: 2.7
Thanks in advance
def unreadMessages(self):
thread = self.client.getThreadInfo(self.userid, 0)
for message in reversed(thread):
print dir(message)
#if message.is_unread:
# print message.body.encode('cp860', errors='ignore')
As following script above, we have this:
['__doc__', '__init__', '__module__', u'action_type', u'attachments',
u'author', u'author_email', u'body', u'commerce_message_type', u'customizations',
u'ephemeral_ttl_mode', u'folder', u'forward_count', u'forward_message_ids',
u'has_attachment', u'is_filtered_content', u'is_filtered_content_account',
u'is_filtered_content_bh', u'is_filtered_content_invalid_app', u'is_filtered_content_quasar',
u'is_forward', u'is_sponsored', u'is_spoof_warning', u'is_unread', u'message_id',
u'meta_ranges', u'offline_threading_id', u'other_user_fbid', u'platform_xmd',
u'ranges', u'raw_attachments', u'source', u'source_tags', u'subject', u'tags',
u'thread_fbid', u'thread_id', u'threading_id', u'timestamp', u'timestamp_absolute',
u'timestamp_datetime', u'timestamp_relative', u'timestamp_time_passed']
Can i get the name/username from message.author
? coz, we only got fbid:100007030058882
.
I'm not familiar enough with the API to know whether that's already possible, but instead of searching for a particular user with its name or UID, it would be great to have ALL users returned into a list (particularly if we have their status without additional queries).
Hello,
After providing correct id/pass this exception occurs:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in
cilent = fbchat.Client(login,pass)
File "C:\Python34\lib\site-packages\fbchat\client.py", line 63, in init
if not self.login():
File "C:\Python34\lib\site-packages\fbchat\client.py", line 106, in login
self.fb_dtsg = soup.find("input", {'name':'fb_dtsg'})['value']
TypeError: 'NoneType' object is not subscriptable
Any ideas?
Thanks!
I'm slogging through the code here and maybe I'm just missing something obvious, but is there a way to get the ThreadID in the on_message function? The author_id is available (while author_name is generally not) but when trying to reply, it would be useful to reply into the same thread.
When images without text body is sent, it just called on_message_error
and not on_message
making users unable to handle them.
I am getting this error
Logging in...
Traceback (most recent call last):
File "C:\Users\jerem\Source\Repos\FBChatBot\FBChatBot\FBChatBot\FBChatBot.py", line 8, in
last_messages = client.getThreadInfo(bot["chatID"],0)
File "C:\Users\jerem\AppData\Local\Programs\Python\Python35\lib\site-packages\fbchat-0.3.1-py3.5.egg\fbchat\client.py", line 266, in getThreadInfo
for message in j['payload']['actions']:
KeyError: 'actions'
Press any key to continue . . .
and this is my code
import fbchat, json
with open("data/user.json") as user:
bot = json.load(user)
client = fbchat.Client(bot["username"], bot["password"])
last_messages = client.getThreadInfo(bot["chatID"],0)
on_message is not triggering message read notifications for other users in group chats.
I using Python 3.4.3 64 bit for windows 8. I using
pip install fbchat
but install error.
No distributions at all found for bs4 (from fbchat)
from setup.py in fbchat.
install_requires=[
'requests',
'bs4'
],
'bs4' to 'beautifulsoup4'
Thank you.
I am unable to use this as there is no documentation and the issue talking about it being in the code is just as unhelpful.
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?
Hi devs,
Is it possible to send attachments or pictures with fbchat?
If it's possible, how can I do that?
Getting this error (I subclassed the Client class and cloned this library into my repo) when trying to login. Anyone else hitting this error?
Traceback (most recent call last):
File "fb_chat.py", line 11, in <module>
client = fb_client.FbClient(username, password)
File "/Users/user/Desktop/FBMessengerPython/fb_client.py", line 11, in __init__
super(FbClient, self).__init__(email, password, debug, user_agent)
File "/Users/user/Desktop/FBMessengerPython/fbchat/client.py", line 88, in __init__
if not self.login():
File "/Users/user/Desktop/FBMessengerPython/fbchat/client.py", line 143, in login
soup = bs(self._get(MobileURL).text, "lxml")
File "/Users/user/Desktop/FBMessengerPython/fbchat/client.py", line 124, in _get
return self._session.get(url, headers=self._header, params=payload, timeout=timeout)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 488, in get
return self.request('GET', url, **kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "/Library/Python/2.7/site-packages/requests/adapters.py", line 487, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='m.facebook.com', port=443): Max retries exceeded with url: /?seq=0&__req=1 (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x1073ae490>: Failed to establish a new connection: [Errno 65] No route to host',))
Most features work fine, but Client.send() always returns False with no message being sent. Comparing the POST requests that fbchat makes with those from messenger.com, Messenger's message_batch[0][message_id] parameter is always a single nine-digit number, while fbchat's is not. But I don't know how it's generated or how to make a valid one. Have others noticed this?
Hi guys, does this method still work?
I tried logging in, and sending a message to a given thread_id, but got a response code 500.
Any reason that might do that?
Hello,
I get this error whenever I try to import fbchat without adding any extra lines
30:52.08 > CMKH1 AUTHENTICATE XOAUTH2
30:52.11 < +
30:52.11 write literal size 112
30:52.29 < + eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
30:52.29 write literal size 112
30:52.36 < CMKH1 NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)
30:52.36 NO response: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
Traceback (most recent call last):
File "./facebook.py", line 2, in
import fbchat
File "/Library/Python/2.7/site-packages/fbchat/init.py", line 14, in
from .client import *
File "/Library/Python/2.7/site-packages/fbchat/client.py", line 14, in
import requests
File "/Library/Python/2.7/site-packages/requests/init.py", line 52, in
from .packages.urllib3.contrib import pyopenssl
File "/Library/Python/2.7/site-packages/requests/packages/init.py", line 27, in
from . import urllib3
File "/Library/Python/2.7/site-packages/requests/packages/urllib3/init.py", line 8, in
from .connectionpool import (
File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 41, in
from .request import RequestMethods
File "/Library/Python/2.7/site-packages/requests/packages/urllib3/request.py", line 7, in
from .filepost import encode_multipart_formdata
File "/Library/Python/2.7/site-packages/requests/packages/urllib3/filepost.py", line 9, in
from .fields import RequestField
File "/Library/Python/2.7/site-packages/requests/packages/urllib3/fields.py", line 2, in
import email.utils
File "/Users/NixPal/email.py", line 19, in
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 364, in authenticate
raise self.error(dat[-1])
imaplib.error: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
When I entered a name into getUsers (example: client.getUsers("person")), it gave an error pointing to line 18 in utils.py which contains
return json.loads(re.sub(r"for.*(.*;.*;.*).*;", '', text.encode('utf-8').decode("unicode-escape"), 1))
with the error message saying ValueError: Expecting ',' delimiter: line 1 column 69 (char 68)
This continued for repeated users but another user I searched for gave a slightly different error message
ValueError: No JSON object could be decoded
My facebook login id and password is true. but
>>> import fbchat
>>> client = fbchat.Client("ID", "PASSWORD")
Logging in...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\py34\lib\site-packages\fbchat-0.0.2-py3.4.egg\fbchat\client.py", line
68, in __init__
NameError: name 'data' is not defined
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AM
D64)] on win32
Thank you.
Getting the following error from the listen() function.
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "fb_chat.py", line 59, in handle_new_message
client.listen()
File "/usr/local/lib/python2.7/dist-packages/fbchat/client.py", line 517, in listen
sticky, pool = self._getSticky()
File "/usr/local/lib/python2.7/dist-packages/fbchat/client.py", line 442, in _getSticky
j = get_json(r.text)
File "/usr/local/lib/python2.7/dist-packages/fbchat/utils.py", line 18, in get_json
return json.loads(re.sub(r"^[^{]*", '', text, 1))
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
With the following lines,
print r
print '-----'
print r.text
I got this output
<Response [400]>
-----
Hi,
I found when sending message to a group chat, the following line should not be exist:
'message_batch[0][specific_to_list][0]' : 'fbid:' + str(thread_id),
'message_batch[0][specific_to_list][1]' : 'fbid:' + str(self.uid),
Those lines are client.py line 211 and 212.
However, I do not know how to determine group or personal chat via thread_id only.
Maybe additional argument is required in send().
If a group_id is given and the message type of "group" passed in, it fails to send a message to anybody and returns a 200.
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?
The login works, I can send messages and retrieve friends, but receiving messages while listening is not firing the on_message
method. Am I doing something wrong?
client = Client(username, password)
client.listen()
in parseMessage
the content
coming in is always {u'reason': 110, u't': u'refresh', u'seq': 0}
and therefore on_message
is never fired.
I googled a bit and I found defaultnamehere/zzzzz#25
Someone here thinks getting new cookies will help.
SOLUTION:
add "clientid": self.client_id,
in the dict data
in Client._pullMessage
method in client.py
for this there seems to be a problem when sending messages of more than 20000 characters? I was doing a binary search to find the limit and the send function returns true even though the message didn't show up in the messenger
You just get
raise Exception("id or password is wrong")
in response. Password and ID are definitely correct because I double-checked them by direct copy and paste via browser.
If two-factor and code generator are disabled, it works but gives the "data" error that is listed as another issue in the issue tracker.
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
When fbchat start listen() and a like notification has push in, fbchat would receive a very long json string. It told you are "liked".
However there are some problems in the json string, and cause json.load() error.
It contains double quote in json value in 2 element. One is the "__html", which contains html code.
Another one is the "tracking" element, which contains another json code.
I have no idea how to fix it.
Regards
when i built with cx_freeze and run the client login, an error occurs.
it says:
Logging in...
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\requests\packages\urllib3\util\ssl_.py", line 295, in ssl_wrap_socket
context.load_verify_locations(ca_certs, ca_cert_dir)
FileNotFoundError: [Errno 2] No such file or directory
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\requests\adapters.py", line 423, in send
timeout=timeout
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 595, in urlopen
chunked=chunked)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 352, in _make_request
self._validate_conn(conn)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 831, in _validate_conn
conn.connect()
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connection.py", line 289, in connect
ssl_version=resolved_ssl_version)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\util\ssl_.py", line 297, in ssl_wrap_socket
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [Errno 2] No such file or directory
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Python\64-bit\3.4\lib\threading.py", line 921, in _bootstrap_inner
File "c:\Python\64-bit\3.4\lib\threading.py", line 869, in run
File "Kontenjan_Takip.py", line 168, in kontenjan_ara
File "C:\Python34\lib\site-packages\fbchat\client.py", line 89, in __init__
if not self.login():
File "C:\Python34\lib\site-packages\fbchat\client.py", line 144, in login
soup = bs(self._get(MobileURL).text, "lxml")
File "C:\Python34\lib\site-packages\fbchat\client.py", line 125, in _get
return self._session.get(url, headers=self._header, params=payload, timeout=timeout)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 488, in get
return self.request('GET', url, **kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "C:\Python34\lib\site-packages\requests\adapters.py", line 497, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [Errno 2] No such file or directory
is it about this module? do you meet with this error? when i run this on pycharm, there is no error. you can follow my topic on stackoverflow
Hi,
I have one problem with the fbchat.
Well ... when I send a message to a friend of mine that I have already spoken, the message arrives perfectly. The problem is when I try to send a message to a friend of mine that I never talked on facebook. The method returns True, but the message does not arrive.
Can anybody help me?
Hi,
I used the example from README, but it doesn't work at all. Can you give me some advices? My code is as follows:
import fbchat
client = fbchat.Client("MY_ID", "MY_PASSWORD")
friends = client.getUsers("Ning") # I tried a friend's name
friend = friends[0]
After executing the code, it shows the following error messages:
friends = client.getUsers('Ning')
File "build/bdist.linux-x86_64/egg/fbchat/client.py", line 189, in getUsers
File "build/bdist.linux-x86_64/egg/fbchat/utils.py", line 18, in get_json
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting ',' delimiter: line 1 column 63 (char 62)
Thanks!
bug in getThreadList() and getUsers()
TypeError: __repr__ returned non-string (type bytes)
GetThreadInfo does not work in group chats.
The error I'm having is
Traceback (most recent call last):
File "/opt/pycharm-com-eap/helpers/pydev/pydevd.py", line 1581, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/opt/pycharm-com-eap/helpers/pydev/pydevd.py", line 964, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/daniel/Dropbox/Code/Python/TesFBChat.py", line 97, in <module>
lastMessageFromThread = (client.getThreadInfo(threadFbId, 0, 0)[0].body).upper()
File "/home/daniel/.local/lib/python2.7/site-packages/fbchat/client.py", line 354, in getThreadInfo
for message in j['payload']['actions']:
KeyError: 'actions'
Python 3.4 64bit Winows 10
Although the message was sent successfully, the program throws an exception as following:
Traceback (most recent call last):
sent = client.send(friend.uid, u"\u4e00")
File "C:\Python34\lib\site-packages\fbchat\client.py", line 292, in send
print(data)
File "C:\Python34\lib\encodings\cp850.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 731-743: character maps to
From some tests I ran, it seems like getThreadList
does not update when new messages are sent. I had to log in again to get the last messages.
Is it just me, or is this in fact the case?
Hi,
After smoothly use for few days, I found fbchat stop pull new message.
When the _pullMessage in listen function return content, it actually return following string:
'for (;;); {"t":"refresh","reason":110,"seq":0}'
It may be mean reload page is required in browser, but have no idea how to do in requests session.
Thanks.
Does login fail for anyone else quite a few times? Retrying usually solves it. Should I add retry logic to login? Voting lines are open!
The call to self._post(SendURL, data)
in Client.send()
is returning a 404 error. After comparing it with captured requests from messenger.com and facebook.com, the request URL matches neither; is https://www.facebook.com/ajax/mercury/send_messages.php
still correct?
All other functionality seems to be fine except for sending messages. This occurs for both group and individual conversations.
After the fix proposed by @Charliiee I wrote this code, his purpose is to use a list of person to send them a message (today's agenda):
Tabl=[List of people name]
for index, item in enumerate(Tabl, start=0):
friends=client.getUsers(item)
friend=friends[0]
az = open(os.path.join(File location),'a') #Keeping people userid for reference and futur use.
message=friend.uid
az.write(str(message)+'\n')
az.close()
with open(os.path.join(location of userid file), 'r') as f:
for line in f:
with open(os.path.join(file location of the message), 'r') as e:
for lined in e:
line=re.sub(r"\W", "", line)
sent = client.send(line, lined)
if sent==False:
print line
sent=False
I've noticed 2 things with this code:
Is there a limit of message that can be sent? Do I need people to often message the bot?
Hello
I am using Python x64 3.4.3 on Windows 8.1. When I try to run the sample code you provided, I face the following error.
Traceback (most recent call last):
File "S:\Dev\python\fbchat.py", line 1, in <module>
import fbchat
File "S:\Dev\python\fbchat.py", line 3, in <module>
client = fbchat.Client("YOUR_ID", "YOUR_PASSWORD")
AttributeError: 'module' object has no attribute 'Client'
The interesting thing is that your lib works perfectly when I run the same code in the Python shell. But when I save the code in a file script.py and call python script.py
, it gives me the error.
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)
need documentation
the actual author's id is in metadata['delta']['messageMetadata']['actorFbId']
. Sending PR
There's a noticeable delay in each call to get_json. Since the cruft at the beginning is always the same, why not use a slice operation instead of a regex?
How would I listen for a message?
Hello all,
I'm using the echobot in a seperate thread of a python file. The threading looks something like this code under. When running the python file it is able to log in to Facebook and echo messages. But script1 isn't running at all, it seems like Echobot is the only thing running. Even if the script is a simple print function it won't run. Am I missing something or is my code just wrong?
if name== 'main':
p1 = threading.Thread(target = script1 )
p1.start()
p2 = threading.Thread(target = EchoBot("", "").listen )
p2.start()
Thanks!
When fbchat listening than you open the Facebook mobile page, the FB server will not send regular message json. it send something like following:
{u'ofd_ts': 1454312455400, u'iseq': 29739, u'type': u'delta', u'delta': {u'body': u'message body', u'irisSeqId': u'29739', u'class': u'NewMessage', u'attachments': [], u'messageMetadata': {u'tags': [u'source:chat:web'], u'actorFbId': u'100000077777777', u'messageId': u'mid.1454312455555:405655314e52eaddddd', u'offlineThreadingId': u'6099828631999999999', u'timestamp': u'1454312455379', u'threadKey': {u'otherUserFbId': u'100000060666666'}}}}
It's should be put in on_message, but it contains no name.
Now this work with Friend name but it is possible to work with facebook link and how.
friends = client.getUsers("FRIEND'S NAME") # return a list of names
friend = friends[0]
sent = client.send(friend.uid, "Your Message")
for example like this.
friends = client.getUsers("https://www.facebook.com/MyProfile") # return a User_Id
friend = friends[0]
sent = client.send(friend.uid, "Your Message")
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.