手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表2020年02月25日的文章

wechaty 在 分拆的文件中使用自身变量

wechaty是目前看来最优雅的机器人库了。使用方式也很简单,官方的demo例子就几行代码,不过看到他们的hot-import-bot.js就感觉慌了。毕竟在同一个页面里,还能直接使用bot变量(例子中实例化的时候,用的是bot,const bot = new Wechaty());但分拆成单独的文件后就没有相应的用法。

看源码中是有这样的代码:

JavaScript代码
  1. public on (event: 'dong',         listener: string | ((this: Wechaty, data?: string) => void))                                                    : this  

是看到确实对每一个件事都是传入两个参数,然而demo里都是类似这样:

JavaScript代码
  1. async function onLogin (user) {  
  2.   console.log(`${user} login`)  
  3. }  

也没有看到有传入第二个变量。如果你主动 传入第二个参数,会直接报undefined。在这样分拆的页面怎么使用bot呢?

我找了一下node的全局变量,发现nodejs有一个global变量。嗯,变量名就叫:global.....,于是将除了message以外的事件放到主文件index.js中。并在onlogin中赋值:global.bot = bot;

然后在分拆后的message中,const bot = global.bot; 果然就可以用了。

问了一下群里,发现有人也这样用,但。。。Huan Li(Huan (李卓桓))说了,其实可以在方法里面直接 const wechaty = this;就可以用了。。。

这么说。。。this就可以直接用?果然不会Ts就是不懂。然后 他还更新了一下 git,并在里面加入了使用方法,详见:https://github.com/wechaty/wechaty-getting-started/blob/master/examples/professional/hot-import-bot/listeners/on-friend.js

JavaScript代码
  1. /** 
  2.  *   Wechaty - https://github.com/chatie/wechaty 
  3.  * 
  4.  *   @copyright 2016-2018 Huan LI <zixia@zixia.net> 
  5.  * 
  6.  *   Licensed under the Apache License, Version 2.0 (the "License"); 
  7.  *   you may not use this file except in compliance with the License. 
  8.  *   You may obtain a copy of the License at 
  9.  * 
  10.  *       http://www.apache.org/licenses/LICENSE-2.0 
  11.  * 
  12.  *   Unless required by applicable law or agreed to in writing, software 
  13.  *   distributed under the License is distributed on an "AS IS" BASIS, 
  14.  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  15.  *   See the License for the specific language governing permissions and 
  16.  *   limitations under the License. 
  17.  * 
  18.  */  
  19. async function onFriend (contact, request) {  
  20.   /** 
  21.    * We can get the Wechaty bot instance from this: 
  22.    *   `const wechaty = this` 
  23.    * Or use `this` directly: 
  24.    *   `console.info(this.userSelf())` 
  25.    */  
  26.   if(request){  
  27.     let name = contact.name()  
  28.     // await request.accept()  
  29.   
  30.     console.log(`Contact: ${name} send request ${request.hello()}`)  
  31.   }  
  32. }  
  33.   
  34. module.exports = onFriend  
看到 if(request) 上的注释了么。。。就是这样简单。

最后想说的是,感觉

  1. public on (event: 'dong',         listener: string | ((this: Wechaty, data?: string) => void))                                                    : this  

这个this的用法就象python的self一样。虽然不懂,但是感觉很厉害的样子。

最近在尝试使用他做了个小机器人,就是当群里有人问天气的时候自动回复了一下。。。目前只是demo。没有细纠,但这时候发现 Room.alias(Contact)。没有拿到群昵称,准备这两天再看看问题是啥。