async def show_styles_handler(message: types.Message, state: FSMContext): user_data = await state.get_data() await types.ChatActions.upload_photo() media = types.MediaGroup() # Флаг указывающий, следует ли расставить картинки стилей в определённом здесь порядке. CUSTOM_ORDER = True if CUSTOM_ORDER: def attach(indexes): for idx in indexes: media.attach_photo(types.InputFile( default_styles[idx]['file']), caption=default_styles[idx]['name']) attach([2, 3]) await message.answer_media_group(media) media = types.MediaGroup() attach([13, 4, 1, 7, 8, 10, 12, 9, 11]) await message.answer_media_group(media) else: counter = 0 for style_id, style in default_styles.items(): # 9 картинок красиво собираются в квадрат. if counter == 9: await message.answer_media_group(media) media = types.MediaGroup() counter = 0 media.attach_photo(types.InputFile(style['file']), caption=style['name']) counter += 1 await message.answer_media_group(media) await message.answer( 'Это только список стандартных стилей. ' 'Перед обработкой вы можете выбрать в качестве стиля любое понравившееся изображение в вашем телефоне.', reply_markup=init_main_keyboard(user_data))
async def process_styles_command(message: types.Message): args = message.get_args() styles = list(interface.examples_styles_images()) n_styles = len(styles) if args == "": return await message.reply( 'Формат команды: "/styles n", где n от 0 до {}'.format(n_styles - 1), reply=False) if args == "all" and False: await types.ChatActions.upload_photo() media = types.MediaGroup() for st, im in styles: media.attach_photo(types.InputFile(st), 'Стиль') media.attach_photo(types.InputFile(im), 'Результат') return await message.reply_media_group(media=media, reply=False) if not is_int(args): return await message.reply( 'Формат команды: "/styles n", где n от 0 до {}'.format(n_styles - 1), reply=False) s = int(args) if s < 0 or s >= n_styles: return await message.reply( 'Номер стиля может быть только от от 0 до {}'.format(n_styles - 1), reply=False) await types.ChatActions.upload_photo() media = types.MediaGroup() media.attach_photo(types.InputFile(interface.example_content()), 'Контент') media.attach_photo(types.InputFile(styles[s][0]), 'Стиль') media.attach_photo(types.InputFile(styles[s][1]), 'Результат') await message.reply_media_group(media=media, reply=False)
async def show_what_you_can(message: Message): # первое сообщение пользователю: await bot.send_message(chat_id=message.from_user.id, text="Вот, что я могу:") # Create media group media_content, media_style, media_finish = types.MediaGroup( ), types.MediaGroup(), types.MediaGroup() media_h2z, media_z2h = types.MediaGroup(), types.MediaGroup() media_content.attach_photo(types.InputFile(r"image_for_bot/karabash.jpg")) media_style.attach_photo(types.InputFile(r"image_for_bot/shanghai.jpg")) media_finish.attach_photo(types.InputFile(r"image_for_bot/result_nst.jpg")) media_h2z.attach_photo(types.InputFile(r"image_for_bot/horse2zebra.jpg")) media_z2h.attach_photo(types.InputFile(r"image_for_bot/zebra2horse.jpg")) # Wait a little... await asyncio.sleep(1) # отправляем картинку-основу await bot.send_message( chat_id=message.from_user.id, text= "Я умею переносить стиль одной картинки на другую. Приведу простой пример" "\nВот картинка-основа \nОжидайте...") # для того, чтобы ползунок вверху писал: "Отправляет фото...>>>" await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=message.from_user.id, media=media_content) # отправляем картинку-стиль await asyncio.sleep(4) await bot.send_message(chat_id=message.from_user.id, text="Вот картинка-стиль \nОжидайте...") await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=message.from_user.id, media=media_style) # отправляем картинку-результат await asyncio.sleep(2) await bot.send_message(chat_id=message.from_user.id, text="А вот то, что мы можем получить \n") await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=message.from_user.id, media=media_finish) # отправляем преобразование лошадь-зебра await asyncio.sleep(4) await bot.send_message(chat_id=message.from_user.id, text="Также умею превращать лошадей в зебр...") await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=message.from_user.id, media=media_h2z) # отправляем преобразование зебра-лошадь await asyncio.sleep(4) await bot.send_message(chat_id=message.from_user.id, text="... и зебр в лошадей...") await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=message.from_user.id, media=media_z2h) await asyncio.sleep(4) await bot.send_message(chat_id=message.from_user.id, text=text_instruction)
async def send_posts(id, posts): for post in posts: post_info = post_markup(id, post) if post.typename == 'GraphImage': await types.ChatActions.upload_photo() await bot.send_photo(id, post.url, caption=post.caption, reply_markup=post_info) elif post.typename == 'GraphVideo': await types.ChatActions.upload_video() await bot.send_video(id, post.video_url, caption=post.caption, reply_markup=post_info) elif post.typename == 'GraphSidecar': media = types.MediaGroup() for edge_number, sidecar_node in enumerate( post.get_sidecar_nodes(), start=1): if sidecar_node.is_video: await types.ChatActions.upload_video() media.attach_video(sidecar_node.video_url) else: await types.ChatActions.upload_photo() media.attach_photo(sidecar_node.display_url) msg = await bot.send_media_group(id, media) if post.caption == None: post.caption = '...' await msg[0].reply(post.caption, reply_markup=post_info)
async def state_style(message: types.Message): state = dp.current_state(user=message.from_user.id) if len(message.photo) == 0: return await message.reply( 'Вы не загрузили контентную картинку... Загрузите, пожалуйста.', reply=False) path_content = 'data/{}_content.jpg'.format(message.from_user.id) path_style = 'data/{}_style.jpg'.format(message.from_user.id) path_output = 'data/{}_output.jpg'.format(message.from_user.id) await message.photo[-1].download(path_content) await do_style(path_style, path_content, path_output) await types.ChatActions.upload_photo() media = types.MediaGroup() media.attach_photo(types.InputFile(path_output), 'Вот результат!') await message.reply_media_group(media=media, reply=False) await state.reset_state() await message.reply("Набери /go или /gan, чтобы начать снова.", reply=False) await gccollect()
async def send_welcome(message: types.Message): # So... At first I want to send something like this: await message.reply("Do you want to see many pussies? Are you ready?") # Wait a little... await asyncio.sleep(3) # Good bots should send chat actions... await types.ChatActions.upload_photo() # Create media group media = types.MediaGroup() # Attach local file media.attach_photo(types.InputFile('data/cat.png'), 'Cat!') # More local files and more cats! media.attach_photo(types.InputFile('data/cats.jpg'), 'More cats!') # You can also use URL's # For example: get random puss: #media.attach_photo('https://avatars.mds.yandex.net/get-zen_gallery/4001064/pub_605cd86ed15daa7344cf4ae7_605cd927d15daa7344cfe3a3/scale_1200', 'Image') # And you can also use file ID: # media.attach_photo('<file_id>', 'cat-cat-cat.') # Done! Send media group # await message.reply_media_group(media=media) loop = asyncio.get_event_loop() loop.run_until_complete(bot.send_message(CHANNEL_ID, media))
async def categories(message: types.Message): # # global categories # global count_items await bot.send_message(message.chat.id, message.text) # table = db_main.Table(tables.names_dict["items"]) category_id = categories.index(message.text) + 1 item = table.select(["name", "description", "price", "photo_id"], ["category_id", "position"], [category_id, 1])[0] name, description, price, photo_id = item[0], item[1], item[2], item[3] table.close() media = types.MediaGroup() media.attach_photo(photo_id) photo_message = await bot.send_media_group(message.chat.id, media=media) photo_message_id = photo_message[0].message_id keyboard, callback = generate_kb(category_id, 1, photo_message_id) await bot.send_message(message.chat.id, generate_item_text(name, description, price), reply_markup=keyboard_main.inline( keyboard, callback))
async def readme_handler(message: types.Message, state: FSMContext): user_data = await state.get_data() await message.answer( 'Я могу обработать фото таким образом, ' 'чтобы стилистически оно стало похоже на другое изображение (стиль).', reply_markup=ReplyKeyboardRemove()) await types.ChatActions.upload_photo() flower_id = 4 if flower_id in examples[0]: media = types.MediaGroup() media.attach_photo( types.InputFile(examples[0][flower_id][ImageTypes.CONTENT]), caption='Например, в качестве фото можно использовать цветы.') media.attach_photo( types.InputFile(examples[0][flower_id][ImageTypes.STYLE]), caption='А в качестве стиля акварельный рисунок цветов.') media.attach_photo( types.InputFile(examples[0][flower_id][ImageTypes.RESULT]), caption='В результате получатся цветы с исходного фото, ' 'но как буд-то нарисованные акварелью.') await message.answer_media_group(media) await message.answer( 'Обычно в качестве стиля используют ' 'либо картинку с содержанием похожим на исходное фото, но оформленным иначе, ' 'либо красивую текстуру.\n\n' 'Подробную информацию о моей реализации смотрите на ' f'{md.hlink("github", "https://github.com/ChumankinYuriy/heroku_chust_bot")}.', reply_markup=init_main_keyboard(user_data), disable_web_page_preview=True, parse_mode=types.ParseMode.HTML)
async def state_go(message: types.Message): state = dp.current_state(user=message.from_user.id) if len(message.photo) == 0: if is_int(message.text): s = int(message.text) styles = interface.style_images() n_styles = len(styles) if s < 0 or s >= n_styles: return await message.reply( 'Номер стиля может быть только от 0 до {}.'.format( n_styles - 1), reply=False) dstyle = 'data/{}_style.jpg'.format(message.from_user.id) shutil.copy(styles[s], dstyle) await types.ChatActions.upload_photo() media = types.MediaGroup() media.attach_photo(types.InputFile(dstyle), 'Вы выбрали такой стиль.') await message.reply_media_group(media=media, reply=False) else: return await message.reply( 'Вы не загрузили стилевую картинку... Загрузите, пожалуйста.', reply=False) else: await message.photo[-1].download('data/{}_style.jpg'.format( message.from_user.id)) await state.set_state(AppStates.STATE_LOAD_CONTENT[0]) await message.reply('Загрузи контентную картинку.', reply=False)
async def send_docs_post(bot: Bot, tg_channel: str, docs: list) -> None: media = types.MediaGroup() for doc in docs: media.attach_document( types.InputMediaDocument(open(f"./temp/{doc['title']}", "rb"))) await bot.send_media_group(tg_channel, media) logger.info("Documents sent to Telegram.")
async def send_welcome(message: types.Message): # So... At first I want to send something like this: await message.reply("Do you want to see many pussies? Are you ready?") # And wait few seconds... await asyncio.sleep(1) # Good bots should send chat actions. Or not. await types.ChatActions.upload_photo() # Create media group media = types.MediaGroup() # Attach local file media.attach_photo(types.InputFile('data/cat.jpg'), 'Cat!') # More local files and more cats! media.attach_photo(types.InputFile('data/cats.jpg'), 'More cats!') # You can also use URL's # For example: get random puss: media.attach_photo('http://lorempixel.com/400/200/cats/', 'Random cat.') # And you can also use file ID: # media.attach_photo('<file_id>', 'cat-cat-cat.') # Done! Send media group await message.reply_media_group(media=media)
async def renewal_post(wait_for): #рассылка новых статей while True: await asyncio.sleep(wait_for) id, data = renovation_post() if (data): if (data['counter'] > 1): await asyncio.sleep(0.6) media = types.MediaGroup() for i in data['image']: media.attach_photo(types.InputFile.from_url(i)) await asyncio.sleep(0.6) text = data['title'] + '.\n' + data['info'] + '.\n' + data[ 'video'] await bot.send_message(id, text) await bot.send_media_group(id, media) else: await asyncio.sleep(0.6) text = data['title'] + '.\n' + data['info'] + '.\n' + data[ 'video'] await bot.send_message(id, text) if (data['image']): await bot.send_photo( id, types.InputFile.from_url(data['image'][0]))
async def download_content(message: types.Message, state: FSMContext): await message.photo[-1].download('test.jpg') import torch import numpy as np from PIL import Image import torchvision.transforms as transforms from torch.autograd import Variable from network import Transformer valid_ext = ['.jpg', '.png'] model = Transformer() # dict = wget.download('http://vllab1.ucmerced.edu/~yli62/CartoonGAN/pytorch_pth/Hayao_net_G_float.pth') dict = 'Hayao_net_G_float.pth' model.load_state_dict(torch.load(dict)) #model = torch.load('model.pth') model.eval() model.float() # load image input_image = Image.open('test.jpg').convert("RGB") # resize image, keep aspect ratio h = input_image.size[0] w = input_image.size[1] ratio = h * 1.0 / w if ratio > 1: h = 310 w = int(h * 1.0 / ratio) else: w = 310 h = int(w * ratio) input_image = input_image.resize((h, w), Image.BICUBIC) input_image = np.asarray(input_image) input_image = input_image[:, :, [2, 1, 0]] input_image = transforms.ToTensor()(input_image).unsqueeze(0) input_image = -1 + 2 * input_image with torch.no_grad(): input_image = Variable(input_image).float() output_image = model(input_image) output_image = output_image[0] output_image = output_image[[2, 1, 0], :, :] output_image = output_image.data.cpu().float() * 0.5 + 0.5 output_image = output_image.squeeze(0) # функция для отрисовки изображения unloader = transforms.ToPILImage() output_image = unloader(output_image) output_image.save('gan.jpg') media = types.MediaGroup() media.attach_photo(types.InputFile('gan.jpg')) await message.reply_media_group(media=media) await message.reply("Ready! To continue choose /gan or /style_transfer") await state.finish()
async def послать_медиа_группу(диспетчер): """ Посылаем медиагруппу из телеграм бота. Параметры ---------- диспетчер : Диспетчер класса Dispatcher, отвечает за маршрутизацию сообщений, не имеет значения для работы данной функции """ # Создаём "контейнер" для наших медиа, т.е. изображений media = types.MediaGroup() # Получаем список текущих изображений в указанной папке все_изображения = получить_название_всех_изображений() текст_ссылки = 'читать дальше ...' ссылка = '' for позиция, путь_к_изображению in enumerate(все_изображения, start=1): # Добавляем описание только к последней фотографии. if позиция == len(все_изображения): описание = "Описание для изображения. " + hlink( текст_ссылки, ссылка) else: описание = None # По очереди добавляем все изображения и директории # К нашему контйнеру. # При этом добавляем описание только к последней фотографии, # А у всех остальных описание = None media.attach_photo(types.InputFile(путь_к_изображению), описание) try: # Пытаемся послать медиагруппу в указанный chat_id await bot.send_media_group(chat_id='-1001188248012', media=media) except Exception as ошибка: # В случае ошибки, сообщаем об этом пользователю и # И прерываем выполнение скрипта командой # raise print("Во время отправки медиагруппы произошла ошибка") raise ошибка # При успешной отправке сообщений # Выводим на экран полезное сообщение # И завершаем работу скрипта. print("Отправка сообщений завершена.") sys.exit(0)
async def lets_go_work(message: Message): user_id = message.from_user.id # создаем экземпляр класса types.MediaGroup() для добавления картинки-основы # file["file_id"] - загруженная на сервер Telegram картинка, поэтому мы можем вывести ее таким образом media_content, media_style = types.MediaGroup(), types.MediaGroup() media_content.attach_photo(dict_for_transfer_style[user_id][0]["file_id"]) media_style.attach_photo(dict_for_transfer_style[user_id][1]["file_id"]) # блок показа пользователю введенных им данных await bot.send_message(chat_id=message.from_user.id, text="Я начал обработку. \n" "Вот что вы загрузили...") await asyncio.sleep(1) await bot.send_message(chat_id=user_id, text="Ваша картинка-основа") await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=user_id, media=media_content) await bot.send_message(chat_id=user_id, text="Ваша картинка-стиль") await asyncio.sleep(1) await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=user_id, media=media_style) await bot.send_message(chat_id=user_id, text="Пожалуйста ожидайте 5-7 минут") # блок работы NST image_content = await bot.download_file( dict_for_transfer_style[user_id][0].file_path) image_style = await bot.download_file( dict_for_transfer_style[user_id][1].file_path) nst = NeuralTransferStyle(content_picture=image_content, style_picture=image_style, max_size=400, number_epochs=700).train_nst() media_result = types.MediaGroup() media_result.attach_photo(nst) await bot.send_message(chat_id=user_id, text="Вот что получилось...") await asyncio.sleep(1) await types.ChatActions.upload_photo() await bot.send_media_group(chat_id=user_id, media=media_result) await bot.send_message( chat_id=user_id, text="Надеюсь, Вам понравилось. Вы можете попробовать снова!" + text_instruction) dict_for_transfer_style[0] = None dict_for_transfer_style[user_id] = []
async def some_cat(msg: types.Message): what_we_want = msg.text.lower() try: if what_we_want == "котик": await types.ChatActions.upload_photo() cat = Animals.give_me_a_cat() cat_n_caption = types.MediaGroup() cat_n_caption.attach_photo(cat[0], cat[1]) await msg.reply_media_group(media=cat_n_caption) if what_we_want == "собачка": await types.ChatActions.upload_photo() dog = Animals.give_me_a_dog() dog_n_caption = types.MediaGroup() dog_n_caption.attach_photo(dog[0], dog[1]) await msg.reply_media_group(media=dog_n_caption) except Exception as some_error: print(some_error) await msg.reply(text("Что-то пошло не так...\nПопробуйте снова!"))
def anime_media_gen(result_1, result_2): media = types.MediaGroup() media.attach_photo( types.InputFile(save_image(result_1[0][1], result_1[0][3])), result_1[0][1]) media.attach_photo( types.InputFile(save_image(result_2[0][1], result_2[0][3])), result_2[0][1]) return media
async def worker(message): media = types.MediaGroup() statistic_df = _get_db_data(database, period='week') stat = statistic_text(statistic_df) _make_picture(statistic_df) sum_stat = printer(*get_yt_info(youtube_token)) text = f"статистика просмотров за {statistic_df.shape[1]} недели\n{stat}\nобщая статистика канала:\n{sum_stat}" media.attach_photo(types.InputFile('week.png'), text) await types.ChatActions.upload_photo() await message.reply_media_group(media=media)
async def worker(message): media = types.MediaGroup() statistic_df = _get_db_data_new(database, n_days=2) stat = statistic_text(statistic_df) _make_picture_new(statistic_df.diff(-1).apply(abs)) sum_stat = printer(*get_yt_info(youtube_token)) text = f"статистика просмотров за {statistic_df.shape[1]} дня\n{stat}\nобщая статистика канала:\n{sum_stat}" media.attach_photo(types.InputFile('hour.png'), text) await types.ChatActions.upload_photo() await message.reply_media_group(media=media)
async def process_start_command(message: types.Message): await message.reply( "Hi!\nThis is bot for neural style transfer and GAN image generation. You can test it.", reply_markup=types.ReplyKeyboardRemove()) await asyncio.sleep(1) await types.ChatActions.upload_photo() media = types.MediaGroup() await message.answer("Trehe are style and content images for NST") media.attach_photo(types.InputFile('./samples/StyleTransfer/style.jpg')) media.attach_photo(types.InputFile('./samples/StyleTransfer/content.jpg')) await message.answer_media_group(media=media) media = types.MediaGroup() await message.answer("Trehe is input guitar sketch for GAN") media.attach_photo(types.InputFile('./samples/GuitarSketch/guitar.png'), ) await message.answer_media_group(media=media) await message.answer( '"/start" - start conversions.\n"/cancel" - cancel conversion.')
def create_media(paths: Tuple[str, str, str, str]) -> types.MediaGroup: media = types.MediaGroup() media.attach_photo(types.InputFile(paths[3]), caption='Average histogram') media.attach_photo(types.InputFile(paths[0]), caption='R channel histogram') media.attach_photo(types.InputFile(paths[1]), caption='B channel histogram') media.attach_photo(types.InputFile(paths[2]), caption='G channel histogram') return media
async def post_downloader(message, post=0, posts=0): row = db.execute_one_query( conn, f'SELECT * FROM users WHERE user_id = "{message.from_user.id}"') if posts == 0: post_info = post_markup(message.from_user.id, post) if post.typename == 'GraphImage': await types.ChatActions.upload_photo() await bot.send_photo(message.chat.id, post.url, caption=post.caption, reply_markup=post_info) elif post.typename == 'GraphVideo': await types.ChatActions.upload_video() await bot.send_video(message.chat.id, post.video_url, caption=post.caption, reply_markup=post_info) elif post.typename == 'GraphSidecar': media = types.MediaGroup() for edge_number, sidecar_node in enumerate( post.get_sidecar_nodes(), start=1): if sidecar_node.is_video: await types.ChatActions.upload_video() media.attach_video(sidecar_node.video_url) else: await types.ChatActions.upload_photo() media.attach_photo(sidecar_node.display_url) msg = await bot.send_media_group(message.chat.id, media) await msg[0].reply(post.caption, reply_markup=post_info) else: if profile.has_public_story: story = key[row[1]][3] else: story = key[row[1]][4] if profile.has_highlight_reels: high = key[row[1]][5] else: high = key[row[1]][6] info = types.InlineKeyboardMarkup(row_width=2) a = types.InlineKeyboardButton( text=f'{key[row[1]][7]} {profile.mediacount}', callback_data=f"posts-{profile.username}-0") b = types.InlineKeyboardButton( text=f'{key[row[1]][8]} {profile.followees}', callback_data='x') c = types.InlineKeyboardButton( text=f'{key[row[1]][9]} {profile.followers}', callback_data="x") d = types.InlineKeyboardButton( text=story, callback_data=f"stories-{profile.userid}-0") e = types.InlineKeyboardButton( text=high, callback_data=f"highlights-{profile.userid}-0") info.add(b, c, e, d, a) await bot.send_photo( message.chat.id, profile.profile_pic_url, caption= f'instagram.com/{profile.username}/\nBio:\n{profile.biography}', reply_markup=info)
async def configure_media_group(post: List, **kwargs): msg = kwargs.get("msg") media = types.MediaGroup() for item in post: if ".mp4" in item: media.attach_video(video=rf"{item}") else: media.attach_photo(photo=rf"{item}") sent = await msg.answer_media_group(media=media) text_msg = await msg.answer(text=kwargs.get("caption"), reply_markup=kwargs.get("markup")) return sent, text_msg
async def send_photos_post(bot: Bot, tg_channel: str, text: str, photos: list) -> None: media = types.MediaGroup() for photo in photos: media.attach_photo(types.InputMediaPhoto(photo)) if (len(text) > 0) and (len(text) <= 1024): media.media[0].caption = text media.media[0].parse_mode = types.ParseMode.HTML elif len(text) > 1024: await send_text_post(bot, tg_channel, text) await bot.send_media_group(tg_channel, media) logger.info("Text post with photos sent to Telegram.")
async def send_movie_info(message, state): data = await state.get_data() movie_list, year, index, genres = data.get("movie_list"), data.get("year"), \ data.get("index"), data.get("genres") if year is not None: print(year, movie_list[0]["release_date"], index) movie_list = [ movie for movie in movie_list if year in movie['release_date'] ] print(movie_list) if len(movie_list) > index: movie = movie_list[index] movie = movie_list[index] reply_text = f"<b>{movie['title']}</b> ({movie['release_date'][:4]})\n" + \ f"Средня оценка: {movie['vote_average']}\n" + \ f"Жанры: {', '.join([genres[idx] for idx in movie['genre_ids']])}\n" if movie['overview'] is not None: reply_text += f"Описание: {movie['overview']}\n" else: await message.answer(f"Фильмов не найдено, попробуйте еще раз") return await MovieSearch.QueryEntering.set() media = types.MediaGroup() if movie['poster_path'] is not None: print(BASE_URL_IMAGE + FILE_SIZE + movie['poster_path']) media.attach_photo(BASE_URL_IMAGE + FILE_SIZE + movie['poster_path'], reply_text) # TODO иногда выдает aiogram.utils.exceptions.BadRequest: Wrong type of the web page content try: await message.answer_media_group(media=media) except aiogram.utils.exceptions.BadRequest: await message.answer(reply_text) else: await message.answer(reply_text) await state.update_data(movie_list=movie_list) link, status = await get_movie_link(movie) keyboard = aiogram.types.InlineKeyboardMarkup() if status: button = aiogram.types.InlineKeyboardButton(text="Смотреть", url=link) keyboard.add(button) await message.answer("Ссылка на фильм", reply_markup=keyboard) else: button = aiogram.types.InlineKeyboardButton(text="Искать", url=link) keyboard.add(button) await message.answer("Найти в Google?", reply_markup=keyboard) await message.answer("Это то, что вы искали? [Да/Нет]") await MovieSearch.MovieCorrectness.set()
async def end_session(message: types.Message): """ This handler will be called when user sends /example command """ # send result to the user:in await types.ChatActions.upload_photo() media = types.MediaGroup() media.attach_photo(types.InputFile('example_content_img.jpg'), 'Content Image') media.attach_photo(types.InputFile('example_style_img.jpg'), 'Style Image') media.attach_photo(types.InputFile('example_output_img.jpg'), 'Output Image') await message.answer(messages['example']) await message.answer_media_group(media=media)
async def fix_size(pictures): resulting_list = [] for picture in pictures: if not isinstance(picture, types.InputFile): print('Жопа в говне size', picture) continue try: if picture.get_file().closed: if isinstance(picture.get_file(), types.input_file._WebPipe): fileo = types.InputFile.from_url( picture.get_file().url).get_file() print(1, fileo) else: fileo = open(picture.get_file().name, 'rb') print(fileo, 2) else: fileo = picture.get_file() if isinstance(fileo, types.input_file._WebPipe): fileo = io.BytesIO(await (fileo.read())) fileo.seek(0) img_obj = Image.open(fileo) except UnidentifiedImageError: resulting_list.append(open(picture.get_file().name, 'rb')) continue ext = picture.filename.split('.')[-1] length = io.BytesIO() img_obj.save(length, ext) length = length.tell() if length < 1024**2 * 10: resulting_list.append(open(picture.get_file().name, 'rb')) else: res = io.BytesIO() img_obj.reduce(1 - (1024**2 * 10 / length)).save(res, ext, optimize=True) print(res.tell() / 1024**2) res.seek(0) resulting_list.append(res) if len(resulting_list) == 1: return types.InputFile(resulting_list[0]) elif len(resulting_list) > 1: return types.MediaGroup([ types.InputMedia(types.InputFile(x)) for x in resulting_list ]) else: print('achko') return
async def process_arms_command(message: types.Message): album = types.MediaGroup() # Прикрепляем фото и видео photo_file_id = "AgACAgIAAxkBAAIKDWAw7qYzSU6s5zhnaehkjPW9io7FAAI3sjEbDueISZPAIXyrF8PgDD_Rmi4AAwEAAwIAA20AA_BQAgABHgQ" '''photo_url = "https://i.pinimg.com/originals/13/25/68/132568dbe8f3316aa56551dba527e7f7.jpg" photo_bytes = InputFile("photos/cat.jpg")''' video_file_id = "BAACAgIAAxkBAAIKXWAxLGQumodw9exdML6JqFRpm5TJAALQDgACDueISYGAWbDXYpnNHgQ" photo_bytes = "AgACAgIAAxkBAAIKA2Aw7lIwpLbn1HrfT0eAmcblZAK6AAImsjEbDueISVkUG7STreoKZBnKly4AAwEAAwIAA20AA84cBwABHgQ" photo_url = "AgACAgIAAxkBAAIJ_mAw7itplNwt6GnAy9aV2EDxmvktAAIWsjEbDueISVnTzXFFo8yjHPLAly4AAwEAAwIAA20AA2IhBwABHgQ" album.attach_photo(photo=photo_file_id, caption="красота") album.attach_photo(photo=photo_url) album.attach_photo(photo=photo_bytes) album.attach_video(video=video_file_id, caption="Видео ") await message.answer_media_group(media=album)
async def process_plot(message: types.Message, state: FSMContext): media = types.MediaGroup() try: image = PlotWidget().plot(message.text) except Exception as e: await message.reply(f"Error: {e}") return await state.finish() media.attach_photo(types.InputFile(image)) await message.reply_media_group(media=media) await message.answer("Следующее действие:", reply_markup=get_keyboard())
async def _compose_media_group(report: dict) -> types.MediaGroup: media_ids = report['media_ids'] media_photos = [] for file_id, file_type in media_ids: media_types = { 'photo': types.InputMediaPhoto, 'video': types.InputMediaVideo } file = await bot.get_file(file_id) url = bot.get_file_url(file.file_path) media_photos.append(media_types[file_type]( types.InputFile.from_url(url))) return types.MediaGroup(media_photos)