【分享】用Python打造自己的微信机器人

简介

由于我没事喜欢去github上找找好玩有趣的东西,这次又淘到一个有意思的应用,通过python调用微信接口来把自己的微信号转变成一个可以自动回复的机器人。

原文地址:http://itchat.readthedocs.io/zh/latest/

实践起来可能还需要有一些调整:

安装

命令行安装(预装pip,没有装的请参考,python3):

1
$pip3 install itchat

接下来我们绕过原文文档的内容,直奔主题

先创建一个文件夹,文件夹里需包含3个文件:

  • wechat.py (主程序)
  • tuling.py (图灵机器人模块调用)
  • tuling.json (图灵账号配置API Key)

配置

wechat.py

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
#coding=utf8
import itchat
# tuling plugin can be get here:
# https://github.com/littlecodersh/EasierLife/tree/master/Plugins/Tuling
from tuling import get_response

@itchat.msg_register('Text')
def text_reply(msg):
if u'作者' in msg['Text'] or u'主人' in msg['Text']:
return u'你可以在这里了解他:https://github.com/littlecodersh'
elif u'源代码' in msg['Text'] or u'获取文件' in msg['Text']:
itchat.send('@fil@main.py', msg['FromUserName'])
return u'这就是现在机器人后台的代码,是不是很简单呢?'
elif u'获取图片' in msg['Text']:
itchat.send('@img@applaud.gif', msg['FromUserName']) # there should be a picture
else:
return get_response(msg['Text']) or u'收到:' + msg['Text']

@itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
def atta_reply(msg):
return ({ 'Picture': u'图片', 'Recording': u'录音',
'Attachment': u'附件', 'Video': u'视频', }.get(msg['Type']) +
u'已下载到本地') # download function is: msg['Text'](msg['FileName'])

@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing'])
def mm_reply(msg):
if msg['Type'] == 'Map':
return u'收到位置分享'
elif msg['Type'] == 'Sharing':
return u'收到分享' + msg['Text']
elif msg['Type'] == 'Note':
return u'收到:' + msg['Text']
elif msg['Type'] == 'Card':
return u'收到好友信息:' + msg['Text']['Alias']

@itchat.msg_register('Text', isGroupChat = True)
def group_reply(msg):
if msg['isAt']:
return u'@%s\u2005%s' % (msg['ActualNickName'],
get_response(msg['Text']) or u'收到:' + msg['Text'])

@itchat.msg_register('Friends')
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.send_msg(u'项目主页:github.com/littlecodersh/ItChat\n'
+ u'源代码 :回复源代码\n' + u'图片获取:回复获取图片\n'
+ u'欢迎Star我的项目关注更新!', msg['RecommendInfo']['UserName'])

itchat.auto_login(True, enableCmdQR=True)
itchat.run()

Tuling.py

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
#coding=utf8
import sys, os
import requests, json

try:
with open('tuling.json') as f: key = json.loads(f.read())['key']
except:
key = '' # if key is '', get_response will return None
# raise Exception('There is something wrong with the format of you plugin/config/tuling.json')

def get_response(msg, storageClass = None, userName = None, userid = 'ItChat'):
url = 'http://www.tuling123.com/openapi/api'
payloads = {
'key': key,
'info': msg,
'userid': userid,
}
try:
r = requests.post(url, data = json.dumps(payloads)).json()
except:
return
if not r['code'] in (100000, 200000, 302000, 308000, 313000, 314000): return
if r['code'] == 100000: # 文本类
return '\n'.join([r['text'].replace('<br>','\n')])
elif r['code'] == 200000: # 链接类
return '\n'.join([r['text'].replace('<br>','\n'), r['url']])
elif r['code'] == 302000: # 新闻类
l = [r['text'].replace('<br>','\n')]
for n in r['list']: l.append('%s - %s'%(n['article'], n['detailurl']))
return '\n'.join(l)
elif r['code'] == 308000: # 菜谱类
l = [r['text'].replace('<br>','\n')]
for n in r['list']: l.append('%s - %s'%(n['name'], n['detailurl']))
return '\n'.join(l)
elif r['code'] == 313000: # 儿歌类
return '\n'.join([r['text'].replace('<br>','\n')])
elif r['code'] == 314000: # 诗词类
return '\n'.join([r['text'].replace('<br>','\n')])

if __name__ == '__main__':
try:
ipt = raw_input
ipt = lambda: raw_input('>').decode(sys.stdin.encoding)
except:
ipt = lambda: input('>')
while True:
a = ipt()
print(get_response(a, 'ItChat'))

Tuling.json

1
2
3
{
"key": "d7f31775f8d048fdxxxxxxxxxx" #替换成自己的API Key
}

图灵API Key

  1. http://www.tuling123.com/注册账号

  2. 创建机器人

  3. 首页-机器人看板 获取API Key,替换掉Tuling.json文件中的key值

运行

接下来,直接运行wechat.py文件,扫描弹出的二维码授权登录,即可。

找几个微信好友调戏起来吧!