Skip to content

Commit 6e3fdda

Browse files
committed
Push Code
1 parent e19fd4e commit 6e3fdda

File tree

14 files changed

+362
-0
lines changed

14 files changed

+362
-0
lines changed

.DS_Store

0 Bytes
Binary file not shown.

Charpter 19/19_1.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
itchat简单使用示例
3+
"""
4+
import itchat
5+
import time
6+
7+
@itchat.msg_register(itchat.content.TEXT)
8+
def reply_msg(msg):
9+
print("收到一条信息:",msg.text)
10+
11+
12+
if __name__ == '__main__':
13+
itchat.auto_login(enableCmdQR=True)
14+
time.sleep(5)
15+
itchat.send("文件助手你好哦", toUserName="filehelper")
16+
itchat.run()

Charpter 19/19_10.py

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import itchat
2+
from itchat.content import *
3+
import os
4+
import time
5+
import re
6+
import shutil
7+
from apscheduler.schedulers.blocking import BlockingScheduler
8+
9+
# 文件临时存储页
10+
rec_tmp_dir = os.path.join(os.getcwd(), 'tmp/')
11+
12+
# 存储数据的字典
13+
rec_msg_dict = {}
14+
15+
# 过滤撤回信息的正则
16+
revoke_msg_compile = re.compile(r'\<\!\[CDATA\[.*撤回了一条消息\]\]\>')
17+
18+
# 提取MsgId的正则
19+
extract_msgid_compile = re.compile(r'\<msgid\>(.*?)\<\/msgid\>')
20+
21+
22+
# 好友信息监听
23+
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True)
24+
def handle_friend_msg(msg):
25+
msg_id = msg['MsgId']
26+
msg_from_user = msg['User']['NickName']
27+
msg_content = ''
28+
# 收到信息的时间
29+
msg_create_time = msg['CreateTime']
30+
msg_type = msg['Type']
31+
32+
if msg['Type'] == 'Text':
33+
msg_content = msg['Content']
34+
elif msg['Type'] == 'Picture' \
35+
or msg['Type'] == 'Recording' \
36+
or msg['Type'] == 'Video' \
37+
or msg['Type'] == 'Attachment':
38+
msg_content = r"" + msg['FileName']
39+
msg['Text'](rec_tmp_dir + msg['FileName'])
40+
rec_msg_dict.update({
41+
msg_id: {
42+
'msg_from_user': msg_from_user,
43+
'msg_create_time': msg_create_time,
44+
'msg_type': msg_type,
45+
'msg_content': msg_content
46+
}
47+
})
48+
49+
50+
# 群聊信息监听
51+
@itchat.msg_register([TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)
52+
def information(msg):
53+
msg_id = msg['MsgId']
54+
msg_from_user = msg['ActualNickName']
55+
msg_content = ''
56+
# 收到信息的时间
57+
msg_create_time = msg['CreateTime']
58+
msg_type = msg['Type']
59+
60+
if msg['Type'] == 'Text':
61+
msg_content = msg['Content']
62+
elif msg['Type'] == 'Picture' \
63+
or msg['Type'] == 'Recording' \
64+
or msg['Type'] == 'Video' \
65+
or msg['Type'] == 'Attachment':
66+
msg_content = r"" + msg['FileName']
67+
msg['Text'](rec_tmp_dir + msg['FileName'])
68+
rec_msg_dict.update({
69+
msg_id: {
70+
'msg_from_user': msg_from_user,
71+
'msg_create_time': msg_create_time,
72+
'msg_type': msg_type,
73+
'msg_content': msg_content
74+
}
75+
})
76+
77+
78+
# 撤回信息监控
79+
@itchat.msg_register([NOTE], isFriendChat=True, isGroupChat=True)
80+
def revoke_msg(msg):
81+
if revoke_msg_compile.search(msg['Content']) is not None:
82+
old_msg_id = extract_msgid_compile.search(msg['Content']).group(1)
83+
old_msg = rec_msg_dict.get(old_msg_id, {})
84+
# 先发送一条文字信息
85+
itchat.send_msg(str(old_msg.get('msg_from_user') + "撤回了一条信息:"
86+
+ old_msg.get('msg_content')), toUserName="filehelper")
87+
# 判断msg_content是否存在,不存在说明是文字,就无需进行下一步
88+
if os.path.exists(os.path.join(rec_tmp_dir, old_msg.get('msg_content'))):
89+
# 判断聊天信息类型是否为图片,是调用发送图片的方法
90+
if old_msg.get('msg_type') == 'Picture':
91+
itchat.send_image(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
92+
toUserName="filehelper")
93+
# 判断聊天信息类型是否为视频,是调用发送视频的方法
94+
elif old_msg.get('msg_type') == 'Video':
95+
itchat.send_video(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
96+
toUserName="filehelper")
97+
# 判断聊天信息类型是否为附件或录音,是调用发送视频的方法
98+
elif old_msg.get('msg_type') == 'Attachment' \
99+
or old_msg.get('msg_type') == 'Recording':
100+
itchat.send_file(os.path.join(rec_tmp_dir, old_msg.get('msg_content')),
101+
toUserName="filehelper")
102+
103+
104+
# 每隔五种分钟执行一次清理任务
105+
def clear_cache():
106+
# 当前时间
107+
cur_time = time.time()
108+
# 遍历字典,如果有创建时间超过2分钟(120s)的记录,删除,非文本的话,连文件也删除掉
109+
for key in list(rec_msg_dict.keys()):
110+
if int(cur_time) - int(rec_msg_dict.get(key).get('msg_create_time')) > 120:
111+
if not rec_msg_dict.get(key).get('msg_type') == 'Text':
112+
file_path = os.path.join(rec_tmp_dir, rec_msg_dict.get(key).get('msg_content'))
113+
print(file_path)
114+
if os.path.exists(file_path):
115+
os.remove(file_path)
116+
rec_msg_dict.pop(key)
117+
118+
119+
# 开始轮询任务
120+
def start_schedule():
121+
sched.add_job(clear_cache, 'interval', minutes=2)
122+
sched.start()
123+
124+
125+
# 退出停止所有任务并清空缓存文件夹
126+
def after_logout():
127+
sched.shutdown()
128+
shutil.rmtree(rec_tmp_dir)
129+
130+
131+
if __name__ == '__main__':
132+
sched = BlockingScheduler()
133+
if not os.path.exists(rec_tmp_dir):
134+
os.mkdir(rec_tmp_dir)
135+
itchat.auto_login(exitCallback=after_logout)
136+
itchat.run(blockThread=False)
137+
start_schedule()

Charpter 19/19_2.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
itchat登录退出回调示例
3+
"""
4+
import itchat
5+
import time
6+
7+
8+
def after_login():
9+
print("登录后调用")
10+
11+
12+
def after_logout():
13+
print("退出后调用")
14+
15+
16+
if __name__ == '__main__':
17+
itchat.auto_login(loginCallback=after_login, exitCallback=after_logout)
18+
time.sleep(5)
19+
itchat.logout()

