itchat 是一个调用微信的python接口,通过itchat,可以基于开发一些扩展功能。官方教程通俗易懂,官方教程入口:
http://itchat.readthedocs.io/zh/latest/tutorial/tutorial0/
下面的代码,添加了自动聊天机器人的功能,里面使用了图灵机器人,可以到官网上申请一个,官网地址:http://www.tuling123.com/
# -*-coding:utf-8-*-
import itchat
import requests
# 这里定义了一个自动聊天的用户列表
# 当以下用户发送消息时,才进行自动聊天
auto_reply_list = [
'家霖',
]
# 对图片的处理:对方发来图片或表情时,直接回复该图片
@itchat.msg_register(itchat.content.PICTURE)
def tuling_reply(msg):
# 如果不在auto_reply_list列表中,则直接返回
if msg.user.RemarkName not in auto_reply_list:
return None
msg.download(msg.fileName)
itchat.send('@%s@%s' % (
'img' if msg['Type'] == 'Picture' else 'fil', msg['FileName']),
msg['FromUserName'])
return '反弹~'
# 对文字的处理:对方发送来文字时,调用图灵机器人的接口,实现自动聊天
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
# 如果不在auto_reply_list列表中,则直接返回
if msg.user.RemarkName not in auto_reply_list:
return None
print(msg.user.RemarkName +" "+ msg['Text'])
defaultReply = '我的主人不在,等主人回来我会将你的话告诉他的~'
reply = get_response(msg['Text'])
return reply or defaultReply
KEY = '' # 替换成自己的key,可以到图灵机器人官网注册并申请一个
def get_response(msg):
# 构造了要发送给服务器的数据
apiUrl = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg,
'userid' : 'wechat-robot',
}
try:
r = requests.post(apiUrl, data=data).json()
return r.get('text')
except:
return
itchat.auto_login(hotReload=True) # 设置为true,不用每一次都扫描二维码
itchat.run()
参考:
http://itchat.readthedocs.io/zh/latest/
https://www.cnblogs.com/Erick-L/p/6895514.html