开头第一句:人生苦短我用Python??!

大家除夕快乐啊,又过年了,面对他人群发的新春祝福,emmm...WeChat自动回复安排一下。

我使用的环境如下:①Python版本3.7;②64位Win10系统;③IDE:PyCharm。

需要pip好的Python库有:①itchat;②requests。

获取图灵机器人API:打开http://www.tuling123.com/,注册并登录账号后,创建一个机器人,然后复制好apikey。

Py代码:

# -*- coding: utf-8 -*-
'''
@Time   : 2019/2/4  11:12
@Author : Don
'''

import itchat
import requests

#获取好友列表

#向api发送请求
def get_response(msg):
    api_url = 'http://www.tuling123.com/openapi/api'  #api地址
    data = {
       'key': '9e1375ab0f3e47e788a2a6b01db16cae',   #输入apikey,以接入我的图灵机器人
       'info': msg,
    }
    try:
       r = requests.post(api_url,data).json()  #通过requests.post()以json形式进行POST请求
       print("您收到了{}发来的消息:{}".format(msg[''],msg))    #查看收到的消息
       if len(msg) > 20:
         return "新年快乐!祝您猪年心想事成!"
       else:
         return r.get('text')
    except Exception as e:  #抛出异常
       print(e)

#封装好装饰器,当接收到的消息是文本消息时
@itchat.msg_register('Text')
def text_reply(msg):
    myUserName = itchat.get_friends(update=True)[0]['UserName']  #获取自己的用户名
    remark_name = msg['User']['RemarkName'] #获取备注名称
    reply_msg = get_response(msg['Text'])  #自动回复的消息
    print("机器人回复:"+reply_msg)
    return reply_msg
    
if __name__ == '__main__':
    itchat.auto_login(hotReload=True)   #通过微信扫描二维码登录
    #若加上hotReload=True,就会保留当前登录的状态,在一定时间内运行该程序都不需要重新扫二维码登陆
    itchat.run()

然后只需要一直运行PyCharm就OK了。祝大家新春快乐!猪?年大吉吧!

不过,这个自动回复有时候回复得不好,毕竟图灵机器人不能经过大脑思考。。。

春节到了 微信自动回复安排一下_春节