微信聊天機(jī)器人2019

昨天,突然想試試把自己的微信號變成聊天機(jī)器人逗逗女友,于是搜集了一些資料,弄了這么個東東。目前可以調(diào)用小冰回復(fù)文字信息,可以調(diào)用baidu-aip識別圖片信息并返回結(jié)果。圖片識別分為通用識別和動物識別兩種,要啟用動物識別,先發(fā)送“動物識別”即可。效果如下:

文字聊天
圖片識別

代碼部分

新建一個名為wechatRobot.py的文件,內(nèi)容如下:

import urllib.parse
import urllib.request
from os import remove

import itchat
import requests
from aip import AipImageClassify
from itchat.content import *


class Robot:
    
    def __init__(self, whiteList, robot):
        """填寫你的baidu-aip信息"""
        APP_ID = '你的APP_ID'
        API_KEY = '你的API_KEY'
        SECRET_KEY = '你的SECRET_KEY'
        self._client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
        self._whiteList = whiteList
        self._robot = robot
        self._pic_class = 'general'
    
    def run(self):
        client = self._client
        whiteList = self._whiteList
        robot = self._robot

        @itchat.msg_register(TEXT)
        def text_reply(msg):
            nickName = msg.user.nickName
            if(msg.text[0:1]=="#"):
                print('本人消息,忽略。')
                return
            if(nickName not in whiteList):
                print('非白名單用戶')
                return
            elif(msg.text=="動物識別"):
                self._pic_class = 'animal'
                return '發(fā)張小動物的圖看看~'
            else:
                robotChat(msg)

        def robotChat(msg):   # 機(jī)器人選擇
            if robot=='ice':
                iceChat(msg)
                return
            if robot=='tuling':
                tulingChat(msg)
                return

        def iceChat(msg):   # 微軟小冰
            print('ice chat')
            print(msg['Text'])
            chatter = msg.user
            sendMsg = msg['Text'].strip()
            try:
                r = requests.get('https://www4.bing.com/socialagent/chat?q=' + sendMsg+'&anid=123456') #小冰接口
                try:
                    r1 = r.json()
                    info = urllib.parse.unquote(r1['InstantMessage']['ReplyText'])
                    print(info)
                    chatter.send(info)
                except Exception as e2:
                    print(e2)
            except Exception as e:
                print(e)

        def tulingChat(msg):   # 圖靈機(jī)器人
            print('tuling chat')
            print(msg['Text'])
            chatter = msg.user
            sendMsg = msg['Text'].strip()
            try:
                api_url = 'http://www.tuling123.com/openapi/api'
                data = {
                    'key': '你的圖靈機(jī)器人key',
                    'info': sendMsg,
                    'userid': 'wechat-robot',
                }
                r = requests.post(api_url, data=data)
                try:
                    r1 = r.json()
                    info = r1.get('text')
                    print(info)
                    chatter.send(info)
                except Exception as e2:
                    print(e2)
            except Exception as e:
                print(e)

        @itchat.msg_register(PICTURE)
        def picture_reply(msg):
            chatter = msg.user
            msg.download(msg.fileName)
            image = get_file_content(msg.fileName)
            if(self._pic_class=='general'):
                general(chatter, image)
            elif(self._pic_class=='animal'):
                animal(chatter, image)
                self._pic_class = 'general'
            remove(msg.fileName)

        # 通用識別
        def general(chatter, image):
            options = {}
            options["baike_num"] = 5
            info = client.advancedGeneral(image, options)
            print(info)
            root = info['result'][0]['root']
            keyword = info['result'][0]['keyword']
            baike_info = info['result'][0]['baike_info']
            reply_str = '這是%s\n' % keyword
            if(baike_info):
                reply_str += '百科:%s\n' % baike_info['description']
                reply_str += '百科鏈接:%s' % baike_info['baike_url']
                if(baike_info['image_url']):
                    urllib.request.urlretrieve(baike_info['image_url'], 'reply.png')
                    chatter.send('@img@%s' % 'reply.png')
            chatter.send(reply_str)
        
        # 動物識別
        def animal(chatter, image):
            options = {}
            options["top_num"] = 3
            options["baike_num"] = 5
            info = client.animalDetect(image, options)
            print(info)
            name = info['result'][0]['name']
            baike_info = info['result'][0]['baike_info']
            reply_str = '這是%s\n' % name
            if(baike_info):
                reply_str += '百科:%s\n' % baike_info['description']
                reply_str += '百科鏈接:%s' % baike_info['baike_url']
                if(baike_info['image_url']):
                    urllib.request.urlretrieve(baike_info['image_url'], 'reply.png')
                    chatter.send('@img@%s' % 'reply.png')
            chatter.send(reply_str)

        # 讀取圖片
        def get_file_content(filePath):
            with open(filePath, 'rb') as fp:
                return fp.read()
        
        itchat.auto_login(hotReload=True)
        itchat.run()

再新建一個名為main.py的文件,內(nèi)容如下:

from wechatRobot import Robot


whiteList = ['昵稱1','昵稱2','昵稱3','昵稱4']   # 聊天白名單,名字是微信昵稱

myRobot = Robot(whiteList=whiteList, robot='ice')   # 創(chuàng)建一個自己的聊天機(jī)器人
myRobot.run()   # 啟動聊天機(jī)器人

運(yùn)行

在命令行輸入:

python3 main.py

會彈出一個二維碼,用手機(jī)微信掃描此二維碼登錄微信,之后你的微信賬號就變成了聊天機(jī)器人,白名單中的用戶和你聊天就會觸發(fā)聊天機(jī)器人~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 之前所做的有一個特點就是需要在樹莓派上連接一個USB麥克風(fēng),通過這個麥克風(fēng)來進(jìn)行語音的輸入,但是在實際使用場景上來...
    IConquer閱讀 7,776評論 2 75
  • 四六級! 想到剛上大學(xué)的時候,對于英語課的影響就是:聽不懂,好難,好煩。 其實我高中時候英語還是不錯的,到后面沖刺...
    阿葵阿葵閱讀 368評論 0 2
  • 今天看微博,偶然發(fā)現(xiàn)這段文字。細(xì)細(xì)讀完,才真正發(fā)掘其背后蘊(yùn)含的深意。不論你說它牽強(qiáng)附會,還是嘩眾取寵也罷...
    耳Dong_閱讀 207評論 0 2
  • 竹枝詞 白水羊頭 晚秋天寒草結(jié)霜, 刀劈斧砍費(fèi)周章。 白水作湯文火煮, 切成紙薄分外香。
    老爸的雜拌兒糖閱讀 821評論 2 9
  • 今天天氣明媚,一如詩雨的心情,明亮而富有生氣。詩雨剛和朋友看完房子回家,這房子的價位和地段以及面積各方面太符合詩雨...
    陌上花開JLY閱讀 559評論 2 5

友情鏈接更多精彩內(nèi)容