Example #1
0
    async def get_random_word(self, ctx, *args):
        """Get random word from list and send it.

        Args:
            ctx (commands.context.Context): Context object to execute functions
            args (tuple): List of arguments (Custom name or mode of function)
        """
        if not args:
            self.curr_user = ctx.author.mention
        else:
            args = list(args)
            if args[0] == "добавить":
                args.pop(0)
                word_to_add = " ".join(args)
                await ctx.reply(
                    words_base.manage_words_table(word_to_add,
                                                  delete_mode=False),
                    delete_after=self.delay_time,
                )
                await asyncio.sleep(self.delay_time)
                await ctx.message.delete()
                return
            if args[0] == "удалить":
                if database.get_data(
                        "mainDB",
                        True,
                        "SELECT * FROM admin_list WHERE admins_id = ?",
                        ctx.author.id,
                ):
                    args.pop(0)
                    word_to_delete = " ".join(args)
                    await ctx.reply(
                        words_base.manage_words_table(word_to_delete,
                                                      delete_mode=True),
                        delete_after=self.delay_time,
                    )
                    await asyncio.sleep(self.delay_time)
                    await ctx.message.delete()
                return
            if args[0] == "рандом":
                try:
                    r_user = await users.get_random_user(ctx.message)
                except UsersNotFound as warning:
                    await ctx.reply(f"Произошла ошибка: {warning}!")
                    return
                self.curr_user = r_user.mention
            else:
                self.curr_user = args[0]
        WORDS_ARRAY = database.get_data("wordsDB", False,
                                        "SELECT words FROM main_words_base")
        if not WORDS_ARRAY:
            await ctx.reply(
                "Я пока не знаю никаких слов, "
                "однако вы можете добавить новые слова в мой словарь",
                delete_after=self.delay_time,
            )
            await asyncio.sleep(self.delay_time)
            await ctx.message.delete()
        else:
            await ctx.send(f"{self.curr_user} {random.choice(WORDS_ARRAY)}")
Example #2
0
def select_bot_config():
    """Select main bot to run.

    This function allows user to select the desired bot to run
    when main script starts up
    """
    list_of_bots = database.get_data("confDB", False,
                                     "SELECT bot_name FROM tokens")
    curr_selected_bot = database.get_data(
        "mainDB", True, "SELECT current_selected_bot FROM variables")
    bots_count = 0
    if not list_of_bots:
        print(
            "\nIt looks like there are no bots in my list, try adding a new one\n"
        )
    elif len(list_of_bots) == 1:
        print("\nSince you haven't added any more bots, "
              f'your only active bot is "{list_of_bots[curr_selected_bot]}"\n')
    else:
        print("\nAt the moment, the selected bot is "
              f'"{list_of_bots[curr_selected_bot]}"')
        print("Here are all the added bots:")
        for bot_name in list_of_bots:
            bots_count += 1
            print(f"{bots_count}. {bot_name}")
        print("0. Exit")
        while True:
            select_bot = get_user_input("\nEnter the number of option:")
            if select_bot == "0":
                print("\nExiting to main menu\n")
                break
            try:
                index_of_bot = int(select_bot) - 1
                selected_bot = list_of_bots[index_of_bot]
                if index_of_bot in range(len(list_of_bots)):
                    print("\nGreat choice! "
                          f'Selecting "{selected_bot}" as default...\n')
                    database.modify_data(
                        "mainDB",
                        "UPDATE variables SET current_selected_bot = ?",
                        index_of_bot,
                    )
                    break
                print("Invalid number of option. Please, try again")
            except ValueError:
                print("\nIt looks like you entered not a number. "
                      "Please, try again")
    time.sleep(0.5)
