微信机器人自动解析二维码
最近老婆在玩的一款游戏,有个任务是分享一个二维码图片给微信好友,然后好友按住图片点两下识别二维码就行了,她总是发给我的帐号,让我给识别,有时候忙起来给忘了,最近在学习Python,就想用Python现成的机器人做一个自动识别二维码的小软件。
直接上代码:
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
import itchat, time
from itchat.content import *
from PIL import Image
import zbarlight
import urllib.request
from urllib import request
import os
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
msg.user.send('%s: %s' % (msg.type, msg.text))
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
msg.download(msg.fileName)
ab_name = msg.fileName
with open(ab_name, 'rb') as image_file:
image = Image.open(image_file)
image.load()
codes = zbarlight.scan_codes('qrcode', image)
a_url = codes[0].decode("utf-8")
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = request.Request(a_url, headers=head)
response = request.urlopen(req)
html = response.read().decode('utf-8')
time.sleep(2)
with open(ab_name, 'rb') as image_file:
image = Image.open(image_file)
image.load()
codes = zbarlight.scan_codes('qrcode', image)
a_url = codes[0].decode("utf-8")
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = request.Request(a_url, headers=head)
response = request.urlopen(req)
html = response.read().decode('utf-8')
return a_url
@itchat.msg_register(FRIENDS)
def add_friend(msg):
msg.user.verify()
msg.user.send('Nice to meet you!')
@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
if msg.isAt:
msg.user.send(u'@%s\u2005I received: %s' % (
msg.actualNickName, msg.text))
itchat.auto_login(enableCmdQR=2)
itchat.run(True)
直接从https://github.com/littlecodersh/ItChat 主页上的样例复制过来,增加了下自己需要的功能,然后在Linux命令行下结合screen命令使用。
Linux命令行下如果二维码显示不全的话,把终端的字体大小调节小一点,我用的上SecureCRT。
效果图:
本文由作者按照
CC BY 4.0
进行授权