Example #1
0
    def test_from_input_input_media(self):
        input_media_no_thumb = InputMediaPhoto(
            media=data_file("telegram.jpg").read_bytes())
        input_media_thumb = InputMediaVideo(
            media=data_file("telegram.mp4").read_bytes(),
            thumb=data_file("telegram.jpg").read_bytes(),
        )

        request_parameter = RequestParameter.from_input(
            "key", input_media_no_thumb)
        expected_no_thumb = input_media_no_thumb.to_dict()
        expected_no_thumb.update(
            {"media": input_media_no_thumb.media.attach_uri})
        assert request_parameter.value == expected_no_thumb
        assert request_parameter.input_files == [input_media_no_thumb.media]

        request_parameter = RequestParameter.from_input(
            "key", input_media_thumb)
        expected_thumb = input_media_thumb.to_dict()
        expected_thumb.update({"media": input_media_thumb.media.attach_uri})
        expected_thumb.update({"thumb": input_media_thumb.thumb.attach_uri})
        assert request_parameter.value == expected_thumb
        assert request_parameter.input_files == [
            input_media_thumb.media, input_media_thumb.thumb
        ]

        request_parameter = RequestParameter.from_input(
            "key", [input_media_thumb, input_media_no_thumb])
        assert request_parameter.value == [expected_thumb, expected_no_thumb]
        assert request_parameter.input_files == [
            input_media_thumb.media,
            input_media_thumb.thumb,
            input_media_no_thumb.media,
        ]
def verify_button_pressed(update, context):
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	query = update.callback_query  # type: Optional[CallbackQuery]
	match = re.match(r"verify_me\((.+?)\)", query.data)
	match = match.group(1).split("|")
	is_ok = match[0]
	user_id = match[1]
	chat_id = match[2]
	message = update.effective_message  # type: Optional[Message]
	print("-> {} was clicked welcome verify button".format(user.id))
	if is_ok == "y":
		if context.bot.getChatMember(chat_id, user_id).status in ('left'):
			query.answer(text=tl(update.effective_message, "Failed: user left chat"))
			return
		try:
			context.bot.restrict_chat_member(chat_id, user_id, permissions=ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True, can_invite_users=True))
			sql.add_to_userlist(chat_id, user_id, True)
			sql.rm_from_timeout(chat_id, user_id)
		except BadRequest as err:
			if not update.effective_chat.get_member(context.bot.id).can_restrict_members:
				query.answer(text=tl(update.effective_message, "Saya tidak dapat membatasi orang disini, tanya admin untuk unmute!"))
			else:
				query.answer(text="Error: " + str(err))
			return
		chat_name = context.bot.get_chat(chat_id).title
		context.bot.edit_message_media(chat.id, message_id=query.message.message_id, media=InputMediaPhoto(media="https://telegra.ph/file/06d2c5ec80af3858c2d4b.jpg", caption=tl(update.effective_message, "*Berhasil!*\n\nKerja bagus manusia, kini Anda dapat chatting di: *{}*").format(chat_name), parse_mode="markdown"))
		query.answer(text=tl(update.effective_message, "Berhasil! Anda dapat chatting di {} sekarang").format(chat_name), show_alert=True)
	else:
		context.bot.edit_message_media(chat.id, message_id=query.message.message_id, media=InputMediaPhoto(media="https://telegra.ph/file/d81cdcbafb240071add84.jpg", caption=tl(update.effective_message, "Maaf robot, kamu telah salah klik tombol verifikasi.\n\nCoba lagi dengan klik tombol verifikasi pada pesan selamat datang."), parse_mode="markdown"))
		query.answer(text=tl(update.effective_message, "Gagal! Kamu telah salah mengklik tombol verifikasi"), show_alert=True)
Example #3
0
def graphs_command(update: Update, context):
	msg = update.message
	chat_id = msg.from_user.id
	date = msg.date
	help_check_user(chat_id, date)
	downloads_graph = create_graph_top_downloaders()
	users_graph = create_graph_users()
	users, nums_downloads = get_data_downloaders()

	caption_text_download_graph = ""
	times = 1

	for user, num_downloads in zip(users, nums_downloads):
		caption_text_download_graph += f"{times} Place: User `{user}` with {num_downloads} downloads\n"
		times += 1

	medias = [
		InputMediaPhoto(
			media = downloads_graph,
			caption = caption_text_download_graph,
			parse_mode = ParseMode.MARKDOWN_V2
		),
		InputMediaPhoto(
			media = users_graph
		)
	]

	bot.send_media_group(
		chat_id = chat_id,
		media = medias
	)
