微信聊天機器人


實現機器人自動回復微信消息

import arrow
import itchat
import pydash
import requests


def local_datetime():
    """格式化的時間戳"""
    return arrow.now().format("YYYY-MM-DD HH:mm:ss")


def get_user_info(wx_msg):
    """獲取發送信息的用戶參數"""
    userName = wx_msg['FromUserName']
    data = itchat.search_friends(userName=userName)
    info = pydash.pick(data, 'UserName', 'NickName', 'RemarkName', 'Signature')
    return info


def get_response(wx_msg):
    """處理接受到的信息,調用機器人接口回復消息"""
    user_info = get_user_info(wx_msg)
    message = wx_msg["Text"]
    print('來至{}\t{}\t{}'.format(user_info.get('RemarkName'), message, local_datetime()))
    reply = access_ownthink_robot(message)
    print('回復{}\t{}\t{}'.format(user_info.get('RemarkName'), reply, local_datetime()))
    return reply


def access_ownthink_robot(message):
    """調用思知機器人回復消息
    origin='https://www.ownthink.com/'
    :param message:
    :return:
    """
    url = "https://api.ownthink.com/bot?appid=替換為思知機器人appid&spoken={}".format(message)
    r = requests.get(url)
    reply = pydash.get(r.json(), 'data.info.text')
    return reply


def access_tuling_robot(message):
    """調用圖靈機器人回復消息
    {
    "intent": {
        "code": 10005,
        "intentName": "",
        "actionName": "",
        "parameters": {
            "nearby_place": "酒店"
        }
    },
    "results": [
        {
             "groupType": 1,
            "resultType": "url",
            "values": {
                "url": "http://m.elong.com/hotel/0101/nlist/#indate=2016-12-10&outdate=2016-12-11&keywords=%E4%BF%A1%E6%81%AF%E8%B7%AF"
            }
        },
        {
             "groupType": 1,
            "resultType": "text",
            "values": {
                "text": "親,已幫你找到相關酒店信息"
            }
        }
        ]
    }
    :param message:
    :return:
    """
    # origin="http://openapi.tuling123.com/"
    url = "http://openapi.tuling123.com/openapi/api/v2"
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": message,
            },
        },
        "userInfo": {
            "apiKey": "替換為圖靈機器人apiKey",
            "userId": "dongting"
        }
    }
    r = requests.post(url, json=data)
    reply = pydash.get(r.json(), 'results.values.text')
    return reply


@itchat.msg_register(itchat.content.TEXT)
def text_reply(wx_msg):
    """接受微信消息並回復"""
    return get_response(wx_msg)


if __name__ == '__main__':
    itchat.auto_login()
    itchat.run()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM