itchat实现自动回复好友消息

# coding=utf8
import itchat

msg_information = {}

# 自动回复
# 封装好的装饰器,当接收到的消息是Text,即文字消息
@itchat.msg_register('Text', isFriendChat=True)
def text_reply(msg):
    from_user_name = msg['FromUserName']
    print("消息发送人", from_user_name)
    if from_user_name == myUserName:
        print("消息发送者是本人")
        return
    if not from_user_name == autoReplyPerson:
        print("消息发送者不是需要自动回复的人")
        return
    msg_content = msg['Text']

    msg_information.update({autoReplyPerson: ""})

    msg_information.update({from_user_name: {"msg": msg_content}})
    msg_information.update({"cur_from_user_name": from_user_name})

    send_msg_xiaoice(msg_content)

    print(msg_information)


    # 当消息不是由自己发出的时候
    # if not from_user_name == myUserName:
    #     # 发送一条提示给文件助手
    #     itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %
    #                     (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),
    #                      msg['User']['NickName'],
    #                      msg['Text']), 'filehelper')
    #     # 回复给好友
    #     return u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['Text'])


def send_msg_xiaoice(msg_conteny):
    mps = itchat.search_mps(name='小冰')
    xiaoice = mps[0]["UserName"]
    itchat.send(msg_conteny, xiaoice)


@itchat.msg_register('Text', isMpChat=True)
def xiaoice_reply(msg):
    from_user_name = msg['FromUserName']
    msg_content = msg['Text']

    msg_information.update({from_user_name: msg_content})
    print('小冰回复了!', msg_information)

    itchat.send_msg(msg_content, msg_information.get("cur_from_user_name"))


if __name__ == '__main__':
    itchat.auto_login(hotReload=True)

    # 获取自己的UserName
    myUserName = itchat.get_friends(update=True)[0]["UserName"]
    autoReplyPerson = itchat.search_friends(name="周菜霞")[0]["UserName"]
    print(autoReplyPerson)
    itchat.run()

环境为python3。试过调用图灵机器人的接口,但是图灵有次数限制。

实现方式:首先要关注"微软小冰";将需要自动回复的好友消息转发给“微软小冰”,将“微软小冰”回复的消息直接转发给好友;只能同时给一个人设置自动回复, 要不然"微软小冰"回复的消息会失去上下文关联, 显得回复有点错了.

你可能感兴趣的:(python)