Example #1
0
        public static ExecuteResult Execute(CompileResult compileResult, IMessageChannel contextChannel)
        {
            var stringBuilder = new StringBuilder();
            var result        = new ExecuteResult
            {
                CompileResult = compileResult
            };
            var globals = new Globals
            {
                Console    = new StringWriter(stringBuilder),
                Random     = Random,
                ReplyAsync = async m => await contextChannel.SendMessageAsync(m)
            };

            var execSw = Stopwatch.StartNew();
            ScriptState <object> scriptState = null;
            var execCts = new CancellationTokenSource(Information.ExecutionTimeout + 100);

            try
            {
                var runThread = new Thread(async() =>
                {
                    scriptState = await compileResult.Script.RunAsync(globals, ex => true, execCts.Token);
                });
                runThread.Start();
                bool successfullyEnded = runThread.Join(Information.ExecutionTimeout);

                if (!successfullyEnded)
                {
                    throw new TaskCanceledException();
                }

                execSw.Stop();
                result.ExecuteTime = execSw.ElapsedMilliseconds;

                if (scriptState != null)
                {
                    if (scriptState.Exception != null)
                    {
                        result.ExecException = scriptState.Exception;
                    }

                    result.ReturnValue = scriptState.ReturnValue;
                }

                if (stringBuilder.Length > 0)
                {
                    result.ConsoleOutput = stringBuilder.Length > 1024
                        ? stringBuilder.ToString().Substring(0, 1019) + " [..]"
                        : stringBuilder.ToString();
                }
            } catch (TaskCanceledException)
            {
                result.ExecException = new TimeoutException(
                    $"The execution of the script took longer than expected! (> {Information.ExecutionTimeout}ms)");
            } catch (Exception ex)
            {
                result.ExecException = ex;
            }

            return(result);
        }