Baphomet is the dedicated bot for nulloctet matrix
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

137 lines
4.7 KiB

  1. let sdk = require('matrix-js-sdk');
  2. let message = require('./message');
  3. let utility = require('./utility');
  4. let { logger } = require('./logging');
  5. class Bot {
  6. constructor(config, buildInfo) {
  7. this.config = config;
  8. this.buildInfo = buildInfo;
  9. this.connected = false;
  10. }
  11. /**
  12. * Initialize the bot connection
  13. */
  14. init(messageCallback) {
  15. logger.info("Creating Matrix Client")
  16. this.client = sdk.createClient({
  17. baseUrl: this.config.baseUrl,
  18. userId: this.config.userId
  19. });
  20. this.client.on("sync", async (state, previousState, data) => {
  21. switch (state) {
  22. case "PREPARED":
  23. this.connected = true;
  24. await this.sendStatusStartup();
  25. this.client.getJoinedRooms()
  26. .done((rooms) => {
  27. logger.info("Connected to: %o", rooms)
  28. });
  29. break;
  30. case "SYNCING":
  31. logger.debug("Syncing")
  32. break;
  33. case "RECONNECTING":
  34. logger.debug("Reconnecting");
  35. break;
  36. default:
  37. logger.error("Unexpected sync state: %s", state);
  38. process.exit(1);
  39. }
  40. });
  41. this.client.on("RoomMember.membership", (event, member) => {
  42. if (member.membership === "invite"
  43. && this.config.admin.indexOf(ember.userId) >= 0) {
  44. this.client.joinRoom(member.roomId).done(() => {
  45. logger.info("Auto-joined %s", member.roomId);
  46. });
  47. }
  48. });
  49. this.client.on("Room.timeline", messageCallback);
  50. return this;
  51. }
  52. async connect() {
  53. // logger.info("Initializing Crypto");
  54. // await bot.client.initCrypto();
  55. let botClient = this.client;
  56. let botConfig = this.config;
  57. let startServerConnection = async () => {
  58. logger.info("Starting Matrix SDK Client");
  59. await this.client.startClient();
  60. }
  61. let connectWithPassword = (err, data) => {
  62. if (err === null) {
  63. logger.info("Successfully authenticated with password %o", data);
  64. startServerConnection();
  65. } else {
  66. logger.error("Failed to authenticate with password %o", err);
  67. }
  68. }
  69. let connectWithToken = (err, data) => {
  70. if (err === null) {
  71. logger.info("Successfully authenticated with access token %o", data);
  72. startServerConnection();
  73. } else {
  74. logger.error("Failed to authenticate with access token %o", err);
  75. if (typeof botConfig.userPassword !== 'undefined') {
  76. botClient.loginWithPassword(botConfig.userId, botConfig.userPassword, connectWithPassword);
  77. } else {
  78. logger.error("No fallback password provided!");
  79. }
  80. }
  81. }
  82. logger.info("Authenticating With Server");
  83. botClient.loginWithToken(this.config.accessToken, connectWithToken);
  84. }
  85. sendStatusStartup() {
  86. let promises = [Promise.resolve(true)]
  87. if (this.connected) {
  88. this.config.statusRooms.forEach(roomId => {
  89. logger.debug("Notifying %s of startup", roomId);
  90. promises.push(this.client.sendMessage(
  91. roomId, message.createBasic("Started with version: " + this.buildInfo, message.types.NOTICE)
  92. ).then(() => {
  93. logger.debug("Notified %s of startup", roomId);
  94. }));
  95. });
  96. } else {
  97. logger.warn("Attempting to send startup message while disconnected");
  98. }
  99. return Promise.all(promises);
  100. }
  101. sendStatusShutdown() {
  102. let promises = [Promise.resolve(true)]
  103. if (this.connected) {
  104. this.config.statusRooms.forEach(roomId => {
  105. logger.debug("Notifying %s of shutdown", roomId);
  106. promises.push(this.client.sendMessage(
  107. roomId, message.createBasic("Shutting down", message.types.NOTICE)
  108. ).then(() => {
  109. logger.debug("Notified %s of shutdown", roomId);
  110. }));
  111. });
  112. } else {
  113. logger.warn("Attempting to send shutdown message while disconnected");
  114. }
  115. return Promise.all(promises);
  116. }
  117. }
  118. function create(config) {
  119. let buildInfo = utility.getBuildInfo();
  120. logger.info("Running version: %s", buildInfo);
  121. return new Bot(config, buildInfo);
  122. }
  123. exports.create = create;