main.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // We need some kind of module resolver for @shared/db. We use module-alias.
  2. require("module-alias/register");
  3. import "./environment";
  4. import * as path from "path";
  5. import { client } from "./client";
  6. import { createConnection, getConnectionOptions } from "typeorm";
  7. import { DB_ENTITIES } from "@shared/db/entities";
  8. import { assertOk } from "@shared/common/async_utils";
  9. import { eventLogger, logger } from "./logging";
  10. import { PluginManager } from "./plugin_manager";
  11. import { startRpcServer } from "./rpc";
  12. export const plgMgr: PluginManager = new PluginManager(path.resolve(path.dirname(module.filename), "plugins"));
  13. export const COMMAND_PREFIX = "/";
  14. client.bot.on("ready", async () => {
  15. logger.info("Starting up NoctBot");
  16. eventLogger.info("Started");
  17. await client.botUser.setActivity(`@${client.botUser.username} help`, { type: "PLAYING" });
  18. await assertOk(plgMgr.start(client.bot));
  19. logger.info("NoctBot is ready");
  20. });
  21. client.bot.on("message", async m => {
  22. if (m.author.id == client.botUser.id)
  23. return;
  24. if (m.channel.type != "text") {
  25. logger.warn("User %s (%s#%s) tried to execute command in DMs. Message: %s.", m.author.id, m.author.username, m.author.discriminator, m.content);
  26. await m.reply("DM commands are disabled, sorry!");
  27. return;
  28. }
  29. if (m.content.startsWith(COMMAND_PREFIX) && await plgMgr.runCommand("prefix", m, m.content.substring(COMMAND_PREFIX.length))) {
  30. return;
  31. }
  32. let content = m.cleanContent.trim();
  33. if (await plgMgr.trigger("message", m, content))
  34. return;
  35. if (m.mentions.users.size > 0 && m.mentions.users.has(client.botUser.id)) {
  36. const trimmedContent = m.content.trim();
  37. if (trimmedContent.startsWith(client.nameMention) || trimmedContent.startsWith(client.usernameMention)) {
  38. content = content.substring(client.cleanMention.length).trim();
  39. const lowerCaseContent = content.toLowerCase();
  40. if (await plgMgr.runCommand("mention", m, content))
  41. return;
  42. if (await plgMgr.trigger("directMention", m, lowerCaseContent))
  43. return;
  44. }
  45. if (await plgMgr.trigger("indirectMention", m))
  46. return;
  47. }
  48. await plgMgr.trigger("postMessage", m);
  49. });
  50. async function main() {
  51. await createConnection({
  52. ...await getConnectionOptions(),
  53. entities: DB_ENTITIES
  54. });
  55. startRpcServer();
  56. client.bot.login(process.env.BOT_TOKEN);
  57. }
  58. main();