Exemplo n.º 1
0
 async def handler(self, event: events.ChatAction,
                   request_context: RequestContext):
     request_context.statbox(action='show', mode='help')
     if event.is_group or event.is_channel:
         await event.reply(t('HELP_FOR_GROUPS',
                             language=request_context.chat.language),
                           buttons=Button.clear())
     else:
         await event.reply(t('HELP',
                             language=request_context.chat.language),
                           buttons=Button.clear())
Exemplo n.º 2
0
async def handler(event):
    if event.data == b'polit':
        await event.answer('Успешно!')
        u_choice['politics'] = 1
    if event.data == b'tech':
        await event.answer('Хороший выбор!')
        u_choice['tech'] = 1
    if event.data == b'business':
        await event.answer('Вау!')
        u_choice['business'] = 1
    if event.data == b'ent':
        await event.answer('Успешно!')
        u_choice['entertainment'] = 1
    if event.data == b'sport':
        await event.answer('Успешно!')
        u_choice['sport'] = 1
    if event.data == b'close':
        await event.answer('Успешно')
        sender = await event.get_sender()
        database.create_new_user(sender.id, u_choice=u_choice)
        await bot.send_message(sender,
                               'Категории выбраны!',
                               buttons=Button.clear())

    if event.data == b'yes':
        sender = await event.get_sender()
        database.delete_user(sender.id)
        await bot.send_message(sender, "Выбери категории:", buttons=buttons)
    if event.data == b'no':
        sender = await event.get_sender()
        await bot.send_message(sender, "Ок")
Exemplo n.º 3
0
async def set_lang_handler(event):
    """ Set the language based on the user selection"""
    lang = event.message.message.split(' ')[0]
    DATABASE.set_locale(event.chat_id, lang)
    locale = DATABASE.get_locale(event.chat_id)
    message = await set_locale_message(lang, locale)
    await event.reply(message, buttons=Button.clear())
    raise events.StopPropagation
Exemplo n.º 4
0
    async def on_start(self, event: NewMessage.Event):
        chat_id = event.chat_id
        with use_session(self.session_cls) as db_session:
            exists = db_session.query(
                db_session.query(User).filter(
                    User.chat_id == chat_id).exists()).scalar()
            if not exists:
                db_session.add(User(chat_id))
                self.logger.debug(
                    'New user ({}) was inserted into db'.format(chat_id))
                db_session.commit()

        await event.respond('Welcome to Youtube Downloader Bot!',
                            buttons=Button.clear())
Exemplo n.º 5
0
    async def get_paginate_messages(self):
        amount = settings.pagination
        loading_msg = ''

        if len(self.channels) > 0:
            loading_msg = await bot.send_message(self.user_id,
                                                 'Ищем вакансии...',
                                                 buttons=Button.clear())
            self.add_message(loading_msg.id)
            await self.delete_last_msg()

            loading_msg = await bot.send_message(self.user_id,
                                                 'Ищем вакансии...')
            self.add_message(loading_msg.id)
        else:
            return

        for (index, channel) in enumerate(self.channels):
            try:
                self.parsed_channels_amount = self.parsed_channels_amount + 1
                self.parsed_channels.append(channel)
                channel_messages = await self.parser.parse_channel(channel)
                if len(channel_messages):
                    self.messages_was_found = True

                self.messages.extend(channel_messages)
                percent = round(self.parsed_channels_amount /
                                len(settings.channels) * 100)
                await bot.edit_message(self.user_id, loading_msg,
                                       f'Ищем вакансии... {percent}%')
                if len(self.messages) > amount:
                    break
            except Exception:
                print('Ошибка:\n', traceback.format_exc())
                continue

        messages_len = len(self.messages)
        if messages_len == 0 and not self.messages_was_found:
            finish_search_text = 'Поиск завершен. По выбранным критериям вакансий не найдено'
        else:
            finish_search_text = 'Поиск завершен'

        complete_msg = await bot.send_message(
            self.user_id,
            finish_search_text,
            buttons=get_return_keyboard(messages_len))
        self.add_message(complete_msg.id)
        self.remove_parsed_channels()
