wxpy——聊天机器人的实现

一、安装wxpy包

通过cmd中输入   pip install -U wxpy -i "https://pypi.doubanio.com/simple/"   进行安装

二、在python中登录微信web版

1 from wxpy import *
2 #初始化执行登陆操作,需要手机扫描登陆   bot = Bot()
3 #自动保存登陆信息,不再需要扫描二维码
4 bot = Bot(cache_path=True)

三、部分简单功能

#给文件助手发送消息
bot.file_helper.send('hi! 助手')   

#指定聊天对象.处需要使用备注名!(尽量唯一)
my_friend = bot.friends().search('xxxx')[0]
my_friend.send('你干啥呢')

#自动回复
my_friend = bot.friends().search('xxxx')[0]
@bot.register(my_friend)
def reply(msg):
    return'目前较忙,已收到您的消息,空闲时将回复' 

 四、智能机器人回复

需要在http://www.tuling123.com上注册账号,通过图灵机器人完成初级的智能回复,比如询问天气等等

from wxpy import *
import requests
import json

bot = Bot(cache_path=True)

def auto_replay(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "7*****************b"
    payload = {'key':api_key,
               'info':text,
               'userid':'rebot'}
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return result['text']
#注意!这是所有人都回复
@bot.register()
def print_message(msg):
    #print(msg.text)
    return auto_replay(msg.text)

五、指定群聊/人自动回复

#指定群聊
group = bot.groups().search('群聊名')[0]
#指定好友
friend = bot.friends().search('好友名')[0]
#按需求修改参数
@bot.register(group,msg_types=TEXT)

 

posted @ 2018-09-15 20:40  没有神保佑的瓶子  阅读(3579)  评论(0编辑  收藏  举报