Example #3
0
def manage_r_words_tables(word, table, delete_mode=False):
    """Manage russian roulette word base.

    Args:
        word (str): Word to add or remove
        table (str): Table to modify
        delete_mode (bool): Trigger for delete mode
        If set to True, words will be deleted from table,
        otherwise - words will be added

    Returns:
        str: Function completion message or warning
    """
    requested_word = database.get_data(
        "wordsDB", True,
        f"SELECT * FROM roulette_{table}_words WHERE words = ?", word)
    if not delete_mode:
        if not requested_word:
            database.modify_data(
                "wordsDB", f"INSERT INTO roulette_{table}_words VALUES (?)",
                word)
            return f'Хей, я успешно добавил слово "{word}" себе в базу!'
        return "Данное слово уже есть в базе данных, попробуйте добавить другое"
    if requested_word:
        database.modify_data(
            "wordsDB", f"DELETE FROM roulette_{table}_words WHERE words = ?",
            word)
        return f'Хей, я успешно удалил слово "{word}" из своей базы!'
    return "Ой, я не смог найти это слово. Убедитесь в правильности написания!"
Example #4
0
def _get_users_list():
    """Get and return list of users ids.

    Returns:
        list: Array of users ids from DB
    """
    return database.get_data("mainDB", False, "SELECT users_id FROM users")
Example #5
0
    async def rsp_mode(self, ctx, *args):
        """Execute correct mode of game depending on arguments.

        If arguments aren't provided, executes multiplayer game.
        Otherwise, executes game with bot

        Args:
            ctx (commands.context.Context): Context object to execute functions
            args (tuple): List of arguments (RSP variants, if playing with bot)
        """
        if not args:
            if database.get_data("mainDB", True,
                                 "SELECT rsp_game_active FROM variables"):
                await ctx.reply("Сессия игры уже запущена, "
                                "чтобы начать новую игру, закончите старую")
                return
            await self.__rsp_multi_game(ctx)
            return
        if len(args) == 1:
            if args[0].isnumeric():
                await self.__rsp_multi_game(ctx, args[0])
                return
            await self.__rsp_bot_game(ctx, args[0])
            return
        if len(args) == 2:
            if args[1].isnumeric():
                await self.__rsp_bot_game(ctx, args[0], args[1])
                return
            await ctx.reply("Похоже вы передали неверное значение!")
            return
Example #6
0
def prepare_chains_data():
    """Prepare list of words and make dictionary.

    This function gets current list of words and make pairs and chains
    to work with

    Also it checks if current database is smaller than 80 words

    Returns:
        Union[list, bool]: List of words array and words dictionary.
        If current size of words database is small, returns False
    """
    word_dict = {}
    database_words = database.get_data("wordsDB", False,
                                       "SELECT * FROM markov_words")
    curr_len = len(database_words)
    if curr_len < 80:
        return False
    pair = make_pairs(database_words)
    for word_1, word_2 in pair:
        if word_1 in word_dict.keys():
            word_dict[word_1].append(word_2)
        else:
            word_dict[word_1] = [word_2]
    return [database_words, word_dict]
Example #7
0
def add_bot_config():
    """Add bot configuration into the database.

    This function require bot's name and token to add this to the database.
    If initial setup was completed, also redirects to main menu of setup only
    """
    current_status = get_curr_setup_status()
    bot_name = get_user_input("\nEnter name of your Discord bot: ")
    if not current_status:
        print("\nEnter your Discord bot token\n"
              "(If you don't know where to get it, "
              f"go to this page - {WIKI_LINK})")
    else:
        if database.get_data("confDB", True,
                             "SELECT * FROM tokens WHERE bot_name = ?",
                             bot_name):
            print("A bot with the same name is already in the database!"
                  "\nCancel adding ...\n")
        print("\nEnter your Discord bot token")
    while True:
        bot_token = get_user_input()
        if len(bot_token) == 59:
            break
        print("\nIt looks like your token is wrong.\n"
              "It must be 59 characters long "
              f"(Yours is {len(bot_token)} characters long)")
    database.modify_data("confDB", "INSERT INTO tokens VALUES (?, ?)",
                         bot_name, bot_token)
    print(f'\nGreat, I added bot "{bot_name}" to the database!')
    if current_status:
        print("")
    time.sleep(0.5)
