rpc.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. const res = await tryDo(client.bot.users.fetch(userId));
  17. if (!res.ok) {
  18. return { exists: false };
  19. }
  20. for (const [_, g] of client.bot.guilds.cache.entries()) {
  21. const res = await tryDo(g.members.fetch(userId));
  22. if (res.ok) {
  23. return { exists: true };
  24. }
  25. }
  26. return { exists: false };
  27. }
  28. };
  29. app.use(ModuleRpcProtocolServer.registerRpcRoutes(NoctBotService, handler));
  30. export function startRpcServer(): void {
  31. logger.info(`Starting RPC at *:${PORT}`);
  32. createServer(app).listen(PORT);
  33. }