Example #4
0
def sendTranslateReview(msg):
    if not msg.reply_to_message:
        return
    if not msg.reply_to_message.forward_from_chat:
        return
    if msg.reply_to_message.forward_from_chat.id != -1001386450222:
        return
    if msg.from_user.id == 420074357:
        return
    if not msg.text:
        return
    if len(msg.text) < 15:
        return
    cap = getText(
        msg.text, msg.reply_to_message.text or msg.reply_to_message.caption
        or '', msg.from_user.id)
    if msg.reply_to_message.video:
        msg.bot.send_video(target_channel,
                           msg.reply_to_message.video.file_id,
                           caption=cap)
        return
    if msg.reply_to_message.media_group_id:
        media = [
            InputMediaPhoto(msg.reply_to_message.photo[-1].file_id,
                            caption=cap)
        ]
        for m in getMore(msg.reply_to_message):
            media.append(InputMediaPhoto(m.photo[-1].file_id))
        return msg.bot.send_media_group(target_channel, media)
    if msg.reply_to_message.photo:
        msg.bot.send_photo(target_channel,
                           msg.reply_to_message.photo[-1].file_id,
                           caption=cap)
        return
    msg.bot.send_message(target_channel, cap)
Example #5
0
def send_info(update: Update, context: CallbackContext, car: Car):
    if settings.SEND_TYPE == "FILE":
        for chunk in chunks(car.images.all(), 10):
            update.message.reply_media_group([
                InputMediaPhoto(open(image.file.path, 'rb')) for image in chunk
            ])
    else:
        for chunk in chunks(car.images.all(), 10):
            update.message.reply_media_group([
                InputMediaPhoto(settings.WEBSITE_LINK + image.file.url)
                for image in chunk
            ])

    keyboard = InlineKeyboardMarkup(
        [[InlineKeyboardButton("Отправить на почту", callback_data=car.id)],
         [
             InlineKeyboardButton(
                 "Открыть карту",
                 url=f"https://yandex.ru/maps?mode=search&text={car.address}")
         ]])
    update.message.reply_text(settings.MESSAGE_TEMPLATE_BOT.format(
        car.brand, car.model, car.year, car.mileage, car.number, car.vin,
        car.address, car.comments),
                              parse_mode=telegram.ParseMode.HTML,
                              reply_markup=keyboard)
def confirmation_callback(update: Update, context: CallbackContext):
    user_data = context.user_data
    callback_query = update.callback_query

    if callback_query.data == 'cancel':
        # Remove certificate from the location
        os.remove(user_data['certs'][user_data['place']]['cert_path'])

        # Remove QR code from the location
        os.remove(user_data['certs'][user_data['place']]['qr_code_path'])

        # delete user_data dict
        del user_data['certs'][user_data['place']]

        callback_query.message.delete()

        text = "O'rinni tanlang:"
        inline_keyboard = InlineKeyboard(choose_place_keyboard, 'uz').get_keyboard()

        message = callback_query.message.reply_text(text, reply_markup=inline_keyboard)

        state = CHOOSE_PLACE
        user_data['message_id'] = message.message_id

    else:
        callback_query.edit_message_reply_markup()

        data = {
            'cert_url': user_data['certs'][user_data['place']]['cert_url'],
            'cert_qr_code': user_data['certs'][user_data['place']]['qr_code_path'].split('/')[-1],
            'fullname': user_data['fullname'],
            'place': user_data['place']
        }
        insert_data(data, table_name='certificates')

        if len(user_data['certs']) == 3:
            callback_query.answer("Barcha o'rinlar uchun sertifikatlar tasqdiqlandi !")

            callback_query.message.reply_media_group([
                InputMediaPhoto(user_data['certs']['1']['cert_url']),
                InputMediaPhoto(user_data['certs']['2']['cert_url']),
                InputMediaPhoto(user_data['certs']['3']['cert_url'])
            ])

            user_data.clear()

            state = ConversationHandler.END

        else:

            text = "O'rinni tanlang:"
            inline_keyboard = InlineKeyboard(choose_place_keyboard, 'uz').get_keyboard()

            message = callback_query.message.reply_text(text, reply_markup=inline_keyboard)

            state = CHOOSE_PLACE
            user_data['message_id'] = message.message_id

    # logger.info('user_data: %s', user_data)
    return state
