tgbot_api.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import BaseService from '../../base';
  2. import TelegramBot = require('node-telegram-bot-api');
  3. import TgGroupType from './tggrouptype';
  4. /**
  5. * tg机器人 api 服务 只有一个进程可以用
  6. */
  7. const botListMap = new Map<number, TelegramBot>();
  8. export default class TgbotApiService extends BaseService {
  9. /**
  10. * 机器人进程初始化
  11. */
  12. async initTgbot() {
  13. await this.initTgBotList();
  14. return true;
  15. }
  16. /**
  17. * 进程通讯
  18. * @param cmd
  19. * @param data
  20. */
  21. async handleReq(cmd:string, data:any) {
  22. switch (cmd) {
  23. case 'addTgBot':
  24. await this.addTgBot(data);
  25. break;
  26. case 'removeTgBot':
  27. await this.removeTgBot(data);
  28. break;
  29. case 'sendMessage':
  30. await this.sendMessage(data);
  31. break;
  32. default:
  33. break;
  34. }
  35. return true;
  36. }
  37. /**
  38. * 初始化机器人监听
  39. */
  40. async initTgBotList() {
  41. const list = await this.getRepo().admin.tg.TgBot.find({ status: 1 });
  42. list.forEach(tgbot => {
  43. this.addTgBot(tgbot.botId, tgbot);
  44. });
  45. }
  46. /**
  47. * 添加机器人监听
  48. * @param botId
  49. * @param botInfo
  50. */
  51. async addTgBot(botId:number, botInfo:any = null) {
  52. if (botListMap.has(botId)) {
  53. return false;
  54. }
  55. if (botInfo == null) {
  56. botInfo = await this.getRepo().admin.tg.TgBot.findOne({ botId });
  57. }
  58. if (botInfo == null || botInfo.status === 0) return false;
  59. const bot = new TelegramBot(botInfo.token, { polling: true });
  60. botListMap.set(botId, bot);
  61. bot.on('message', msg => {
  62. this.onReciveMessage(botId, msg);
  63. });
  64. return true;
  65. }
  66. /**
  67. * 移除机器人监听
  68. * @param botId
  69. */
  70. async removeTgBot(botId:number) {
  71. if (!botListMap.has(botId)) {
  72. return false;
  73. }
  74. const bot = botListMap.get(botId);
  75. await bot.stopPolling();
  76. botListMap.delete(botId);
  77. return true;
  78. }
  79. /**
  80. * 解析msg
  81. * @param botId
  82. * @param msg
  83. */
  84. // {"message_id":83,"from":{"id":5034446407,"is_bot":false,"first_name":"xdh","username":"hdx234","language_code":"zh-hans"},"chat":{"id":-4870165498,"title":"z & xdh","type":"group","all_members_are_administrators":true,"accepted_gift_types":{"unlimited_gifts":false,"limited_gifts":false,"unique_gifts":false,"premium_subscription":false}},"date":1752997603,"text":"123452"}
  85. // {"message_id":85,"from":{"id":5034446407,"is_bot":false,"first_name":"xdh","username":"hdx234","language_code":"zh-hans"},"chat":{"id":5034446407,"first_name":"xdh","username":"hdx234","type":"private"},"date":1753021095,"text":"11111"}
  86. parseMessage(msg:any) {
  87. if (msg == null) return null;
  88. const { message_id, from, chat, date, text } = msg;
  89. return {
  90. messageId: message_id,
  91. chatId: chat?.id,
  92. chatType: chat?.type,
  93. chatTitle: chat?.title,
  94. chatName: chat?.first_name,
  95. chatUsername: chat?.username,
  96. fromUserId: from?.id,
  97. fromName: from?.first_name,
  98. fromUsername: from?.username,
  99. isBot: from && from.is_bot ? 1 : 0,
  100. sentTime: date,
  101. text,
  102. };
  103. }
  104. async recordMessage(botId:number, message:any) {
  105. try {
  106. const data = Object.assign({}, message, { botId });
  107. await this.getRepo().admin.tg.TgMessage.save(data);
  108. } catch (error) {
  109. console.error(error);
  110. }
  111. }
  112. async recordSendMessage(groupId:any, botId:any, text:any) {
  113. try {
  114. await this.getRepo().admin.tg.TgBotSendLog.save({ groupId, botId, text });
  115. } catch (error) {
  116. console.error(error);
  117. }
  118. }
  119. /**
  120. * 监听消息处理
  121. * @param botId
  122. * @param msg
  123. */
  124. async onReciveMessage(botId:number, msg:any) {
  125. const message = this.parseMessage(msg);
  126. const group = await this.getRepo().admin.tg.TgGroup.findOne({ groupId: message?.chatId });
  127. const groupType = group ? group.type : TgGroupType.LISTEN_ONLY;
  128. // 是否记录
  129. if (groupType === TgGroupType.LISTEN_ONLY || groupType === TgGroupType.BOTH) {
  130. await this.recordMessage(botId, message);
  131. await this.service.admin.tg.tgmsghandler.handleMessage(group, message);
  132. }
  133. }
  134. async sendMessage(message:any[]) {
  135. if (message == null) return false;
  136. try {
  137. for (const value of message) {
  138. const { groupId, botId, text } = value;
  139. if (botListMap.has(botId)) {
  140. const bot = botListMap.get(botId);
  141. bot.sendMessage(groupId, text);
  142. await this.recordSendMessage(groupId, botId, text);
  143. }
  144. }
  145. } catch (error) {
  146. console.error(error);
  147. return false;
  148. }
  149. return true;
  150. }
  151. }