用python的第三方库itcha,做一个微信聊天机器人。
import requests import itchat KEY = '**************************' #KEY为图灵机器人的api密钥,自己可以去官网申请 def get_response(msg): apiUrl = 'http://www.tuling123.com/openapi/api' data = { 'userid' : 'wechat-robot', 'key' : KEY, 'info' : msg, } try: r = requests.post(apiUrl, data=data).json() return r.get('text') except: return @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg): defaultReply = 'I received: ' + msg['Text'] reply = get_response(msg['Text']) return reply or defaultReply itchat.auto_login(hotReload=True) itchat.run()
当然,要优化一下代码会超过20行,但是请不用介意。另外这是P3版本的代码。itchat包除了可以做机器人,还可以很多功能,点击查看。