提交 79b756d3 编写于 作者: L LittleCoder

Add download and verify

上级 fd6236dd
......@@ -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)
```
### 命令行二维码
......@@ -234,6 +259,8 @@ A: 有些账号是天生无法给自己的账号发送信息的,建议使用`f
## 类似项目
[youfou/wxpy][youfou-wxpy]: 优秀的api包装和配套插件,微信机器人/优雅的微信个人号API
[liuwons/wxBot][liuwons-wxBot]: 类似的基于Python的微信机器人
[zixia/wechaty][zixia-wechaty]: 基于Javascript(ES6)的微信个人账号机器人NodeJS框架/库
......@@ -265,6 +292,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
......
......@@ -68,7 +68,7 @@ def produce_msg(core, msgList):
# we don't need to update chatroom here because we have
# updated once when producing basic message
elif actualOpposite in ('filehelper', 'fmessage'):
m['User'] = templates.MassivePlatform({'UserName': actualOpposite})
m['User'] = templates.User({'UserName': actualOpposite})
else:
m['User'] = core.search_mps(userName=actualOpposite) or \
core.search_friends(userName=actualOpposite) or \
......@@ -109,6 +109,7 @@ def produce_msg(core, msgList):
'userName' : m['RecommendInfo']['UserName'],
'verifyContent' : m['Ticket'],
'autoUpdate' : m['RecommendInfo'], }, }
m['User'].verifyDict = msg['Text']
elif m['MsgType'] == 42: # name card
msg = {
'Type': 'Card',
......@@ -228,7 +229,7 @@ def produce_group_chat(core, msg):
else:
msg['ActualUserName'] = core.storageClass.userName
msg['ActualNickName'] = core.storageClass.nickName
msg['isAt'] = False
msg['IsAt'] = False
return
chatroom = core.storageClass.search_chatrooms(userName=chatroomUserName)
member = utils.search_dict_list((chatroom or {}).get(
......@@ -246,7 +247,7 @@ def produce_group_chat(core, msg):
utils.msg_formatter(msg, 'Content')
atFlag = '@' + (chatroom['self']['DisplayName']
or core.storageClass.nickName)
msg['isAt'] = (
msg['IsAt'] = (
(atFlag + (u'\u2005' if u'\u2005' in msg['Content'] else ' '))
in msg['Content'] or msg['Content'].endswith(atFlag))
......
import os, time, copy
try:
import Queue
except ImportError:
import queue as Queue
from threading import Lock
from .messagequeue import Queue
from .templates import (
ContactList, AbstractUserDict, User,
MassivePlatform, Chatroom, ChatroomMember)
......@@ -23,7 +20,7 @@ class Storage(object):
self.memberList = ContactList()
self.mpList = ContactList()
self.chatroomList = ContactList()
self.msgList = Queue.Queue(-1)
self.msgList = Queue(-1)
self.lastInputUserName = None
self.memberList.set_default_value(contactClass=User)
self.memberList.core = core
......
try:
import Queue as queue
except ImportError:
import queue
class Queue(queue.Queue):
def put(self, message):
queue.Queue.put(self, Message(message))
class Message(dict):
def download(self, fileName):
if hasattr(self.text, '__call__'):
return self.text(fileName)
else:
return b''
def __getattr__(self, value):
value = value[0].upper() + value[1:]
return self.get(value, '')
def __str__(self):
return '{%s}' % ', '.join(
['%s: %s' % (repr(k),repr(v)) for k,v in self.items()])
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__.split('.')[-1],
self.__str__())
......@@ -133,7 +133,7 @@ class User(AbstractUserDict):
def set_pinned(self, isPinned=True):
return self.core.set_pinned(self.userName, isPinned)
def verify(self):
return self.core.add_friend(**verifyDict)
return self.core.add_friend(**self.verifyDict)
def __deepcopy__(self, memo):
r = super(User, self).__deepcopy__(memo)
r.verifyDict = copy.deepcopy(self.verifyDict)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册