コード例 #1
0
        public async Task ReactionAdded(ReactionContext context, SocketReaction reactionAdded)
        {
            if (!(await ValidateAsync(context, reactionAdded)) || // do we have everything we need
                !Game.AddVote(UserReacted.Id, PlayerVoted.Id))
            {
                if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there
                {
                    if (PrivateVoting)
                    {
                        await context.Channel.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} times.");
                    }
                    else
                    {
                        await context.Message.RemoveReactionAsync(reactionAdded.Emote, reactionAdded.User.Value);
                    }
                }
                return;
            }

            Games.Update(Game);

            if (Game.Score())
            {
                Games.Update(Game);
                await Output.Score(Game, Context.Channel);
            }
        }
コード例 #2
0
ファイル: LiteQueue.cs プロジェクト: TheDuQe/LiteQueue
        /// <summary>
        /// Batch equivalent of <see cref="Dequeue"/>
        /// </summary>
        /// <param name="batchSize">The maximum number of items to dequeue</param>
        /// <returns>The items found or an empty collection (never null)</returns>
        public List <QueueEntry <T> > Dequeue(int batchSize)
        {
            if (_transactional)
            {
                lock (_dequeueLock)
                {
                    var items = _collection.Find(x => !x.IsCheckedOut, 0, batchSize);

                    // Capture the result before changing IsCheckedOut, otherwise items is being changed
                    var result = new List <QueueEntry <T> >(items);

                    foreach (var item in result)
                    {
                        item.IsCheckedOut = true;
                        _collection.Update(item);
                    }

                    return(result);
                }
            }
            else
            {
                var items  = _collection.Find(x => true, 0, batchSize);
                var result = new List <QueueEntry <T> >(items);

                foreach (var item in items)
                {
                    _collection.Delete(new BsonValue(item.Id));
                }

                return(result);
            }
        }
コード例 #3
0
 public void UpdateTrack(Mediafile file)
 {
     if (file != null && tracks.Exists(t => t.Path == file.Path))
     {
         tracks.Update(file);
     }
 }
コード例 #4
0
ファイル: VotingHandler.cs プロジェクト: piranna0/tynibot
        public async Task ReactionAdded(ReactionContext context, SocketReaction reactionAdded)
        {
            if (!(await ValidateAsync(context, reactionAdded)) || // do we have everything we need
                !Game.AddVote(UserReacted.Id, PlayerVoted.Id))
            {
                if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there
                {
                    await UserReacted.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} time{(Game.Mafia.Count > 1 ? "s" : "")}.");

                    if (!PrivateVoting)
                    {
                        try
                        {
                            await context.Message.RemoveReactionAsync(reactionAdded.Emote, reactionAdded.User.Value);
                        }
                        catch (Discord.Net.HttpException)
                        {
                            await context.Channel.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} time{(Game.Mafia.Count > 1 ? "s" : "")}.");

                            await context.Channel.SendMessageAsync($"This bot needs manage message permissions to remove the reaction from above. Until this permission is given the user must remove it themselves.");
                        }
                    }
                }
                return;
            }

            Games.Update(Game);

            if (Game.Score())
            {
                Games.Update(Game);
                await Output.Score(Game, Context.Channel);
            }
        }
コード例 #5
0
        public void SetItemPrice(string name, float price)
        {
            Item item = GetItem(name);

            item.Price = price;
            _Items.Update(item);
        }
コード例 #6
0
        /// <summary>
        /// Syncs a character with the remote version
        /// </summary>
        /// <param name="Character"></param>
        /// <returns>The Synced character</returns>
        public async Task <Character> SyncCharacter(Character character)
        {
            HttpResponseMessage response = await Client.GetAsync(Api + character.RemoteId);

            response.EnsureSuccessStatusCode();

            string responsebody = await response.Content.ReadAsStringAsync();

            var json = JObject.Parse(responsebody);

            character.LastUpdated = DateTime.Now;

            character.Type = Enum.Parse <SheetType>(((string)json["data"]["type"]).Uppercase());

            character.Name = (string)json["data"]["name"] ?? "Unnamed Character";

            var notes = json["data"]["customnotes"];

            if (notes != null && notes.HasValues)
            {
                foreach (var n in notes.Where(x => (string)x["uiid"] == "character"))
                {
                    if (((string)n["body"]).IsImageUrl())
                    {
                        character.ImageUrl = (string)n["body"];
                        break;
                    }
                }
                foreach (var n in notes.Where(x => (string)x["uiid"] == "companion"))
                {
                    if (((string)n["body"]).IsImageUrl())
                    {
                        character.ImageUrl = (string)n["body"];
                        break;
                    }
                }
            }

            var familiar = json["data"]["familiars"][0];

            if (familiar["name"] != null)
            {
                character.Familiar = (string)familiar["name"];
            }
            else
            {
                character.Familiar = null;
            }

            if (json["values"] != null && json["values"].HasValues)
            {
                character.Values            = json["values"].ToString();
                character.ValuesLastUpdated = DateTime.Now;
            }

            collection.Update(character);

            return(character);
        }
