轉載注明出處
原文連結:https://blog.csdn.net/splawny/article/details/93068669
昨天,突然想試試把自己的微信号變成聊天機器人逗逗女友,于是搜集了一些資料,弄了這麼個東東。目前可以調用小冰回複文字資訊,可以調用baidu-aip識别圖檔資訊并傳回結果。圖檔識别分為通用識别和動物識别兩種,要啟用動物識别,先發送“動物識别”即可。效果如下:
代碼部分
建立一個名為wechatRobot.py的檔案,内容如下:
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):
"""填寫你的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 = 'tuling' # 預設使用圖靈機器人
self._pic_class = 'general'
def run(self):
client = self._client
whiteList = self._whiteList
@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
if(msg.text=="動物識别"):
self._pic_class = 'animal'
return '發張小動物的圖看看~'
elif(msg.text=='呼叫小冰'):
self._robot = 'ice'
return '我是小冰,什麼事兒呀~'
elif(msg.text=='呼叫圖靈'):
self._robot = 'tuling'
return '我是圖靈機器人,什麼事兒呀~'
else:
robotChat(msg)
def robotChat(msg): # 機器人選擇
if self._robot=='ice':
iceChat(msg)
return
if self._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): # 圖靈機器人
print('tuling chat')
print(msg['Text'])
chatter = msg.user
sendMsg = msg['Text'].strip()
try:
api_url = 'http://www.tuling123.com/openapi/api'
data = {
'key': '你的圖靈機器人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的檔案,内容如下:
from wechatRobot import Robot
whiteList = ['昵稱1','昵稱2','昵稱3','昵稱4'] # 聊天白名單,名字是微信昵稱
myRobot = Robot(whiteList=whiteList) # 建立一個自己的聊天機器人
myRobot.run() # 啟動聊天機器人
運作
在指令行輸入:
python3 main.py
會彈出一個二維碼,用手機微信掃描此二維碼登入微信,之後你的微信賬号就變成了聊天機器人,白名單中的使用者和你聊天就會觸發聊天機器人~
預設是圖靈機器人跟你聊,如果你發送“呼叫小冰”,就會換成小冰跟你聊,如果再發送“呼叫圖靈”,就會換回圖靈機器人。
作者:splwany,CSDN原文連結