Пример #1
0
        public void FirstOrDefault(int expected, int input)
        {
            // Arrange
            var list = new ConcurrentHashSet <int>();

            // Act
            var actual = list.FirstOrDefault(x => x == input);

            // Assert
            Assert.Equal(expected, actual);
            list.Dispose();
        }
Пример #2
0
 public IFeature Find(IFeature feature)
 {
     return(_cache.FirstOrDefault(f => f == feature));
 }
Пример #3
0
        private async Task AddTextReactionAsync(CommandContext ctx, string trigger, string response, bool regex)
        {
            if (string.IsNullOrWhiteSpace(response))
            {
                throw new InvalidCommandUsageException("Response missing or invalid.");
            }

            if (trigger.Length < 2 || response.Length < 2)
            {
                throw new CommandFailedException("Trigger or response cannot be shorter than 2 characters.");
            }

            if (trigger.Length > 120 || response.Length > 120)
            {
                throw new CommandFailedException("Trigger or response cannot be longer than 120 characters.");
            }

            if (!this.Shared.TextReactions.ContainsKey(ctx.Guild.Id))
            {
                this.Shared.TextReactions.TryAdd(ctx.Guild.Id, new ConcurrentHashSet <TextReaction>());
            }

            if (regex && !trigger.IsValidRegex())
            {
                throw new CommandFailedException($"Trigger {Formatter.Bold(trigger)} is not a valid regular expression.");
            }

            if (this.Shared.GuildHasTextReaction(ctx.Guild.Id, trigger))
            {
                throw new CommandFailedException($"Trigger {Formatter.Bold(trigger)} already exists.");
            }

            if (this.Shared.Filters.TryGetValue(ctx.Guild.Id, out ConcurrentHashSet <Administration.Common.Filter> filters) && filters.Any(f => f.Trigger.IsMatch(trigger)))
            {
                throw new CommandFailedException($"Trigger {Formatter.Bold(trigger)} collides with an existing filter in this guild.");
            }

            int id;

            using (DatabaseContext db = this.Database.CreateContext()) {
                DatabaseTextReaction dbtr = db.TextReactions.FirstOrDefault(tr => tr.GuildId == ctx.Guild.Id && tr.Response == response);
                if (dbtr is null)
                {
                    dbtr = new DatabaseTextReaction {
                        GuildId  = ctx.Guild.Id,
                        Response = response,
                    };
                    db.TextReactions.Add(dbtr);
                    await db.SaveChangesAsync();
                }

                dbtr.DbTriggers.Add(new DatabaseTextReactionTrigger {
                    ReactionId = dbtr.Id, Trigger = regex ? trigger : Regex.Escape(trigger)
                });

                await db.SaveChangesAsync();

                id = dbtr.Id;
            }

            var eb = new StringBuilder();

            ConcurrentHashSet <TextReaction> treactions = this.Shared.TextReactions[ctx.Guild.Id];
            TextReaction reaction = treactions.FirstOrDefault(tr => tr.Response == response);

            if (reaction is null)
            {
                if (!treactions.Add(new TextReaction(id, trigger, response, regex)))
                {
                    throw new CommandFailedException($"Failed to add trigger {Formatter.Bold(trigger)}.");
                }
            }
            else
            {
                if (!reaction.AddTrigger(trigger, regex))
                {
                    throw new CommandFailedException($"Failed to add trigger {Formatter.Bold(trigger)}.");
                }
            }

            DiscordChannel logchn = this.Shared.GetLogChannelForGuild(ctx.Client, ctx.Guild);

            if (!(logchn is null))
            {
                var emb = new DiscordEmbedBuilder {
                    Title = "New text reaction added",
                    Color = this.ModuleColor
                };
                emb.AddField("User responsible", ctx.User.Mention, inline: true);
                emb.AddField("Invoked in", ctx.Channel.Mention, inline: true);
                emb.AddField("Response", response, inline: true);
                emb.AddField("Trigger", trigger);
                if (eb.Length > 0)
                {
                    emb.AddField("With errors", eb.ToString());
                }
                await logchn.SendMessageAsync(embed : emb.Build());
            }

            if (eb.Length > 0)
            {
                await this.InformFailureAsync(ctx, eb.ToString());
            }
            else
            {
                await this.InformAsync(ctx, "Successfully added given text reaction.", important : false);
            }
        }
