private async Task PaginateResult(SocketCommandContext context, string title, List <ShareCentral> orderedList) { List <string> playlistsString = new List <string>(); int pageAmount = (int)Math.Ceiling(orderedList.Count / 7.0); int addToJ = 0; int amountLeft = orderedList.Count; for (int i = 0; i < pageAmount; i++) { string addToList = ""; for (int j = 0; j < (amountLeft > 7 ? 7 : amountLeft); j++) { var sharedPlaylist = orderedList[j + addToJ]; addToList += $"{(sharedPlaylist.IsPrivate ? "[P] " : "")}**[{sharedPlaylist.Titel}]({sharedPlaylist.ShareLink})**\nVotes: {sharedPlaylist.Upvotes} / {sharedPlaylist.Downvotes} \tTags: {sharedPlaylist.Tags.Replace(";", " - ")}\n\n"; } playlistsString.Add(addToList); amountLeft -= 7; addToJ += 7; } if (pageAmount > 1) { var pmsg = new PaginatedMessage() { Author = new EmbedAuthorBuilder() { IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar, Name = context.User.Username }, Color = Utility.PurpleEmbed, Title = title, Options = new PaginatedAppearanceOptions() { DisplayInformationIcon = false, Timeout = TimeSpan.FromSeconds(60), InfoTimeout = TimeSpan.FromSeconds(60) }, Content = "Only the invoker may switch pages, ⏹ to stop the pagination", Pages = playlistsString }; Criteria <SocketReaction> criteria = new Criteria <SocketReaction>(); criteria.AddCriterion(new EnsureReactionFromSourceUserCriterionMod()); await _interactive.SendPaginatedMessageAsync(context, pmsg, criteria); } else { var eb = new EmbedBuilder() { Author = new EmbedAuthorBuilder() { IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar, Name = context.User.Username }, Color = Utility.PurpleEmbed, Title = title, Description = playlistsString[0], Footer = new EmbedFooterBuilder() { Text = "Page 1/1" } }; await context.Channel.SendMessageAsync("", embed : eb); } }
public async Task Marry(SocketCommandContext context, SocketUser user) { //Check if its urself if (user.Id == context.User.Id) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"You can't and shouldn't marry yourself ;_;")); return; } using (var soraContext = new SoraContext()) { var requestorDb = Utility.GetOrCreateUser(context.User.Id, soraContext); var askedDb = Utility.GetOrCreateUser(user.Id, soraContext); int allowedMarriagesRequestor = ((int)(Math.Floor((double)(ExpService.CalculateLevel(requestorDb.Exp) / 10)))) + 1; int allowedMarriagesAsked = ((int)(Math.Floor((double)(ExpService.CalculateLevel(askedDb.Exp) / 10)))) + 1; //check both limits if (requestorDb.Marriages.Count >= allowedMarriagesRequestor) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(context.User)}, you already reached your marriage limit. Level up to increase it")); return; } if (askedDb.Marriages.Count >= allowedMarriagesAsked) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(user)} already reached their marriage limit. They must level up to increase the limit")); //TODO this sounds like shit. change it return; } //Check for duplicate if (requestorDb.Marriages.Any(x => x.PartnerId == user.Id) || askedDb.Marriages.Any(x => x.PartnerId == context.User.Id)) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"You cannot marry someone twice!")); return; } //Proceed to ask for marriage var msg = await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.PurpleEmbed, Utility.SuccessLevelEmoji[4], $"{Utility.GiveUsernameDiscrimComb(user)}, do you want to marry {Utility.GiveUsernameDiscrimComb(context.User)}? 💍")); Criteria <SocketMessage> criteria = new Criteria <SocketMessage>(); criteria.AddCriterion(new EnsureFromUserInChannel(user.Id, context.Channel.Id)); var response = await _interactive.NextMessageAsync(context, criteria, TimeSpan.FromSeconds(45)); if (response == null) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(user)} didn't answer in time >.<")); return; } if ((!response.Content.Contains(" yes ", StringComparison.OrdinalIgnoreCase) && !response.Content.Contains(" yes,", StringComparison.OrdinalIgnoreCase) && !response.Content.Contains("yes ", StringComparison.OrdinalIgnoreCase) && !response.Content.Contains("yes,", StringComparison.OrdinalIgnoreCase)) && !response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase)) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"{Utility.GiveUsernameDiscrimComb(user)} didn't answer with a yes ˚‧º·(˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ )‧º·˚")); return; } //Answer contains a yes requestorDb.Marriages.Add(new Marriage() { PartnerId = user.Id, Since = DateTime.UtcNow }); //_soraContext.SaveChangesThreadSafe(); askedDb.Marriages.Add(new Marriage() { PartnerId = context.User.Id, Since = DateTime.UtcNow }); await soraContext.SaveChangesAsync(); } await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.PurpleEmbed, Utility.SuccessLevelEmoji[4], $"You are now married 💑").WithImageUrl("https://media.giphy.com/media/iQ5rGja9wWB9K/giphy.gif")); }
/// <summary>Creates a poll with specified question and choices. /// </summary> public static async Task CreatePollAsync(string question, string choice1, string choice2, SocketCommandContext context) { var pollEmbed = new EmbedBuilder() .WithTitle(question) .WithDescription($":one: {choice1}\n\n:two: {choice2}") .WithColor(0x268618) .WithFooter($"Poll created by: {context.User}"); var sentMessage = await context.Channel.SendMessageAsync(embed : pollEmbed.Build()); var one = new Emoji("1️⃣"); var two = new Emoji("2️⃣"); await sentMessage.AddReactionsAsync(new[] { one, two }); }
public Task <bool> JudgeAsync(SocketCommandContext sourceContext, SocketReaction parameter) { var ok = parameter.UserId == sourceContext.User.Id; return(Task.FromResult(ok)); }
public DiscordIntegratedEnqueueResult EnqueueWithDiscordRole(ulong userId, FFXIVRole role, IRole discordRole, SocketCommandContext context, string eventId) { if (context.Guild == null) { return(DiscordIntegratedEnqueueResult.NoGuild); } if (!context.Guild.GetUser(userId).HasRole(discordRole)) { return(DiscordIntegratedEnqueueResult.DoesNotHaveRole); } var queue = GetQueue(role); lock (queue) { if (queue.Any(s => EventValid(eventId)(s) && s.Id == userId)) { return(DiscordIntegratedEnqueueResult.AlreadyInQueue); } eventId ??= ""; var slot = new QueueSlot(userId, eventId, roleIds: new[] { discordRole.Id }); queue.Add(slot); return(DiscordIntegratedEnqueueResult.Success); } }
public Task <bool> JudgeAsync(SocketCommandContext sourceContext, SocketMessage parameter) { var ok = _id == parameter.Author.Id; return(Task.FromResult(ok)); }
private async Task OnMessageReceivedAsync(SocketMessage s) { SocketUserMessage msg = s as SocketUserMessage; // Ensure the message is from a user/bot if (msg == null) { return; } if (msg.Author.Id == _discord.CurrentUser.Id) { return; // Ignore self when checking commands } if (msg.Channel.ToString().StartsWith('@')) { return; // Ignore DMs } var context = new SocketCommandContext(_discord, msg); // Create the command context var guild = context.Guild; var user = guild.Users.FirstOrDefault(iterator => iterator.Id == msg.Author.Id); if (user == null) { return; } var isUserAdmin = user.GuildPermissions.Administrator; if (string.IsNullOrWhiteSpace(msg.Content)) { return; } if (await BotDetector.Instance.ScanMessage(context, msg)) // returns true if an action was taken { return; //don't evaluate further if an action was taken } if (await OwlBrain.ReportSuspiciousness(context, msg)) // returns true if an action was taken { return; //don't evaluate further if an action was taken } var mentionnedUsers = s.MentionedUsers; var mentionnedRoles = s.MentionedRoles; var msgParts = msg.Content.Split(" "); if (isUserAdmin) { switch (msgParts[0].ToUpper()) { case "ORLY.HELP": await Handlers.HELP(context); return; case "ORLY.ADD_BLACKLISTED_ROLES": await Handlers.ADD_BLACKLISTED_ROLES(msg, context, guild); return; case "ORLY.REMOVE_BLACKLISTED_ROLES": await Handlers.REMOVE_BLACKLISTED_ROLES(msg, context, guild); return; case "ORLY.CLEAR_BLACKLISTED_ROLES": await Handlers.CLEAR_BLACKLISTED_ROLES(context, guild); return; case "ORLY.SHOW_BLACKLISTED_ROLES": await Handlers.SHOW_BLACKLISTED_ROLES(context, guild); return; case "ORLY.SET_REPORT_CHANNEL": await Handlers.SET_REPORT_CHANNEL(s, context, guild); return; case "ORLY.DISABLE_REPORT_CHANNEL": await Handlers.DISABLE_REPORT_CHANNEL(context, guild); return; case "ORLY.SHOW_REPORT_CHANNEL": await Handlers.SHOW_REPORT_CHANNEL(context, guild); return; case "ORLY.ADD_SUSPICIOUS_WORDS": await Handlers.ADD_SUSPICIOUS_WORDS(msg, context, guild, msgParts); return; case "ORLY.REMOVE_SUSPICIOUS_WORDS": await Handlers.REMOVE_SUSPICIOUS_WORDS(msg, context, guild, msgParts); return; case "ORLY.CLEAR_SUSPICIOUS_WORDS": await Handlers.CLEAR_SUSPICIOUS_WORDS(context, guild); return; case "ORLY.SHOW_SUSPICIOUS_WORDS": await Handlers.SHOW_SUSPICIOUS_WORDS(context, guild); return; case "ORLY.ADD_IGNORED_CHANNELS": await Handlers.ADD_IGNORED_CHANNELS(msg, context, guild); return; case "ORLY.REMOVE_IGNORED_CHANNELS": await Handlers.REMOVE_IGNORED_CHANNELS(msg, context, guild); return; case "ORLY.CLEAR_IGNORED_CHANNELS": await Handlers.CLEAR_IGNORED_CHANNELS(context, guild); return; case "ORLY.SHOW_IGNORED_CHANNELS": await Handlers.SHOW_IGNORED_CHANNELS(context, guild); return; } } }
private async Task MessageReceived(SocketMessage rawMessage) { // Ignore system messages and messages from bots if (!(rawMessage is SocketUserMessage message)) { return; } if (message.Source != MessageSource.User) { return; } var context = new SocketCommandContext(_discord, message); if (hasLatexMathQuotes(message.Content)) { var latexTypingState = context.Channel.EnterTypingState(); string formattedLatex = formatLatexString(message.Content); var pictureService = new PictureService(new System.Net.Http.HttpClient()); var image = pictureService.GetLatexImage(formattedLatex).Result; image.Seek(0, SeekOrigin.Begin); await context.Channel.SendFileAsync(image, "latex.png"); latexTypingState.Dispose(); } if (featureToggleService.CheckFeature("auto-jfif-to-jpeg", context.Guild.Id.ToString())) { foreach (Attachment attachment in context.Message.Attachments) { if (attachment.Filename.EndsWith(".jfif") || attachment.Filename.EndsWith(".JFIF") || attachment.Filename.EndsWith(".jfif-large")) { pictureService.ConvertJfifToJpeg(context, attachment.Url); } } } int argPos = 0; if (!(message.HasMentionPrefix(_discord.CurrentUser, ref argPos) || message.HasStringPrefix(Program._config["prefix"] + " ", ref argPos))) { return; } //var typingState = context.Channel.EnterTypingState(); var result = await _commands.ExecuteAsync(context, argPos, _provider); if (result.Error.HasValue && result.Error.Value != CommandError.UnknownCommand) { await context.Channel.SendMessageAsync(result.ToString()); return; } if (result.Error.HasValue && result.Error.Value == CommandError.UnknownCommand) { string[] parts = message.Content.Split(' '); if (parts.Length >= 2) { string textResponseLookup = parts[1]; Regex userIdCheck = new Regex(@"<@![0-9]+>", RegexOptions.Compiled); if (userIdCheck.IsMatch(textResponseLookup)) { textResponseLookup = textResponseLookup.Replace("!", string.Empty); } string response = StaticTextResponseService.getGlobalResponse(textResponseLookup) ?? staticTextResponseService.getResponse(context.Guild.Id, textResponseLookup); if (response != null) { await context.Channel.SendMessageAsync(response); } } } //typingState.Dispose(); }
private async Task HandleCommandAsync(SocketMessage arg) { SocketUserMessage msg = arg as SocketUserMessage; if (msg == null || arg.Author.IsBot) { return; } int pos = 0; if (msg.HasMentionPrefix(client.CurrentUser, ref pos) || msg.HasStringPrefix("k.", ref pos)) { SocketCommandContext context = new SocketCommandContext(client, msg); if ((await commands.ExecuteAsync(context, pos)).IsSuccess) { await Utils.WebsiteUpdate("Konari", websiteName, websiteToken, "nbMsgs", "1"); } } #pragma warning disable 4014 ITextChannel textChan = arg.Channel as ITextChannel; if (textChan == null || (textChan.IsNsfw && db.GetNsfw(textChan.GuildId) == "O")) { return; } ulong guildId = textChan.GuildId; string textVal = db.GetText(guildId); string imageVal = db.GetImage(guildId); string serverVal = db.GetServer(guildId); ITextChannel textReport = await GetTextChannel(textVal, textChan.Guild); ITextChannel imageReport = await GetTextChannel(imageVal, textChan.Guild); if (textVal != "O") { Task.Run(async() => { var tmp = await Analyze.CheckText(msg, arg, textReport); if (serverVal != "O") { await Analyze.SendToServerAsync(tmp, requestUrlText, arg.Author.Id.ToString()); } }); } if (imageVal != "O") { Task.Run(async() => { var tmp = await Analyze.CheckImage(msg, arg, imageReport); if (serverVal != "O") { await Analyze.SendToServerAsync(tmp, requestUrlImage, arg.Author.Id.ToString()); } }); Task.Run(async() => { foreach (Match m in Regex.Matches(msg.Content, "https?:\\/\\/[^ ]+")) { if (Utils.IsLinkValid(m.Value)) { var tmp = await Analyze.CheckImageUrl(m.Value, msg, arg, imageReport); if (serverVal != "O" && await Analyze.SendToServerAsync(tmp, requestUrlImage, arg.Author.Id.ToString())) { break; } } } }); } #pragma warning restore 4014 }
private async Task Client_MessageReceived(SocketMessage arg) { try { var msg = arg as SocketUserMessage; if (msg == null) { return; } var ctx = new SocketCommandContext(Global.Client, msg); if (ctx.User.IsBot) { return; } if (msg.MentionedUsers.Count > 0 && MarkResource.Instance.Contains(ctx.Guild.Id, ctx.User.Id)) { await ctx.Message.DeleteAsync(); await ctx.User.SendMessageAsync($"Your {Config.Bot.Guilds[ctx.Guild.Id].Mark} is stopping you from mentioning users"); await TimeoutResource.Instance.SetTimeout(ctx.User as IGuildUser, 1); return; } var resp = string.Join("\n", ReactionResource.Instance.Find(ctx.Guild.Id, msg.Content)); if (!string.IsNullOrEmpty(resp)) { await ctx.Channel.SendMessageAsync(resp); } if (BlacklistResource.Instance.Contains(ctx.Guild.Id, ctx.User.Id)) { return; } int argPos = 0; var settings = Config.Bot.Guilds[ctx.Guild.Id]; if (msg.HasCharPrefix(settings.Prefix, ref argPos) || msg.HasMentionPrefix(Global.Client.CurrentUser, ref argPos)) { var result = await this.Service.ExecuteAsync(ctx, argPos, null); if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) { LogUtil.Write("Client_MessageReceived", $"Message: {msg.Content} | Error: {result.ErrorReason}"); await ctx.User.SendMessageAsync(result.ErrorReason); } } else if (new Random(DateTime.UtcNow.Millisecond).Next(1, 100 + 1) <= settings.Markov.Chance) { using (ctx.Channel.EnterTypingState()) { await MarkovTalk(ctx, (int)settings.Markov.Source, (int)settings.Markov.Step, (int)settings.Markov.Count); } } } catch (Exception e) { LogUtil.Write("CommandHandler:Client_MessageReceived", e.Message); } }
private async Task HandleCommandAsync(SocketMessage messageParam) { // Don't process the command if it was a System Message var message = messageParam as SocketUserMessage; if (message == null) { return; } // If it's part of a custom reaction, skip command processing foreach (var k in CustomReactions.Keys) { string[] key = k.ToLower().Trim().Split(' '); string[] msg = message.Content.ToLower().Trim().Split(' '); bool matchesKey = true; int index = 0; try { foreach (string kword in key) { string keyw; switch (kword) { case "%mention%": keyw = _client.CurrentUser.Mention; break; case "%user%": keyw = message.Author.Mention; break; default: keyw = kword; break; } if (kword != msg[index]) { matchesKey = false; } index++; } } catch (Exception) //TODO: This is a sloppy workaround and may not be the best solution; rewrite the code { //LogManager.GetCurrentClassLogger().Debug("fix buggy message handling code in Program.cs pl0x"); } if (matchesKey) { return; } } // Create a number to track where the prefix ends and the command begins int argPos = 0; if (!(message.HasStringPrefix(prefix, ref argPos))) { return; } // Create a Command Context var context = new SocketCommandContext(_client, message); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully) var result = await _commands.ExecuteAsync(context, argPos, _services); if (!result.IsSuccess) { string errtext; switch (result.Error) { case CommandError.UnknownCommand: //Unknown command errtext = StringResourceHandler.GetTextStatic("err", "unknownCommand"); break; case CommandError.MultipleMatches: //oops errtext = StringResourceHandler.GetTextStatic("err", "multipleCommandDefs"); break; case CommandError.Exception: //Exception during command processing errtext = StringResourceHandler.GetTextStatic("err", "exception", result.ErrorReason); break; default: //Other situations which I haven't accounted for (or are better shown as-is) errtext = result.ErrorReason; break; } await context.Channel.SendMessageAsync($":no_entry: `{errtext}`"); //TODO: There are a ton of strings for errors in BotStrings.resx; perhaps we should use those eventually? } }
private async Task Message1337(SocketMessage rawMessage) { // Ignore system messages and messages from bots if (!(rawMessage is SocketUserMessage message)) { return; } if (message.Source != MessageSource.User) { return; } var context = new SocketCommandContext(this._client, message); bool check = _c.ReadChannel1337Listen(context); if (!check) { return; } // Get Time to Check if we are on right time and prepare the string for it string timeNowAsString = DateTime.Now.ToString(formatTime); string result = t.RemoveSpecificCharFromString(timeNowAsString, ':'); int timeNowAsInt = Convert.ToInt32(result); // check if message contains a mention and get this mention as id to string string rolles = " "; if (message.MentionedRoles.Count == 1) { foreach (var item in message.MentionedRoles) { if (item.Name == "1337") { rolles = item.Id.ToString(); } } } // Split Message and count every 1337 and @1337 string[] userMessage = message.Content.Split(' '); int counter1337 = 0; int counterM1337 = 0; // count foreach (var item in userMessage) { if (item == "1337") { counter1337++; } else if (item == "<@&" + rolles + ">") { counterM1337++; } } // check if message has 1337 or @1337 ones! if (counter1337 == 1 && counterM1337 != 1 || counter1337 != 1 && counterM1337 == 1) { //Check if it is the right time! 133700 - 133800 otherwise break if (!(133700 <= timeNowAsInt && 133800 >= timeNowAsInt)) { if (this._devMode) { await _c.SendTo1337ChannelAsync(context.Guild.GetUser(message.Author.Id).Mention + " Nicht in der richtigen Zeit!", context); } LogMain("1 " + context.Guild.GetUser(message.Author.Id).Username + " Nicht in der richtigen Zeit!", LogLevel.Log); return; } this.db = this.dbClass.connect(); TablesHeader dbTable = new TablesHeader(this.db); // select the curent users userid from database var table1337 = dbTable.Table1337; var userID = from table in table1337 where table.userid == message.Author.Id select table.userid; // Check if this user is in Database if (userID.Count() == 0) { // Add new User to Database if not exist Table1337 addNewUser = new Table1337() { userid = message.Author.Id, username = context.Guild.GetUser(message.Author.Id).Username, counter_all = 1, counter_streak = 1, counter_longest_streak = 1, date_begin = DateTime.Today.ToString(formatDate), date_last = DateTime.Today.ToString(formatDate) }; dbTable.Table1337.InsertOnSubmit(addNewUser); dbTable.SubmitChanges(); // Counts User for bot respons counterUserPerDay++; if (this._devMode) { await _c.SendTo1337ChannelAsync(context.Guild.GetUser(message.Author.Id).Mention + " Hab dich gezählt :P", context); } LogMain("2 " + context.Guild.GetUser(message.Author.Id).Username + " Hab dich gezählt :P ", LogLevel.Log); } else // Update user if allready exist { //get colum from current user by id var userID2 = from table in table1337 where table.userid == message.Author.Id select table; // temp variable for changes uint counter_allQ = 0; uint counter_streakQ = 0; uint counter_logest_streakQ = 0; string date_lastQ = " "; // get current data from user foreach (var item in userID2) { counter_allQ = item.counter_all; counter_streakQ = item.counter_streak + 1; counter_logest_streakQ = item.counter_longest_streak; date_lastQ = item.date_last; } if (date_lastQ != DateTime.Today.ToString(formatDate)) { // update counter longest streak if user got higher streak if (counter_streakQ > counter_logest_streakQ) { counter_logest_streakQ = counter_streakQ; } // get the user which should be updated by id var updateTable = dbTable.Table1337.Single((item) => item.userid == message.Author.Id); // update values for user updateTable.username = context.Guild.GetUser(message.Author.Id).Username; updateTable.counter_all = counter_allQ + 1; if (date_lastQ != DateTime.Today.AddDays(-1).ToString(formatDate)) { updateTable.counter_streak = 1; } else { updateTable.counter_streak = counter_streakQ; } // Muss noch angepasst werden | An Tag anpassen updateTable.counter_longest_streak = counter_logest_streakQ; updateTable.date_last = DateTime.Today.ToString(formatDate); // send data to database when SubmitChanges() is called. dbTable.SubmitChanges(); // Counts User for bot respons counterUserPerDay++; if (_devMode) { await _c.SendTo1337ChannelAsync(context.Guild.GetUser(message.Author.Id).Mention + " Hab dich gezählt :P", context); } LogMain("3 " + context.Guild.GetUser(message.Author.Id).Username + " Hab dich gezählt :P ", LogLevel.Log); } else { if (this._devMode) { await _c.SendTo1337ChannelAsync(context.Guild.GetUser(message.Author.Id).Mention + " Du wurdest heute schon gezählt. Schummeln gilt nicht!! <:pandabulle:327873024017563649>", context); } LogMain("4 " + context.Guild.GetUser(message.Author.Id).Username + " Du wurdest heute schon gezählt. Schummeln gilt nicht!! <:pandabulle:327873024017563649> ", LogLevel.Log); } } this.db.Close(); } }
public async void HandleMessage( SocketMessage message, SocketCommandContext context, IDiscordClient client) { var messageChannel = context.Channel; if (messageChannel.Name == "vb-safe-images") { if (message.Content.Contains("https://twitter.com/")) { await context.Channel.SendMessageAsync("i can't get images from f*****g twitter links"); } else if (message.Attachments.Count > 0) { var attachment = message.Attachments.First(); using (var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(attachment.Url), @"C:\Users\jacob\Desktop\ml_training\safe\" + attachment.Filename); } } } else if (messageChannel.Name == "vb-lewd-images") { if (message.Content.Contains("https://twitter.com/")) { await context.Channel.SendMessageAsync("i can't get images from f*****g twitter links"); } else if (message.Attachments.Count > 0) { var attachment = message.Attachments.First(); using (var webClient = new WebClient()) { webClient.DownloadFileAsync(new Uri(attachment.Url), @"C:\Users\jacob\Desktop\ml_training\lewd\" + attachment.Filename); } } } var botMention = message.MentionedUsers.FirstOrDefault(x => x.Id == client.CurrentUser.Id); if (botMention == null) { return; } var content = message.Content; if (content.Contains("can you breathe")) { var audioService = _services.GetRequiredService <AudioService>(); var voiceChannel = ((IGuildUser)context.User).VoiceChannel; if (voiceChannel == null) { await context.Channel.SendMessageAsync("no i can't breathe"); return; } await audioService.PlayFileAsync(@"C:\Users\jacob\Desktop\breathe.mp3", context); } else if (content.Contains("kill yourself")) { await context.Channel.SendMessageAsync("Shutting down."); await client.StopAsync(); } }
private async Task OnMessageReceivedAsync(SocketMessage s) { var msg = s as SocketUserMessage; if (msg == null) { return; } // Ignore self and other bots when checking commands if (msg.Author.Id == _discord.CurrentUser.Id || msg.Author.IsBot) { return; } var context = new SocketCommandContext(_discord, msg); int argPos = 0; // Check if the message has a valid command prefix if (msg.HasStringPrefix(_config["prefix"], ref argPos) || msg.HasMentionPrefix(_discord.CurrentUser, ref argPos)) { var result = await _commands.ExecuteAsync(context, argPos, _provider); // Execute the command if (result.IsSuccess) { return; } if (!result.IsSuccess && result.ToString() != "UnknownCommand: Unknown command.") { await context.Channel.SendMessageAsync(result.ToString()); } if (msg.HasStringPrefix(_config["prefix"], ref argPos)) { // check for other conditions var key = msg.Content.Substring(_config["prefix"].Length).Split(' ').First(); if (_db.Defs.Any(d => d.Id == key)) { // get def await context.Channel.SendMessageAsync($"**{key}**: {_db.Defs.Find(key).Def}"); } else if (_db.Images.Any(i => i.Id == key)) { // get img await context.Channel.TriggerTypingAsync(); await context.Message.DeleteAsync(); await context.Channel.SendFileAsync($"UploadedImages/{_db.Images.Find(key).FilePath}", $"{key} by {context.User.Mention}"); } else if (UnicodeFonts.Fonts.ContainsKey(key)) { // convert font await context.Channel.SendMessageAsync(UnicodeFonts.Fonts[key].Convert(msg.Content.Substring(msg.Content.IndexOf(" ") + 1))); } } } else { // add poll options var id = context.Channel.Id; if (_polls.ContainsKey(id) && _polls[id].Owner == context.User && !_polls[id].IsOpen) { _polls[id].Options.Add(new PollOption { Text = msg.Content }); await context.Channel.SendMessageAsync($"{msg.Content} added!"); } // handle hangman guess await _hangman.HandleMove(msg, context); // handle tictactoe games await _tic.HandleMove(msg, context); } }
private static async Task Stop(IAudioClient Client, SocketCommandContext Context) { Database.Update("Music", "Playing", "Server_ID", Context.Guild.Id.ToString(), false); await Client.StopAsync(); }
private async Task HandleUnknownCommand(SocketCommandContext context) { //Could do something where you could check a users script for commands }
private static int PeopleInCall(SocketCommandContext Context, IVoiceChannel Channel) { return(Context.Client.GetGuild(Context.Guild.Id).GetVoiceChannel(Channel.Id).Users.Count - 1); }
public Task <bool> JudgeAsync(SocketCommandContext sourceContext, SocketMessage parameter) { bool ok = int.TryParse(parameter.Content, out _); return(Task.FromResult(ok)); }
public abstract Task Execute(SocketCommandContext context);
public static async Task RequestHouseApproval(SocketCommandContext context) { await context.Message.AddReactionAsync(new Emoji(Setup.BallotCheckEmoji)); }
public async Task MessageReceivedAsync(SocketMessage rawMessage) { try { // Ignore system messages, or messages from other bots if (!(rawMessage is SocketUserMessage message)) { return; } if (message.Source != MessageSource.User) { return; } if (message.Channel is SocketDMChannel dmChannel) { await this.privateMessageService.HandleMessage(message, dmChannel); return; } // This value holds the offset where the prefix ends var argPos = 0; // Perform prefix check. You may want to replace this with // (!message.HasCharPrefix('!', ref argPos)) // for a more traditional command format like !help. if (!message.HasMentionPrefix(discord.CurrentUser, ref argPos)) { this.chatService.AddMessage(new DiscordMessage() { ChannelId = message.Channel.Id, Message = message.Content, Username = message.Author.Username }); // all messages needs to be routed to admin module. Maybe they contain commands - it will be evaluated by admin module. await this.adminService.HandleMessage(message.Channel.Id, message.Content); return; } this.logger.LogInformation($"Received command {message.Content} on {message.Channel.Name}"); var context = new SocketCommandContext(discord, message); // Perform the execution of the command. In this method, // the command service will perform precondition and parsing check // then execute the command if one is matched. var result = await commands.ExecuteAsync(context, argPos, services); if (result.IsSuccess == false) { logger.LogError($"Error executing {message.Content} on {message.Channel.Name} - {result.Error} - {result.ErrorReason}"); } // Note that normally a result will be returned by this format, but here // we will handle the result in CommandExecutedAsync, } catch (Exception e) { logger.LogError($"{e.Message}"); } }
public static ITextChannel ModChannel(SocketCommandContext context) { ulong modChannelId = (ulong)AppSettingsUtil.AppSettingsLong("modChannel", true, 330948240805462026); return(context.Client.GetChannel(modChannelId) as ITextChannel); }
public int GetPositionWithDiscordRole(ulong userId, FFXIVRole role, IRole discordRole, SocketCommandContext context, string eventId) { return(GetQueue(role) .Where(s => SlotHasRole(s, discordRole, context)) .Where(EventValid(eventId)) .ToList() .IndexOf(s => s.Id == userId) + 1); }
public static ITextChannel ModLogChannel(SocketCommandContext context) { ulong modlogChannelId = (ulong)AppSettingsUtil.AppSettingsLong("modlogChannel", true, 473590680103419943); return(context.Client.GetChannel(modlogChannelId) as ITextChannel); }
public int CountWithDiscordRole(FFXIVRole role, IRole discordRole, SocketCommandContext context, string eventId) { return(GetQueue(role) .Where(EventValid(eventId)) .Count(s => SlotHasRole(s, discordRole, context))); }
public static ITextChannel BotSpamChannel(SocketCommandContext context) { ulong botspamChannelId = (ulong)AppSettingsUtil.AppSettingsLong("botspamChannel", true, 331106174722113548); return(context.Client.GetChannel(botspamChannelId) as ITextChannel); }
protected sealed override async Task <PreconditionResult> CheckPermissionsAsync(SocketCommandContext Context, SocketGuildUser target) => Context.User is SocketGuildUser ? await VerifyUser.BotIsHigher(Context.Guild.CurrentUser, target) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError($"We cannot {command} members with equal or higher authority than ourselves.") : PreconditionResult.FromError("You must be in a server to run this command.");
public static SocketGuild ServerGuild(SocketCommandContext context) { ulong serverGuild = (ulong)AppSettingsUtil.AppSettingsLong("serverGuild", true, 330944238910963714); return(context.Client.GetGuild(serverGuild)); }
public static ulong?GetGuildId(this SocketCommandContext context) { return(context.Guild?.Id); }
public async Task SharePlaylist(SocketCommandContext context, string shareUrl, string title, string tags, bool isPrivate) { using (var soraContext = new SoraContext()) { var userDb = Utility.OnlyGetUser(context.User.Id, soraContext); if (userDb == null || ExpService.CalculateLevel(userDb.Exp) < MIN_LEVEL) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], $"You need to be at least lvl {MIN_LEVEL} to share playlists!")); return; } if (await CanAddNewPlaylist(context, userDb) == false) { return; } if (!shareUrl.StartsWith("https://hastebin.com/")) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "The link must be a valid hastebin link!")); return; } if (!shareUrl.EndsWith(".sora") && !shareUrl.EndsWith(".fredboat")) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Must be an originaly exported sora or fredboat playlist!") .WithDescription( $"Use `{Utility.GetGuildPrefix(context.Guild, soraContext)}export` when you have a Queue! This is to minimize errors.")); return; } if (shareUrl.EndsWith(".fredboat")) { shareUrl = shareUrl.Replace(".fredboat", ".sora"); } if (soraContext.ShareCentrals.Any(x => x.ShareLink == shareUrl)) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Playlist already exists!")); return; } string[] seperatedTags; if (tags.IndexOf(";", StringComparison.Ordinal) < 1) { seperatedTags = new[] { tags }; } else { seperatedTags = tags.Split(";"); } List <string> betterTags = new List <string>(); foreach (var tag in seperatedTags) { string finalTag = tag; if (finalTag.Contains(";")) { finalTag = finalTag.Replace(";", ""); } if (!string.IsNullOrWhiteSpace(finalTag)) { betterTags.Add(finalTag.Trim()); } } if (betterTags.Count < 1) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Add at least one Tag!").WithDescription("Tags must be added like this: `trap;edm;chill music;other`")); return; } if (betterTags.Count > 10) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Please dont exceed 10 tags!")); return; } string joinedTags = String.Join(";", betterTags); var eb = new EmbedBuilder() { Color = Utility.BlueInfoEmbed, Title = $"{Utility.SuccessLevelEmoji[3]} Are you sure you want share this? y/n", Description = $"{shareUrl}\n" + $"You can change the Title and Tags afterwards but never the playlist link!", Author = new EmbedAuthorBuilder() { IconUrl = context.User.GetAvatarUrl() ?? Utility.StandardDiscordAvatar, Name = Utility.GiveUsernameDiscrimComb(context.User) } }; eb.AddField(x => { x.IsInline = false; x.Name = "Title"; x.Value = title; }); eb.AddField(x => { x.IsInline = true; x.Name = "Tags"; x.Value = joinedTags.Replace(";", " - "); }); eb.AddField(x => { x.IsInline = true; x.Name = "Is Private?"; x.Value = $"{(isPrivate ? "Yes" : "No")}"; }); var msg = await context.Channel.SendMessageAsync("", embed : eb); var response = await _interactive.NextMessageAsync(context, true, true, TimeSpan.FromSeconds(45)); await msg.DeleteAsync(); if (response == null) { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer in time ;_;")); return; } if (response.Content.Equals("y", StringComparison.OrdinalIgnoreCase) || response.Content.Equals("yes", StringComparison.OrdinalIgnoreCase)) { userDb.ShareCentrals.Add(new ShareCentral() { CreatorId = context.User.Id, Downvotes = 0, Upvotes = 0, ShareLink = shareUrl, Titel = title, IsPrivate = isPrivate, Tags = joinedTags }); await soraContext.SaveChangesAsync(); await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.GreenSuccessEmbed, Utility.SuccessLevelEmoji[0], $"Successfully {(isPrivate ? "saved" : "shared")} playlist (ノ◕ヮ◕)ノ*:・゚✧")); } else { await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Didn't answer with y or yes! Discarded changes")); } } }