Skip to content

Commit

Permalink
No more re-scan in repeat login [RB#31: ccaapton]
Browse files Browse the repository at this point in the history
  • Loading branch information
littlecodersh committed Jul 19, 2016
1 parent caf1ae5 commit 8847d95
Show file tree
Hide file tree
Showing 8 changed files with 116 additions and 33 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ def text_reply(msg):
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])

itchat.auto_login()
# if you don't want to use hot reload, you may use the following login command instead
# itchat.auto_login(hotReload = False)
itchat.run()
```

Expand Down
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ Here is the `code <https://github.com/littlecodersh/ItChat/tree/robot>`__.
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])
itchat.auto_login()
# if you don't want to use hot reload, you may use the following login command instead
# itchat.auto_login(hotReload = False)
itchat.run()
**FAQ**
Expand Down
2 changes: 2 additions & 0 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ def text_reply(msg):
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])

itchat.auto_login()
# if you don't want to use hot reload, you may use the following login command instead
# itchat.auto_login(hotReload = False)
itchat.run()
```

Expand Down
42 changes: 31 additions & 11 deletions docs/2.Login.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
#登陆
# 登陆

itchat提供了`auto_login`方法,调用即可完成登录。

itchat也提供了登陆状态暂存,关闭程序后一定时间内不需要扫码即可登录。

## 短时间关闭程序后重连

这样即使程序关闭,一定时间内重新开启也可以不用重新扫码。

```python
import itchat

if itchat.load_login_status():
@itchat.msg_register('Text')
def simple_reply(msg):
print(msg['Text'])
itchat.run()
else:
itchat.auto_login()
itchat.dump_login_status()
print('Config stored')
```

## 自定义登录过程

如果需要控制登录的过程,可以阅读下面的内容。

同时itchat也提供了登陆所需的每一步的方法,登陆的过程按顺序为:
Expand All @@ -12,65 +34,63 @@ itchat提供了`auto_login`方法,调用即可完成登录。
* 更新微信相关信息(通讯录、手机登陆状态)
* 循环扫描新信息(开启心跳)

##相关方法简单介绍

###获取二维码uuid
### 获取二维码uuid

获取生成二维码所需的uuid,并返回。

* 方法名称:`get_QRuuid`
* 所需值:无
* 返回值:成功->uuid,失败->None

###获取二维码
### 获取二维码

根据uuid获取二维码并打开,返回是否成功。

* 方法名称:`get_QR`
* 所需值:uuid
* 返回值:成功->True,失败->False

###判断是否已经登陆成功
### 判断是否已经登陆成功

判断是否已经登陆成功,返回扫描的状态码。

* 方法名称:`check_login`
* 所需值:uuid
* 返回值:登陆成功->'200',已扫描二维码->'201',二维码失效->'408',未获取到信息->'0'

###获取初始化数据
### 获取初始化数据

获取微信用户信息以及心跳所需要的数据。

* 方法名称:`web_init`
* 所需值:无
* 返回值:存储登录微信用户信息的字典

###获取微信通讯录
### 获取微信通讯录

获取微信的所有好友信息并更新。

* 方法名称:`get_contract`
* 所需值:无
* 返回值:存储好友信息的列表

###更新微信手机登陆状态
### 更新微信手机登陆状态

在手机上显示登录状态。

* 方法名称:`show_mobile_login`
* 所需值:无
* 返回值:无

###循环扫描新信息(开启心跳)
### 循环扫描新信息(开启心跳)

循环扫描是否有新的消息,开启心跳包。

* 方法名称:`start_receiving`
* 所需值:无
* 返回值:无

##示例
## 示例

itchat自带的`auto_login`通过如下代码可以实现:

Expand Down
7 changes: 5 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,16 @@ def download_files(msg):
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.get_contract()
itchat.send_msg(msg['RecommendInfo']['UserName'], 'Nice to meet you!')
itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])

@itchat.msg_register('Text', isGroupChat = True)
def text_reply(msg):
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])
if msg['isAt']:
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])

itchat.auto_login()
# if you don't want to use hot reload, you may use the following login command instead
# itchat.auto_login(hotReload = False)
itchat.run()
```

Expand Down
16 changes: 13 additions & 3 deletions itchat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@

import traceback

__version__ = '1.0.11'
__version__ = '1.0.12'