コード例 #7
0
        private Task CheckStreamerStatus()
        {
            LiteCollection <Streamer> streamers = null;

            lock (dbLock)
            {
                streamers = database.GetCollection <Streamer>("streamers");
            }

            foreach (var streamer in streamers.FindAll())
            {
                var info = twitch.TwitchQuery(Twitch.HelixStrings.Streams, streamer.Name.ToLower());
                if (info == null)
                {
                    if (streamer.IsStreaming)
                    {
                        streamer.IsStreaming = false;
                        lock (dbLock)
                        {
                            streamers.Update(streamer);
                        }
                    }
                    continue;
                }

                var gamePlayed = twitch.TwitchQuery(Twitch.HelixStrings.Games, (string)info.Result["game_id"]).Result;

                streamer.Game = gamePlayed == null ? "" : (string)gamePlayed["name"];

                if (!streamer.IsStreaming)
                {
                    streamer.IsStreaming = true;
                }

                streamer.StreamTitle = (string)info.Result["title"];

                if (streamer.MessageId == null)
                {
                    var user        = guild.GetUser(streamer.Id);
                    var content     = string.Format(Twitch.DefaultStreamMessage, $"**{(user as IGuildUser)?.Nickname}**", streamer.StreamUrl);
                    var embed       = CreateMessageEmbed(streamer).Result;
                    var liveChannel = guild.GetTextChannel(Program.ChannelId);
                    var msg         = liveChannel.SendMessageAsync(content, embed: embed).Result;
                    streamer.MessageId = (msg as IUserMessage).Id;
                    Console.Out.WriteLineAsync($"Set streamer {streamer.Name} to msgId {streamer.MessageId}");
                }

                lock (dbLock)
                {
                    streamers.Update(streamer);
                }
            }

            return(Task.CompletedTask);
        }
コード例 #8
0
        public async Task ReactionAdded(ReactionContext context, SocketReaction reaction)
        {
            if (!(await Validate(context, reaction)))
            {
                if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there
                {
                    await Context.Message.RemoveReactionAsync(new Emoji(reaction.Emote.Name), reaction.User.Value);
                }
                return;
            }

            switch (reaction.Emote.Name) // Which reaction was clicked?
            {
            case Output.OrangeEmoji:
                await SelectWinningTeamAsync(Team.Orange);

                break;

            case Output.BlueEmoji:
                await SelectWinningTeamAsync(Team.Blue);

                break;

            case Output.OvertimeEmoji:
                Game.OvertimeReached = true;
                Games.Update(Game);
                break;

            case Output.EndedEmoji:
                if (Game.WinningTeam == null)     // if we don't have a winner remove emoji and return
                {
                    await Context.Message.RemoveReactionAsync(new Emoji(Output.EndedEmoji), UserReacted);

                    return;
                }

                // Un-register this message for receiving new reactions
                ReactionHandlers.Delete(u => u.MsgId == this.MsgId);

                // Output voting notification message
                var votingMessages = await Output.StartVoting(Game, Context.Channel, VotingHandler.PrivateVoting);

                Games.Update(Game);     // Update so we store emojis on user

                // Register new message for receiving reactions
                foreach (var votingMessage in votingMessages)
                {
                    ReactionHandlers.Insert(new VotingHandler()
                    {
                        MsgId = votingMessage.Id, GameId = Game.Id
                    });
                }
                break;
            }
        }
コード例 #9
0
        /// <summary>
        /// Update the value <see cref="FileMetaData.LastTouchedTimestamp"/>
        /// </summary>
        /// <param name="name">The name of the <see cref="FileMetaData"/></param>
        public override void TouchFile(string name)
        {
            var result = _fileMetaDataCollection.FindOne(fm => fm.Name == name);

            if (result != null)
            {
                result.LastTouchedTimestamp = DateTime.UtcNow;
                _fileMetaDataCollection.Update(result);
            }

            GC.Collect();
        }
