//When a user has been banned, tell it them in the welcomings channel. public static async Task UserBannedAsync(SocketUser user, SocketGuild guild) { var server = Tools.GetServerInfo(guild.Id); if (server.welcomingChannel == 0) return; await Tools.ReplyAsync(user, Storage.client.GetChannel(server.welcomingChannel) as ITextChannel, $"**{user.Mention}** has been banned from the server. ({user.Username})", false); }
private Task Client_UserBanned(SocketUser arg1, SocketGuild arg2) { UpdateUserState(arg2, arg1, "getting banned"); return(Task.CompletedTask); }
//Removes element from dict, thats all private void RemoveUser(SocketUser user, Dictionary <ulong, Tuple <TimeSpan, DateTime> > _dict) { _dict.Remove(user.Id); }
public static string GetAvatarUrl(SocketUser user) { return user.GetAvatarUrl(size: 1024) ?? user.GetDefaultAvatarUrl(); // Get the avatar and resize it 1024x1024. if the user has no avatar, get the default discord logo. }
public override async Task OnExecuteFromDiscord(SocketGuild guild, SocketUser user, SocketTextChannel channel, SocketMessage messageobject, string fullmessage, string arguments_string, List <string> arguments) { int page = 0; List <string> pages = new List <string>(); Emoji em1 = new Emoji("\u23EE"); Emoji em2 = new Emoji("\u23ED"); String currentPage = "```A list of known commands:"; List <SystemCommand> commands = new List <SystemCommand>(); foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { bool found = false; foreach (CmdCategory cat in command.Categories) { if (cat.name.ToLower() == arguments[0].ToLower()) { found = true; break; } } if (!found) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { bool found = false; foreach (CmdCategory cat in command.Categories) { if (cat.name.ToLower().StartsWith(arguments[0].ToLower())) { found = true; break; } } if (!found) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { bool found = false; foreach (CmdCategory cat in command.Categories) { if (cat.name.ToLower().Contains(arguments[0].ToLower())) { found = true; break; } } if (!found) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { if (command.commandid.ToLower() != arguments[0].ToLower()) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { if (!command.commandid.ToLower().StartsWith(arguments[0].ToLower())) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { if (!command.commandid.ToLower().Contains(arguments[0].ToLower())) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { if (!command.description.ToLower().StartsWith(arguments[0].ToLower())) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in GetBot().commands) { if (arguments.Count != 0) { if (!command.description.ToLower().Contains(arguments[0].ToLower())) { continue; } } if (!commands.Contains(command)) { commands.Add(command); } } foreach (SystemCommand command in commands) { if (!Bot.GetBot().CheckPermissions(command.permissionnode, user, guild)) { continue; } if (currentPage.Length + 3 >= 2000) { currentPage += "```"; pages.Add(currentPage); currentPage = "```A list of known commands (page " + pages.Count + "):"; } currentPage += ("\n - " + command.commandid + (command.helpsyntax == "" ? "" : " " + command.helpsyntax) + " - " + command.description); } if (currentPage.Length != ("```A list of known commands (page " + pages.Count + "):").Length) { currentPage += "```"; pages.Add(currentPage); } Discord.Rest.RestUserMessage message = await channel.SendMessageAsync(pages[page]); Func <Cacheable <IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> handler = new Func <Cacheable <IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>((arg1, arg2, arg3) => { if (arg3.MessageId == message.Id && arg3.Channel.Id == message.Channel.Id) { if (arg3.Emote.Name == em1.Name) { bool changed = false; var v = message.GetReactionUsersAsync(em1, int.MaxValue).GetAsyncEnumerator(); while (true) { if (v.Current != null) { foreach (IUser usr in v.Current) { if (!usr.Id.Equals(Bot.GetBot().client.CurrentUser.Id)) { message.RemoveReactionAsync(em1, usr).GetAwaiter().GetResult(); changed = true; } } } if (!v.MoveNextAsync().GetAwaiter().GetResult()) { break; } } if (changed) { page--; var oldmsg = message; message = channel.SendMessageAsync(pages[page]).GetAwaiter().GetResult(); oldmsg.DeleteAsync().GetAwaiter().GetResult(); if (page != 0) { message.AddReactionAsync(em1).GetAwaiter().GetResult(); } if (page != pages.Count - 1) { message.AddReactionAsync(em2).GetAwaiter().GetResult(); } } } if (arg3.Emote.Name == em2.Name) { bool changed = false; var v = message.GetReactionUsersAsync(em2, int.MaxValue).GetAsyncEnumerator(); while (true) { if (v.Current != null) { foreach (IUser usr in v.Current) { if (!usr.Id.Equals(Bot.GetBot().client.CurrentUser.Id)) { message.RemoveReactionAsync(em1, usr).GetAwaiter().GetResult(); changed = true; } } } if (!v.MoveNextAsync().GetAwaiter().GetResult()) { break; } } if (changed) { page++; var oldmsg = message; message = channel.SendMessageAsync(pages[page]).GetAwaiter().GetResult(); oldmsg.DeleteAsync().GetAwaiter().GetResult(); if (page != 0) { message.AddReactionAsync(em1).GetAwaiter().GetResult(); } if (page != pages.Count - 1) { message.AddReactionAsync(em2).GetAwaiter().GetResult(); } } } } return(null); }); Bot.GetBot().client.ReactionAdded += handler; Bot.GetBot().client.MessageDeleted += (arg11, arg22) => { if (arg11.Id == message.Id) { Bot.GetBot().client.ReactionAdded -= handler; } return(null); }; if (pages.Count != 1) { if (page != pages.Count) { await message.AddReactionAsync(em2); } } }
public async Task OnMoviesModified(Movie m, SocketGuild guild, ISocketMessageChannel channel, SocketUser user) { //Update the data and embed totalPages = showWatched ? serverData.GetWatchedMovies().Count() : serverData.GetSuggestedMovies().Count(); totalPages = (int)Math.Ceiling(totalPages / (float)pageSize); pageNumber = Math.Min(totalPages - 1, pageNumber); await suggestionsMessage.ModifyAsync(VoteMessage => { VoteMessage.Content = "Moves Info!!"; VoteMessage.Embed = MakeEmbed(); return; }); }
public bool IsAuthUser(SocketUser user) => AuthUsers.Contains(user.Id) ? true : false;
public static async Task AddToQueueAsync(this SocketCommandContext Context, int code, string trainer, RequestSignificance sig, PK8 trade, PokeRoutineType routine, PokeTradeType type, SocketUser trader, GiveawayPoolEntry poolEntry) { if ((uint)code > MaxTradeCode) { await Context.Channel.SendMessageAsync("Trade code should be 00000000-99999999!").ConfigureAwait(false); return; } IUserMessage test; try { const string helper = "I've added you to the queue! I'll message you here when your trade is starting."; test = await trader.SendMessageAsync(helper).ConfigureAwait(false); } catch (HttpException ex) { await Context.Channel.SendMessageAsync($"{ex.HttpCode}: {ex.Reason}!").ConfigureAwait(false); var noAccessMsg = Context.User == trader ? "You must enable private messages in order to be queued!" : "The mentioned user must enable private messages in order for them to be queued!"; await Context.Channel.SendMessageAsync(noAccessMsg).ConfigureAwait(false); return; } // Try adding var result = Context.AddToTradeQueue(trade, code, poolEntry, trainer, sig, routine, type, trader, out var msg); // Notify in channel await Context.Channel.SendMessageAsync(msg).ConfigureAwait(false); // Notify in PM to mirror what is said in the channel. await trader.SendMessageAsync(msg).ConfigureAwait(false); // Clean Up if (result) { // Delete the user's join message for privacy if (!Context.IsPrivate) { await Context.Message.DeleteAsync(RequestOptions.Default).ConfigureAwait(false); } } else { // Delete our "I'm adding you!", and send the same message that we sent to the general channel. await test.DeleteAsync().ConfigureAwait(false); } }
public static async Task Render_Quick_Scene_P2IS_PS1(SocialLinkerCommand sl_command, OfficialSetData set_data, MakerCommandData command_data) { // Create variables to store the width and height of the template. int template_width = 320; int template_height = 240; // Create two variables for the command user and the command channel, derived from the message object taken in. SocketUser user = sl_command.User; SocketTextChannel channel = (SocketTextChannel)sl_command.Channel; // Send a loading message to the channel while the sprite sheet is being made. RestUserMessage loader = await channel.SendMessageAsync("", false, P2IS_PS1_Loading_Message().Build()); // Get the account information of the command's user. var account = UserInfoClasses.GetAccount(user); BustupData bustup_data = BustupDataMethods.Get_Bustup_Data(account, set_data, command_data); // Create a starting base bitmap to render all graphics on. Bitmap base_template = new Bitmap(template_width, template_height); // Create another bitmap the same size. // In case the user has set a colored bitmap in their settings, we'll need to use this to render it. Bitmap colored_background_bitmap = new Bitmap(template_width, template_height); // Here, we want to grab any images attached to the message to use it as a background. // Create a variable for the message attachment. var attachments = sl_command.Attachments; // Create an empty string variable to hold the URL of the attachment. string url = ""; // If there are no attachments on the message, set the URL string to "None". if (attachments == default || attachments.LongCount() == 0) { url = "None"; } // Else, assign the URL of the attachment to the URL string. else { url = attachments.ElementAt(0).Url; } // Initialize a bitmap object for the user's background. It's small now because we'll reassign it depending on our circumstances. Bitmap background = new Bitmap(2, 2); // If a URL for a message attachment exists, download it and copy its contents to the bitmap variable we just created. if (url != "None") { // Here, we'll want to try and retrieve the user's input image. try { // Declare variables for a web request to retrieve the image. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); webRequest.AllowWriteStreamBuffering = true; webRequest.Timeout = 30000; // Create a stream and download the image to it. System.Net.WebResponse webResponse = webRequest.GetResponse(); System.IO.Stream stream = webResponse.GetResponseStream(); // Copy the stream's contents to the background bitmap variable. background = (Bitmap)System.Drawing.Image.FromStream(stream); webResponse.Close(); } // If an exception occurs here, the filetype is likely incompatible. // Send an error message, delete the loading message, and return. catch (System.ArgumentException e) { Console.WriteLine(e); await loader.DeleteAsync(); _ = ErrorHandling.Incompatible_File_Type(sl_command); return; } } // Render the uploaded image based on the user's background settings. switch (account.Setting_BG_Upload) { case "Maintain Aspect Ratio": background = Center_Image(background); break; case "Stretch to Fit": background = Stretch_To_Fit(background); break; } // The user may have a custom mono-colored background designated in their settings. Let's handle that now. // Check if the user's background color setting is set to something other than "Transparent". // If so, we have a color to render for the background! if (account.Setting_BG_Color != "Transparent") { // Convert the user's HTML color setting to one we can use and assign it to a color variable. System.Drawing.Color user_background_color = System.Drawing.ColorTranslator.FromHtml(account.Setting_BG_Color); // Color the entirety of the background bitmap the user's selected color. using (Graphics graphics = Graphics.FromImage(colored_background_bitmap)) { graphics.Clear(user_background_color); } } // Next, time for the conversation portrait! Create and initialize a new bitmap variable for it. Bitmap bustup = new Bitmap(2, 2); // Check if the base sprite number is something other than zero. // If it is zero, we have nothing to render. Otherwise, retrieve the bustup. if (command_data.Base_Sprite != 0) { bustup = OfficialSetMethods.Bustup_Selection(sl_command, account, set_data, bustup_data, command_data); } // If the bustup returns as null, however, something went wrong with rendering the animation frames. // An error message has already been sent in the frame rendering method, so delete the loading message and return. if (bustup == null) { await loader.DeleteAsync(); return; } List <string>[] dialogue_lines = Line_Parser(sl_command, command_data.Dialogue); // Time to put it all together! using (Graphics graphics = Graphics.FromImage(base_template)) { // Draw the input dialogue to the template. graphics.DrawImage(Render_Bustup(account, bustup_data, bustup), 0, 0, template_width, template_height); graphics.DrawImage(Render_Message_Window(account), 0, 0, template_width, template_height); graphics.DrawImage(Combined_Text_Layers(bustup_data, dialogue_lines), 0, 0, template_width, template_height); } // Save the entire base template to a data stream. MemoryStream memoryStream = new MemoryStream(); base_template.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); memoryStream.Seek(0, SeekOrigin.Begin); try { // Send the image. await sl_command.Channel.SendFileAsync(memoryStream, $"scene_{sl_command.User.Id}_{DateTime.UtcNow}.png"); } catch (Exception e) { Console.WriteLine(e); // Send an error message to the user if the image upload fails. _ = ErrorHandling.Image_Upload_Failed(sl_command); // Clean up resources used by the stream, delete the loading message, and return. memoryStream.Dispose(); await loader.DeleteAsync(); return; } // Clean up resources used by the stream and delete the loading message. memoryStream.Dispose(); await loader.DeleteAsync(); // If the user has auto-delete for their commands set to on, delete their command as well. if (account.Auto_Delete_Commands == "On") { await sl_command.Message.DeleteAsync(); } }
private async Task client_UserVoiceStateUpdated(SocketUser user, SocketVoiceState before, SocketVoiceState after) { await _hub.Clients.All.SendAsync("VoiceStateUpdated", GetCurrentState()); }
public PoxelCardOptions(PoxelUnitScale scale, SocketUser user) { //if (Container.TryGetOriUser(user, out OriUser oriUser)) // User = new PoxelCardUserData(user, oriUser); }
public async Task <(ulong, ulong, string)> GetAnswerAsync(string game) { ulong newAuthor = _commandService.Message.Author.Id + 1; // Needs to make sure authors don't match at the first iteration SocketUser newAuthorAsSocketUser = _commandService.Message.Author; ulong originalAuthor = 0; string originalMessage = ""; string newMessage = ""; int index = 0; string reply = ""; ulong firstDisposableMessage = 0; ulong secondDisposableMessage = 0; // Searches for possible matches on steam and returns them as a json string string searchResult = await _api.GetResult(game); JArray jsonResult = await _handler.Parse(searchResult); while (true) { // Sets newAuthor to the author of the newest message if (originalAuthor != 0 && !originalMessage.Equals(newMessage)) { newAuthor = _commandService.Message.Author.Id; newMessage = _commandService.Message.Content; } // Only executes once so that it sets the user who originally initialized the command if (!_commandService.Message.Author.IsBot && originalAuthor == 0 && string.IsNullOrEmpty(originalMessage)) { originalAuthor = _commandService.Message.Author.Id; originalMessage = _commandService.Message.Content; } // Builds the embed and sends it to the channel if (index.Equals(0) && !jsonResult.Count.Equals(0)) { List <(string, string)> list = new List <(string, string)>(); int listIterator = 0; foreach (var o in jsonResult) { string name = o.SelectToken("pagemap").SelectToken("product")[0].SelectToken("name").ToString(); list.Add(($"{++listIterator}", name)); } Embed embed = await _embed.Build(list, "Result of steam search:"); await _commandService.Message.Channel.SendMessageAsync(text : "Which one?", embed : embed); firstDisposableMessage = _commandService.Message.Id; index = 1; } // Checks if there's nothing in the result, break out of the loop if (jsonResult.ToString().Equals(searchResult)) { reply = "Game not found. Weird."; break; } // Will only execute if we got a reply from the same user if (originalAuthor != 0 && originalAuthor.Equals(newAuthor) && !newAuthorAsSocketUser.IsBot && !originalMessage.Equals(newMessage)) { // Checks if it's a number and if the number is in the list if (int.TryParse(_commandService.Message.Content, out int answer)) { secondDisposableMessage = _commandService.Message.Id; if (answer < jsonResult.Count) { reply = jsonResult.AsJEnumerable().ElementAt(answer - 1).SelectToken("formattedUrl").ToString(); break; } else { reply = "That number is not in the list."; break; } } else { reply = "Not a number."; break; } } } return(firstDisposableMessage, secondDisposableMessage, reply); }
public static async Task Give(SocketUser fromuser, SocketUser touser, int amount) => await Give(fromuser.Id, touser.Id, amount);
public static async Task Subtract(SocketUser user, int amount) => await Subtract(user.Id, amount);
public static void UserSession(object threadContext) { Socket userSocket = (Socket)threadContext; SocketUser user = new SocketUser(userSocket); user.Chat(); }
public static async Task Add(SocketUser user, int amount) => await Add(user.Id, amount);
/// <summary> /// Return username#discriminator of the user /// </summary> /// <param name="_user"></param> /// <returns></returns> private string GetUniqueDiscriminator(SocketUser _user) { return($"{_user.Username}#{_user.Discriminator}"); }
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, GiveawayPoolEntry poolEntry, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg) { var user = trader; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, user, Context); var detail = new PokeTradeDetail <PK8>(pk8, trainer, poolEntry, notifier, t, code: code, sig == RequestSignificance.Favored); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if (t == PokeTradeType.Specific && pk8.Species != 0) { pokeName = $" Receiving: {(hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + new ShowdownSet(pk8).Text.Split('@','\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}."; } msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}.{pokeName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }
public static UserAccount GetAccount(SocketUser user) { return(GetOrCreateAccount(user.Id)); }
public UserWrapper(SocketUser user) { this.headless = false; this.user = user; }
private async Task <MALAccount> GetAccount(SocketUser user, SocketGuild guild) { return(await _context.MALAccounts.FirstOrDefaultAsync(mal => mal.UserId == user.Id && mal.GuildId == guild.Id)); }
public static UserAccount GetAccount(SocketUser user) => GetOrCreateUserAccount(user.Id);
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg, string requestedIgn = "") { var user = trader; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context, user); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code, userID, sig == RequestSignificance.Favored, requestedIgn); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Favored); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if (t == PokeTradeType.LanTrade || t == PokeTradeType.Specific || t == PokeTradeType.EggRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0) { pokeName = $" Receiving: {(t == PokeTradeType.EggRoll ? "Mysterious Egg" : hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + ShowdownSet.GetShowdownText(pk8).Split('@', '\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}{(pk8.IsEgg && t != PokeTradeType.EggRoll ? " (Egg)" : "")}."; } if (t == PokeTradeType.LanRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0) { pokeName = $" Receiving: An Illegal Egg."; } string overallPosition = ""; if (Info.Hub.Config.Discord.PostOverallQueueCount) { if (position.QueueCount != position.OverallQueueCount) { if (type == PokeRoutineType.SeedCheck && hub.Config.Queues.FlexMode == FlexYieldMode.LessCheatyFirst) { overallPosition = $" | __Overall: {position.Position}/{position.OverallQueueCount}__"; } else { overallPosition = $" | __Overall: {position.OverallPosition}/{position.OverallQueueCount}__"; } } else { overallPosition = $""; } } var ignName = ""; if (t == PokeTradeType.LanTrade || t == PokeTradeType.LanRoll) { if (requestedIgn != string.Empty) { ignName = $" Looking for {requestedIgn}."; } } msg = $"{user.Mention} - Added to the **{type}** queue{ticketID}. Current Position: __{type}: {position.Position}/{position.QueueCount}__{overallPosition}.{pokeName}{ignName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }
public async Task SiegeStartCommand([Remainder] string overrideString = "") { ulong fileId = Context.IsPrivate ? Context.User.Id : Context.Guild.Id; if (_gamesService.Sieges.ContainsKey(fileId) && _gamesService.Sieges[fileId].Active) { await SendErrorAsync("A battle is currently ongoing!"); return; } if (!File.Exists($"Data{Path.DirectorySeparatorChar}{fileId}.siege")) { await SendErrorAsync($"**{Context.User.Username}**, no-one is signed up!"); return; } // Get marbles List <(ulong id, string name)> rawMarbleData; using (var marbleList = new StreamReader($"Data{Path.DirectorySeparatorChar}{fileId}.siege")) { var formatter = new BinaryFormatter(); if (marbleList.BaseStream.Length == 0) { await SendErrorAsync($"**{Context.User.Username}**, no-one is signed up!"); return; } rawMarbleData = (List <(ulong id, string name)>)formatter.Deserialize(marbleList.BaseStream); } if (rawMarbleData.Count == 0) { await SendErrorAsync($"**{Context.User.Username}**, no-one is signed up!"); return; } var marbles = new List <SiegeMarble>(); var marbleOutput = new StringBuilder(); var mentionOutput = new StringBuilder(); int stageTotal = 0; foreach ((ulong id, string name) in rawMarbleData) { var user = (await MarbleBotUser.Find(Context, id)) !; stageTotal += user.Stage; marbles.Add(new SiegeMarble(id, name, 0) { Shield = user.GetShield(), Spikes = user.GetSpikes() }); marbleOutput.AppendLine($"**{name}** [{user.Name}#{user.Discriminator}]"); SocketUser socketUser = Context.Client.GetUser(id); if (user.SiegePing && socketUser != null && socketUser.Status != UserStatus.Offline) { mentionOutput.Append($"<@{user.Id}> "); } } Boss boss; if (!_gamesService.Sieges.TryGetValue(fileId, out Siege? currentSiege)) { // Pick boss & set battle stats based on boss if (overrideString.Contains("override") && (_botCredentials.AdminIds.Any(id => id == Context.User.Id) || Context.IsPrivate)) { boss = Boss.GetBoss(overrideString.Split(' ')[1].RemoveChar(' ')); } else { // Choose a stage 1 or stage 2 boss depending on the stage of each participant float stage = stageTotal / (float)marbles.Count; if (Math.Abs(stage - 1f) < float.Epsilon) { boss = ChooseStageOneBoss(marbles); } else if (Math.Abs(stage - 2f) < float.Epsilon) { boss = ChooseStageTwoBoss(marbles); } else { stage--; boss = _randomService.Rand.NextDouble() < stage ? ChooseStageTwoBoss(marbles) : ChooseStageOneBoss(marbles); } } _gamesService.Sieges.TryAdd(fileId, currentSiege = new Siege(Context, _gamesService, _randomService, boss, marbles)); } else { boss = currentSiege.Boss; currentSiege.Marbles = marbles; } int marbleHealth = ((int)boss.Difficulty + 2) * 5; foreach (SiegeMarble marble in marbles) { marble.MaxHealth = marbleHealth; } var builder = new EmbedBuilder() .WithColor(GetColor(Context)) .WithDescription("Get ready! Use `mb/siege attack` to attack and `mb/siege grab` to grab power-ups when they appear!") .WithTitle("The Siege has begun! :crossed_swords:") .WithThumbnailUrl(boss.ImageUrl) .AddField($"Marbles: **{marbles.Count}**", marbleOutput.ToString()) .AddField($"Boss: **{boss.Name}**", new StringBuilder() .AppendLine($"Health: **{boss.Health}**") .AppendLine($"Attacks: **{boss.Attacks.Length}**") .AppendLine($"Difficulty: **{boss.Difficulty} {(int)boss.Difficulty}**/10") .ToString()); // Siege Start IUserMessage countdownMessage = await ReplyAsync("**3**"); await Task.Delay(1000); await countdownMessage.ModifyAsync(m => m.Content = "**2**"); await Task.Delay(1000); await countdownMessage.ModifyAsync(m => m.Content = "**1**"); await Task.Delay(1000); await countdownMessage.ModifyAsync(m => m.Content = "**BEGIN THE SIEGE!**"); await ReplyAsync(embed : builder.Build()); currentSiege.Start(); if (mentionOutput.Length != 0 && _botCredentials.AdminIds.Any(id => id == Context.User.Id) && !overrideString.Contains("noping")) { await ReplyAsync(mentionOutput.ToString()); } }
public async Task SetStrike([Summary("The number of strikes you want to set")] int strikes, [Summary("The user to strike")] SocketUser user) { ulong id = user.Id; if (!(ids.Contains(id))) { ids.Add(id); nams.Add(user.Username + "#" + user.Discriminator); dict.Add(id, 0); } bool moreStrikes = strikes > dict[id]; bool sameStrikes = strikes == dict[id]; bool oneDif = strikes - dict[id] == 1 || dict[id] - strikes == 1; bool negStrike = strikes < 0; bool negVal = dict[id] < 0; dict[id] = strikes; string s = (strikes == 1) ? "":"s"; SaveData(); string ss = "*"; if (strikes != 0) { if (sameStrikes) { ss += "looks at the tally*\n" + user.Username + " already has " + strikes + " strike" + s + "!"; } else { if (moreStrikes) { if (oneDif) { ss += "scratches in a tally*\n" + user.Username + " now has " + strikes + " strike" + s + "!"; } else { ss += "scratches in a few tallies*\n" + user.Username + " now has " + strikes + " strike" + s + "!"; } } else { if (oneDif) { ss += "rubs out a tally*\n" + user.Username + " now has " + strikes + " strike" + s + "!"; } else { ss += "rubs out a few tallies*\n" + user.Username + " now has " + strikes + " strike" + s + "!"; } } } } else { ss += "rubs out all of the tallies*\n" + user.Username + " now has " + strikes + " strike" + s + " x3"; } await Context.Channel.SendMessageAsync(ss); }
private Task UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after) { var user = (iuser as SocketGuildUser); var guild = user?.Guild; if (guild == null) { return(Task.CompletedTask); } var botUserPerms = guild.CurrentUser.GuildPermissions; if (before.VoiceChannel == after.VoiceChannel) { return(Task.CompletedTask); } if (!VoicePlusTextCache.Contains(guild.Id)) { return(Task.CompletedTask); } var _ = Task.Run(async() => { try { if (!botUserPerms.ManageChannels || !botUserPerms.ManageRoles) { try { await guild.Owner.SendErrorAsync( _strings.GetText("vt_exit", guild.Id, "Administration".ToLowerInvariant(), Format.Bold(guild.Name))).ConfigureAwait(false); } catch { // ignored } using (var uow = _db.UnitOfWork) { uow.GuildConfigs.For(guild.Id, set => set).VoicePlusTextEnabled = false; VoicePlusTextCache.TryRemove(guild.Id); await uow.CompleteAsync().ConfigureAwait(false); } return; } var semaphore = _guildLockObjects.GetOrAdd(guild.Id, (key) => new SemaphoreSlim(1, 1)); try { await semaphore.WaitAsync().ConfigureAwait(false); var beforeVch = before.VoiceChannel; if (beforeVch != null) { var beforeRoleName = GetRoleName(beforeVch); var beforeRole = guild.Roles.FirstOrDefault(x => x.Name == beforeRoleName); if (beforeRole != null) { _log.Info("Removing role " + beforeRoleName + " from user " + user.Username); await user.RemoveRoleAsync(beforeRole).ConfigureAwait(false); await Task.Delay(200).ConfigureAwait(false); } } var afterVch = after.VoiceChannel; if (afterVch != null && guild.AFKChannel?.Id != afterVch.Id) { var roleName = GetRoleName(afterVch); var roleToAdd = guild.Roles.FirstOrDefault(x => x.Name == roleName) ?? (IRole)await guild.CreateRoleAsync(roleName, GuildPermissions.None).ConfigureAwait(false); ITextChannel textChannel = guild.TextChannels .FirstOrDefault(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant()); if (textChannel == null) { var created = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false)); try { await guild.CurrentUser.AddRoleAsync(roleToAdd).ConfigureAwait(false); } catch { /*ignored*/ } await Task.Delay(50).ConfigureAwait(false); await created.AddPermissionOverwriteAsync(roleToAdd, new OverwritePermissions( readMessages: PermValue.Allow, sendMessages: PermValue.Allow)) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); await created.AddPermissionOverwriteAsync(guild.EveryoneRole, new OverwritePermissions( readMessages: PermValue.Deny, sendMessages: PermValue.Deny)) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); } _log.Info("Adding role " + roleToAdd.Name + " to user " + user.Username); await user.AddRoleAsync(roleToAdd).ConfigureAwait(false); } } finally { semaphore.Release(); } } catch (Exception ex) { _log.Warn(ex); } }); return(Task.CompletedTask); }
public async Task CreateNewTeamAsync(string teamName, SocketGuild guild, SocketUser identity) { var myTeam = await _factory.CreateTeamAsync(teamName, guild); }
public async Task <RuntimeResult> Listenn(float minutes, SocketUser user = null) { if (user == null) { user = Context.User; } DateTime utcNow = DateTime.UtcNow; if (_dictionary.ContainsKey(user.Id)) { return(MyCommandResult.FromError($"Shhh... :eyes: 'Listen' is already running for user {user.Mention}!\nEstimated end time : `{(_dictionary[user.Id].Item1 - (utcNow - _dictionary[user.Id].Item2) ).ToString(@"hh\:mm\:ss")}`")); } else { TimeSpan span = TimeSpan.FromMinutes(minutes); // converting float minutes to timespan minutes _dictionary.Add(user.Id, new Tuple <TimeSpan, DateTime>(span, utcNow)); //filling dict } Random random = new Random(); Color color = new Color(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); try { Console.Write(user.Username + "\n"); //test : see which user we listen to var embedBuilder = new EmbedBuilder(); if (minutes < 0.5f) { throw new ArgumentException("Time period must be more than 0,5 min."); } if (minutes > 60f) { throw new ArgumentException("Time period cant be more than 1 hour."); } int p = (int)(minutes * 60) / wait_seconds; //How many times loop will run song_data[] songData = new song_data[p]; int d = 0; var embed = new EmbedBuilder(); embed.Description += $"starting... \nListening for {minutes} minute(s).."; embed.WithColor(color); await Context.Channel.SendMessageAsync("", false, embed.Build()); for (int i = 0; i < p; i++) { bool Spotify_exists = false; //To determine whether first activity check contains spotify var activities = user.Activities; foreach (var activity in activities) //Typecheck.... { if (activity is SpotifyGame spot) { Spotify_exists = true; //Console.WriteLine($"{d + 1} song recieved"); var tuple = spotify.Listen(spot.TrackTitle + " " + spot.Artists.First()); songData[d].s_popularity = tuple.Result.Item1; // <- song pop songData[d].a_popularity = tuple.Result.Item2; // <- artist pop songData[d].genre_string = tuple.Result.Item3; //Console.WriteLine(spot.TrackTitle); //Console.WriteLine(songData[d].genre_string); d++; } } if (!Spotify_exists && i == 0) { throw new Exception($"No spotify activity detected.\n[What is spotify activity?]({spotify_activity_Explanation}) :confused:"); } if (i != p - 1) //For not delaying after last time { await Task.Delay(wait_seconds * 1000); } } //Console.WriteLine("\n\n"); var distinct_data = songData.Distinct(); //Deletes similar elements. float[] popularities = new float[distinct_data.Count()]; // song popularities int dd = 0; string distinct_genres = ""; foreach (var data in distinct_data) { //Console.WriteLine(data.songname); //Console.WriteLine(data.genre_string); popularities[dd] = (data.s_popularity * 0.25f + data.a_popularity * 0.75f); dd++; distinct_genres = distinct_genres + "+" + data.genre_string;//all genres to one string, in order to pass it to GetTopGenres(); } //Console.WriteLine($"\n\n{distinct_genres}"); - in case you wanna see it var topGenres = spotify.GetTopGenres(distinct_genres); var field = new EmbedFieldBuilder(); field.WithName($"How basic your music taste is, based on {popularities.Length} song(s) "); field.WithValue($"Your current songs are `{Math.Round(popularities.Average(), 1)}%` basic."); field.IsInline = true; var author = new EmbedAuthorBuilder(); author.Name += $"for {user.Username}"; author.IconUrl += user.GetAvatarUrl(); embedBuilder.AddField(field); embedBuilder.WithAuthor(author) .WithCurrentTimestamp() .WithColor(color) .WithThumbnailUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Spotify_logo_without_text.svg/768px-Spotify_logo_without_text.svg.png"); if (topGenres.Length > 2) { var genre_field = new EmbedFieldBuilder(); genre_field.WithName("**Top genres are** :"); genre_field.IsInline = true; var genre_arr = topGenres.Split(", "); foreach (var genre in genre_arr) { genre_field.Value += $"• {genre}\n"; } embedBuilder.AddField(genre_field); } RemoveUser(user, _dictionary); await Context.Channel.SendMessageAsync(user.Mention, false, embedBuilder.Build()); return(MyCommandResult.FromSuccess()); } catch (Exception e) { RemoveUser(user, _dictionary); return(MyCommandResult.FromError($"Command aborted : {e.Message}")); } }
/// <summary> /// Starts and adds a new vote to a server /// </summary> /// <param name="voteTitle"></param> /// <param name="voteDescription"></param> /// <param name="lastTime"></param> /// <param name="yesEmoji"></param> /// <param name="noEmoji"></param> /// <param name="guild"></param> /// <param name="channel"></param> /// <param name="userWhoExecuted"></param> /// <returns></returns> public static async Task StartVote(string voteTitle, string voteDescription, TimeSpan lastTime, string yesEmoji, string noEmoji, SocketGuild guild, IMessageChannel channel, SocketUser userWhoExecuted) { if (lastTime.TotalMilliseconds > Config.bot.VoteSettings.MaxVoteTime.TotalMilliseconds) { await channel.SendMessageAsync("The vote time succeeds the maximum allowed time for a vote to last!"); return; } ServerList server = ServerListsManager.GetServer(guild); if (server.Votes.Count >= Config.bot.VoteSettings.MaxRunningVotesPerGuild) { await channel.SendMessageAsync( $"There are already {Config.bot.VoteSettings.MaxRunningVotesPerGuild} votes running on this guild right now!\nEnd a vote to start a new one."); return; } //Setup Emojis Emoji yesEmote = new Emoji(yesEmoji); Emoji noEmote = new Emoji(noEmoji); //Setup embed EmbedBuilder embed = new EmbedBuilder(); embed.WithTitle("Setting up vote..."); //Send the message and add the initial reactions IUserMessage voteMessage = await channel.SendMessageAsync("", false, embed.Build()); await voteMessage.AddReactionAsync(yesEmote); await voteMessage.AddReactionAsync(noEmote); Vote newVote = new Vote { VoteMessageId = voteMessage.Id, VoteMessageChannelId = channel.Id, VoteTitle = voteTitle, VoteDescription = voteDescription, VoteStarterUserId = userWhoExecuted.Id, NoCount = 0, YesCount = 0, NoEmoji = noEmoji, YesEmoji = yesEmoji, VoteLastTime = lastTime, VoteStartTime = DateTime.Now, CancellationToken = new CancellationTokenSource() }; //User last vote UserAccountsManager.GetAccount((SocketGuildUser)userWhoExecuted).UserLastVoteId = voteMessage.Id; UserAccountsManager.SaveAccounts(); //Add our vote to the server list server.Votes.Add(newVote); ServerListsManager.SaveServerList(); embed.WithTitle(voteTitle); embed.WithDescription(voteDescription + $"\nReact to this message with {yesEmoji} to say **YES** or react with {noEmoji} to say **NO**."); embed.WithFooter( $"Vote started by {userWhoExecuted} at {DateTime.Now:g} and will end at {DateTime.Now.Add(lastTime):g}.", userWhoExecuted.GetAvatarUrl()); await MessageUtils.ModifyMessage(voteMessage, embed); await RunVote(newVote, guild); }
public static void SendMainMessage(DiscordSocketClient client, RestTextChannel channel, SocketUser user, TicketChild child) { var message = channel.SendMessageAsync("", false, GetLockEmbed(child, user.Mention)); message.Wait(); message.Result.AddReactionAsync(LockEmoji); child.MainMessageId = message.Result.Id; }
private Task UserUpdatedEventHandler(SocketUser user, SocketVoiceState before, SocketVoiceState after) { if (!(user is SocketGuildUser guildUser)) { return(Task.CompletedTask); } var botUserPerms = guildUser.Guild.CurrentUser.GuildPermissions; if (before.VoiceChannel == after.VoiceChannel) { return(Task.CompletedTask); } using var uow = _db.UnitOfWork; var gc = uow.GuildConfigs.For(guildUser.Guild.Id); if (!gc.VoicePlusTextEnabled) { return(Task.CompletedTask); } var _ = Task.Run(async() => { try { if (!botUserPerms.ManageChannels || !botUserPerms.ManageRoles) { try { await guildUser.Guild.Owner.SendErrorAsync(_strings.GetText("administration", "vt_exit", guildUser.Guild.Id, Format.Bold(guildUser.Guild.Name))).ConfigureAwait(false); } catch { } gc.VoicePlusTextEnabled = false; await uow.SaveChangesAsync().ConfigureAwait(false); } else { var semaphore = _guildLockObjects.GetOrAdd(guildUser.Guild.Id, (key) => new SemaphoreSlim(1, 1)); try { await semaphore.WaitAsync().ConfigureAwait(false); var beforeVch = before.VoiceChannel; if (beforeVch != null) { var beforeRoleName = GetRoleName(beforeVch); var beforeRole = guildUser.Guild.Roles.FirstOrDefault(x => x.Name.Equals(beforeRoleName, StringComparison.OrdinalIgnoreCase)); if (beforeRole != null) { _log.Info($"Removing role {beforeRoleName} from user {guildUser.Username}"); await guildUser.RemoveRoleAsync(beforeRole).ConfigureAwait(false); await Task.Delay(200).ConfigureAwait(false); } } var afterVch = after.VoiceChannel; if (afterVch != null && guildUser.Guild.AFKChannel?.Id != afterVch.Id) { var roleToAdd = guildUser.Guild.Roles.FirstOrDefault(x => x.Name.Equals(GetRoleName(afterVch), StringComparison.OrdinalIgnoreCase)); if (roleToAdd != null) { _log.Info($"Adding role {roleToAdd.Name} to user {guildUser.Username}"); await guildUser.AddRoleAsync(roleToAdd).ConfigureAwait(false); } } } finally { semaphore.Release(); } } } catch (Exception ex) { _log.Warn(ex); } }); return(Task.CompletedTask); }
public static async Task<IUserMessage> ReplyAsync(SocketUser user, IMessageChannel channel, string text, bool mentionUser) { try { if (!string.IsNullOrWhiteSpace(text)) { if (channel as IPrivateChannel != null || !mentionUser) return await channel.SendMessageAsync(text); else return await channel.SendMessageAsync($"{user.Mention}: {text}"); } } catch (Exception e) { LogError("Couldn't send message.", e.Message); } return null; }
public static async Task <int> Get(SocketUser user) => await Get(user.Id);