__client = client()
def auto_login(): return __client.auto_login()
# The following method are all included in auto_login >>>
def auto_login(hotReload = True, statusStorageDir = 'itchat.pkl'):
if hotReload:
if __client.load_login_status(statusStorageDir): return
__client.auto_login()
__client.dump_login_status(statusStorageDir)
else:
__client.auto_login()
# The following method are all included in __client.auto_login >>>
def get_QRuuid(): return __client.get_QRuuid()
def get_QR(uuid = None): return __client.get_QR(uuid)
def check_login(uuid = None): return __client.check_login(uuid)
Expand All @@ -18,6 +24,10 @@ def get_chatrooms(update = False): return __client.get_chatrooms(update)
def show_mobile_login(): return __client.show_mobile_login()
def start_receiving(): return __client.start_receiving()
# <<<
# The following method are for reload without re-scan the QRCode
def dump_login_status(fileDir = 'itchat.pkl'): return __client.dump_login_status(fileDir)
def load_login_status(fileDir = 'itchat.pkl'): return __client.load_login_status(fileDir)
# <<<
# if toUserName is set to None, msg will be sent to yourself
def send_msg(msg = 'Test Message', toUserName = None): return __client.send_msg(msg, toUserName)
def send_file(fileDir, toUserName): return __client.send_file(fileDir, toUserName)
Expand Down
48 changes: 37 additions & 11 deletions itchat/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import os, sys
import os, sys, pickle
import requests, time, re
import thread, subprocess
import json, xml.dom.minidom, mimetypes
Expand All @@ -15,6 +15,33 @@ def __init__(self):
self.loginInfo = {}
self.s = requests.Session()
self.uuid = None
def dump_login_status(self, fileDir):
try:
with open(fileDir, 'wb') as f: f.write('DELETE THIS')
os.remove(fileDir)
except:
raise Exception('Incorrect fileDir')
status = {
'loginInfo' : self.loginInfo,
'cookies' : self.s.cookies.get_dict(),
'storage' : self.storageClass.dumps()}
with open(fileDir, 'wb') as f:
pickle.dump(status, f)
def load_login_status(self, fileDir):
try:
with open(fileDir, 'rb') as f:
j = pickle.load(f)
except Exception as e:
return False
self.loginInfo = j['loginInfo']
self.s.cookies = requests.utils.cookiejar_from_dict(j['cookies'])
self.storageClass.loads(j['storage'])
if self.__sync_check():
out.print_line('Login successfully as %s\n'%self.storageClass.nickName, False)
self.start_receiving()
return True
else:
return False
def auto_login(self):
def open_QR():
for get_count in range(10):
Expand Down Expand Up @@ -388,16 +415,15 @@ def get_msg_purecontent(content): #added by brothertian
def send_msg(self, msg = 'Test Message', toUserName = None):
url = '%s/webwxsendmsg'%self.loginInfo['url']
payloads = {
'BaseRequest': self.loginInfo['BaseRequest'],
'Msg': {
'Type': 1,
'Content': msg.encode('utf8') if isinstance(msg, unicode) else msg,
'FromUserName': self.storageClass.userName.encode('utf8'),
'ToUserName': (toUserName if toUserName else self.storageClass.userName).encode('utf8'),
'LocalID': int(time.time()),
'ClientMsgId': int(time.time()),
},
}
'BaseRequest': self.loginInfo['BaseRequest'],
'Msg': {
'Type': 1,
'Content': msg.encode('utf8') if isinstance(msg, unicode) else msg,
'FromUserName': self.storageClass.userName.encode('utf8'),
'ToUserName': (toUserName if toUserName else self.storageClass.userName).encode('utf8'),
'LocalID': int(time.time()),
'ClientMsgId': int(time.time()),
}, }
headers = { 'ContentType': 'application/json; charset=UTF-8' }
r = self.s.post(url, data = json.dumps(payloads, ensure_ascii = False), headers = headers)
def __upload_file(self, fileDir, isPicture = False):
Expand Down
30 changes: 24 additions & 6 deletions itchat/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,31 @@

class Storage:
def __init__(self):
self.userName = None
self.nickName = None
self.memberList = []
self.chatroomList = []
self.msgList = []
self.groupDict = {}
self.userName = None
self.nickName = None
self.memberList = []
self.chatroomList = []
self.msgList = []
self.groupDict = {}
self.lastInputUserName = None
def dumps(self):
return {
'userName' : self.userName,
'nickName' : self.nickName,
'memberList' : self.memberList,
'chatroomList' : self.chatroomList,
'groupDict' : self.groupDict,
'lastInputUserName' : self.lastInputUserName, }
def loads(self, j):
self.userName = j.get('userName', None)
self.nickName = j.get('nickName', None)
del self.memberList[:]
for i in j.get('memberList', []): self.memberList.append(i)
del self.chatroomList[:]
for i in j.get('chatroomList', []): self.chatroomList.append(i)
self.groupDict.clear()
for k, v in j.get('groupDict', {}).iteritems(): self.groupDict[k] = v
self.lastInputUserName = j.get('lastInputUserName', None)
def find_username(self, n):
r = []
for member in self.memberList:
Expand Down

0 comments on commit 8847d95

Please sign in to comment.