Charpter 19/19_3.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
itchat查找用户代码示例
3+
"""
4+
5+
import itchat
6+
import time
7+
8+
if __name__ == '__main__':
9+
itchat.auto_login()
10+
11+
# 获取自己的用户信息,返回自己的属性字典
12+
# result = itchat.search_friends()
13+
# print(result)
14+
15+
# 根据姓名查找用户
16+
# result = itchat.search_friends(name='培杰')
17+
# print(result)
18+
19+
# 根据微信号查找用户
20+
# result = itchat.search_friends(wechatAccount='zpj779878443')
21+
# print(result)
22+
23+
# 根据userName查找用户
24+
result = itchat.search_friends(userName='@40b096c3036543e5b2d4de4fc22208ed')
25+
print(result)
26+

Charpter 19/19_4.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
itchat发送信息代码示例
3+
"""
4+
import itchat
5+
import time
6+
7+
8+
def after():
9+
user_info = itchat.search_friends(name='培杰')
10+
if len(user_info) > 0:
11+
# 拿到用户名
12+
user_name = user_info[0]['UserName']
13+
# 发送文字信息
14+
itchat.send_msg('培杰你好啊!', user_name)
15+
# 发送图片
16+
time.sleep(10)
17+
itchat.send_image('cat.jpg', user_name)
18+
# 发送文件
19+
time.sleep(10)
20+
itchat.send_file('19_2.py', user_name)
21+
# 发送视频
22+
time.sleep(10)
23+
itchat.send_video('sport.mp4', user_name)
24+
25+
26+
if __name__ == '__main__':
27+
itchat.auto_login(loginCallback=after)
28+
itchat.run()