コード例 #10
0
ファイル: Hasher.cs プロジェクト: fonsp/nancy-test
        public static bool AttemptLogin(string username, string passwordAttempt)
        {
            UserEntry userEntry = FindUser(username);
            bool      valid     = Hasher.VerifyPassword(passwordAttempt, userEntry.saltHashCombo);

            if (valid)
            {
                userEntry.lastLogin = DateTime.Now;
                users.Update(userEntry);
            }
            return(valid);
        }
コード例 #11
0
        public async Task <IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();

            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }

            await Task.Run(() => { _roles.Update(role.Id, role); }, cancellationToken);

            return(IdentityResult.Success);
        }
コード例 #12
0
        /// <summary>Increases the playcount and updates the last playtime.</summary>
        /// <param name="ale">The <see cref="AudioLogEntry"/> to update.</param>
        private void LogEntryPlay(AudioLogEntry ale)
        {
            if (ale == null)
            {
                throw new ArgumentNullException(nameof(ale));
            }

            // update the playtime
            ale.Timestamp = Util.GetNow();
            // update the playcount
            ale.PlayCount++;

            audioLogEntries.Update(ale);
        }
コード例 #13
0
 public Task <bool> UpdateRecordAsync <T>(T record, long id)
 {
     return(Task.Run(() =>
     {
         try
         {
             return currentCollection.Update(id, (IDbRecord)record);
         }
         catch
         {
             return false;
         }
     }));
 }
コード例 #14
0
        public TodoItem CreateItem(TodoItem item)
        {
            var existingTodoItem = _collection.FindById(item.Id);

            if (existingTodoItem == null)
            {
                _collection.Insert(item);
            }
            else
            {
                _collection.Update(item);
            }

            return(item);
        }
コード例 #15
0
        public void UpdateUser(User user)
        {
            var existingRecord = this.GetUser(user.Id);
            var mergedRecord   = userServices.MergeRecords(existingRecord, user);

            usersRepository.Update(mergedRecord);
        }
コード例 #16
0
 public static void OnUpshelf(this ProductItem product, LiteCollection <ProductItem> productItems)
 {
     product.正在上架     =
         product.正在上架 = false;
     product.Where    = "出售中";
     productItems.Update(product);
 }
コード例 #17
0
        public async Task Refresh()
        {
            var result = await backendService.GetSpeakSessions().ConfigureAwait(false);

            foreach (var room in result.SpeakSessions.Select(s => s.Room))
            {
                if (rooms.FindById(room.Id) == null)
                {
                    rooms.Insert(room);
                }
                else
                {
                    rooms.Update(room);
                }
            }

            foreach (var session in result.SpeakSessions)
            {
                if (collection.FindById(session.Id) == null)
                {
                    collection.Insert(session);
                }
                else
                {
                    collection.Update(session);
                }
            }
        }
コード例 #18
0
        private string HandleExistingUser(ITweet tweet, string targetAddress, Reward reward, RewardType rewardType)
        {
            var canWithdraw = _withdrawalService.CanExecuteAsync(rewardType).GetAwaiter().GetResult();

            if (!canWithdraw)
            {
                _logger.Warning("Not enough funds for withdrawal.");
                return(string.Format(_appSettings.BotSettings.MessageFaucetDrained, tweet.CreatedBy.ScreenName));
            }

            reward.Followers = tweet.CreatedBy.FollowersCount;

            if (reward.Withdrawals >= reward.Followers)
            {
                return(string.Format(_appSettings.BotSettings.MessageReachedLimit, tweet.CreatedBy.ScreenName));
            }

            if (reward.LastRewardDate.Date.Equals(DateTime.UtcNow.Date))
            {
                return(GenerateMessageDailyLimitReached(tweet.CreatedBy.ScreenName));
            }

            _withdrawalService.ExecuteAsync(rewardType, targetAddress).GetAwaiter().GetResult();
            _statService.AddStat(DateTime.UtcNow, _amountHelper.GetAmount(rewardType), false);

            reward.LastRewardDate = DateTime.UtcNow;
            reward.Withdrawals++;
            _rewardCollection.Update(reward);

            return(string.Format(_appSettings.BotSettings.MessageRewarded, tweet.CreatedBy.ScreenName, _amountHelper.GetAmount(rewardType)));
        }
