private static async Task DownloadAndExtractFiles(DiscordAttachment attachment) { WebRequest webRequest = WebRequest.Create(attachment.Url); WebResponse response = await webRequest.GetResponseAsync(); Stream dataStream = response.GetResponseStream(); string programToGrade = attachment.FileName[0..^ 4];
public async Task <bool> CanHandleAsync(DiscordAttachment attachment) { if (!attachment.FileName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { return(false); } try { using (var client = HttpClientFactory.Create()) using (var stream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false)) { var buf = bufferPool.Rent(1024); bool result; try { var read = await stream.ReadBytesAsync(buf).ConfigureAwait(false); var firstEntry = Encoding.ASCII.GetString(new ReadOnlySpan <byte>(buf, 0, read)); result = firstEntry.Contains(".log", StringComparison.InvariantCultureIgnoreCase); } finally { bufferPool.Return(buf); } return(result); } } catch (Exception e) { Config.Log.Error(e, "Error sniffing the zip content"); return(false); } }
/// <summary> /// Downloads the file from discord message asynchronously. /// </summary> /// <param name="context">The context where the file was attached.</param> /// <returns>Completed Task of type boolean. True if the process was a success</returns> public static async Task <bool> DownloadFileFromDiscordMessageAsync(CommandContext context) { if (context.Message.Attachments.Count <= 0) { context.Client.DebugLogger.Warn(string.Format("{0} forgot to upload a file with the custom command", context.User.Username)); await context.RespondAsync("No file was attached to the message :^("); return(false); } DiscordAttachment attachment = context.Message.Attachments[0]; string customAudioPath = string.Format(@"AudioFiles\{0}", attachment.FileName); if (File.Exists(customAudioPath)) { context.Client.DebugLogger.Warn(string.Format("{0} uploaded a file thats name already existed", context.User.Username)); await context.RespondAsync("filename already exists :^("); return(false); } using (var client = new WebClient()) { client.DownloadFile(attachment.Url, customAudioPath); } context.Client.DebugLogger.Info("A file was successfully uploaded"); return(true); }
public AttachmentViewer(DiscordAttachment attachment) { InitializeComponent(); Attachment = attachment; DataContext = attachment; HorizontalAlignment = HorizontalAlignment.Left; }
public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer) { using (var client = HttpClientFactory.Create()) using (var stream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false)) { try { int read; FlushResult flushed; do { var memory = writer.GetMemory(Config.MinimumBufferSize); read = await stream.ReadAsync(memory, Config.Cts.Token); writer.Advance(read); flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false); } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested)); } catch (Exception e) { Config.Log.Error(e, "Error filling the log pipe"); writer.Complete(e); return; } } writer.Complete(); }
internal DiscordAttachmentSource(DiscordAttachment attachment, IArchiveHandler handler, string fileName, int fileSize) { this.attachment = attachment; this.handler = handler; FileName = fileName; SourceFileSize = fileSize; }
public async Task DatabaseQuery(CommandContext ctx) { if (!ctx.Message.Attachments.Any()) { throw new CommandFailedException("Either write a query or attach a .sql file containing it!"); } DiscordAttachment attachment = ctx.Message.Attachments.FirstOrDefault(att => att.FileName.EndsWith(".sql")); if (attachment is null) { throw new CommandFailedException("No .sql files attached!"); } string query; try { query = await _http.GetStringAsync(attachment.Url).ConfigureAwait(false); } catch (Exception e) { this.Shared.LogProvider.Log(LogLevel.Debug, e); throw new CommandFailedException("An error occured while getting the file.", e); } await this.DatabaseQuery(ctx, query); }
public async Task CreateEmote(CommandContext ctx, [Description("emote name.\n" + "Default: will give a png filename if empty.")] string emoteName = "") { if (ctx.Channel.IsPrivate) { await ctx.RespondAsync(":x: This command is only for server use."); return; } var emotepath = "D:\\source\\emotes\\temp\\"; await ctx.TriggerTypingAsync(); if (ctx.Message.Attachments == null) { await ctx.RespondAsync("No new emote attached. Cancelling."); } else { try { DiscordAttachment newemote = ctx.Message.Attachments[0]; string filetype = newemote.FileName.Substring(newemote.FileName.LastIndexOf(".", StringComparison.Ordinal), 4); bool isImage = filetype is ".png" or ".gif"; if (!isImage) { await ctx.RespondAsync("Wrong file type. Cancelling."); } else if (newemote.FileSize > 256 * 1024) { await ctx.RespondAsync("New emote file size more that 256Kb. Cancelling."); } else { if (emoteName.Length == 0) { emoteName = newemote.FileName.Substring(0, newemote.FileName.LastIndexOf(".", StringComparison.Ordinal)); } await FileHandler.DownloadUrlFile(newemote.Url, emotepath, ctx.Client, $"{emoteName}{filetype}"); await Task.Delay(1000); // little delay for our file stream await using (FileStream fileStream = File.OpenRead($"{emotepath}{emoteName}{filetype}")) { DiscordGuildEmoji createdEmote = await ctx.Guild.CreateEmojiAsync(emoteName, fileStream); await ctx.RespondAsync($"Created new emote: {createdEmote}"); fileStream.Close(); } File.Delete($"{emotepath}{emoteName}{filetype}"); } } catch { // ignored } } }
public async Task Grade(CommandContext commandContext, [Description("What class to grade for. Valid options: CS1430, CS143, 1430, 143, CS2430, CS243, 2430, 243. Defaults to CS2430")] string className = "CS2430", [Description("Indicates if this is the final submission or not. Defaults to false")] bool final = false) { DiscordAttachment attachment = commandContext.Message.Attachments.FirstOrDefault(); GradeTypes gradeType; switch (className.ToLower()) { case "cs1430": case "cs143": case "1430": case "143": if (attachment == null || !(attachment.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) || attachment.FileName.EndsWith(".cpp", StringComparison.OrdinalIgnoreCase))) { await commandContext.RespondAsync(attachment == null? "You forgot attach the program to grade" : "I can only grade zips or a single cpp"); await DefaultHelpAsync(commandContext, nameof(Grade)); return; } gradeType = GradeTypes.CPlusPlus; break; case "cs2430": case "cs243": case "2430": case "243": if (attachment == null || !(attachment.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) || attachment.FileName.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))) { await commandContext.RespondAsync(attachment == null? "You forgot attach the program to grade" : "I can only grade zips or a single cs"); await DefaultHelpAsync(commandContext, nameof(Grade)); return; } gradeType = GradeTypes.CSharp; break; default: await commandContext.RespondAsync("I need to know what class to grade for! (Valid options: CS1430, CS143, 1430, 143, CS2430, CS243, 2430, 243)"); await DefaultHelpAsync(commandContext, nameof(Grade)); return; } string currentDirectory = Directory.GetCurrentDirectory(); await commandContext.RespondAsync("Getting files and building"); string programToGrade = attachment.FileName.Split('.')[0]; LogMessage(commandContext, $"Grading {gradeType} {programToGrade} for {commandContext.User.Username}({commandContext.User.Id})"); switch (gradeType) { case GradeTypes.CSharp: await Grader.GradeCSharp(commandContext, attachment, currentDirectory, programToGrade, final); break; case GradeTypes.CPlusPlus: await Grader.GradeCPP(commandContext, attachment, currentDirectory, programToGrade, final); break; } }
public Task <bool> CanHandleAsync(DiscordAttachment attachment) { if (!attachment.FileName.EndsWith(".7z", StringComparison.InvariantCultureIgnoreCase)) { return(Task.FromResult(false)); } return(Task.FromResult(true)); }
public async Task <object> Convert(string arg, Type to, CommandContext context) { Image <Rgba32> finishedImage = null; Uri url = null; DiscordAttachment attachment = context.Message.Attachments.FirstOrDefault(); if (attachment != null && attachment.Width > 0 && attachment.Height > 0) { url = new Uri(attachment.Url); } else { foreach (string a in context.Arguments) { if (Uri.TryCreate(a, UriKind.Absolute, out url)) { var temp = context.Arguments.ToList(); temp.Remove(a); context.Arguments = temp.ToArray(); break; } } } if (url == null) { if (ImageCommandResult.ImageCache.TryGetValue(context.Channel.Id, out var img) && img != null) { return(img); } else { var messages = await context.Channel.GetMessagesBeforeAsync(context.Message.Id, 10); DiscordMessage msg = messages.FirstOrDefault(m => m.Attachments.Any() && m.Attachments.FirstOrDefault()?.Width != 0); if (msg != null) { attachment = msg.Attachments.FirstOrDefault(); if (attachment != null && attachment.Width > 0 && attachment.Height > 0) { url = new Uri(attachment.Url); } } } } finishedImage = Image.Load <Rgba32>(await _client.GetStreamAsync(url)); return(finishedImage); }
public async Task AddTorrent(CommandContext ctx) { try { DiscordAttachment file = ctx.Message.Attachments.First(); WebClient client = new WebClient(); client.DownloadFile(file.Url, Properties.Settings.Default.TorrentFolder + file.FileName); ctx.RespondAsync(Utilities.QuickEmbed("Se ha descargado el torrent")); } catch (Exception e) { ctx.RespondAsync(Utilities.QuickEmbed("No se ha podido descargar el torrent", "Error: " + e.Message, false, false, DiscordColor.Red.ToString())); } }
public static void DownloadCharacterSheet(DiscordAttachment _file, CommandContext ctx) { string directory = @"Data\Stats\"; string pathString = System.IO.Path.Combine(directory, ctx.User.Username); System.IO.Directory.CreateDirectory(pathString); pathString = System.IO.Path.Combine(pathString, _file.FileName); if (!File.Exists(pathString)) { using (var client = new WebClient()) { client.DownloadFile(_file.Url, pathString); } } }
/// <summary> /// Начинает отслеживание реакций сообщения с картинкой. /// </summary> /// <param name="message">Отслеживаемое изображение</param> /// <param name="attachment">Картинка</param> private async Task ExecuteMessageTrack(DiscordMessage message, DiscordAttachment attachment) { var res = await queue.QueueTask(() => DownloadAndRecognizeImage(attachment)); if (res == null) { return; } Beatmapset banchoBeatmapset = res.Item1; Beatmap banchoBeatmap = res.Item2; // Ignore beatmap for several minutes foreach (var kvp in ignoreList) { if (DateTime.Now - kvp.Value > TimeSpan.FromMinutes(10)) { ignoreList.Remove(kvp.Key); } } if (ignoreList.ContainsKey(banchoBeatmap.id)) { logger.LogInformation($"Beatmap is in ignore list {banchoBeatmap.id}"); return; } ignoreList.Add(banchoBeatmap.id, DateTime.Now); // Contruct message DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder(); TimeSpan mapLen = TimeSpan.FromSeconds(banchoBeatmap.total_length); DiscordEmoji banchoRankEmoji = emoji.RankStatusEmoji(banchoBeatmap.ranked); DiscordEmoji diffEmoji = emoji.DiffEmoji(banchoBeatmap.difficulty_rating); // Check gatari GBeatmap gBeatmap = gapi.TryGetBeatmap(banchoBeatmap.id); DiscordEmbed embed = utils.BeatmapToEmbed(banchoBeatmap, banchoBeatmapset, gBeatmap); await message.RespondAsync(embed : embed); }
public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer) { try { using (var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 16384, FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose)) { using (var client = HttpClientFactory.Create()) using (var downloadStream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false)) await downloadStream.CopyToAsync(fileStream, 16384, Config.Cts.Token).ConfigureAwait(false); fileStream.Seek(0, SeekOrigin.Begin); using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read)) { var logEntry = zipArchive.Entries.FirstOrDefault(e => e.Name.EndsWith(".log", StringComparison.InvariantCultureIgnoreCase)); if (logEntry == null) { throw new InvalidOperationException("No zip entries that match the log criteria"); } using (var zipStream = logEntry.Open()) { int read; FlushResult flushed; do { var memory = writer.GetMemory(Config.MinimumBufferSize); read = await zipStream.ReadAsync(memory, Config.Cts.Token); writer.Advance(read); flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false); } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested)); } } } } catch (Exception e) { Config.Log.Error(e, "Error filling the log pipe"); writer.Complete(e); return; } writer.Complete(); }
public async Task FillPipeAsync(DiscordAttachment attachment, PipeWriter writer) { try { using (var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 16384, FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose)) { using (var client = HttpClientFactory.Create()) using (var downloadStream = await client.GetStreamAsync(attachment.Url).ConfigureAwait(false)) await downloadStream.CopyToAsync(fileStream, 16384, Config.Cts.Token).ConfigureAwait(false); fileStream.Seek(0, SeekOrigin.Begin); using (var zipArchive = SevenZipArchive.Open(fileStream)) using (var zipReader = zipArchive.ExtractAllEntries()) while (zipReader.MoveToNextEntry()) { if (!zipReader.Entry.IsDirectory && zipReader.Entry.Key.EndsWith(".log", StringComparison.InvariantCultureIgnoreCase)) { using (var rarStream = zipReader.OpenEntryStream()) { int read; FlushResult flushed; do { var memory = writer.GetMemory(Config.MinimumBufferSize); read = await rarStream.ReadAsync(memory, Config.Cts.Token); writer.Advance(read); flushed = await writer.FlushAsync(Config.Cts.Token).ConfigureAwait(false); } while (read > 0 && !(flushed.IsCompleted || flushed.IsCanceled || Config.Cts.IsCancellationRequested)); } writer.Complete(); return; } } Config.Log.Warn("No 7z entries that match the log criteria"); } } catch (Exception e) { Config.Log.Error(e, "Error filling the log pipe"); } writer.Complete(); }
public async Task AddCustom(CommandContext ctx, [RemainingText, Description("Name of the command")] string customCommandName) { CustomAudioCommandModel custCom = CustomAudioCommandFile.Instance.GetAudioFileForCommand(customCommandName); if (custCom != null) { await ctx.RespondAsync("A command with that name already exists :^("); return; } if (await FileDownloadUtil.DownloadFileFromDiscordMessageAsync(ctx)) { DiscordAttachment attachment = ctx.Message.Attachments[0]; string customAudioPath = string.Format(@"AudioFiles\{0}", attachment.FileName); CustomAudioCommandFile.Instance.AddCustomCommand(customCommandName, customAudioPath); await ctx.RespondAsync(string.Format("Custom command ```{0}``` was added :^)", customCommandName)); } }
public async Task <CommandResult> RunAsync() { DiscordAttachment attach = Context.Message.Attachments.FirstOrDefault(); if (attach != null) { string code = await _client.GetStringAsync(attach.Url); DiscordMessage message = await Context.ReplyAsync("Evaluating..."); DiscordEmbedBuilder builder = Context.GetEmbedBuilder("Evaluation Result"); builder.AddField("Code", $"```js\r\n{Static.ShrinkToEmbed(code)}\r\n```"); Static.RunEvalProcess(Context.Message, code, "js", builder, RunJSEval); await message.DeleteAsync(); return(builder.Build()); } return("Type or upload code!"); }
private async Task AvatarFromAttachment(AvatarLocation location, Context ctx, PKMember target, DiscordAttachment attachment) { ctx.CheckSystem().CheckOwnMember(target); await AvatarUtils.VerifyAvatarOrThrow(attachment.Url); await UpdateAvatar(location, ctx, target, attachment.Url); if (location == AvatarLocation.Server) { await ctx.Reply($"{Emojis.Success} Member server avatar changed to attached image. This avatar will now be used when proxying in this server (**{ctx.Guild.Name}**). Please note that if you delete the message containing the attachment, the avatar will stop working."); } else if (location == AvatarLocation.Member) { await ctx.Reply($"{Emojis.Success} Member avatar changed to attached image. Please note that if you delete the message containing the attachment, the avatar will stop working."); } }
/// <summary> /// Начинает распознавание картинки /// </summary> /// <param name="attachment">Картинка</param> private Tuple <Beatmapset, Beatmap> DownloadAndRecognizeImage(DiscordAttachment attachment) { string webFileName = $"{DateTime.Now.Ticks}-{attachment.FileName}"; webClient.DownloadFile(attachment.Url, $"downloads/{webFileName}"); string fileName = $"downloads/{webFileName}"; Image image = Image.FromFile(fileName); string[] rawrecedText = recognizer.RecognizeTopText(image).Split('\n'); sheduler.AddFileDeleteTask(fileName); foreach (string s in rawrecedText) { logger.LogDebug(s); } // Searching for first non-empty or almost string string recedText = string.Empty; foreach (string s in rawrecedText) { if (!string.IsNullOrWhiteSpace(s) && s.Length > 10) { recedText = s; break; } } logger.LogDebug($"Recognized text: {recedText}"); // Cut artist int indexStart = recedText.IndexOf('-'); if (indexStart == -1) { indexStart = recedText.IndexOf('–'); } if (indexStart != -1) { logger.LogDebug("Cutting artist"); recedText = recedText.Substring(indexStart).TrimStart(new char[] { ' ', '-', '–' }); } logger.LogDebug($"Searching for: {recedText}"); List <Beatmapset> bmsl = api.Search(recedText, WAV_Osu_NetApi.Bancho.QuerryParams.MapType.Any); // Get map diff indexStart = recedText.IndexOf('['); if (indexStart == -1) { logger.LogInformation($"Coulnd't get map difficulty"); return(null); } string diffName = recedText.Substring(indexStart).TrimStart('[').TrimEnd(']'); logger.LogDebug($"diffName: {diffName}"); if (bmsl == null || bmsl.Count == 0) { logger.LogInformation($"Api search return null or empty List"); return(null); } string mapper = string.Empty; mapper = rawrecedText.Select(x => x) .FirstOrDefault(x => { x = x.ToLowerInvariant(); return(x.Contains("mapped") || x.Contains("beatmap")); }); Beatmapset bms = null; if (!string.IsNullOrEmpty(mapper)) { mapper = mapper?.Substring(10); logger.LogDebug($"Got mapper: {mapper}. Comparing..."); List <Tuple <Beatmapset, double> > bsm = bmsl.Select(x => Tuple.Create(x, WAV_Osu_Recognizer.RecStringComparer.Compare(x.creator, mapper))) .OrderByDescending(x => x.Item2) .ToList(); foreach (var b in bsm) { logger.LogDebug($"{b.Item1.creator}: {b.Item2}"); } if (bsm == null || bsm.Count == 0) { bms = bmsl.FirstOrDefault(); } else { bms = bsm.First().Item1; } } else { logger.LogInformation($"Couldn't get mapper"); bms = bmsl.FirstOrDefault(); } if (bms == null) { logger.LogInformation($"No matching beatmapsets"); return(null); } else { logger.LogDebug($"Beatmapsets count: {bmsl.Count}"); } List <Tuple <Beatmap, double> > bmds = bms.beatmaps.Select(x => Tuple.Create(x, WAV_Osu_Recognizer.RecStringComparer.Compare(x.version, diffName))) .OrderByDescending(x => x.Item2) .ToList(); logger.LogDebug("Comparing beatmap versions:"); foreach (var k in bmds) { logger.LogDebug($"{k.Item1.version} {k.Item2}"); } var result = Tuple.Create(bms, bmds.First().Item1); logger.LogInformation($"Success. bms_id: {result.Item1.id}, bm_id: {result.Item2.id}"); return(result); }
public static async Task onMsgCreated(MessageCreateEventArgs args) { if (!autoEmbedderEnabled) { return; } if (args.Author != MainWindow.userClient.CurrentUser) { return; } DiscordMessage msg = args.Message; if (msg.Content == null) { return; } if (msg.Content.Length < 1) { return; } DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder(); embedBuilder.Title = $"Сообщение в {DateTime.Now.ToString()} от {(msg.Channel.IsPrivate ? msg.Author.Username : (((DiscordMember)msg.Author).Nickname!=null ? ((DiscordMember)msg.Author).Nickname : msg.Author.Username))}"; embedBuilder.Description = msg.Content; if (msg.Attachments != null && msg.Attachments.Count > 0) { DiscordAttachment img = msg.Attachments[0]; if (img.FileName.EndsWith(".jpg", true, CultureInfo.InvariantCulture) || img.FileName.EndsWith(".png", true, CultureInfo.InvariantCulture) || img.FileName.EndsWith(".bmp", true, CultureInfo.InvariantCulture)) { string url = img.Url; embedBuilder.ImageUrl = url; } else { string url = img.Url; embedBuilder.Url = url; } } Random random = new Random(); DiscordColor randColor; switch (random.Next(0, 7)) { case 0: randColor = DiscordColor.Red; break; case 1: randColor = DiscordColor.Green; break; case 2: randColor = DiscordColor.Blue; break; case 3: randColor = DiscordColor.Yellow; break; case 4: randColor = DiscordColor.Cyan; break; case 5: randColor = DiscordColor.Violet; break; case 6: randColor = DiscordColor.Azure; break; case 7: randColor = DiscordColor.Blurple; break; default: randColor = new DiscordColor(); break; } embedBuilder.Color = randColor; embedBuilder.ThumbnailUrl = msg.Author.AvatarUrl; if (autoEmbedderMode == 0) { await msg.ModifyAsync(content : "", embed : embedBuilder.Build()); } else { await msg.Channel.SendMessageAsync(embed : embedBuilder.Build()); await msg.Channel.DeleteMessageAsync(msg); } }
public async Task SubmitScore(CommandContext commandContext) { DiscordMessage msg = await commandContext.Channel.GetMessageAsync(commandContext.Message.Id); logger.LogInformation($"DM {msg.Author}: {msg.Content} : {msg.Attachments.Count}"); WAVMemberCompitInfo compitInfo = wavMembers.GetCompitInfo(commandContext.Member.Id); if (compitInfo.NonGrata) { await commandContext.RespondAsync("Извините, но вы не можете принять участие в данном конкурсе, т.к. внесены в черный список."); return; } if (compitInfo.ProvidedScore) { await commandContext.RespondAsync("Вы уже отправили скор."); return; } if (msg.Attachments.Count == 0) { await commandContext.RespondAsync("Вы не прикрепили к сообщению никаких файлов."); return; } if (msg.Attachments.Count > 1) { await commandContext.RespondAsync("К сообщению можно прикрепить только один файл."); return; } DiscordAttachment attachment = msg.Attachments.First(); if (!attachment.FileName.EndsWith("osr")) { await commandContext.RespondAsync("Файл не является реплеем."); return; } Replay replay = null; try { string fileName = $"{DateTime.Now.Ticks}-{attachment.FileName}"; webClient.DownloadFile(attachment.Url, $"downloads/{fileName}"); replay = ReplayDecoder.Decode($"downloads/{fileName}"); sheduler.AddFileDeleteTask(fileName); } catch (Exception e) { logger.LogCritical(e, "Exception while parsing score"); } if ((int)replay.Mods != 0) { const int b = (int)(OsuParsers.Enums.Mods.NoFail | OsuParsers.Enums.Mods.Perfect | OsuParsers.Enums.Mods.SuddenDeath); if (((int)replay.Mods | b) != b) { await commandContext.RespondAsync("Мы не можем принять данный скор по причине того, что он поставлен с запрещенными на W.w.W модами. \nРазрешенные на W.w.W моды - `NF`, `SD`, `PF`\nСкор система: V1"); return; } } DiscordMember member = await guild.GetMemberAsync(msg.Author.Id); string category = member.Roles.Select(x => x.Name) .FirstOrDefault((x) => { foreach (var xx in (new string[] { "beginner", "alpha", "beta", "gamma", "delta", "epsilon" })) if (x.Contains(xx)) return true; return false; }); StringBuilder sb = new StringBuilder(); sb.AppendLine($"Osu nickname: `{replay.PlayerName}`"); sb.AppendLine($"Discord nickname: `{msg.Author.Username}`"); sb.AppendLine($"Score: `{replay.ReplayScore:N0}`"); // Format: 123456789 -> 123 456 789 sb.AppendLine($"Category: `{category ?? "No category"}`"); sb.AppendLine($"Mods: `{utils.ModsToString((WAV_Osu_NetApi.Bancho.Models.Enums.Mods)replay.Mods)}`"); DiscordEmbedBuilder embed = new DiscordEmbedBuilder().WithAuthor(msg.Author.Username, iconUrl: msg.Author.AvatarUrl) .WithTitle($"Added replay {DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}") .WithUrl(attachment.Url) .WithDescription(sb.ToString()) .AddField("OSR Link:", attachment.Url) .AddField("File name:", $"`{attachment.FileName}`") .WithTimestamp(DateTime.Now); await wavScoresChannel.SendMessageAsync(embed: embed); await commandContext.RespondAsync("Ваш скор был отправлен на рассмотрение. Спасибо за участие!"); }
private async Task <Task> Client_MessageCreated(DiscordClient sender, MessageCreateEventArgs e) { if (e.Author.IsBot || e.Author.IsCurrent) { return(Task.CompletedTask); } //Esto es horrible pero bueno string mensaje = e.Message.Content.ToLower(); if (mensaje.StartsWith("-wote") || mensaje.StartsWith("wote") || e.Message.ChannelId == suggestions.Id || e.Message.ChannelId == adminSuggestions.Id) { await WoteAsync(e.Message, true); } if (e.Channel == introductions) { DiscordMember member = (DiscordMember)e.Author; bool hasroles = checkroles(member); if (!hasroles) { await member.SendMessageAsync(EasyDualLanguageFormatting( "Nos hemos dado cuenta que no tienes los roles de nativo, puedes obtenerlos en #roles.\n" + "**Necesitas un rol de nativo para interactuar en el servidor.**\n" + "Si tienes algun problema puedes preguntar a algun miembro del staff.", "We've noticed that you don't have any native roles, you can grab them in #roles.\n" + "**You need a native role to interact on the server.**\n" + "If You're having trouble feel free to ask anyone from the staff team.")); } bool checkroles(DiscordMember member) { return(member.Roles.Where( role => role == EnglishNative || role == SpanishNative || role == OtherNative ).Any()); } } if (!mensaje.StartsWith("-")) { return(Task.CompletedTask); //OPTIMIZAAAAAAR } string[] content = mensaje.Trim().Split(' '); bool isAdmin = IsAdmin(e.Author); if (mensaje.StartsWith("-roles")) { await e.Channel.SendMessageAsync( $"{DiscordEmoji.FromName(Client, ":flag_es:")} Por favor ponte los roles adecuados en {roles.Mention} ¡No te olvides el rol de nativo!\n" + $"{DiscordEmoji.FromName(Client, ":flag_gb:")} Please set up your roles in {roles.Mention} Don't forget the native role!" ); return(Task.CompletedTask); } if (mensaje.StartsWith("-ping")) { await e.Message.RespondAsync("Pong! " + Client.Ping + "ms"); return(Task.CompletedTask); } if (mensaje.StartsWith("-help")) { DiscordMember member = (DiscordMember)e.Author; await member.SendMessageAsync(GenerateHelp(member)); e.Message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":white_check_mark:")); return(Task.CompletedTask); } if (mensaje.StartsWith("-sendwotd") && isAdmin) { bool confirmacion = await VerificarAsync(e.Channel, e.Author, 15); if (confirmacion) { await SendWOTDAsync(); e.Message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":white_check_mark:")); } return(Task.CompletedTask); } if (mensaje.StartsWith("-version")) { await e.Channel.SendMessageAsync(GetVersionEmbed()); return(Task.CompletedTask); } if (mensaje.StartsWith("-checkusers") && isAdmin) { _ = Task.Run(async() => { IEnumerable <DiscordMember> members = await languageServer.GetAllMembersAsync(); int i = 0; int max = members.Count(); DiscordMessage msg = await e.Channel.SendMessageAsync( HelperMethods.QuickEmbed($"Checking Users... This is going to take a while", $"{i}/{max}\n{HelperMethods.GenerateProgressBar(0)}")); DateTime lastEdit = DateTime.Now; foreach (DiscordMember member in members) { if (CheckUser(member)) { HelperMethods.Delay(100); } else { HelperMethods.Delay(50); } i++; if (DateTime.Now - lastEdit > TimeSpan.FromSeconds(8)) { lastEdit = DateTime.Now; msg.ModifyAsync(null, HelperMethods.QuickEmbed($"Checking Users...{i}/{max}", HelperMethods.GenerateProgressBar(((double)i / max)))); } } msg.ModifyAsync(null, HelperMethods.QuickEmbed("All users have been checked")); }); return(Task.CompletedTask); } if (mensaje.StartsWith("-isblocked") && isAdmin) { DiscordMember senderMember = (DiscordMember)e.Author; string nickname = ""; try { ulong userid = ulong.Parse(mensaje.Substring(10)); DiscordUser objUser = await Client.GetUserAsync(userid); DiscordMember objMember = await languageServer.GetMemberAsync(userid); nickname = objMember.Nickname; IReadOnlyList <DiscordMessage> mensajes = await conelBot.GetMessagesAsync(250); bool ischecked = false; foreach (DiscordMessage MensajeLocal in mensajes) { if (MensajeLocal.Author == objMember && !ischecked) { ischecked = true; await MensajeLocal.CreateReactionAsync(DiscordEmoji.FromName(Client, ":thinking:")); HelperMethods.Delay(); await MensajeLocal.DeleteOwnReactionAsync(DiscordEmoji.FromName(Client, ":thinking:")); await senderMember.SendMessageAsync($"El usuario {nickname} **No** ha bloqueado al bot"); } } } catch (Exception ex) { if (ex is ArgumentNullException || ex is FormatException || ex is OverflowException) { await senderMember.SendMessageAsync("Excepcion no controlada. Es posible que no hayas puesto bien el ID"); } if (ex.Message == "Unauthorized: 403") { await senderMember.SendMessageAsync($"El usuario {nickname} ha bloqueado al bot"); } } return(Task.CompletedTask); } if (mensaje.StartsWith("-gimmiadmin") && e.Author == yoshi) { //await e.Message.DeleteAsync(); DiscordMember member = (DiscordMember)e.Author; await member.GrantRoleAsync(admin); await member.SendMessageAsync("Admin == true"); return(Task.CompletedTask); } if (mensaje.StartsWith("-dletadmin") && e.Author == yoshi) { await e.Message.DeleteAsync(); DiscordMember member = (DiscordMember)e.Author; await member.SendMessageAsync("Admin == false"); await member.RevokeRoleAsync(admin); return(Task.CompletedTask); } if (mensaje.StartsWith("-restart") && isAdmin) { bool confirmacion = await VerificarAsync(e.Channel, e.Author, 15); if (confirmacion) { e.Message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":white_check_mark:")); HelperMethods.Delay(1500); Environment.Exit(0); } else { await e.Message.DeleteAsync(); } } if (mensaje.StartsWith("-embed") && isAdmin) { String message = e.Message.Content.Substring(6); DiscordMember member = (DiscordMember)e.Author; bool hasfile = e.Message.Attachments.Count > 0; bool isfilenamevaild = false; String filecontent = ""; if (hasfile) { DiscordAttachment file = e.Message.Attachments[0]; isfilenamevaild = file.FileName.Equals("message.txt"); string FileName = DateTime.Now.Ticks.ToString("X16") + @".txt"; //https://stackoverflow.com/questions/7874111/convert-datetime-now-to-a-valid-windows-filename => I hate the world using (WebClient client = new WebClient()) { client.DownloadFile(file.Url, FileName); } filecontent = File.ReadAllText(FileName); File.Delete(FileName); } HelperMethods.Delay(350); await e.Message.DeleteAsync(); try { if (!hasfile) { await e.Channel.SendMessageAsync(HelperMethods.QuickEmbed($"Embed de {member.Nickname ?? member.DisplayName: member.Nickname}", message, false)); } else if (hasfile && isfilenamevaild) { await e.Channel.SendMessageAsync(HelperMethods.QuickEmbed($"Embed de {member.Nickname ?? member.DisplayName: member.Nickname}", filecontent, false)); } } catch (Exception ex) { await botupdates.SendMessageAsync(new DiscordMessageBuilder() .WithContent("Excepcion con un Embed") .WithEmbed(GenerateErrorEmbed(ex)) ); DiscordMessage errorembed = await e.Channel.SendMessageAsync(HelperMethods.QuickEmbed(":warning: Error :warning:", EasyDualLanguageFormatting("Mensaje demasiado largo o contiene caracteres no validos", "Message too large or has invalid characters"), false, "#FF0000")); HelperMethods.Delay(5000); await errorembed.DeleteAsync(); } return(Task.CompletedTask); } if (mensaje.StartsWith("-https://cdn.discordapp.com/attachments/479257969427611649/803398998710681690/b.png") && isAdmin) { String[] imageformats = { "png", "jpg", "gif", "WebP" }; if (content.Length >= 2 && Uri.IsWellFormedUriString(content[1], UriKind.Absolute) && imageformats.Contains(content[1].Split('.').Last().Substring(0, 3))) { using (WebClient wc = new WebClient()) { string currentformat = content[1].Split('.').Last().Substring(0, 3); string filepath = DateTime.Now.Ticks.ToString("X16") + "." + currentformat; wc.DownloadFile(content[1], filepath); DiscordGuildEmoji guildEmoji = await e.Guild.CreateEmojiAsync(content[2], File.OpenRead(filepath)); await e.Channel.SendMessageAsync(guildEmoji.ToString()); File.Delete(filepath); } } else { await e.Message.DeleteAsync(); await e.Channel.SendMessageAsync(HelperMethods.QuickEmbed("No se puedo añadir el emoji", "Puede que no tenga el formato correcto[png, jpg, gif, WebP]\nUso:-Addemoji<URL> < Nombre_emoji >", false, "#ff0000")); } } if (mensaje.StartsWith("-usercount") && isAdmin) { UpdateUserCountChannel(); e.Message.CreateReactionAsync(DiscordEmoji.FromName(Client, ":white_check_mark:")); } //END OF IF WALL return(Task.CompletedTask); }
public override async Task <CommandResult> RunVoiceCommand(string[] args, CommandContext context, ConnectionModel connection) { SongModel model = new SongModel(); if (args.Any() && !string.IsNullOrEmpty(args[0])) { if (File.Exists(args[0])) { model.FilePath = args[0]; model.Title = Path.GetFileNameWithoutExtension(args[0]); } else if (Uri.TryCreate(args[0], UriKind.Absolute, out Uri uri)) { byte[] hash = _md5.Value.ComputeHash(Encoding.UTF8.GetBytes(uri.ToString())); string name = ""; if (uri.Host.ToLowerInvariant().Contains("youtu")) { var queryDictionary = HttpUtility.ParseQueryString(uri.Query); name = queryDictionary["v"]; if (string.IsNullOrEmpty(name)) { name = uri.Segments.LastOrDefault(); } } else { name = string.Join("", hash.Select(b => b.ToString("x2"))); } string path = Path.Combine(Path.GetTempPath(), name + ".m4a"); string thumbnailPath = Path.ChangeExtension(path, ".jpg"); string metaPath = Path.ChangeExtension(path, ".info.json"); model.Source = uri.ToString(); if (!File.Exists(path) || !File.Exists(metaPath)) { var message = await context.ReplyAsync("Attempting to download via youtube-dl"); DownloadAndWait(uri, name, false); await message.DeleteAsync(); } if (File.Exists(metaPath)) { JObject meta = JObject.Parse(File.ReadAllText(metaPath)); if (File.Exists(path)) { model.FilePath = path; } else if (File.Exists(Path.ChangeExtension(path, ".aac"))) { model.FilePath = Path.ChangeExtension(path, ".aac"); } model.Title = meta["fulltitle"].ToObject <string>(); model.Album = meta["uploader"]?.ToObject <string>(); model.Artist = meta["extractor_key"].ToObject <string>(); if (meta.TryGetValue("duration", out var token)) { model.Duration = TimeSpan.FromSeconds(token.ToObject <int>()); } model.Description = meta["description"]?.ToObject <string>(); if (!File.Exists(thumbnailPath) && meta.TryGetValue("thumbnail", out var thumbToken)) { using (FileStream thumbStr = File.Create(thumbnailPath)) using (Stream remoteStr = await _httpClient.GetStreamAsync(thumbToken.ToObject <string>())) { await remoteStr.CopyToAsync(thumbStr, 81920, connection.Token); } } if (File.Exists(thumbnailPath)) { model.ThumbnailPath = thumbnailPath; } } else { if (File.Exists(path)) { model.Title = "Metadata Unavailable"; model.FilePath = path; } else { try { var message = await context.ReplyAsync("Attempting to download as direct URL..."); using (Stream remoteStr = await _httpClient.GetStreamAsync(uri)) using (FileStream str = File.Create(path)) { await remoteStr.CopyToAsync(str); } model.FilePath = path; } catch (Exception ex) { return($"Failed to download URL. {ex.Message}"); } } } } } else if (context.Message.Attachments.Any()) { DiscordAttachment attachment = context.Message.Attachments.First(); DiscordMessage message = await context.ReplyAsync($"Downloading \"{Path.GetFileName(attachment.FileName)}\"..."); string filePath = ""; using (Stream remoteStr = await _httpClient.GetStreamAsync(attachment.Url)) { using (MemoryStream memStr = new MemoryStream()) { await remoteStr.CopyToAsync(memStr); memStr.Seek(0, SeekOrigin.Begin); byte[] hash = _md5.Value.ComputeHash(memStr); string name = string.Join("", hash.Select(b => b.ToString("x2"))); filePath = Path.Combine(Path.GetTempPath(), name + Path.GetExtension(attachment.FileName)); if (!File.Exists(filePath)) { using (FileStream str = File.Create(filePath)) { memStr.Seek(0, SeekOrigin.Begin); await memStr.CopyToAsync(str, 81920, connection.Token); } } } } model.FilePath = filePath; model.Title = Path.GetFileNameWithoutExtension(attachment.FileName).Replace("_", " "); try { await message.DeleteAsync(); } catch { } } else { DiscordEmbedBuilder builder = context.GetEmbedBuilder("Current Queue"); if (connection.Songs.Any() || connection.NowPlaying != null) { if (connection.NowPlaying != null) { AddSongField(builder, connection.NowPlaying, true); } foreach (SongModel song in connection.Songs) { AddSongField(builder, song, false); } } else { builder.AddField("No songs!", "You'll need to add a song or two! You're already using the right command, come on!"); } return(builder.Build()); } string defaultThumb = Path.ChangeExtension(model.FilePath, ".png"); if (!string.IsNullOrEmpty(model.FilePath)) { try { using (var tag = TagLib.File.Create(model.FilePath)) { if (!tag.PossiblyCorrupt) { if (!string.IsNullOrWhiteSpace(tag.Tag.Title)) { model.Title = tag.Tag.Title; } if (string.IsNullOrWhiteSpace(model.Album) || string.IsNullOrWhiteSpace(model.Artist)) { model.Album = tag.Tag.Album; model.Artist = string.Join(", ", tag.Tag.Performers); } if (model.Duration == null) { model.Duration = tag.Properties.Duration; } var art = tag.Tag.Pictures.FirstOrDefault(); if (art != null && !File.Exists(defaultThumb)) { using (var image = SixLabors.ImageSharp.Image.Load <Rgba32>(art.Data.Data)) { using (FileStream str = File.OpenWrite(defaultThumb)) { image.SaveAsPng(str); model.ThumbnailPath = defaultThumb; } } } } } } catch { } if (string.IsNullOrWhiteSpace(model.ThumbnailPath)) { if (File.Exists(defaultThumb)) { model.ThumbnailPath = defaultThumb; } else { try { using (var img = Thumbnails.GetThumbnail(model.FilePath)) { string path = defaultThumb; img.Save(path, ImageFormat.Png); model.ThumbnailPath = path; } } catch { } } } model.User = context.Author; connection.Songs.Enqueue(model); await context.ReplyAsync($"Queued: {model}"); } return(CommandResult.Empty); }
public static DiscordEmbed LeaderboardError(MessageCreateEventArgs e, DiscordAttachment attachment, string error) { var _userAvatarUrl = e.Author.AvatarUrl; LeaderboardErrorMessages _error = null; try { _error = JsonConvert.DeserializeObject <LeaderboardErrorMessages>(error); } catch (Exception ex) { var f = ex.Message; _error = null; } string _description = "My apologies, I was unable to process your image. Here's why:\n"; if (_error == null) { _description += error; } else { if (_error.Image != null && _error.Image.Any()) { _description += "**Image Errors:**\n"; foreach (var item in _error.Image) { _description += $"{item}\n"; } } if (_error.Parser != null && _error.Parser.Any()) { _description += "**Parser Errors:**\n"; foreach (var item in _error.Parser) { _description += $"{item}\n"; } } } var _ret = new DiscordEmbedBuilder { Title = $"Unable to process image", Description = (_error == null) ? _description : "My apologies, I was unable to process your image. Here's why:", ThumbnailUrl = _userAvatarUrl, ImageUrl = attachment.Url, Color = DiscordColor.IndianRed, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = $"Star Citizen Tools by SC TradeMasters", IconUrl = e.Client.CurrentUser.AvatarUrl } }; if (_error != null) { if (_error.Image != null && _error.Image.Any()) { _ret.AddField("Image Errors", string.Join("\n", _error.Image)); } if (_error.Parser != null && _error.Parser.Any()) { _ret.AddField("Parser Errors", string.Join("\n", _error.Parser)); } } return(_ret); }
public static void DownloadFile(DiscordAttachment file, MessageCreateEventArgs e) { // const string NewFiles = "./newfiles/"; // const string OldFiles = "./oldfiles/"; var json = File.ReadAllText(@"Config\urls.json"); var urls = JsonConvert.DeserializeObject <List <Url> >(json); var announcements = e.Guild.Channels.FirstOrDefault(x => x.Name == "announcements"); switch (file.FileName) { case "settings.cfg": // var settings = Directory.GetFiles(NewFiles).FirstOrDefault(x => x.Contains(file.FileName)); // var oldSettings = Directory.GetFiles(OldFiles).FirstOrDefault(x => x.Contains(file.FileName)); // if (settings != null) // { // if (File.Exists(oldSettings)) if (oldSettings != null) File.Delete(oldSettings); // File.Move(settings, OldFiles + "settings.cfg"); // e.Channel.SendMessageAsync($"Backed up old version to: {OldFiles}settings.cfg"); // } // using (var client = new WebClient()) // { // client.DownloadFileCompleted += async (sender, args) => // { // await e.Channel.SendMessageAsync($"New version downloaded to: {NewFiles}settings.cfg"); // var announcements = e.Guild.Channels.FirstOrDefault(x => x.Id == 344202765725073429); // if (announcements != null) // await announcements.SendMessageAsync( // "@everyone **New settings update posted in <#347409218715910155>. Please use `;update settings` in <#347430400424935426> to get the lastest version.**"); // }; // client.DownloadFileAsync(new Uri(file.Url), NewFiles + file.FileName); // } urls.First(setting => setting.Name == "oldsettings").Link = urls.First(setting => setting.Name == "newsettings").Link; // Backup old link e.Channel.SendMessageAsync(@"Backed up old version to: \Config\urls.json @ oldsettings"); urls.First(x => x.Name == "newsettings").Link = file.Url; e.Channel.SendMessageAsync(@"New version downloaded to: \Config\urls.json @ newsettings"); if (announcements != null) { announcements.SendMessageAsync( "@everyone **New settings update posted in <#347409218715910155>. Please use `;update settings` in <#347430400424935426> to get the lastest version.**"); } break; case "cheat.rar": // var discord = Directory.GetFiles(NewFiles).FirstOrDefault(x => x.Contains(file.FileName)); // var oldDiscord = Directory.GetFiles(OldFiles).FirstOrDefault(x => x.Contains(file.FileName)); // if (discord != null) // { // if (File.Exists(oldDiscord)) if (oldDiscord != null) File.Delete(oldDiscord); // File.Move(discord, OldFiles + "cheat.rar"); // e.Channel.SendMessageAsync($"Backed up old version to: {OldFiles}cheat.rar"); // } // using (var client = new WebClient()) // { // client.DownloadFileCompleted += async (sender, args) => // { // await e.Channel.SendMessageAsync($"New version downloaded to: {NewFiles}cheat.rar"); // if (announcements != null) // await announcements.SendMessageAsync( // "@everyone **New cheat update posted in <#347409218715910155>. Please use `;update cheat` in <#347430400424935426> to get the lastest version.**"); // }; // client.DownloadFileAsync(new Uri(file.Url), NewFiles + file.FileName); // } urls.First(setting => setting.Name == "oldcheat").Link = urls.First(setting => setting.Name == "newcheat").Link; // Backup old link e.Channel.SendMessageAsync(@"Backed up old version to: \Config\urls.json @ oldcheat"); urls.First(x => x.Name == "newcheat").Link = file.Url; e.Channel.SendMessageAsync(@"New version downloaded to: \Config\urls.json @ newcheat"); if (announcements != null) { announcements.SendMessageAsync( "@everyone **New settings update posted in <#347409218715910155>. Please use `;update cheat` in <#347430400424935426> to get the lastest version.**"); } break; case "loader.rar": // var loader = Directory.GetFiles(NewFiles).FirstOrDefault(x => x.Contains(file.FileName)); // var oldLoader = Directory.GetFiles(OldFiles).FirstOrDefault(x => x.Contains(file.FileName)); // if (loader != null) // { // if (File.Exists(oldLoader)) if (oldLoader != null) File.Delete(oldLoader); // File.Move(loader, OldFiles + "loader.rar"); // e.Channel.SendMessageAsync($"Backed up old version to: {OldFiles}loader.rar"); // } // using (var client = new WebClient()) // { // client.DownloadFileCompleted += async (sender, args) => // { // await e.Channel.SendMessageAsync($"New version downloaded to: {NewFiles}loader.rar"); // if (announcements != null) // await announcements.SendMessageAsync( // "@everyone **New loader update posted in <#347409218715910155>. Please use `;update loader` in <#347430400424935426> to get the lastest version.**"); // }; // client.DownloadFileAsync(new Uri(file.Url), NewFiles + file.FileName); // } urls.First(setting => setting.Name == "oldloader").Link = urls.First(setting => setting.Name == "newloader").Link; // Backup old link e.Channel.SendMessageAsync(@"Backed up old version to: \Config\urls.json @ oldloader"); urls.First(x => x.Name == "newloader").Link = file.Url; e.Channel.SendMessageAsync(@"New version downloaded to: \Config\urls.json @ newloader"); if (announcements != null) { announcements.SendMessageAsync( "@everyone **New settings update posted in <#347409218715910155>. Please use `;update loader` in <#347430400424935426> to get the lastest version.**"); } break; default: e.Channel.SendMessageAsync( $"What are you trying to upload <@{e.Channel.GetMessageAsync(e.Channel.LastMessageId).Result.Author.Id}>?\n" + "(cheat.rar | loader.rar | settings.cfg) only"); return; } WriteJson(e.Message, json, @"Config\urls.json", urls); }
// Debug only internal static Task Main(MessageCreateEventArgs Message_Objects) { StringBuilder Message_Log = new StringBuilder("Message Log"); if (Message_Objects.Channel.IsPrivate) { Message_Log.AppendFormat("\n[Channel] Name: {0}, ID: {1}", Message_Objects.Channel.Name ?? "Direct Message", Message_Objects.Channel.Id); Message_Log.AppendFormat("\n[Author] Name: {0}#{1}, ID: {2}, Bot: {3}", Message_Objects.Author.Username, Message_Objects.Author.Discriminator, Message_Objects.Author.Id, Message_Objects.Author.IsBot); Message_Log.AppendFormat("\n[Message] Content: {0}, ID: {1}", Message_Objects.Message.Content, Message_Objects.Message.Id); } else { Message_Log.AppendFormat("\n[Guild] Name: {0}, ID: {1}", Message_Objects.Guild.Name, Message_Objects.Guild.Id); Message_Log.AppendFormat("\n[Channel] Name: {0}, ID: {1}", Message_Objects.Channel.Name, Message_Objects.Channel.Id); Message_Log.AppendFormat("\n[Author] Name: {0}#{1}, ID: {2}, Bot: {3}", Message_Objects.Author.Username, Message_Objects.Author.Discriminator, Message_Objects.Author.Id, Message_Objects.Author.IsBot); Message_Log.AppendFormat("\n[Message] Content: {0}, ID: {1}", Message_Objects.Message.Content, Message_Objects.Message.Id); } if (!Message_Objects.Channel.IsPrivate) { if (Message_Objects.Message.MentionedUsers.Count > 0) { IEnumerator <DiscordUser> MentionedUsers = Message_Objects.Message.MentionedUsers.GetEnumerator(); StringBuilder MentionedUsers_Log = new StringBuilder("\n[MentionedUsers] "); bool MentionedUser_Next = MentionedUsers.MoveNext(); int UserCount = 0; while (MentionedUser_Next) { try { DiscordUser MentionedUser = MentionedUsers.Current; StringBuilder MentionedUser_Log = new StringBuilder().AppendFormat("{0}#{1}", MentionedUser.Username, MentionedUser.Discriminator); MentionedUser_Next = MentionedUsers.MoveNext(); if (MentionedUser_Next) { MentionedUser_Log.Append(", "); UserCount++; } MentionedUsers_Log.Append(MentionedUser_Log); } catch (NullReferenceException) { Log.Warning(string.Format("MentionedUser {0} is null", UserCount)); StringBuilder MentionedUser_Log = new StringBuilder("unknown-user"); MentionedUser_Next = MentionedUsers.MoveNext(); if (MentionedUser_Next) { MentionedUser_Log.Append(", "); UserCount++; } MentionedUsers_Log.Append(MentionedUser_Log); } } Message_Log.Append(MentionedUsers_Log); } if (Message_Objects.Message.MentionedRoles.Count > 0) { IEnumerator <DiscordRole> MentionedRoles = Message_Objects.Message.MentionedRoles.GetEnumerator(); StringBuilder MentionedRoles_Log = new StringBuilder("\n[MentionedRoles] "); bool MentionedRole_Next = MentionedRoles.MoveNext(); int RoleCount = 0; while (MentionedRole_Next) { try { DiscordRole MentionedRole = MentionedRoles.Current; StringBuilder MentionedRole_Log = new StringBuilder(MentionedRole.Name); MentionedRole_Next = MentionedRoles.MoveNext(); if (MentionedRole_Next) { MentionedRole_Log.Append(", "); RoleCount++; } MentionedRoles_Log.Append(MentionedRole_Log); } catch (NullReferenceException) { Log.Warning(string.Format("MentionedRole {0} is null", RoleCount)); StringBuilder MentionedRole_Log = new StringBuilder("deleted-role"); MentionedRole_Next = MentionedRoles.MoveNext(); if (MentionedRole_Next) { MentionedRole_Log.Append(", "); RoleCount++; } MentionedRoles_Log.Append(MentionedRole_Log); } } Message_Log.Append(MentionedRoles_Log); } if (Message_Objects.Message.MentionedChannels.Count > 0) { IEnumerator <DiscordChannel> MentionedChannels = Message_Objects.Message.MentionedChannels.GetEnumerator(); StringBuilder MentionedChannels_Log = new StringBuilder("\n[MentionedChannels] "); bool MentionedChannel_Next = MentionedChannels.MoveNext(); int ChannelCount = 0; while (MentionedChannel_Next) { try { DiscordChannel MentionedChannel = MentionedChannels.Current; StringBuilder MentionedChannel_Log = new StringBuilder(MentionedChannel.Name); MentionedChannel_Next = MentionedChannels.MoveNext(); if (MentionedChannel_Next) { MentionedChannel_Log.Append(", "); ChannelCount++; } MentionedChannels_Log.Append(MentionedChannel_Log); } catch (NullReferenceException) { Log.Warning($"MentionedChannel {ChannelCount} is null"); StringBuilder MentionedChannel_Log = new StringBuilder("deleted-channel"); MentionedChannel_Next = MentionedChannels.MoveNext(); if (MentionedChannel_Next) { MentionedChannel_Log.Append(", "); ChannelCount++; } MentionedChannels_Log.Append(MentionedChannel_Log); } } Message_Log.Append(MentionedChannels_Log); } } if (Message_Objects.Message.Attachments.Count > 0) { IEnumerator <DiscordAttachment> MessageAttachments = Message_Objects.Message.Attachments.GetEnumerator(); StringBuilder MessageAttachments_Log = new StringBuilder("\n[MessageAttachments] "); bool MessageAttachment_Next = MessageAttachments.MoveNext(); while (MessageAttachment_Next) { DiscordAttachment MessageAttachment = MessageAttachments.Current; StringBuilder MessageAttachment_Log = new StringBuilder().AppendFormat("Url: {0} ProxyUrl: {1}", MessageAttachment.Url, MessageAttachment.ProxyUrl); MessageAttachment_Next = MessageAttachments.MoveNext(); if (MessageAttachment_Next) { MessageAttachment_Log.Append(", "); } MessageAttachments_Log.Append(MessageAttachment_Log); } Message_Log.Append(MessageAttachments_Log); } Log.Debug(Message_Log.ToString()); return(Task.CompletedTask); }
public static async Task GradeCPP(CommandContext commandContext, DiscordAttachment attachment, string currentDirectory, string programToGrade, bool final) { string runPath = Path.Combine(Config.Instance.GraderDump, $"{commandContext.User.Id}/CS1430/{programToGrade}"); bool finalExists = Directory.Exists(runPath) && Directory.EnumerateDirectories(runPath, "*-final").Any(); if (finalExists) { await commandContext.RespondAsync("Unable to grade, you've already submitted your final submission"); } else { string graderDataFolder = Path.Join(currentDirectory, "GraderData", programToGrade); if (Directory.Exists(graderDataFolder)) { await DownloadAndExtractFiles(attachment); string sourcePath = Path.Join(currentDirectory, ExtractFolderName); List <string> sourceFiles = new List <string>(); sourceFiles.AddRange(Directory.EnumerateFiles(sourcePath, "*.cpp")); sourceFiles.AddRange(Directory.EnumerateFiles(sourcePath, "*.h")); string sources = string.Join(' ', sourceFiles.Select(a => $"\"{a}\"")); string exeFile = Path.Join(sourcePath, $"{programToGrade}.exe"); string argumentString = $"{sources} -o {exeFile} -static-libgcc -static-libstdc++"; try { ProcessStartInfo buildPSI = new ProcessStartInfo(@"C:\MinGW\bin\g++.exe", argumentString) { WorkingDirectory = @"C:\MinGW\bin\" }; var(buildStandard, buildError, buildTimeout) = RunProcess(buildPSI, 5000); if (File.Exists(exeFile)) { StringBuilder runsStringBuilder = new StringBuilder(); string fileGradeResults = GradeCPPFiles(sourceFiles); if (!string.IsNullOrWhiteSpace(fileGradeResults)) { runsStringBuilder.AppendLine("File Grade Results:"); runsStringBuilder.AppendLine(fileGradeResults); } await commandContext.RespondAsync("Build succeeded: Starting to test!"); List <string> filesToZip = new List <string>(); string runsFolder = Path.Join(ExtractFolderName, "Runs"); if (Directory.Exists(runsFolder)) { Directory.Delete(runsFolder, true); } bool anyFailed = false; Directory.CreateDirectory($"{ExtractFolderName}/Runs"); foreach (string inputFilePath in Directory.EnumerateFiles(graderDataFolder, "Input*").OrderBy(a => a)) { FileInfo fileInfo = new FileInfo(inputFilePath); string runNumber = fileInfo.Name.Replace("Input", "").Replace(".txt", ""); string input = File.ReadAllText(inputFilePath); string expectedOutput = File.ReadAllText(Path.Join(graderDataFolder, $"Output{runNumber}.txt")); try { string results = RunProgram(sourcePath, exeFile, input); anyFailed |= !GradeOutput(runsStringBuilder, runNumber, expectedOutput, results); string expFileName = Path.Join(runsFolder, $"{programToGrade}Expected{runNumber}.txt"); string actFileName = Path.Join(runsFolder, $"{programToGrade}Actual{runNumber}.txt"); File.WriteAllText(expFileName, expectedOutput); File.WriteAllText(actFileName, results); filesToZip.AddRange(new[] { expFileName, actFileName }); } catch (Exception exc) { anyFailed = true; runsStringBuilder.AppendLine($"Exception thrown on Run {runNumber}:"); runsStringBuilder.AppendLine(exc.Message); } } string filePrefix = $"{programToGrade}_{DateTime.Now:MMddyyyy-HH-mm-ss}"; string shortZipFileName = $"{filePrefix}.zip"; string zipFileName = Path.Combine(ExtractFolderName, shortZipFileName); ZipFile.CreateFromDirectory(runsFolder, zipFileName); Directory.Delete(runsFolder, true); string finalResult = runsStringBuilder.ToString(); string shortFileName = $"{filePrefix}_GraderResult.txt"; string fileName = Path.Combine(ExtractFolderName, shortFileName); File.WriteAllText(fileName, finalResult); using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) using (FileStream zipFileStream = new FileStream(zipFileName, FileMode.Open)) { await commandContext.RespondWithFilesAsync(new Dictionary <string, Stream>() { { shortFileName, fileStream }, { shortZipFileName, zipFileStream } }, anyFailed? "You're gonna wanna check the files" : "Nice work"); } } else { var extractDir = new DirectoryInfo("extract"); string failString = buildError.Replace(extractDir.FullName, ""); DiscordEmbedBuilder discordEmbedBuilder = Config.Instance.GetDiscordEmbedBuilder() .WithTitle("Failed to build"); if (failString.Length > 1500) { File.WriteAllText("Fail.txt", failString); await commandContext.RespondWithFileAsync("Fail.txt", embed : discordEmbedBuilder.Build()); } else { discordEmbedBuilder = discordEmbedBuilder.WithDescription(failString); await commandContext.RespondAsync(embed : discordEmbedBuilder.Build()); } } Directory.CreateDirectory(runPath); Directory.Move(ExtractFolderName, Path.Combine(runPath, $"{DateTime.Now:MMddyyyy-HH-mm-ss}{(final ? "-final" : "")}")); } catch (Exception e) { await commandContext.RespondAsync($"Failed to build: {e.Message}"); } } else { await commandContext.RespondAsync($"I am not yet ready to grade {programToGrade}!"); } } }
public static async Task GradeCSharp(CommandContext commandContext, DiscordAttachment attachment, string currentDirectory, string programToGrade, bool final) { string runPath = Path.Combine(Config.Instance.GraderDump, $"{commandContext.User.Id}/CS2430/{programToGrade}"); bool finalExists = Directory.Exists(runPath) && Directory.EnumerateDirectories(runPath, "*-final").Any(); if (finalExists) { await commandContext.RespondAsync("Unable to grade, you've already submitted your final submission"); } else { string graderDataFolder = Path.Join(currentDirectory, "GraderData", "CS2430", programToGrade); if (Directory.Exists(graderDataFolder)) { await DownloadAndExtractFiles(attachment); string sourcePath = Path.Join(currentDirectory, ExtractFolderName); File.WriteAllText(Path.Combine(ExtractFolderName, "Build.csproj"), "<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>netcoreapp3.1</TargetFramework></PropertyGroup></Project>"); ProcessStartInfo buildStartInfo = new ProcessStartInfo("dotnet", "build") { WorkingDirectory = ExtractFolderName }; (string buildStandard, string buildError, bool buildTimeout) = RunProcess(buildStartInfo, 5000); string exeFile = Path.Combine(ExtractFolderName, "bin\\debug\\netcoreapp3.1\\Build.exe"); if (!buildTimeout && File.Exists(exeFile)) { StringBuilder runsStringBuilder = new StringBuilder(); string fileGradeResults = GradeCSFiles(Directory.EnumerateFiles(sourcePath, "*.cs")); if (!string.IsNullOrWhiteSpace(fileGradeResults)) { runsStringBuilder.AppendLine("File Grade Results:"); runsStringBuilder.AppendLine(fileGradeResults); } await commandContext.RespondAsync("Build succeeded: Starting to test!"); List <string> filesToZip = new List <string>(); string runsFolder = Path.Join(ExtractFolderName, "Runs"); if (Directory.Exists(runsFolder)) { Directory.Delete(runsFolder, true); } bool anyFailed = false; Directory.CreateDirectory($"{ExtractFolderName}/Runs"); foreach (string inputFilePath in Directory.EnumerateFiles(graderDataFolder, "Input*").OrderBy(a => a)) { FileInfo fileInfo = new FileInfo(inputFilePath); string runNumber = fileInfo.Name.Replace("Input", "").Replace(".txt", ""); string input = File.ReadAllText(inputFilePath); string expectedOutput = File.ReadAllText(Path.Join(graderDataFolder, $"Output{runNumber}.txt")); string results = RunProgram(sourcePath, exeFile, input); anyFailed |= !GradeOutput(runsStringBuilder, runNumber, expectedOutput, results); string expFileName = Path.Join(runsFolder, $"{programToGrade}Expected{runNumber}.txt"); string actFileName = Path.Join(runsFolder, $"{programToGrade}Actual{runNumber}.txt"); File.WriteAllText(expFileName, expectedOutput); File.WriteAllText(actFileName, results); filesToZip.AddRange(new[] { expFileName, actFileName }); } string filePrefix = $"{programToGrade}_{DateTime.Now:MMddyyyy-HH-mm-ss}"; string shortZipFileName = $"{filePrefix}.zip"; string zipFileName = Path.Combine(ExtractFolderName, shortZipFileName); ZipFile.CreateFromDirectory(runsFolder, zipFileName); Directory.Delete(runsFolder, true); string finalResult = runsStringBuilder.ToString(); string shortFileName = $"{filePrefix}_GraderResult.txt"; string fileName = Path.Combine(ExtractFolderName, shortFileName); File.WriteAllText(fileName, finalResult); using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) using (FileStream zipFileStream = new FileStream(zipFileName, FileMode.Open)) { await commandContext.RespondWithFilesAsync(new Dictionary <string, Stream>() { { shortFileName, fileStream }, { shortZipFileName, zipFileStream } }, anyFailed? "You're gonna wanna check the files" : "Nice work"); } } else { var extractDir = new DirectoryInfo("extract"); string failString = buildStandard.Replace(extractDir.FullName, ""); DiscordEmbedBuilder discordEmbedBuilder = Config.Instance.GetDiscordEmbedBuilder() .WithTitle("Failed to build"); if (failString.Length > 1500) { File.WriteAllText("Fail.txt", failString); await commandContext.RespondWithFileAsync("Fail.txt", embed : discordEmbedBuilder.Build()); } else { discordEmbedBuilder = discordEmbedBuilder.WithDescription(failString); await commandContext.RespondAsync(embed : discordEmbedBuilder.Build()); } } ProcessStartInfo cleanStartInfo = new ProcessStartInfo("dotnet", "clean") { WorkingDirectory = ExtractFolderName }; RunProcess(cleanStartInfo, 5000); Directory.CreateDirectory(runPath); Directory.Move(ExtractFolderName, Path.Combine(runPath, $"{DateTime.Now:MMddyyyy-HH-mm-ss}{(final ? "-final" : "")}")); } else { await commandContext.RespondAsync($"I am not yet ready to grade {programToGrade}!"); } } }
public static DiscordEmbed CreateScreen(AddCreateScreen_Record data, MessageCreateEventArgs e, DiscordAttachment attachment, int recordId) { var _userName = e.Author.Username; var _userDiscriminator = e.Author.Discriminator; var _userAvatarUrl = e.Author.AvatarUrl; var _userId = e.Author.Id; var _channelName = (e.Channel?.Name != null && e.Channel?.Name.Trim().Length > 0) ? e.Channel?.Name : "Direct User"; var _channelId = e.Channel.Id; var _guildName = (e.Guild?.Name != null) ? e.Guild.Name : "Direct User"; //var _guildId = e.Guild.Id; var _ret = new DiscordEmbedBuilder { Title = $"New Refinery Sale Option by {_userName}", Description = $"**{_userName}** is showing an option to sell **{data.TotalCargoSpace - data.EmptyCargoSpace}**{data.CargoUnitOfMeasure.ToString()} of goods for a gross profit of **{data.TotalTransactionValue}**aUEC.\nUpon completing this sale **{data.TotalTransactionValue}**xp will be awarded to the player, team, and org.", ThumbnailUrl = _userAvatarUrl, ImageUrl = attachment.Url, Color = DiscordColor.Yellow, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = $"Star Citizen Tools by SC TradeMasters >> CreateScreen:{recordId}", IconUrl = e.Client.CurrentUser.AvatarUrl } } .AddField("Organization", $"**{_guildName}**", true) .AddField("Team", $"**{_channelName}**", true) //.AddField($"**{_userName}#{_userDiscriminator}**", ":trophy:**Rank 1** [**27,324**xp]") .AddField($"Ship", data.ShipIdentifier) .AddField($"Total Value *({data.Items.Count} item types)*", $"**{data.TotalTransactionValue}** aUEC") ; foreach (var item in data.Items) { _ret.AddField($"**{item.Name}** ({Math.Round(item.Units / (data.TotalCargoSpace - data.EmptyCargoSpace),2)}%)", $"{item.Units}{data.CargoUnitOfMeasure.ToString()} @ {item.PricePerUnit} = {item.LoadValue}", true); } return(_ret); }