/// <summary> /// Constructs the required type of command context that is used by this Discord bot. /// </summary> /// <param name="msg">The message to construct the context from.</param> /// <returns>The created context.</returns> public IDiscordBotCommandContext CreateCommandContext(SocketUserMessage msg) { return(new DiscordBotCommandContext(Services, Client, msg)); }
public Task <Result> Execute(SocketUserMessage e, CultureInfo info) { UserConfiguration.SetSetting(e.Author.Id, "Culture", info); return(TaskResult(info, "Successfully sat culture to " + info.DisplayName)); }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AdvancedCommandsMode"); return(TaskResult(result, "Advanced commands mode enabled: " + result.ToString())); }
public async Task GetBeatmapPack(string ID) { SocketUserMessage msg = await Context.Channel.SendMessageAsync("Fetching data...", attachID : true); IEnumerable <OsuBeatmap> beatmapPack = await OsuNetwork.DownloadBeatmapPack(int.Parse(ID), logger : msg); beatmapPack = beatmapPack.OrderBy(x => x.Difficulty.Rating).OrderBy(x => x.GameMode); OsuGameModes[] gameModes; //get amount of gamemodes present in the beatmapset { List <OsuGameModes> collector = new List <OsuGameModes>(); Tool.ForEach(beatmapPack, x => { if (!collector.Contains(x.GameMode)) { collector.Add(x.GameMode); } }); gameModes = collector.ToArray(); } OsuBeatmap packRef = beatmapPack.First(); OsuUser creator = await OsuNetwork.DownloadUser(packRef.Creator, OsuGameModes.STD, tolerateNull : true, maxAttempts : 3); EmbedBuilder eb = new EmbedBuilder(); eb.WithAuthor(x => { x.Name = packRef.Title; x.Url = packRef.URL; x.IconUrl = "https://cdn.discordapp.com/attachments/420948614966411299/421301562032390164/beatmapPackLogo.png"; }); eb.Image = $"{packRef.CoverPictureURL}"; //$"https://b.ppy.sh/thumb/{packRef.BeatmapSetID}l.jpg"; eb.Description = ""; if (creator != null) { eb.Description += $"Created By: [{creator.Username}]({creator.ProfileURL})\n"; } eb.Description += $"📥 **[Download]({packRef.DownloadURL(false)})**"; eb.Color = Color.FromArgb(28, 164, 185); eb.Thumbnail = packRef.ThumbnailPictureURL; eb.Footer = packRef.GetFooter(creator); eb.AddField(x => { x.Name = $"{packRef.Length} ⏱ {packRef.FavouriteCount} ❤️"; x.Value = $"BPM: **{string.Format("{0:0.##}", packRef.BPM)}**"; }); //Display beatmaps { void addBeatmapField(OsuGameModes gamemode, bool includeName) { eb.AddField(x => { x.Name = includeName ? $"{CustomEmoji.Osu.Gamemode.GetGamemodeEmoji(gamemode)} {OsuGameModesConverter.GameModeName(gamemode)}" : CustomEmoji.Void.ToString(); x.Value = "empty"; x.IsInline = true; }); } for (int i = 0; i < gameModes.Length; i++) { for (int ii = 0; ii < 2; ii++) { addBeatmapField(gameModes[i], ii == 0); } } OsuGameModes previousMode = OsuGameModes.None; int efbRef = 0; int efbPos = -1; foreach (OsuBeatmap beatmap in beatmapPack) { if (previousMode != beatmap.GameMode) { previousMode = beatmap.GameMode; efbPos++; efbRef = 0; } string beatmapVersion = beatmap.Version; if (beatmapVersion.Length > 14) { beatmapVersion = beatmapVersion.Substring(0, 14) + "..."; } string beatmapInfo = $"{CustomEmoji.Osu.Difficulty.GetDifficultyEmoji(beatmap.Difficulty.Rating, beatmap.GameMode)} **[{beatmapVersion}](https://osu.ppy.sh/b/{beatmap.BeatmapID})**\n"; // - *{string.Format("{0:0.##}", beatmap.Difficulty.Rating)}★* if (eb.Fields[efbPos * 2 + efbRef + 1].Value == "empty") { eb.Fields[efbPos * 2 + efbRef + 1].Value = beatmapInfo; } else { eb.Fields[efbPos * 2 + efbRef + 1].Value += beatmapInfo; } efbRef++; if (efbRef == 2) { efbRef = 0; } } } //Insert a zero width space char to make a new line or remove useless \n for (int i = 1; i < eb.Fields.Count; i++) { string efbStr = eb.Fields[i].Value.ToString(); if (i < eb.Fields.Count - 2) { eb.Fields[i].Value = efbStr + '\u200b'; } else { if (eb.Fields[i].Value == "empty") { eb.Fields.Remove(eb.Fields[i]); } else { eb.Fields[i].Value = efbStr.Remove(efbStr.Length - 1, 1); } } } await msg.EditAsync($"showing {beatmapPack.Count()} beatmaps", eb.Build()); }
public async Task GetBeatmap(string ID, string mode = null, string action = null) { SocketUserMessage msg = await Context.Channel.SendMessageAsync("Fetching data...", attachID : true); OsuGameModes gameMode = (string.IsNullOrEmpty(mode) ? OsuGameModes.None : OsuGameModesConverter.FromOfficialNumeration(byte.Parse(mode))); OsuBeatmap beatmap = await OsuNetwork.DownloadBeatmap(int.Parse(ID), gameMode, msg); gameMode = beatmap.GameMode; OsuUser creator = await OsuNetwork.DownloadUser(beatmap.Creator, OsuGameModes.STD, tolerateNull : true, maxAttempts : 3); Task <OsuScore[]> bestPlayDownloader = OsuNetwork.DownloadBeatmapBest(beatmap, gameMode, scoreCount: 3, logger: msg, tolerateNull: true, maxAttempts: 2); OsuBoundUserDB bound = await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Author.ID); Task <OsuScore[]> boundBestScoreDownloader = OsuNetwork.DownloadBeatmapBest(beatmap, gameMode, user: bound.UserID, logger: msg, tolerateNull: true, maxAttempts: 3); EmbedBuilder eb = beatmap.ToEmbedBuilder(gameMode, creator); OsuScore[] bestPlays = await bestPlayDownloader; await msg.EditAsync("Fetching best plays...", null); if (bestPlays[0] != null) { EmbedFieldBuilder rankingsField = new EmbedFieldBuilder { Name = $"{CustomEmoji.Osu.Gamemode.GetGamemodeEmoji(beatmap.GameMode)}", Value = "report to LtLi0n" }; OsuUser[] bestPlayUsers = new OsuUser[bestPlays.Length]; int longestName = int.MinValue; for (int i = 0; i < bestPlays.Length; i++) { bestPlayUsers[i] = await OsuNetwork.DownloadUser(bestPlays[i].Username, beatmap.GameMode, logger : msg, maxAttempts : 2); if (bestPlayUsers[i].Username.Length > longestName) { longestName = bestPlayUsers[i].Username.Length; } } for (int i = 0; i < bestPlayUsers.Length; i++) { string toAdd = bestPlays[i].ToScoreString(bestPlayUsers[i].Country, gameMode, i + 1, nameFormat: '\u200b'); if (i == 0) { rankingsField.Value = toAdd; } else { rankingsField.Value += toAdd; } } rankingsField.IsInline = true; eb.AddField(rankingsField); if (bound != null) { try { OsuScore boundBestScore = (await boundBestScoreDownloader)[0]; if (boundBestScore != null) { eb.AddField(x => { x.Name = $"Your best"; x.Value = boundBestScore.ToScoreString(bound.Country, gameMode, includeReplay: boundBestScore.HasReplay, nameFormat: '\u200b'); x.IsInline = true; }); } } catch (Exception e) { } } } else { string[] lines_f1 = eb.Fields[0].Value.ToString().Split('\n'); lines_f1[0] += "\t\t\u200b"; string convertBack = ""; Tool.ForEach(lines_f1, x => convertBack += (x + '\n')); eb.Fields[0].Value = convertBack; eb.Fields[1].Value = '\u200b'; } string additional = string.Empty; if (action != null) { additional = action.ToLower() == "json" ? $"```json\n{JValue.Parse(JsonConvert.SerializeObject(beatmap)).ToString(Formatting.Indented)}```" : string.Empty; } await msg.EditAsync((additional), embed : eb.Build()); }
private async Task HandleCommand(SocketUserMessage message, CommandRegistrationFindResult findResult) { var correlationId = Guid.NewGuid(); var logger = _logger.WithCommandScope(message, correlationId, findResult.Registration, findResult.Usage); var stopwatch = Stopwatch.StartNew(); var gatewayDelay = DateTimeOffset.UtcNow - message.Timestamp; var counter = Interlocked.Increment(ref _commandCounter); var guild = (message.Channel as IGuildChannel)?.Guild; // Don't log command content for non-guild channels, since these commands are usually meant to be private if (guild != null) { logger.LogInformation("Command {CommandCounter} {MessageContent} with {MessageAttachmentCount} attachments", counter, message.Content, message.Attachments.Count); } else { logger.LogInformation("Command {CommandCounter} {MessageContentRedacted} with {MessageAttachmentCount} attachments", counter, findResult.Prefix + findResult.Usage.InvokeUsage, message.Attachments.Count); } // Check if the channel type is valid for this command if (!IsValidCommandSource(message.Channel, findResult.Registration)) { logger.LogInformation("Command {CommandCounter} rejected in {TotalElapsed:F3}s (g: {GatewayElapsed:F3}s) due to invalid channel type", counter, stopwatch.Elapsed.TotalSeconds, gatewayDelay.TotalSeconds); if (message.Channel is ITextChannel && findResult.Registration.Flags.HasFlag(CommandFlags.DirectMessageOnly)) { await _communicator.CommandReplyDirectMessageOnly(message.Channel, findResult.Registration); } return; } // Check owner if (findResult.Registration.Flags.HasFlag(CommandFlags.OwnerOnly) && !_ownerIDs.Contains(message.Author.Id)) { logger.LogInformation("Command {CommandCounter} rejected in {TotalElapsed:F3}s (g: {GatewayElapsed:F3}s) due to the user not being an owner", counter, stopwatch.Elapsed.TotalSeconds, gatewayDelay.TotalSeconds); await _communicator.CommandReplyNotOwner(message.Channel, findResult.Registration); return; } // Check guild permisssions if (message.Channel is IGuildChannel guildChannel) { // User var guildUser = message.Author as IGuildUser; var missingPermissions = findResult.Registration.UserPermissions.Where(x => !guildUser.GuildPermissions.Has(x)); if (missingPermissions.Any()) { logger.LogInformation("Command {CommandCounter} rejected in {TotalElapsed:F3}s (g: {GatewayElapsed:F3}s) due to missing user permissions", counter, stopwatch.Elapsed.TotalSeconds, gatewayDelay.TotalSeconds); await _communicator.CommandReplyMissingPermissions(message.Channel, findResult.Registration, missingPermissions); return; } // Bot var selfUser = await guild.GetCurrentUserAsync(); var missingBotPermissions = findResult.Registration.BotPermissions.Where(x => !selfUser.GuildPermissions.Has(x)); if (missingBotPermissions.Any()) { logger.LogInformation("Command {CommandCounter} rejected in {TotalElapsed:F3}s (g: {GatewayElapsed:F3}s) due to missing bot permissions", counter, stopwatch.Elapsed.TotalSeconds, gatewayDelay.TotalSeconds); await _communicator.CommandReplyMissingBotPermissions(message.Channel, findResult.Registration, missingBotPermissions); return; } } var verificationElapsed = stopwatch.Elapsed; // Create command var parseResult = await _commandParser.Parse(message, findResult.Registration, findResult.Usage, findResult.Prefix); if (parseResult.Type != CommandParseResultType.Success) { string explanation = ""; switch (parseResult.Type) { case CommandParseResultType.NotEnoughParameters: explanation = Properties.Resources.Command_NotEnoughParameters; break; case CommandParseResultType.TooManyParameters: explanation = Properties.Resources.Command_TooManyParameters; break; case CommandParseResultType.InvalidParameterFormat: explanation = string.Format(Properties.Resources.Command_InvalidParameterFormat, ((InvalidParameterCommandParseResult)parseResult).InvalidPosition); break; } logger.LogInformation("Command {CommandCounter} rejected in {TotalElapsed:F3}s (g: {GatewayElapsed:F3}s) due to incorrect parameters", counter, stopwatch.Elapsed.TotalSeconds, gatewayDelay.TotalSeconds); await _communicator.CommandReplyIncorrectParameters(message.Channel, findResult.Registration, explanation, findResult.Prefix); return; } var command = new Command((SuccessCommandParseResult)parseResult, _communicator); var parsingElapsed = stopwatch.Elapsed; // Execute if (findResult.Registration.Flags.HasFlag(CommandFlags.Synchronous)) { await ExecuteCommandAsync(counter, correlationId, logger, findResult, command, stopwatch, verificationElapsed, parsingElapsed, gatewayDelay); } else { TaskHelper.FireForget(() => ExecuteCommandAsync(counter, correlationId, logger, findResult, command, stopwatch, verificationElapsed, parsingElapsed, gatewayDelay), x => logger.LogError(x, "Uncaught exception while handling command.")); } }
private async Task BadWords(SocketUserMessage message) { List <string> resList = new List <string>(); foreach (var bad in badWords) { if (WholeMatch(bad, message.Content)) { resList.Add(bad); } } resList = resList.Distinct().ToList(); string combined = ""; if (resList.Count != 0) { for (int i = 0; i < resList.Count; i++) { if (i != 0 && i == resList.Count - 1) { combined = combined.TrimEnd(','); combined += " and " + "\"" + resList[i] + "\""; } else { combined += "" + "\"" + resList[i] + "\""; if (resList.Count != 1) { combined += ", "; } } } await message.AddReactionAsync(new Emoji("😠")); int numWar = IncrementWarning(message.Author.DiscriminatorValue); if (numWar % 5 == 0) { Random rand = new Random(); int badIndex = rand.Next(badWords.Count); string name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(badWords[badIndex].ToLower()); try { if (db.GetUserIfBanned(message.Author.DiscriminatorValue) == null) { var author = message.Author as SocketGuildUser; string currentName = string.IsNullOrEmpty(author.Nickname) ? author.Username : author.Nickname; await(author).ModifyAsync(u => u.Nickname = name); await message.Channel.SendMessageAsync("Alright " + currentName + ". I've had enough of your little outbursts. Enjoy your new nickname. It will be changed back when your peers have forgiven you. \n (!forgive " + author.Mention + ")"); AddToBannedDb(author, name); } } catch (Exception ex) { await message.Channel.SendMessageAsync("Felix, you absolute f**k"); } } else if (db.LoadRecordsById(message.Author.DiscriminatorValue).DoWarn) { await message.Channel.SendMessageAsync(message.Author.ToString() + " said " + combined + ". You think that makes you seem cool? You now have " + numWar + " warning" + (numWar == 1 ? "" : "s")); } } }
bool HasPrefix(SocketUserMessage Message, char Prefix, ref int ArgPos) => Message.HasCharPrefix(Prefix, ref ArgPos);
bool SelfMention(SocketUserMessage Message, ref int ArgPos) => Message.HasMentionPrefix(Client.CurrentUser, ref ArgPos);
private async Task <bool> CanBotRunCommandsAsync(SocketUserMessage msg) => await Task.Run(() => msg.Author.Id == client.CurrentUser.Id);
bool InvalidMessage(SocketUserMessage Message, ref int ArgPos) { return(!HasPrefix(Message, '!', ref ArgPos) || SelfMention(Message, ref ArgPos) || Message.Author.IsBot); }
public ScopedCommandContext(IServiceScope serviceScope, DiscordSocketClient client, SocketUserMessage msg) : base(client, msg) { ServiceScope = serviceScope; }
public CancelableSocketContext(DiscordSocketClient client, SocketUserMessage msg) : base(client, msg) { }
private bool CanUseFilteredWords(SocketUserMessage msg) { return(msg.Author.IsBot || (msg.Author as IGuildUser).GetPermissionLevel(_dataService.Configuration) >= PermissionLevel.Moderator); }
/// <summary> /// Updates user XP and saves the server /// </summary> /// <param name="msg"> /// The msg. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task DoLevelsAsync(SocketUserMessage msg) { if (msg.Channel is IDMChannel) { return; } var gChannel = msg.Channel as IGuildChannel; var guild = gChannel.Guild as SocketGuild; var gUser = msg.Author as SocketGuildUser; var levels = Service.GetLevelSetup(guild.Id); if (levels == null) { return; } if (!levels.Settings.Enabled) { return; } if (!levels.Users.ContainsKey(msg.Author.Id)) { levels.Users.TryAdd(msg.Author.Id, new LevelService.LevelSetup.LevelUser(msg.Author.Id)); levels.Save(); return; } var levelUser = levels.Users[msg.Author.Id]; if (levelUser.LastUpdate > DateTime.UtcNow) { return; } levelUser.XP += 10; levelUser.LastUpdate = DateTime.UtcNow + TimeSpan.FromMinutes(1); var requiredXP = (levelUser.Level * 50) + ((levelUser.Level * levelUser.Level) * 25); if (levelUser.XP > requiredXP) { levelUser.Level++; string roleAdded = null; if (levels.RewardRoles.Any()) { var roles = GetRoles(levels, levelUser); var rolesToReceive = roles.Key; var rolesAvailable = roles.Value; if (rolesToReceive.Count != 0) { foreach (var role in rolesToReceive) { if (((IGuildUser)msg.Author).RoleIds.Contains(role.RoleID)) { continue; } var socketRole = guild.GetRole(role.RoleID); if (socketRole != null) { try { await gUser.AddRoleAsync(socketRole); roleAdded += $"Role Reward: {socketRole.Name}\n"; } catch { // Ignored } } else { levels.RewardRoles.Remove(role); } } await RemoveRolesAsync(gUser, guild, rolesToReceive, rolesAvailable); } } await DoResponseAsync(msg, levels, levelUser, requiredXP, roleAdded); } levels.Save(); }
private async Task w_Async(SocketUserMessage message) { try { if (Helper.isChannelEnabled(message.Channel.Id.ToString())) { string blancOutput = Helper.blanc_w_Output; int[] inputNumbers = null; int[] randNumbers = null; string reply = ""; int sum = 0; MatchCollection values = new Regex(@"\d+").Matches(message.Content); inputNumbers = new int[values.Count]; for (int i = 0; i < values.Count; i++) { inputNumbers[i] = Int32.Parse(values[i].ToString()); } randNumbers = new int[inputNumbers[0]]; if (inputNumbers.Length == 1) { #region Logik_w3 if (inputNumbers[0] < 1) { await ReplyManager.send_Async(message, "Syntax Error", "❗Syntax Error : Eingabe muss größer als 0 sein!"); return; } else { randNumbers[0] = Helper.getRandomNumber(inputNumbers[0]); //Output zusammenbauen blancOutput = blancOutput.Replace("+", ""); reply += blancOutput; reply = reply.Replace("$RANDNUMBER$", randNumbers[0].ToString()); sum = randNumbers[0]; reply = reply.Replace("$SUM$", sum.ToString()); reply = reply.Replace("$ADD$", ""); reply = reply.Replace("$RESULT$", (sum).ToString()); await ReplyManager.send_Async(message, reply); Helper.setLastSendMsgAndFunc(message.Author.Id.ToString(), new Tuple <Func <SocketUserMessage, Task>, SocketUserMessage>(w_Async, message)); } #endregion } else if (inputNumbers.Length == 2) { if (message.Content.Contains("+") || message.Content.Contains("-")) { #region Logik_w3+3 if (inputNumbers[0] < 1) { await ReplyManager.send_Async(message, "Syntax Erro", "❗Syntax Error : Eingabe muss größer als 0 sein!"); return; } else { if (message.Content.Contains("-")) { inputNumbers[1] = -inputNumbers[1]; //letzte zahl umkehren blancOutput = blancOutput.Replace("+", ""); } //______________Logik w3+3______________________ randNumbers[0] = Helper.getRandomNumber(inputNumbers[0]); //Output zusammenbauen reply += blancOutput; reply = reply.Replace("$RANDNUMBER$", randNumbers[0].ToString()); sum = randNumbers[0]; reply = reply.Replace("$SUM$", sum.ToString()); reply = reply.Replace("$ADD$", inputNumbers[1].ToString()); reply = reply.Replace("$RESULT$", (sum + inputNumbers[1]).ToString()); await ReplyManager.send_Async(message, reply); Helper.setLastSendMsgAndFunc(message.Author.Id.ToString(), new Tuple <Func <SocketUserMessage, Task>, SocketUserMessage>(w_Async, message)); } #endregion } else { #region Logik_3w3 if (inputNumbers[0] < 1 || inputNumbers[1] < 1) { await ReplyManager.send_Async(message, "Syntax Erro", "❗Syntax Error : Eingabe muss größer als 0 sein!"); return; } else { //______________Logik 3w3______________________ for (int i = 0; i < inputNumbers[0]; i++) //random zahlen generieren { randNumbers[i] = Helper.getRandomNumber(inputNumbers[1]); } //Output zusammenbauen reply += blancOutput; reply = reply.Replace("$RANDNUMBER$", randNumbers[0] + "+$RANDNUMBER$"); sum = randNumbers[0]; for (int i = 1; i < randNumbers.Length; i++) { reply = reply.Replace("$RANDNUMBER$", randNumbers[i] + "+$RANDNUMBER$"); sum += randNumbers[i]; } reply = reply.Replace("+$RANDNUMBER$", ""); reply = reply.Replace("$SUM$", sum.ToString()); reply = reply.Replace("+$ADD$", ""); reply = reply.Replace("$RESULT$", (sum).ToString()); await ReplyManager.send_Async(message, reply); Helper.setLastSendMsgAndFunc(message.Author.Id.ToString(), new Tuple <Func <SocketUserMessage, Task>, SocketUserMessage>(w_Async, message)); } #endregion } } else if (inputNumbers.Length == 3 || inputNumbers[1] < 1) //3w3+3 OR 3w3-3 { #region Logik_3w3+3 if (inputNumbers[0] < 1) { await ReplyManager.send_Async(message, "Syntax Erro", "❗Syntax Error : Eingabe muss größer als 0 sein!"); return; } else { if (message.Content.Contains("-")) { inputNumbers[2] = 0 - inputNumbers[2]; //letzte zahl umkehren blancOutput = blancOutput.Replace("+", ""); } //______________Logik 3w3+3______________________ for (int i = 0; i < inputNumbers[0]; i++) //random zahlen generieren { randNumbers[i] = Helper.getRandomNumber(inputNumbers[1]); } //Output zusammenbauen reply += blancOutput; reply = reply.Replace("$USERNAME$", message.Author.Username); reply = reply.Replace("$RANDNUMBER$", randNumbers[0] + "+$RANDNUMBER$"); sum = randNumbers[0]; for (int i = 1; i < randNumbers.Length; i++) { reply = reply.Replace("$RANDNUMBER$", randNumbers[i] + "+$RANDNUMBER$"); sum += randNumbers[i]; } reply = reply.Replace("+$RANDNUMBER$", ""); reply = reply.Replace("$SUM$", sum.ToString()); reply = reply.Replace("$ADD$", inputNumbers[2].ToString()); reply = reply.Replace("$RESULT$", (sum + inputNumbers[2]).ToString()); await ReplyManager.send_Async(message, reply); Helper.setLastSendMsgAndFunc(message.Author.Id.ToString(), new Tuple <Func <SocketUserMessage, Task>, SocketUserMessage>(w_Async, message)); } #endregion } } } catch (Exception) { await ReplyManager.send_Async(message, "Exception in w_Async... Versuche es bitte erneut mit anderen Inputs..."); } }
/// <summary> /// Handles the message if it is not a command. /// </summary> /// <param name="message"> /// The message. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> private static async Task PostCommand(SocketUserMessage message) { int luckyNumber = Globals.Random.Next(0, 1000); if (luckyNumber == 166) { await message.Channel.SendMessageAsync("This feels gay"); } if (MiscCommands.NumberGameInstances.TryGetValue(message.Channel.Id, out NumberGame game) && message.Author.Id == game.PlayerUser.Id) { if (int.TryParse(message.Content, out int guess)) { await game.GuessNumber(guess); if (game.IsGameOver) { MiscCommands.NumberGameInstances.Remove(message.Channel.Id); } return; } } if (message.Content.ToLower().Contains("hello") && message.MentionedUsers.Any(e => e.Id == Program.Client.CurrentUser.Id)) { await message.Channel.SendMessageAsync($"Hello {message.Author.Username}!"); } if (message.Content.Contains("(╯°□°)╯︵ ┻━┻")) { await message.Channel.SendMessageAsync("┬─┬ ノ( ゜-゜ノ)"); return; } if (message.Content.Contains("┬─┬ ノ( ゜-゜ノ)")) { await message.Channel.SendMessageAsync("https://youtu.be/To6nhootM3w"); return; } if (message.Content.ToLower().Contains("no u") && Globals.Random.NextDouble() < 0.3) { await message.Channel.SendMessageAsync("no u"); return; } if (message.Content.ToLower().Contains("boo") && message.Content.ToLower().Contains("u") && message.MentionedUsers.Any(e => e.Id == Program.Client.CurrentUser.Id)) { string booU = "boo"; for (int i = 0; i < Globals.Random.Next(7); i++) { booU += "o"; } booU += " "; for (int i = -1; i < Globals.Random.Next(7); i++) { booU += "u"; } await message.Channel.SendMessageAsync($"no {booU} {message.Author.Mention}"); return; } if (message.Content.ToLower().Contains("f**k") && (message.Content.ToLower().Contains("you") || message.Content.ToLower().Contains(" u")) && message.MentionedUsers.Any(e => e.Id == Program.Client.CurrentUser.Id)) { await message.Channel.SendMessageAsync("~~Please do~~"); } }
private async Task swd_Async(SocketUserMessage message) { try { if (Helper.isChannelEnabled(message.Channel.Id.ToString())) { string blancOutput = Helper.blanc_swd_Output; int[] inputNumbers = null; Tuple <int, string> explodingDice0 = null; Tuple <int, string> explodingDice1 = null; string reply = ""; MatchCollection values = new Regex(@"\d+").Matches(message.Content); inputNumbers = new int[3]; inputNumbers[2] = 0; for (int i = 0; i < values.Count; i++) { inputNumbers[i] = Int32.Parse(values[i].ToString()); } if (inputNumbers[0] < 2 || inputNumbers[1] < 2) { await ReplyManager.send_Async(message, "Syntax Error", "❗Syntax Error : Eingabe muss größer als 1 sein!"); return; } else { explodingDice0 = Helper.getExplodingDice(inputNumbers[0]); explodingDice1 = Helper.getExplodingDice(inputNumbers[1]); //Output zusammenbauen if (message.Content.Count(x => x == ',') == 2 || message.Content.Contains("+") || message.Content.Contains("-")) { if (message.Content.Contains("-")) //nachricht enthält minus { inputNumbers[2] = -inputNumbers[2]; //letzte zahl umkehren blancOutput = blancOutput.Replace("+$ADD$", "$ADD$"); } } else { blancOutput = blancOutput.Replace("+$ADD$ ", ""); } if (!explodingDice0.Item2.Contains("+")) //Addition wird nicht benötigt { blancOutput = blancOutput.Replace("Rechnung: $RANDNUMBERS0$\nSumme", "Ergebnis"); } if (!explodingDice1.Item2.Contains("+")) //Addition wird nicht benötigt { blancOutput = blancOutput.Replace("Rechnung: $RANDNUMBERS1$\nSumme", "Ergebnis"); } reply += blancOutput; reply = reply.Replace("$INPUTNUMBER0$", inputNumbers[0].ToString()); reply = reply.Replace("$INPUTNUMBER1$", inputNumbers[1].ToString()); reply = reply.Replace("$RANDNUMBERS0$", explodingDice0.Item2); reply = reply.Replace("$RANDNUMBERS1$", explodingDice1.Item2); reply = reply.Replace("$SUM0$", explodingDice0.Item1.ToString()); reply = reply.Replace("$SUM1$", explodingDice1.Item1.ToString()); reply = reply.Replace("$ADD$", inputNumbers[2].ToString()); reply = reply.Replace("$RESULT$", (explodingDice0.Item1 + explodingDice1.Item1 + inputNumbers[2]).ToString()); await ReplyManager.send_Async(message, reply); Helper.setLastSendMsgAndFunc(message.Author.Id.ToString(), new Tuple <Func <SocketUserMessage, Task>, SocketUserMessage>(swd_Async, message)); } } } catch (Exception) { await ReplyManager.send_Async(message, "Exception in sww_Async... Versuche es bitte erneut mit anderen Inputs..."); } }
private async Task <CommandRegistrationFindResult> FindCommandRegistrationAsync(SocketUserMessage userMessage) { var prefix = _defaultCommandPrefix; if (userMessage.Channel is ITextChannel guildChannel) { var guildConfig = await _guildConfigProvider.GetConfigAsync(guildChannel.GuildId); if (!string.IsNullOrEmpty(guildConfig?.CustomCommandPrefix)) { prefix = guildConfig.CustomCommandPrefix; } } // Check prefix if (!userMessage.Content.StartsWith(prefix)) { return(null); } // Check if the message contains a command invoker var invoker = _commandParser.ParseInvoker(userMessage.Content, prefix); if (string.IsNullOrEmpty(invoker)) { return(null); } lock (_commandsMappingLock) { // Try to find command registrations for this invoker List <CommandInfo> commandRegistrations; if (!_commandsMapping.TryGetValue(invoker.ToLowerInvariant(), out commandRegistrations)) { return(null); } var match = _commandParser.Match(userMessage.Content, prefix, commandRegistrations); if (match == null) { return(null); } var(registration, usage) = match.Value; return(new CommandRegistrationFindResult(prefix, registration, usage)); } }
public override async Task ReactAsync(SocketUserMessage msg) { _ = base.ReactAsync(msg); _ = GoldenSun.AwardClassSeries("Curse Mage Series", msg.Author, msg.Channel); await Task.CompletedTask; }
public async Task GetRecent([Remainder] string target = null) { SocketUserMessage msg = await Context.Channel.SendMessageAsync("Fetching data...", attachID : true); ulong?targetID = null; string username = string.Empty; string country = string.Empty; OsuGameModes gameMode = OsuGameModes.STD; if (string.IsNullOrEmpty(target)) { OsuBoundUserDB bound = await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Author.ID); if (bound != null) { targetID = bound.UserID; country = bound.Country; username = bound.UserName; gameMode = bound.MainMode; } else { await msg.EditAsync($"You were not found in the database.\n" + $"To use this command without parameters, proceed to bind your profile with `$osubind [username]`", null); } } else { if (target.Where(x => x < '0' || x > '9').Count() > 0) { //Not ID } else { targetID = ulong.Parse(target); } } OsuUserRecent recent = await OsuNetwork.DownloadUserRecent(targetID.Value, gameMode); OsuBeatmap beatmap = await OsuNetwork.DownloadBeatmap(recent.BeatmapID, gameMode); if (beatmap == null) { await msg.EditAsync("", null); } else { OsuUser beatmapCreator = await OsuNetwork.DownloadUser(beatmap.Creator, gameMode); EmbedBuilder eb = beatmap.ToEmbedBuilder(gameMode, beatmapCreator, true); eb.Fields.Insert(0, new EmbedFieldBuilder { Name = $"Recent {CustomEmoji.Osu.Gamemode.GetGamemodeEmoji(gameMode)}", Value = recent.ToScoreString(country, gameMode, username, nameFormat: '\u200b') }); await msg.EditAsync("", eb.Build()); } }
internal CommandContext(DiscordSocketClient client, SocketUserMessage msg, string[] args) : base(client, msg) { Args = args; ArgCnt = args.Length; }
private static async Task OsuFlexible(string username, CommandEventArgs Context, OsuGameModes gamemode = OsuGameModes.None) { if (Context.Message.Mentions.Length > 1) { await Context.Channel.SendMessageAsync("AAAA Too many mentions, calm down.\nOne at a time :)"); return; } OsuBoundUserDB boundUser = string.IsNullOrEmpty(username) ? boundUser = await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Author.ID) : Context.Message.Mentions.Length == 1 ? await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Mentions[0]) : await OsuDB.GetBoundUserBy_UserName(username); if (Context.Message.Mentions.Length == 1 && boundUser == null) { await Context.Channel.SendMessageAsync("Mentioned user is not binded."); return; } if (boundUser != null) { username = boundUser.UserName; } else if (string.IsNullOrEmpty(username)) { await Context.Channel.SendMessageAsync( "You don't exist in the database yet." + "Do `$osubind [username]` to continue the use of `$osu` without parameters."); } OsuGameModes gameMode = gamemode == OsuGameModes.None ? (boundUser != null ? boundUser.MainMode : OsuGameModes.STD) : gamemode; SocketUserMessage msg = await Context.Channel.SendMessageAsync("Fetching data...", attachID : true); OsuUser osuUser = await OsuNetwork.DownloadUser(username, gameMode, maxAttempts : 2); EmbedBuilder eb = new EmbedBuilder(); double progressDebug = osuUser.OsuLevel.Progress; eb.Description = $"*• PP:* __***{Math.Round(osuUser.PP, 2, MidpointRounding.AwayFromZero)}***__\n" + $"*• Accuracy:* __***{string.Format("{0:0.##}", osuUser.Accuracy)}%***__\n" + $"*• Level:* __***{osuUser.OsuLevel.Level}***__ ~~-~~ *{osuUser.OsuLevel.Progress.ToString("#0.000%")}*"; if (boundUser != null) { //Get all entries of tracked user gameplay statistics OsuGameModes[] userGameModes = OsuGameModesConverter.ToGameModesArray(boundUser.GameModes); OsuGameModeUserDB[] gameModeUsers = new OsuGameModeUserDB[userGameModes.Length]; for (int i = 0; i < userGameModes.Length; i++) { gameModeUsers[i] = await OsuDB.GetGameModeUserBy_OsuID(boundUser.UserID, userGameModes[i]); } if (userGameModes.Length > 0) { for (int i = 0; i < userGameModes.Length; i++) { string emoji = CustomEmoji.Osu.Gamemode.GetGamemodeEmoji(userGameModes[i]).ToString(); eb.AddField(x => { x.Name = $"{emoji} Total Hits {Enum.GetName(typeof(OsuGameModes), userGameModes[i])} {CustomEmoji.TotalHits_Anim}"; if (gameModeUsers[i] != null) { string hitsDaily = gameModeUsers[i].HitsDaily / 10000 > 0 ? gameModeUsers[i].HitsDaily.ToString("#,#", CultureInfo.InvariantCulture) : gameModeUsers[i].HitsDaily.ToString(); string hitsWeekly = gameModeUsers[i].HitsWeekly / 10000 > 0 ? gameModeUsers[i].HitsWeekly.ToString("#,#", CultureInfo.InvariantCulture) : gameModeUsers[i].HitsWeekly.ToString(); string hitsMonthly = gameModeUsers[i].HitsMonthly / 10000 > 0 ? gameModeUsers[i].HitsMonthly.ToString("#,#", CultureInfo.InvariantCulture) : gameModeUsers[i].HitsMonthly.ToString(); string hitsSince = gameModeUsers[i].HitsSince / 10000 > 0 ? gameModeUsers[i].HitsSince.ToString("#,#", CultureInfo.InvariantCulture) : gameModeUsers[i].HitsSince.ToString(); string totalHits = gameModeUsers[i].TotalHits / 10000 > 0 ? gameModeUsers[i].TotalHits.ToString("#,#", CultureInfo.InvariantCulture) : gameModeUsers[i].TotalHits.ToString(); x.Value = $"*Today:* ***{hitsDaily}***\n" + $"*This Week:* ***{hitsWeekly}***\n" + $"*This Month:* ***{hitsMonthly}***\n" + $"*Since:* ***{hitsSince}*** / ***{totalHits}***"; } else { x.Value = $"No stored data has been found yet.\n" + $"Wait for the next update.\n" + $"*maximum waiting time - 1 minute*"; } if (gameModeUsers.Length > 2 && i < 2) { x.Value += "\n\u200b"; } else if (i == 0) { x.Value += "\t\t\t\u200b"; } x.IsInline = true; }); } } } eb.WithAuthor(x => { x.IconUrl = CustomEmoji.Osu.Gamemode.GetGamemodeEmoji(gameMode).URL; x.Name = osuUser.Username; x.Url = osuUser.ProfileURL; }); eb.Color = Color.LightPink; eb.Thumbnail = osuUser.AvatarURL; await msg.EditAsync("", eb.Build()); }
internal CommandContext(DiscordSocketClient client, SocketUserMessage msg) : base(client, msg) { Args = msg.Content.Split(" "); Args[0] = Args[0].Substring(1); ArgCnt = Args.Length; }
private static async Task HandleCommand(Input input) { int argPos = input.ArgumentPosition ?? 0; SocketUserMessage message = input.Message; // Create a Command Context SocketCommandContext context = new SocketCommandContext(client, message); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully) IResult result = await commands.ExecuteAsync(context, argPos, services); string commandResult; if (result.Error == CommandError.UnknownCommand) { Dictionary <string, int> messageCompareValues = new Dictionary <string, int>(); foreach (Type commandClass in commandClasses) { MemberInfo[] memInfo = commandClass.GetMembers(); foreach (MemberInfo memberInfo in memInfo) { string resultCommand = ""; Object[] att = memberInfo.GetCustomAttributes(typeof(CommandAttribute), false); if (att.Length == 0) { continue; } Type parent = commandClass; while (parent != null) { Object[] classAtt = parent.GetCustomAttributes(typeof(GroupAttribute), false); if (classAtt.Length != 0) { resultCommand = ((GroupAttribute)classAtt[0]).Prefix + " " + resultCommand; } parent = parent.DeclaringType; } resultCommand += ((CommandAttribute)att[0]).Text; string copMessage = message.Content.Substring(1); int stringValue; while (copMessage.Contains(" ")) { stringValue = Helper.CalcLevenshteinDistance(resultCommand, copMessage); if (!messageCompareValues.ContainsKey(resultCommand)) { messageCompareValues.Add(resultCommand, stringValue); } if (messageCompareValues[resultCommand] > stringValue) { messageCompareValues[resultCommand] = stringValue; } copMessage = copMessage.Substring(0, copMessage.LastIndexOf(" ")); } stringValue = Helper.CalcLevenshteinDistance(resultCommand, copMessage); if (!messageCompareValues.ContainsKey(resultCommand)) { messageCompareValues.Add(resultCommand, stringValue); } if (messageCompareValues[resultCommand] > stringValue) { messageCompareValues[resultCommand] = stringValue; } } } commandResult = String.Join(Environment.NewLine, messageCompareValues.Where(d => d.Value == messageCompareValues.Values.Min()).Select(k => k.Key)); //await context.Channel.SendMessageAsync($"Sorry, I dont know what you are saying ¯\\_(ツ)_/¯, but did you mean: {commandResult}"); EmbedBuilder embed = new EmbedBuilder() .WithColor(new Color((uint)Convert.ToInt32(CommandHandlerService.MessageAuthor.EmbedColor, 16))) .WithCurrentTimestamp() .WithFooter(NET.DataAccess.File.FileAccess.GENERIC_FOOTER, NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL) .WithThumbnailUrl("https://sallynet.blob.core.windows.net/content/question.png") .WithTitle("Sorry, I dont know what you are saying ¯\\_(ツ)_/¯") .AddField("I have following commands, which might be correct", commandResult); await context.Channel.SendMessageAsync(embed : embed.Build()); return; } //Error Handler if (!result.IsSuccess) { await context.Channel.SendMessageAsync($"{result.ErrorReason} ¯\\_(ツ)_/¯"); } logger.Info($"{context.Message.Content} from {context.Message.Author}"); }
public async Task InspectAsync(SocketUserMessage message, string property = null) { var result = Inspect <SocketMessage>(message, property); await ReplyAsync("", embed : result); }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AutoLooking"); return(TaskResult(result, "Autolooking on voice channels enabled: " + result.ToString())); }
public abstract Task ProcessMessage(SocketUserMessage input);
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AllowSnooping"); return(TaskResult(result, "Bot snooping enabled: " + result.ToString())); }
public ScopedSocketCommandContext(DiscordSocketClient client, SocketUserMessage msg, IServiceScope serviceScope) : base(client, msg) { ServiceScope = serviceScope ?? throw new ArgumentNullException(nameof(serviceScope)); }