コード例 #19
0
ファイル: TestConfiguration.cs プロジェクト: thmundal/SatStat
        public void Save(TestConfiguration existing, Action <TestConfiguration> cb = null)
        {
            if (Name == String.Empty || Name == null)
            {
                // Must have a name
                return;
            }

            using (LiteDatabase db = new LiteDatabase(Program.settings.DatabasePath))
            {
                LiteCollection <TestConfiguration> collection = db.GetCollection <TestConfiguration>(Program.settings.TestConfigDatabase);

                if (existing == null)
                {
                    this.Id = null;
                    collection.Insert(this);
                }
                else
                {
                    this.Id = existing.Id;
                    collection.Update(this);
                }

                if (cb != null)
                {
                    cb.Invoke(this);
                }
            }
        }
コード例 #20
0
 public static void OnUpshelf(this ProductItem product, LiteCollection<ProductItem> productItems)
 {
     product.正在上架 =
     product.正在上架 = false;
     product.Where = "出售中";
     productItems.Update(product);
 }
コード例 #21
0
        public async Task Shuffle(CommandContext ctx)
        {
            // Search for the active server
            using (LiteDatabase db = new LiteDatabase("data.db"))
            {
                LiteCollection <ServerConfig> servers = db.GetCollection <ServerConfig>("servers");
                ServerConfig server = servers.FindOne(s => s.Server == ctx.Guild.Id);

                // No server config found, add one
                if (server == null)
                {
                    await ctx.RespondAsync(":warning: No server config available! Add an icon first!");

                    return;
                }

                // Add the icon ID
                server.NextSet = DateTime.Now;
                servers.Update(server);

                // Reply
                await ctx.RespondAsync(
                    ":white_check_mark: Shuffled the icon. It can take up to one minute until it actually changes.");
            }
        }
コード例 #22
0
 public void Update(DBEntity ent, object sender)
 {
     _collection.Update(ent);
     Senders.Add(sender);
     EntityUpdated?.Invoke(this, ent);
     Senders.Clear();
 }
コード例 #23
0
        //Changes the password of a user
        public bool ChangePassword(int nID, string sPass)
        {
            if (sPass.Length == 0)
            {
                return(false);
            }

            LiteCollection <UserStructDb> aDBValues = m_db.GetCollection <UserStructDb>("users");
            UserStructDb results = aDBValues.FindOne(x => x.Id == nID);

            if (results == null)
            {
                return(false);
            }

            //Create new password
            byte[] plaintext = Encoding.ASCII.GetBytes(sPass + sUserSalt);

            // Generate additional entropy (will be used as the Initialization vector)
            byte[] entropy = new byte[15];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                rng.GetBytes(entropy);

            byte[] ciphertext = ProtectedData.Protect(plaintext, entropy, DataProtectionScope.LocalMachine);

            results.entropy    = entropy;
            results.ciphertext = ciphertext;
            aDBValues.Update(results);

            return(true);
        }
コード例 #24
0
        /// <summary>
        /// Writes stock data to db and refreshes references
        /// </summary>
        /// <param name="stock"></param>
        /// <returns></returns>
        public bool UpdateStock(Stock stock)
        {
            try
            {
                using (var db = new LiteDatabase(_dataBaseFile))
                {
                    // Get a collection (or create, if doesn't exist)
                    LiteCollection <Stock> currentCollection = db.GetCollection <Stock>("Stocks");
                    if (currentCollection == null)
                    {
                        throw new Exception("Update not possible data/collection does not exist");
                    }
                    // not sure why, but in some cases upsert fails...
                    if (!currentCollection.Upsert(stock))
                    {
                        if (!currentCollection.Update(stock))
                        {
                            throw new Exception($"Update failed, stock [{stock.Id}], [{stock.Company}] not found");
                        }
                    }

                    SetReferences(stock.Financials);
                }

                return(true);
            }
            catch (Exception x)
            {
                Log.Error(x);
                return(false);
            }
        }
コード例 #25
0
        //Register a device on a user
        public bool MobileRegister(Mobileunit mobileunit)
        {
            //No love if these variables are no good
            if (mobileunit.DeviceID.Length == 0 ||
                mobileunit.Displayname.Length == 0 ||
                GetUsername(mobileunit.UserID).Length == 0)
            {
                return(false);
            }

            //Add database access
            LiteCollection <Mobileunit> aDBValues = m_db.GetCollection <Mobileunit>("mobile");

            //Set the time for adding
            mobileunit.Added = DateTime.Now;

            //Check if it exists already
            //Add new mobile to register if not
            if (IsMobileRegistered(mobileunit.DeviceID, mobileunit.UserID))
            {
                var results = aDBValues.FindOne(x => x.DeviceID == mobileunit.DeviceID);
                mobileunit.Id = results.Id;
                aDBValues.Update(mobileunit);
            }
            else
            {
                aDBValues.Insert(mobileunit);
            }

            return(true);
        }
