async def catch_youtube_dldata(c, q): filename = None cb_data = q.data.strip() # Callback Data Check yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation filext = "%(title)s.%(ext)s" userdir = os.path.join(os.getcwd(), "downloads", str(q.message.chat.id)) if not os.path.isdir(userdir): os.makedirs(userdir) await q.edit_message_reply_markup( InlineKeyboardMarkup([[InlineKeyboardButton("Downloading...", callback_data="down")]])) filepath = os.path.join(userdir, filext) # await q.edit_message_reply_markup([[InlineKeyboardButton("Processing..")]]) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio( media=filename, caption=os.path.basename(filename), title=os.path.basename(filename) ) if cb_data.startswith("video"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo( media=filename, duration=dur, caption=os.path.basename(filename), supports_streaming=True ) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument( media=filename, caption=os.path.basename(filename), ) if cb_data.startswith("docvideo"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument( media=filename, caption=os.path.basename(filename), ) if med: loop.create_task(send_file(c, q, med, filename)) else: print("med not found")
async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") LOGGER.info(thumbnail_location) # try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "starting upload of {}".format( os.path.basename(local_file_name))) if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds # width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) else: thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), (duration / 2)) # get the correct width, height, and duration for videos greater than 10MB if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # resize image # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaAudio(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: sent_message = await message.reply_audio( audio=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) else: thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html") # quote=True, ) else: sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("trying to upload", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) except Exception as e: await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() os.remove(local_file_name) return sent_message
async def catch_youtube_dldata(c, q): thumb_image_path = os.getcwd() + "/" + "thumbnails" + "/" + str( q.from_user.id) + ".jpg" yt_thumb_image_path = os.getcwd() + "/" + "YouTubeThumb" + "/" + str( q.from_user.id) + ".jpg" if os.path.exists(thumb_image_path): thumb_image = thumb_image_path else: thumb_image = yt_thumb_image_path file_name = str(Config.PRE_FILE_TXT) cb_data = q.data # Callback Data Check (for Youtube formats) if cb_data.startswith(("video", "audio", "docaudio", "docvideo")): yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation new_filext = "%(title)s.%(ext)s" filext = file_name + new_filext saved_file_path = os.path.join(os.getcwd(), "downloads", str(q.message.chat.id)) if not os.path.isdir(saved_file_path): os.makedirs(saved_file_path) dl_folder = [f for f in os.listdir(saved_file_path)] for f in dl_folder: try: os.remove(os.path.join(saved_file_path, f)) except IndexError: pass await q.edit_message_text(text=Translation.DOWNLOAD_START) filepath = os.path.join(saved_file_path, filext) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl ] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio(media=filename, caption=os.path.basename(filename), title=os.path.basename(filename), thumb=thumb_image) if cb_data.startswith("video"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo(media=filename, duration=dur, caption=os.path.basename(filename), thumb=thumb_image, supports_streaming=True) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument(media=filename, caption=os.path.basename(filename), thumb=thumb_image) if cb_data.startswith("docvideo"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument(media=filename, caption=os.path.basename(filename), thumb=thumb_image) if med: loop.create_task(send_file(c, q, med)) else: print("med not found") ######################################### CB Data query for Bot Settings ############################################### else: # Callback Data Check (for bot settings) if cb_data.startswith(("help", "view_thumb", "close", "start", "thumb_del_conf", "del_sure")): if cb_data.startswith("help"): await help_me(c, q) if cb_data.startswith("close"): await close_button(c, q) if cb_data.startswith("view_thumb"): await view_thumbnail(c, q) if cb_data.startswith("start"): await start_bot(c, q) if cb_data.startswith("thumb_del_conf"): await del_thumb_confirm(c, q) if cb_data.startswith("del_sure"): await delete_thumbnail(c, q)
async def catch_youtube_dldata(c, q): cb_data = q.data.strip() #print(q.message.chat.id) # Callback Data Check yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] thumb_image_path = "/app/downloads" + \ "/" + str(q.message.chat.id) + ".jpg" print(thumb_image_path) if os.path.exists(thumb_image_path): width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) #print(metadata) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") img = Image.open(thumb_image_path) if cb_data.startswith(("audio", "docaudio", "docvideo")): img.resize((320, height)) else: img.resize((90, height)) img.save(thumb_image_path, "JPEG") # print(thumb_image_path) if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation filext = "%(title)s.%(ext)s" userdir = os.path.join(os.getcwd(), "downloads", str(q.message.chat.id)) if not os.path.isdir(userdir): os.makedirs(userdir) await q.edit_message_reply_markup( InlineKeyboardMarkup( [[InlineKeyboardButton("Downloading...", callback_data="down")]])) filepath = os.path.join(userdir, filext) # await q.edit_message_reply_markup([[InlineKeyboardButton("Processing..")]]) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl ] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio(media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), title=os.path.basename(filename)) if cb_data.startswith("video"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo(media=filename, duration=dur, width=width, height=height, thumb=thumb_image_path, caption=os.path.basename(filename), supports_streaming=True) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument( media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), ) if cb_data.startswith("docvideo"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument( media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), ) if med: loop.create_task(send_file(c, q, med, filename)) else: print("med not found")
async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = None start_time = time.time() # thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg") LOGGER.info(thumbnail_location) dyna_user_config_upload_as_doc = False for key in iter(user_specific_config): if key == from_user: dyna_user_config_upload_as_doc = user_specific_config[ key].upload_as_doc LOGGER.info(f'Found dyanamic config for user {from_user}') # if UPLOAD_AS_DOC.upper() == 'TRUE' or dyna_user_config_upload_as_doc: thumb_image_path = None if thumbnail_location is not None and os.path.exists( thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) if thumb_image_path is not None and os.path.exists(thumb_image_path): Image.open(thumb_image_path).convert("RGB").save(thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((32, 32)) img.save(thumb_image_path, "JPEG") thumb = None if thumb_image_path is not None and os.path.isfile(thumb_image_path): thumb = thumb_image_path message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "<b>Starting Upload 📤</b>\n\n<b>File Name :</b> <code>{}</code>" .format(os.path.basename(local_file_name))) sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("<b>Trying To Upload....📤</b>", message_for_progress_display, start_time)) if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() os.remove(local_file_name) else: try: message_for_progress_display = message if not edit_media: message_for_progress_display = await message.reply_text( "<b>Starting Upload 📤</b>\n\n<b>File Name :</b> <code>{}</code>" .format(os.path.basename(local_file_name))) if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds width = 0 height = 0 thumb_image_path = None if os.path.exists(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) else: LOGGER.info("Taking Screenshot") thumb_image_path = await take_screen_shot( local_file_name, os.path.dirname(os.path.abspath(local_file_name)), math.floor(duration / 2)) # get the correct width, height, and duration for videos greater than 10MB if thumb_image_path is not None and os.path.isfile( thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save( thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails # thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send video if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaVideo(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", width=width, height=height, duration=duration, supports_streaming=True) # quote=True, ) else: sent_message = await message.reply_video( video=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, width=width, height=height, thumb=thumb, supports_streaming=True, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("<b>Trying To Upload....📤</b>", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) elif local_file_name.upper().endswith( ("MP3", "M4A", "M4B", "FLAC", "WAV")): metadata = extractMetadata(createParser(local_file_name)) duration = 0 title = "" artist = "" if metadata.has("duration"): duration = metadata.get('duration').seconds if metadata.has("title"): title = metadata.get("title") if metadata.has("artist"): artist = metadata.get("artist") thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # send audio if edit_media and message.photo: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) sent_message = await message.edit_media( media=InputMediaAudio(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title) # quote=True, ) else: sent_message = await message.reply_audio( audio=local_file_name, # quote=True, caption=caption_str, parse_mode="html", duration=duration, performer=artist, title=title, thumb=thumb, disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("<b>Trying To Upload....📤</b>", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) else: thumb_image_path = None if os.path.isfile(thumbnail_location): thumb_image_path = await copy_file( thumbnail_location, os.path.dirname(os.path.abspath(local_file_name))) # if a file, don't upload "thumb" # this "diff" is a major derp -_- 😔😭😭 thumb = None if thumb_image_path is not None and os.path.isfile( thumb_image_path): thumb = thumb_image_path # # send document if edit_media and message.photo: sent_message = await message.edit_media( media=InputMediaDocument(media=local_file_name, thumb=thumb, caption=caption_str, parse_mode="html") # quote=True, ) else: sent_message = await message.reply_document( document=local_file_name, # quote=True, thumb=thumb, caption=caption_str, parse_mode="html", disable_notification=True, # reply_to_message_id=message.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=("<b>Trying To Upload....📤</b>", message_for_progress_display, start_time)) if thumb is not None: os.remove(thumb) except Exception as e: await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) LOGGER.exception(e) else: if message.message_id != message_for_progress_display.message_id: await message_for_progress_display.delete() os.remove(local_file_name) return sent_message
def poll_user(user, user_id, client): try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) telegram_user_id = int(user_id.split(":")[1]) logging.debug("Выполняется polling пользователя c ID: {0}".format(user_id)) try: assert user['VK_TOKEN'] assert user['VK_SECRET'] except (AssertionError, KeyError, TypeError): return {"status": "ERROR", "details": "У пользователя указан неверный VK токен (или он отстутствует)"} try: assert user['VK_LP_KEY'] assert user['VK_LP_SERVER'] assert user['VK_LP_PTS'] except (AssertionError, KeyError, TypeError): logging.debug("У пользователя {0} нет данных о LongPoll сервере.".format(user_id)) data = {"need_pts": 1, "lp_version": 3, "access_token": user['VK_TOKEN'], "v": 5.92} response_lps = requests.post("https://api.vk.com/method/messages.getLongPollServer", data=sign_data(data, "messages.getLongPollServer", user['VK_SECRET'])).json() logging.debug("Ответ на запрос метода messages.getLongPollServer: " + str(response_lps)) response_lps = response_lps['response'] user['VK_LP_KEY'] = response_lps['key'] user['VK_LP_SERVER'] = response_lps['server'] user['VK_LP_PTS'] = response_lps['pts'] asyncio.get_event_loop().run_until_complete( redis.execute("HSET", user_id, "VK_LP_KEY", response_lps['key'], "VK_LP_SERVER", response_lps['server'], "VK_LP_PTS", response_lps['pts'])) data = {"key": user['VK_LP_KEY'], "server": user['VK_LP_SERVER'], "pts": user['VK_LP_PTS'], "fields": "screen_name", "mode": 2, "lp_version": 3, "access_token": user['VK_TOKEN'], "v": 5.92} response_lph = requests.post("https://api.vk.com/method/messages.getLongPollHistory", data=sign_data(data, "messages.getLongPollHistory", user['VK_SECRET'])).json() logging.debug("Ответ на запрос метода messages.getLongPollHistory: " + str(response_lph)) response_lph = response_lph['response'] for message in response_lph['messages']['items']: if int(message['out']) == 1: continue message_id = "{0}_{1}".format(message['peer_id'], message['conversation_message_id']) # Проверяем сообщение на наличие вложений в сообщении media = [] # TODO: Добавить chat_action (загрузка видео, аудио) for attachment in message['attachments']: if attachment['type'] == "photo": photo_sorted_sizes = sorted(attachment['photo']['sizes'], key=itemgetter('width')) with NamedTemporaryFile(suffix=".jpg", delete=False) as photo: photo.write(requests.get(photo_sorted_sizes[-1]['url'], stream=True).content) media.extend([InputMediaPhoto(photo.name)]) if attachment['type'] == "video": # Получаем видео, которое сможем загрузить при лимите в 1.5 ГБ video_url = None for video_quality in attachment['video']['files']: if video_quality == "hls" or video_quality == "external": continue video_size = int(requests.get(attachment['video']['files'][video_quality], stream=True). headers['Content-length']) if video_size < 1500 * 1024 * 1024: video_url = attachment['video']['files'][video_quality] if not video_url: continue video_hash = sha1(video_url.split("?extra")[0].encode("UTF-8")).hexdigest() video = asyncio.get_event_loop().run_until_complete( hgetall("files:telegram:video:{0}".format(video_hash))) if not video: logging.debug("Видео ({0}) не найдено в кэше, загружается новое.".format(video_hash)) with NamedTemporaryFile(suffix=".mp4") as video_file: logging.debug("Видео ({0}) сохраняется во временный файл {1}.".format( video_hash, video_file.name)) video_file.write(requests.get(video_url, stream=True).content) # Отправляем видео и сразу удаляем (это необходимо, чтобы получить File ID видео) video_message = client.send_video(telegram_user_id, video_file.name, disable_notification=True) client.delete_messages(telegram_user_id, video_message.message_id) video['FILE_ID'] = video_message.video.file_id video['CAPTION'] = attachment['video']['title'] asyncio.get_event_loop().run_until_complete(redis.execute( "HSET", "files:telegram:video:{0}".format(video_hash), "FILE_ID", video['FILE_ID'], "CAPTION", video['CAPTION'])) media.extend([InputMediaVideo(video['FILE_ID'], caption=video['CAPTION'])]) # TODO: Добавить поддержку плейлистов (корректное отображение) if attachment['type'] == "audio": audio_hash = sha1(attachment['audio']['url'].encode("UTF-8")).hexdigest() audio = asyncio.get_event_loop().run_until_complete( redis.execute("HGET", "files:telegram:audio:{0}".format(audio_hash), "FILE_ID"))['details'] # В Redis нет смысла сохранять исполнителя и название песни, так как при последующей отправке по # File ID, данные об исполнителе и названии песни остаются. if audio: logging.debug("Аудио ({0}) находится в кэше, отправляется по File ID.".format(audio_hash)) client.send_audio(telegram_user_id, audio) else: logging.debug("Аудио ({0}) не найдено в кэше, загружается новое.".format(audio_hash)) # VK может вернуть пустое URL, проверяем это сначала if not attachment['audio']['url']: logging.debug("Аудио, которое было отправлено пользователю, не может быть загружено, " "так как в нем не содержится ссылки (скорее всего, оно защищено " "авторскими правами и может воспроизводиться только из РФ).") client.send_message(telegram_user_id, "❗ Аудио ({0} — {1}) не может быть отправлено вам, так как " "оно защищено авторскими правами и может воспроизводиться только с " "территории Российской Федерации.".format( attachment['audio']['title'], attachment['audio']['artist'])) continue with NamedTemporaryFile(suffix=".mp3") as audio_file: logging.debug("Аудио ({0}) сохраняется во временный файл {1}.".format( audio_hash, audio_file.name)) audio_file.write(requests.get(attachment['audio']['url'], stream=True).content) audio = client.send_audio(telegram_user_id, audio_file.name, performer=attachment['audio']['artist'], title=attachment['audio']['title']).audio.file_id asyncio.get_event_loop().run_until_complete( redis.execute("HSET", "files:telegram:audio:{0}".format(audio_hash), "FILE_ID", audio)) if attachment['type'] == "sticker": sticker_hash = sha1(attachment['sticker']['images'][4]['url'].encode("UTF-8")).hexdigest() sticker = asyncio.get_event_loop().run_until_complete( redis.execute("HGET", "files:telegram:sticker:{0}".format(sticker_hash), "FILE_ID"))['details'] if sticker: logging.debug("Стикер ({0}) находится в кэше, отправляется по File ID.".format(sticker_hash)) client.send_sticker(telegram_user_id, sticker) else: logging.debug("Стикер ({0}) не найден в кэше, загружается новый.".format(sticker_hash)) sticker_png = Image.open( BytesIO(requests.get(attachment['sticker']['images'][4]['url'], stream=True).content)) with NamedTemporaryFile() as sticker_file: logging.debug("Стикер ({0}) сохраняется во временный файл {1}.".format( sticker_hash, sticker_file.name)) sticker_png.save(sticker_file, format="WEBP", lossless=True, quality=100, method=6) sticker = client.send_sticker(telegram_user_id, sticker_file.name).sticker.file_id asyncio.get_event_loop().run_until_complete( redis.execute("HSET", "files:telegram:sticker:{0}".format(sticker_hash), "FILE_ID", sticker)) if attachment['type'] == "audio_message": with NamedTemporaryFile(suffix=".ogg") as voice_message_file: logging.debug("Голосовое сообщение сохраняется во временный файл {0}.".format( voice_message_file.name)) voice_message_file.write( requests.get(attachment['audio_message']['link_ogg'], stream=True).content) client.send_voice(telegram_user_id, voice_message_file.name) # Проверяем, есть ли какое-то медиа (фотографии, видео) if media: client.send_media_group(telegram_user_id, media) sender = [sender for sender in response_lph['profiles'] if sender['id'] == message['from_id']][0] formatted_message_text = markup_multipurpose_fixes(message['text']) message_text = "**{0} {1}**{2}".format(sender['first_name'], sender['last_name'], # Если есть текст в сообщении, то добавляем его в сообщении "\n\n" + formatted_message_text if formatted_message_text else "") markup = InlineKeyboardMarkup([[InlineKeyboardButton("📋 Подробнее", callback_data=b"TEST")]]) message_data = client.send_message(telegram_user_id, message_text, reply_markup=markup) asyncio.get_event_loop().run_until_complete( redis.execute("SET", "message:telegram:{0}_{1}".format(message_data.chat.id, message_data.message_id), message_id) ) asyncio.get_event_loop().run_until_complete(redis.execute("HSET", user_id, "VK_LP_PTS", response_lph['new_pts'])) return {"status": "OK", "details": None} except Exception as e: logging.error("Произошла ошибка при polling'е аккаунта VK пользователя {0}.".format(user_id), exc_info=True) return e