def create_report(start, end, chat_id):
    if report_json := get_report_json(start, end, chat_id):
        if report_json['incomes'] is not None and report_json['outcome']:
            report = [hbold(f'📊 Отчет \n{start}\n{end}\n'), hbold('📈 Доходы')]

            for income in report_json['incomes']:
                report.append(
                    f"👤 {income['username']}: {income['user_amount']} ({income['percentage']})"
                )
            report.append(
                hunderline(
                    f"💰 Итого: {report_json['incomes_total_amount']}\n"))

            report.append(hbold('📉 Расходы'))
            for outcome in report_json['outcome']:
                report.append(
                    f"{outcome['category_name']}: {outcome['category_amount']} ({outcome['percentage']})"
                )
            report.append(
                hunderline(f"💰 Итого: {report_json['outcome_total_amount']}"))
            report.append(
                hbold(
                    f"\n💸 Остаток: {round(report_json['incomes_total_amount'] - report_json['outcome_total_amount'], 0)}"
                ))
            return '\n'.join(report)
        else:
            return 'Необходимо заполнить доходы и расходы'
Exemple #2
0
async def get_posts(message: types.Message):
    get = db.connect()
    user_id = message.from_user.id
    query = 'SELECT token FROM USERS WHERE user_id=?'
    get_token = get.execute(query, (user_id, ))
    token = get_token.fetchone()[0]

    url = 'https://experts-community.herokuapp.com/api'

    headers = {'Authorization': f'Token {token}'}
    resp = requests.get(url, headers=headers)
    posts = resp.json()

    count = posts['count']
    await message.answer(f'Всего на сайте опубликовано {count} постов.')
    book = []

    for i in range(len(posts['results'][:2])):
        await message.answer(
            (emoji.emojize(":rocket:") * 10) + '\n' + ('Автор:) ' + hunderline(
                str(posts['results'][i]['author']['first_name']) + ' ' +
                str(posts['results'][i]['author']['last_name']))) + '\n' +
            'Название: ' + str(posts['results'][i]['title']) + '\n' +
            'Содержание: ' + hitalic(str(posts['results'][i]['content'])) +
            '\n' + 'Дата: ' +
            code(str(posts['results'][i]['created_at'][:10])) + '\n' +
            (emoji.emojize(":rocket:") * 10))
Exemple #3
0
    def get_all_posts(self):
        get = db.connect()
        user_id = env.int("ADMINS")
        query = 'SELECT token FROM USERS WHERE user_id=?'
        get_token = get.execute(query, (user_id, ))
        token = get_token.fetchone()[0]

        url = 'https://experts-community.herokuapp.com/api'
        headers = {'Authorization': f'Token {token}'}
        resp = requests.get(url, headers=headers)
        posts = resp.json()

        count = posts['count']
        book = self._book
        _ = '\n__________________________________\n'
        for i in range(len(posts['results'])):
            book.append(
                (emoji.emojize(":rocket:") * 3 +
                 hitalic(f'Всего {count} страниц.' +
                         emoji.emojize(":rocket:") * 3 + f'{_}')) + '\n' +
                ('Автор: ' + hunderline(
                    str(posts['results'][i]['author']['first_name']) + ' ' +
                    str(posts['results'][i]['author']['last_name']))) +
                f'{_}' + 'Название: ' + str(posts['results'][i]['title']) +
                f'{_}' + 'Содержание: \n' +
                hitalic(str(posts['results'][i]['content'])) + f'{_}' +
                'Дата: ' + code(str(posts['results'][i]['created_at'][:10])), )
        return book
async def variants_formatting(message: types.Message):
    await message.answer(hbold('hbold'))
    await message.answer(hcode('hcode'))
    await message.answer(hitalic('hitalic'))
    await message.answer(hunderline('hunderline'))
    await message.answer(hstrikethrough('hstrikethrough'))
    await message.answer(hpre('hpre'))
Exemple #5
0
def text_answer(data: list):
    text = fmt.text(
        fmt.text(fmt.hbold(data[0])),
        fmt.text(fmt.hunderline(data[1])),
        fmt.text(data[2], '\n'),
        fmt.text(data[3], '\n'),
        sep='\n',
    )
    return text
async def show_dynamic_formatting(message: types.Message):
    print("OK")
    await message.answer(fmt.text(fmt.text(fmt.hunderline("Яблоки"),
                                           ", вес 1 кг."),
                                  fmt.text("Старая цена:",
                                           fmt.hstrikethrough(50), "рублей"),
                                  fmt.text("Новая цена:", fmt.hbold(25),
                                           "рублей"),
                                  sep="\n"),
                         parse_mode="HTML")
Exemple #7
0
def create_answer(regatta: Event):
    start = regatta.RegattaStartDate
    end = regatta.RegattaEndDate
    date = f'{start.day}.{start.month}.{start.year}-{end.day}.{end.month}.{end.year}'
    text = fmt.text(
        fmt.text(fmt.hbold(regatta.YachtClass)),
        fmt.text(fmt.hunderline(regatta.RegattaName)),
        fmt.text(date, '\n'),
        fmt.text(regatta.RegattaLocation, '\n'),
        sep='\n',
    )
    return [
        regatta.YachtClass, regatta.RegattaName, date, regatta.RegattaLocation
    ]
