Пример #1
0
        private static void AddOneChatWithTwoForbiddenWordsAndOnePromotedMember(BotDbContext context)
        {
            var chat = new Chat(ChatId)
            {
                ChatId         = ChatId,
                ForbiddenWords = new List <ForbiddenChatWord>
                {
                    new ForbiddenChatWord {
                        Id = 1, Word = "abcd"
                    },
                    new ForbiddenChatWord {
                        Id = 2, Word = "1234"
                    },
                }
            };

            context.Chats.Add(chat);
            context.SaveChanges();

            var chatPromotedMember = new ChatToPromotedMember
            {
                Chat = chat,
                PromotedChatMember = context.PromotedMembers.Single(pm => pm.UserId == 1)
            };

            chat.PromotedMembers.Add(chatPromotedMember);
            context.SaveChanges();
        }
Пример #2
0
        public User Insert(User user)
        {
            user = _dbContext.Users.Add(user).Entity;
            _dbContext.SaveChanges();

            return(user);
        }
Пример #3
0
 public bool SaveQuestion(Question entity)
 {
     try
     {
         dbContext.Question.Add(entity);
         dbContext.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        /// <summary>Checks quizes and removes those that are expired.</summary>
        private void CheckQuizesExpired()
        {
            this.logger.Trace("()");

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                foreach (QuizModel quiz in context.ActiveQuizes.ToList())
                {
                    if (DateTime.Now > (quiz.CreationTime + TimeSpan.FromMinutes(quiz.DurationMinutes)))
                    {
                        // Quiz expired. Return money to creator and remove the quiz.
                        this.logger.Info("Quiz {0} expired.", quiz.Id);

                        DiscordUserModel quizCreator = context.Users.Single(x => x.DiscordUserId == quiz.CreatorDiscordUserId);
                        quizCreator.Balance += quiz.Reward;
                        context.Update(quizCreator);

                        context.ActiveQuizes.Remove(quiz);
                        context.SaveChanges();
                    }
                }
            }

            this.logger.Trace("(-)");
        }
        /// <summary>Transfers <paramref name="amount"/> of money from <paramref name="sender"/> to <paramref name="userBeingTipped"/>.</summary>
        /// <exception cref="CommandExecutionException">Thrown when user supplied invalid input data.</exception>
        public void TipUser(IUser sender, IUser userBeingTipped, decimal amount)
        {
            this.logger.Trace("({0}:{1},{2}:'{3}',{4}:{5})", nameof(sender), sender.Id, nameof(userBeingTipped), userBeingTipped.Id, nameof(amount), amount);

            this.AssertAmountPositive(amount);
            this.AssertUsersNotEqual(sender, userBeingTipped);

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                DiscordUserModel discordUserSender = this.GetOrCreateUser(context, sender);

                this.AssertBalanceIsSufficient(discordUserSender, amount);

                DiscordUserModel discordUserReceiver = this.GetOrCreateUser(context, userBeingTipped);

                discordUserSender.Balance   -= amount;
                discordUserReceiver.Balance += amount;

                context.Update(discordUserReceiver);

                this.AddTipToHistory(context, amount, discordUserReceiver.DiscordUserId, discordUserSender.DiscordUserId);

                context.SaveChanges();

                this.logger.Debug("User '{0}' tipped {1} to '{2}'", discordUserSender, discordUserReceiver, amount);
            }

            this.logger.Trace("(-)");
        }
        /// <summary>
        /// Checks if money were deposited to an address associated with any user who has a deposit address.
        /// When money are deposited user's balance is updated.
        /// </summary>
        private void CheckDeposits(BotDbContext context)
        {
            this.logger.Trace("()");

            List <DiscordUserModel> usersToTrack = context.Users.Where(x => x.DepositAddress != null).ToList();

            this.logger.Trace("Tracking {0} users.", usersToTrack.Count);

            foreach (DiscordUserModel user in usersToTrack)
            {
                decimal receivedByAddress = this.coinService.GetReceivedByAddress(user.DepositAddress, this.settings.MinConfirmationsForDeposit);

                if (receivedByAddress > user.LastCheckedReceivedAmountByAddress)
                {
                    this.logger.Debug("New value for received by address is {0}. Old was {1}. Address is {2}.", receivedByAddress, user.LastCheckedReceivedAmountByAddress, user.DepositAddress);

                    decimal recentlyReceived = receivedByAddress - user.LastCheckedReceivedAmountByAddress;
                    user.LastCheckedReceivedAmountByAddress = receivedByAddress;

                    user.Balance += recentlyReceived;

                    this.logger.Info("User '{0}' deposited {1}!", user, recentlyReceived);

                    context.Update(user);
                    context.SaveChanges();
                }
            }

            this.logger.Trace("(-)");
        }
        private async Task ClearWelcomeCommand(Message message, ServicesContext serviceContext, BotDbContext dbContext)
        {
            var client        = serviceContext.TelegramBotService.Client;
            var table         = dbContext.GroupMessages;
            var existingEntry = table.Where(welcome => welcome.ChatId == message.Chat.Id).FirstOrDefault();

            if (existingEntry != null)
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "Updated welcome message ^-^",
                    replyToMessageId : message.MessageId
                );

                table.Remove(existingEntry);
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "No welcome message anymore ^-^",
                    replyToMessageId : message.MessageId
                );
            }
            dbContext.SaveChanges();
        }
        /// <summary>Populates database with unused addresses.</summary>
        private void PregenerateAddresses(BotDbContext context)
        {
            this.logger.Trace("()");
            this.logger.Info("Database was not prefilled with unused addresses. Starting.");

            this.logger.Info("Generating {0} addresses.", this.settings.PregeneratedAddressesCount);

            try
            {
                var unusedAddressResult = blockCoreNodeAPI.GetUnusedAddresses(settings.PregeneratedAddressesCount).Result;

                foreach (string address in unusedAddressResult)
                {
                    context.UnusedAddresses.Add(new AddressModel()
                    {
                        Address = address
                    });
                }

                context.SaveChanges();
                this.logger.Info("Addresses generated.");
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.ToString);
            }
            this.logger.Trace("(-)");
        }
