微信聊天機械人2019

2021-09-24 15:04:36 字數 4450 閱讀 8463

新建乙個名為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資訊"""

api_key = '你的api_key'

secret_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('' + 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 = ''

data =

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']

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']

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

myrobot = robot(whitelist=whitelist) # 建立乙個自己的聊天機械人

myrobot.run() # 啟動聊天機械人

在命令列輸入:

python3 main.py
預設是圖靈機械人跟你聊,如果你傳送「呼叫小冰」,就會換成小冰跟你聊,如果再傳送「呼叫圖靈」,就會換回圖靈機械人。

微信聊天機械人

import arrow import itchat import pydash import requests deflocal datetime 格式化的時間戳 return arrow.now format yyyy mm dd hh mm ss defget user info wx msg...

微信自動聊天機械人

背景 操作步驟 操作過程 import requests import itchat 圖靈機人人的apikey key d7b92b1df4ef4ba6a6c649200208f103 defget response msg 這個位址在此處給出,一看就懂 apiurl data的本質是乙個地點,要想...

微信聊天機械人(wepy)的使用

是基於wxpy的,所以在使用之前得安裝wxpy pip install wxpy 或者pip3 install wxpy 去官方提供的api是可以進行基礎學習,這裡就不細說了,直接上機械人聊天部分,官網的api提供了兩種機械人 圖靈機和小i 我們首先來看一下圖靈機 from wxpy import ...