static StreamNotificationCommands() { _log = NLog.LogManager.GetCurrentClassLogger(); checkTimer = new Timer(async(state) => { oldCachedStatuses = new ConcurrentDictionary <string, StreamStatus>(cachedStatuses); cachedStatuses.Clear(); IEnumerable <FollowedStream> streams; using (var uow = DbHandler.UnitOfWork()) { streams = uow.GuildConfigs.GetAllFollowedStreams(); } await Task.WhenAll(streams.Select(async fs => { try { var newStatus = await GetStreamStatus(fs).ConfigureAwait(false); if (FirstPass) { return; } StreamStatus oldStatus; if (oldCachedStatuses.TryGetValue(newStatus.ApiLink, out oldStatus) && oldStatus.IsLive != newStatus.IsLive) { var server = NadekoBot.Client.GetGuild(fs.GuildId); var channel = server?.GetTextChannel(fs.ChannelId); if (channel == null) { return; } try { await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); } catch { } } } catch { } })); FirstPass = false; }, null, TimeSpan.Zero, TimeSpan.FromSeconds(60)); }
private async Task InternalWarnlog(ulong userId, int page) { if (page < 0) { return; } Warning[] warnings; using (var uow = DbHandler.UnitOfWork()) { warnings = uow.Warnings.For(Context.Guild.Id, userId); } warnings = warnings.Skip(page * 9) .Take(9) .ToArray(); var embed = new EmbedBuilder().WithOkColor() .WithTitle(GetText("warnlog_for", (Context.Guild as SocketGuild)?.GetUser(userId)?.ToString() ?? userId.ToString())) .WithFooter(efb => efb.WithText(GetText("page", page + 1))); if (!warnings.Any()) { embed.WithDescription(GetText("warnings_none")); } else { foreach (var w in warnings) { var name = GetText("warned_on_by", w.DateAdded.Value.ToString("dd.MM.yyy"), w.DateAdded.Value.ToString("HH:mm"), w.Moderator); if (w.Forgiven) { name = Format.Strikethrough(name) + " " + GetText("warn_cleared_by", w.ForgivenBy); } embed.AddField(x => x .WithName(name) .WithValue(w.Reason)); } } await Context.Channel.EmbedAsync(embed); }
public async Task RoleCmd(CommandInfo command, PermissionAction action, [Remainder] IRole role) { if (role == role.Guild.EveryoneRole) { return; } using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission { PrimaryTarget = PrimaryPermissionType.Role, PrimaryTargetId = role.Id, SecondaryTarget = SecondaryPermissionType.Command, SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); Cache.AddOrUpdate(Context.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); } if (action.Value) { await ReplyConfirmLocalized("rx_enable", Format.Code(command.Aliases.First()), GetText("of_command"), Format.Code(role.Name)).ConfigureAwait(false); } else { await ReplyConfirmLocalized("rx_disable", Format.Code(command.Aliases.First()), GetText("of_command"), Format.Code(role.Name)).ConfigureAwait(false); } }
public async Task AntispamIgnore() { var channel = (ITextChannel)Context.Channel; var obj = new AntiSpamIgnore() { ChannelId = channel.Id }; bool added; using (var uow = DbHandler.UnitOfWork()) { var gc = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.AntiSpamSetting).ThenInclude(x => x.IgnoredChannels)); var spam = gc.AntiSpamSetting; if (spam == null) { return; } if (spam.IgnoredChannels.Add(obj)) { AntiSpamStats temp; if (_antiSpamGuilds.TryGetValue(Context.Guild.Id, out temp)) temp.AntiSpamSettings.IgnoredChannels.Add(obj); added = true; } else { spam.IgnoredChannels.Remove(obj); AntiSpamStats temp; if (_antiSpamGuilds.TryGetValue(Context.Guild.Id, out temp)) temp.AntiSpamSettings.IgnoredChannels.Remove(obj); added = false; } await uow.CompleteAsync().ConfigureAwait(false); } if (added) await ReplyConfirmLocalized("spam_ignore", "Anti-Spam").ConfigureAwait(false); else await ReplyConfirmLocalized("spam_not_ignore", "Anti-Spam").ConfigureAwait(false); }
public async Task Iamnot([Remainder] IRole role) { var guildUser = (IGuildUser)Context.User; bool autoDeleteSelfAssignedRoleMessages; IEnumerable <SelfAssignedRole> roles; using (var uow = DbHandler.UnitOfWork()) { autoDeleteSelfAssignedRoleMessages = uow.GuildConfigs.For(Context.Guild.Id, set => set).AutoDeleteSelfAssignedRoleMessages; roles = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id); } if (roles.FirstOrDefault(r => r.RoleId == (long)role.Id) == null) { await ReplyErrorLocalized("self_assign_not").ConfigureAwait(false); return; } if (!guildUser.RoleIds.Contains(role.Id)) { await ReplyErrorLocalized("self_assign_not_have", Format.Bold(role.Name)).ConfigureAwait(false); return; } try { await guildUser.RemoveRolesAsync(role).ConfigureAwait(false); } catch (Exception) { await ReplyErrorLocalized("self_assign_perms").ConfigureAwait(false); return; } var msg = await ReplyConfirmLocalized("self_assign_remove", Format.Bold(role.Name)).ConfigureAwait(false); if (autoDeleteSelfAssignedRoleMessages) { msg.DeleteAfter(3); Context.Message.DeleteAfter(3); } }
public async Task RepeatRemove(int index) { if (index < 1) { return; } index -= 1; ConcurrentQueue <RepeatRunner> rep; if (!repeaters.TryGetValue(Context.Guild.Id, out rep)) { return; } var repeaterList = rep.ToList(); if (index >= repeaterList.Count) { await Context.Channel.SendErrorAsync("Index out of range.").ConfigureAwait(false); return; } var repeater = repeaterList[index]; repeater.Stop(); repeaterList.RemoveAt(index); using (var uow = DbHandler.UnitOfWork()) { var guildConfig = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(gc => gc.GuildRepeaters)); guildConfig.GuildRepeaters.RemoveWhere(r => r.Id == repeater.Repeater.Id); await uow.CompleteAsync().ConfigureAwait(false); } if (repeaters.TryUpdate(Context.Guild.Id, new ConcurrentQueue <RepeatRunner>(repeaterList), rep)) { await Context.Channel.SendConfirmAsync("Message Repeater", $"#{index+1} stopped.\n\n{repeater.ToString()}").ConfigureAwait(false); } }
public async Task DeleteQuote([Remainder] string keyword) { if (string.IsNullOrWhiteSpace(keyword)) { return; } var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator; keyword = keyword.ToUpperInvariant(); var sucess = false; string response; using (var uow = DbHandler.UnitOfWork()) { var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword)?.Where(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id).ToArray(); if (qs == null || !qs.Any()) { sucess = false; response = "No quotes found which you can remove."; } else { var q = qs[new NadekoRandom().Next(0, qs.Length)]; uow.Quotes.Remove(q); await uow.CompleteAsync().ConfigureAwait(false); sucess = true; response = "🗑 **Deleted a random quote.**"; } } if (sucess) { await Context.Channel.SendConfirmAsync(response); } else { await Context.Channel.SendErrorAsync(response); } }
public async Task AllSrvrMdls(PermissionAction action) { using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission { PrimaryTarget = PrimaryPermissionType.Server, PrimaryTargetId = 0, SecondaryTarget = SecondaryPermissionType.AllModules, SecondaryTargetName = "*", State = action.Value, }; uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); var allowUser = new Permission { PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = Context.User.Id, SecondaryTarget = SecondaryPermissionType.AllModules, SecondaryTargetName = "*", State = true, }; var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, allowUser); Cache.AddOrUpdate(Context.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); } if (action.Value) { await ReplyConfirmLocalized("asm_enable").ConfigureAwait(false); } else { await ReplyConfirmLocalized("asm_disable").ConfigureAwait(false); } }
public void StartModuleTest() { DbHandler _dbh = new DbHandler(); // Eliminar archivo de datos serializados creado en prueba anteriores if (System.IO.File.Exists(_dbh.DbName)) { System.IO.File.Delete(_dbh.DbName); } Assert.IsNull(_dbh.DbRoot); _dbh.Start(); Assert.IsNotNull(_dbh.DbRoot); Assert.IsNotNull(_dbh.DbRoot.ClientManager); Assert.IsNotNull(_dbh.DbRoot.SystemConfig); _dbh.Stop(); }
public async Task Playlists([Remainder] int num = 1) { if (num <= 0) { return; } List <MusicPlaylist> playlists; using (var uow = DbHandler.UnitOfWork()) { playlists = uow.MusicPlaylists.GetPlaylistsOnPage(num); } var embed = new EmbedBuilder() .WithAuthor(eab => eab.WithName($"Page {num} of Saved Playlists").WithMusicIcon()) .WithDescription(string.Join("\n", playlists.Select(r => $"`#{r.Id}` - **{r.Name}** by *{r.Author}* ({r.Songs.Count} songs)"))) .WithOkColor(); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); }
public AddArmour(InventoryManager inventory) { InitializeComponent(); this.inventory = inventory; cbMod.Items.Add("STR"); cbMod.Items.Add("DEX"); cbMod.Items.Add("CON"); cbMod.Items.Add("INT"); cbMod.Items.Add("WIS"); cbMod.Items.Add("CHA"); cbMod.Items.Add("NA"); cbType.Items.Add("Light"); cbType.Items.Add("Medium"); cbType.Items.Add("Heavy"); cbType.Items.Add("Shield"); db = new DbHandler(); }
private string savePackage(DbHandler db, SqlConnection conn, LedorVadorFlowPackage package) { DataSet ds = db.Call("MIG_DocumentoFromQTECH_sp", conn, (SqlDataAdapter da) => { da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@HistClinica", DbType.Int32).Value = package.histClinica; da.SelectCommand.Parameters.AddWithValue("@RazonSocial", DbType.String).Value = package.razonSocial; da.SelectCommand.Parameters.AddWithValue("@EmpresaID_Propia", DbType.Int32).Value = package.empresaPropia; da.SelectCommand.Parameters.AddWithValue("@Documento_ExternID", DbType.String).Value = package.documento_externId; da.SelectCommand.Parameters.AddWithValue("@Establecimiento_Numero", DbType.String).Value = package.establecimiento_numero; da.SelectCommand.Parameters.AddWithValue("@Documento_Numero", DbType.String).Value = package.documento_numero; da.SelectCommand.Parameters.AddWithValue("@Fecha", DbType.DateTime).Value = package.fecha; da.SelectCommand.Parameters.AddWithValue("@Observacion", DbType.String).Value = package.observacion; da.SelectCommand.Parameters.AddWithValue("@TipoServicioID", DbType.Int32).Value = package.tipoServicioId; da.SelectCommand.Parameters.AddWithValue("@TipoImpuestoID_IVA", DbType.Int32).Value = package.tipoImpuestoId_Iva; da.SelectCommand.Parameters.AddWithValue("@Cantidad", DbType.Decimal).Value = package.cantidad; da.SelectCommand.Parameters.AddWithValue("@ImporteUnitario", DbType.Double).Value = package.importeUnitario; }); return(""); }
public async Task ResetPermissions() { var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.PermissionsFor(Context.Guild.Id); config.RootPermission = Permission.GetDefaultRoot(); var toAdd = new PermissionCache() { RootPermission = config.RootPermission, PermRole = config.PermissionRole, Verbose = config.VerbosePermissions, }; Cache.AddOrUpdate(channel.Guild.Id, toAdd, (id, old) => toAdd); await uow.CompleteAsync(); } await ReplyConfirmLocalized("perms_reset").ConfigureAwait(false); }
public T Add(T entity) { try { var sessionFactory = DbHandler.CreateSessionFactory(); using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(entity); transaction.Commit(); return(entity); } } } catch (Exception e) { throw new Exception(e.Message); } }
//Edits the Selected Item(Event) in the database and resets the UI elements bound to it public override void EditItem() { if (SelectedItem != null) { if (CheckDate(SelectedItem.ScheduledDate)) { DbHandler <Event> .UpdateItem(SelectedItem); SelectedItem = new Event() { ScheduledDate = DateTime.Now }; NotEditable = true; ItemsList = DbHandler <Event> .LoadElements(); SelectedItemFilter = EventListFilter.All_Active; ConfirmActionVisibility = System.Windows.Visibility.Hidden; } } }
public static PermissionCache GetCache(ulong guildId) { PermissionCache pc; if (!Permissions.Cache.TryGetValue(guildId, out pc)) { using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.For(guildId, set => set.Include(x => x.Permissions)); Permissions.UpdateCache(config); } Permissions.Cache.TryGetValue(guildId, out pc); if (pc == null) { throw new Exception("Cache is null."); } } return(pc); }
public async Task DelAllQuotes([Remainder] string keyword) { if (string.IsNullOrWhiteSpace(keyword)) { return; } keyword = keyword.ToUpperInvariant(); using (var uow = DbHandler.UnitOfWork()) { var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); //todo kwoth please don't be complete retard uow.Quotes.RemoveRange(quotes.ToArray());//wtf?! await uow.CompleteAsync(); } await Context.Channel.SendConfirmAsync($"🗑 **Deleted all quotes** with **{keyword}** keyword."); }
public async Task Repeat(IUserMessage imsg) { var channel = (ITextChannel)imsg.Channel; RepeatRunner rep; if (repeaters.TryRemove(channel.Id, out rep)) { using (var uow = DbHandler.UnitOfWork()) { uow.Repeaters.Remove(rep.Repeater); await uow.CompleteAsync(); } rep.Stop(); await channel.SendConfirmAsync("✅ **Stopped repeating a message.**").ConfigureAwait(false); } else { await channel.SendConfirmAsync("ℹ️ **No message is repeating.**").ConfigureAwait(false); } }
public void Delete(int id) { try { var sessionFactory = DbHandler.CreateSessionFactory(); using (var session = sessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { T entity = session.Get <T>(id); session.Delete(entity); transaction.Commit(); } } } catch (Exception e) { throw new Exception(e.Message); } }
public async Task DelAllQuotes([Remainder] string keyword) { if (string.IsNullOrWhiteSpace(keyword)) { return; } keyword = keyword.ToUpperInvariant(); using (var uow = DbHandler.UnitOfWork()) { var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); //todo kwoth please don't be complete retard uow.Quotes.RemoveRange(quotes.ToArray());//wtf?! await uow.CompleteAsync(); } await ReplyConfirmLocalized("quotes_deleted", Format.Bold(keyword)).ConfigureAwait(false); }
public async Task RotatePlaying(IUserMessage umsg) { var channel = (ITextChannel)umsg.Channel; using (var uow = DbHandler.UnitOfWork()) { var config = uow.BotConfig.GetOrCreate(); RotatingStatuses = config.RotatingStatuses = !config.RotatingStatuses; await uow.CompleteAsync(); } if (RotatingStatuses) { await channel.SendMessageAsync("`Rotating playing status enabled.`"); } else { await channel.SendMessageAsync("`Rotating playing status disabled.`"); } }
public async Task Playlists(IUserMessage umsg, [Remainder] int num = 1) { var channel = (ITextChannel)umsg.Channel; if (num <= 0) { return; } List <MusicPlaylist> playlists; using (var uow = DbHandler.UnitOfWork()) { playlists = uow.MusicPlaylists.GetPlaylistsOnPage(num); } await channel.SendMessageAsync($@"`Page {num} of saved playlists` " + string.Join("\n", playlists.Select(r => $"`#{r.Id}` - `{r.Name}` by {r.Author} - **{r.Songs.Count}** songs"))).ConfigureAwait(false); }
public async Task Change_User_Role() { DbHandler ticket = new DbHandler(connString); var user1 = await ticket.GetUserAsync("test-role"); Assert.AreEqual(UserRole.User, user1.Role); var respond = await ticket.ChangeUserRole(user1, UserRole.Admin); Assert.AreEqual(MessageType.OK, respond.MessageType); var user2 = await ticket.GetUserAsync("test-role"); Assert.AreEqual(UserRole.Admin, user2.Role); var respondd = await ticket.ChangeUserRole(user2, UserRole.User); var user3 = await ticket.GetUserAsync("test-role"); Assert.AreEqual(UserRole.User, user3.Role); }
public async Task Tesar() { bool areExclusive; using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); areExclusive = config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles; await uow.CompleteAsync(); } if (areExclusive) { await ReplyConfirmLocalized("self_assign_excl").ConfigureAwait(false); } else { await ReplyConfirmLocalized("self_assign_no_excl").ConfigureAwait(false); } }
private static GreetSettings GetOrAddSettingsForGuild(ulong guildId) { GreetSettings settings; guildConfigsCache.TryGetValue(guildId, out settings); if (settings != null) { return(settings); } using (var uow = DbHandler.UnitOfWork()) { var gc = uow.GuildConfigs.For(guildId, set => set); settings = GreetSettings.Create(gc); } guildConfigsCache.TryAdd(guildId, settings); return(settings); }
public async Task DeletePlaylist([Remainder] int id) { bool success = false; MusicPlaylist pl = null; try { using (var uow = DbHandler.UnitOfWork()) { pl = uow.MusicPlaylists.Get(id); if (pl != null) { if (NadekoBot.Credentials.IsOwner(Context.User) || pl.AuthorId == Context.User.Id) { uow.MusicPlaylists.Remove(pl); await uow.CompleteAsync().ConfigureAwait(false); success = true; } else { success = false; } } } if (!success) { await Context.Channel.SendErrorAsync("Failed to delete that playlist. It either doesn't exist, or you are not its author.").ConfigureAwait(false); } else { await Context.Channel.SendConfirmAsync("🗑 Playlist successfully **deleted**.").ConfigureAwait(false); } } catch (Exception ex) { _log.Warn(ex); } }
static SelfCommands() { _log = LogManager.GetCurrentClassLogger(); using (var uow = DbHandler.UnitOfWork()) { var config = uow.BotConfig.GetOrCreate(); _forwardDMs = config.ForwardMessages; _forwardDMsToAllOwners = config.ForwardToAllOwners; } var _ = Task.Run(async() => { while (!NadekoBot.Ready) { await Task.Delay(1000); } foreach (var cmd in NadekoBot.BotConfig.StartupCommands) { if (cmd.GuildId != null) { var guild = NadekoBot.Client.GetGuild(cmd.GuildId.Value); var channel = guild?.GetChannel(cmd.ChannelId) as SocketTextChannel; if (channel == null) { continue; } try { IUserMessage msg = await channel.SendMessageAsync(cmd.CommandText).ConfigureAwait(false); msg = (IUserMessage)await channel.GetMessageAsync(msg.Id).ConfigureAwait(false); await NadekoBot.CommandHandler.TryRunCommand(guild, channel, msg).ConfigureAwait(false); //msg.DeleteAfter(5); } catch { } } await Task.Delay(400).ConfigureAwait(false); } }); }
public async Task VoicePlusText(IUserMessage msg) { var channel = (ITextChannel)msg.Channel; var guild = channel.Guild; var botUser = guild.GetCurrentUser(); if (!botUser.GuildPermissions.ManageRoles || !botUser.GuildPermissions.ManageChannels) { await channel.SendMessageAsync(":anger: `I require manage roles and manage channels permissions to enable this feature.`"); return; } try { bool isEnabled; using (var uow = DbHandler.UnitOfWork()) { var conf = uow.GuildConfigs.For(guild.Id); isEnabled = conf.VoicePlusTextEnabled = !conf.VoicePlusTextEnabled; await uow.CompleteAsync().ConfigureAwait(false); } if (!isEnabled) { voicePlusTextCache.TryRemove(guild.Id); foreach (var textChannel in guild.GetTextChannels().Where(c => c.Name.EndsWith("-voice"))) { try { await textChannel.DeleteAsync().ConfigureAwait(false); } catch { } } await channel.SendMessageAsync("Successfuly removed voice + text feature.").ConfigureAwait(false); return; } voicePlusTextCache.Add(guild.Id); await channel.SendMessageAsync("Successfuly enabled voice + text feature.").ConfigureAwait(false); } catch (Exception ex) { await channel.SendMessageAsync(ex.ToString()).ConfigureAwait(false); } }
public async Task CmdCooldown(IUserMessage imsg, Command command, int secs) { var channel = (ITextChannel)imsg.Channel; if (secs < 0 || secs > 3600) { await channel.SendMessageAsync("⚠️ Invalid second parameter. (Must be a number between 0 and 3600)").ConfigureAwait(false); return; } using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.For(channel.Guild.Id); var localSet = commandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet <CommandCooldown>()); config.CommandCooldowns.RemoveWhere(cc => cc.CommandName == command.Text.ToLowerInvariant()); localSet.RemoveWhere(cc => cc.CommandName == command.Text.ToLowerInvariant()); if (secs != 0) { var cc = new CommandCooldown() { CommandName = command.Text.ToLowerInvariant(), Seconds = secs, }; config.CommandCooldowns.Add(cc); localSet.Add(cc); } await uow.CompleteAsync().ConfigureAwait(false); } if (secs == 0) { var activeCds = activeCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet <ActiveCooldown>()); activeCds.RemoveWhere(ac => ac.Command == command.Text.ToLowerInvariant()); await channel.SendMessageAsync($"🚮 Command **{command}** has no coooldown now and all existing cooldowns have been cleared.").ConfigureAwait(false); } else { await channel.SendMessageAsync($"✅ Command **{command}** now has a **{secs} {(secs == 1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false); } }
public static bool SetByeMessage(ulong guildId, ref string message) { message = message?.SanitizeMentions(); if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentNullException(nameof(message)); } bool byeMsgEnabled; using (var uow = DbHandler.UnitOfWork()) { var conf = uow.GuildConfigs.For(guildId, set => set); conf.ChannelByeMessageText = message; byeMsgEnabled = conf.SendChannelByeMessage; uow.Complete(); } return(byeMsgEnabled); }