Merge pull request #98 from madsmtm/master

Added functions to save and load session cookies to and from file
This commit is contained in:
Taehoon Kim
2017-02-07 16:59:55 +09:00
committed by GitHub
2 changed files with 110 additions and 55 deletions

View File

@@ -94,6 +94,22 @@ Example Echobot
bot.listen()
Saving session
==========================
.. code-block:: python
client.saveSession(sessionfile)
Loading session
==========================
.. code-block:: python
client = fbchat.Client(None, None, do_login=False)
client.loadSession(sessionfile)
Authors
=======

View File

@@ -59,7 +59,7 @@ class Client(object):
"""
def __init__(self, email, password, debug=True, user_agent=None , max_retries=5):
def __init__(self, email, password, debug=True, user_agent=None , max_retries=5, do_login=True):
"""A client for the Facebook Chat (Messenger).
:param email: Facebook `email` or `id` or `phone number`
@@ -70,11 +70,9 @@ class Client(object):
"""
if not (email and password):
if do_login and not (email and password):
raise Exception("id and password or config is needed")
self.email = email
self.password = password
self.debug = debug
self._session = requests.session()
self.req_counter = 1
@@ -120,20 +118,8 @@ class Client(object):
log.addHandler(handler)
log.setLevel(logging.DEBUG)
# Logging in
log.info("Logging in...")
for i in range(1,max_retries+1):
if not self.login():
log.warning("Attempt #{} failed{}".format(i,{True:', retrying'}.get(i<5,'')))
time.sleep(1)
continue
else:
log.info("Login successful")
break
else:
raise Exception("login failed. Check id/password")
if do_login:
self.login(email, password, max_retries)
self.threads = []
@@ -146,7 +132,7 @@ class Client(object):
>>> from fbchat.client import Client, log
>>> log.setLevel(logging.DEBUG)
You can do the same thing by addint the 'debug' argument:
You can do the same thing by adding the 'debug' argument:
>>> from fbchat import Client
>>> client = Client("...", "...", debug=True)
@@ -193,24 +179,8 @@ class Client(object):
payload=self._generatePayload(None)
return self._session.post(url, data=payload, timeout=timeout, files=files)
def login(self):
if not (self.email and self.password):
raise Exception("id and password or config is needed")
soup = bs(self._get(MobileURL).text, "lxml")
data = dict((elem['name'], elem['value']) for elem in soup.findAll("input") if elem.has_attr('value') and elem.has_attr('name'))
data['email'] = self.email
data['pass'] = self.password
data['login'] = 'Log In'
r = self._cleanPost(LoginURL, data)
# Sometimes Facebook tries to show the user a "Save Device" dialog
if 'save-device' in r.url:
r = self._cleanGet(SaveDeviceURL)
if 'home' in r.url:
def _post_login(self):
self.payloadDefault = {}
self.client_id = hex(int(random()*2147483648))[2:]
self.start_time = now()
self.uid = int(self._session.cookies['c_user'])
@@ -219,6 +189,8 @@ class Client(object):
r = self._get(BaseURL)
soup = bs(r.text, "lxml")
log.debug(r.text)
log.debug(r.url)
self.fb_dtsg = soup.find("input", {'name':'fb_dtsg'})['value']
self.fb_h = soup.find("input", {'name':'h'})['value']
self._setttstamp()
@@ -245,10 +217,77 @@ class Client(object):
self.tmp_prev = now()
self.last_sync = now()
def _login(self):
if not (self.email and self.password):
raise Exception("id and password or config is needed")
soup = bs(self._get(MobileURL).text, "lxml")
data = dict((elem['name'], elem['value']) for elem in soup.findAll("input") if elem.has_attr('value') and elem.has_attr('name'))
data['email'] = self.email
data['pass'] = self.password
data['login'] = 'Log In'
r = self._cleanPost(LoginURL, data)
# Sometimes Facebook tries to show the user a "Save Device" dialog
if 'save-device' in r.url:
r = self._cleanGet(SaveDeviceURL)
if 'home' in r.url:
self._post_login()
return True
else:
return False
def saveSession(self, sessionfile):
"""Dumps the session cookies to (sessionfile).
WILL OVERWRITE ANY EXISTING FILE
:param sessionfile: location of saved session file
"""
log.info('Saving session')
with open(sessionfile, 'w') as f:
# Grab cookies from current session, and save them as JSON
f.write(json.dumps(self._session.cookies.get_dict(), ensure_ascii=False))
def loadSession(self, sessionfile):
"""Loads session cookies from (sessionfile)
:param sessionfile: location of saved session file
"""
log.info('Loading session')
with open(sessionfile, 'r') as f:
try:
j = json.load(f)
if not j or 'c_user' not in j:
return False
# Load cookies into current session
self._session.cookies = requests.cookies.merge_cookies(self._session.cookies, j)
self._post_login()
return True
except Exception as e:
raise Exception('Invalid json in {}, or bad merging of cookies'.format(sessionfile))
def login(self, email, password, max_retries=5):
# Logging in
log.info("Logging in...")
self.email = email
self.password = password
for i in range(1,max_retries+1):
if not self._login():
log.warning("Attempt #{} failed{}".format(i,{True:', retrying'}.get(i<5,'')))
time.sleep(1)
continue
else:
log.info("Login successful")
break
else:
raise Exception("login failed. Check id/password")
def logout(self, timeout=30):
data = {}
data['ref'] = "mb"