コード例 #26
0
ファイル: Database.cs プロジェクト: ZapDragon/DreadBot
 internal static void SaveConfig()
 {
     lock (Configs.RunningConfig)
     {
         DreadBotCol.Update(Configs.RunningConfig);
     }
 }
コード例 #27
0
        public static SMessage DeleteSMessage(SMessage smessage)
        {
            LiteDatabase db = null;

            try
            {
                ConnectionString cn = ldbConfig.ldbSMessageConnectionString;
                db = new LiteDatabase(cn);
                LiteCollection <SMessage> dbSMessage = db.GetCollection <SMessage>("SMessage");
                //dbSMessage.Delete(Query.EQ("Id", smessage.Id));
                //LiteCollection<SMessage> lst=dbSMessage.Where(x => x.Id == smessage.Id).ToList<SMessage>();
                SMessage sm = dbSMessage.FindById(smessage.Id);
                if (sm != null)
                {
                    sm.IsDeleted = 1;
                }
                dbSMessage.Update(sm);
                //List<SMessage> lst = dbSMessage.FindAll().Where(x => x.IsDeleted != 1).ToList<SMessage>();
                return(sm);
            }
            catch (Exception ex)
            {
                DBHelper.LogFile(ex);
                return(null);
            }
        }
コード例 #28
0
        public async Task Interval(CommandContext ctx, [Description("The min. amount of days between icon changes.")] Single min, [Description("The max. amount of days between icon changes.")] Single max)
        {
            // Search for the active server
            using (LiteDatabase db = new LiteDatabase("data.db"))
            {
                LiteCollection <ServerConfig> servers = db.GetCollection <ServerConfig>("servers");
                ServerConfig server = servers.FindOne(s => s.Server == ctx.Guild.Id);

                // No server config found, add one
                if (server == null)
                {
                    await ctx.RespondAsync(":warning: No server config available! Add an icon first!");

                    return;
                }

                // Add the icon ID
                server.IntervalMax = max;
                server.IntervalMin = min;
                servers.Update(server);

                // Reply
                await ctx.RespondAsync(":white_check_mark: Updated the interval.");
            }
        }
コード例 #29
0
        //+
        private void OnData_Changed(object s, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                return;
            }

            if (e.ColumnIndex == 1)
            {
                clients[e.RowIndex].ClientName = dataGridView1["name", e.RowIndex].Value.ToString();
            }
            else
            {
                int oldVar = clients[e.RowIndex].ClientDiscount;

                if (int.TryParse(dataGridView1["discount", e.RowIndex].Value.ToString(), out int val))
                {
                    clients[e.RowIndex].ClientDiscount = val;
                }
                else
                {
                    MessageBox.Show("Ошибка ввода скидки, доступны только числа!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dataGridView1["discount", e.RowIndex].Value = oldVar;
                    return;
                }
            }

            colClients.Update(clients[e.RowIndex]);
        }
コード例 #30
0
    private void SetToDb(string key, BsonValue value)
    {
        var x = optionsCollection.FindOne(z => z.ContainsKey(key));

        x[key] = value;
        optionsCollection.Update(x);
    }
コード例 #31
0
        public async Task Remove(CommandContext ctx, [Description("The id of the icon to delete.")] Int32 id)
        {
            // Look up the server config in the database
            using (LiteDatabase db = new LiteDatabase("data.db"))
            {
                LiteCollection <ServerConfig> servers = db.GetCollection <ServerConfig>("servers");
                ServerConfig server = servers.FindOne(s => s.Server == ctx.Guild.Id);

                // No server config found, add one
                if (server == null)
                {
                    await ctx.RespondAsync(":warning: No server config available! Add an icon first!");

                    return;
                }

                // Remove the icon ID
                server.Thumbnails.RemoveAt(id - 1);

                if (server.Thumbnails.Count == 0)
                {
                    servers.Delete(s => s.Id == server.Id);
                }
                else
                {
                    servers.Update(server);
                }

                // Reply
                await ctx.RespondAsync(":white_check_mark: Removed Icon **" + id + "**");
            }
        }
コード例 #32
0
 public static void OnUpshelfing(this ProductItem product, LiteCollection<ProductItem> productItems)
 {
     product.正在上架 = true;
     productItems.Update(product);
 }