Exemplo n.º 6
0
async def start(event):
    try:
        user_info = await bot.get_entity(event.original_update.message.peer_id)
        user = users.get_user(user_info.id)
        msg = await event.respond('Возвращаемся в начало',
                                  buttons=Button.clear())
        user.add_message(msg)
        user.add_user_message(event.message.id)
        await user.delete_all_messages()
        user_info = await bot.get_entity(event.original_update.message.peer_id)
        user = User(user_info.id, user_info.username, '', '')
        users.add_user(user)
        msg = await event.respond(welcome_text, buttons=welcome_keyboard)
        user.add_message(msg)
    except Exception:
        print('Ошибка:\n', traceback.format_exc())
Exemplo n.º 7
0
    async def on_video_format_picked(self, event: CallbackQuery.Event):
        splitted_data = event.data.decode().split('_')
        download_id = splitted_data[1]
        format_id = '_'.join(splitted_data[2:])
        self.logger.debug('Video format id was picked: {}'.format(format_id))

        with use_session(self.session_cls) as db_session:
            download = db_session.query(Download).filter(
                Download.chat_id == event.chat_id).one_or_none()

        if download is None or download.download_id != download_id:
            self.logger.error('Download object was not exists. Skip.')
            await event.delete()
            return

        await event.delete()
        self.logger.debug('Start downloading {}'.format(download.url))
        target_message = await event.respond(
            '<b>{}</b>\nStart downloading. Please wait'.format(download.title),
            buttons=Button.clear())

        video_path = await self.youtube_manager.download_video(
            download.url, format_id, chat_id=event.chat_id)
        await event.client.delete_messages(event.chat_id, target_message)

        if video_path is None:
            self.logger.error('Cannot download. Error occurred')
            await event.respond(
                '<b>{}</b>\nCannot download. Something wrong'.format(
                    download.title))
            return

        self.logger.debug('Successfully downloaded. Start sending')
        target_message = await event.respond(
            '<b>{}</b>\nSuccessfully downloaded. Start sending'.format(
                download.title))
        video_message = await event.client.send_file(event.chat_id, video_path)
        await event.client.delete_messages(event.chat_id, target_message)

        if Path(video_path).exists():
            Path(video_path).unlink()

        self.logger.debug('Successfully sent')
        await event.respond('<b>{}</b>\n0:00'.format(download.title),
                            reply_to=video_message)
Exemplo n.º 8
0
async def request(event):
    """request a firmware"""
    params = event.data.decode("utf-8")
    model = params.split('_')[1]
    region = params.split('_')[2]
    entity = await BOT.get_entity(PeerChannel(1348663969))
    message = f"**New Firmware request**!\n\n" \
              f"**Device**: {SAM_FIRM.get_device_name(model)}\n" \
              f"**Model: {model}\n" \
              f"**Region: {region}\n\n" \
              f"`/samup {model} {region}`"
    await BOT.send_message(entity, message)
    try:
        await event.edit(
            "**Your request has been submitted.**\n"
            "Join @samsungfws to get notified when your request is processed.",
            buttons=Button.clear())
    except MessageNotModifiedError:
        pass
Exemplo n.º 9
0
    async def on_url(self, event: NewMessage.Event):
        if self.youtube_manager.is_downloading(event.chat_id):
            self.logger.debug('Already downloading for {}'.format(
                event.chat_id))
            await event.respond('Something already downloading. Please wait')
            return

        url: str = event.raw_text
        self.logger.debug('Url received: {}'.format(url))
        target_message = await event.respond('Checking...')
        info = await self.youtube_manager.get_info(url)
        if info is None:
            self.logger.debug('Video was not found')
            await event.respond('Video was not found', buttons=Button.clear())
            return

        download_id = random_string(16)
        with use_session(self.session_cls, autocommit=True) as db_session:
            download = Download(event.chat_id, download_id, url, info['title'],
                                info['duration'], json.dumps(info['formats']))
            db_session.insert_or_replace(download)

        self.logger.debug('Download object was created for {}'.format(
            info['title'][:30]))
        await event.client.delete_messages(
            event.chat_id, [event.message.id, target_message.id])

        await event.respond(
            '<b>{}</b>\nChoose download type:'.format(info['title']),
            buttons=[
                Button.inline(
                    'Video',
                    data=f'type_{download_id}_{DownloadType.VIDEO.name}'),
                Button.inline(
                    'Audio (default)',
                    data=f'type_{download_id}_{DownloadType.AUDIO_DEFAULT.name}'
                ),
                Button.inline(
                    'Audio (custom)',
                    data=f'type_{download_id}_{DownloadType.AUDIO_CUSTOM.name}'
                )
            ])
