-
Notifications
You must be signed in to change notification settings - Fork 1
/
push.py
129 lines (113 loc) · 3.65 KB
/
push.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# -*- coding: utf8 -*-
import hashlib
import urllib
import urllib2
import json
import poster
import cookielib
import time
import settings
import logging
from util import singleton
from bs4 import BeautifulSoup as bs
from model import WXUser as user
@singleton
class Push(object):
"""
推送消息
"""
push_msg_type = {
'text': 1,
'img': 2,
'audio': 3,
'video': 4,
'img_and_text': 10
}
def __init__(self, email=None, password=None):
self.email = email
self.password = None
self.token = None
if password:
self.password = hashlib.md5(password).hexdigest()
def login(self):
"""
强制重新登录,不论是否曾经登录过
"""
if not self.email:
self.email = settings.wx_email
if not self.password:
self.password = hashlib.md5(settings.wx_password).hexdigest()
body = self.gen_body('login')
self.opener = poster.streaminghttp.register_openers()
self.cookie = cookielib.CookieJar()
self.opener.add_handler(
urllib2.HTTPCookieProcessor(self.cookie))
self.opener.addheaders = settings.wx_header
try:
msg = json.loads(self.opener.open(
settings.wx_login_url, urllib.urlencode(body), timeout=5).read())
except Exception as e:
raise LoginException(e)
if msg['ErrCode'] not in (0, 65202):
raise LoginException(msg)
self.token = msg['ErrMsg'].split('=')[-1]
time.sleep(1)
def login_unless_not(self):
"""
登录如果曾经登陆过,则忽略此次登录操作
"""
if not self.token:
self.login()
def gen_body(self, type, fake_id=None):
body = {}
if type == 'login':
body['username'] = self.email
body['pwd'] = self.password
body['imgcode'] = ''
body['f'] = 'json'
elif type == 'push':
body['error'] = 'false'
body['token'] = self.token
body['tofakeid'] = fake_id
body['ajax'] = 1
return body
def send_txt_msg(self, send_to, msg):
self.login_unless_not()
data = {
'type': self.push_msg_type['text'],
'content': msg
}
self.opener.addheaders += [('Referer', settings.wx_send_msg_referer_url % str(send_to))]
body = self.gen_body('push', send_to)
body.update(data)
try:
msg = json.loads(self.opener.open(settings.wx_single_send_url, urllib.urlencode(body), timeout=5).read())
except urllib2.URLError, e:
logging.error(e.message, e)
return False
if msg['msg'] == 'ok':
return True
def get_contact_by_group(self, groupid=2):
self.login_unless_not()
self.opener.addheaders += [('Referer', settings.wx_index_url % self.token)]
try:
html = self.opener.open(settings.wx_contact_url % (self.token, groupid)).read()
except Exception, e:
logging.error(e.message, e)
return
users_json = json.loads(bs(html).findAll(id="json-friendList")[0].text)
users = []
for i in xrange(0, len(users_json)):
user_json = users_json[i]
u = user()
u.nickname = user_json['nickName']
u.fake_id = user_json['fakeId']
u.remark_name = user_json['remarkName']
u.group_id = int(user_json['groupId'])
u.save()
users.append(u)
return users
class PushException(Exception):
pass
class LoginException(Exception):
pass