Пример #4
0
        private async Task AddEmojiReactionAsync(CommandContext ctx, DiscordEmoji emoji, bool regex, params string[] triggers)
        {
            if (emoji is DiscordGuildEmoji && !ctx.Guild.Emojis.Values.Contains(emoji))
            {
                throw new CommandFailedException("The reaction has to be an emoji from this guild.");
            }

            if (triggers is null || !triggers.Any())
            {
                throw new InvalidCommandUsageException("Missing trigger words!");
            }

            if (!this.Shared.EmojiReactions.ContainsKey(ctx.Guild.Id))
            {
                if (!this.Shared.EmojiReactions.TryAdd(ctx.Guild.Id, new ConcurrentHashSet <EmojiReaction>()))
                {
                    throw new ConcurrentOperationException("Failed to create emoji reaction data structure");
                }
            }

            int id;

            using (DatabaseContext db = this.Database.CreateContext()) {
                DatabaseEmojiReaction dber = db.EmojiReactions.FirstOrDefault(er => er.GuildId == ctx.Guild.Id && er.Reaction == emoji.GetDiscordName());
                if (dber is null)
                {
                    dber = new DatabaseEmojiReaction {
                        GuildId  = ctx.Guild.Id,
                        Reaction = emoji.GetDiscordName()
                    };
                    db.EmojiReactions.Add(dber);
                    await db.SaveChangesAsync();
                }

                foreach (string trigger in triggers)
                {
                    dber.DbTriggers.Add(new DatabaseEmojiReactionTrigger {
                        ReactionId = dber.Id, Trigger = regex ? trigger : Regex.Escape(trigger)
                    });
                }

                await db.SaveChangesAsync();

                id = dber.Id;
            }

            var eb = new StringBuilder();

            foreach (string trigger in triggers.Select(t => t.ToLowerInvariant()))
            {
                if (trigger.Length > 120)
                {
                    eb.AppendLine($"Error: Trigger {Formatter.Bold(trigger)} is too long (120 chars max).");
                    continue;
                }

                if (regex && !trigger.IsValidRegex())
                {
                    eb.AppendLine($"Error: Trigger {Formatter.Bold(trigger)} is not a valid regular expression.");
                    continue;
                }

                ConcurrentHashSet <EmojiReaction> ereactions = this.Shared.EmojiReactions[ctx.Guild.Id];

                string ename = emoji.GetDiscordName();
                if (ereactions.Where(er => er.ContainsTriggerPattern(trigger)).Any(er => er.Response == ename))
                {
                    eb.AppendLine($"Error: Trigger {Formatter.Bold(trigger)} already exists for this emoji.");
                    continue;
                }

                EmojiReaction reaction = ereactions.FirstOrDefault(tr => tr.Response == ename);
                if (reaction is null)
                {
                    if (!ereactions.Add(new EmojiReaction(id, trigger, ename, isRegex: regex)))
                    {
                        throw new CommandFailedException($"Failed to add trigger {Formatter.Bold(trigger)}.");
                    }
                }
                else
                {
                    if (!reaction.AddTrigger(trigger, isRegex: regex))
                    {
                        throw new CommandFailedException($"Failed to add trigger {Formatter.Bold(trigger)}.");
                    }
                }
            }

            DiscordChannel logchn = this.Shared.GetLogChannelForGuild(ctx.Client, ctx.Guild);

            if (!(logchn is null))
            {
                var emb = new DiscordEmbedBuilder {
                    Title = "New emoji reactions added",
                    Color = this.ModuleColor
                };
                emb.AddField("User responsible", ctx.User.Mention, inline: true);
                emb.AddField("Invoked in", ctx.Channel.Mention, inline: true);
                emb.AddField("Reaction", emoji, inline: true);
                emb.AddField("Triggers", string.Join("\n", triggers));
                if (eb.Length > 0)
                {
                    emb.AddField("With errors", eb.ToString());
                }
                await logchn.SendMessageAsync(embed : emb.Build());
            }

            if (eb.Length > 0)
            {
                await this.InformFailureAsync(ctx, $"Action finished with following warnings/errors:\n\n{eb.ToString()}");
            }
            else
            {
                await this.InformAsync(ctx, "Successfully added all given emoji reactions.", important : false);
            }
        }
Пример #5
0
 public TMRoom FindRoomByClient(TMClient client)
 {
     return(Rooms.FirstOrDefault(room => room.ClientInfos.Any(info => info.Client == client)));
 }
 public static CommandStringsModel GetCommandStringModel(string name)
 => _commandStrings.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) ?? throw new Exception($"CommandStringsModel for command '{name}' not found.");
Пример #7
0
 public static CommandStringsModel GetCommandStringModel(string name)
 => _commandStrings.FirstOrDefault(c => c.Name == name) ?? new CommandStringsModel
 {
     Name = name, Command = name + "_cmd"
 };
 public static VerificationKey GetKey(ulong guildId, ulong userId, long forumUserId, VerificationKeyScope keyScope)
 => _verificationKeys.FirstOrDefault(vk => vk.IsKeyFor(guildId, userId, forumUserId, keyScope));