Skip to content

Throttled Rate for WeChat Web API

Huan LI edited this page Jun 19, 2017 · 3 revisions

Say Event

As of 2017-01-29, according to @xinbenlv's measurement, when doing await Sayable.say(), there is an approximately 120 messages limit per 50 seconds, or more conservatively 1min. Other events, such as Contact.add() or Contact.del() might also have similar throttled rate too.

Here is the code to verify the limit

import {Wechaty, Contact} from "wechaty";

console.log(`--- WeChat Bulk Msg Starts! ---`);

const bot = Wechaty.instance();
bot
    .on('scan', async (url, code) => {
      let loginUrl = url.replace('qrcode', 'l');
      require('qrcode-terminal').generate(loginUrl);
    })
    .on('login', async (user:Contact) => {
      console.log(`Logined: User = ${JSON.stringify(user)}`);
      let start:Date = new Date();
      let counter = 0;
      while(true) {
        let now = new Date();
        counter ++;
        try {
          let msg = `${(now.getUTCSeconds() - start.getUTCSeconds())} ` + 
              `seconds since start, msg #${counter}`;
          await user.say(msg);
          console.log(msg);
        } catch (e){
          console.log('XXX say failure');
          console.warn(e);
        }
        if (counter % 120 == 0) {
          for (let i = 0; i < 49; i++) {
            console.log(`Wait for count down ${60 - i}`);
            await sleep(1000);
          }
        }
      }
    })

    .on('logout', async user => {
    })
    .init();

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

References

RxSJ

Consider using RxJS to implement a throttled module:

var source = Rx.Observable
  .range(0, 3)
  .delay(function (x) { return Rx.Observable.timer(x * 400); })
  .timeInterval()
  .map(function (x) { return x.value + ':' + x.interval; });

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 0:0
// => Next: 1:400
// => Next: 2:400
// => Completed