main.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #!/usr/bin/env node
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as commandLineUsage from 'command-line-usage';
  5. import * as exampleConfig from '../config.example.json';
  6. import { list, sub, unsub, unsubAll } from './command';
  7. import { getLogger, setLogLevels } from './loggers';
  8. import QQBot from './koishi';
  9. import Worker from './twitter';
  10. const logger = getLogger();
  11. const sections: commandLineUsage.Section[] = [
  12. {
  13. header: 'GoCQHTTP Twitter Bot',
  14. content: 'The QQ Bot that forwards twitters.',
  15. },
  16. {
  17. header: 'Synopsis',
  18. content: [
  19. '$ twitter-bot {underline config.json}',
  20. '$ twitter-bot {bold --help}',
  21. ],
  22. },
  23. {
  24. header: 'Documentation',
  25. content: [
  26. 'Project home: {underline https://github.com/CL-Jeremy/mirai-twitter-bot}',
  27. 'Example config: {underline https://git.io/JJ0jN}',
  28. ],
  29. },
  30. ];
  31. const usage = commandLineUsage(sections);
  32. const args = process.argv.slice(2);
  33. if (args.length === 0 || args[0] === 'help' || args[0] === '-h' || args[0] === '--help') {
  34. console.log(usage);
  35. process.exit(0);
  36. }
  37. const configPath = args[0];
  38. type Config = typeof exampleConfig;
  39. let config: Config;
  40. try {
  41. config = JSON.parse(fs.readFileSync(path.resolve(configPath), 'utf8')) as Config;
  42. } catch (e) {
  43. console.log('Failed to parse config file: ', configPath);
  44. console.log(usage);
  45. process.exit(1);
  46. }
  47. const requiredFields = [
  48. 'twitter_consumer_key', 'twitter_consumer_secret', 'twitter_access_token_key', 'twitter_access_token_secret',
  49. 'cq_bot_qq', ...(config.mode || exampleConfig.mode) === 0 ? ['playwright_ws_spec_endpoint'] : [],
  50. ];
  51. const warningFields = [
  52. 'cq_ws_host', 'cq_ws_port', 'cq_access_token',
  53. ...(config.redis ?? exampleConfig.redis) ? ['redis_host', 'redis_port', 'redis_expire_time'] : [],
  54. ];
  55. const optionalFields = [
  56. 'lockfile', 'work_interval', 'webshot_delay', 'loglevel', 'mode', 'resume_on_start', 'redis',
  57. ].concat(warningFields);
  58. if (requiredFields.some((value) => config[value] === undefined)) {
  59. console.log(`${requiredFields.join(', ')} are required`);
  60. process.exit(1);
  61. }
  62. optionalFields.forEach(key => {
  63. if (config[key] === undefined || typeof(config[key]) !== typeof (exampleConfig[key])) {
  64. if (warningFields.includes(key)) logger.warn(`${key} is undefined, use ${exampleConfig[key] || 'empty string'} as default`);
  65. config[key] = exampleConfig[key as keyof Config];
  66. }
  67. });
  68. setLogLevels(config.loglevel);
  69. let lock: ILock;
  70. if (fs.existsSync(path.resolve(config.lockfile))) {
  71. try {
  72. lock = JSON.parse(fs.readFileSync(path.resolve(config.lockfile), 'utf8')) as ILock;
  73. } catch (err) {
  74. logger.error(`Failed to parse lockfile ${config.lockfile}: `, err);
  75. lock = {
  76. workon: 0,
  77. feed: [],
  78. threads: {},
  79. };
  80. }
  81. fs.access(path.resolve(config.lockfile), fs.constants.W_OK, err => {
  82. if (err) {
  83. logger.fatal(`cannot write lockfile ${path.resolve(config.lockfile)}, permission denied`);
  84. process.exit(1);
  85. }
  86. });
  87. } else {
  88. lock = {
  89. workon: 0,
  90. feed: [],
  91. threads: {},
  92. };
  93. try {
  94. fs.writeFileSync(path.resolve(config.lockfile), JSON.stringify(lock));
  95. } catch (err) {
  96. logger.fatal(`cannot write lockfile ${path.resolve(config.lockfile)}, permission denied`);
  97. process.exit(1);
  98. }
  99. }
  100. if (!config.resume_on_start) {
  101. Object.keys(lock.threads).forEach(key => {
  102. lock.threads[key].offset = '-1';
  103. });
  104. }
  105. const qq = new QQBot({
  106. access_token: config.cq_access_token,
  107. host: config.cq_ws_host,
  108. port: config.cq_ws_port,
  109. bot_id: config.cq_bot_qq,
  110. list: (c, a, cb) => list(c, a, cb, lock),
  111. sub: (c, a, cb) => sub(c, a, cb, lock, config.lockfile),
  112. unsub: (c, a, cb) => unsub(c, a, cb, lock, config.lockfile),
  113. unsubAll: (c, a, cb) => unsubAll(c, a, cb, lock, config.lockfile),
  114. });
  115. const worker = new Worker({
  116. consumerKey: config.twitter_consumer_key,
  117. consumerSecret: config.twitter_consumer_secret,
  118. accessTokenKey: config.twitter_access_token_key,
  119. accessTokenSecret: config.twitter_access_token_secret,
  120. lock,
  121. lockfile: config.lockfile,
  122. workInterval: config.work_interval,
  123. bot: qq,
  124. webshotDelay: config.webshot_delay,
  125. mode: config.mode,
  126. wsUrl: config.playwright_ws_spec_endpoint,
  127. redis: !config.redis ? undefined : {
  128. redisHost: config.redis_host,
  129. redisPort: config.redis_port,
  130. redisExpireTime: config.redis_expire_time,
  131. },
  132. });
  133. worker.launch();
  134. qq.connect();