main.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 } from './command';
  7. import { getLogger, setLogLevels } from './loggers';
  8. import QQBot from './mirai';
  9. import Worker from './twitter';
  10. const logger = getLogger();
  11. const sections: commandLineUsage.Section[] = [
  12. {
  13. header: 'MiraiTS Twitter Bot',
  14. content: 'The QQ Bot that forwards twitters.',
  15. },
  16. {
  17. header: 'Synopsis',
  18. content: [
  19. '$ mirai-twitter-bot {underline config.json}',
  20. '$ mirai-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. ];
  50. const warningFields = [
  51. 'mirai_http_host', 'mirai_http_port', 'mirai_access_token',
  52. ];
  53. const optionalFields = [
  54. 'lockfile', 'work_interval', 'webshot_delay', 'loglevel', 'mode', 'resume_on_start',
  55. ].concat(warningFields);
  56. if (requiredFields.some((value) => config[value] === undefined)) {
  57. console.log(`${requiredFields.join(', ')} are required`);
  58. process.exit(1);
  59. }
  60. optionalFields.forEach(key => {
  61. if (config[key] === undefined || typeof(config[key]) !== typeof (exampleConfig[key])) {
  62. if (key in warningFields) logger.warn(`${key} is undefined, use ${exampleConfig[key] || 'empty string'} as default`);
  63. config[key] = exampleConfig[key as keyof Config];
  64. }
  65. });
  66. setLogLevels(config.loglevel);
  67. let lock: ILock;
  68. if (fs.existsSync(path.resolve(config.lockfile))) {
  69. try {
  70. lock = JSON.parse(fs.readFileSync(path.resolve(config.lockfile), 'utf8')) as ILock;
  71. } catch (err) {
  72. logger.error(`Failed to parse lockfile ${config.lockfile}: `, err);
  73. lock = {
  74. workon: 0,
  75. feed: [],
  76. threads: {},
  77. };
  78. }
  79. fs.access(path.resolve(config.lockfile), fs.constants.W_OK, err => {
  80. if (err) {
  81. logger.fatal(`cannot write lockfile ${path.resolve(config.lockfile)}, permission denied`);
  82. process.exit(1);
  83. }
  84. });
  85. } else {
  86. lock = {
  87. workon: 0,
  88. feed: [],
  89. threads: {},
  90. };
  91. try {
  92. fs.writeFileSync(path.resolve(config.lockfile), JSON.stringify(lock));
  93. } catch (err) {
  94. logger.fatal(`cannot write lockfile ${path.resolve(config.lockfile)}, permission denied`);
  95. process.exit(1);
  96. }
  97. }
  98. if (!config.resume_on_start) {
  99. Object.keys(lock.threads).forEach(key => {
  100. lock.threads[key].offset = '-1';
  101. });
  102. }
  103. const qq = new QQBot({
  104. access_token: config.mirai_access_token,
  105. host: config.mirai_http_host,
  106. port: config.mirai_http_port,
  107. bot_id: config.mirai_bot_qq,
  108. list: (c, a, cb) => list(c, a, cb, lock),
  109. sub: (c, a, cb) => sub(c, a, cb, lock, config.lockfile),
  110. unsub: (c, a, cb) => unsub(c, a, cb, lock, config.lockfile),
  111. });
  112. const worker = new Worker({
  113. consumerKey: config.twitter_consumer_key,
  114. consumerSecret: config.twitter_consumer_secret,
  115. accessTokenKey: config.twitter_access_token_key,
  116. accessTokenSecret: config.twitter_access_token_secret,
  117. privateAuthToken: config.twitter_private_auth_token,
  118. privateCsrfToken: config.twitter_private_csrf_token,
  119. lock,
  120. lockfile: config.lockfile,
  121. workInterval: config.work_interval,
  122. bot: qq,
  123. webshotDelay: config.webshot_delay,
  124. mode: config.mode,
  125. wsUrl: config.playwright_ws_spec_endpoint,
  126. });
  127. worker.launch();
  128. qq.connect();