Charpter 19/19_5.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
itchat监听信息并响应代码示例
3+
"""
4+
import itchat
5+
6+
7+
@itchat.msg_register(itchat.content.TEXT)
8+
def reply_msg(msg):
9+
if msg['Content'] == u'你好':
10+
itchat.send_msg(msg['User']['NickName'] + "你好啊!", msg['FromUserName'])
11+
12+
13+
if __name__ == '__main__':
14+
itchat.auto_login()
15+
itchat.run()

Charpter 19/19_6.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
itchat 群聊相关使用代码示例
3+
"""
4+
5+
import itchat
6+
import time
7+
8+
9+
@itchat.msg_register(itchat.content.TEXT, isGroupChat=True)
10+
def reply_msg(msg):
11+
print("收到一条群信息:", msg['ActualNickName'], msg['Content'])
12+
13+
14+
def after_login():
15+
# 获得完整的群聊列表
16+
print("完整的群聊列表如下:")
17+
print(itchat.get_chatrooms())
18+
# 查找特定群聊
19+
time.sleep(10)
20+
# 通过群聊名查找
21+
chat_rooms = itchat.search_chatrooms(name='小猪的Python学习交流群')
22+
if len(chat_rooms) > 0:
23+
print(chat_rooms[0])
24+
itchat.send_msg('测试', chat_rooms[0]['UserName'])
25+
26+
27+
if __name__ == '__main__':
28+
itchat.auto_login(loginCallback=after_login)
29+
itchat.run()

Charpter 19/19_7.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
itchat公众号相关使用代码示例
3+
"""
4+
import itchat
5+
6+
7+
@itchat.msg_register(itchat.content.TEXT, isMpChat=True)
8+
def reply_msg(msg):
9+
print("收到一条公众号信息:", msg['User']['NickName'], msg['Content'])
10+
11+
12+
def login_after():
13+
mps = itchat.search_mps(name='CoderPig')
14+
if len(mps) > 0:
15+
print(mps)
16+
itchat.send_msg('人生苦短', toUserName=mps[0]['UserName'])
17+
18+
19+
if __name__ == '__main__':
20+
itchat.auto_login(loginCallback=login_after)
21+
itchat.run()

Charpter 19/19_8.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
利用itchat定时发送信息
3+
"""
4+
import itchat
5+
from apscheduler.schedulers.blocking import BlockingScheduler
6+
import time
7+
8+
9+
# 发送信息
10+
def send_msg():
11+
user_info = itchat.search_friends(name='培杰')
12+
if len(user_info) > 0:
13+
user_name = user_info[0]['UserName']
14+
itchat.send_msg('生日快乐哦!', toUserName=user_name)
15+
16+
17+
def after_login():
18+
sched.add_job(send_msg, 'cron', year=2018, month=7, day=28, hour=16, minute=5, second=30)
19+
sched.start()
20+
21+
22+
def after_logout():
23+
sched.shutdown()
24+
25+
26+
if __name__ == '__main__':
27+
sched = BlockingScheduler()
28+
itchat.auto_login(loginCallback=after_login, exitCallback=after_login)
29+
itchat.run()

Charpter 19/19_9.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
itchat集成图灵API制作聊天机器人代码示例
3+
"""
4+
import itchat
5+
import requests as rq
6+
7+
8+
@itchat.msg_register(itchat.content.TEXT)
9+
def reply_msg(msg):
10+
info = msg['Content'].encode('utf8')
11+
# 图灵API接口
12+
api_url = 'http://openapi.tuling123.com/openapi/api/v2'
13+
# 接口请求数据
14+
data = {
15+
"reqType": 0,
16+
"perception": {
17+
"inputText": {
18+
"text": str(info)
19+
}
20+
},
21+
"userInfo": {
22+
"apiKey": "7e9377d76fc7ee9499f6dec8eed37bbb",
23+
"userId": "123"
24+
}
25+
}
26+
27+
headers = {
28+
'Content-Type': 'application/json',
29+
'Host': 'openapi.tuling123.com',
30+
'User-Agent': 'Mozilla/5.0 (Wi`ndows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3486.0 '
31+
'Safari/537.36 '
32+
}
33+
# 请求接口
34+
result = rq.post(api_url, headers=headers, json=data).json()
35+
# 提取text,发送给发信息的人
36+
itchat.send_msg(result['results'][0]['values']['text'], msg['FromUserName'])
37+
print()
38+
39+
40+
if __name__ == '__main__':
41+
itchat.auto_login()
42+
itchat.run()

Charpter 19/cat.jpg

87.3 KB
Loading

Charpter 19/sport.mp4

1.06 MB
Binary file not shown.

Charpter 19/voice.amr

2.32 KB
Binary file not shown.

0 commit comments

Comments
 (0)