Example #1
0
    def message(self) -> Optional[str]:
        """Returns message about route for sending to user.

        Raises:
            KeyError: if no route selected.

        Returns:
            String message in HTML format or None if have a problem with
            request or parsing.
        """
        if not self.url:
            raise KeyError  # TODO: add message

        timestamp = time.time()
        maps = yandex.YandexMaps(self.url)

        try:
            weather = yandex.YandexWeather(maps.coords)

            # add timestamp to avoid image caching
            map_url = hide_link(f'{maps.map}&{timestamp}')

            return (f'{map_url}'
                    f'Маршрут <b>{self.name}</b> займет <b>{maps.time}</b> '
                    f'<a href="{maps.url}">(открыть)</a>. '
                    f'За окном <b>{weather.temp}</b> {weather.fact} '
                    f'<a href="{maps.url}">(подробнее)</a>.')
        except (NoMapContent, NoWeatherContent):
            return None
Example #2
0
async def send_content(bot: Bot, **kwargs) -> web.Response:
    def can_text_be_caption(text):
        return text is None or len(text) < CAPTION_MAX_SIZE

    kb = get_inline_kb(kwargs['button_text'], kwargs['button_url'])
    if kwargs['photo_url'] is not None and can_text_be_caption(kwargs['text']):
        logger.debug(kwargs['photo_url'])
        await bot.send_photo(config.TARGET_CHAT_ID,
                             photo=kwargs['photo_url'],
                             caption=kwargs['text'],
                             parse_mode=kwargs['parse_mode'],
                             reply_markup=kb)
    elif kwargs['text'] is not None and kwargs['photo_url'] is not None:
        await bot.send_message(config.TARGET_CHAT_ID,
                               text=kwargs['text'] +
                               hide_link(kwargs['photo_url']),
                               parse_mode=types.ParseMode.HTML,
                               reply_markup=kb)
    elif kwargs['text'] is not None:
        await bot.send_message(config.TARGET_CHAT_ID,
                               text=kwargs['text'],
                               parse_mode=kwargs['parse_mode'],
                               reply_markup=kb)
    else:
        return web.Response(text="Unexpected error", status=500)
    return web.Response(text='ok')
Example #3
0
async def get_mentions_admins(chat: types.Chat):
    admins = await chat.get_administrators()
    admins_mention = ""
    for admin in admins:
        if admin.user.is_bot:
            continue
        if need_notify_admin(admin):
            admins_mention += hide_link(admin.user.url)
    return admins_mention
async def add_to_schedule_pt2(message: types.Message, state: FSMContext):
    data = await state.get_data()
    text = '<b>' + data['name'] + '</b>\n' \
           + hide_link(data['link']) + data['hyperlinks'] + '\n' \
           + '\n' + data['text']
    try:
        await pp.add_to_schedule(job_name=data['name'],
                                 timer=message.text,
                                 mes_text=text)
        await state.set_state('States:menu')
        await message.answer('Пост добавлен в расписание',
                             reply_markup=kb.start)
        await state.reset_data()
        tgh.delete_media()
    except ValueError:
        await message.answer('Введена неверная дата, попробуйте еще:')
Example #5
0
async def media_add(message: types.Message, state: FSMContext):
    photo_msg = message.photo[-1]
    photo = await photo_link(photo=photo_msg)
    data = await state.get_data()
    text = hide_link(photo) + f'{data.get("text")}'
    if data.get("ib") is None:
        murkup = await r_i_buttons(type="text", doc_type=False)
        await message.answer(text=text, reply_markup=murkup)
    else:
        murkup = await splited(text=data.get("ib"), type='text', doc_status=False)
        await message.answer(text, reply_markup=murkup)
    await state.update_data({
        "text": text,
        "am": photo_msg
    })
    await state.reset_state(with_data=False)
