这几天一直在研究一个基于微信的机器人,但是研究过后发现,我的微信居然没有办法网页登录,算了,这个玩意真的要把人给气死,在github以及google的搜索下,终于发现了一个wechaty,基于微信ipad协议的。接下来就是我试用15天的感受。
了解wechaty有哪些接口
- scan事件会在需要扫码登陆微信的被触发
- login事件会在机器人成功登陆后被触发
- logout事件会在机器人掉线以后被触发
- message事件会在有新消息的时候被触发
- error事件会在程序出现error的时候被触发
- friend事件会在有好友请求的时候被触发
- room-join事件会在有人加入群时被触发
- room-leave事件会在群主移好友出群时被触发
- room-topic事件会在群名称被修改时被触发
编写wechaty代码
-
由于我使用的是node的wechaty代码,接下来都是基于wechaty进行开发的。
//最基本的代码段 const { Wechaty } = require('wechaty')
Wechaty.instance() // Singleton .on('scan', (url, code) => console.log(
Scan QR Code to login: ${code}\n${url})) .on('login', user => console.log(User ${user} logined)) .on('message', message => console.log(Message: ${message})) .init()
这个代码段就可以让你在页面中显示你所要操作的东西了,那么,如何进行开发定制一个自己想要的机器人,来解放自我,或者就是单纯的想要哄女朋友开心,让家人知道今天的天气,以及每天给暗恋的对象一个亲切的问候。这样的话就需要涉及到定时器了,这个下个篇幅在做扩展。今天就单纯的介绍一下,如何基于腾讯的闲聊机器人,来开发一个可以聊天的机器人。
//引入几个核心包,qr-image是为了将二维码输出至本地
var qrImg = require('qr-image');
const { Wechaty } = require("wechaty") // Wechaty核心包
const { PuppetPadplus } = require("wechaty-puppet-padplus") // padplus协议包
const { Friendship } = require("wechaty")
const config = require("./src/config") // 配置文件
var fs = require('fs');
var request = require('request');
const tencentcloud = require("tencentcloud-sdk-nodejs");
const NlpClient = tencentcloud.nlp.v20190408.Client;
const addFriendKeywords = config.personal.addFriendKeywords
// 初始化
const bot = new Wechaty({
puppet: new PuppetPadplus({
token: config.token
}),
name: config.name
})
//初始化闲聊机器人,创建链接
const clientConfig = {
credential: {
secretId: "你的腾讯闲聊机器人的id",
secretKey: "闲聊机器人的key",
},
region: "ap-guangzhou",
profile: {
httpProfile: {
endpoint: "nlp.tencentcloudapi.com",
},
},
};
//大餐正式开始
bot
.on("scan", function onScan(qrcode, status) {
//这是初始化扫码
var img = qrImg.image(qrcode, { size: 10 });
img.pipe(fs.createWriteStream("logo.png"));
})
.on('login', async user => {
//后续这边编写定时任务
})
.on("message", async message => {
//当有人给你发送消息的时候
if(message.self()) return ;
const contact = message.from()
const contact1 = await bot.Contact.find({name: contact.name()})
var params = {
"Query": message.text()
}
client.ChatBot(params).then(
async function(data){
await contact1.say(data.Reply)
},
(err) => {
console.error("error", err);
}
);
})
.on("friendship", async friendship =>{
//发送好友请求
switch (friendship.type()) {
case Friendship.Type.Receive:
if (addFriendKeywords.some(v => v == friendship.hello())) {
friendship.accept()
}
break
}
})
.start();
接下来还有一些配置文件:
module.exports = {
// puppet_padplus Token
token: "你的token",
// 机器人名字
name: "名字",
// 私人
personal: {
// 好友验证自动通过关键字
addFriendKeywords: ["定时", "博客", "彩虹屁", "天气"],
// 是否开启加群
addRoom: true
}
}
有人会问了,那我没有token怎么办?如何申请token
因为会有无偿使用的15天,所以,这是我使用15天之后的感受,另外附上我的开源代码(该部分包括定时任务代码)。
附:需要安装代码框架
npm install -save qr-image
npm install -save wechaty
npm install -save wechaty-puppet-padplus
npm install -save fs
npm install -save request
npm install -save tencentcloud-sdk-nodejs