Example #8
0
    async def ship_func_chooser(self, ctx, *args):
        """Select correct function depending of statement.

        This function chooses another function to run, when
        certain statement is true

        Args:
            ctx (commands.context.Context): Context object to execute functions
            args (tuple): List of arguments

        Returns:
            None: If there is an active shipping
        """
        if database.get_data("mainDB", True,
                             "SELECT ship_in_active FROM variables"):
            return
        if len(args) == 1:
            if "скип" in args:
                await self.__reset_ship(ctx)
            elif "фаст" in args:
                await self.__random_ship(ctx, True)
            elif "реролл" in args:
                await self.__reset_ship(ctx, False)
                await self.__random_ship(ctx)
            elif "выйти" in args or "войти" in args:
                await self.__manage_ship_ignore(ctx, ctx.author.id, args[0])
            else:
                await ctx.reply("Я не могу шипперить одного человека. "
                                "Добавьте ещё кого-то, чтобы я смог "
                                'сделать "магию"')
        elif len(args) == 2:
            await self.__custom_ship(ctx, list(args))
        else:
            await self.__random_ship(ctx)
Example #9
0
    async def send_uptime(self, ctx):
        """Calculate and send current uptime of bot.

        Also, it's stores bot start time in order to prevent
        from constant calls to database on each uptime request

        Args:
            ctx (commands.context.Context): Context object to execute functions
        """
        if not self.start_time:
            self.start_time = database.get_data(
                "mainDB", True, "SELECT bot_uptime FROM variables")
        curr_uptime = int(time.time()) - self.start_time
        time_string = td_format.format_timedelta(
            datetime.timedelta(seconds=curr_uptime))
        if curr_uptime < 36000:
            await ctx.reply(
                f"Я не сплю уже на протяжении **0{time_string}**",
                delete_after=self.delay_time,
            )
        else:
            await ctx.reply(
                f"Я не сплю уже на протяжении **{time_string}**",
                delete_after=self.delay_time,
            )
        await asyncio.sleep(self.delay_time)
        await ctx.message.delete()
Example #10
0
    async def __delete_exist_word(self, ctx, args):
        """Delete existing word from Russian Roulette DB.

        This function controls deleting word from DB,
        as well as simplifiying main code base.

        Also, there are checks for any non-standard situation,
        like if arguments tuple having less than 2 elements,
        user wrote wrong table alias or user isn't bot admin.

        Args:
            ctx (commands.context.Context): Context object to execute functions
            args (tuple): List of arguments (Bullet count number)
        """
        if len(args) == 1:
            await ctx.reply(
                "Вы не передали никаких дополнительных аргументов!",
                delete_after=self.delete_time,
            )
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        if args[1] not in self.tables_aliases:
            await ctx.reply(
                "Вы указали неверное название таблицы. "
                "Доступные названия: "
                f'{", ".join(key for key in self.tables_aliases)}',
                delete_after=self.delete_time,
            )
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        bot_admin = database.get_data(
            "mainDB",
            True,
            "SELECT * FROM admin_list "
            "WHERE admins_id = ?",
            ctx.author.id,
        )
        if bot_admin is None:
            await ctx.reply(
                "Вы не имеете необходимых прав для удаления слов. "
                "Удаление слов доступно администраторам бота",
                delete_after=self.delete_time,
            )
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        table_to_modify = self.tables_aliases[args[1]]
        word_to_delete = " ".join(args[2:])
        await ctx.reply(
            words_base.manage_r_words_tables(word_to_delete,
                                             table_to_modify,
                                             delete_mode=True),
            delete_after=self.delete_time,
        )
        await asyncio.sleep(self.delete_time)
        await ctx.message.delete()
        return
Example #11
0
def get_curr_setup_status():
    """Get current setup status from database.

    Returns:
        int: Current setup status value
    """
    current_status = database.get_data(
        "mainDB", True, "SELECT is_setup_completed FROM variables")
    return current_status
Example #12
0
def check_bots_database():
    """Check for elements in bot's database.

    Returns:
        int: Size of list if there is any elements
        None: If table is empty
    """
    db_status = database.get_data("confDB", False,
                                  "SELECT bot_name FROM tokens")
    return None if not db_status else len(db_status)
