def telegram_bot_sendGroupMedia(bot_pic_URLs, id, listingNumber): try: imgArray = [] bot_chatID = str(id) #Attach image URLs for idx, url in enumerate(bot_pic_URLs): if idx == 0: photo = telegram.InputMediaPhoto( media=url, caption="---------- End of listing " + str(listingNumber) + " ----------", parse_mode="markdown") else: photo = telegram.InputMediaPhoto(media=url, caption=None, parse_mode="markdown") imgArray.append(photo) photo1 = telegram.InputMediaPhoto(media=open('Images/map.jpg', 'rb'), caption=None) imgArray.append(photo1) response = bot.sendMediaGroup(chat_id=bot_chatID, media=imgArray, disable_notification=True) except Exception as ex: print("Telegram group photo error...")
def dmmphoto(update, context): searchid = context.args[0] #chat_id = update.message.chat_id list_of_urls = prephotos(searchid) if list_of_urls == []: if len(context.args) == 1: searchidd = context.args[0] searchidd = searchidd.replace('-',' ') else: searchidd = ' '.join(context.args[:]) boxlist,stitle = dmmsearch(searchidd,'onlysearch') if boxlist == '選択した条件で商品は存在しませんでした': update.message.reply_text('没有找到 %s 预览图片'%searchid) return #print(boxlist) firstlist = boxlist[0] wcid = firstlist.get('cid') list_of_urls = prephotos(wcid) if len(list_of_urls)<=10: media_group = [] for number, url in enumerate(list_of_urls): media_group.append(telegram.InputMediaPhoto(media=url, caption="Turtle" + str(number))) update.message.reply_media_group(media=media_group) else: list_of_urls = split_list(list_of_urls,10) for i in list_of_urls: media_group = [] for number, url in enumerate(i): #print(telegram.InputMediaPhoto(media=url, caption="Photos" + str(number))) media_group.append(telegram.InputMediaPhoto(media=url, caption="Photos" + str(number))) #print(media_group) update.message.reply_media_group(media=media_group)
def _push_photos(self, paths, caption): try: tmp = 0 media_list = [] for p in paths: if tmp >= 10: self._bot.send_media_group(self.chat_id, media_list, timeout=DEFAULT_TIMEOUT) tmp = 0 media_list.clear() # set caption property only for the first element of an array if len(media_list) == 0: media_list.append( telegram.InputMediaPhoto(open(p, "rb"), caption=caption)) else: media_list.append(telegram.InputMediaPhoto(open(p, "rb"))) tmp += 1 self._bot.send_media_group(self.chat_id, media_list, timeout=DEFAULT_TIMEOUT) except telegram.error.BadRequest as e: logging.warning("bad requeset with error message: " + e.message) for p in paths: self._bot.send_document(self.chat_id, open(p, 'rb'))
def broadcastMessage(self, msg, parse_mode=None, reply_markup=None, include_images=False): for chat_id in self.valid_chat_ids: self.updater.bot.send_message(chat_id=chat_id, text=msg, parse_mode=parse_mode, reply_markup=reply_markup) if include_images: cameras = self.config.get('cameras', []) print("= Send warning images for {} cameras".format(len(cameras))) media = [] for camera in cameras: try: r = requests.get(camera['url'], auth=HTTPDigestAuth( camera['auth'][0], camera['auth'][1])) fp = BytesIO(r.content) media.append(telegram.InputMediaPhoto(fp)) except Exception as e: print("error fetching for camera: {}".format( camera['url'])) print(e) if len(media) > 1: for chat_id in self.valid_chat_ids: self.updater.bot.send_media_group(chat_id=chat_id, media=media, parse_mode=parse_mode)
def update_plot(self, message: telegram.Message, plt, name: str = None): """ Update plot function. Arguments: message : Message to update plt : New plot to send name : Name of the temporary file """ if not os.path.exists(self.tmp_dir): os.makedirs(self.tmp_dir) if name is None: ts = int(time.time()) img_path = self.tmp_dir + str(ts) + '.png' else: img_path = self.tmp_dir + name plt.savefig(img_path, dpi=100) new_media = telegram.InputMediaPhoto(open(img_path, 'rb')) try: message.edit_media(new_media) except Exception as e: pass
def echo(update, context): # search link based on input text with open('googling.json') as f: apis = json.load(f) page = [j for j in range(10)] shuffle(page) for i in page: try: # link search_link = "https://customsearch.googleapis.com/customsearch/v1?cx={0}&imgSize=LARGE&num=10&q={1}&searchType=image&start={3}&key={2}".format( apis['cx'], update.message.text, apis['key'], i * 10 + 1) # get images res = rqs.get(search_link) if res.status_code != 200: raise # get photos urls from response json photos = [] search_photos = json.loads(res.text) for photo in search_photos["items"]: photos.append(telegram.InputMediaPhoto(media=photo["link"])) # send album of photos context.bot.send_media_group(chat_id=update.effective_chat.id, media=photos) except telegram.TelegramError as e: logging.info("Problem with telegram: %s" % e) else: break else: context.bot.send_message(chat_id=update.effective_chat.id, text='Seems to be nothing?')
async def sent_telegram(message: schemas.TelegramMessage): bot = telegram.Bot(token=os.getenv('TG_BOT_TOKEN')) # bot_all = telegram.Bot(token=os.getenv('TG_BOT_TOKEN_ALL')) media_array = [] for image in message.images: media_array.append( telegram.InputMediaPhoto(image.url, caption=image.caption)) media_array_split = [ media_array[i:i + 10] for i in range(0, len(media_array), 10) ] ret = bot.send_message( chat_id=message.chat_id, text=message.message, parse_mode=telegram.ParseMode.HTML, timeout=message.timeout, disable_web_page_preview=message.disable_web_page_preview, ) for small_array in media_array_split: bot.send_media_group( chat_id=message.chat_id, media=small_array, timeout=message.timeout, ) return ret
def send_gallery(self, dict_of_dicts_of_pics, text): self.send_text(text) long_sleep() cnt = 0 for k, dict_of_pics in dict_of_dicts_of_pics.items(): list_of_items_in_one_group = list() for item in sorted(dict_of_pics.items(), key=lambda item: item[0]): if item[1]['type'] == 'pic': list_of_items_in_one_group.append( telegram.InputMediaPhoto(item[1]['url'])) elif item[1]['type'] == 'video': list_of_items_in_one_group.append( telegram.InputMediaVideo(item[1]['url'])) else: logging.error('Unkown item in gallery.') return SupplyResult.SKIP_FOR_NOW try: self.telegram_bot.send_media_group( chat_id=self.t_channel, media=list_of_items_in_one_group, timeout=66) logging.info('Successful gallery sent.') except Exception as e: logging.error('Gallery sent failed.') cnt += 1 long_sleep(cnt + 1) return SupplyResult.SUCCESSFULLY
def send_images(self, images: typing.Any) -> None: if not images: return self._bot.send_media_group( self.chat_id, media=list(telegram.InputMediaPhoto(image) for image in images), )
def button_callback(update, context): print(update.callback_query.data) if update.callback_query.message.reply_to_message.from_user == update.callback_query.from_user: args = update.callback_query.data.split('#') if args[0] == 'READ_HW': if args[1] == 'CANCEL': update.callback_query.message.delete() else: if args[1] == 'EXT': res = get_external_hw(args[2], for_today=bool(args[3])) elif args[1] == 'LOCAL': res = get_local_hw(args[2], context.chat_data) if res[1]: req_msg = update.callback_query.message.reply_to_message update.callback_query.message.delete() photo_objs = [tg.InputMediaPhoto(media=res[1][0], caption=res[0])] photo_objs += [tg.InputMediaPhoto(media=i) for i in res[1][1:]] answer = req_msg.reply_media_group(media=photo_objs) else: req_msg = update.callback_query.message.reply_to_message update.callback_query.message.delete() req_msg.reply_text(text=res[0]) elif args[0] == 'WRITE_HW': if args[1] == 'CANCEL': request_msgid = update.callback_query.message.reply_to_message.message_id prev_hw = context.chat_data['temp']['hw'][request_msgid] if prev_hw: context.chat_data['hw'][args[2]] = prev_hw else: del context.chat_data['hw'][args[2]] del context.chat_data['temp']['hw'][request_msgid] update.callback_query.message.delete() elif args[0] == 'DEL_HW': if args[1] == 'CANCEL': request_msgid = update.callback_query.message.reply_to_message.message_id prev_hw = context.chat_data['temp']['hw'][request_msgid] print(prev_hw) context.chat_data['hw'][args[2]] = prev_hw del context.chat_data['temp']['hw'][request_msgid] update.callback_query.message.delete()
def get_image(self, as_media_photo=False): if not self.__image: return None if not as_media_photo: return open('files' + self.__image, "rb") else: return telegram.InputMediaPhoto(media=open('files' + self.__image, "rb"))
def view_stream_image_callback(update, CallbackContext): username = CallbackContext.match.string.replace("view_stream_image_callback_", "") chatid = update.callback_query.message.chat_id messageid = update.callback_query.message.message_id if Utils.is_chatid_temp_banned(chatid): return model_instance = Model(username) keyboard = [[InlineKeyboardButton("Watch the live", url=f'http://chaturbate.com/{username}'), InlineKeyboardButton("Update stream image", callback_data='view_stream_image_callback_' + username)]] markup = InlineKeyboardMarkup(keyboard) try: bot.edit_message_media(chat_id=chatid, message_id=messageid, media=telegram.InputMediaPhoto(model_instance.model_image,caption=f"{username} is now <b>online</b>!",parse_mode=telegram.ParseMode.HTML), reply_markup=markup) except Exceptions.ModelPrivate: send_message(chatid, f"The model {username} is in private now, try again later", bot) logging.warning(f'{chatid} could not view {username} image update because is private') except Exceptions.ModelAway: send_message(chatid, f"The model {username} is away, try again later", bot) logging.warning(f'{chatid} could not view {username} image update because is away') except Exceptions.ModelPassword: send_message(chatid, f"The model {username} cannot be seen because is password protected", bot) logging.warning(f'{chatid} could not view {username} image update because is password protected') except (Exceptions.ModelDeleted, Exceptions.ModelBanned, Exceptions.ModelGeoblocked, Exceptions.ModelCanceled, Exceptions.ModelOffline): keyboard = [[InlineKeyboardButton("Watch the live", url=f'http://chaturbate.com/{username}')]] markup = InlineKeyboardMarkup(keyboard) bot.edit_message_reply_markup(chat_id=chatid, message_id=messageid, reply_markup=markup) #remove update image button send_message(chatid, f"The model {username} cannot be seen because is {model_instance.status}", bot) logging.warning(f'{chatid} could not view {username} image update because is {model_instance.status}') except Exceptions.ModelNotViewable: send_message(chatid, f"The model {username} is not visible", bot) logging.warning(f'{chatid} could not view {username} image update') except ConnectionError: send_message(chatid, f"The model {username} cannot be seen because of connection issues, try again later", bot) logging.warning(f'{chatid} could not view {username} image update because of connection issues') except Exception as e: if hasattr(e, 'message'): if "Message is not modified" in e.message: send_message(chatid, f"This is the latest update of {username}", bot) if not Utils.admin_check(chatid): if Utils.get_last_spam_date(chatid)==None: Utils.set_last_spam_date(chatid, datetime.datetime.now()) elif (datetime.datetime.now()-Utils.get_last_spam_date(chatid)).total_seconds() <= 3: Utils.temp_ban_chatid(chatid, 25) send_message(chatid, "You have been temporarily banned for spamming, try again later", bot) logging.warning(f"Soft banned {chatid} for 25 seconds for spamming image updates") else: Utils.set_last_spam_date(chatid, datetime.datetime.now())
def save_in_telegram(twitter_msg, context): """ Saves a tweet and video in Telegram (with a archive.is link) :param twitter_msg: Twitter Status Object :param context: Telegram bot context :return: nothing """ tweet_url = "https://www.twitter.com/{}/status/{}".format( twitter_msg.user.screen_name, twitter_msg.id) logging.info("Saving tweet {}".format(tweet_url)) if twitter_msg.media is not None: saved_url = archive.save_in_archive(tweet_url) config.save_config() location = tweets.get_geo(twitter_msg) caption = "{} {}".format(saved_url, location) msg = None if saved_url is not None: # Individual file if len(twitter_msg.media) == 1: m = twitter_msg.media[0] if m.type == "photo": msg = context.bot.send_photo(config.config["telegram"]["chatid"], m.media_url_https, disable_notification=True, caption=caption) elif m.type == "video": best_variant = tweets.get_best_variant(m.video_info["variants"]) if best_variant is not None: msg = context.bot.send_video(config.config["telegram"]["chatid"], best_variant, disable_notification=True, caption=caption) elif len(twitter_msg.media) > 1: mediaArr = [] for m in twitter_msg.media: if m.type == "photo": mediaArr.append(telegram.InputMediaPhoto(media=m.media_url_https, caption=saved_url)) elif m.type == "video": best_variant = tweets.get_best_variant( m.video_info["variants"]) if best_variant is not None: mediaArr.append(telegram.InputMediaVideo(media=best_variant, caption=saved_url)) resps = context.bot.send_media_group(config.config["telegram"]["chatid"], mediaArr, disable_notification=True) if len(resps) > 0: msg = resps[0] config.config["cached"][str(twitter_msg.id)] = { "archive_url": saved_url, "telegram_url": msg.link } config.save_config() else: logging.info("error saving tweet {}") return msg
def check(): with open('pages.csv', mode='r+') as csv_file, NamedTemporaryFile(mode='w', delete=False) as tempfile: csv_reader = csv.DictReader(csv_file) csv_writer = csv.DictWriter(tempfile, fields) line_count = 0 csv_writer.writeheader() for page in csv_reader: try: posts = list(get_posts(page['page_tag'], pages=2, cookies='cookies.txt')) except OSError as err: print("Got an exception while trying to retrieve posts") traceback.print_exc() if err.errno == 101 or err.errno == 500: print("Network unreachable, waiting 5 minutes") time.sleep(300) break else: sys.exit() posts.sort(key = lambda x: int(x['post_id'])) for post in posts: if int(post['post_id']) <= int(page['last_post_used']): # post already sent to channel continue post_text = telegram.utils.helpers.escape_markdown(post['post_text'], version=2) if post['post_text'] else '' if post['shared_post_url'] is not None: shared_text = '_' + telegram.utils.helpers.escape_markdown(post['shared_text'][post['shared_text'].find('\n', post['shared_text'].find('\n')+1)+2:], version=2) + '_' if post['shared_text'] else '' message = u'\U0001F501' + ' ' + post['shared_username'] + '\n' + shared_text + '\n\n' + post_text + '\n\[' + page['page_name'] + '\]' else: message = post_text + '\n\[' + page['page_name'] + '\]' if post['images'] is not None and len(post['images']) > 0: images = [telegram.InputMediaPhoto(post['images'][0], caption=message, parse_mode=telegram.constants.PARSEMODE_MARKDOWN_V2)] for image in post['images'][1:]: images.append(telegram.InputMediaPhoto(image)) bot.send_media_group(chat_id, images) elif post['video'] is not None: bot.send_video(chat_id, post['video'], caption=message) elif post['text'] is not None: bot.send_message(chat_id, message, parse_mode=telegram.constants.PARSEMODE_MARKDOWN_V2) if len(posts) != 0: # according to facebook-scraper devs you can get 0 posts if # you get temporarily ip banned for too many requests page['last_post_used'] = posts[-1]['post_id'] row = {'page_name': page['page_name'], 'page_tag': page['page_tag'], 'last_post_used': page['last_post_used']} csv_writer.writerow(row) shutil.move(tempfile.name, 'pages.csv') threading.Timer(WAIT_SECONDS, check).start()
def search_license_plate(self, chat_id, message_id, search_query_id, page, edit): search_query = db.get_search_query(search_query_id) lp_num = search_query.query_text lp_type = search_query.num_type key = f"avtonomer.search_{lp_type}({lp_num})" result = cache.get(key) if not result: if lp_type == "ru": result = avtonomer.search_ru(lp_num) else: result = avtonomer.search_su(lp_num) if not result: bot.send_message( chat_id, "По вашему запросу ничего не найдено", reply_to_message_id=message_id, ) return cache.add(key, result, timedelta(minutes=5)) car = result.cars[page] cars_count = len(result.cars) key = f"avtonomer.load_photo({car.thumb_url})" file_id = cache.get(key) if not file_id: photo = avtonomer.load_photo(car.thumb_url) if not photo: photo = open(PHOTO_NOT_FOUND, "rb") else: photo = file_id caption = get_car_caption(car, lp_num, page, cars_count) markup = get_car_reply_markup(cars_count, search_query_id, page) if edit: message = bot.edit_message_media( media=telegram.InputMediaPhoto(photo, caption=caption), reply_markup=markup, chat_id=chat_id, message_id=message_id, ) else: message = bot.send_photo( chat_id, photo, caption, reply_to_message_id=message_id, reply_markup=markup, ) if not file_id: cache.add(key, message.photo[-1].file_id, timedelta(minutes=30))
def sendTelegramMediaGroup(chat_id, photos): imgArray = [] try: if len(photos) > 5: for i in range(0, 5): photo = telegram.InputMediaPhoto(media=open(photos[i], 'rb'), caption=None) imgArray.append(photo) else: for i in range(0, len(photos)): photo = telegram.InputMediaPhoto(media=open(photos[i], 'rb'), caption=None) imgArray.append(photo) response = bot.sendMediaGroup(chat_id=chat_id, media=imgArray, disable_notification=True) except Exception as ex: print("Telegram group photo error...") print(ex)
def sendMediaGroup(media, caption): media_to_send = [] # Append the first element with captions media_to_send.append( telegram.InputMediaPhoto(media[0], caption=caption, parse_mode=None)) # And remove from media media.pop(0) # For the other -> Append to array for element in media: media_to_send.append(telegram.InputMediaPhoto(element)) status = bot.sendMediaGroup(chat_id=chat_id, media=media_to_send) return status # status_multiple = sendMediaGroup() # print(status_multiple)
def skip_photo(update, context): chat_id = update.message.from_user media_group = [] for file_id in adoptions[chat_id]['photo']: media_group.append(telegram.InputMediaPhoto(media=file_id)) update.message.reply_text('Класс! Сейчас запостим и начнется поиск родителей! Спасибо <3') update.message.reply_text(text=parse(adoptions[chat_id]), parse_mode=telegram.ParseMode.MARKDOWN) context.bot.send_media_group(update.message.chat.id, media=media_group) return ConversationHandler.END
def send_photos(self, fnames, timeout=60): photos = [ telegram.InputMediaPhoto(open(fname, "rb")) for fname in fnames ] self.bot.send_chat_action(chat_id=self.chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) try: self.bot.send_media_group(chat_id=self.chat_id, media=photos, timeout=timeout) except telegram.error.BadRequest as e: logging.error(f"{e}. Retrying one more time...") self.send_photos(fnames, timeout=timeout)
def urlsForAlbum(urls): video_output = [] photo_output = [] for url in urls: if "mp4" in url or "gif" in url: video_output.append( telegram.InputMediaVideo(media=url['url'], caption=url['caption'])) else: photo_output.append( telegram.InputMediaPhoto(media=url['url'], caption=url['caption'])) return photo_output, video_output
def send_photo(filepath, bot, update): os.mkdir(os.path.splitext(filepath)[0]) is_w_f = False images = generate_screen_shots(filepath, os.path.splitext(filepath)[0], is_w_f, "", 150, 9) media_album_p = [] if images is not None: for image in images: with open(image, 'rb') as fp: media_album_p.append(telegram.InputMediaPhoto(media=fp)) sendGroup(media_album_p, bot, update) LOGGER.info(images)
def send_charts(): global ids data = draw_plots() for message_id in ids: bot.delete_message(chat_id=conf.chat, message_id=message_id) ids.clear() for filename in files: photos = [] for extension in extensions: if not filename == 'general_plot' or extension not in general_excluded_plots: try: with open(filename + extension, 'rb') as input_photo: photos.append( telegram.InputMediaPhoto(caption=extensions[extension], media=input_photo)) except Exception: pass media_ids = [message.message_id for message in bot.send_media_group(chat_id=conf.chat, media=photos, disable_notification=True, timeout=300)] if filename == "general_plot": ids.append( bot.send_message(chat_id=conf.chat, disable_notification=True, text="📈 <b>Grafico generale</b>", parse_mode='HTML', reply_to_message_id=media_ids[0], timeout=300).message_id) else: ids.append( bot.send_message(chat_id=conf.chat, disable_notification=True, text=("📈 <b>" + filename.replace("_", " ").title() + "</b> (" + f"{data[-1][filename]:,d}".replace(',', '.') + ", Δ=" + f"{data[-1][filename]-data[-2][filename]:,d}".replace(',', '.') + ")"), parse_mode='HTML', reply_to_message_id=media_ids[0], timeout=300).message_id) ids += media_ids
def send_album(self, photo_urls, caption=None, chat_id=USER_CHANNEL_ID, parse_mode='HTML'): """Send 2-10 photos with caption to channel""" media_group = [ telegram.InputMediaPhoto(url, parse_mode=None) for url in photo_urls ] media_group[0].caption = caption message = self.bot.send_media_group(chat_id=chat_id, media=media_group) return message
def new_post(self, post: Post): text = post.get_telegram_text() msg = self.bot.send_message( chat_id=self.channel, text=text, parse_mode='html', disable_web_page_preview=not post.get_hidden_link(), reply_markup=self.build_post_markup(post)) for title, url in post.doc: self.bot.send_document(chat_id=self.channel, document=url, filename=title) if len(post.photo) > 1: media = [telegram.InputMediaPhoto(url) for url in post.photo] self.bot.send_media_group(self.channel, media) return msg
def cleanPost(post_id, result, bot): if result is True: text = 'The post has been accepted.' elif result is False: text = 'The post has been rejected.' thisPost = globals.posts[str(post_id)] text += '\n\nAccept: {}, Reject: {}'.format(thisPost.status[0], thisPost.status[1]) if thisPost.post_method == 'text': for i in thisPost.owners: bot.edit_message_text(chat_id=i[0], message_id=i[1], text=text) elif thisPost.post_method == 'photo': media = telegram.InputMediaPhoto(open('ok.png' if result else 'no.png', 'rb'), caption=text) for i in thisPost.owners: bot.edit_message_media(chat_id=i[0], message_id=i[1], media=media) del globals.posts[str(post_id)]
def wrapper(bot: telegram.Bot, update: telegram.Update): text = '{}\n\n{}'.format(WAIT_TEXT, LOADING_URL) try: message = update.message.reply_text(text, quote=False, disable_notification=True) media = [ telegram.InputMediaPhoto(url) for url in provider.get_random_images(IMAGES_NUMBER) ] bot.send_media_group(update.message.chat.id, media, disable_notification=True) message.delete() except Exception as exc: LOGGER.error('Error occurred during processing command.\n%s"', str(exc))
def pixiv_handler(update: telegram.Update, context): """返回pixiv日榜图片""" download_tip: telegram.Message = update.message.reply_text("下载中,请稍候") # update.message.reply_photo(open('pixiv_downloads/88588799_p0.jpg','rb')) photos = [] i = 0 while i < PIXIV_SEND_NUMBER: pic = ranking.get_pic() fsize = os.path.getsize(pic) if fsize > SIZE_LIMIT: # logger.info('over size limit ==> ' + pic) continue photos.append(telegram.InputMediaPhoto(open(pic, 'rb'))) # logger.info('send ==> ' + pic) i += 1 # update.message.reply_photo(open(ranking.get_pic(), 'rb')) update.message.reply_media_group(photos) download_tip.delete()
def random(bot, update): random_post = next(posts_collection.aggregate([{"$sample": {"size": 1}}])) bot.send_message( chat_id=update.message.chat_id, text= f"<a href='{random_post['url']}'>[{datetime.utcfromtimestamp(int(random_post['date'])).strftime('%d %b %Y')}]</a> {random_post['text']}", parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True) if 'photos' in random_post: photos = [ telegram.InputMediaPhoto( media=open(f"public/{photo['url']}", "rb")) for photo in random_post['photos'] ] if len(photos) > 0: bot.send_media_group(chat_id=update.message.chat_id, media=photos[:10], disable_notification=True)
def show_first_activity(chat_id, message_id, data, chosen_hotel, activity): print("activityyyyyyyyyyyyyy: ", activity) photo = get_photo_ref(activity)[0] print("photo ", photo) if photo == 'None': photo = 'https://www.thermaxglobal.com/wp-content/uploads/2020/05/image-not-found.jpg' else: photo = SearchEngine.get_place_photos_from_reference(photo).url print("photo ", photo) keyboard = [] for hotel in data.keys(): keyboard.append(set_hotel_button(hotel, len(data.get(hotel)))) keyboard.insert(0, set_activity_buttons(activity, chosen_hotel)) reply_markup = telegram.InlineKeyboardMarkup(keyboard) telegram.Bot(TOKEN).editMessageMedia(chat_id, message_id, media=telegram.InputMediaPhoto( photo, caption=activity), reply_markup=reply_markup) return Response("success")
def __send_post(self, post): photos = [] if ('attachments' in post.keys()): for attachment in post['attachments']: if attachment['type'] == 'photo': photos.append(attachment['photo']['sizes'][-1]['url']) if ('text' in post.keys()): self.__bot.send_message(self.__bot_settings['telegram_channel_id'], post['text']) if len(photos) == 1: self.__bot.send_photo(self.__bot_settings['telegram_channel_id'], photo=photos[0], disable_notification=True) elif len(photos) > 1: media = [telegram.InputMediaPhoto(photo) for photo in photos] self.__bot.send_media_group( self.__bot_settings['telegram_channel_id'], media, disable_notification=True)