async def find_amiibo(message: types.Message): log(message) response = requests.get("http://www.amiiboapi.com/api/amiibo/?character=" + message.get_args()) amiibos = response.json().get('amiibo') #print(amiibos) if (amiibos is None): await message.reply('No amiibo found with this name') elif (len(amiibos) == 1): await message.reply_photo(amiibos[0].get('image'), disable_notification=True, reply=True) elif (len(amiibos) > 1 and len(amiibos) <= 10): imgList = [] for a in amiibos: imgList.append(types.InputMediaPhoto(a.get('image'), "View")) await message.reply_media_group(imgList, disable_notification=True, reply=True) elif (len(amiibos) > 10): imgList = [] for i in range(0, 9): imgList.append( types.InputMediaPhoto(amiibos[i].get('image'), "View")) await message.reply_media_group(imgList, disable_notification=True, reply=True)
async def get_sticker_id(photo: types.PhotoSize): file_id = photo.photo[-1].file_id file_info = await bot.get_file(file_id) photo_path = file_info.file_path await bot.download_file_by_id(file_id, photo_path) text_from_photo = get_text_from_photo(photo_path) words = get_words(text_from_photo) for word in words: d = parse_translate_audio(word) if d: media = [] photoes = get_photoes_urls(word) i = 0 while i < len(photoes): if i == 0: media.append(types.InputMediaPhoto(photoes[i], caption=f'<b>{word}</b> - <i>{d["translate"]}</i>', parse_mode=types.ParseMode.HTML)) else: media.append(types.InputMediaPhoto(photoes[i])) i += 1 # for photo_url in photoes: # media.append(types.InputMediaPhoto(photo_url, caption=f'<b>{word}</b> - <i>{d["translate"]}</i>', parse_mode=types.ParseMode.HTML)) # await bot.send_message(chat_id=photo.chat.id, text=f'<b>{word}</b> - <i>{d["translate"]}</i>', parse_mode=types.ParseMode.HTML) await bot.send_media_group(chat_id=photo.chat.id, media=media) await bot.send_audio(chat_id=photo.chat.id, audio=d['audio_url'])
async def callback_inline(callback_query: types.CallbackQuery): text_data = callback_query.data if text_data == "post": text = callback_query.message.caption photo = callback_query.message.photo video = callback_query.message.video if photo: await bot.send_photo(c.group1, photo[-1].file_id, caption=text) elif video: await bot.send_video(c.group1, video.file_id, caption=text) await callback_query.answer() await callback_query.message.answer("Опубликовано!") elif text_data == "post_group": data = str(callback_query.message.text) i = data.find('{"photo_group":') text = data[:i] photo_data = eval(data[i:])['photo_group'] photos = [types.InputMediaPhoto(photo_data[0], caption=text)] \ + [types.InputMediaPhoto(x) for x in photo_data[1:]] await bot.send_media_group(c.group1, photos) await callback_query.answer() await callback_query.message.answer("Опубликовано!") else: if text_data == "item_1": key = types.InlineKeyboardMarkup() but_1 = types.InlineKeyboardButton("1", callback_data="sub_item_1") but_2 = types.InlineKeyboardButton("2", callback_data="sub_item_2") but_3 = types.InlineKeyboardButton("3", callback_data="sub_item_3") key.add(but_1, but_2, but_3) await callback_query.message.answer( sub_main_text, parse_mode=types.ParseMode.MARKDOWN, reply_markup=key) elif text_data == "sub_item_1": await choose_service(callback_query.message, "символические 20 грн 💁♂", 20) elif text_data == "sub_item_2": await choose_service(callback_query.message, "всего 38 грн 🌺", 38) elif text_data == "sub_item_3": await choose_service(callback_query.message, "всего 76 грн 🌺", 76) elif text_data == "item_2": await choose_service(callback_query.message, "всего 140 грн 🌺", 140) elif text_data == "item_3": await choose_service( callback_query.message, "237 грн. Мы вам гарантируем до 2000 просмотров за пару дней 🥳", 237) try: await bot.delete_message(callback_query.message.chat.id, callback_query.message.message_id) except utils.exceptions.MessageCantBeDeleted: pass except utils.exceptions.MessageToDeleteNotFound: pass
async def make_post(message, data): so_id = save_special_offer(data.get('special')) key = types.InlineKeyboardMarkup() first_name = str(message.from_user.first_name).replace('_', '\\_').replace( '*', '\\*').replace('`', '\\`').replace('[', '\\[') username = str(message.from_user.username).replace('_', '\\_').replace( '*', '\\*').replace('`', '\\`').replace('[', '\\[') comm = str(data['comm']).replace('_', '\\_').replace('*', '\\*').replace( '`', '\\`').replace('[', '\\[') for admin in c.admins1: await send_message( bot.send_photo, chat_id=admin, photo=data['pay_photo'], caption= f"Оплата: [{first_name}](tg://user?id={message.from_user.id})\n" f"@{username}\n\nКомментарий: {comm}", parse_mode=types.ParseMode.MARKDOWN) if data['photo']: if len(data['photo']) == 1: key.add( types.InlineKeyboardButton("Опубликовать", callback_data=f'post{so_id}')) await send_message(bot.send_photo, chat_id=admin, photo=data['photo'][0], caption=data['text'], reply_markup=key) else: key.add( types.InlineKeyboardButton("Опубликовать", callback_data="post_group")) photos = [types.InputMediaPhoto(data['photo'][0], caption=data['text'])] \ + [types.InputMediaPhoto(x) for x in data['photo'][1:]] m = await send_message(bot.send_media_group, chat_id=admin, media=photos) if not m: continue photo_group = json.dumps( {"photo_group": [x.photo[-1].file_id for x in m]}) await send_message(bot.send_message, chat_id=admin, text=f"{data['text']}\n\n{photo_group}", reply_markup=key) elif data['video']: key.add( types.InlineKeyboardButton("Опубликовать", callback_data=f'post{so_id}')) await send_message(bot.send_video, chat_id=admin, video=data['video'], caption=data['text'], reply_markup=key)
async def test_send_media_group(bot: Bot): """ sendMediaGroup method test with file_id """ from .types.dataset import MESSAGE_WITH_MEDIA_GROUP, PHOTO msg = types.Message(**MESSAGE_WITH_MEDIA_GROUP) photo = types.PhotoSize(**PHOTO) media = [types.InputMediaPhoto(media=photo.file_id), types.InputMediaPhoto(media=photo.file_id)] async with FakeTelegram(message_data=[MESSAGE_WITH_MEDIA_GROUP, MESSAGE_WITH_MEDIA_GROUP]): result = await bot.send_media_group(msg.chat.id, media=media, disable_notification=False) assert len(result) == len(media) assert result.pop().media_group_id
async def process_callback_button(callback_query: types.CallbackQuery): data = callback_query.data.split() await bot.send_message(callback_query.from_user.id, "Processing...") user = InstaUser(data[0]) if data[1] == 'likes': if len(data) > 3: posts = filter_by_date(sort(get_posts(user.account),\ by = 'likes'), _from = data[3], _to = data[4]) else: posts = sort(get_posts(user.account), by='likes') elif data[1] == 'comments': if len(data) > 3: posts = filter_by_date(sort(get_posts(user.account),\ by = 'comments'), _from = data[3], _to = data[4]) else: posts = sort(get_posts(user.account), by='comments') elif data[1] == 'posts': posts = filter_by_date(get_posts(user.account),\ _from = data[3], _to = data[4]) if posts[int(data[2]):int(data[2]) + 10]: for post in posts[int(data[2]):int(data[2]) + 10]: try: media = list( map(lambda x: types.InputMediaPhoto(x), post['images'])) media[-1] = types.InputMediaPhoto(post['images'][-1], caption = \ message_text.format(post['description'], post['likes_count'], post['comment_count'], post['post_url'])) await bot.send_media_group(callback_query.from_user.id, media) except: pass if len(data) > 3: inline_btn = types.InlineKeyboardButton('Show more', callback_data = \ f"{user.account} {data[1]} {int(data[2])+10} {data[3]} {data[4]}") else: inline_btn = types.InlineKeyboardButton('Show more', callback_data = \ f"{user.account} {data[1]} {int(data[2])+10}") inline = types.InlineKeyboardMarkup(row_width=2).add(inline_btn) await callback_query.message.answer("Press the button to show more", reply_markup=inline) else: await bot.send_message(callback_query.from_user.id, "No more posts")
async def comments(message: types.Message): arguments = message.get_args().split() if arguments: try: await bot.send_message(message.from_user.id, "Processing...") user = InstaUser(arguments[0]) if user.is_public: if len(arguments) == 1: posts = sort(get_posts(user.account), by='comments') else: posts = filter_by_date(sort(get_posts(user.account),\ by = 'comments'), _from = arguments[1], _to = arguments[3]) for post in posts[:10]: try: media = list( map(lambda x: types.InputMediaPhoto(x), post['images'])) media[-1] = types.InputMediaPhoto(post['images'][-1], caption = \ message_text.format(post['description'], post['likes_count'], post['comment_count'], post['post_url'])) await bot.send_media_group(message.from_user.id, media) except: await bot.send_message(message.from_user.id, "Account does not exist!") if len(arguments) == 1: inline_btn = types.InlineKeyboardButton('Show more', \ callback_data = f"{user.account} likes 10") else: inline_btn = types.InlineKeyboardButton('Show more', callback_data = \ f"{user.account} likes 10 {arguments[1]} {arguments[3]}") inline = types.InlineKeyboardMarkup( row_width=2).add(inline_btn) await message.answer("Press the button to show more", reply_markup=inline) else: lang = 1 if message.from_user.language_code == 'ru' else 0 await message.answer(text['private'][lang]) except: await bot.send_message(message.from_user.id, "Account does not exist!")
async def confirm_post(message, data): if data['photo']: if len(data['photo']) == 1: await bot.send_photo(message.chat.id, data['photo'][0], caption=data['text']) else: photos = [types.InputMediaPhoto(data['photo'][0], caption=data['text'])] \ + [types.InputMediaPhoto(x) for x in data['photo'][1:]] await bot.send_media_group(message.chat.id, photos) elif data['video']: await bot.send_video(message.chat.id, data['video'], caption=data['text'])
async def back_to_main(call: types.CallbackQuery): chat, mess = call.from_user.id, call.message.message_id status = await db.subscriptions_exist(chat) num = await db.get_counts(chat) if status[0] == False: await bot.edit_message_media(types.InputMediaPhoto(startPic, text), chat, mess, reply_markup=mark) else: await bot.edit_message_media(types.InputMediaPhoto( prof, profT.format(call.from_user.full_name, num[0])), chat, mess, reply_markup=profMark)
async def answer_product_slide( message: types.Message, state: FSMContext, locale: str, product_slide: ProductAnswer, edit: bool = False, ) -> None: product = product_slide.product caption = await product_slide.get_caption() keyboard = product_slide.make_keyboard() if not edit: await message.answer_photo( product.main_picture.pic, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, ) else: await message.edit_media( types.InputMediaPhoto( product.main_picture.pic, product.main_picture.thumbnail, caption=caption, parse_mode=ParseMode.MARKDOWN, ), reply_markup=keyboard, )
async def sheduler(wait_for): while True: await asyncio.sleep(wait_for) users = await db.get_users() for user in users: if not os.path.exists(f'{DIR}\\{user[1]}.csv'): open(f'{DIR}\\{user[1]}.csv', 'x').close() with open(f'{DIR}\\{user[1]}.csv', 'r', encoding = 'utf-8') as data_file: data = data_file.read().split('\n') urls = await parse_urls(user[4]) difference = [item for item in urls if item not in data] if difference: with open(f'{DIR}\\{user[1]}.csv', 'w', encoding = 'utf-8') as data_file: for url in urls: data_file.write(f'{url}\n') post = await parse(difference[0]) media = types.InputMediaPhoto(post['img'], caption = ( post['title'] + '\n' + post['description'][:300] + '...' + '\n' + post['price'] )) inline = types.InlineKeyboardMarkup(row_width = 2) await bot.send_media_group(user[1], [media]) await bot.send_message(user[1], 'Полностью можно посмотреть по ссылке', reply_markup = inline.add( types.InlineKeyboardButton('Перейти к объявлению', url = post['url']) ))
async def get_prev(call: types.CallbackQuery, state: FSMContext): await bot.answer_callback_query(call.id) try: async with state.proxy() as data: if data['page'] > 1: data['page'] -= 1 product_id = list(data['products'].keys())[data['page'] - 1] values = list(data['products'].values())[data['page'] - 1] product = await Botbakuadmin_product.filter(id=product_id) totals_sum = await total_sum(data['products']) cb_page_text = f'{data["page"]}/{len(data["products"])}' await types.ChatActions.upload_photo() photo = types.InputFile(os.path.join(BASE_DIR, product[0].img)) media = types.InputMediaPhoto( media=photo, caption=f'<b>{product[0].name}</b>', parse_mode='HTML') await call.message.edit_media(media=media, reply_markup=get_cart_kb( cb_page_text, values, totals_sum)) else: pass except KeyError: await call.answer(text='OPS. Похоже корзина пуста')
async def show_item(callback: types.CallbackQuery, change_scroll=False, scroll=True): message = callback.message category_id, position, photo_message_id = int( callback.data.split()[1]), int(callback.data.split()[2]), int( callback.data.split()[3]) table = db_main.Table(tables.names_dict["items"]) item = table.select(["name", "description", "price", "photo_id"], ["category_id", "position"], [category_id, position])[0] name, description, price, photo_id = item[0], item[1], item[2], item[3] table.close() if change_scroll == False: media = types.InputMediaPhoto(photo_id) await bot.edit_message_media(chat_id=message.chat.id, message_id=photo_message_id, media=media) keyboard, callback = generate_kb(category_id, position, photo_message_id, scroll) if change_scroll == False: await bot.edit_message_text( chat_id=message.chat.id, message_id=message.message_id, text=generate_item_text(name, description, price), reply_markup=keyboard_main.inline(keyboard, callback)) else: await bot.edit_message_reply_markup(chat_id=message.chat.id, message_id=message.message_id, reply_markup=keyboard_main.inline( keyboard, callback))
async def make_post(message, data): key = types.InlineKeyboardMarkup() first_name = str(message.from_user.first_name).replace('_', '\\_').replace( '*', '\\*').replace('`', '\\`').replace('[', '\\[') username = str(message.from_user.username).replace('_', '\\_').replace( '*', '\\*').replace('`', '\\`').replace('[', '\\[') comm = str(data['comm']).replace('_', '\\_').replace('*', '\\*').replace( '`', '\\`').replace('[', '\\[') await bot.send_photo( c.admin1, data['pay_photo'], f"Оплата: [{first_name}](tg://user?id={message.from_user.id})\n" f"@{username}\n\nКомментарий: {comm}", parse_mode=types.ParseMode.MARKDOWN) if data['photo']: if len(data['photo']) == 1: key.add( types.InlineKeyboardButton("Опубликовать", callback_data="post")) await bot.send_photo(c.admin1, data['photo'][0], caption=data['text'], reply_markup=key) else: key.add( types.InlineKeyboardButton("Опубликовать", callback_data="post_group")) photos = [types.InputMediaPhoto(data['photo'][0], caption=data['text'])] \ + [types.InputMediaPhoto(x) for x in data['photo'][1:]] m = await bot.send_media_group(c.admin1, photos) await bot.send_message( c.admin1, f'{data["text"]}\n\n{{"photo_group": {[x.photo[-1].file_id for x in m]}}}', reply_markup=key) elif data['video']: key.add( types.InlineKeyboardButton("Опубликовать", callback_data="post")) await bot.send_video(c.admin1, data['video'], caption=data['text'], reply_markup=key)
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 kline(message, query=None): logging.info(f'{message.text}') args = argparse_kline(message.text) if args.help: await message.reply(argparse_kline.__doc__) return 0 try: stock_list = stock_query(keyword=args.keyword[0], filter_md5=args.md5) except IndexError: raise logging.info(f'query result:{stock_list}') # Get time_range from user input if args.days: time_arg = '-d '+args.days time_begin, time_end = get_time_range(int(args.days)) macd = (int(args.days) >= 100) else: time_arg = None time_begin, time_end = get_time_range() macd = True if len(stock_list) == 1: stock = stock_list[0] buf = io.BytesIO() if type(stock) == Stock_mix: stock_info = '' time_mix_created = stock.create_time.strftime("%Y%m%d") if args.days is None: time_begin = time_mix_created macd = False stock_data, _ = await mix_data_collector_async(stock, time_begin=time_begin, time_end=time_end, time_ref='oldest') else: stock_data, _ = await mix_data_collector_async(stock, time_begin=time_begin, time_end=time_end, time_ref='created') plot_kline(stock_data=stock_data, title=f'kline of {stock.code}', plot_type='line', volume=False, macd=macd, output=buf) else: if stock_info := stock.company_info: stock_info = f"[INFO]({stock_info})" plot_kline(stock_data=stock.collect_data_daily(time_begin, time_end), title=f'kline of {stock.code}', plot_type='hollow_candle', macd=macd, output=buf) buf.seek(0) kline_caption = (' '.join([stock.code, stock.name, stock_info])).replace('*', '\*') # A-share sucks! if args.md5: # Not open to user input, can only result from inline keyboard callback await query.message.edit_media(types.InputMediaPhoto(media=buf, caption=kline_caption, parse_mode=ParseMode.MARKDOWN)) else: await message.reply_photo(buf, caption=kline_caption, parse_mode=ParseMode.MARKDOWN)
async def reload_prof(call: types.CallbackQuery): chat, mess = call.from_user.id, call.message.message_id num = await db.get_counts(chat) try: await bot.edit_message_media(types.InputMediaPhoto( prof, profT.format(call.from_user.full_name, num[0])), chat, mess, reply_markup=profMark) except: await bot.answer_callback_query( call.id, text= f'Обновлено✅\n\nКогда прогноз будет готов я тебе напишу\n\nОсталось прогнозов: {num[0]}', show_alert=True)
async def publish_to_channel(data): if len(data) == 4: text, photo, video, so_id = data key = None if so_id != 0: key = types.InlineKeyboardMarkup() key.add( types.InlineKeyboardButton("Специальное предложение", callback_data=f'so{so_id}')) if photo: await bot.send_photo(c.group1, photo, caption=text, reply_markup=key) elif video: await bot.send_video(c.group1, video, caption=text, reply_markup=key) else: text, photo_data = data photos = [types.InputMediaPhoto(photo_data[0], caption=text)] \ + [types.InputMediaPhoto(x) for x in photo_data[1:]] await bot.send_media_group(c.group1, photos)
async def account(message: types.Message): arguments = message.get_args().split() if arguments: try: account = InstaUser(arguments[0]) media = types.InputMediaPhoto(account.profile_pic_url, caption = \ account_message_text.format(account.biography, '' \ if not account.external_url else account.external_url, \ account.followed_count, account.follow_count, account.posts_count, \ f'https://instagram.com/{account.account}') ) await bot.send_media_group(message.from_user.id, [media]) except: pass
async def now(message, query=None): logging.info(f'{message.text}') try: args = argparse_now(message.text) except argparse.ArgumentError: pass if args.help: await message.reply(argparse_now.__doc__) return 0 try: stock_list = stock_query(keyword=args.keyword, filter_md5=args.md5) except IndexError: raise logging.info(f'query result:{stock_list}') if len(stock_list) == 1: buf = io.BytesIO() stock = stock_list[0] if type(stock_mix := stock_list[0]) is Stock_mix: try: time_begin, _ = get_time_range(int(message.text.split()[2])) except IndexError: time_begin = stock_mix.create_time.strftime("%Y%m%d") datetime_ref = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).strftime("%Y%m%d") # refer to last trading day stock_data, matrix_close_price = await mix_data_collector_async(stock_mix, time_begin=datetime_ref) profit_ratio, stock_profit_ratio = stock_mix.get_profit_ratio(stock_data, matrix_close_price, date_ref='latest') plot_stock_profit(stock_mix, stock_profit_ratio, title=f'{stock_mix.name} Latest return rate', #TODO add a timestamp output=buf) buf.seek(0) await message.reply_photo(buf, caption=stock_mix.code+' '+stock_mix.name+\ "\nLatest return rate: {:.2%}".format(profit_ratio[-1])) else: if stock_info := stock.company_info: stock_info = f"[INFO]({stock_info})" plot_kline(stock_data=stock.collect_data_live(), title=f'Live price of {stock.code} (UTC+8)', plot_type='line', volume=True, macd=False, output=buf) buf.seek(0) now_caption = (' '.join([stock.code, stock.name, stock_info])).replace('*', '\*') # A-share sucks! if args.md5: # Not open to user input, can only result from inline keyboard callback await query.message.edit_media(types.InputMediaPhoto(media=buf, caption=now_caption, parse_mode=ParseMode.MARKDOWN)) else: await message.reply_photo(buf, caption=now_caption, parse_mode=ParseMode.MARKDOWN)
async def take_image(message: types.Message): from models import Img def try_parse_int(s, base=10, val=False): try: return int(s, base) except ValueError: return val ln = 2 if message.get_args(): args = message.get_args().split() if len(args) != 0 and try_parse_int(args[0]): ln = int(args[0]) if not 1 <= ln <= 10: await message.reply( 'Количество изображений может быть в диапазоне от 1 до 10') return m = False i = 0 max_tries = 3 while not m and i < max_tries: try: imgs = Img.normal().order_by_raw('RAND()').limit(ln).get() media_group = [ types.InputMediaPhoto( img.resource_id if img.resource_id else img.file_url, caption= f'Author: {img.author} | Rating: {img.rating}\nTags: {" ".join(img.tags)}' ) for img in imgs ] m = await message.answer_media_group(media_group) for each, img in zip(m, imgs): if not img.resource_id and each.photo[0].file_id: img.resource_id = each.photo[0].file_id img.save() except: i += 1 if i == max_tries: await message.answer('Произошла ошибка, попробуйте позже') await asyncio.sleep(1)
async def post_all_pictures( callback_query: types.CallbackQuery, *, state: FSMContext, handled_params: tuple, locale: str, regexp: Match, **kwargs, ) -> None: try: await dp.throttle(regexp.string, rate=60) except Throttled: await callback_query.answer(_("Please try again in a minute.")) else: product = await get_product(state, *handled_params) pictures = [ types.InputMediaPhoto(picture.pic, picture.thumbnail) for picture in product.pictures ] await callback_query.message.reply_media_group(pictures) await callback_query.answer()
async def imgurize(message): im = pyimgur.Imgur(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET) im.refresh_token = IMGUR_REFRESH_TOKEN im.refresh_access_token() file_id = message.photo[-1].file_id file_obj = await bot.get_file(file_id) dest = file_obj.file_path.replace('photos/', '') await bot.download_file(file_obj.file_path, dest) await send_chat_action(message.chat.id, 'upload_photo') log.debug(f"Image uploading begin") uploaded_image = await in_thread(im.upload_image, path=dest, album=IMGUR_ALBUM_ID) log.debug(f"Image uploaded") await send_photo(message.chat.id, types.InputMediaPhoto(file_id), uploaded_image.link) await send_message(message.chat.id, "Ссылка на Imgur'е", reply_markup=gen_imgur_markup(uploaded_image.link)) os.remove(dest)
async def prognoz(call: types.CallbackQuery): chat, mess = call.from_user.id, call.message.message_id await bot.edit_message_media(types.InputMediaPhoto(pic, priceT), chat, mess, reply_markup=payMark)
async def photo_ed(message: types.Message): if (message.from_user.id in cycle): await message.photo[-1].download("images/" + str(message.from_user.id) + '.jpg') img = Image.open('images/' + str(message.from_user.id) + '.jpg') # open("images/" + str(message.from_user.id) + '.jpg', 'rb') h, w = img.size # print(img.shape) t1 = transforms.Compose([ transforms.Resize((512, 512)), # transforms.ToTensor() ]) t2 = transforms.Compose([ transforms.Resize((256, 256)), # transforms.ToTensor() ]) img = t1(img) img = model(img) img = np.transpose(img, (1, 2, 0)) img = Image.fromarray((img * 255).astype(np.uint8)) t = transforms.Compose([ transforms.Resize((w, h)), transforms.ToTensor() ]) img = t(img).numpy() img = np.transpose(img, (1, 2, 0)) img = Image.fromarray(np.uint8(img * 255)) img.save('images/' + str(message.from_user.id) + '.jpg') img2 = t2(img) img2 = model2(img2) img2 = np.transpose(img2, (1, 2, 0)) img2 = Image.fromarray((img2 * 255).astype(np.uint8)) t = transforms.Compose([ transforms.Resize((w, h)), transforms.ToTensor() ]) img2 = t(img2).numpy() img2 = np.transpose(img2, (1, 2, 0)) img2 = Image.fromarray(np.uint8(img2 * 255)) img2.save('images/' + str(message.from_user.id) + '_2.jpg') img_ = open('images/' + str(message.from_user.id) + '.jpg', 'rb') img_2 = open('images/' + str(message.from_user.id) + '_2.jpg', 'rb') media = [types.InputMediaPhoto(img_, "Преобразованное фото"), types.InputMediaPhoto(img_2)] await bot.send_media_group(message.from_user.id, media) cycle.remove(message.from_user.id) os.remove("images/" + str(message.from_user.id) + '.jpg') elif (message.from_user.id in styles): await message.photo[-1].download("images/" + str(message.from_user.id) + '.jpg') styles.remove(message.from_user.id) styles_.add(message.from_user.id) await message.answer("Принято! Отправь еще фотку стиля, который нужно перенести.") elif (message.from_user.id in styles_): await message.photo[-1].download("images/" + str(message.from_user.id) + 'style.jpg') # img = Image.open('images/' + str(message.from_user.id) + '.jpg') await message.answer("Отлично! Осталось подождать 5-10 минут и бот пришлет результат.") #async def asynctransf(): nm = StyleTransfer("images/" + str(message.from_user.id) + '.jpg', "images/" + str(message.from_user.id) + 'style.jpg') x = nm.getRes() x = Image.fromarray((x.detach().numpy().squeeze(0).transpose((1, 2, 0)) * 255).astype(np.uint8)) x.save("images/" + str(message.from_user.id) + '.jpg') with open('images/' + str(message.from_user.id) + '.jpg', 'rb') as img_: await bot.send_photo(message.from_user.id, img_, caption="Преобразованное фото") styles_.remove(message.from_user.id) os.remove("images/" + str(message.from_user.id) + '.jpg') os.remove("images/" + str(message.from_user.id) + 'style.jpg') #await asynctransf() #pool = ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) #loop = asyncio.get_event_loop() #loop.run_in_executor(pool, asynctransf) #loop.close() else: await message.answer( "Ой, ты не выбрал, что хочешь сделать с картинкой. Введи /start и выбери на клавиатуре действие!")
async def process_group_command(message: types.Message): media = [types.InputMediaPhoto('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTdHGQK-txQEVDsQbodeD6OCm2d43X2gATUthchIBs0vvTHDD2yJ9kvQjUWKFk&s', caption='<b>apapap</b>', parse_mode=types.ParseMode.HTML)] media.append(types.InputMediaPhoto('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTdHGQK-txQEVDsQbodeD6OCm2d43X2gATUthchIBs0vvTHDD2yJ9kvQjUWKFk&s')) await bot.send_media_group(message.from_user.id, media)
async def searching(c: types.CallbackQuery, state: FSMContext): data_comm = c.data[:4] data_prof = c.data[5:] if data_comm == 'like' or data_comm == 'pass': if data_comm == "like": # check @user if not c.message.chat.username: return await c.message.edit_text('У тебя нет @username!', reply_markup=await KEY.search(None)) get_profile = dict(await PG.user_info_by_id(data_prof)) my_profile = dict(await PG.user_info(c.message.chat.id)) await MongoDB.update_bucket( chat=get_profile['chat_id'], bucket={str(my_profile["id"]): "liked"}) await bot.send_photo( get_profile['chat_id'], photo=income_picture, caption="Кажется ты кому-то нравишься!\n" "Чтобы узнать кому, открой анкету по кнопке внизу:", reply_markup=await KEY.liked(str(my_profile['id']))) await MongoDB.update_bucket(bucket={data_prof: data_comm}, chat=c.message.chat.id) await c.message.edit_reply_markup( reply_markup=await KEY.profile_status(data_comm)) prof = await PG.search_profile( c.message.chat.id, await MongoDB.get_bucket(chat=c.message.chat.id)) await asyncio.sleep(1) if prof: prof_id = str(dict(prof)['id']) await state.update_data(watched_profile=prof_id) await c.message.answer_photo(f"{dict(prof)['photo_id']}", caption=await TEXTS.profile(prof, c.message.chat.id), reply_markup=await KEY.search(prof_id)) else: await state.reset_data() await MongoDB.set_bucket(chat=c.message.chat.id, bucket={}) await c.message.answer(await TEXTS.profile(prof, c.message.chat.id), reply_markup=await KEY.search(prof)) elif data_comm == 'seen' or data_comm == 'mess': if not c.message.chat.username: return await c.message.edit_caption( 'У тебя нет ссылки @username! Чтобы открыть профиль, тебе необходимо иметь' ' эту ссылку. Её можно сделать в настройках профиля Telegram.', reply_markup=await KEY.liked(data_prof)) mes_for_you = '' get_profile = await PG.user_info_by_id(data_prof) await asyncio.sleep(1) if data_comm == 'mess': bucket = await MongoDB.get_bucket(chat=c.message.chat.id) mes_for_you = f'\n\nСообщение для тебя: {bucket[data_prof]}' media = types.InputMediaPhoto( dict(get_profile)['photo_id'], caption=await TEXTS.profile(get_profile, c.message.chat.id) + mes_for_you) await c.message.edit_media(media, reply_markup=await KEY.profile_income(data_prof)) elif data_comm == "send": await c.message.edit_caption( 'Введи сообщение которое ты хочешь отправить.\nМаксимальная длина сообщения - 200.' ) await Profile.like_message.set() elif data_comm == 'yess' or data_comm == 'nope': await c.message.edit_reply_markup( reply_markup=await KEY.profile_income_status(data_comm)) if data_comm == 'yess': get_profile = await PG.user_info_by_id(data_prof) get_chat_tg = await bot.get_chat(dict(get_profile)['chat_id']) await asyncio.sleep(1) if not get_chat_tg.username: return await c.message.answer( 'Хм... Прости, но у юзера отсутствует @username. Он будет наказан!' ) prof = await PG.user_info(c.message.chat.id) await bot.send_photo( dict(get_profile)['chat_id'], photo=dict(prof)['photo_id'], caption=await TEXTS.profile(prof, c.message.chat.id) + f"\n\nЕсть взаимность! Добавляй: @{c.message.chat.username}") await c.message.edit_caption( await TEXTS.profile(get_profile, c.message.chat.id) + f'\n\nДобавляй: @{get_chat_tg.username}') elif data_comm == 'back': try: await c.message.edit_text('А пока...') except BadRequest: await c.message.edit_reply_markup( reply_markup=await KEY.profile_status(data_comm)) await asyncio.sleep(1) key = types.ReplyKeyboardMarkup(resize_keyboard=True) key.add('Моя анкета') await c.message.answer( 'Подождем, пока кто-нибудь увидит твою анкету...', reply_markup=key)
async def rules(call: types.CallbackQuery): chat, mess = call.from_user.id, call.message.message_id await bot.edit_message_media(types.InputMediaPhoto(rulesPic, rulesTex), chat, mess, reply_markup=back)
from aiogram import types from .dataset import AUDIO, ANIMATION, \ DOCUMENT, PHOTO, VIDEO WIDTH = 'width' HEIGHT = 'height' input_media_audio = types.InputMediaAudio(types.Audio(**AUDIO)) input_media_animation = types.InputMediaAnimation(types.Animation(**ANIMATION)) input_media_document = types.InputMediaDocument(types.Document(**DOCUMENT)) input_media_video = types.InputMediaVideo(types.Video(**VIDEO)) input_media_photo = types.InputMediaPhoto(types.PhotoSize(**PHOTO)) def test_field_width(): """ https://core.telegram.org/bots/api#inputmedia """ assert not hasattr(input_media_audio, WIDTH) assert not hasattr(input_media_document, WIDTH) assert not hasattr(input_media_photo, WIDTH) assert hasattr(input_media_animation, WIDTH) assert hasattr(input_media_video, WIDTH) def test_field_height(): """ https://core.telegram.org/bots/api#inputmedia """ assert not hasattr(input_media_audio, HEIGHT)