Exemple #8
0
async def text_message(msg: types.Message):
    if msg.text and not msg.text.startswith("/"):
        if msg.text.lower() == "привет":
            await bot.send_message(msg.from_user.id, "Привет!")
        elif msg.text.lower() == "как дела?":
            await bot.send_message(msg.from_user.id, "Хорошо! А у тебя как?")
        elif msg.text.lower() == "как тебя зовут?" or msg.text.lower(
        ) == "как тебя зовут":
            await bot.send_message(msg.from_user.id, "quazun")
        elif msg.text.lower() == "фото":
            await bot.send_photo(msg.from_user.id, photo)
        elif msg.text.lower() == "текст":
            await msg.answer("обычный, *жирный* , _курсив_ , `ошибка`",
                             parse_mode="Markdown")
        elif msg.text.lower() == "эмодзи":
            await msg.reply(emojize(":fire:") + emojize(":ghost:"))
        elif msg.text.lower() == "кто твой папочка" or msg.text.lower(
        ) == "кто твой папочка?":
            button = types.InlineKeyboardButton(
                text="Папочка всех ботов", url="tg://resolve?domain=quazun")
            keyboard = types.InlineKeyboardMarkup()
            keyboard.add(button)
            await msg.answer("Мой батька:", reply_markup=keyboard)
        elif msg.text.lower() == "стикер":
            await bot.send_sticker(
                msg.from_user.id,
                "CAACAgQAAxkBAAIBL2BXOUXucU8oG9GXxB28tyd5TospAAKFAwACyt9oBeyJQn52NhMoHgQ"
            )
        elif msg.text.lower() == "текст2":
            await msg.answer(fmt.text(fmt.text(fmt.hunderline("подчеркнутый")),
                                      fmt.text(
                                          fmt.hstrikethrough("зачеркнутый")),
                                      sep="\n"),
                             parse_mode="HTML")
        else:
            await bot.send_message(
                msg.from_user.id,
                msg.from_user.first_name + ", я тебя непонял")
    else:
        await bot.send_message(msg.from_user.id,
                               "`У меня нет такой команды`",
                               parse_mode="Markdown")
Exemple #9
0
async def process_description(message: Message, state: FSMContext):
    description = message.text
    async with state.proxy() as data:
        data['description'] = description

    db = SessionLocal()
    tuning = create_tuning(db, message, data)
    db.close()
    await message.answer(fmt.text(
        fmt.text(fmt.hunderline("Фирма лодки:"), data['boat']),
        fmt.text(fmt.hunderline("Фирма паруса:"), data['sail_firm']),
        fmt.text(fmt.hunderline("Модель паруса:"), data['sail_model']),
        fmt.text(fmt.hunderline("Место:"), data['place']),
        fmt.text(fmt.hunderline("Ветер:"), data['wind'], 'kt'),
        fmt.text(fmt.hunderline("Порывы:"), data['gusts'], 'kt'),
        fmt.text(fmt.hunderline("Высота волн:"), data['wave_height'], 'm'),
        fmt.text(fmt.hunderline("Длина волн:"), data['wave_length']),
        fmt.text(fmt.hunderline("Вес экипажа:"), data['crew_weight'], 'kg'),
        fmt.text(fmt.hunderline("Завал:"), data['mast_rake'], 'm'),
        fmt.text(fmt.hunderline("Пребенд:"), data['prebend'], 'mm'),
        fmt.text(fmt.hunderline("Натяжение на штаге:"), data['tension']),
        fmt.text(fmt.hunderline("Дырка степса:"), data['mast_step']),
        fmt.text(fmt.hunderline("Упор:"), data['chocks']),
        fmt.text(fmt.hunderline("Длина краспиц:"), data['spreraders_leng'],
                 'mm'),
        fmt.text(fmt.hunderline("Качество завала:"), data['quality']),
        fmt.text(fmt.hunderline("Описание:"), data['description']),
        sep="\n"),
                         parse_mode="HTML",
                         reply_markup=tuning_inline_kb(tuning.id))
    await message.answer(
        'Настройка записана. Просмотр, изменение и удаление настройки выполняется в команде /show.'
        'Для продолжения работы с ботом введите /help.')
    await state.finish()
Exemple #10
0
from aiogram import types
from loader import dp

from aiogram.utils.markdown import hbold, hcode, hitalic, hunderline, hlink, hstrikethrough
from aiogram.dispatcher.filters import Command

html_text = "\n".join([
    "Hello, " + hbold("my friend"),
    hitalic("What is your favorite color?"), ""
    "Don't choose this " + hstrikethrough("ABC"),
    "Buy water " + hlink("here", "https://www.apple.com/ru/"),
    hunderline("Attention"), "",
    hcode("example")
])

html_text += hcode(html_text)


@dp.message_handler(Command("html"))
async def show_html(message: types.Message):
    await message.answer(html_text, parse_mode=types.ParseMode.HTML)