Exemplo n.º 10
0
 async def close(event):
     await event.edit("Button closed!", buttons=Button.clear())
Exemplo n.º 11
0
 async def close(event):
     await event.edit(
         "Menu di tutup!\nUntuk Melihat Menu, Silahkan Ketik `.rhelp`",
         buttons=Button.clear())
Exemplo n.º 12
0
class buttons:
    main_menu = [[Button.text("🍕 Піца", resize=True, single_use=True), Button.text("🍕 Піца з половинок")],
                 [Button.text("🍕 Конструктор піци"), Button.text("🍗 Снеки")],
                 [Button.text("🍲 Соуси"), Button.text("🥤 Напої")],
                 [Button.text("🛒 Перевірити кошик"), Button.text("📋 Оформити замовлення")],
                 [Button.text("📩 Контактна інформація")]]

    @staticmethod
    def halfs_menu(single_click = False):
        if single_click:
            btn = Button.text(HalfNizhna.name, resize=True, single_use=True)
        else:
            btn = Button.text(HalfNizhna.name, resize=True, selective=True)
        return [[ btn,
                   Button.text(HalfApetitna.name),
                   Button.text(HalfSitna.name)],
               [Button.text(HalfSalyami.name),
                   Button.text(HalfSokovita.name),
                   Button.text(HalfFourChese.name)],
               [Button.text(HalfPikantna.name),
                   Button.text(HalfFourMeat.name),
                   Button.text(HalfNapoliPikantna.name)],
               [Button.text(HalfPekelna.name),
                   Button.text("↪ Меню")]]

    @staticmethod
    def products_menu(previous, chat_id, next, curr_index, product_type = None):
        return [[Button.inline("⬅ Попередня", f"{product_type}|previous|{previous}".encode("utf-8")),
                Button.inline("↪ Меню", "back to main".encode("utf-8")),
                Button.inline("➡ Наступна", f"{product_type}|next|{next}".encode("utf-8"))],
                [Button.inline("🛒 В кошик", f"{product_type}|choice|{chat_id}|{curr_index}".encode("utf-8"))]]

    @staticmethod
    def pizza_from_scratch(previous, chat_id, next, curr_index, message_id = None):
        return [[Button.inline("⬅", f"i_prev|{message_id}|{previous}".encode("utf-8")),
                 Button.inline("↪ Меню", f"back to main|{message_id}".encode("utf-8")),
                 Button.inline("➡", f"i_next|{message_id}|{next}".encode("utf-8"))],
                [Button.inline("➕ Додати до піци", f"ingredient|{message_id}|{chat_id}|{curr_index}".encode("utf-8"))],
                [Button.inline("✅ Додати в кошик", f"pizza is ready|{message_id}|{chat_id}")]]

    address_buttons = [Button.text("Ввести адресу", resize=True, single_use=True),
                       Button.request_location("Відправити геоданні")]

    contacts_button = [Button.text("Ввести номер телефону", resize=True, single_use=True),
                       Button.request_phone("Використати телефон аккаунтa")]

    payment_button = [Button.text("💵 Оплата готівкою", resize=True, single_use=True),
                      Button.text("💳 Оплата на картку")]

    pizza_basement = [Button.text("Томатний соус", resize=True, single_use=True),
                      Button.text("Вершковий соус")]

    pizza_basement_cheese = [Button.text("сир Моцарелла", resize=True, single_use=True),
                            Button.text("сир Сулугуні")]


    wait_for_input = Button.force_reply()

    clear = Button.clear()

    @staticmethod
    def accept_order(chat_id, first_name):
        return Button.inline("✅ Підтвердити", f"order confirmed|{chat_id}|{first_name}")