y21

embedding js implementation

y21
Jul 6th, 2021
850
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // dash.ts: https://github.com/y21/dash/blob/master/wasm/frontend/dash.ts
  2. import { Engine } from './dash';
  3.  
  4. const commands = new discord.command.CommandGroup({
  5.   defaultPrefix: '..'
  6. });
  7.  
  8. function removeCodeblock(code: string): string {
  9.   return code.replace(/^```\w*|```$/g, '');
  10. }
  11.  
  12. function codeblock(language: string, code: string) {
  13.   return '```' + language + '\n' + code.substr(0, 1900) + '\n```';
  14. }
  15.  
  16. const engine = new Engine();
  17. const WASM_URL = 'http://dash.y21_.repl.co/wasm/v3';
  18.  
  19. discord.on(discord.Event.MESSAGE_CREATE, async (message) => {
  20.   // initialize js engine if it's not yet ready
  21.   if (!engine.initialized) {
  22.     await engine.init(WASM_URL);
  23.   }
  24. });
  25.  
  26. async function handleEval(
  27.   message: discord.GuildMemberMessage,
  28.   { code }: { code: string }
  29. ) {
  30.   code = removeCodeblock(code);
  31.   let result;
  32.  
  33.   let before = await pylon.getCpuTime();
  34.   try {
  35.     result = engine.eval(code);
  36.   } catch (e) {
  37.     result = e.message;
  38.   }
  39.   let now = await pylon.getCpuTime();
  40.  
  41.   message.reply({
  42.     content: (now - before).toFixed(2) + ' ms' + codeblock('js', result),
  43.     allowedMentions: {}
  44.   });
  45. }
  46.  
  47. const dashGroup = commands.subcommandGroup({
  48.   name: 'eval2'
  49. });
  50.  
  51. dashGroup.default(
  52.   (args) => ({
  53.     code: args.text()
  54.   }),
  55.   handleEval
  56. );
  57.  
  58. dashGroup.on(
  59.   'run',
  60.   (args) => ({
  61.     code: args.text()
  62.   }),
  63.   handleEval
  64. );
  65.  
RAW Paste Data