rpc.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import express from "express";
  2. import { createServer } from "http";
  3. import { ModuleRpcServer } from "rpc_ts/lib/server";
  4. import { ModuleRpcProtocolServer } from "rpc_ts/lib/protocol/server";
  5. import { NoctBotService } from "@shared/rpc/backend";
  6. import { logger } from "./logging";
  7. import { client } from "./client";
  8. import { tryDo } from "@shared/common/async_utils";
  9. const PORT = +(process.env.RPC_PORT ?? "8181");
  10. const app = express();
  11. const handler: ModuleRpcServer.ServiceHandlerFor<typeof NoctBotService> = {
  12. async getPing({ ping }): Promise<{ text: string }> {
  13. return { text: `pong: ${ping}` };
  14. },
  15. async userInServer({ userId }): Promise<{ exists: boolean }> {
  16. for (const g of client.bot.guilds.cache.values()) {
  17. const res = await tryDo(g.members.fetch(userId));
  18. if (res.ok) {
  19. return { exists: true };
  20. }
  21. }
  22. return { exists: false };
  23. }
  24. };
  25. app.use(ModuleRpcProtocolServer.registerRpcRoutes(NoctBotService, handler));
  26. export function startRpcServer(): void {
  27. logger.info(`Starting RPC at *:${PORT}`);
  28. createServer(app).listen(PORT);
  29. }