Example #7
0
def create_media_group_for_double_faced_cards(card_list):
    media = []
    media_one = InputMediaPhoto(media=card_list[0]['image_uris']['normal'])
    media_two = InputMediaPhoto(media=card_list[1]['image_uris']['normal'])
    media.append(media_one)
    media.append(media_two)
    return media
Example #8
0
def test(url, rotate=False):
    result = web_2_album.get(url)
    suffix = '[source](%s)' % url

    if result.video:
        with open('tmp/video.mp4', 'wb') as f:
            f.write(cached_url.get(result.video, force_cache=True, mode='b'))
        group = [
            InputMediaVideo(open('tmp/video.mp4', 'rb'),
                            caption=cutCaption(result.cap, suffix, 1000),
                            parse_mode='Markdown')
        ]
        return tele.bot.send_media_group(-1001198682178,
                                         group,
                                         timeout=20 * 60)

    imgs = pic_cut.getCutImages(result.imgs, 9)
    if imgs:
        imgs = pic_cut.getCutImages(result.imgs, 9)
        if rotate:
            for img_path in imgs:
                img = Image.open(img_path)
                img = img.rotate(180)
                img.save(img_path)
        group = [InputMediaPhoto(open(imgs[0], 'rb'),
         caption=cutCaption(result.cap, suffix, 1000), parse_mode='Markdown')] + \
         [InputMediaPhoto(open(x, 'rb')) for x in imgs[1:]]
        return tele.bot.send_media_group(-1001198682178,
                                         group,
                                         timeout=20 * 60)

    tele.bot.send_message(-1001198682178,
                          cutCaption(result.cap, suffix, 4000),
                          timeout=20 * 60)
Example #9
0
def send_mars_photos(bot, pictures, chat_id):
    arr = []
    if len(pictures) > 5:
        for i in range(5):
            img = pictures[randint(0, len(pictures) - 1)]
            arr.append(
                InputMediaPhoto(media=img['img_src'],
                                caption='<code>Mars rover: </code><b>{}</b>, '
                                '<code>Earth date: </code><b>{}</b>, '
                                '<code>Sol: </code><b>{}</b>, '
                                '<code>Camera: </code><b>{}</b>'.format(
                                    img['rover']['name'], img['earth_date'],
                                    img['sol'], img['camera']['full_name']),
                                parse_mode=ParseMode.HTML))
    else:
        for img in pictures:
            arr.append(
                InputMediaPhoto(media=img['img_src'],
                                caption='<code>Mars rover: </code><b>{}</b>, '
                                '<code>Earth date: </code><b>{}</b>, '
                                '<code>Sol: </code><b>{}</b>, '
                                '<code>Camera: </code><b>{}</b>'.format(
                                    img['rover']['name'], img['earth_date'],
                                    img['sol'], img['camera']['full_name']),
                                parse_mode=ParseMode.HTML))

    if len(arr) > 0:
        bot.send_media_group(chat_id=chat_id,
                             media=arr,
                             disable_notification=True)
Example #10
0
def send_gallery(update, context):
    list = []

    list.append(InputMediaPhoto(media='https://github.com/gcatanese/TelegramBotDemo/raw/main/files/mintie.jpg', caption='Mint'))
    list.append(InputMediaPhoto(media='https://github.com/gcatanese/TelegramBotDemo/raw/main/files/pinkie.jpg', caption='Pink'))
    list.append(InputMediaPhoto(media='https://github.com/gcatanese/TelegramBotDemo/raw/main/files/orangie.jpg', caption='Orange'))

    context.bot.send_media_group(chat_id=get_chat_id(update, context), media=list)
