之前发表过chatterbot 的自定义api本人的流程 但是有粉丝或游客私信我 怎样对接自己个人微信 现在统一回复下 自己的心得流程 实现等
在写代码之前我先表述下 之前个人微信接口 使用itchat 等 在使用这类的前提是可以 登录网页版微信 网页版微信登录链接 itchat原理就是一种爬虫 获取绘话信息处理并返回自定义信息(跑远了…) 要想获取个人微信中的对话 必须登录 才能自定义一些逻辑啥的
前几天自己写了能实现对接chatterbot的api接口
1 首先我们要绕过登录验证 能成功登录
2 我是用node.js(对用开发来说这个学习起来还好…)+wechaty这是前端 后端django chatterbot等 参考项目 参考资料
3 点击参考资料下载 配置什么的可以点击参考资料 我现在主要讲解下 微信对接api
项目中node配置之后安装包时候可能会有些问题(除了那个文档之外的命令)
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
npm config set puppeteer_download_host https://npm.taobao.org/mirrors
set WECHATY_LOG=verbose
set WECHATY_PUPPET=wechaty-puppet-wechat
目录中index.js 我只添加了一部分代码 用于调用自己的后台接口 其中 reply = await superagent.getMonekyReply(content);调用自己的获取后台的方式
// 监听对话
async function onMessage(msg) {
const contact = msg.talker(); // 发消息人
const content = msg.text().trim(); // 消息内容
const room = msg.room(); // 是否是群消息
const alias = await contact.alias() || await contact.name(); // 发消息人备注
const isText = msg.type() === bot.Message.Type.Text;
if (msg.self()) {
return;
}
if (room && isText) {
// 如果是群消息 目前只处理文字消息
const topic = await room.topic();
console.log(`群名: ${topic} 发消息人: ${await contact.name()} 内容: ${content}`);
} else if (isText) {
// 如果非群消息 目前只处理文字消息
console.log(`发消息人: ${alias} 消息内容: ${content}`);
if (content.substr(0, 1) == '?' || content.substr(0, 1) == '?') {
let contactContent = content.replace('?', '').replace('?', '');
if (contactContent) {
let res = await superagent.getRubbishType(contactContent);
await delay(2000);
await contact.say(res);
}
} else if (config.AUTOREPLY && config.AUTOREPLYPERSON.indexOf(alias) > -1) {
// 如果开启自动聊天且已经指定了智能聊天的对象才开启机器人聊天\
if (content) {
let reply;
if (config.DEFAULTBOT == '0') {
// 天行聊天机器人逻辑
reply = await superagent.getMonekyReply(content);
console.log('Monkey机器人回复:', reply);
} else if (config.DEFAULTBOT == '1') {
// 图灵聊天机器人
reply = await superagent.getTuLingReply(content);
console.log('图灵机器人回复:', reply);
} else if (config.DEFAULTBOT == '2') {
// 天行对接的图灵聊
reply = await superagent.getTXTLReply(content);
console.log('天行对接的图灵机器人回复:', reply);
}
try {
await delay(2000);
await contact.say(reply);
} catch (e) {
console.error(e);
}
}
}
}
}
superagent->index.js
const MONKEYAPI = 'http://127.0.0.1:8000/'; // 自建1.0接口api
async function getMonekyReply(world) {
// 获取自建机器人信息
let url = MONKEYAPI + 'testbot/';
try {
let content = await superagent.req({
url, method: 'POST', data: {
"text":world
}
});
console.info(content);
c_text = content.text
c_replace_text = c_text.replace(/'/g, `"`)
c_json= JSON.parse(c_replace_text)
obj = c_json.words
return obj;
//if (content.code === 200) {
// let obj = content["text"]["worlds"][0];
//console.info('获取成功', obj);
//return obj;
//}
} catch (err) {
console.log('请求失败', err);
}
}
module.exports = {
XXX,
getMonekyReply
};
superagent ->superagent.js中修改
.set('Content-Type', 'application/json')
大致项目改了这几处 效果如下 api对接一个简单的天气爬虫…