微信聊天机器人2019

转载注明出处

原文链接: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原文链接

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值