python操作微信机器人自动回复

作者: 望月成三人 | 来源:发表于2019-03-24 19:10 被阅读16次

运行下面的代码,可以自动给指定的微信好友发消息

import itchat

#产生二维码
itchat.auto_login(hotReload=True)
#定义用户的昵称
send_userid='亲爱的'
#查找用户的userid
itcaht_user_name = itchat.search_friends(name=send_userid)[0]['UserName']
#利用send_msg发送消息
itchat.send_msg('这是一个测试',toUserName=itcaht_user_name)

运行下面的代码,好友发消息给你后自动回复

  • 自动回复的内容用的是图灵机器人
import requests
import itchat
# 去图灵机器人官网注册后会生成一个apikey,可在个人中心查看
KEY = '8edce3ce905a4c1dbb96**************'
def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'   : KEY,
        'info'   : msg,   # 这是要发送出去的信息
        'userid'  : 'wechat-rebot',  #这里随意写点什么都行
    }
    try:
        # 发送一个post请求
        r = requests.post(apiUrl, data =data).json()
        # 获取文本信息,若没有‘Text’ 值,将返回Nonoe 
        return r.get('text')
    except:
        return
# 通过定义装饰器加强函数 tuling_reply(msg) 功能,获取注册文本信息
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 设置一个默认回复,在出现问题仍能正常回复信息
    defaultReply = 'I received: ' +msg['Text']
    reply = get_response(msg['Text'])
    # a or b 表示,如有a有内容,那么返回a,否则返回b
    return reply or defaultReply
# 使用热启动,不需要多次扫码
itchat.auto_login(hotReload=True)
itchat.run()
  • 注意图灵机器人的免费个人账号的限制

其他

相关文章

网友评论

    本文标题:python操作微信机器人自动回复

    本文链接:https://www.haomeiwen.com/subject/dotpvqtx.html