Example #13
0
    async def __remove_admin(self, ctx, user_id):
        """Remove user's ID from admin list.

        This function handles removal of user's ID from admin list.

        **Noteworthy:** Since this list is very important for the bot's operation,
        several checks have been added here: if the list consists of one ID,
        it cancels the deletion, if the admin wants to delete himself,
        he is asked to confirm the action

        Args:
            ctx (commands.context.Context): Context object to execute functions
            user_id (str): User's ID to remove from admins
        """
        if int(user_id) == ctx.author.id and users.is_user_admin(user_id):
            if (len(
                    database.get_data(
                        "mainDB", False,
                        "SELECT admins_id FROM admin_list")) == 1):
                await ctx.reply("Вы единственный админ бота. "
                                "Управление ботом будет затруднено, "
                                "если список админов будет пуст, "
                                "поэтому я отменяю удаление")
            else:
                ask_msg = await ctx.reply("Вы уверены что хотите убрать себя?"
                                          " (Да/Нет)")
                try:
                    wait_msg = await self.client.wait_for("message",
                                                          timeout=15)
                except asyncio.TimeoutError:
                    await ask_msg.edit(
                        content="Похоже вы не решились с выбором. "
                        "Я отменил удаление вас из списка")
                else:
                    if wait_msg.content.lower() in ["да", "ок", "давай"]:
                        database.modify_data(
                            "mainDB",
                            "DELETE FROM admin_list WHERE admins_id = ?",
                            user_id,
                        )
                        await ask_msg.edit(content="Я удалил вас из админов :("
                                           )
                    elif wait_msg.content.lower() in ["не", "нет", "неа"]:
                        await ask_msg.edit(content="Удаление было отменено")
                    else:
                        await ask_msg.edit(content="Вы ответили как-то иначе, "
                                           "удаление было отменено")
        else:
            if not users.is_user_admin(user_id):
                await ctx.reply("Данный пользователь не является админом")
            else:
                database.modify_data(
                    "mainDB", "DELETE FROM admin_list WHERE admins_id = ?",
                    user_id)
                await ctx.reply("Я успешно удалил такого админа")
Example #14
0
async def on_member_leave(member):
    """Remove left server users from database.

    This function removes every left user from database, while bot is running.
    This helps to prevent any problems with commands that use a table of users.

    Args:
        member (discord.member.Member): Data about left user
    """
    member_status = database.get_data(
        "mainDB", True, "SELECT * FROM users WHERE users_id = ?", member.id)
    if not member.bot and member_status is not None:
        users.rem_member_from_db(member.id)
Example #15
0
def bot_panel_init():
    """Select function depending on status.

    This function checks the current setting status
    and selects the required function to run.
    If current_status is 0, launches setup of bot,
    otherwise - main menu
    """
    current_status = database.get_data(
        "mainDB", True, "SELECT is_setup_completed FROM variables")
    if not current_status:
        panel_scripts.bot_setup()
    bot_menu()
Example #16
0
def _get_admin_status(user_id):
    """Get user_id and compares with one in DB.

    Args:
        user_id (str): ID of user to check

    Returns:
        bool: True, if compare successful. False otherwise
    """
    return database.get_data(
        "mainDB", False,
        "SELECT admins_id FROM admin_list WHERE admins_id = ?",
        user_id) == int(user_id)
Example #17
0
    async def __manage_ship_ignore(self, ctx, user_id, mode):
        """Manage ignore list of shipping users.

        This function helps users to opt out of shipping or
        opt in.

        Args:
            ctx (commands.context.Context): Context object to execute functions
            user_id (int): ID of user to ignore/add
            mode (str): Mode of operation with ignore list
        """
        user_state = database.get_data(
            "mainDB", True, "SELECT * FROM ignored_users WHERE users_id = ?",
            user_id)
        if mode == "выйти":
            if user_state is None:
                database.modify_data("mainDB",
                                     "INSERT INTO ignored_users VALUES (?)",
                                     user_id)
                database.modify_data("mainDB",
                                     "DELETE FROM users WHERE users_id = ?",
                                     user_id)
                await ctx.reply(
                    "Вы были убраны из списка участников шиппинга!",
                    delete_after=self.delete_time,
                )
                await asyncio.sleep(self.delete_time)
                await ctx.message.delete()
                return
            await ctx.reply("Вы не учавствуете в шиппинге!",
                            delete_after=self.delete_time)
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        if user_state is not None:
            database.modify_data(
                "mainDB", "DELETE FROM ignored_users WHERE users_id = ?",
                user_id)
            database.modify_data("mainDB", "INSERT INTO users VALUES (?)",
                                 user_id)
            await ctx.reply(
                "Вы были добавлены в список участников шиппинга!",
                delete_after=self.delete_time,
            )
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        await ctx.reply("Вы уже учавствуете в шиппинге!",
                        delete_after=self.delete_time)
        await asyncio.sleep(self.delete_time)
        await ctx.message.delete()
