qq.js 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const CQWebsocket = require("cq-websocket");
  4. const log4js = require("log4js");
  5. const helper_1 = require("./helper");
  6. const logger = log4js.getLogger('cq-websocket');
  7. logger.level = 'info';
  8. class default_1 {
  9. constructor(opt) {
  10. this.retryInterval = 1000;
  11. this.initWebsocket = () => {
  12. this.bot = new CQWebsocket({
  13. access_token: this.botInfo.access_token,
  14. enableAPI: true,
  15. enableEvent: true,
  16. host: this.botInfo.host,
  17. port: this.botInfo.port,
  18. });
  19. this.bot.on('socket.connect', () => {
  20. logger.info('websocket connected');
  21. this.retryInterval = 1000;
  22. });
  23. this.bot.on('socket.close', () => {
  24. logger.error('websocket closed');
  25. this.reconnect();
  26. });
  27. this.bot.on('socket.error', () => {
  28. logger.error('websocket connect error');
  29. this.reconnect();
  30. });
  31. this.bot.on('message', (e, context) => {
  32. e.cancel();
  33. const chat = {
  34. chatType: context.message_type,
  35. chatID: 0,
  36. };
  37. switch (context.message_type) {
  38. case "private" /* Private */:
  39. chat.chatID = context.user_id;
  40. break;
  41. case "group" /* Group */:
  42. chat.chatID = context.group_id;
  43. break;
  44. case "discuss" /* Discuss */:
  45. chat.chatID = context.discuss_id;
  46. }
  47. const cmdObj = helper_1.default(context.raw_message);
  48. switch (cmdObj.cmd) {
  49. case 'twitter_sub':
  50. case 'twitter_subscribe':
  51. return this.botInfo.sub(chat, cmdObj.args);
  52. case 'twitter_unsub':
  53. case 'twitter_unsubscribe':
  54. return this.botInfo.unsub(chat, cmdObj.args);
  55. case 'ping':
  56. case 'twitter':
  57. return this.botInfo.list(chat, cmdObj.args);
  58. case 'help':
  59. return `推特搬运机器人:
  60. /twitter - 查询当前聊天中的订阅
  61. /twitter_subscribe [链接] - 订阅 Twitter 搬运
  62. /twitter_unsubscribe [链接] - 退订 Twitter 搬运`;
  63. }
  64. });
  65. };
  66. this.connect = () => {
  67. this.initWebsocket();
  68. logger.warn('connecting to websocket...');
  69. this.bot.connect();
  70. };
  71. this.reconnect = () => {
  72. this.retryInterval *= 2;
  73. if (this.retryInterval > 300000)
  74. this.retryInterval = 300000;
  75. logger.info(`retrying in ${this.retryInterval / 1000}s...`);
  76. setTimeout(() => {
  77. logger.warn('reconnecting to websocket...');
  78. this.connect();
  79. }, this.retryInterval);
  80. };
  81. logger.info(`init cqwebsocket for ${opt.host}:${opt.port}, with access_token ${opt.access_token}`);
  82. this.botInfo = opt;
  83. }
  84. }
  85. exports.default = default_1;