Example #6
0
async def pre_show(message: Message, state: FSMContext):
    data = await state.get_data()
    if data.get('name') is None:
        await message.answer('Вы не добавили название, введите его:')
        await state.set_state('States:add_name')
        return

    elif data.get('text') is None:
        await message.answer('Вы не добавили описание, введите его:')
        await state.set_state('States:add_text')
        return

    elif data.get('price') is None:
        await message.answer('Вы не добавили цену, введите её:')
        await state.set_state('States:add_price')
        return

    elif data.get('link') is None:
        await message.answer('Загружаю фото..')
        link = create_site(name=data['name'], id_u=str(message.from_user.id))
        if link == -1:
            await message.answer('Вы не добавили фото')
            await message.answer('Добавте их прямо сейчас и нажмите принять:',
                                 reply_markup=photo)
            await state.set_state('States:add_photo')
            return
        await state.update_data(link=link)
    else:
        link = data['link']
    if data.get('sale') is None:
        product_price = data['price']
    else:
        product_price = data['sale'] + '  <s>' + data['price'] + '</s>'
    text = '<b>' + data['name'] + '</b>' + '\n' \
           + hide_link(link) + product_price + '\n' \
           + '\n' + data['text'] + '\n'
    if message.text == 'Предпросмотр':
        await message.answer('Предпросмотр товара:')
        await message.answer(text=text,
                             parse_mode='HTML',
                             reply_markup=add_product)
    else:
        await message.answer(
            'Выберите категорию в которую необходимо добавить товар',
            reply_markup=type_object)
        await state.set_state('States:set_category')
async def add_item(message: types.Message, state: FSMContext):
    try:
        name, price, description, pic = message.text.split('\n')
    except ValueError:
        await message.answer('Текст заполнен не правильно')
    else:
        await message.answer('%s'
                             '<b>Товар:</b> %s\n'
                             '<b>Цена:</b> %s₽\n'
                             '<b>Описание:</b>\n%s\n\n'
                             '<i>Дата выставления товара: сейчас</i>' % \
                             (hide_link(pic), name, price, description))
        await state.update_data(name=name,
                                price=price,
                                description=description,
                                pic=pic)
        await message.answer('Вы уверены что хотите добавить этот товар?',
                             reply_markup=button_confirm_add)
Example #8
0
async def show_message(message: types.Message, state: FSMContext):
    data = await state.get_data()
    if data.get('name') is None:
        await message.answer('Вы не добавили название, введите его:')
        await state.set_state('States:add_name')
        return
    elif data.get('text') is None:
        await message.answer('Вы не добавили текст, введите его:')
        await state.set_state('States:add_text')
        return
    elif data.get('hyperlinks') is None:
        await message.answer('Вы не добавили гиперссылки, введите их:')
        await state.set_state('States:add_hyperlinks')
        return
    elif data.get('link') is None:
        await message.answer('Загружаю фото..')
        if data.get('tgh_text') is not None:
            link = tgh.create_site(name=data['name'], text=data['tgh_text'])
        else:
            link = tgh.create_site(name=data['name'])
        if link == -1:
            await message.answer('Вы не добавили фото для Telegraph')
            await message.answer('Добавте их прямо сейчас и нажмите принять:',
                                 reply_markup=kb.next_state)
            await state.set_state('States:add_photo')
            return
        await state.update_data(link=link)
    else:
        link = data['link']

    await message.answer('Отправляю..', reply_markup=kb.start)
    print('отправляем сообщение в канал:')
    text = '<b>' + data['name'] + '</b>' + '\n' \
           + hide_link(link) + data['hyperlinks'] + '\n' \
           + '\n' + data['text']

    await state.update_data(link=link)
    await bot.send_message(
        chat_id=ch_id,
        text=text,
        parse_mode='HTML',
        reply_markup=kb.favourite,
    )
    await state.reset_data()