async def process_tuning(message: Message, state: FSMContext):
    async with state.proxy() as data:
        data['model'] = message.text

        markup = ReplyKeyboardRemove()

        await message.answer(fmt.text(fmt.text(fmt.hunderline("Sail: "),
                                               data['sail']),
                                      fmt.text(fmt.hunderline("Sail model:"),
                                               data['model']),
                                      sep="\n"),
                             reply_markup=markup,
                             parse_mode="HTML")

    location = data['location']
    latitude = location['latitude']
    longitude = location['longitude']
    position = str(latitude) + ',' + str(longitude)
    forecast = await weather.current(position)
    text = current_weather_format(forecast)
    await message.reply(text=text[0], reply=False)
    await message.reply(text=text[1], reply=False)
    cur = forecast['current']
    wind_kt = cur['wind_kph'] * 0.54
    gusts_kt = cur['gust_kph'] * 0.54
    avg_wind = round((wind_kt + gusts_kt) / 2, 1)
    tuning = choice_tuning(data['sail'], data['model'], avg_wind)
    user = message['from']
    logger.write(
        '\n' + 'TUNING' + '\n' + user.first_name + ' ' + user.last_name +
        '\n' + text[0] + '\n', 'debug')
    # print(message, data['sail'], location, text[0])
    await message.answer(fmt.text(
        fmt.text(fmt.hunderline("Фирма:"), tuning['Фирма']),
        fmt.text(fmt.hunderline("Модель паруса:"), tuning["Модель паруса"]),
        fmt.text(fmt.hunderline("Ветер:"), tuning["Ветер"]),
        fmt.text(fmt.hunderline("Ветер завала:"), tuning["Ветер завала"]),
        fmt.text(fmt.hunderline("Завал:"), tuning["Завал"]),
        fmt.text(fmt.hunderline("Пребенд:"), tuning["Пребенд"]),
        fmt.text(fmt.hunderline("Натяжение на штаге:"),
                 tuning["Натяжение на штаге"]),
        fmt.text(fmt.hunderline("Дырка в степсе:"), tuning["Дырка в степсе"]),
        fmt.text(fmt.hunderline("Упор:"), tuning["Упор"]),
        fmt.text(fmt.hunderline("Длина краспиц:"), tuning["Длина краспиц"]),
        sep="\n"),
                         reply_markup=markup,
                         parse_mode="HTML")
    # Finish conversation
    await state.finish()
Exemple #12
0
async def summa(message: types.Message, state: FSMContext):
    """Enter summa expense."""
    async with state.proxy() as data:
        condition_user_anton = all([
            message.text == 'Назад',
            data['income_or_expense'] == 'Доход',
            message['from']['id'] == 409501763,
        ])
        condition_user_kristina = all([
            message.text == 'Назад',
            data['income_or_expense'] == 'Доход',
            message['from']['id'] == 333252589,
        ])
        condition_income = all([
            message.text == 'Назад',
            data['income_or_expense'] == 'Расход',
        ])
        if any([
                condition_user_anton,
                condition_user_kristina,
                condition_income,
        ]):
            await BudgetingState.income_and_expense.set()
            await message.answer(
                'Вы хотите записать доход или расход?',
                reply_markup=income_and_expense,
            )
            return

        if message.text in category_income_list:
            await state.update_data(category_income_or_expense=message.text)
            await BudgetingState.summa.set()
            await message.answer(
                'Введите сумму дохода в BYN:',
                reply_markup=types.ReplyKeyboardRemove(),
            )
        elif message.text in category_expense_list:
            await state.update_data(category_income_or_expense=message.text)
            await BudgetingState.summa.set()
            await message.answer(
                'Введите сумму расхода в BYN:',
                reply_markup=types.ReplyKeyboardRemove(),
            )
        else:
            summa_is_number = check_is_digit(message.text.replace(',', '.'))
            if summa_is_number:
                data['amount'] = summa_is_number
                name_for_db = data.get(
                    "name_user",
                    "Аноним",
                )
                income_expense_for_db = data.get(
                    "income_or_expense",
                    "Не понятно что",
                )
                category_for_db = data.get(
                    "category_income_or_expense",
                    "Зарплата.",
                )
                amount_for_db = data.get(
                    "amount",
                    "Сумма не указана",
                )
                await message.answer(markdown.text(
                    markdown.text(markdown.hitalic("Данные записаны!")),
                    markdown.text(
                        "Имя: ",
                        markdown.hunderline(f"{name_for_db}"),
                    ),
                    markdown.text(f"Раздел: {income_expense_for_db}"),
                    markdown.text(f"Категория: {category_for_db}"),
                    markdown.text(
                        "Сумма: ",
                        markdown.hbold(f'{amount_for_db}'),
                        "BYN",
                    ),
                    sep="\n",
                ),
                                     parse_mode="HTML")
                write_entry(
                    name_for_db,
                    income_expense_for_db,
                    category_for_db,
                    amount_for_db,
                )
            else:
                await message.answer('Некорретный формат ввода суммы, '
                                     'попробуйте снова!. Пример: 25.37')
                return
            await state.finish()