Пример #9
0
        private static async Task ClearWelcomeCommand(IBotService botService, Message message, BotDbContext dbContext)
        {
            var client        = botService.Client;
            var table         = dbContext.WelcomeMessages;
            var existingEntry = table.Where(welcome => welcome.ChatId == message.Chat.Id).FirstOrDefault();

            if (existingEntry != null)
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "Updated Welcome Message",
                    replyToMessageId : message.MessageId
                );

                table.Remove(existingEntry);
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "No Welcome Message",
                    replyToMessageId : message.MessageId
                );
            }
            dbContext.SaveChanges();
        }
        /// <summary>
        /// Checks if money were deposited to an address associated with any user who has a deposit address.
        /// When money are deposited user's balance is updated.
        /// </summary>
        private void CheckDeposits(BotDbContext context)
        {
            this.logger.Trace("()");

            List <DiscordUserModel> usersToTrack = context.Users.AsQueryable().Where(x => x.DepositAddress != null).ToList();

            this.logger.Trace("Tracking {0} users.", usersToTrack.Count);
            try
            {
                foreach (DiscordUserModel user in usersToTrack)
                {
                    var addressHistory = blockCoreNodeAPI.GetAddressesHistory(user.DepositAddress).Result;

                    var transactionHistory = addressHistory.history.Where(x => x.accountName == AccountName).SelectMany(x => x.transactionsHistory);

                    var receivedByAddress = transactionHistory.Where(x => x.type == "received");

                    if (receivedByAddress.Count() > 0)
                    {
                        decimal totalRecivedByAddress = receivedByAddress.Sum(x => x.amount);

                        decimal balance = Money.FromUnit(totalRecivedByAddress, MoneyUnit.Satoshi).ToUnit(MoneyUnit.BTC);

                        if (balance > user.LastCheckedReceivedAmountByAddress)
                        {
                            decimal recentlyReceived = balance - user.LastCheckedReceivedAmountByAddress;

                            // Prevent users from spamming small amounts of coins.
                            // Also keep in mind if you'd like to change that- EF needs to be configured to track such changes.
                            // https://stackoverflow.com/questions/25891795/entityframework-not-detecting-changes-to-decimals-after-a-certain-precision
                            if (recentlyReceived < 0.01m)
                            {
                                this.logger.Trace("Skipping dust {0} for user {1}.", recentlyReceived, user);
                                continue;
                            }

                            this.logger.Debug("New value for received by address is {0}. Old was {1}. Address is {2}.", receivedByAddress, user.LastCheckedReceivedAmountByAddress, user.DepositAddress);

                            user.LastCheckedReceivedAmountByAddress = balance;
                            user.Balance += recentlyReceived;

                            context.Attach(user);
                            context.Entry(user).Property(x => x.Balance).IsModified = true;
                            context.Entry(user).Property(x => x.LastCheckedReceivedAmountByAddress).IsModified = true;
                            context.SaveChanges();

                            this.logger.Info("User '{0}' deposited {1}!. New balance is {2}.", user, recentlyReceived, user.Balance);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.Error(ex.ToString);
            }

            this.logger.Trace("(-)");
        }
        public AnswerToQuizResponseModel AnswerToQuiz(IUser user, string answer)
        {
            this.logger.Trace("({0}:'{1}')", nameof(answer), answer);

            if (answer.Length > 1024)
            {
                // We don't want to hash big strings.
                this.logger.Trace("(-)[ANSWER_TOO_LONG]");
                return(new AnswerToQuizResponseModel()
                {
                    Success = false
                });
            }

            string answerHash = Cryptography.Hash(answer);

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                foreach (QuizModel quiz in context.ActiveQuizes.ToList())
                {
                    if (DateTime.Now > (quiz.CreationTime + TimeSpan.FromMinutes(quiz.DurationMinutes)))
                    {
                        // Quiz expired but just not deleted yet.
                        continue;
                    }

                    if (quiz.AnswerHash == answerHash)
                    {
                        DiscordUserModel winner = this.GetOrCreateUser(context, user);

                        winner.Balance += quiz.Reward;
                        context.Update(winner);

                        context.ActiveQuizes.Remove(quiz);
                        context.SaveChanges();

                        this.logger.Debug("User {0} solved quiz with hash {1} and received a reward of {2}.", winner, quiz.AnswerHash, quiz.Reward);

                        var response = new AnswerToQuizResponseModel()
                        {
                            Success = true,
                            Reward  = quiz.Reward,
                            QuizCreatorDiscordUserId = quiz.CreatorDiscordUserId,
                            QuizQuestion             = quiz.Question
                        };

                        this.logger.Trace("(-)");
                        return(response);
                    }
                }
            }

            this.logger.Trace("(-)[QUIZ_NOT_FOUND]");
            return(new AnswerToQuizResponseModel()
            {
                Success = false
            });
        }
Пример #12
0
        private Conversation _findOrInsertConversation(Conversation conversation)
        {
            var dbConversation = _db.Conversations.Find(conversation.ConversationId);

            if (dbConversation == null)
            {
                dbConversation = conversation;
                _db.Conversations.Add(dbConversation);
                _db.SaveChanges();
            }
            else if (dbConversation.Title != conversation.Title)
            {
                _db.Conversations.Update(conversation);
                _db.SaveChanges();
            }

            return(dbConversation);
        }
        public void Setup()
        {
            _context = new BotDbContext();
            _context.Database.EnsureCreated();
            var piter = new Human("Piter", 19);

            _context.Add(piter);
            _context.SaveChanges();
        }
Пример #14
0
        private static async Task SaveMessage(IBotService botService, Message message, BotDbContext dbContext)
        {
            var messageParts = message.Text.Split(' ');
            var client       = botService.Client;

            if (messageParts.Length >= 2)
            {
                var originMessage = message.ReplyToMessage;
                if (originMessage == null)
                {
                    await client.SendTextMessageAsync
                    (
                        message.Chat.Id,
                        "pweese repwy to that users message fiwst >w<!",
                        replyToMessageId : message.MessageId
                    );
                }
                else
                {
                    var table         = dbContext.SavedMessages;
                    var existingEntry = table.Where(savedMessage => savedMessage.UserId == message.From.Id && savedMessage.MessageTag == messageParts[1]).FirstOrDefault();
                    if (existingEntry != null)
                    {
                        await client.SendTextMessageAsync
                        (
                            message.Chat.Id,
                            "Updated Message",
                            replyToMessageId : message.MessageId
                        );

                        existingEntry.ChatId    = message.Chat.Id;
                        existingEntry.MessageId = originMessage.MessageId;
                    }
                    else
                    {
                        await client.SendTextMessageAsync
                        (
                            message.Chat.Id,
                            "Saved Message",
                            replyToMessageId : message.MessageId
                        );

                        table.Add(new UserSavedMessages(messageParts[1], message.From.Id, message.Chat.Id, originMessage.MessageId));
                    }
                    dbContext.SaveChanges();
                }
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "Invalid Request",
                    replyToMessageId : message.MessageId
                );
            }
        }
Пример #15
0
        private static BotDbContext GetContextWithEmptyChat()
        {
            var context = new BotDbContext(CreateNewContextOptions());

            context.Database.EnsureDeleted();
            context.Chats.Add(new Chat(ChatId));
            context.SaveChanges();
            return(context);
        }
Пример #16
0
        public async Task <OkResult> GetUpdates([FromBody] Update updates)
        {
            if (updates.Type == UpdateType.Unknown)
            {
                return(Ok());
            }
            else if (updates.Type == UpdateType.Message)
            {
                if (updates.Message.Chat.Type == ChatType.Private)
                {
                    if (updates.Type == UpdateType.Message)
                    {
                    }
                }
                else if (updates.Message.Chat.Type == ChatType.Supergroup || updates.Message.Chat.Type == ChatType.Group)
                {
                    if (updates.Message.Text == "فعال شدن")
                    {
                        var creator = await _client.GetChatMemberAsync(updates.Message.Chat.Id, updates.Message.From.Id);

                        if (creator.Status == ChatMemberStatus.Creator)
                        {
                            if (_context.Groups.Any(c => c.Id == updates.Message.Chat.Id.ToString()))
                            {
                                await _client.SendTextMessageAsync(updates.Message.Chat.Id, ErrorAnswerModel.GroupAddedbefor);
                            }
                            else
                            {
                                try
                                {
                                    _context.Groups.Add(new Group
                                    {
                                        Id         = updates.Message.Chat.Id.ToString(),
                                        BotSetting = new botSetting {
                                            LockGap = false, LockSticker = false, LockVideo = false, LockVoice = false, SettingId = Guid.NewGuid().ToString()
                                        },
                                        GroupAdded  = true,
                                        GroupName   = updates.Message.Chat.FirstName + updates.Message.Chat.LastName,
                                        MemberCount = await _client.GetChatMembersCountAsync(updates.Message.Chat.Id),
                                    });

                                    _context.Admins.Add(new Admin
                                    {
                                        Id       = updates.Message.From.Id.ToString(),
                                        Name     = updates.Message.From.FirstName + updates.Message.From.LastName,
                                        UserName = updates.Message.From.Username ?? default
                                    });

                                    _context.AdminGroups.Add(new AdminGroup {
                                        AdminId = updates.Message.From.Id.ToString(), GroupId = updates.Message.Chat.Id.ToString()
                                    });

                                    _context.SaveChanges();

                                    await _client.SendTextMessageAsync(updates.Message.Chat.Id, TextAnswerModel.GapAdded(updates.Message.Chat.Id, updates.Message.From.Id));
                                }
Пример #17
0
        /// <summary>
        /// Добавить пользователя в базу данных.
        /// Добавить все зависимые сущности, чтобы не проверять их потом на null.
        /// Аккуратно добавить все зависимости, внешние IDшники.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="chatId"></param>
        public static void AddUserToDb(BotDbContext db, long chatId)
        {
            //Создадим пользователя.
            User user = new User()
            {
                ChatId = chatId,
                Role   = "user",
            };

            db.Users.Add(user);

            //Создадим сущность UserInfo
            UserInfo uInfo = new UserInfo()
            {
                ChatId = chatId,
                User   = user,
                UserId = user.Id,
            };

            db.UserInfo.Add(uInfo);

            //Привяжем UserInfo к пользователю
            user.Info = uInfo;

            //Создадим сущность ChatState
            ChatState chatState = new ChatState()
            {
                ChatId = chatId,
                UserId = user.Id,
                User   = user,
            };

            db.ChatState.Add(chatState);

            //Привяжем ChatState к пользователю
            user.ChatState = chatState;

            //Создадим сущность Goal
            Goal goal = new Goal()
            {
                ChatId = chatId,
                User   = user,
                UserId = user.Id,
            };

            db.Goals.Add(goal);

            //Привяжем Goal к пользователю
            user.Goal = goal;

            //Сохраняем все изменения и все добавленные сущности.
            db.SaveChanges();
        }
Пример #18
0
        private static void AddOnePromotedChatMember(BotDbContext context)
        {
            var promotedChatMember = new PromotedChatMember
            {
                Id       = 1,
                Username = "******",
                FullName = "User for tests",
                UserId   = UserId
            };

            context.PromotedMembers.Add(promotedChatMember);
            context.SaveChanges();
        }
Пример #19
0
        public void CreateDiscordUser(IUser user, decimal amount)
        {
            using (BotDbContext dbContext = this.CreateDbContext())
            {
                dbContext.Users.Add(new DiscordUserModel()
                {
                    DiscordUserId = user.Id,
                    Username      = user.Username,
                    Balance       = amount
                });

                dbContext.SaveChanges();
            }
        }
Пример #20
0
    private void InitDbContext(BotDbContext context)
    {
        context.BotUsers.Add(DefaultUser);
        context.BotUsers.Add(AdminUser);
        context.BotUsers.Add(DefaultUserWithMaxReminds);

        for (var i = 0; i < AddRemindCommand.MaxRemindsCount; i++)
        {
            context.Reminds.Add(new Remind(DefaultUserWithMaxReminds.Id, "text", new DateTime(2101, 1, 1, 1, 1, 1),
                                           ConsumerType.Vkontakte));
        }

        context.SaveChanges();
    }
Пример #21
0
        public void AnswerToQuiz_FailsIfTimeIsCorrectButExpired()
        {
            this.testContext.CommandsManager.StartQuiz(this.caller, 2, Cryptography.Hash("1"), 2, string.Empty);

            using (BotDbContext dbContext = this.testContext.CreateDbContext())
            {
                QuizModel quiz = dbContext.ActiveQuizes.First();
                quiz.CreationTime = DateTime.Now - TimeSpan.FromMinutes(20);
                dbContext.Update(quiz);
                dbContext.SaveChanges();
            }

            AnswerToQuizResponseModel answer = this.testContext.CommandsManager.AnswerToQuiz(this.caller, "1");

            Assert.False(answer.Success);
        }
Пример #22
0
        /// <summary>Populates database with unused addresses.</summary>
        private void PregenerateAddresses(BotDbContext context)
        {
            this.logger.Trace("()");
            this.logger.Info("Database was not prefilled with addresses. Starting.");

            int alreadyGenerated = this.coinService.GetAddressesByAccount(AccountName).Count;

            this.logger.Info("{0} addresses are already in the wallet.", alreadyGenerated);

            long toGenerateCount = this.settings.PregeneratedAddressesCount - alreadyGenerated;

            this.logger.Info("Generating {0} addresses.", toGenerateCount);

            for (long i = 0; i < toGenerateCount; ++i)
            {
                try
                {
                    this.coinService.GetNewAddress(AccountName);
                }
                catch (RpcException e)
                {
                    this.logger.Info("Too many attempts. Waiting 10 sec.", toGenerateCount);
                    this.logger.Trace("Exception: {0}", e.ToString());
                    Thread.Sleep(10000);
                    i--;
                }

                if (i % 1000 == 0)
                {
                    this.logger.Info("Generated {0} addresses.", i);
                }
            }

            List <string> allAddresses = this.coinService.GetAddressesByAccount(AccountName);

            foreach (string address in allAddresses)
            {
                context.UnusedAddresses.Add(new AddressModel()
                {
                    Address = address
                });
            }

            context.SaveChanges();
            this.logger.Info("Addresses generated.");
            this.logger.Trace("(-)");
        }
Пример #23
0
        /// <summary>Withdraws given amount of money to specified address.</summary>
        /// <exception cref="CommandExecutionException">Thrown when user supplied invalid input data.</exception>
        public void Withdraw(IUser user, decimal amount, string address)
        {
            this.logger.Trace("({0}:{1},{2}:{3},{4}:'{5}')", nameof(user), user.Id, nameof(amount), amount, nameof(address), address);

            this.AssertAmountPositive(amount);

            if (amount < this.settings.MinWithdrawAmount)
            {
                this.logger.Trace("(-)[MIN_WITHDRAW_AMOUNT]");
                throw new CommandExecutionException($"Minimal withdraw amount is {this.settings.MinWithdrawAmount} {this.settings.Ticker}.");
            }

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                DiscordUserModel discordUser = this.GetOrCreateUser(context, user);

                // Don't allow withdrawals to deposit address.
                if (discordUser.DepositAddress != null && discordUser.DepositAddress == address)
                {
                    this.logger.Trace("(-)[WITHDRAWAL_TO_DEPOSIT_ADDR]");
                    throw new CommandExecutionException("You can't withdraw to your own deposit address!");
                }

                decimal amountToSend = amount - this.settings.NetworkFee;
                this.logger.Trace("(The amount after fee: {0})", amountToSend);

                this.AssertBalanceIsSufficient(discordUser, amountToSend);

                try
                {
                    this.nodeIntegration.Withdraw(amountToSend, address);
                    this.logger.Debug("User '{0}' withdrew {1} to address '{2}'. After fee subtracted '{3}'", discordUser, amount, address, amountToSend);
                }
                catch (InvalidAddressException)
                {
                    this.logger.Trace("(-)[INVALID_ADDRESS]");
                    throw new CommandExecutionException("Address specified is invalid.");
                }

                discordUser.Balance -= amount;

                context.Update(discordUser);
                context.SaveChanges();
            }

            this.logger.Trace("(-)");
        }
Пример #24
0
        public QuizTests()
        {
            this.testContext = new TestContext();

            this.caller = this.testContext.SetupUser(1, "caller");

            // That will create a user in db.
            this.testContext.CommandsManager.GetUserBalance(this.caller);

            using (BotDbContext dbContext = this.testContext.CreateDbContext())
            {
                DiscordUserModel user = dbContext.Users.First();
                user.Balance = 10;
                dbContext.Update(user);
                dbContext.SaveChanges();
            }
        }
        private DiscordUserModel CreateUser(BotDbContext context, IUser user)
        {
            this.logger.Trace("({0}:{1})", nameof(user), user.Id);
            this.logger.Debug("Creating a new user with id {0} and username '{1}'.", user.Id, user.Username);

            var discordUser = new DiscordUserModel()
            {
                Balance       = 0,
                DiscordUserId = user.Id,
                Username      = user.Username
            };

            context.Users.Add(discordUser);
            context.SaveChanges();

            this.logger.Trace("(-):'{0}'", discordUser);
            return(discordUser);
        }
Пример #26
0
        private static async Task ClearSavedMessage(IBotService botService, Message message, BotDbContext dbContext)
        {
            var messageParts = message.Text.Split(' ');
            var client       = botService.Client;
            var table        = dbContext.SavedMessages;
            IQueryable <UserSavedMessages> results;

            if (messageParts.Length >= 2)
            {
                results = table.Where(savedMessage => savedMessage.UserId == message.From.Id && savedMessage.MessageTag == messageParts[1]);
            }
            else
            {
                results = table.Where(savedMessage => savedMessage.UserId == message.From.Id);
            }
            table.RemoveRange(results);
            dbContext.SaveChanges();
        }
Пример #27
0
        private static async Task WelcomeCommand(IBotService botService, Message message, BotDbContext dbContext)
        {
            var client = botService.Client;

            if (message.Text.Length > 10)
            {
                var welcomeMessage = message.Text.Substring(9);
                var table          = dbContext.WelcomeMessages;
                var existingEntry  = table.Where(welcome => welcome.ChatId == message.Chat.Id).FirstOrDefault();
                if (existingEntry != null)
                {
                    await client.SendTextMessageAsync
                    (
                        message.Chat.Id,
                        "Updated Welcome Message",
                        replyToMessageId : message.MessageId
                    );

                    existingEntry.ChatId = message.Chat.Id;
                    existingEntry.Text   = welcomeMessage;
                }
                else
                {
                    await client.SendTextMessageAsync
                    (
                        message.Chat.Id,
                        "Saved Welcome Message",
                        replyToMessageId : message.MessageId
                    );

                    table.Add(new GroupWelcomeMessages(message.Chat.Id, welcomeMessage));
                }
                dbContext.SaveChanges();
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "Invalid Request",
                    replyToMessageId : message.MessageId
                );
            }
        }
Пример #28
0
        /// <summary>
        /// Поменять текущее состояние в базе данных или содать это состояние.
        /// </summary>
        /// <param name="chatId"></param>
        /// <param name="hopType"></param>
        /// <param name="newStateName"></param>
        private static void ChangeCurrentChatState(long chatId, HopType hopType, string newStateName)
        {
            using (BotDbContext db = new BotDbContext(HelperDataBase.DB_OPTIONS))
            {
                //Возьмем значение состояния из базы
                ChatState chatState =
                    (from s in db.ChatState
                     where s.ChatId == chatId
                     select s).FirstOrDefault();

                string stateString = chatState?.State;

                //Если ячейка в базе пустая, то заполним её чем-нибудь и поменяем тип хопа чтобы потом переписать несусветицу.
                if (string.IsNullOrEmpty(stateString?.Trim(' ')))
                {
                    stateString = "___";
                    hopType     = HopType.RootLevelHope;
                }

                //Поменять состояние в базе данных.
                StateController stateCtrl = new StateController(stateString);

                //Будем изменять значение состояния в зависимости от типа перехода состояния.
                switch (hopType)
                {
                case HopType.NextLevelHope:
                    stateCtrl.AddStateAsNextState(newStateName);
                    break;

                case HopType.CurrentLevelHope:
                    stateCtrl.ChangeCurrentStateName(newStateName);
                    break;

                case HopType.RootLevelHope:
                    stateCtrl.SetRootState(newStateName);
                    break;
                }

                //получаем измененную строку состояния и сохраняем в базу
                string newStateString = stateCtrl.State;
                chatState.State = newStateString;
                db.SaveChanges();
            }
        }
Пример #29
0
        /// <summary>
        /// Checks if money were deposited to an address associated with any user who has a deposit address.
        /// When money are deposited user's balance is updated.
        /// </summary>
        private void CheckDeposits(BotDbContext context)
        {
            this.logger.Trace("()");

            List <DiscordUserModel> usersToTrack = context.Users.Where(x => x.DepositAddress != null).ToList();

            this.logger.Trace("Tracking {0} users.", usersToTrack.Count);

            foreach (DiscordUserModel user in usersToTrack)
            {
                decimal receivedByAddress = this.coinService.GetReceivedByAddress(user.DepositAddress, this.settings.MinConfirmationsForDeposit);

                if (receivedByAddress > user.LastCheckedReceivedAmountByAddress)
                {
                    decimal recentlyReceived = receivedByAddress - user.LastCheckedReceivedAmountByAddress;

                    // Prevent users from spamming small amounts of coins.
                    // Also keep in mind if you'd like to change that- EF needs to be configured to track such changes.
                    // https://stackoverflow.com/questions/25891795/entityframework-not-detecting-changes-to-decimals-after-a-certain-precision
                    if (recentlyReceived < 0.01m)
                    {
                        this.logger.Trace("Skipping dust {0} for user {1}.", recentlyReceived, user);
                        continue;
                    }

                    this.logger.Debug("New value for received by address is {0}. Old was {1}. Address is {2}.", receivedByAddress, user.LastCheckedReceivedAmountByAddress, user.DepositAddress);

                    user.LastCheckedReceivedAmountByAddress = receivedByAddress;
                    user.Balance += recentlyReceived;

                    context.Attach(user);
                    context.Entry(user).Property(x => x.Balance).IsModified = true;
                    context.Entry(user).Property(x => x.LastCheckedReceivedAmountByAddress).IsModified = true;
                    context.SaveChanges();

                    this.logger.Info("User '{0}' deposited {1}!. New balance is {2}.", user, recentlyReceived, user.Balance);
                }
            }

            this.logger.Trace("(-)");
        }
        /// <summary>Gets deposit address for a user.</summary>
        /// <exception cref="OutOfDepositAddressesException">Thrown when bot ran out of unused deposit addresses.</exception>
        public string GetDepositAddress(IUser user)
        {
            this.logger.Trace("({0}:{1})", nameof(user), user.Id);

            using (BotDbContext context = this.contextFactory.CreateContext())
            {
                DiscordUserModel discordUser = this.GetOrCreateUser(context, user);

                string depositAddress = discordUser.DepositAddress;

                // Assign deposit address if it wasn't assigned it.
                if (depositAddress == null)
                {
                    this.logger.Trace("Assigning deposit address for '{0}'.", discordUser);

                    AddressModel unusedAddress = context.UnusedAddresses.FirstOrDefault();

                    if (unusedAddress == null)
                    {
                        var message = "Bot ran out of deposit addresses!";
                        this.logger.Fatal(message);
                        this.fatalNotifier.NotifySupport(message);

                        this.logger.Trace("(-)[NO_ADDRESSES]");
                        throw new OutOfDepositAddressesException();
                    }

                    context.UnusedAddresses.Remove(unusedAddress);

                    depositAddress             = unusedAddress.Address;
                    discordUser.DepositAddress = depositAddress;
                    context.Update(discordUser);
                    context.SaveChanges();
                }

                this.logger.Trace("(-):'{0}'", depositAddress);
                return(depositAddress);
            }
        }