Example #11
0
def media_group(photo, thumb):  # noqa: F811
    return [
        InputMediaPhoto(photo, caption='*photo* 1', parse_mode='Markdown'),
        InputMediaPhoto(thumb, caption='<b>photo</b> 2', parse_mode='HTML'),
        InputMediaPhoto(
            photo, caption='photo 3', caption_entities=[MessageEntity(MessageEntity.BOLD, 0, 5)]
        ),
    ]
Example #12
0
def verify_button_pressed(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    query = update.callback_query  # type: Optional[CallbackQuery]
    match = re.match(r"verify_me\((.+?)\)", query.data)
    match = match.group(1).split("|")
    is_ok = match[0]
    user_id = match[1]
    chat_id = match[2]
    message = update.effective_message  # type: Optional[Message]
    print("-> {} was clicked welcome verify button".format(user.id))
    if is_ok == "y":
        if context.bot.getChatMember(chat_id, user_id).status in ('left'):
            query.answer(text="Failed: user left chat")
            return
        try:
            context.bot.restrict_chat_member(
                chat_id,
                user_id,
                permissions=ChatPermissions(can_send_messages=True,
                                            can_send_media_messages=True,
                                            can_send_other_messages=True,
                                            can_add_web_page_previews=True))
            sql.add_to_userlist(chat_id, user_id, True)
            sql.rm_from_timeout(chat_id, user_id)
        except BadRequest as err:
            if not update.effective_chat.get_member(
                    context.bot.id).can_restrict_members:
                query.answer(
                    text=
                    "I can't restrict people here, ask admin to unmute you!")
            else:
                query.answer(text="Error: " + str(err))
            return
        chat_name = context.bot.get_chat(chat_id).title
        context.bot.edit_message_media(
            chat.id,
            message_id=query.message.message_id,
            media=InputMediaPhoto(
                media="https://telegra.ph/file/32dbdc63c6957b8345a32.jpg",
                caption=
                "*Success!*\n\nGood work human, you can now chat in: *{}*".
                format(chat_name),
                parse_mode="markdown"))
        query.answer(text="Success! You can chat in {} now".format(chat_name),
                     show_alert=True)
    else:
        context.bot.edit_message_media(
            chat.id,
            message_id=query.message.message_id,
            media=InputMediaPhoto(
                media="https://telegra.ph/file/32dbdc63c6957b8345a32.jpg",
                caption=
                "Sorry robot, you are clicked wrong button.\n\nTry again by click welcome security button.",
                parse_mode="markdown"))
        query.answer(text="Failed! You are clicked wrong button",
                     show_alert=True)
Example #13
0
 async def func():
     return await bot.send_media_group(
         chat_id,
         [
             InputMediaVideo(video_file),
             InputMediaPhoto(photo_file),
             InputMediaPhoto(data_file("telegram.jpg").read_bytes()),
         ],
     )
Example #14
0
def media_group(photo, thumb):  # noqa: F811
    return [
        InputMediaPhoto(photo, caption="*photo* 1", parse_mode="Markdown"),
        InputMediaPhoto(thumb, caption="<b>photo</b> 2", parse_mode="HTML"),
        InputMediaPhoto(
            photo,
            caption="photo 3",
            caption_entities=[MessageEntity(MessageEntity.BOLD, 0, 5)]),
    ]
    def send_mediagroup(self, match):
        with self.telegram_bot_instance.chat_lock:
            media_group = list()
            for number, url in enumerate(match.photos.split('\n\n')):

                media_group.append(
                    InputMediaPhoto(media=url,
                                    caption=match.pretty_conversation))

            try:
                self.telegram_bot_instance.bot.send_media_group(
                    chat_id=self.telegram_bot_instance.chat_id,
                    media=media_group[:10])
            except telegram.error.BadRequest as e:
                if 'Media_caption_too_long' in e.message:
                    print(
                        f'Failed to send mediagroup with long caption {len(match.pretty_conversation)} symbols'
                    )

                    media_group = list()
                    for number, url in enumerate(match.photos.split('\n\n')):
                        media_group.append(
                            InputMediaPhoto(
                                media=url,
                                caption=match.pretty_conversation[-999:]))
                    self.telegram_bot_instance.bot.send_media_group(
                        chat_id=self.telegram_bot_instance.chat_id,
                        media=media_group[:10])
                else:
                    image_downloader = ImageDownloader()
                    try:
                        media_group = list()
                        for number, url in enumerate(
                                match.photos.split("\n\n")):

                            try:
                                downloaded_file = image_downloader.download_image(
                                    url)
                            except Exception as e:
                                if '[ImageDownloader] Cannot download image' in ''.join(
                                        e.args):
                                    continue
                                else:
                                    raise e

                            media_group.append(
                                InputMediaPhoto(
                                    media=open(downloaded_file, 'rb'),
                                    caption=match.pretty_conversation))

                        self.telegram_bot_instance.bot.send_media_group(
                            chat_id=self.telegram_bot_instance.chat_id,
                            media=media_group[:10])

                    finally:
                        image_downloader.cleanup_tmp_dir()
Example #16
0
 def func():
     with open('tests/data/telegram.jpg', 'rb') as file:
         return bot.send_media_group(
             chat_id,
             [
                 InputMediaVideo(video_file),
                 InputMediaPhoto(photo_file),
                 InputMediaPhoto(file.read()),
             ],
         )
Example #17
0
    def finish(
        self,
        force_exec=0
    ):  #проверка на окончание хода; если force_exec не равно 0, то игра завершается в любом случае: если force_exec = -1 - игру прервал админ, если force_exec = 1 - противник сдался
        player, opponent, allies, enemies, whites_turn = self.get_context()

        self.turn -= 1
        if force_exec == -1:
            input_media = self.last_mainmenu
            input_media.caption = f'Игра окончена: админ группы прервал игру\nНичья!\nХодов: {str(self.turn)}'
            self.match_msg.edit_media(input_media)
            return True

        if force_exec == 1:
            self.match_msg.edit_media(
                InputMediaPhoto(
                    media=self.assemble_board(),
                    caption=
                    f'Игра окончена: {opponent.name} сдался\nПобедитель: {player.name}\nХодов: {str(self.turn)}'
                ))
            return True

        if self.is_stalemate(allies, enemies):
            self.match_msg.edit_media(
                InputMediaPhoto(
                    media=self.assemble_board(),
                    caption=
                    f'Игра окончена: Пат\nНичья!\nХодов: {str(self.turn)}'))
            return True

        if self.empty_turns >= 50:
            self.match_msg.edit_media(
                InputMediaPhoto(
                    media=self.assemble_board(),
                    caption=
                    f'Игра окончена: Оба игрока ни двинули ни одну пешку и ни захватили ни одной фигуры оппонента в течении 50 ходов\nНичья!\nХодов: {str(self.turn)}'
                ))
            return True

        double_check = self.is_check and self.get_king(
            not whites_turn).is_check([i.pos for i in enemies], allies)
        if self.get_king(whites_turn).is_checkmate([i.pos for i in allies],
                                                   enemies) or double_check:
            self.match_msg.edit_media(
                InputMediaPhoto(
                    media=self.assemble_board(),
                    caption=
                    f'Игра окончена: Шах и Мат\nПобедитель: {opponent.name}\nХодов: {str(self.turn)}'
                ))
            return True

        self.turn += 1
        return False
Example #18
0
def get_photo(image_url):
    """Build InputMediaPhoto from image url"""
    try:
        return InputMediaPhoto(image_url)
    except TimedOut:
        logger.info('Request for photo from %s timed out.', image_url)
        logger.info('Retrying..')
        try:
            return InputMediaPhoto(image_url)
        except TimedOut:
            logger.info('Retry Failed.')
            return None
Example #19
0
def handler_statistics(update: Update, context: CallbackContext):
    query = update.callback_query
    request = query.data
    user = session.query(User).filter(
        User.telegram_user_id == update.effective_user.id).first()
    graph_controller = context.user_data.get('statistics')
    if not graph_controller:
        graph_controller = GraphController(
            make_default_graph(user),
            get_lifetime_user(user, datetime.datetime.now()),
            TypeTransaction.CONSUMPTION)
        context.user_data['statistics'] = graph_controller
    if request == '{}earnings'.format(prefix_query_statistics):
        graph_controller.update_type_transactions(TypeTransaction.EARNING)
        handler_button_choose_type_transactions(update, context, user)
    elif request == '{}consumptions'.format(prefix_query_statistics):
        graph_controller.update_type_transactions(TypeTransaction.CONSUMPTION)
        handler_button_choose_type_transactions(update, context, user)
    elif request == '{}time_period'.format(prefix_query_statistics):
        media_object = InputMediaPhoto(
            open(graph_controller.path_to_current_graph, 'rb'))
        bot.edit_message_media(chat_id=query.message.chat_id,
                               message_id=query.message.message_id,
                               media=media_object,
                               reply_markup=reply_keyboard_choose_time_period)
    elif request == '{}yesterday'.format(prefix_query_statistics):
        graph_controller.update_time_period(
            get_yesterday(datetime.datetime.now()))
        handler_button_choose_time_period(update, context, user)
    elif request == '{}today'.format(prefix_query_statistics):
        graph_controller.update_time_period(get_today(datetime.datetime.now()))
        handler_button_choose_time_period(update, context, user)
    elif request == '{}current_week'.format(prefix_query_statistics):
        graph_controller.update_time_period(
            get_current_week(datetime.datetime.now()))
        handler_button_choose_time_period(update, context, user)
    elif request == '{}current_month'.format(prefix_query_statistics):
        graph_controller.update_time_period(
            get_current_month(datetime.datetime.now()))
        handler_button_choose_time_period(update, context, user)
    elif request == '{}all_time'.format(prefix_query_statistics):
        graph_controller.update_time_period(
            get_lifetime_user(user, datetime.datetime.now()))
        handler_button_choose_time_period(update, context, user)
    elif request == '{}back'.format(prefix_query_statistics):
        media_object = InputMediaPhoto(
            open(graph_controller.path_to_current_graph, 'rb'))
        bot.edit_message_media(
            chat_id=update.callback_query.message.chat_id,
            message_id=update.callback_query.message.message_id,
            media=media_object,
            reply_markup=reply_main_keyboard)
Example #20
0
def help_anime_funcs_handler(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer(text='Hold on..', show_alert=False)
    match = query.data.split('_')[1]
    if match == 'animesearch':
        query.message.edit_media(InputMediaPhoto(
            help_for_specific_commands['search_anime']['pic'],
            caption=help_for_specific_commands['search_anime']['text']),
                                 reply_markup=back_to_anime_help_button)
    if match == 'mangasearch':
        query.message.edit_media(InputMediaPhoto(
            help_for_specific_commands['search_manga']['pic'],
            caption=help_for_specific_commands['search_manga']['text']),
                                 reply_markup=back_to_anime_help_button)
Example #21
0
def help_funcs_handler(update: Update, context: CallbackContext):  #r="h_"
    query = update.callback_query
    query.answer(text='Hold on..', show_alert=False)
    match = query.data.split('_')[1]
    if match == 'am':  #h_am
        query.message.edit_media(InputMediaPhoto(
            help_for_specific_commands['anime_manga_section']['pic'],
            help_for_specific_commands['anime_manga_section']['text']),
                                 reply_markup=anime_buttons)
    elif match == 'imgmanipulation':  #h_imgmanipulation
        query.message.edit_media(InputMediaPhoto(
            help_for_specific_commands['img_manipulation_section']['pic'],
            help_for_specific_commands['img_manipulation_section']['text']),
                                 reply_markup=img_manipulation_buttons)
Example #22
0
def job():
    global db

    # Job running...
    print('Job running...')

    # Download data
    intro, plot1, plot2 = download()

    # Get active user with daily news
    users = db.users.find({"active": True, "news": True})

    # Counters
    news_sent_counter = 0
    news_fail_counter = 0
    # Send news to all active user
    for user in users:

        try:
            # Send photos
            p1 = open(intro['results'], 'rb')
            p2 = open(plot1['results'], 'rb')
            p3 = open(plot2['results'], 'rb')

            p1 = InputMediaPhoto(media=p1)
            p2 = InputMediaPhoto(media=p2)
            p3 = InputMediaPhoto(media=p3)

            updater.bot.send_media_group(chat_id=user['_id'],
                                         media=[p1, p2, p3])
            # Count news successfully sent
            news_sent_counter = news_sent_counter + 1
            # Log
            print('[JOB] Message successfully sent to ', user['_id'])
        except:
            # Count news fail
            news_fail_counter = news_fail_counter + 1
            # Error on sending
            print('[JOB] Failed to send to ', user['_id'])

    # Log results
    print(
        "[JOB] Results: {sent} messages sent, {fail} messages failed.".format(
            sent=news_sent_counter, fail=news_fail_counter))

    # Remove tmp files
    for data in [intro, plot1, plot2]:
        os.remove(data['plot'])
        os.remove(data['webpage'])
        os.remove(data['results'])
Example #23
0
File: pic.py Project: obviyus/bot
def pic(update: 'telegram.Update', context: 'telegram.ext.CallbackContext') -> None:
    """Get random images from imgur"""
    if not update.message:
        return

    chars: str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'
    length: int = 5

    try:
        n: int = int(context.args[0]) if context.args else 1
        # Request maximum 5 images at once
        n = min(n, 5)
    except ValueError:
        n = 1

    media_group: List[InputMediaPhoto] = []
    while n > 0:
        address: str = 'https://i.imgur.com/' + "".join(choices(chars, k=length)) + '.jpg'
        r = requests.get(address)

        # Ignore any images < 1000B
        if r.url == address and int(r.headers['content-length']) > 1000:
            media_group.append(InputMediaPhoto(media=address))
            n -= 1

    update.message.reply_media_group(
        media=media_group,
    )
Example #24
0
def on_callback_coin_flip(update: Update, context: CallbackContext):
    message = update.effective_message

    query = update.callback_query
    query.answer()

    reply_markup = InlineKeyboardMarkup.from_row([
        InlineKeyboardButton(
            '🔁 Повторить',
            callback_data=fill_string_pattern(PATTERN_COIN_FLIP)),
        InlineKeyboardButton(
            '❌ Убрать',
            callback_data=fill_string_pattern(PATTERN_HIDE_COIN_FLIP)),
    ])

    value = random.choice(list(COIN_VARIANTS))
    f = open(COIN_VARIANTS[value], 'rb')

    is_new = not message.photo
    if is_new:
        message.reply_photo(f,
                            caption=f"🍀 Бросок: {value}",
                            reply_markup=reply_markup,
                            reply_to_message_id=message.message_id)
    else:
        message.edit_media(InputMediaPhoto(f, f'{message.caption}, {value}'),
                           reply_markup=reply_markup)
Example #25
0
def send_album(context):
    media_group_id = context.job.context[0]
    updates = ALBUM_DICT[media_group_id]

    # delete from ALBUM_DICT
    del ALBUM_DICT[media_group_id]

    # ordering album updates
    updates.sort(key=lambda x: x.message.message_id)

    media = []
    for update in updates:
        if update.message.photo:
            media.append(
                InputMediaPhoto(media=update.message.photo[-1].file_id,
                                caption='' if update.message.caption is None
                                else update.message.caption_html,
                                parse_mode=ParseMode.HTML))
        elif update.message.video:
            media.append(
                InputMediaVideo(media=update.message.video.file_id,
                                caption='' if update.message.caption is None
                                else update.message.caption_html,
                                parse_mode=ParseMode.HTML))
    context.bot.sendMediaGroup(chat_id=updates[0].message.from_user.id,
                               media=media)
Example #26
0
def latest_job(context):
    today = dt.now().strftime("%Y-%m-%d")
    data = get_vaccines_data()
    data["date"] = dt.now().strftime("%b %-d, %Y - %H:%M")
    with codecs.open("template.html", "r", encoding="UTF-8") as file:
        template = Template(file.read())

    job = context.job

    today_wordy = dt.now().strftime("%b %-d, %Y")

    plot_urls = [
        f"https://raw.githubusercontent.com/mttmantovani/telegram-covid-bot/main/charts/{today}-{plot}.png"
        for plot in ["total", "daily", "map"]
    ]
    captions = [f"Daily report of {today_wordy}", "", ""]

    plots = [
        InputMediaPhoto(url, caption)
        for url, caption in zip(plot_urls, captions)
    ]

    context.bot.send_message(job.context,
                             text=template.render(**data),
                             parse_mode="HTML")
    context.bot.send_media_group(job.context, plots)
Example #27
0
def publish(bot, update):
    from_chat_id = update.message.chat.id

    if not chat_id_to_photo_ids_f(from_chat_id):
        update.message.reply_text("nothing to send")
        return True

    photo_ids = chat_id_to_photo_ids_f(from_chat_id)
    media_group = [InputMediaPhoto(id) for id in photo_ids]

    media_group_id = time.time()

    add_photo_ids(media_group_id, photo_ids)

    admin_keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton("Approve",
                             callback_data="a,{},{}".format(
                                 media_group_id, from_chat_id)),
        InlineKeyboardButton("Reject",
                             callback_data="r,{},{}".format(
                                 media_group_id, from_chat_id))
    ]])

    for admin_chat_id in admin_chat_ids_f():
        messages = bot.sendMediaGroup(admin_chat_id, media_group)

        bot.sendMessage(admin_chat_id,
                        "from @{}".format(update.message.from_user.username),
                        reply_markup=admin_keyboard)

    bot.sendMessage(from_chat_id, PHOTOS_SENT_TEXT)

    return reset(bot, update)
