Skip to content

Commit

Permalink
Merge 1.3.0 into master and update to 1.3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
littlecodersh committed Mar 25, 2017
2 parents 8c205a0 + 7781490 commit 6fcce75
Show file tree
Hide file tree
Showing 14 changed files with 924 additions and 508 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ dist/*
tests/*
itchat.egg-info/*
*.pyc
*.pkl
*.swp
test.py
itchat.pkl
Expand Down
46 changes: 37 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,36 +59,61 @@ itchat.run()

## 进阶应用

### 特殊的字典使用方式

通过打印itchat的用户以及注册消息的参数,可以发现这些值都是字典。

但实际上itchat精心构造了相应的消息、用户、群聊、公众号类。

其所有的键值都可以通过这一方式访问:

```python
@itchat.msg_register(TEXT)
def _(msg):
# equals to print(msg['FromUserName'])
print(msg.fromUserName)
```

属性名为键值首字母小写后的内容。

```python
author = itchat.search_friends(nickName='LittleCoder')[0]
author.send('greeting, littlecoder!')
```

### 各类型消息的注册

通过如下代码,微信已经可以就日常的各种信息进行获取与回复。

```python
#coding=utf8
import itchat, time
from itchat.content import *

@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])
msg.user.send('%s: %s' % (msg.type, msg.text))

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
msg['Text'](msg['FileName'])
return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])
msg.download(msg.fileName)
typeSymbol = {
PICTURE: 'img',
VIDEO: 'vid', }.get(msg.type, 'fil')
return '@%s@%s' % (typeSymbol, msg.fileName)

@itchat.msg_register(FRIENDS)
def add_friend(msg):
itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录
itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])
msg.user.verify()
msg.user.send('Nice to meet you!')

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

itchat.auto_login(True)
itchat.run()
itchat.run(True)
```

### 命令行二维码
Expand Down Expand Up @@ -234,6 +259,8 @@ A: 有些账号是天生无法给自己的账号发送信息的,建议使用`f

## 类似项目

[youfou/wxpy][youfou-wxpy]: 优秀的api包装和配套插件,微信机器人/优雅的微信个人号API

[liuwons/wxBot][liuwons-wxBot]: 类似的基于Python的微信机器人

[zixia/wechaty][zixia-wechaty]: 基于Javascript(ES6)的微信个人账号机器人NodeJS框架/库
Expand Down Expand Up @@ -267,6 +294,7 @@ A: 有些账号是天生无法给自己的账号发送信息的,建议使用`f
[littlecodersh]: https://github.com/littlecodersh
[tempdban]: https://github.com/tempdban
[Chyroc]: https://github.com/Chyroc
[youfou-wxpy]: https://github.com/youfou/wxpy
[liuwons-wxBot]: https://github.com/liuwons/wxBot
[zixia-wechaty]: https://github.com/zixia/wechaty
[Mojo-Weixin]: https://github.com/sjdy521/Mojo-Weixin
Expand Down
24 changes: 13 additions & 11 deletions itchat/components/contact.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .. import config, utils
from ..returnvalues import ReturnValue
from ..storage import contact_change
from ..storage import contact_change, templates

logger = logging.getLogger('itchat')

Expand Down Expand Up @@ -99,8 +99,8 @@ def update_friend(self, userName):
return r if len(r) != 1 else r[0]

def update_info_dict(oldInfoDict, newInfoDict):
'''
only normal values will be updated here
''' only normal values will be updated here
because newInfoDict is normal dict, so it's not necessary to consider templates
'''
for k, v in newInfoDict.items():
if any((isinstance(v, t) for t in (tuple, list, dict))):
Expand Down Expand Up @@ -130,8 +130,8 @@ def update_local_chatrooms(core, l):
if oldChatroom:
update_info_dict(oldChatroom, chatroom)
# - update other values
memberList, oldMemberList = (c.get('MemberList', [])
for c in (chatroom, oldChatroom))
memberList = chatroom.get('MemberList', [])
oldMemberList = oldChatroom.memberList
if memberList:
for member in memberList:
oldMember = utils.search_dict_list(
Expand All @@ -141,17 +141,19 @@ def update_local_chatrooms(core, l):
else:
oldMemberList.append(member)
else:
oldChatroom = chatroom
core.chatroomList.append(chatroom)
oldChatroom = templates.wrap_user_dict(chatroom)
core.chatroomList.append(oldChatroom)
# delete useless members
if len(chatroom['MemberList']) != len(oldChatroom['MemberList']) and \
chatroom['MemberList']:
existsUserNames = [member['UserName'] for member in chatroom['MemberList']]
delList = []
for i, member in enumerate(oldChatroom['MemberList']):
if member['UserName'] not in existsUserNames: delList.append(i)
if member['UserName'] not in existsUserNames:
delList.append(i)
delList.sort(reverse=True)
for i in delList: del oldChatroom['MemberList'][i]
for i in delList:
del oldChatroom['MemberList'][i]
# - update OwnerUin
if oldChatroom.get('ChatRoomOwner') and oldChatroom.get('MemberList'):
oldChatroom['OwnerUin'] = utils.search_dict_list(oldChatroom['MemberList'],
Expand Down Expand Up @@ -184,8 +186,8 @@ def update_local_friends(core, l):
utils.emoji_formatter(friend, 'NickName')
if 'DisplayName' in friend:
utils.emoji_formatter(friend, 'DisplayName')
if 'RemarkName' in member:
utils.emoji_formatter(member, 'RemarkName')
if 'RemarkName' in friend:
utils.emoji_formatter(friend, 'RemarkName')
oldInfoDict = utils.search_dict_list(
fullList, 'UserName', friend['UserName'])
if oldInfoDict is None:
Expand Down
3 changes: 3 additions & 0 deletions itchat/components/hotreload.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from ..config import VERSION
from ..returnvalues import ReturnValue
from ..storage import templates
from .contact import update_local_chatrooms, update_local_friends
from .messages import produce_msg

Expand Down Expand Up @@ -50,6 +51,8 @@ def load_login_status(self, fileDir,
'ErrMsg': 'cached status ignored because of version',
'Ret': -1005, }})
self.loginInfo = j['loginInfo']
self.loginInfo['User'] = templates.User(self.loginInfo['User'])
self.loginInfo['User'].core = self
self.s.cookies = requests.utils.cookiejar_from_dict(j['cookies'])
self.storageClass.loads(j['storage'])
msgList, contactList = self.get_msg()
Expand Down
4 changes: 3 additions & 1 deletion itchat/components/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from .. import config, utils
from ..returnvalues import ReturnValue
from ..storage.templates import wrap_user_dict
from .contact import update_local_chatrooms, update_local_friends
from .messages import produce_msg

Expand Down Expand Up @@ -182,7 +183,7 @@ def web_init(self):
# deal with login info
utils.emoji_formatter(dic['User'], 'NickName')
self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount'])
self.loginInfo['User'] = utils.struct_friend_info(dic['User'])
self.loginInfo['User'] = wrap_user_dict(utils.struct_friend_info(dic['User']))
self.memberList.append(self.loginInfo['User'])
self.loginInfo['SyncKey'] = dic['SyncKey']
self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val'])
Expand Down Expand Up @@ -247,6 +248,7 @@ def maintain_loop():
else:
otherList.append(contact)
chatroomMsg = update_local_chatrooms(self, chatroomList)
chatroomMsg['User'] = self.loginInfo['User']
self.msgList.put(chatroomMsg)
update_local_friends(self, otherList)
retryCount = 0
Expand Down
Loading

0 comments on commit 6fcce75

Please sign in to comment.