Example #9
0
async def show_message(message: types.Message, state: FSMContext):
    data = await state.get_data()
    print(data.get('name'))
    if data.get('name') is None:
        await message.answer('Вы не добавили название, введите его:')
        await state.set_state('States:add_name')
        return

    elif data.get('text') is None:
        await message.answer('Вы не добавили текст, введите его:')
        await state.set_state('States:add_text')
        return

    elif data.get('hyperlinks') is None:
        await message.answer('Вы не добавили гиперссылки, введите их:')
        await state.set_state('States:add_hyperlinks')
        return

    elif data.get('link') is None:
        await message.answer('Загружаю фото..')
        if data.get('tgh_text') is not None:
            link = tgh.create_site(name=data['name'], text=data['tgh_text'])
        else:
            link = tgh.create_site(name=data['name'])
        if link == -1:
            await message.answer('Вы не добавили фото для Telegraph')
            await message.answer('Добавте их прямо сейчас и нажмите принять:',
                                 reply_markup=kb.next_state)
            await state.set_state('States:add_photo')
            return
        await state.update_data(link=link)
    else:
        link = data['link']

    text = '<b>' + data['name'] + '</b>' + '\n' \
           + hide_link(link) + data['hyperlinks'] + '\n' \
           + '\n' + data['text']

    await message.answer('Предпросмотр поста:')
    await message.answer(
        text=text,
        parse_mode='HTML',
        reply_markup=kb.done,
    )
Example #10
0
async def watch_get_six(m: types.Message, user: dict, chat: dict):
    pic_url = 'https://user-images.githubusercontent.com/24507532/97610210-a0decc00-1a25-11eb-9622-7b1e3536dfc0.png'
    get = await bot.send_message(
        m.chat.id,
        text=hide_link(pic_url) + hbold('🎉 GET /hw/ 6️⃣0️⃣0️⃣0️⃣0️⃣0️⃣0️⃣') +
        '\n\n' +
        "Забавный факт - если поделить гет на 100, то получится цена RTX 3070!"
    )
    try:
        await bot.pin_chat_message(m.chat.id,
                                   get.message_id,
                                   disable_notification=False)
    except:
        pass

    await bot.send_message(
        94026383,
        text='GET @{} {}'.format(
            m.chat.username,
            hlink(str(get.message_id),
                  'https://t.me/{}/{}'.format(m.chat.username,
                                              get.message_id))))
    SkipHandler()
Example #11
0
 async def peer_data_compile(
         self, user: User, login: str,
         is_single: bool) -> Tuple[Union[Peer, None], str]:
     peer = await self._get_peer(user=user, login=login)
     if isinstance(peer, str):
         return None, peer
     courses = '\n'.join([
         f'{hbold(cursus.name, ":", sep="")} {cursus.level}'
         for cursus in peer.cursus_data
     ])
     coalition = ''
     if peer.coalition:
         coalition = f'{hbold(Config.local.coalition.get(user.language), ":", sep="")} {peer.coalition}\n'
     pool = ''
     if peer.pool_month and peer.pool_year:
         months = {
             'january': '01',
             'february': '02',
             'march': '03',
             'april': '04',
             'may': '05',
             'june': '06',
             'july': '07',
             'august': '08',
             'september': '09',
             'october': '10',
             'november': '11',
             'december': '12'
         }
         pool = f'{hbold(Config.local.piscine.get(user.language), ":", sep="")} ' \
                f'{months[peer.pool_month]}.{peer.pool_year}\n'
     peer_location = ''
     if peer.is_staff:
         peer_location = Config.local.ask_adm.get(user.language)
     elif peer.location and not peer.is_staff:
         peer_location = hcode(peer.location)
     elif not peer.location:
         peer_location = self._last_seen_time_compile(
             user=user,
             last_seen_time=peer.last_seen_time,
             last_location=peer.last_location)
     full_name = hbold(peer.full_name)
     if is_single:
         full_name = hlink(title=peer.full_name, url=peer.link)
     username = ''
     if peer.username:
         username = f'{hbold("Telegram:")} @{peer.username}\n'
     title = f'{peer.status}{full_name} aka {hcode(peer.login)}\n'
     dignity = f'{hitalic(peer.dignity.replace("%login", peer.login))}\n' if peer.dignity else ''
     campus = f'{hbold(Config.local.campus.get(user.language), ":", sep="")} {peer.campus}\n'
     location = f'{hbold(Config.local.location.get(user.language), ":", sep="")} {peer_location}'
     text = f'{title}' \
            f'{dignity}' \
            f'{username}' \
            f'{pool}' \
            f'{coalition}' \
            f'{courses}\n' \
            f'{campus}' \
            f'{location}'
     text = hide_link(url=peer.avatar) + text
     return peer, text