Example #18
0
def markov_delay_handler(mode):
    """Handle needed delay operation for Markov chains.

    This function manages delay of autogenerated message and
    updates current message counter

    Here are modes, such as:
    - Update: Updates current message counter (+1)
    - Clear: Updates delay of autogenerated message
    (Random integer from 20 to 45)
    - Get: Return delay and message counter

    If wrong mode provided or it isn't a 'get' mode, returns None

    Args:
        mode (str): Mode of delay handler

    Returns:
        Union[list, None]: List of current delay and message counter.
        If wrong mode/'update' or 'clear' mode were provided, returns None
    """
    current_delay = database.get_data("mainDB", True,
                                      "SELECT markov_delay FROM variables")
    msg_counter = database.get_data("mainDB", True,
                                    "SELECT msg_counter FROM variables")
    if mode == "update":
        database.modify_data("mainDB", "UPDATE variables SET msg_counter = ?",
                             msg_counter + 1)
    elif mode == "clear":
        database.modify_data(
            "mainDB",
            "UPDATE variables SET markov_delay = ?, msg_counter = ?",
            random.randint(60, 120),
            1,
        )
    elif mode == "get":
        return [current_delay, msg_counter]
    return None
Example #19
0
def parsed_accounts_data(limit=None):
    """Get parsed accounts data into dictionaries.

    This function is used to get needed accounts data, or some of them,
    from the database and return it as a list of dictionaries.

    Note: The data is returned in descending order of the balance
    and all deleted accounts are ignored

    Args:
        limit (int): The amount of accounts to return

    Returns:
        dict: Dictionary containing needed accounts data (ID's, balance)
    """
    user_ids = database.get_data(
        "pointsDB",
        False,
        "SELECT user_id FROM points_accounts WHERE is_deleted = 0 "
        "ORDER BY points_balance DESC",
    )
    accounts_balance = database.get_data(
        "pointsDB",
        False,
        "SELECT points_balance FROM points_accounts WHERE is_deleted = 0 "
        "ORDER BY points_balance DESC",
    )
    if user_ids is None or accounts_balance is None:
        return None
    if limit is None:
        return dict(zip(user_ids, accounts_balance))
    accounts_dict = {}
    if len(user_ids) < limit:
        limit = len(user_ids)
    for i in range(limit):
        accounts_dict[user_ids[i]] = accounts_balance[i]
    return accounts_dict
Example #20
0
def get_ship_data():
    """Get ship data from DB and return dictionary.

    Returns:
        dict: Dictionary with ship data
    """
    ship_data = database.get_data(
        "mainDB",
        False,
        "SELECT ship_date, ship_activated, ship_in_active FROM variables",
    )
    return {
        "ship_date": ship_data[0],
        "ship_activated": ship_data[1],
        "ship_in_active": ship_data[2],
    }
Example #21
0
def change_bot_name(bot_name):
    """Handle name changing of bot.

    Args:
        bot_name (str): Current name of bot
    """
    new_bot_name = get_user_input("\nEnter new bot's name:")
    bot_info = database.get_data("confDB", False,
                                 "SELECT * FROM tokens WHERE bot_name = ?",
                                 bot_name)
    database.modify_data(
        "confDB",
        "UPDATE tokens SET bot_name = ?, bot_token = ?",
        new_bot_name,
        bot_info[1],
    )
    print(f'\nGreat, I changed name from "{bot_name}" to "{new_bot_name}"\n')
