Esempio n. 1
0
async def YesShowRating(message: types.message, state: FSMContext):
    await message.answer(text=hitalic("Спасибо за прохождение викторины"),
                         reply_markup=ReplyKeyboardRemove())
    await state.finish()
from aiogram.utils.markdown import hitalic, hbold, text
from aiogram.utils.emoji import emojize

SELECTING_ACTIVITY = emojize(
    'Выбери занятие, которое хочешь начать :arrow_down::arrow_down::arrow_down:'
)

SELECTING_SUBACTIVITY = emojize(
    'Выбери подзанятие, которое хочешь начать :arrow_down::arrow_down::arrow_down:'
)

STARTED_ACTIVITY = text(emojize(':rocket: Ты начал(-a) занятие "'),
                        hitalic('{activity_type_name}'),
                        '".',
                        sep="")

STARTED_SUBACTIVITY = text(text(emojize(':rocket: Ты начал(-a) занятие'),
                                hitalic('{activity_type_name}')),
                           text(emojize(":open_file_folder: Подзанятие:"),
                                hitalic('{subactivity_name}')),
                           sep="\n")

STOPPED_ACTIVITY = text(
    emojize(':white_check_mark: Занятие завершено ({activity_type_name})'),
    "",
    emojize(
        ':stopwatch: Продолжительность: {hours} часов {minutes} минут {seconds} секунд'
    ),
    emojize(
        '🧮 Всего за сегодня: {total_hours} часов {total_minutes} минут {total_seconds} секунд'
    ),
Esempio n. 3
0
async def cmd_lang(message: types.Message, locale):
    await message.reply(_('Your current language: {}').format(hitalic(locale)))
from aiogram import types
from aiogram.dispatcher.filters import Command

from loader import dp, bot
from aiogram.utils.markdown import hbold, hcode, hitalic, hunderline, hstrikethrough, hlink

text = "\n".join([
    "Привет" + hbold(" пользователь!"),
    "Здесь мы тестируем форматирование" + " " + hitalic("текста c HTML"),
    "Уверен ты работал с html" + " " + "(" + hstrikethrough("или нет") + ")",
    "Почитать подробнее можно " +
    hlink("тут", "http://htmlbook.ru/content/formatirovanie-teksta"),
    hcode("While(true)"),
])


@dp.message_handler(Command("html_parse_text"))
async def get_answer_html(message: types.Message):
    await message.answer(text, parse_mode="HTML")
Esempio n. 5
0
async def process_city(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['city'] = str(message.text).capitalize()
        await Profile.next()
        await message.answer(hitalic('Ваш род занятий (специальность, увлечение)?'), parse_mode=ParseMode.HTML)
Esempio n. 6
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)
Esempio n. 7
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['name'] = message.text

    await Profile.next()
    await message.answer(hitalic("Сколько Вам лет?"), parse_mode=ParseMode.HTML)
Esempio n. 8
0
async def process_gender(query: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = query.data
        await Profile.next()
        await query.message.edit_text(hitalic('Ваш город (Кириллицей)'), parse_mode=ParseMode.HTML)
Esempio n. 9
0
async def process_about(message: types.Message, state: FSMContext):
    await state.update_data(about=message.text)
    await Profile.next()
    await message.answer(hitalic('Пришлите своё фото.'), parse_mode=ParseMode.HTML,
                         reply_markup=types.ReplyKeyboardRemove())
Esempio n. 10
0
async def process_occupation(message: types.Message, state: FSMContext):
    await state.update_data(occupation=message.text)
    await Profile.next()
    await message.answer(hitalic('Опишите себя одним предложением.'), parse_mode=ParseMode.HTML)
Esempio n. 11
0
async def btn_vote(c: types.CallbackQuery, user: dict, chat: dict,
                   callback_data: dict):
    voteban = await get_voteban(int(callback_data['chat_id']),
                                int(callback_data['user_id']))
    try:
        user_request = await bot.get_chat_member(chat['id'], c.from_user.id)
    except:
        return
    if user_request.is_admin() or user.get('status', 0) >= 3:
        if voteban['active']:
            vote_user = await db.users.find_one(
                {'id': int(callback_data['user_id'])})
            vote_user.update({'spamer': 1.0})
            usr = {'$set': vote_user}
            await db.users.find_one_and_update(
                {'_id': vote_user['id']},
                usr,
                upsert=True,
                return_document=ReturnDocument.AFTER)
            await update_voteban(
                chat['id'], vote_user['id'],
                {'$set': {
                    'active': False,
                    'confirmed': True
                }})
            try:
                await bot.kick_chat_member(int(callback_data['chat_id']),
                                           int(callback_data['user_id']))
            except:
                await c.answer(
                    text='Возникла ошибка при попытке забанить пользователя.',
                    show_alert=True)
                return
            text = 'Воутбан завершён, пользователь был забанен.'
            await c.message.edit_text(text=c.message.html_text + '\n\n' +
                                      hitalic(text))
            await c.answer(text='Пользователь был забанен!')
            await add_log(chat['id'],
                          vote_user['id'],
                          LogEvents.BAN,
                          by=c.from_user.id)
            await log(event=LogEvents.BAN,
                      chat=chat,
                      user=vote_user,
                      message_id=c.message.message_id,
                      admin=user)
            await mp.track(c.from_user.id, StatsEvents.VOTEBAN_CONFIRM, c)
        else:
            if voteban['confirmed']:
                text = 'Воутбан завершён, пользователь был забанен.'
            else:
                text = 'Воутбан завершён, пользователь не был забанен.'

            await c.answer(text=text, show_alert=True)
            await c.message.edit_text(text=c.message.html_text + '\n\n' +
                                      hitalic(text))
    else:
        if voteban['active']:
            user_voted = bool([
                vote for vote in voteban['votes']
                if vote['user_id'] == user['id']
            ])

            if user_voted:
                command = '$pull'
            else:
                command = '$push'

            u = {command: {'votes': {'user_id': user['id']}}}

            voteban = await update_voteban(voteban['chat_id'],
                                           voteban['user_id'], u)
            kb = render_voteban_kb(voteban)

            try:
                await bot.edit_message_reply_markup(c.message.chat.id,
                                                    c.message.message_id,
                                                    reply_markup=kb)
            except exceptions.MessageNotModified:
                pass
            if user_voted:
                answer_text = 'Голос убран'
                await mp.track(c.from_user.id, StatsEvents.VOTEBAN_UNVOTE, c)
            else:
                answer_text = 'Вы проголосовали за бан'
                await mp.track(c.from_user.id, StatsEvents.VOTEBAN_VOTE, c)
            await c.answer(text=answer_text)
        else:
            if voteban['confirmed']:
                text = 'Воутбан завершён, пользователь был забанен.'
            else:
                text = 'Воутбан завершён, пользователь не был забанен.'

            await c.answer(text=text, show_alert=True)
            await c.message.edit_text(text=c.message.html_text + '\n\n' +
                                      hitalic(text))
Esempio n. 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()
Esempio n. 13
0
from aiogram.utils.markdown import (
    hbold,
    hcode,
    hitalic,
    hunderline,
    hstrikethrough,
    hlink,
    hpre,
)


html_text = "\n".join(
    [
        "Привет, " + hbold("Сирежа"),
        "Как говорится:",
        hitalic("Волков боятся - в лес не ходить!"),
        "",
        "но мы не боимся дать отпор! " + hstrikethrough("Что тебе нужно?"),
        "Все это чистая хтмлуйня! ",
        "Узнай про себя кое что новое " + hlink("тут", "http://ya.ru"),
        "и нимножко коды: "
        + hpre(
            "from aiogram.dispatcher.filters import Command;from loguru import logger;from src.loader import dp;from aiogram.utils.markdown import hbold, hcode",
            sep=";",
        ),
    ]
)


@dp.message_handler(Command("format"))
async def bot_echo(message: types.Message):