Un robot node.js para wechat.
El sistema de respuesta automática de la interfaz de información abierta proporcionada por la plataforma pública WeChat.
weixin-robot
es un contenedor de alto nivel para webot y wechat-mp. webot
es responsable de definir las reglas de respuesta wechat-mp
es responsable de comunicarse con el servidor WeChat.
Características:
Agregue una cuenta WeChat y pruebe el efecto:
Más lista de robots WeChat que utilizan este proyecto
var express = require ( 'express' ) ;
var webot = require ( 'weixin-robot' ) ;
var app = express ( ) ;
// 指定回复消息
webot . set ( 'hi' , '你好' ) ;
webot . set ( 'subscribe' , {
pattern : function ( info ) {
return info . is ( 'event' ) && info . param . event === 'subscribe' ;
} ,
handler : function ( info ) {
return '欢迎订阅微信机器人' ;
}
} ) ;
webot . set ( 'test' , {
pattern : / ^test / i ,
handler : function ( info , next ) {
next ( null , 'roger that!' )
}
} )
// 你可以获取已定义的 rule
//
// webot.get('subscribe') ->
//
// {
// name: 'subscribe',
// pattern: function(info) {
// return info.is('event') && info.param.event === 'subscribe';
// },
// handler: function(info) {
// return '欢迎订阅微信机器人';
// }
// }
//
// 接管消息请求
webot . watch ( app , { token : 'your1weixin2token' , path : '/wechat' } ) ;
// 如果需要多个实例(即为多个微信账号提供不同回复):
var webot2 = new webot . Webot ( ) ;
webot2 . set ( {
'/hi/i' : 'Hello' ,
'/who (are|r) (you|u)/i' : 'I'm a robot.'
} ) ;
webot2 . watch ( app , {
token : 'token2' ,
path : '/wechat_en' , // 这个path不能为之前已经监听过的path的子目录
} ) ;
// 启动 Web 服务
// 微信后台只允许 80 端口
app . listen ( 80 ) ;
// 如果你不想让 node 应用直接监听 80 端口
// 可以尝试用 nginx 或 apache 自己做一层 proxy
// app.listen(process.env.PORT);
// app.enable('trust proxy');
Luego puede completar la dirección de su interfaz y el token en el fondo de la plataforma pública WeChat, o usar webot-cli para depurar mensajes.
Si todo va bien y has construido tu propio robot, bienvenido a la página wiki de este proyecto para agregar tu cuenta.
Proporcionar un archivo ejecutable webot
para enviar mensajes de prueba. Instale webot-cli usando npm
:
npm install webot-cli -g
webot-cli proporciona la función de procesar menús personalizados de WeChat. Después de la instalación, ejecute:
webot help menu
0.5.0 - Cambiar a un módulo wechat-mp más optimizado
Nota: Ahora, si desea habilitar el soporte de sesión, webot.watch
debe estar antes de app.use(connect.session())
> Para obtener definiciones de reglas específicas, consulte la documentación de webot.
API principal:
El objeto de información recibido por el controlador de la regla webot contiene el contenido del mensaje de solicitud y el soporte de sesión.
info
de wexin-robot
empaqueta el contenido de la solicitud de WeChat en un valor que está más en línea con las reglas de nomenclatura js y almacena parámetros adicionales en info.param
de acuerdo con MsgType
. Esto garantiza la estandarización de los objetos info
y le facilita el uso del mismo robot en diferentes plataformas.
Puede obtener el objeto de parámetro coherente con el documento oficial de WeChat a través de info.raw
.
Tabla de comparación de parámetros de solicitud originales y atributos de información:
官方参数名 定义 info对象属性 备注
-------------------------------------------------------------------------------------------------------
ToUserName 开发者微信号 info.sp sp means "service provider"
FromUserName 发送方帐号(一个OpenID) info.uid
CreateTime 消息创建时间 (整型)
MsgId 消息id info.id
MsgType 消息类型 info.type
-------------------------------------------------------------------------------------------------------
Content 文本消息内容 info.text MsgType == text
-------------------------------------------------------------------------------------------------------
PicUrl 图片链接 info.param.picUrl MsgType == image
-------------------------------------------------------------------------------------------------------
Location_X 地理位置纬度(lat) info.param.lat MsgType == location
Location_Y 地理位置经度(lng) info.param.lng
Scale 地图缩放大小 info.param.scale
Label 地点名 info.param.label 可能为空
-------------------------------------------------------------------------------------------------------
Title 消息标题 info.param.title MsgType == link
Description 消息描述 info.param.description
Url 消息链接 info.param.url
-------------------------------------------------------------------------------------------------------
Event 事件类型 info.param.event MsgType == event
subscribe(订阅)、
unsubscribe(取消订阅)、
CLICK(自定义菜单点击事件)
LOCATION(上报地理位置事件)
EventKey 事件KEY值,与自定义菜单接 info.param.eventKey
口中KEY值对应
--------------------------------------------------------------------------------------------------------
MediaId 媒体文件的 id info.param.mediaId MsgType == voice / video
Recognition 语音识别的文本 info.param.recognition MsgType == voice
ThumbMediaId 视频消息缩略图的媒体id info.param.thumbMediaId MsgType == video
Format 音频文件的格式 info.param.format
Aviso:
Location_X
y Location_Y
de información geográfica.info.text
, pero info.type
es diferente.Por ejemplo, un mensaje de ubicación (MsgType === 'ubicación') se convertirá a:
{
uid : 'the_FromUserName' ,
sp : 'the_ToUserName' ,
id : 'the_MsgId' ,
type : 'location' ,
param : {
lat : 'the_Location_X' ,
lng : 'the_Location_Y' ,
scale : 'the_Scale' ,
label : 'the_Label'
}
}
La mayoría de las veces no es necesario asignar un valor a info.reply directamente .
Solo necesita proporcionar el contenido del mensaje de respuesta en el valor de retorno de rule.handler
o callbak. El middleware rápido que viene con webot.watch
asignará automáticamente un valor a info.reply
, lo empaquetará en XML y lo enviará al. Servidor WeChat.
Tipos de datos admitidos por info.reply
:
info . reply = '收到你的消息了,谢谢'
title 消息标题
url 消息网址
description 消息描述
picUrl 消息图片网址
info . reply = {
title : '消息标题' ,
url : 'http://example.com/...' ,
picUrl : 'http://example.com/....a.jpg' ,
description : '对消息的描述出现在这里' ,
}
// or
info . reply = [ {
title : '消息1' ,
url : 'http://example.com/...' ,
picUrl : 'http://example.com/....a.jpg' ,
description : '对消息的描述出现在这里' ,
} , {
title : '消息2' ,
url : 'http://example.com/...' ,
picUrl : 'http://example.com/....a.jpg' ,
description : '对消息的描述出现在这里' ,
} ]
title 标题
description 描述
musicUrl 音乐链接
hqMusicUrl 高质量音乐链接,wifi 环境下会优先使用该链接播放音乐
Debes especificar reply.type
como 'music'
:
info . reply = {
type : 'music' ,
title : 'Music 101' ,
musicUrl : 'http://....x.mp3' ,
hqMusicUrl : 'http://....x.m4a'
}
¡Diviértete con wechat y disfruta siendo un robot!
Si no desea responder a un mensaje, puede configurar info.noReply = true
// 比如对于语音类型的消息不回复
webot . set ( 'ignore' , {
pattern : function ( info ) {
return info . is ( 'voice' ) ;
} ,
handler : function ( info ) {
info . noReply = true ;
return ;
}
} ) ;
(La licencia MIT)
Por el presente se otorga permiso, sin cargo, a cualquier persona que obtenga una copia de este software y los archivos de documentación asociados (el 'Software'), para operar con el Software sin restricciones, incluidos, entre otros, los derechos de uso, copia, modificación, fusión. , publicar, distribuir, sublicenciar y/o vender copias del Software, y permitir que las personas a quienes se les proporciona el Software lo hagan, sujeto a las siguientes condiciones:
El aviso de derechos de autor anterior y este aviso de permiso se incluirán en todas las copias o partes sustanciales del Software.
EL SOFTWARE SE PROPORCIONA "TAL CUAL", SIN GARANTÍA DE NINGÚN TIPO, EXPRESA O IMPLÍCITA, INCLUYENDO, ENTRE OTRAS, LAS GARANTÍAS DE COMERCIABILIDAD, IDONEIDAD PARA UN PROPÓSITO PARTICULAR Y NO INFRACCIÓN, EN NINGÚN CASO LOS AUTORES O TITULARES DE LOS DERECHOS DE AUTOR SERÁN RESPONSABLES DE NINGÚN TIPO. RECLAMACIÓN, DAÑOS U OTROS RESPONSABILIDAD, YA SEA EN UNA ACCIÓN CONTRACTUAL, AGRAVIO O DE OTRA MANERA, QUE SURJA DE, FUERA DE O EN RELACIÓN CON EL SOFTWARE O EL USO U OTRAS NEGOCIOS EN EL SOFTWARE.