Example #22
0
    def __get_random_word(self, condition):
        """Get random word from database.

        This function handles getting random word from DB
        depending on condition of game

        Args:
            condition (str): Condition of game when executed

        Returns:
            str: Random chosen word depending on condition
        """
        words_list = database.get_data(
            "wordsDB", False, f"SELECT words FROM roulette_{condition}_words")
        if words_list is None:
            return self.backup_words[condition]
        return random.choice(words_list)
Example #23
0
async def on_member_join(member):
    """Add new server users to database.

    This function adds every new user/bot to database, while bot is running.
    This helps prevent new users from being ignored in commands
    that use use a table of users (And helps to ignore any bot in commands)

    Args:
        member (discord.member.Member): Data about joined user/bot
    """
    member_status = database.get_data(
        "mainDB", True, "SELECT * FROM ignored_users WHERE users_id = ?",
        member.id)
    if not member.bot and member_status is not None:
        users.add_member_to_db(member.id)
        return
    users.add_bot_to_db(member.id)
Example #24
0
async def update_member_list(client):
    """Update users database on load.

    **Noteworthy:** Currently adding bot to multiple server can cause
    some DB issues. This will be fixed/implemented in future releases.

    Args:
        client (discord.Client): Client object to fetch members of server
    """
    ignored_users_id = database.get_data("mainDB", False,
                                         "SELECT * FROM ignored_users")
    if ignored_users_id is None:
        ignored_users_id = []
    for guild in client.guilds:
        async for member in guild.fetch_members(limit=None):
            if not member.bot and member.id not in ignored_users_id:
                users.add_member_to_db(member.id)
Example #25
0
def get_account_balance(user_id):
    """Get balance of user points account.

    Args:
        user_id (int): The ID of the user

    Returns:
        int: The balance of the user account
        None: If the user does not have an account
    """
    account_status = check_account(user_id)
    if not account_status:
        return None
    user_account = database.get_data(
        "pointsDB",
        True,
        "SELECT points_balance FROM points_accounts WHERE user_id = ?",
        user_id,
    )
    return user_account
Example #26
0
def check_account(user_id):
    """Check if points account exists.

    Args:
        user_id (int): The ID of ther user

    Returns:
        None: If account does not exist
        bool: True if account exists, False if account deleted.
    """
    account_status = database.get_data(
        "pointsDB",
        True,
        "SELECT is_deleted FROM points_accounts WHERE user_id = ?",
        user_id,
    )
    if account_status is None:
        return None
    if account_status == 1:
        return False
    return True
Example #27
0
def get_avatar_bytes(avatar_cooldown=None):
    """Get bytes from avatar picture.

    This function has built-in check for
    avatar change cooldown

    Args:
        avatar_cooldown (Union[int, None]): Cooldown for setting new avatar

    Returns:
        Union[int, list[bytes, int]]:
        Current cooldown time or bytes of PNG w/ new cooldown time
    """
    if not avatar_cooldown:
        avatar_cooldown = database.get_data(
            "mainDB",
            True,
            "SELECT avatar_cooldown FROM variables",
        )
    curr_time = int(time.time())
    curr_cooldown = avatar_cooldown - curr_time
    if curr_cooldown > 0:
        return {
            "avatar_cooldown": avatar_cooldown,
            "curr_cooldown": int(curr_cooldown),
            "avatar_bytes": None,
        }
    new_avatar_cooldown = curr_time + avatar_cooldown
    database.modify_data("mainDB", "UPDATE variables SET avatar_cooldown = ?",
                         new_avatar_cooldown)
    avatar_path = (f"{pathlib.Path().absolute()}/src/avatars/"
                   f"Avatar_{random.randint(1, 16)}.png")
    with open(avatar_path, "rb") as f:
        avatar_bytes = f.read()
    f.close()
    return {
        "avatar_cooldown": new_avatar_cooldown,
        "curr_cooldown": None,
        "avatar_bytes": avatar_bytes,
    }
