public async Task UserInfo(IUserMessage msg, IGuildUser usr = null) { var channel = (ITextChannel)msg.Channel; var user = usr ?? msg.Author as IGuildUser; if (user == null) return; var toReturn = $"👤 __`Name:`__ **{user.Username}#{user.Discriminator}**\n"; if (!string.IsNullOrWhiteSpace(user.Nickname)) toReturn += $"🆕 __`Nickname:`__ **{user.Nickname}** "; toReturn += $@"🏷 __`ID:`__ **{user.Id}** 🎮 __`Current Game:`__ **{(user.Game?.Name == null ? "-" : user.Game.Name)}** 📅 __`Joined Server:`__ **{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}** 🗓 __`Joined Discord:`__ **{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}** ⚔ __`Roles:`__ **({user.Roles.Count()}) - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}**"; if (!string.IsNullOrWhiteSpace(user.AvatarUrl)) toReturn += $@" 📷 __`Avatar URL:`__ **{await NadekoBot.Google.ShortenUrl(user.AvatarUrl).ConfigureAwait(false)}**"; await msg.Reply(toReturn).ConfigureAwait(false); }
public static async Task TriggeredAntiProtection(IGuildUser[] users, PunishmentAction action, ProtectionType protection) { if (users.Length == 0) return; LogSetting logSetting; if (!GuildLogSettings.TryGetValue(users.First().Guild.Id, out logSetting) || !logSetting.IsLogging) return; ITextChannel logChannel; if ((logChannel = TryGetLogChannel(users.First().Guild, logSetting)) == null) return; var punishment = ""; if (action == PunishmentAction.Mute) { punishment = "🔇 MUTED"; //punishment = "MUTED"; } else if (action == PunishmentAction.Kick) { punishment = "☣ SOFT-BANNED (KICKED)"; //punishment = "KICKED"; } else if (action == PunishmentAction.Ban) { punishment = "⛔️ BANNED"; //punishment = "BANNED"; } await logChannel.SendMessageAsync(String.Join("\n",users.Select(user=>$"‼️ {Format.Bold(user.ToString())} got **{punishment}** due to __**{protection}**__ protection on **{user.Guild.Name}** server."))) //await logChannel.SendMessageAsync(String.Join("\n",users.Select(user=>$"{Format.Bold(user.ToString())} was **{punishment}** due to `{protection}` protection on **{user.Guild.Name}** server."))) .ConfigureAwait(false); }
public static async Task AddCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage) { await AddCurrencyAsync(author.Id, reason, amount); if (sendMessage) try { await author.SendMessageAsync($"`You received:` {amount} {Gambling.CurrencySign}\n`Reason:` {reason}").ConfigureAwait(false); } catch { } }
public static async Task<bool> RemoveCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage) { var success = await RemoveCurrencyAsync(author.Id, reason, amount); if (success && sendMessage) try { await author.SendMessageAsync($"`You lost:` {amount} {Gambling.CurrencySign}\n`Reason:` {reason}").ConfigureAwait(false); } catch { } return success; }
private Task UserJoined(IGuildUser user) { var joinedTask = Task.Run(async () => { try { GuildConfig conf; using (var uow = DbHandler.UnitOfWork()) { conf = uow.GuildConfigs.For(user.Guild.Id); } if (conf.SendChannelGreetMessage) { var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.GreetMessageChannelId); if (channel != null) //maybe warn the server owner that the channel is missing { var msg = conf.ChannelGreetMessageText.Replace("%user%", user.Mention).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name); if (!string.IsNullOrWhiteSpace(msg)) { try { var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); if (conf.AutoDeleteGreetMessagesTimer > 0) { var t = Task.Run(async () => { await Task.Delay(conf.AutoDeleteGreetMessagesTimer * 1000).ConfigureAwait(false); // 5 minutes try { await toDelete.DeleteAsync().ConfigureAwait(false); } catch { } }); } } catch (Exception ex) { _log.Warn(ex); } } } } if (conf.SendDmGreetMessage) { var channel = await user.CreateDMChannelAsync(); if (channel != null) { var msg = conf.DmGreetMessageText.Replace("%user%", user.Username).Replace("%server%", user.Guild.Name); if (!string.IsNullOrWhiteSpace(msg)) { await channel.SendMessageAsync(msg).ConfigureAwait(false); } } } } catch { } }); return Task.CompletedTask; }
public async Task<string> Admin_TimeoutUserAsync (CommandArgs e, double minutes, IGuildUser user) { var response = await TimeoutUserAsync(e, minutes, user); if (response == 1) return $"timed out {user.Mention} for {minutes} minutes."; else if (response == 2) return $"added {minutes} more minutes to {user.Mention}'s timeout."; else if (response == 3) return $"removed {user.Mention}'s time out. Hooray!"; else return $"failed to time out {user.Mention}. You might stupid."; }
/// <summary> /// Times out a user. /// </summary> /// <param name="minutes">How long to time the user out.</param> /// <param name="user">User to time out</param> /// <returns>0, 1, 2 or 3 if the timing out failed, succeeded, time was added or the time out was removed. Respectively.</returns> public async Task<int> TimeoutUserAsync(CommandArgs e, double minutes, IGuildUser user) { List<TimedoutUser> users; timedoutUsers.TryGetValue(e.Guild.Id, out users); if (users == null) { users = new List<TimedoutUser>(); timedoutUsers.Add(e.Guild.Id, users); } var userTimeout = users.FirstOrDefault(x => x.userID == user.Id); if (userTimeout == null) { if (minutes <= 0) return 0; //Failed await StartTimeoutAsync(e, minutes, user, users); return 1; } else { if (minutes <= 0) { await StopTimeoutAsync(users, userTimeout, user, e.Guild); return 3; } var timeToAdd = (DateTime.Now - userTimeout.t).TotalMinutes; timeToAdd = userTimeout.timeoutTime - timeToAdd; Console.WriteLine($"{user.Username}'s timeout has been lengthed to {timeToAdd + minutes}"); await StopTimeoutAsync(users, userTimeout, user, e.Guild); await StartTimeoutAsync(e, timeToAdd + minutes, user, users); return 2; // Time added } }
private Task _client_UserJoined(IGuildUser usr) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserJoined) return Task.CompletedTask; ITextChannel logChannel; if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null) return Task.CompletedTask; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"❕🕓`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__✅ **| USER JOINED |** 🆔 `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); return Task.CompletedTask; }
private Task _client_UserUpdated(IGuildUser before, IGuildUser after) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(before.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserUpdated) return Task.CompletedTask; ITextChannel logChannel; if ((logChannel = TryGetLogChannel(before.Guild, logSetting)) == null) return Task.CompletedTask; var task = Task.Run(async () => { try { string str = $"🕔`{prettyCurrentTime}`"; if (before.Username != after.Username) //str += $"**Name Changed**`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; str += $"👤__**{before.Username}#{before.Discriminator}**__ **| Name Changed |** 🆔 `{before.Id}`\n\t\t`New:` **{after.ToString()}**"; else if (before.Nickname != after.Nickname) str += $"👤__**{before.Username}#{before.Discriminator}**__ **| Nickname Changed |** 🆔 `{before.Id}`\n\t\t`Old:` **{before.Nickname}#{before.Discriminator}**\n\t\t`New:` **{after.Nickname}#{after.Discriminator}**"; //str += $"**Nickname Changed**`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; else if (before.AvatarUrl != after.AvatarUrl) //str += $"**Avatar Changed**👤`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; str += $"👤__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** 🆔 `{before.Id}`\n\t🖼 {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; else if (!before.Roles.SequenceEqual(after.Roles)) { if (before.Roles.Count() < after.Roles.Count()) { var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); //str += $"**User's Roles changed ⚔➕**👤`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; str += $"👤__**{before.ToString()}**__ **| User's Role Added |** 🆔 `{before.Id}`\n\t✅ {string.Join(", ", diffRoles)}\n\t\t⚔ **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** ⚔"; } else if (before.Roles.Count() > after.Roles.Count()) { var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); //str += $"**User's Roles changed **`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; str += $"👤__**{before.ToString()}**__ **| User's Role Removed |** 🆔 `{before.Id}`\n\t🚮 {string.Join(", ", diffRoles)}\n\t\t⚔ **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** ⚔"; } } else return; try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } catch { } }); return Task.CompletedTask; }
public async Task <MemoryStream> GenerateImageAsync(IGuildUser user) { var stats = await GetUserStatsAsync(user); return(await GenerateImageAsync(stats)); }
private async Task RescanUser(IGuildUser user, StreamRoleSettings setting, IRole addRole = null) { if (user.Game.HasValue && user.Game.Value.StreamType != StreamType.NotStreaming && setting.Enabled && !setting.Blacklist.Any(x => x.UserId == user.Id) && user.RoleIds.Contains(setting.FromRoleId) && (string.IsNullOrWhiteSpace(setting.Keyword) || user.Game.Value.Name.ToLowerInvariant().Contains(setting.Keyword.ToLowerInvariant()) || setting.Whitelist.Any(x => x.UserId == user.Id))) { try { addRole = addRole ?? user.Guild.GetRole(setting.AddRoleId); if (addRole == null) { throw new StreamRoleNotFoundException(); } //check if he doesn't have addrole already, to avoid errors if (!user.RoleIds.Contains(setting.AddRoleId)) { await user.AddRoleAsync(addRole).ConfigureAwait(false); } _log.Info("Added stream role to user {0} in {1} server", user.ToString(), user.Guild.ToString()); } catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.Forbidden) { await StopStreamRole(user.Guild).ConfigureAwait(false); _log.Warn("Error adding stream role(s). Forcibly disabling stream role feature."); _log.Error(ex); throw new StreamRolePermissionException(); } catch (Exception ex) { _log.Warn("Failed adding stream role."); _log.Error(ex); } } else { //check if user is in the addrole if (user.RoleIds.Contains(setting.AddRoleId)) { try { addRole = addRole ?? user.Guild.GetRole(setting.AddRoleId); if (addRole == null) { throw new StreamRoleNotFoundException(); } await user.RemoveRoleAsync(addRole).ConfigureAwait(false); _log.Info("Removed stream role from a user {0} in {1} server", user.ToString(), user.Guild.ToString()); } catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.Forbidden) { await StopStreamRole(user.Guild).ConfigureAwait(false); _log.Warn("Error removing stream role(s). Forcibly disabling stream role feature."); _log.Error(ex); throw new StreamRolePermissionException(); } _log.Info("Removed stream role from the user {0} in {1} server", user.ToString(), user.Guild.ToString()); } } }
private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => $"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content;
public async Task <(AssignResult Result, bool AutoDelete, object extra)> Assign(IGuildUser guildUser, IRole role) { LevelStats userLevelData; using (var uow = _db.UnitOfWork) { var stats = uow.Xp.GetOrCreateUser(guildUser.Guild.Id, guildUser.Id); userLevelData = new LevelStats(stats.Xp + stats.AwardedXp); } var(autoDelete, exclusive, roles) = GetAdAndRoles(guildUser.Guild.Id); var theRoleYouWant = roles.FirstOrDefault(r => r.RoleId == role.Id); if (theRoleYouWant == null) { return(AssignResult.Err_Not_Assignable, autoDelete, null); } else if (theRoleYouWant.LevelRequirement > userLevelData.Level) { return(AssignResult.Err_Lvl_Req, autoDelete, theRoleYouWant.LevelRequirement); } else if (guildUser.RoleIds.Contains(role.Id)) { return(AssignResult.Err_Already_Have, autoDelete, null); } var roleIds = roles .Where(x => x.Group == theRoleYouWant.Group) .Select(x => x.RoleId).ToArray(); if (exclusive) { var sameRoles = guildUser.RoleIds .Where(r => roleIds.Contains(r)); foreach (var roleId in sameRoles) { var sameRole = guildUser.Guild.GetRole(roleId); if (sameRole != null) { try { await guildUser.RemoveRoleAsync(sameRole).ConfigureAwait(false); await Task.Delay(300).ConfigureAwait(false); } catch { // ignored } } } } try { await guildUser.AddRoleAsync(role).ConfigureAwait(false); } catch (Exception ex) { return(AssignResult.Err_Not_Perms, autoDelete, ex); } return(AssignResult.Assigned, autoDelete, null); }
public static async Task StopTimeoutAsync(List<TimedoutUser> users, TimedoutUser info, IGuildUser user, IGuild guild) { users.Remove(info); Console.WriteLine($"{user.Username}'s time out has been removed!"); var role = guild.Roles.FirstOrDefault(x => x.Name == "qttimedout"); var userroles = user.RoleIds.ToList(); userroles.Remove(role.Id); try { await user.ModifyAsync(x => x.RoleIds = userroles.ToArray()); } catch (Exception) { } info.timer.Dispose(); return; }
public async Task SetBack(IGuildUser user) { await SetBack(forced : true, forceUser : user); }
public async Task SetBack(bool forced = false, IGuildUser forceUser = null) { try { IGuildUser user = null; StringBuilder sb = new StringBuilder(); var data = new AwayData(); if (forced) { user = forceUser; } else { user = Context.User as IGuildUser; } string userName = string.Empty; string userMentionName = string.Empty; if (user != null) { userName = user.Username; userMentionName = user.Mention; } var attempt = data.getAwayUser(userName); var away = new AwaySystem(); if (attempt != null) { away.UserName = attempt.UserName; away.Status = attempt.Status; if (!(bool)away.Status) { sb.AppendLine($"You're not even away yet, **{userMentionName}**"); } else { away.Status = false; away.Message = string.Empty; var awayData = new AwayData(); awayData.setAwayUser(away); string awayDuration = string.Empty; if (attempt.TimeAway.HasValue) { var awayTime = DateTime.Now - attempt.TimeAway; if (awayTime.HasValue) { awayDuration = $"**{awayTime.Value.Days}** days, **{awayTime.Value.Hours}** hours, **{awayTime.Value.Minutes}** minutes, and **{awayTime.Value.Seconds}** seconds"; } } if (forced) { sb.AppendLine($"You're now set as back **{userMentionName}** (forced by: **{Context.User.Username}**)!"); } else { sb.AppendLine($"You're now set as back, **{userMentionName}**!"); } sb.AppendLine($"You were away for: [{awayDuration}]"); } await _cc.Reply(Context, sb.ToString()); } } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Something went wrong marking you as back :("); _logger.LogError($"Back command error {ex.Message}"); await _cc.Reply(Context, sb.ToString()); } }
Task <bool> IPermissionConfig.RemoveSpecialUser(ITextChannel channel, IGuildUser user) { return(Task.FromResult(SpecialPermissionUsersList[channel.Id].Remove(user.Id))); }
Task IPermissionConfig.AddUser(IGuildUser user) { return(Task.CompletedTask); }
public async Task Ban(IGuildUser userToBan = null, [Remainder] string reason = null) { if (userToBan == null) { await ReplyAsync("Please specify a user!"); return; } if (reason == null) { reason = "Not specified"; } IGuildUser user = null; IGuildUser userInEmbed = null; ulong userID; if (ulong.TryParse(userToBan.ToString(), out userID)) { user = Context.Guild.GetUser(userID); if (user.Id == Context.User.Id) { await ReplyAsync("You cannot ban yourself, sorry!"); return; } if (user.Id == 720579758026522667) { await ReplyAsync("I cannot ban myself, sorry!"); return; } await Context.Guild.AddBanAsync(user, 7, reason); userInEmbed = user; } else { if (userToBan.Id == Context.User.Id) { await ReplyAsync("You cannot ban yourself, sorry!"); return; } if (userToBan.Id == 720579758026522667) { await ReplyAsync("I cannot ban myself, sorry!"); return; } await Context.Guild.AddBanAsync(userToBan, 7, reason); userInEmbed = userToBan; } var EmbedBuilderReply = new EmbedBuilder(); var EmbedBuilderDM = new EmbedBuilder(); EmbedBuilderReply.WithTitle($":white_check_mark: {userInEmbed.Username}#{userInEmbed.Discriminator} was banned"); EmbedBuilderReply.WithDescription($"User {userInEmbed.Mention} has been successfully banned"); EmbedBuilderReply.AddField("Moderator", Context.User.Mention, true); EmbedBuilderReply.AddField("Reason", reason, true); Embed embed = EmbedBuilderReply.Build(); await ReplyAsync(embed : embed); EmbedBuilderDM.WithTitle($"You have been banned from **{Context.Guild.Name}**!"); EmbedBuilderDM.AddField("Reason", reason, true); Embed embedDM = EmbedBuilderDM.Build(); await userInEmbed.SendMessageAsync(embed : embedDM); ITextChannel logChannel = Context.Client.GetChannel(Global.ModLogChannel) as ITextChannel; var EmbedBuilderLog = new EmbedBuilder(); EmbedBuilderLog.WithTitle($"{userInEmbed.Username}#{userInEmbed.Discriminator} was banned"); EmbedBuilderLog.AddField("Moderator", Context.User.Mention, true); EmbedBuilderLog.AddField("Reason", reason, true); Embed embedLog = EmbedBuilderLog.Build(); await logChannel.SendMessageAsync(embed : embedLog); }
private Task Client_MessageReceived(SocketMessage msg) { var _ = Task.Run(async() => { await _moveLock.WaitAsync().ConfigureAwait(false); try { var curUser = _users[_curUserIndex]; if (_phase == Phase.Ended || msg.Author?.Id != curUser.Id) { return; } if (int.TryParse(msg.Content, out var index) && --index >= 0 && index <= 9 && _state[index / 3, index % 3] == null) { _state[index / 3, index % 3] = _curUserIndex; // i'm lazy if (_state[index / 3, 0] == _state[index / 3, 1] && _state[index / 3, 1] == _state[index / 3, 2]) { _state[index / 3, 0] = _curUserIndex + 2; _state[index / 3, 1] = _curUserIndex + 2; _state[index / 3, 2] = _curUserIndex + 2; _phase = Phase.Ended; } else if (_state[0, index % 3] == _state[1, index % 3] && _state[1, index % 3] == _state[2, index % 3]) { _state[0, index % 3] = _curUserIndex + 2; _state[1, index % 3] = _curUserIndex + 2; _state[2, index % 3] = _curUserIndex + 2; _phase = Phase.Ended; } else if (_curUserIndex == _state[0, 0] && _state[0, 0] == _state[1, 1] && _state[1, 1] == _state[2, 2]) { _state[0, 0] = _curUserIndex + 2; _state[1, 1] = _curUserIndex + 2; _state[2, 2] = _curUserIndex + 2; _phase = Phase.Ended; } else if (_curUserIndex == _state[0, 2] && _state[0, 2] == _state[1, 1] && _state[1, 1] == _state[2, 0]) { _state[0, 2] = _curUserIndex + 2; _state[1, 1] = _curUserIndex + 2; _state[2, 0] = _curUserIndex + 2; _phase = Phase.Ended; } var reason = ""; if (_phase == Phase.Ended) // if user won, stop receiving moves { reason = GetText("ttt_matched_three"); _winner = _users[_curUserIndex]; _client.MessageReceived -= Client_MessageReceived; OnEnded?.Invoke(this); } else if (IsDraw()) { reason = GetText("ttt_a_draw"); _phase = Phase.Ended; _client.MessageReceived -= Client_MessageReceived; OnEnded?.Invoke(this); } var sendstate = Task.Run(async() => { var del1 = msg.DeleteAsync(); var del2 = _previousMessage?.DeleteAsync(); try { _previousMessage = await _channel.EmbedAsync(GetEmbed(reason)).ConfigureAwait(false); } catch { } try { await del1.ConfigureAwait(false); } catch { } try { if (del2 != null) { await del2.ConfigureAwait(false); } } catch { } }); _curUserIndex ^= 1; _timeoutTimer.Change(_options.TurnTimer * 1000, Timeout.Infinite); } } finally { _moveLock.Release(); } }); return(Task.CompletedTask); }
/// <summary> /// Handles a command, represented in the given message. /// </summary> private async Task HandleCommand(SocketMessage s, DiscordSocketClient client) { if (!(s is SocketUserMessage msg)) { return; } int argPos = 0; if (!msg.HasStringPrefix(CommandPrefix, ref argPos)) { return; } IGuildUser author = s.Author as IGuildUser; CommandContext context = new CommandContext(client, msg); Log.WriteLine($"{msg.Author} attempted to invoke \"{msg.Content}\"."); if (context.IsPrivate) { // Don't allow bot usage in private messages await context.Channel.SendMessageAsync("I'm sorry but you can't use commands here since they don't work in DMs (not my fault, I swear :eyes:). Please run the commands in our server! :smile:"); return; } // Check if there is a custom command registered under the name string commandName = msg.Content.Substring(argPos).Split(' ')[0].ToLowerInvariant(); CustomCommand customCommand = _customCommandModule.FindCommand(commandName); if (customCommand != null) { // Attempt to execute the custom command try { await customCommand.Execute(author, context.Channel); } // If an exception occurs, print it catch (Exception ex) { EmbedBuilder eb = new EmbedBuilder() .WithColor(Color.Red) .WithTitle("Error") .WithDescription(ex.Message); await context.Channel.SendMessageAsync(string.Empty, false, eb); } return; } else { // No custom command was found? Search the commands from the command modules. CommandInfo executedCommand = null; try { executedCommand = _commandService.Search(context, argPos).Commands.First().Command; } catch { // Also no regular command was found? Check all commands and custom commands if there was a close match somewhere IEnumerable <string> commandNames = _commandService.Commands .Where(c => // Make sure that only commands that can be used by the user get listed { PermissionRestrictionAttribute pra = c.Attributes.FirstOrDefault(a => a is PermissionRestrictionAttribute) as PermissionRestrictionAttribute; if (pra != null) { UserType roles = pra.AllowedRoles; // Allow the command usage if anyone can use it, or the user is a staff member if (roles.HasFlag(UserType.Everyone) || author.HasStaffRole()) { return(true); } // If the command is for gurus, check if the user has the guru role if (roles.HasFlag(UserType.Guru)) { return(author.HasGuruRole()); } return(false); } return(true); }) .Select(c => c.Name) .Concat(_data.CustomCommands.CommandNames) .Distinct(); const int LEVENSHTEIN_TOLERANCE = 2; string closeMatch = commandNames .ToDictionary(l => l, l => commandName.ToLowerInvariant().ComputeLevenshtein(l.ToLowerInvariant())) // Use lower casing to avoid too high intolerance .Where(l => l.Value <= LEVENSHTEIN_TOLERANCE) .OrderBy(l => l.Value) .FirstOrDefault().Key; if (closeMatch != null) { // A close match was found! Notify the user. EmbedBuilder eb = new EmbedBuilder() .WithColor(Color.Red) .WithTitle("Error") .WithDescription($"The command \"{commandName}\" could not be found. Did you mean \"{closeMatch}\"?"); await context.Channel.SendMessageAsync(string.Empty, false, eb); } // The entered command was just nonsense. Just ignore it. return; } PermissionRestrictionAttribute restriction = executedCommand.Attributes.FirstOrDefault(a => a is PermissionRestrictionAttribute) as PermissionRestrictionAttribute; if (restriction != null) { EmbedBuilder eb = new EmbedBuilder() .WithTitle("Insufficient permissions") .WithDescription("You don't have the required permissions to run that command.") .WithColor(Color.Red); bool denyInvokation = true; UserType roles = restriction.AllowedRoles; // Allow the command usage if anyone can use it, or the user is a staff member if (roles.HasFlag(UserType.Everyone) || author.HasStaffRole()) { denyInvokation = false; } // If the command is for gurus, check if the user has the guru role if (roles.HasFlag(UserType.Guru) && author.HasGuruRole()) { denyInvokation = false; } if (denyInvokation) { var message = await context.Channel.SendMessageAsync(string.Empty, false, eb); _ = message.TimedDeletion(5000); Log.WriteLine($"The command \"{msg.Content}\" failed with the reason InsufficientPermissions."); return; } } bool cooldownCommand = CheckIfCommandHasCooldown(executedCommand.Name.ToLower()); bool sameParamCommand = false; bool cooldownExpired = false; string parameters = ""; if (cooldownCommand && !UserHelper.HasStaffRole(s.Author as IGuildUser)) { sameParamCommand = CheckIfSameParameterCommand(executedCommand.Name.ToLower()); parameters = s.ToString().Remove(0, s.ToString().IndexOf(' ') + 1); cooldownExpired = HasCooldownExpired(executedCommand.Name, s.Author as IGuildUser, sameParamCommand, parameters); if (!cooldownExpired) { TimeSpan ts = GetTimeUntilCooldownHasExpired(executedCommand.Name.ToLower(), s.Author as IGuildUser, sameParamCommand, parameters); Embed eb = new EmbedBuilder() .WithTitle("Cooldown hasn't expired yet") .WithDescription($"{s.Author.Mention}, you can't run this command yet. Please wait {ts.Hours} hours, {ts.Minutes} minutes and {ts.Seconds} seconds.") .WithColor(Color.Orange); await context.Channel.SendMessageAsync(string.Empty, false, eb); return; } } IResult result = await _commandService.ExecuteAsync(context, argPos, ServiceProvider); if (!result.IsSuccess) { Log.WriteLine($"The command \"{msg.Content}\" failed with the reason {result.Error.Value}: \"{result.ErrorReason}\""); if (result.Error == CommandError.UnknownCommand || result.Error == CommandError.BadArgCount || result.Error == CommandError.ParseFailed) { return; } EmbedBuilder builder = new EmbedBuilder() .WithTitle("Error") .WithDescription(result.ErrorReason) .WithColor(Color.Red); IMessage errorMsg = await context.Channel.SendMessageAsync(string.Empty, false, builder.Build()); } else { if (cooldownCommand && !UserHelper.HasStaffRole(s.Author as IGuildUser)) { AddUserToCooldown(executedCommand.Name, s.Author as IGuildUser, sameParamCommand, parameters); } string command = executedCommand.Name; if (_data.Statistics.Has(command)) { _data.Statistics.Set(command, _data.Statistics.Get(command) + 1); } else { _data.Statistics.Add(command, 1); } } } }
public async Task JoinRace(IGuildUser u, int amount = 0) { var animal = ""; if (!animals.TryDequeue(out animal)) { await raceChannel.SendMessageAsync($"{u.Mention} `There is no running race on this server.`"); return; } var p = new Participant(u, animal, amount); if (participants.Contains(p)) { await raceChannel.SendMessageAsync($"{u.Mention} `You already joined this race.`"); return; } if (Started) { await raceChannel.SendMessageAsync($"{u.Mention} `Race is already started`"); return; } if (amount > 0) if (!await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)u, "BetRace", amount, true).ConfigureAwait(false)) { try { await raceChannel.SendMessageAsync($"{u.Mention} You don't have enough {Gambling.CurrencyName}s.").ConfigureAwait(false); } catch { } return; } participants.Add(p); await raceChannel.SendMessageAsync($"{u.Mention} **joined the race as a {p.Animal}" + (amount > 0 ? $" and bet {amount} {CurrencySign}!**" : "**")); }
public async Task Roles(IUserMessage msg, IGuildUser target, int page = 1) { var channel = (ITextChannel)msg.Channel; var guild = channel.Guild; const int RolesPerPage = 20; if (page < 1 || page > 100) return; if (target != null) { await msg.Reply($"⚔ **Page #{page} of roles for {target.Username}:** ```css\n• " + string.Join("\n• ", target.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); } else { await msg.Reply($"⚔ **Page #{page} of all roles on this server:** ```css\n• " + string.Join("\n• ", guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); } }
/*public static ulong ResolveChannel(IGuildUser user, IGuildChannel channel) * { * return ResolveChannel(user, channel, ResolveGuild(user)); * }*/ public static ulong ResolveChannel(IGuild guild, IGuildUser user, IGuildChannel channel, ulong guildPermissions) { ulong resolvedPermissions = 0; ulong mask = ChannelPermissions.All(channel).RawValue; if (GetValue(guildPermissions, GuildPermission.Administrator)) //Includes owner { resolvedPermissions = mask; //Owners and administrators always have all permissions } else { OverwritePermissions?perms; //Start with this user's guild permissions resolvedPermissions = guildPermissions; //Give/Take Everyone permissions perms = channel.GetPermissionOverwrite(guild.EveryoneRole); if (perms != null) { resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue; } //Give/Take Role permissions ulong deniedPermissions = 0UL, allowedPermissions = 0UL; foreach (var roleId in user.RoleIds) { if (roleId != guild.EveryoneRole.Id) { perms = channel.GetPermissionOverwrite(guild.GetRole(roleId)); if (perms != null) { allowedPermissions |= perms.Value.AllowValue; deniedPermissions |= perms.Value.DenyValue; } } } resolvedPermissions = (resolvedPermissions & ~deniedPermissions) | allowedPermissions; //Give/Take User permissions perms = channel.GetPermissionOverwrite(user); if (perms != null) { resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue; } //TODO: C#7 Typeswitch candidate var textChannel = channel as ITextChannel; if (textChannel != null) { if (!GetValue(resolvedPermissions, ChannelPermission.ReadMessages)) { //No read permission on a text channel removes all other permissions resolvedPermissions = 0; } else if (!GetValue(resolvedPermissions, ChannelPermission.SendMessages)) { //No send permissions on a text channel removes all send-related permissions resolvedPermissions &= ~(1UL << (int)ChannelPermission.SendTTSMessages); resolvedPermissions &= ~(1UL << (int)ChannelPermission.MentionEveryone); resolvedPermissions &= ~(1UL << (int)ChannelPermission.EmbedLinks); resolvedPermissions &= ~(1UL << (int)ChannelPermission.AttachFiles); } } resolvedPermissions &= mask; //Ensure we didnt get any permissions this channel doesnt support (from guildPerms, for example) } return(resolvedPermissions); }
public TimedoutUser(IGuildUser user) { this.userID = user.Id; }
public async Task UsrMdl(IUserMessage imsg, Module module, PermissionAction action, [Remainder] IGuildUser user) { var channel = (ITextChannel)imsg.Channel; using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission { PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = user.Id, SecondaryTarget = SecondaryPermissionType.Module, SecondaryTargetName = module.Name.ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, Verbose = config.VerbosePermissions }, (id, old) => { old.RootPermission = config.RootPermission; return(old); }); await uow.CompleteAsync().ConfigureAwait(false); } await channel.SendMessageAsync($"{(action.Value ? "Allowed" : "Denied")} usage of `{module.Name}` module for `{user}` user.").ConfigureAwait(false); }
public async Task VoiceUnmute(IUserMessage umsg, IGuildUser user) { var channel = (ITextChannel)umsg.Channel; try { await user.ModifyAsync(usr => usr.Mute = false).ConfigureAwait(false); await channel.SendMessageAsync($"🎙✅ **{user}** has been **voice unmuted** successfully.").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }
public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) { await textCh.SendErrorAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice (ITextChannel)Context.Channel, try rejoining.").ConfigureAwait(false); } throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) { throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); } var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server => { float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; using (var uow = DbHandler.UnitOfWork()) { vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume; } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async(s, song) => { try { if (lastFinishedMessage != null) { lastFinishedMessage.DeleteAfter(0); } lastFinishedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo))) .ConfigureAwait(false); if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.ProviderType == MusicType.Normal) { await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } }; mp.OnStarted += async(player, song) => { try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); } catch { } var sender = player as MusicPlayer; if (sender == null) { return; } try { if (playingMessage != null) { playingMessage.DeleteAfter(0); } playingMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Playing Song").WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo))) .ConfigureAwait(false); } catch { } }; mp.OnPauseChanged += async(paused) => { try { IUserMessage msg; if (paused) { msg = await textCh.SendConfirmAsync("🎵 Music playback **paused**.").ConfigureAwait(false); } else { msg = await textCh.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false); } if (msg != null) { msg.DeleteAfter(10); } } catch { } }; mp.SongRemoved += async(song, index) => { try { var embed = new EmbedBuilder() .WithAuthor(eab => eab.WithName("Removed song #" + (index + 1)).WithMusicIcon()) .WithDescription(song.PrettyName) .WithFooter(ef => ef.WithText(song.PrettyInfo)) .WithErrorColor(); await textCh.EmbedAsync(embed).ConfigureAwait(false); } catch { } }; return(mp); }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await SongHandler.ResolveSong(query, musicType).ConfigureAwait(false); if (resolvedSong == null) { throw new SongNotFoundException(); } musicPlayer.AddSong(resolvedSong, queuer.Username); } catch (PlaylistFullException) { try { await textCh.SendConfirmAsync($"🎵 Queue is full at **{musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}**."); } catch { } throw; } if (!silent) { try { //var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var queuedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Queued Song #" + (musicPlayer.Playlist.Count + 1)).WithMusicIcon()) .WithDescription($"{resolvedSong.PrettyName}\nQueue ") .WithThumbnailUrl(resolvedSong.Thumbnail) .WithFooter(ef => ef.WithText(resolvedSong.PrettyProvider))) .ConfigureAwait(false); if (queuedMessage != null) { queuedMessage.DeleteAfter(10); } } catch { } // if queued message sending fails, don't attempt to delete it } }
public static int GetPerms(CommandArgs e, IGuildUser u) { return GetPerms(e.Guild.Id, u); }
public static WoWSRegion GetUserWoWSRegion(this IGuildUser user) => GetUserWoWSRegion(user as SocketGuildUser);
public Task Award(ShmartNumber amount, [Leftover] IGuildUser usr) => Award(amount, usr.Id);
public static async Task UnmuteAsync(this IGuildUser user, ICommandContext context) => await user.RemoveRoleAsync(GetMutedRole(context));
public async Task MuteUser([Remainder] IGuildUser user) { await m_Service.MuteUser(Context.Guild, user); }
public static PermissionLevel GetPermissionLevel(this IGuildUser user, ICommandContext context) => (context is BrackeysBotContext botContext)
private Task _client_UserPresenceUpdated(IGuildUser usr, IPresence before, IPresence after) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.LogUserPresence || before.Status == after.Status) return Task.CompletedTask; ITextChannel logChannel; if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogChannelType.UserPresence)) == null) return Task.CompletedTask; string str; if (before.Status != after.Status) str = $"🔵`{prettyCurrentTime}`👤__**{usr.Username}**__ is now **{after.Status}**."; else str = $"👾`{prettyCurrentTime}`👤__**{usr.Username}**__ is now playing **{after.Game}**."; UserPresenceUpdates.AddOrUpdate(logChannel, new List<string>() { str }, (id, list) => { list.Add(str); return list; }); return Task.CompletedTask; }
private static string GetMessage(ITextChannel channel, IGuildUser user, IUserMessage message) => $"**{channel.Guild.Name} | {channel.Name}** `{user.Username}`: " + message.Content.SanitizeMentions();
public async Task WaifuClaimerAffinity([Remainder] IGuildUser u = null) { if (u?.Id == Context.User.Id) { await ReplyErrorLocalized("waifu_egomaniac").ConfigureAwait(false); return; } DiscordUser oldAff = null; var sucess = false; TimeSpan? remaining = null; using (var uow = _db.UnitOfWork) { var w = uow.Waifus.ByWaifuUserId(Context.User.Id); var newAff = u == null ? null : uow.DiscordUsers.GetOrCreate(u); var now = DateTime.UtcNow; if (w?.Affinity?.UserId == u?.Id) { } else if (!_cache.TryAddAffinityCooldown(Context.User.Id, out remaining)) { } else if (w == null) { var thisUser = uow.DiscordUsers.GetOrCreate(Context.User); uow.Waifus.Add(new WaifuInfo() { Affinity = newAff, Waifu = thisUser, Price = 1, Claimer = null }); sucess = true; uow._context.WaifuUpdates.Add(new WaifuUpdate() { User = thisUser, Old = null, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged }); } else { if (w.Affinity != null) { oldAff = w.Affinity; } w.Affinity = newAff; sucess = true; uow._context.WaifuUpdates.Add(new WaifuUpdate() { User = w.Waifu, Old = oldAff, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged }); } await uow.CompleteAsync().ConfigureAwait(false); } if (!sucess) { if (remaining != null) { await ReplyErrorLocalized("waifu_affinity_cooldown", Format.Bold(((int)remaining?.TotalHours).ToString()), Format.Bold(remaining?.Minutes.ToString())).ConfigureAwait(false); } else { await ReplyErrorLocalized("waifu_affinity_already").ConfigureAwait(false); } return; } if (u == null) { await ReplyConfirmLocalized("waifu_affinity_reset").ConfigureAwait(false); } else if (oldAff == null) { await ReplyConfirmLocalized("waifu_affinity_set", Format.Bold(u.ToString())).ConfigureAwait(false); } else { await ReplyConfirmLocalized("waifu_affinity_changed", Format.Bold(oldAff.ToString()), Format.Bold(u.ToString())).ConfigureAwait(false); } }
public async Task <(DiscordUser, bool, TimeSpan?)> ChangeAffinityAsync(IUser user, IGuildUser target) { DiscordUser oldAff = null; var success = false; TimeSpan? remaining = null; using (var uow = _db.UnitOfWork) { var w = uow.Waifus.ByWaifuUserId(user.Id); var newAff = target == null ? null : uow.DiscordUsers.GetOrCreate(target); var now = DateTime.UtcNow; if (w?.Affinity?.UserId == target?.Id) { } else if (!_cache.TryAddAffinityCooldown(user.Id, out remaining)) { } else if (w == null) { var thisUser = uow.DiscordUsers.GetOrCreate(user); uow.Waifus.Add(new WaifuInfo() { Affinity = newAff, Waifu = thisUser, Price = 1, Claimer = null }); success = true; uow._context.WaifuUpdates.Add(new WaifuUpdate() { User = thisUser, Old = null, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged }); } else { if (w.Affinity != null) { oldAff = w.Affinity; } w.Affinity = newAff; success = true; uow._context.WaifuUpdates.Add(new WaifuUpdate() { User = w.Waifu, Old = oldAff, New = newAff, UpdateType = WaifuUpdateType.AffinityChanged }); } await uow.CompleteAsync(); } return(oldAff, success, remaining); }
public Participant(IGuildUser u, string a, int amount) { this.User = u; this.Animal = a; this.AmountBet = amount; }
public async Task Setrole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role) { var channel = (ITextChannel)umsg.Channel; try { await usr.AddRolesAsync(role).ConfigureAwait(false); await channel.SendMessageAsync($"ℹ️ Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false); } catch (Exception ex) { await channel.SendMessageAsync("⚠️ Failed to add role. **Bot has insufficient permissions.**\n").ConfigureAwait(false); Console.WriteLine(ex.ToString()); } }
public async Task UserId(IUserMessage msg, IGuildUser target = null) { var usr = target ?? msg.Author; await msg.Reply($"🆔 of the user **{ usr.Username }** is `{ usr.Id }`").ConfigureAwait(false); }
public async Task Softban(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null) { var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(msg)) { msg = "❗️No reason provided."; } if (umsg.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)umsg.Author).Roles.Select(r => r.Position).Max()) { await channel.SendMessageAsync("⚠️ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; } try { await user.SendMessageAsync($"☣ **You have been SOFT-BANNED from `{channel.Guild.Name}` server.**\n" + $"⚖ *Reason:* {msg}").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); } catch { } try { await channel.Guild.AddBanAsync(user, 7).ConfigureAwait(false); try { await channel.Guild.RemoveBanAsync(user).ConfigureAwait(false); } catch { await channel.Guild.RemoveBanAsync(user).ConfigureAwait(false); } await channel.SendMessageAsync("☣ **Soft-Banned** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } }
public TimeoutInfo(List<TimedoutUser> users, TimedoutUser info, IGuildUser user, IGuild guild) { this.users = users; this.info = info; this.user = user; this.guild = guild; }
public async Task Mute(IUserMessage umsg, IGuildUser user) { var channel = (ITextChannel)umsg.Channel; try { await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false); await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); await channel.SendMessageAsync($"🔇 **{user}** has been **muted** from text and voice chat successfully.").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }
public async Task SetNick(IGuildUser gu, [Leftover] string newNick = null) { await gu.ModifyAsync(u => u.Nickname = newNick).ConfigureAwait(false); await ReplyConfirmLocalizedAsync("user_nick", Format.Bold(gu.ToString()), Format.Bold(newNick) ?? "-").ConfigureAwait(false); }
private async Task CheckStats(ICommandContext context) { try { StreamReader reader = new StreamReader(program.Config.SyncFile); StringReader input = new StringReader(reader.ReadToEnd()); reader.Close(); YamlStream yaml = new YamlStream(); yaml.Load(input); YamlMappingNode mapping = (YamlMappingNode)yaml.Documents[0].RootNode; Sync[] syncs = mapping.Children.Select(entry => new Sync { DiscordId = ulong.Parse(entry.Key.ToString()), SteamId = entry.Value.ToString() }).ToArray(); string[] args = context.Message.Content.Split(new string[1] { " " }, StringSplitOptions.None); Console.WriteLine(args.Length); Stats stats; EmbedBuilder embed; string steamId; string path; string steamName; ulong result1; if (args.Length > 1 && !ulong.TryParse(args[1], out result1)) { string name = args[1]; if (args[1].Contains("@")) { name = args[1].Replace("@", ""); name = name.Replace("<", ""); name = name.Replace(">", ""); if (name.Contains("!")) { name = name.Replace("!", ""); } } IEnumerable <IGuildUser> users = context.Guild.GetUsersAsync(CacheMode.CacheOnly).Result.Where(u => { ulong result; if (!ulong.TryParse(name, out result)) { return(u.Username == name); } return((long)u.Id == (long)result); }); IGuildUser user = users.OrderBy(u => u.Username.Length).First(); if (user != null) { ulong id = user.Id; if (syncs.All(s => (long)s.DiscordId != (long)id)) { await context.Channel.SendMessageAsync("User is not synced!"); } else { steamId = syncs[Array.FindIndex(syncs, s => (long)s.DiscordId == (long)id)].SteamId; path = program.Config.StatsFile + "/" + steamId + ".txt"; Console.WriteLine(path); if (!File.Exists(path)) { await context.Channel.SendMessageAsync("No stats found."); } else { steamName = await GetSteamName(steamId.Replace("@steam", "")); stats = DeserializeStats(path); embed = new EmbedBuilder(); if (string.IsNullOrEmpty(stats.LastKiller)) { stats.LastKiller = "None"; } if (string.IsNullOrEmpty(stats.LastVictim)) { stats.LastVictim = "None"; } embed.WithTitle("Joker's Playground Player Stats for: " + steamName + "(" + steamId + ")"); embed.AddField("Total Kills", stats.Kills, true); embed.AddField("Total SCP Kills", stats.ScpKills, true); embed.AddField("Deaths", stats.Deaths, true); embed.AddField("Suicides", stats.Suicides, true); embed.AddField("SCP-207 Drinks", stats.Scp207Uses, true); embed.AddField("SCP-018 Throws", stats.Scp018Throws, true); embed.AddField("Last Killed", stats.LastKiller, true); embed.AddField("Last Victim", stats.LastVictim, true); embed.AddField("KDR", stats.Krd, true); embed.AddField("Escapes Made", stats.Escapes, true); embed.AddField("Rounds Played", stats.RoundsPlayed); embed.AddField("Time Played", GetHRT(stats.SecondsPlayed)); embed.WithFooter(f => f.Text = "Joker's Playground Stats Bot by Joker119").WithColor(Color.Blue) .WithCurrentTimestamp(); await context.Channel.SendMessageAsync(null, false, embed.Build()); } } } else { await context.Channel.SendMessageAsync("User not found."); } } else if (args.Length > 1 && ulong.TryParse(args[1], out result1)) { steamId = args[1] + "@steam"; path = program.Config.StatsFile + "/" + steamId + ".txt"; Console.WriteLine(path); if (!File.Exists(path)) { await context.Channel.SendMessageAsync("No stats found."); } else { steamName = await GetSteamName(steamId.Replace("@steam", "")); stats = DeserializeStats(path); embed = new EmbedBuilder(); if (string.IsNullOrEmpty(stats.LastKiller)) { stats.LastKiller = "None"; } if (string.IsNullOrEmpty(stats.LastVictim)) { stats.LastVictim = "None"; } embed.WithTitle("Joker's Playground Player Stats for: " + steamName + "(" + steamId + ")"); embed.AddField("Total Kills", stats.Kills, true); embed.AddField("Total SCP Kills", stats.ScpKills, true); embed.AddField("Deaths", stats.Deaths, true); embed.AddField("Suicides", stats.Suicides, true); embed.AddField("SCP-207 Drinks", stats.Scp207Uses, true); embed.AddField("SCP-018 Throws", stats.Scp018Throws, true); embed.AddField("Last Killed", stats.LastKiller, true); embed.AddField("Last Victim", stats.LastVictim, true); embed.AddField("KDR", stats.Krd, true); embed.AddField("Escapes Made", stats.Escapes, true); embed.AddField("Rounds Played", stats.RoundsPlayed); embed.AddField("Time Played", GetHRT(stats.SecondsPlayed)); embed.WithFooter(f => f.Text = "Joker's Playground Stats Bot by Joker119").WithColor(Color.Blue) .WithCurrentTimestamp(); await context.Channel.SendMessageAsync("", false, embed.Build()); } } else if (syncs.All(s => (long)s.DiscordId != (long)context.Message.Author.Id)) { await context.Channel.SendMessageAsync("Your discord is not synced!"); } else { steamId = syncs[Array.FindIndex(syncs, s => (long)s.DiscordId == (long)context.Message.Author.Id)].SteamId; path = program.Config.StatsFile + "/" + steamId + ".txt"; Console.WriteLine(path); if (!File.Exists(path)) { await context.Channel.SendMessageAsync("No stats found."); } else { steamName = await GetSteamName(steamId.Replace("@steam", "")); stats = DeserializeStats(path); embed = new EmbedBuilder(); if (string.IsNullOrEmpty(stats.LastKiller)) { stats.LastKiller = "None"; } if (string.IsNullOrEmpty(stats.LastVictim)) { stats.LastVictim = "None"; } embed.WithTitle("Joker's Playground Player Stats for: " + steamName + "(" + steamId + ")"); embed.AddField("Total Kills", stats.Kills, true); embed.AddField("Total SCP Kills", stats.ScpKills, true); embed.AddField("Deaths", stats.Deaths, true); embed.AddField("Suicides", stats.Suicides, true); embed.AddField("SCP-207 Drinks", stats.Scp207Uses, true); embed.AddField("SCP-018 Throws", stats.Scp018Throws, true); embed.AddField("Last Killed", stats.LastKiller, true); embed.AddField("Last Victim", stats.LastVictim, true); embed.AddField("KDR", stats.Krd, true); embed.AddField("Escapes Made", stats.Escapes, true); embed.AddField("Rounds Played", stats.RoundsPlayed); embed.AddField("Time Played", GetHRT(stats.SecondsPlayed)); embed.WithFooter(f => f.Text = "Joker's Playground Stats Bot by Joker119").WithColor(Color.Blue) .WithCurrentTimestamp(); await context.Channel.SendMessageAsync("", false, embed.Build()); } } } catch (Exception ex) { Console.WriteLine(ex); } }
private async Task StartTimeoutAsync(CommandArgs e, double minutes, IGuildUser user, List<TimedoutUser> users) { users.Add(new TimedoutUser(user)); var info = users[users.Count - 1]; info.SetTimer(new TimeSpan(0, (int)minutes, (int)minutes % 60), new TimeoutInfo(users, info, user, user.Guild)); timedoutUsers[user.GuildId] = new List<TimedoutUser>(users); info.t = DateTime.Now; info.timeoutTime = minutes; SocketRole role = null; var roles = e.Guild.Roles.ToArray(); for(int i = 0; i < roles.Length; i++) { if(roles[i].Name == "qttimedout") { role = roles[i]; break; } } if (role == null) return; var userroles = user.RoleIds.ToList(); userroles.Add(role.Id); try { await user.ModifyAsync(x => x.RoleIds = userroles.ToArray()); } catch (Exception) { } return; }
public async Task BanUserAsync(IGuildUser user, [Remainder] string reason = null) { await user.Guild.AddBanAsync(user, reason : reason); await ReplyAsync("ok!"); }
public async Task Removerole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role) { var channel = (ITextChannel)umsg.Channel; try { await usr.RemoveRolesAsync(role).ConfigureAwait(false); await channel.SendMessageAsync($"ℹ️ Successfully removed role **{role.Name}** from user **{usr.Username}**").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ Failed to remove role. Most likely reason: **Insufficient permissions.**").ConfigureAwait(false); } }
private async void Kick(IGuildUser user, IUserMessage message, IGuild guild) { try { if (await guild.GetUserAsync(user.Id) == null) { //already kicked by ReactionAdded event or server left return; } List <IUser> yesUser = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickYes)); List <IUser> noUser = new List <IUser>(await message.GetReactionUsersAsync(Information.VotekickNo)); string nl = Environment.NewLine; // -1 for own reaction int yes = yesUser.Count - 1; int no = noUser.Count - 1; //only users in a voice channel can votekick int online = new List <IGuildUser>(((await guild.GetUsersAsync()).Where(u => (u.Status == UserStatus.Online && u.VoiceChannel != null)))).Count; //more than half of server users voted yes if (yes > online / 2 && no < yes) { //check if admin voted no -> dismiss vote foreach (IUser iuser in noUser) { if (CheckIfAdmin(iuser as IGuildUser)) { await message.Channel.SendMessageAsync($"An admin voted _no_, _{Helper.GetName(user)}_ cannot be kicked!"); return; } } IInviteMetadata invite = await((IGuildChannel)message.Channel).CreateInviteAsync(maxUses: 1); try { IDMChannel dm = await user.CreateDMChannelAsync(); await dm.SendMessageAsync($"You've been kicked from the _{guild.Name}_ guild by votekick!" + nl + $"As I'm very generous today, here's an invite link to the _{guild.Name}_ guild:" + nl + invite.Url); } catch { //user is not allowing DMs? await message.Channel.SendMessageAsync($"{Helper.GetName(user)} is not allowing private messages, " + "someone gotta send him an invite link again.." + nl + invite.Url); } await user.KickAsync(); await message.Channel.SendMessageAsync($"You bullies kicked the poor {Helper.GetName(user)}.."); try { Cirilla.Client.ReactionAdded -= ReactionAdded; } catch { //event removed } } else { await message.Channel.SendMessageAsync($"Time's up. Less than half of the online users ({yes}) " + $"voted to kick {Helper.GetName(user)}. Votekick dismissed."); } } catch { await message.Channel.SendMessageAsync($"Could not kick {Helper.GetName(user)}.. :confused:"); } }
public async Task Kick(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null) { var channel = (ITextChannel)umsg.Channel; if (user == null) { await channel.SendMessageAsync("❗️User not found.").ConfigureAwait(false); return; } if (umsg.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)umsg.Author).Roles.Select(r => r.Position).Max()) { await channel.SendMessageAsync("⚠️ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; } if (!string.IsNullOrWhiteSpace(msg)) { try { await user.SendMessageAsync($"‼️**You have been KICKED from `{channel.Guild.Name}` server.**\n" + $"⚖ *Reason:* {msg}").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); } catch { } } try { await user.KickAsync().ConfigureAwait(false); await channel.SendMessageAsync("‼️**Kicked** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } }
public Task Warnlog(int page, IGuildUser user) => Warnlog(page, user.Id);
public async Task ChatUnmute(IUserMessage umsg, IGuildUser user) { var channel = (ITextChannel)umsg.Channel; try { await user.RemoveRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); await channel.SendMessageAsync($"✏️✅ **{user}** has been **unmuted** from chatting successfully.").ConfigureAwait(false); } catch { await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }
public Task Warnclear(IGuildUser user, int index = 0) => Warnclear(user.Id, index);
public async Task Prune(IUserMessage msg, IGuildUser user, int count = 100) { var channel = (ITextChannel)msg.Channel; int limit = (count < 100) ? count : 100; var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit)).Where(m => m.Author == user); await msg.Channel.DeleteMessagesAsync(enumerable); }
/// <summary> /// Finds and modifies a user document. /// </summary> /// <param name="user">The user to modify.</param> /// <param name="function">Modification of the user.</param> public Task ModifyUserAsync(IGuildUser user, Action <User> function) { return(ModifyAsync(y => y.UserId == user.Id && y.GuildId == user.GuildId, function)); }
public static int GetPerms(ulong serverId, IGuildUser u) { if (u.Id == (ulong)Storage.programInfo.DevID) return int.MaxValue; if (Storage.serverInfo.ContainsKey(serverId)) { var surfer = Storage.serverInfo[serverId]; int perm = 0; foreach (var role in u.RoleIds) { if (surfer.roleImportancy.ContainsKey(role)) { if (surfer.roleImportancy[role] > perm) perm = surfer.roleImportancy[role]; } } return perm; } //returns -1 if failed or role has no tier set. return -1; }
public Task Give(ShmartNumber amount, [Leftover] IGuildUser receiver) => Give(amount, receiver, null);
public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) await textCh.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server => { float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume; using (var uow = DbHandler.UnitOfWork()) { vol = uow.GuildConfigs.For(textCh.Guild.Id).DefaultMusicVolume; } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; IUserMessage lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) { try { if (lastFinishedMessage != null) await lastFinishedMessage.DeleteAsync().ConfigureAwait(false); if (playingMessage != null) await playingMessage.DeleteAsync().ConfigureAwait(false); try { lastFinishedMessage = await textCh.SendMessageAsync($"🎵`Finished`{song.PrettyName}").ConfigureAwait(false); } catch { } if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } } }; mp.OnStarted += async (s, song) => { if (song.PrintStatusMessage) { var sender = s as MusicPlayer; if (sender == null) return; var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`"; try { playingMessage = await textCh.SendMessageAsync(msgTxt).ConfigureAwait(false); } catch { } } }; return mp; }); Song resolvedSong; try { musicPlayer.ThrowIfQueueFull(); resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false); if (resolvedSong == null) throw new SongNotFoundException(); musicPlayer.AddSong(resolvedSong, queuer.Username); } catch (PlaylistFullException) { try { await textCh.SendMessageAsync($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); } catch { } throw; } if (!silent) { try { var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false); var t = Task.Run(async () => { try { await Task.Delay(10000).ConfigureAwait(false); await queuedMessage.DeleteAsync().ConfigureAwait(false); } catch { } }).ConfigureAwait(false); } catch { } // if queued message sending fails, don't attempt to delete it } }
public Task Award(ShmartNumber amount, IGuildUser usr, [Leftover] string msg) => Award(amount, usr.Id, msg);