npm install --save wechat4u@latest
const Wechat = require ( 'wechat4u' )
let bot = new Wechat ( )
bot . start ( )
// 或使用核心API
// const WechatCore = require('wechat4u/lib/core')
git clone https://github.com/nodeWechat/wechat4u.git
cd wechat4u
npm install
npm run core // 命令行模式
npm run compile // babel编译
node run-core.js
See the code for logic, it’s concise and complete, be sure to read it
let bot = new Wechat ( [ botData ] )
If botData
is passed in, this robot information will be used to restart the previous synchronization.
All properties are read-only
Exportable basic information of the instance. You can fill in this information and resynchronize it when you create a new bot next time.
Necessary information to stay logged in
Configuration information, including current server address, API path and some constants
The program needs to use the constants in CONF to determine the new message type of the current status.
bot . state == bot . CONF . STATE . init // 初始化状态
bot . state == bot . CONF . STATE . uuid // 已获取 UUID
bot . state == bot . CONF . STATE . login // 已登录
bot . state == bot . CONF . STATE . logout // 已退出登录
msg . MsgType == bot . CONF . MSGTYPE_TEXT // 文本消息
msg . MsgType == bot . CONF . MSGTYPE_IMAGE // 图片消息
msg . MsgType == bot . CONF . MSGTYPE_VOICE // 语音消息
msg . MsgType == bot . CONF . MSGTYPE_EMOTICON // 自定义表情消息
msg . MsgType == bot . CONF . MSGTYPE_MICROVIDEO // 小视频消息
msg . MsgType == bot . CONF . MSGTYPE_VIDEO // 视频消息
Current status
Current logged in user information
All contacts, including address book contacts, recent contact groups, and public accounts
The key is the contact UserName. UserName is the UUID of each contact during this login, but it will change next time you login.
value is a Contact
object. For specific attribute methods, see src/interface/contact.js
All messages received after logging in
msg is a Message
object. For specific attribute methods, see src/interface/message.js
Launch an instance, log in and stay in sync
After calling this method, process the message by listening to the event
Use the necessary information that the instance has obtained to log in again and synchronize
Stop the instance and log out
After calling this method, log out by listening to the logout
event
Customize heartbeat message content
The getter
function returns the heartbeat message content
typeof(getter())
should be "string"
bot . setRollingMessageGetter ( function ( ) {
//
return ( new Date ( ) ) . toJSON ( ) ;
} ) ;
Custom heartbeat interval
The getter
function returns the heartbeat interval in milliseconds
typeof(getter())
should be "number"
bot . setRollingIntervalGetter ( function ( ) {
return 2 * 60 * 1000 ;
} ) ;
Custom heartbeat target user
The getter
function returns UserName
of the target user (in the form of @xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
typeof(getter())
should be "string"
Note: If you want to use bot.user.UserName
, you need to define the target user after the login
event
bot . setRollingmeGetter ( function ( ) {
return bot . user . UserName ;
} ) ;
The following methods all return Promise
Send text messages, which can include emoji (?) and QQ emoticons ([bad smile])
Upload media files
return
{
name : name ,
size : size ,
ext : ext ,
mediatype : mediatype ,
mediaId : mediaId
}
Send pictures, mediaId is the mediaId returned by uploadMedia
bot . uploadMedia ( fs . createReadStream ( 'test.png' ) )
. then ( res => {
return bot . sendPic ( res . mediaId , ToUserName )
} )
. catch ( err => {
console . log ( err )
} )
Send an emoticon, but it is the MD5 of the emoticon or the mediaId returned by uploadMedia.
The MD5 of the emoticon can be calculated by yourself but may not exist in the WeChat server. It can also be obtained from the emoticon message returned by WeChat.
Send video
Send files as application cards, and you can send voices through this API
The encapsulation of the above method of sending messages is a general method of sending messages.
When msg
is string, send text message
When msg
is {file:xxx,filename:'xxx.ext'}
, send the corresponding media file
When msg
is {emoticonMd5:xxx}
, send emoticon
bot . sendMsg ( {
file : request ( 'https://raw.githubusercontent.com/nodeWechat/wechat4u/master/bot-qrcode.jpg' ) ,
filename : 'bot-qrcode.jpg'
} , ToUserName )
. catch ( err => {
console . log ( err )
} )
Forward the message, msg
msg
object passed by the message
event
Withdraw message
MsgID
is the ID representing the message returned after sending the message.
bot . sendMsg ( '测试撤回' , toUserName )
. then ( res => {
return bot . revokeMsg ( res . MsgID , toUserName )
} )
. catch ( err => {
console . log ( err )
} )
Get contacts from address book
Seq
is the seq returned after the last call to bot.getContact. It does not need to be passed in the first call.
Get specified contact data in batches
contacts
array, specifying the data to be obtained
When contacts
is [{UserName: xxx}]
, the specified contact or group information can be obtained
When contacts
is [{UserName: xxx, EncryChatRoomId: xxx}]
, detailed information of members in the specified group can be obtained, and EncryChatRoomId can be obtained from the group information
Get contact avatar
bot . getHeadImg ( bot . contacts [ UserName ] . HeadImgUrl ) . then ( res => {
fs . writeFileSync ( ` ${ UserName } .jpg` , res . data )
} ) . catch ( err => {
console . log ( err )
} )
Get a picture or emoticon
bot . getMsgImg ( msg . MsgId ) . then ( res => {
fs . writeFileSync ( ` ${ msg . MsgId } .jpg` , res . data )
} ) . catch ( err => {
console . log ( err )
} )
Get voice
Get short videos or videos
Get the file. When MsgType
of the message is 49 and AppMsgType
is 6, it is a file.
Add friends
UserName
can generally be obtained from group information
Content
verification information
Add request via friend
Create a group
Topic
group chat name
MemberList
array, UserName of at least two people besides yourself, the format is [ {"UserName":"@250d8d156ad9f8b068c2e3df3464ecf2"}, {"UserName":"@42d725733741de6ac53cbe3738d8dd2e"} ]
Update group members
ChatRoomUserName
Group UserName starting with '@@'
MemberList
array, contact UserNa
fun
optional 'addmember', 'delmember', 'invitemember'
Update group name
ChatRoomUserName
Group UserName starting with '@@'
NewName
string, new group name
Pin or unpin a contact to the top. You can obtain the group ChatRoomOwner by directly unpinning the group.
OP == 0 Unpin
OP == 1 pinned
Set contact notes or labels
After getting the uuid, you can construct a QR code or obtain the QR code from the WeChat server.
bot . on ( 'uuid' , uuid => {
qrcode . generate ( 'https://login.weixin.qq.com/l/' + uuid , {
small : true
} )
console . log ( '二维码链接:' , 'https://login.weixin.qq.com/qrcode/' + uuid )
} )
After scanning with your mobile phone, you can get the Data URL of the logged-in user's avatar.
Mobile phone confirmation login
Successfully logged out
Contact update, you can get the updated contact list
For all messages obtained through synchronization, the message type is determined by msg.MsgType
bot . on ( 'message' , msg => {
switch ( msg . MsgType ) {
case bot . CONF . MSGTYPE_STATUSNOTIFY :
break
case bot . CONF . MSGTYPE_TEXT :
break
case bot . CONF . MSGTYPE_RECALLED :
break
}
} )
Each contact inherits from interface/contact and extends the following attributes in addition to the original json:
contact . AvatarUrl // 处理过的头像地址
contact . isSelf // 是否是登录用户本人
contact . getDisplayName ( )
contact . canSearch ( keyword )
In addition, wechat4u provides Contact as a common interface for contacts on the instance, extending the following properties:
wechat . Contact . isRoomContact ( )
wechat . Contact . isSpContact ( )
wechat . Contact . isPublicContact ( )
wechat . Contact . getUserByUserName ( )
wechat . Contact . getSearchUser ( keyword )
Each msg object inherits from interface/message and has the following attributes in addition to the original json:
message . isSendBySelf // 是否是本人发送
message . isSendBy ( contact )
message . getPeerUserName ( ) // 获取所属对话的联系人 UserName
message . getDisplayTime ( ) // 获取形如 12:00 的时间戳信息
Regarding the implementation of WeChat web robots, there are already a lot of wheels. Thank you all! (The ranking is not in order. The collection must be uneven.)
Regarding the interface description of the WeChat web page, there are several articles that analyze it very well.
MIT