微信自动回复简单示例01
环境:Python 3.7.0b3
平台:Windows
编译工具:PyCharm
所需模块Module:itchat、 requests(pip install)
准备:获取图灵机器人的api key(先在http://www.tuling123.com/openapi/api注册,然后创建机器人)
发送post请求:将一json串传给requests.post()的json参数
(注意中英文符号!!!)
代码如下(key部分自做修改,注释部分可调出单独调试):
'''
Created on 2018年11月26日
@author: 狗卖萌
'''
#coding=utf8
import requests
import itchat
#itchat是一个开源的微信个人号接口,为python调用微信
#itchat不是微信官方提供的库,有风险;注意!!!消息发送不过于频繁及过多重复信息,以免被封
#二维码登陆网页版微信
itchat.auto_login(hotReload=True)
#itchat.auto_login(hotReload=True)参数为True,退出程序以后暂存登录状态
#保持热登录状态,但有时限。登录信息保存在同目录下itchat.pkl文件中,下次登陆再次调用此方法登入
listfriends = itchat.get_friends()[0:]#获取好友列表
# [0:] 切片,slice表示一般是start:end:step
# a[start:] >>> items start through the rest of the array
#print(listfriend[0:])此处可获取好友列表
#exit()
#API调用
apiUrl = 'http://www.tuling123.com/openapi/api'
def get_response(message):
#发给服务器的数据
data = {
'key':'Input Your apiUrlKey',#yes,do as you see
'info': message,
'userid' : '狗卖萌',
}
try:
r = requests.post(apiUrl, data=data).json()
#捕捉异常,post发送方式到apiUrl,在没有'text'的值的时候返回None
print('狗卖萌 :%s'% r["text"])#机器人回复的消息
return r.get('text')
except:
#返回None
return
#get_response('狗卖萌呀?')
@itchat.msg_register(itchat.content.TEXT)
def auto_reply(msg):#通过run调用
#name = input('清输入要自动回复的微信好友')
defaultReply = 'I received: ' + msg['Text']
#realFriends = itchat.search_friends('DUDUDU')
#获取微信好友姓名name='DUDUDU'(示例)
#注意后面的if与else
realFriendsName = realFriends[0]['UserName']
#nickName,微信编码后的名称
#print(realFriendsName)
print('User:%s' % msg['Text']) # 获取机器人回复的消息
reply = get_response(msg['Text'])
'''
if msg['FromUserName'] == realFriendsName:#加if与else
itchat.send(reply,toUserName=realFriendsName)
else:
itchat.send(reply,toUserName=realFriendsName)
#给指定人发消息>>>if
'''
return reply or defaultReply
#如果return有内容,那么返回return,否则返回defaultReply
itchat.run()
好像是有点生硬来着,也可以改人物设置的,只是嘛要钱钱
若需要机器人持久在线,可以把脚本挂到服务器上,全天运行
(新微信号暂时无法网页登陆)
若需快速退出的话可以调用itchat.logout()注销登录状态
注意:新微信号暂时无法登入网页版微信