Skip to content

Instantly share code, notes, and snippets.

@dofine
Created March 27, 2016 17:59
Show Gist options
  • Save dofine/2625a44f7bfa2d7a40a2 to your computer and use it in GitHub Desktop.
Save dofine/2625a44f7bfa2d7a40a2 to your computer and use it in GitHub Desktop.
chat api
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import logging
import os
from cookielib import LWPCookieJar
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_handler = logging.FileHandler("log.log")
log_handler.setLevel(logging.INFO)
log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
class Chat(object):
BASE_URL = "http://example.com"
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36",
"Referer": "http://123.58.173.197:8080/gmchat/chat",
}
session = requests.Session()
session.cookies = LWPCookieJar("cookiejar")
def __init__(self, username, password, product, user_type, login_status):
self.username = username
self.password = password
def _params(self, **kwargs):
params = {}
for k, v in kwargs.items():
params[k] = v
return params
def _url(self, endpoint):
return "{0}/{1}".format(self.BASE_URL, endpoint)
def execute(self, url, headers, method="get", **kwargs):
_headers = self.HEADERS
_headers.update(headers)
params = self._params(**kwargs)
if method == "get":
r = self.session.get(url, headers=_headers, params=params)
elif method == "post":
r = self.session.post(url, headers=_headers, data=params)
else:
raise NotImplementedError("Method {0} not implement.".format(method))
r.raise_for_status()
if not r.raise_for_status():
return r
def login(self):
headers = self.HEADERS
headers["Referer"] = "http://example.com/login"
payload = {
"workId": self.username,
"password": self.password,
}
r = self.session.post(url=self._url("login"),
headers=self.HEADERS,
data=payload)
r.raise_for_status()
if r.status_code == 200:
logger.info("login success %s", self.username)
else:
logger.error("login failed %s", self.username)
self.session.cookies.save()
def get_friend_list(self):
url = self._url("chat/get_friend_list")
headers = {"X-Requested-With": "XMLHttpRequest"}
r = self.execute(url, headers=headers)
r.raise_for_status()
# success, result = self.parse_json_from_response(r)
resp = r.json()
if resp["success"]:
for each in resp["friends"]:
print(each["name"])
else:
logger.error("getting friends name failed.")
def send_chat(self, friend_id=None, mesg=None):
if not (friend_id and mesg):
raise ValueError("Must supply friend_id and mesg")
url = self._url('chat/send_chat')
headers = {"X-Requested-With": "XMLHttpRequest"}
r = self.execute(url, headers, method="post",
friendid=friend_id, mesg=mesg)
r.raise_for_status()
logger.info('msg to:%s, content:%s', urs, mesg)
if __name__ == '__main__':
c = Chat("testid", "password")
c.login()
c.send_chat(friend_id=1234, mesg='hello world!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment