示例#1
0
 internal void RemoveReaction(DiscordEmoji emoji, DiscordUser member)
 {
     if (_collected.Any(x => x.Emoji == emoji))
     {
         if (_collected.Any(x => x.Voted.Contains(member)))
         {
             var e = _collected.First(x => x.Emoji == emoji);
             _collected.TryRemove(e);
             e.Voted.TryRemove(member);
             _collected.Add(e);
         }
     }
 }
            public async Task Lsar(int page = 1)
            {
                if (--page < 0)
                {
                    return;
                }

                var toRemove  = new ConcurrentHashSet <SelfAssignedRole>();
                var removeMsg = new StringBuilder();
                var rolesStr  = new StringBuilder();
                var roleCnt   = 0;
                var exclusive = false;

                using (var uow = _db.UnitOfWork)
                {
                    exclusive = uow.GuildConfigs.For(Context.Guild.Id, set => set)
                                .ExclusiveSelfAssignedRoles;
                    var roleModels = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id)
                                     .Skip(page * 20)
                                     .Take(20)
                                     .ToDictionary(x => x.Key, x => x.AsEnumerable().ToArray())
                                     .OrderBy(x => x.Key);
                    foreach (var kvp in roleModels)
                    {
                        rolesStr.AppendLine("\t\t\t\t『" + Format.Bold(GetText("self_assign_group", kvp.Key)) + "』");
                        foreach (var roleModel in kvp.Value)
                        {
                            var role = Context.Guild.Roles.FirstOrDefault(r => r.Id == roleModel.RoleId);
                            if (role == null)
                            {
                                toRemove.Add(roleModel);
                                uow.SelfAssignedRoles.Remove(roleModel);
                            }
                            else
                            {
                                rolesStr.AppendLine(Format.Bold(role.Name));
                                roleCnt++;
                            }
                        }
                    }
                    if (toRemove.Any())
                    {
                        rolesStr.AppendLine("\t\t\t\t『』");
                    }
                    foreach (var role in toRemove)
                    {
                        rolesStr.AppendLine(GetText("role_clean", role.RoleId));
                    }
                    await uow.CompleteAsync();
                }

                await Context.Channel.SendConfirmAsync("",
                                                       Format.Bold(GetText("self_assign_list", roleCnt))
                                                       + "\n\n" + rolesStr.ToString(),
                                                       footer : exclusive
                                                       ?GetText("self_assign_are_exclusive")
                                                       : GetText("self_assign_are_not_exclusive")).ConfigureAwait(false);
            }
示例#3
0
 /// <summary>
 /// To join the game. Retrieve a competitor. If such wasn't found retrieve null and save user to allow to notify about game start later.
 /// </summary>
 /// <param name="user">User to join</param>
 /// <param name="type">Type of the game</param>
 /// <returns></returns>
 public User JoinGame(User user, GameType type)
 {
     if (WaitingUsers.Contains(user) || Games.Any(g => g.Participates(user)))
     {
         return(null);//TODO: check
     }
     return(type switch
     {
         GameType.RandomCompetitor => JoinRandomGame(user),
         GameType.Bot => JoinToBot(user),
         _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
     });
示例#4
0
            public async Task Lgp()
            {
                if (!BlockedModules.Any() && !BlockedCommands.Any())
                {
                    await ReplyErrorLocalized("lgp_none").ConfigureAwait(false);

                    return;
                }

                var embed = new EmbedBuilder().WithOkColor();

                if (BlockedModules.Any())
                {
                    embed.AddField(efb => efb.WithName(GetText("blocked_modules")).WithValue(string.Join("\n", BlockedModules)).WithIsInline(false));
                }

                if (BlockedCommands.Any())
                {
                    embed.AddField(efb => efb.WithName(GetText("blocked_commands")).WithValue(string.Join("\n", BlockedCommands)).WithIsInline(false));
                }

                await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
            }
示例#5
0
        public void BanUtxo(OutPoint utxo)
        {
            // if already banned, return
            if (Utxos.Any(x => x.Utxo.Hash == utxo.Hash && x.Utxo.N == utxo.N))
            {
                return;
            }

            Utxos.Add(new BannedUtxo
            {
                Utxo      = utxo,
                TimeOfBan = DateTimeOffset.UtcNow
            });
        }
示例#6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="scriptPubKey"></param>
        /// <param name="receivedTransactions">int: block height</param>
        /// <param name="spentTransactions">int: block height</param>
        /// <returns></returns>
        public bool TryFindConfirmedTransactions(Script scriptPubKey, out ConcurrentHashSet <SmartTransaction> receivedTransactions, out ConcurrentHashSet <SmartTransaction> spentTransactions)
        {
            var found = false;

            receivedTransactions = new ConcurrentHashSet <SmartTransaction>();
            spentTransactions    = new ConcurrentHashSet <SmartTransaction>();

            foreach (var tx in TrackedTransactions.Where(x => x.Confirmed))
            {
                // if already has that tx continue
                if (receivedTransactions.Any(x => x.GetHash() == tx.GetHash()))
                {
                    continue;
                }

                foreach (var output in tx.Transaction.Outputs)
                {
                    if (output.ScriptPubKey.Equals(scriptPubKey))
                    {
                        receivedTransactions.Add(tx);
                        found = true;
                    }
                }
            }

            if (found)
            {
                foreach (var tx in TrackedTransactions.Where(x => x.Confirmed))
                {
                    // if already has that tx continue
                    if (spentTransactions.Any(x => x.GetHash() == tx.GetHash()))
                    {
                        continue;
                    }

                    foreach (var input in tx.Transaction.Inputs)
                    {
                        if (receivedTransactions.Select(x => x.GetHash()).Contains(input.PrevOut.Hash))
                        {
                            spentTransactions.Add(tx);
                            found = true;
                        }
                    }
                }
            }

            return(found);
        }
        public async Task<bool> AddFilterAsync(ulong gid, Regex? regex)
        {
            if (regex is null)
                return false;

            string regexString = regex.ToString();

            ConcurrentHashSet<Filter> fs = this.filters.GetOrAdd(gid, new ConcurrentHashSet<Filter>());
            if (fs.Any(f => string.Compare(f.RegexString, regexString, true) == 0))
                return false;

            using TheGodfatherDbContext db = this.dbb.CreateContext();
            var filter = new Filter {
                GuildId = gid,
                RegexString = regexString,
                RegexLazy = regex,
            };
            db.Filters.Add(filter);
            await db.SaveChangesAsync();
            return fs.Add(filter);
        }
示例#8
0
        public async Task StartVerificationAsync(IGuildUser guildUser)
        {
            if (VerificationProcesses.Any(vp => vp.GuildUser == guildUser))
            {
                throw new UserAlreadyVerifyingException();
            }

            using (var uow = _db.UnitOfWork) {
                if (uow.VerifiedUsers.IsVerified(guildUser.GuildId, guildUser.Id))
                {
                    throw new UserAlreadyVerifiedException();
                }
            }

            var verificationProcess = new VerificationProcess(guildUser, _client, _db, this, _stringService, _fs);

            try {
                await verificationProcess.StartAsync();
            } catch (Exception) {
                verificationProcess.Dispose();
                throw;
            }
            VerificationProcesses.Add(verificationProcess);
        }
示例#9
0
        public override async Task RunAsync(LocalizationService lcs)
        {
            if (_countries is null)
            {
                throw new InvalidOperationException("The quiz flag paths have not been loaded.");
            }

            var questions = new Queue <string>(_countries.Keys.Shuffle().Take(this.NumberOfQuestions));

            int timeouts = 0;

            for (int i = 0; i < this.NumberOfQuestions; i++)
            {
                string question = questions.Dequeue();

                var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);
                emb.WithLocalizedDescription("fmt-game-quiz-q", i + 1);
                await this.Channel.SendFileAsync("flag.png", new FileStream(question, FileMode.Open), embed : emb.Build());

                bool timeout     = true;
                var  failed      = new ConcurrentHashSet <ulong>();
                var  answerRegex = new Regex($@"\b{_countries[question]}\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                InteractivityResult <DiscordMessage> res = await this.Interactivity.WaitForMessageAsync(
                    xm => {
                    if (xm.ChannelId != this.Channel.Id || xm.Author.IsBot || failed.Contains(xm.Author.Id))
                    {
                        return(false);
                    }
                    timeout = false;
                    if (answerRegex.IsMatch(xm.Content))
                    {
                        return(true);
                    }
                    else
                    {
                        failed.Add(xm.Author.Id);
                    }
                    return(false);
                },
                    TimeSpan.FromSeconds(10)
                    );

                if (res.TimedOut)
                {
                    if (!failed.Any())
                    {
                        timeouts = timeout ? timeouts + 1 : 0;
                        if (timeouts == 3)
                        {
                            this.IsTimeoutReached = true;
                            return;
                        }
                    }
                    else
                    {
                        timeouts = 0;
                    }
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.AlarmClock, DiscordColor.Teal, "fmt-game-quiz-timeout", _countries[question]);
                }
                else
                {
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.CheckMarkSuccess, DiscordColor.Teal, "fmt-game-quiz-correct", res.Result.Author.Mention);

                    this.results.AddOrUpdate(res.Result.Author, u => 1, (u, v) => v + 1);
                }

                await Task.Delay(TimeSpan.FromSeconds(2));
            }
        }
示例#10
0
        public void StartInstallingItems(PullItemModel args, BlockingCollection <IItemData> itemsToInstall, int threads, CancellationTokenSource cancellation)
        {
            Status.StartedTime = DateTime.Now;
            Status.RootNodes   = args.Ids.Select(x => new ContentTreeNode(x));
            Status.IsPreview   = args.Preview;
            Status.Server      = args.Server;
            int items = 0;

            for (int i = 0; i < threads; i++)
            {
                Task.Run(async() =>
                {
                    Thread.CurrentThread.Priority = ThreadPriority.Lowest;
                    BulkUpdateContext bu          = null;
                    EventDisabler ed = null;
                    try
                    {
                        if (args.BulkUpdate)
                        {
                            bu = new BulkUpdateContext();
                        }
                        if (args.EventDisabler)
                        {
                            ed = new EventDisabler();
                        }
                        using (new SecurityDisabler())
                        {
                            while (!Completed)
                            {
                                IItemData remoteData;
                                if (!itemsToInstall.TryTake(out remoteData, int.MaxValue, cancellation.Token))
                                {
                                    lock (_locker)
                                    {
                                        if (!Completed && !_currentlyProcessing.Any())
                                        {
                                            Finalize(items, args);
                                        }
                                    }
                                    break;
                                }
                                _currentlyProcessing.Add(remoteData.Id);
                                Item localItem      = _sitecore.GetItem(remoteData.Id);
                                IItemData localData = localItem == null ? null : new Rainbow.Storage.Sc.ItemData(localItem);
                                await ProcessItem(args, localData, remoteData, localItem);
                                lock (_locker)
                                {
                                    items++;
                                    _currentlyProcessing.Remove(remoteData.Id);
                                    if (_currentlyProcessing.Any() || !itemsToInstall.IsAddingCompleted || itemsToInstall.Count != 0)
                                    {
                                        continue;
                                    }

                                    if (!Completed)
                                    {
                                        Finalize(items, args);
                                    }
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException e)
                    {
                        Log.Warn("Content migration operation was cancelled", e, this);
                        Status.Cancelled = true;
                        lock (_locker)
                        {
                            if (!Completed)
                            {
                                Finalize(items, args);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error("Catastrophic error when installing items", e, this);
                    }
                    finally
                    {
                        if (args.BulkUpdate)
                        {
                            bu?.Dispose();
                        }
                        if (args.EventDisabler)
                        {
                            ed?.Dispose();
                        }
                    }
                });
            }
        }
示例#11
0
        public override async Task RunAsync(LocalizationService lcs)
        {
            int timeouts = 0;

            foreach ((QuizQuestion question, int i) in this.questions.Select((q, i) => (q, i)))
            {
                var emb = new LocalizedEmbedBuilder(lcs, this.Channel.GuildId);
                emb.WithLocalizedTitle("fmt-game-quiz-q", i + 1);
                emb.WithDescription(Formatter.Bold(question.Content));
                emb.WithColor(DiscordColor.Teal);
                emb.AddLocalizedTitleField("str-category", question.Category, inline: false);

                var answers = new List <string>(question.IncorrectAnswers)
                {
                    question.CorrectAnswer
                }.Shuffle().ToList();

                foreach ((string answer, int index) in answers.Select((a, i) => (a, i)))
                {
                    emb.AddLocalizedTitleField("fmt-game-quiz-a", answer, inline: true, titleArgs: index + 1);
                }

                var            options = Emojis.Numbers.All.Skip(1).Take(4).ToList();
                DiscordMessage msg     = await this.Channel.SendMessageAsync(embed : emb.Build());

                foreach (DiscordEmoji emoji in options)
                {
                    await msg.CreateReactionAsync(emoji);
                }

                bool timeout = true;
                var  failed  = new ConcurrentHashSet <ulong>();
                InteractivityResult <MessageReactionAddEventArgs> res = await this.Interactivity.WaitForReactionAsync(
                    e => {
                    if (e.User.IsBot || failed.Contains(e.User.Id) || e.Message != msg)
                    {
                        return(false);
                    }
                    int opt = options.IndexOf(e.Emoji);
                    if (opt == -1)
                    {
                        return(false);
                    }
                    if (answers[opt].Equals(question.CorrectAnswer))
                    {
                        return(true);
                    }
                    else
                    {
                        failed.Add(e.User.Id);
                    }
                    return(false);
                },
                    TimeSpan.FromSeconds(10)
                    );

                if (res.TimedOut)
                {
                    if (!failed.Any())
                    {
                        timeouts = timeout ? timeouts + 1 : 0;
                        if (timeouts == 3)
                        {
                            this.IsTimeoutReached = true;
                            return;
                        }
                    }
                    else
                    {
                        timeouts = 0;
                    }
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.AlarmClock, DiscordColor.Teal, "fmt-game-quiz-timeout", question.CorrectAnswer);
                }
                else
                {
                    await this.Channel.LocalizedEmbedAsync(lcs, Emojis.CheckMarkSuccess, DiscordColor.Teal, "fmt-game-quiz-correct", res.Result.User.Mention);

                    this.results.AddOrUpdate(res.Result.User, u => 1, (u, v) => v + 1);
                }

                await Task.Delay(TimeSpan.FromSeconds(2));
            }
        }
        private async Task ItemInstaller(PullItemModel args, BlockingCollection <IItemData> itemsToInstall, CancellationToken cancellationToken)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            BulkUpdateContext bu = null;
            EventDisabler     ed = null;

            try
            {
                if (args.BulkUpdate)
                {
                    bu = new BulkUpdateContext();
                }
                if (args.EventDisabler)
                {
                    ed = new EventDisabler();
                }
                using (new SecurityDisabler())
                {
                    while (!Completed)
                    {
                        IItemData remoteData;
                        if (!itemsToInstall.TryTake(out remoteData, int.MaxValue, cancellationToken))
                        {
                            lock (_locker)
                            {
                                if (!Completed && !CurrentlyProcessing.Any())
                                {
                                    Finalize(ItemsInstalled, args);
                                }
                            }
                            break;
                        }
                        CurrentlyProcessing.Add(remoteData.Id);
                        IItemData localData = _sitecore.GetItemData(remoteData.Id);
                        await ProcessItem(args, localData, remoteData).ConfigureAwait(false);

                        lock (_locker)
                        {
                            ItemsInstalled++;
                            CurrentlyProcessing.Remove(remoteData.Id);
                            if (CurrentlyProcessing.Any() || !itemsToInstall.IsAddingCompleted || itemsToInstall.Count != 0)
                            {
                                continue;
                            }

                            if (!Completed)
                            {
                                Finalize(ItemsInstalled, args);
                            }
                        }
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                Log.Warn("Content migration operation was cancelled", e, this);
                Status.Cancelled = true;
                lock (_locker)
                {
                    if (!Completed)
                    {
                        Finalize(ItemsInstalled, args);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Catastrophic error when installing items", e, this);
            }
            finally
            {
                if (args.BulkUpdate)
                {
                    bu?.Dispose();
                }
                if (args.EventDisabler)
                {
                    ed?.Dispose();
                }
            }
        }
 public static bool HasVerificationKey(VerificationKey key, bool ignoreKey = false)
 => _verificationKeys.Any(vkey => vkey.Equals(key, ignoreKey));