Example #28
0
def daily_points_manager(user_id):
    """Manage daily points rewarding.

    Args:
        user_id (int): The ID of the user

    Returns:
        int: The amount of bouns points
        bool: False if points accounts does not exist
        None: If user alredy got daily points
    """
    account_status = check_account(user_id)
    if not account_status:
        return False
    current_date = dt.datetime.now().date()
    next_date = (dt.datetime.now() + dt.timedelta(days=1)).date()
    daily_points_date = database.get_data(
        "pointsDB",
        True,
        "SELECT daily_points_date FROM points_accounts WHERE user_id = ?",
        user_id,
    )
    if (not daily_points_date or current_date >= dt.datetime.strptime(
            daily_points_date, "%Y-%m-%d").date()):
        random_points = random.randrange(100, 2000, 100)
        add_points(user_id, random_points, skip_check=True)
        database.modify_data(
            "pointsDB",
            "UPDATE points_accounts SET daily_points_date = ? "
            "WHERE user_id = ?",
            next_date,
            user_id,
        )
        return random_points
    if current_date < dt.datetime.strptime(daily_points_date,
                                           "%Y-%m-%d").date():
        return None
Example #29
0
def is_bot_in_database():
    """Check for bot existence in database.

    **Noteworthy:** This function has failed attempts counter.
    If it hits 3, function will redirect to main menu.

    Returns:
        str: Bot name if it was found in database
        None: If hit 3 failed attempts
    """
    failed_attempts = 1
    while True:
        bot_name = get_user_input("\nEnter the name of the bot:")
        if database.get_data("confDB", True,
                             "SELECT bot_name FROM tokens WHERE bot_name = ?",
                             bot_name):
            return bot_name
        if failed_attempts == 3:
            print("You have entered the bot name "
                  f"incorrectly {failed_attempts} times\n")
            return None
        print("I did not find this name in my database, "
              "please try to enter the correct name again")
        failed_attempts += 1
Example #30
0
    async def __random_ship(self, ctx, fast_mode=False):
        """Ship with two randomly chosen names.

        This function runs ship with random users,
        rather shipping two custom names from arguments

        Args:
            ctx (commands.context.Context): Context object to execute functions
            fast_mode (bool): Skip 'prelude' part before results

        Returns:
            None: If there is an error
        """
        try:
            users_info = await users.get_shipping_users(ctx.message)
        except UsersNotFound as warning:
            await ctx.reply(f"Произошла ошибка: {warning}!",
                            delete_after=self.delete_time)
            await asyncio.sleep(self.delete_time)
            await ctx.message.delete()
            return
        current_date = dt.datetime.now().date()
        next_date = (dt.datetime.now() + dt.timedelta(days=1)).date()
        ship_data = shipping_utils.get_ship_data()
        if ship_data["ship_in_active"]:
            return
        if not ship_data["ship_activated"] and not ship_data["ship_in_active"]:
            await shipping_utils.lock_shipping()
            formatted_data = await shipping_utils.format_usernames(users_info)
            if fast_mode:
                await ctx.reply(
                    f"**Парочка дня на сегодня:** {formatted_data[0]} "
                    ":two_hearts:")
            else:
                await self.__random_ship_messages(ctx, formatted_data[0])
            database.modify_data(
                "mainDB",
                "UPDATE variables SET ship_date = ?, ship_text_full = ?, "
                "ship_text_short = ?, ship_in_active = ?",
                next_date,
                formatted_data[1],
                formatted_data[0],
                0,
            )
        elif (ship_data["ship_activated"] and current_date <
              dt.datetime.strptime(ship_data["ship_date"], "%Y-%m-%d").date()):
            ship_text_full = database.get_data(
                "mainDB", True, "SELECT ship_text_full FROM variables")
            next_date = database.get_data("mainDB", True,
                                          "SELECT ship_date FROM variables")
            next_date_string = self.weekday_dict[dt.datetime.strptime(
                next_date, "%Y-%m-%d").weekday()]
            await ctx.reply(
                f"**Парочка дня на сегодня:** {ship_text_full} "
                ":two_hearts: \n\n*Следующий шиппинг будет доступен "
                f"{next_date_string}*")
        elif (ship_data["ship_activated"] and current_date >=
              dt.datetime.strptime(ship_data["ship_date"], "%Y-%m-%d").date()):
            database.modify_data("mainDB",
                                 "UPDATE variables SET ship_activated = ?", 0)
            await self.__random_ship(ctx, fast_mode)