/// <summary> /// Uploads a given piece of code to the service, and returns the URL to the post. /// </summary> /// <param name="code">The code to post</param> /// <returns>The URL to the newly created post</returns> public async Task <string> UploadCodeAsync(string code, string language = null) { var usingFallback = false; var content = FormatUtilities.BuildContent(code); HttpResponseMessage response; try { response = await _client.PostAsync($"{ApiReferenceUrl}documents", content); } catch (TaskCanceledException) { usingFallback = true; response = await _client.PostAsync($"{FallbackApiReferenceUrl}documents", content); } if (!response.IsSuccessStatusCode) { var body = await response.Content?.ReadAsStringAsync(); throw new Exception($"{response.StatusCode} returned when calling {response.RequestMessage.RequestUri}. Response body: {body}"); } var urlResponse = await response.Content.ReadAsStringAsync(); var pasteKey = JObject.Parse(urlResponse)["key"].Value <string>(); var domain = usingFallback ? FallbackApiReferenceUrl : ApiReferenceUrl; return($"{domain}{pasteKey}.{language ?? (FormatUtilities.GetCodeLanguage(code) ?? "cs")}"); }
/// <summary> /// Uploads a given piece of code to the service, and returns the URL to the post. /// </summary> /// <param name="code">The code to post</param> /// <returns>The URL to the newly created post</returns> public async Task <string> UploadCode(string code, string language = null) { var usingFallback = false; var content = FormatUtilities.BuildContent(code); HttpResponseMessage response; try { response = await client.PostAsync($"{_ApiReferenceUrl}documents", content); } catch (TaskCanceledException) { usingFallback = true; response = await client.PostAsync($"{_FallbackApiReferenceUrl}documents", content); } if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while posting code to Hastebin."); } var urlResponse = await response.Content.ReadAsStringAsync(); var pasteKey = JObject.Parse(urlResponse)["key"].Value <string>(); var domain = usingFallback ? _FallbackApiReferenceUrl : _ApiReferenceUrl; return($"{domain}{pasteKey}.{language ?? (FormatUtilities.GetCodeLanguage(code) ?? "cs")}"); }
/// <summary> /// Uploads a given piece of code to the service, and returns the URL to the post. /// </summary> /// <param name="code">The code to post</param> /// <returns>The URL to the newly created post</returns> public async Task <string> UploadCode(string code, string language = null) { var response = await client.PostAsync($"{_ApiReferenceUrl}documents", FormatUtilities.BuildContent(code)); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while posting code to Hastebin."); } var urlResponse = await response.Content.ReadAsStringAsync(); var pasteKey = JObject.Parse(urlResponse)["key"].Value <string>(); return($"{_ApiReferenceUrl}{pasteKey}.{language ?? (FormatUtilities.GetCodeLanguage(code) ?? "cs")}"); }
/// <summary> /// Uploads a given piece of code to the service, and returns the URL to the post. /// </summary> /// <param name="code">The code to post</param> /// <returns>The URL to the newly created post</returns> public async Task <string> UploadCodeAsync(string code) { var content = FormatUtilities.BuildContent(code); var client = _httpClientFactory.CreateClient(HttpClientNames.TimeoutFiveSeconds); var response = await client.PostAsync($"{ApiReferenceUrl}documents", content); if (!response.IsSuccessStatusCode) { var body = await response.Content?.ReadAsStringAsync(); throw new Exception($"{response.StatusCode} returned when calling {response.RequestMessage?.RequestUri}. Response body: {body}"); } var urlResponse = await response.Content.ReadAsStringAsync(); var pasteKey = JObject.Parse(urlResponse)["key"]?.Value <string>(); return($"{ApiReferenceUrl}{pasteKey}"); }
public async Task ReplInvokeAsync( [Remainder] [Summary("The code to decompile.")] string code) { if (!(Context.Channel is IGuildChannel)) { await ReplyAsync("il can only be executed in public guild channels."); return; } code = FormatUtilities.StripFormatting(code); if (code.Length > 1000) { await ReplyAsync("Decompile Failed: Code is greater than 1000 characters in length"); return; } var guildUser = Context.User as IGuildUser; var message = await Context.Channel.SendMessageAsync("Working..."); var content = FormatUtilities.BuildContent(code); HttpResponseMessage res; try { var client = _httpClientFactory.CreateClient(); using (var tokenSrc = new CancellationTokenSource(30000)) { res = await client.PostAsync(_ilUrl, content, tokenSrc.Token); } } catch (TaskCanceledException) { await message.ModifyAsync(a => { a.Content = $"Gave up waiting for a response from the Decompile service."; }); return; } catch (Exception ex) { await message.ModifyAsync(a => { a.Content = $"Decompile failed: {ex.Message}"; }); Log.Error(ex, "Decompile Failed"); return; } if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest) { await message.ModifyAsync(a => { a.Content = $"Decompile failed: {res.StatusCode}"; }); return; } var parsedResult = await res.Content.ReadAsStringAsync(); var embed = await BuildEmbedAsync(guildUser, code, parsedResult); await _autoRemoveMessageService.RegisterRemovableMessageAsync(Context.User, embed, async (e) => { await message.ModifyAsync(a => { a.Content = string.Empty; a.Embed = e.Build(); }); return(message); }); await Context.Message.DeleteAsync(); }
public async Task ReplInvokeAsync( [Remainder] [Summary("The code to execute.")] string code) { if (!(Context.Channel is IGuildChannel) || !(Context.User is IGuildUser guildUser)) { await ModifyOrSendErrorEmbed("The REPL can only be executed in public guild channels."); return; } var message = await Context.Channel .SendMessageAsync(embed : new EmbedBuilder() .WithTitle("REPL Executing") .WithUserAsAuthor(Context.User) .WithColor(Color.LightOrange) .WithDescription($"Compiling and Executing [your code]({Context.Message.GetJumpUrl()})...") .Build()); var content = FormatUtilities.BuildContent(code); // make it easier to trace calls back to discord if moderation or investigation needs to happen content.Headers.TryAddWithoutValidation("X-Modix-DiscordUserId", Context.User.Id.ToString()); content.Headers.TryAddWithoutValidation("X-Modix-DiscordUsername", Context.User.GetFullUsername()); var messageLink = $"https://discord.com/channels/{Context.Guild.Id}/{Context.Channel.Id}/{message.Id}"; content.Headers.TryAddWithoutValidation("X-Modix-MessageLink", messageLink); HttpResponseMessage res; try { var client = _httpClientFactory.CreateClient(HttpClientNames.RetryOnTransientErrorPolicy); res = await client.PostAsync(_replUrl, content); } catch (IOException ex) { await ModifyOrSendErrorEmbed("Recieved an invalid response from the REPL service." + $"\n\n{Format.Bold("Details:")}\n{ex.Message}", message); return; } catch (Exception ex) { await ModifyOrSendErrorEmbed("An error occurred while sending a request to the REPL service. " + "This may be due to a StackOverflowException or exceeding the 30 second timeout." + $"\n\n{Format.Bold("Details:")}\n{ex.Message}", message); return; } if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest) { await ModifyOrSendErrorEmbed($"Status Code: {(int)res.StatusCode} {res.StatusCode}", message); return; } var parsedResult = JsonConvert.DeserializeObject <Result>(await res.Content.ReadAsStringAsync()); var embed = await BuildEmbedAsync(guildUser, parsedResult); await _autoRemoveMessageService.RegisterRemovableMessageAsync(Context.User, embed, async (e) => { await message.ModifyAsync(a => { a.Content = string.Empty; a.Embed = e.Build(); }); return(message); }); await Context.Message.DeleteAsync(); }
public async Task ReplInvoke([Remainder] string code) { if (!(Context.Channel is SocketGuildChannel)) { await ReplyAsync("exec can only be executed in public guild channels."); return; } if (code.Length > 1000) { await ReplyAsync("Exec failed: Code is greater than 1000 characters in length"); return; } var guildUser = Context.User as SocketGuildUser; var message = await Context.Channel.SendMessageAsync("Working..."); var content = FormatUtilities.BuildContent(code); HttpResponseMessage res; try { var tokenSrc = new CancellationTokenSource(30000); res = await _client.PostAsync(ReplRemoteUrl, content, tokenSrc.Token); } catch (TaskCanceledException) { await message.ModifyAsync(a => { a.Content = $"Gave up waiting for a response from the REPL service."; }); return; } catch (Exception ex) { await message.ModifyAsync(a => { a.Content = $"Exec failed: {ex.Message}"; }); Log.Error(ex, "Exec Failed"); return; } if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest) { await message.ModifyAsync(a => { a.Content = $"Exec failed: {res.StatusCode}"; }); return; } var parsedResult = JsonConvert.DeserializeObject <Result>(await res.Content.ReadAsStringAsync()); var embed = await BuildEmbed(guildUser, parsedResult); await message.ModifyAsync(a => { a.Content = string.Empty; a.Embed = embed.Build(); }); await Context.Message.DeleteAsync(); }
public async Task ReplInvokeAsync( [Remainder] [Summary("The code to execute.")] string code) { if (!(Context.Channel is IGuildChannel) || !(Context.User is IGuildUser guildUser)) { await ModifyOrSendErrorEmbed("The REPL can only be executed in public guild channels."); return; } var message = await Context.Channel .SendMessageAsync(embed : new EmbedBuilder() .WithTitle("REPL Executing") .WithUserAsAuthor(Context.User) .WithColor(Color.LightOrange) .WithDescription($"Compiling and Executing [your code]({Context.Message.GetJumpUrl()})...") .Build()); var content = FormatUtilities.BuildContent(code); HttpResponseMessage res; try { var client = _httpClientFactory.CreateClient(); res = await client.PostAsync(_replUrl, content); } catch (IOException ex) { await ModifyOrSendErrorEmbed("Recieved an invalid response from the REPL service." + $"\n\n{Format.Bold("Details:")}\n{ex.Message}", message); return; } catch (Exception ex) { await ModifyOrSendErrorEmbed("An error occurred while sending a request to the REPL service. " + "This is probably due to container exhaustion - try again later." + $"\n\n{Format.Bold("Details:")}\n{ex.Message}", message); return; } if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest) { await ModifyOrSendErrorEmbed($"Status Code: {(int)res.StatusCode} {res.StatusCode}", message); return; } var parsedResult = JsonConvert.DeserializeObject <Result>(await res.Content.ReadAsStringAsync()); var embed = await BuildEmbedAsync(guildUser, parsedResult); await _autoRemoveMessageService.RegisterRemovableMessageAsync(Context.User, embed, async (e) => { await message.ModifyAsync(a => { a.Content = string.Empty; a.Embed = e.Build(); }); return(message); }); await Context.Message.DeleteAsync(); }