Example #28
0
def send_photos(update, context):
    # print(update.effective_message.chat_id)

    if update.message.chat_id in ALLOWED_IDS:
        context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.UPLOAD_PHOTO)
        media = []
        for i in range(1, 8):
            photo_url, text = GENERAL_VK.get_random_photo()

            if photo_url:
                text_length = len(text)
                if text_length > 1024:
                    text = text[:1023]
                # logging.error(text)
                media.append(InputMediaPhoto(caption=text, media=photo_url))

        try:
            update.message.reply_media_group(media, disable_notification=True, timeout=90)
        except TimedOut:
            update.message.reply_text('VK server timeout, try again')
        except BadRequest:
            error_message = [input_media.caption for input_media in media]
            logging.warning(f'error with {error_message}')
            update.message.reply_text('VK server timeout, try again')
            raise

    else:
        context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING)
        update.message.reply_text('Access restricted')
Example #29
0
def send_album(bot, job):
    user_id, media_group_id = job.context
    items = ALBUM_DICT[media_group_id]
    # delete from ALBUM_DICT
    del ALBUM_DICT[media_group_id]
    media = []
    for item in items:
        if item['type'] == 'photo':
            media.append(
                InputMediaPhoto(
                    media=item['file_id'],
                    caption=item['caption'],
                    parse_mode=ParseMode.HTML
                )
            )
        elif item['type'] == 'video':
            media.append(
                InputMediaVideo(
                    media=item['file_id'],
                    caption=item['caption'],
                    parse_mode=ParseMode.HTML
                )
            )
    bot.sendMediaGroup(
        chat_id=user_id,
        media=media
    )
Example #30
0
def send_back_result(bot, data, item, newSearch, size, type, update):
    keys = keymap(type, data)
    setup_keyboard(data, keys, size)
    markup = InlineKeyboardMarkup(keys)
    if item['artist']:
        caption = "{} - {}".format(item["title"], item["artist"])
    else:
        caption = "{}".format(item["title"])
    if newSearch:
        bot.delete_message(chat_id=update.callback_query.message.chat_id,
                           message_id=update.callback_query.message.message_id)
        bot.send_photo(
            photo="https://anghamicoverart.akamaized.net/?id={}".format(
                item["coverArt"]),
            caption=caption,
            chat_id=update.callback_query.message.chat_id,
            reply_markup=markup)
    else:
        bot.answer_callback_query(callback_query_id=update.callback_query.id)
        bot.edit_message_media(
            media=InputMediaPhoto(
                media="https://anghamicoverart.akamaized.net/?id={}".format(
                    item["coverArt"]),
                caption=caption),
            chat_id=update.callback_query.message.chat_id,
            message_id=update.callback_query.message.message_id,
            reply_markup=markup)