Exemple #1
0
def get_messages(client: Client, cid: int, mids: Union[int, Iterable[int]]) -> Union[Message, List[Message], None]:
    # Get some messages
    result = None

    try:
        result = client.get_messages(chat_id=cid, message_ids=mids)
    except FloodWait as e:
        raise e
    except PeerIdInvalid:
        return None
    except Exception as e:
        logger.warning(f"Get messages {mids} in {cid} error: {e}", exc_info=True)

    return result
def get_messages(client: Client, cid: int, mids: Iterable[int]) -> Optional[List[Message]]:
    # Get some messages
    result = None
    try:
        flood_wait = True
        while flood_wait:
            flood_wait = False
            try:
                result = client.get_messages(chat_id=cid, message_ids=mids)
            except FloodWait as e:
                flood_wait = True
                wait_flood(e)
    except Exception as e:
        logger.warning(f"Get messages {mids} in {cid} error: {e}", exc_info=True)

    return result
class TelegramDownloadHelper(DownloadHelper):
    def __init__(self, listener):
        super().__init__()
        self.__listener = listener
        self.__resource_lock = threading.RLock()
        self.__name = ""
        self.__gid = ''
        self.__start_time = time.time()
        self.__user_bot = Client(api_id=TELEGRAM_API,
                                 api_hash=TELEGRAM_HASH,
                                 session_name=USER_SESSION_STRING)
        self.__user_bot.start()
        self.__is_cancelled = False

    @property
    def gid(self):
        with self.__resource_lock:
            return self.__gid

    @property
    def download_speed(self):
        with self.__resource_lock:
            return self.downloaded_bytes / (time.time() - self.__start_time)

    def __onDownloadStart(self, name, size, file_id):
        with download_dict_lock:
            download_dict[self.__listener.uid] = TelegramDownloadStatus(
                self, self.__listener)
        with global_lock:
            GLOBAL_GID.add(file_id)
        with self.__resource_lock:
            self.name = name
            self.size = size
            self.__gid = file_id
        self.__listener.onDownloadStarted()

    def __onDownloadProgress(self, current, total):
        if self.__is_cancelled:
            self.__onDownloadError('Cancelled by user!')
            self.__user_bot.stop_transmission()
            return
        with self.__resource_lock:
            self.downloaded_bytes = current
            try:
                self.progress = current / self.size * 100
            except ZeroDivisionError:
                self.progress = 0

    def __onDownloadError(self, error):
        with global_lock:
            try:
                GLOBAL_GID.remove(self.gid)
            except KeyError:
                pass
        self.__listener.onDownloadError(error)

    def __onDownloadComplete(self):
        with global_lock:
            GLOBAL_GID.remove(self.gid)
        self.__listener.onDownloadComplete()

    def __download(self, message, path):
        download = self.__user_bot.download_media(
            message, progress=self.__onDownloadProgress, file_name=path)
        if download is not None:
            self.__onDownloadComplete()
        elif not self.__is_cancelled:
            self.__onDownloadError('Internal error occurred')

    def add_download(self, message, path):
        _message = self.__user_bot.get_messages(message.chat.id,
                                                message.message_id)
        media = None
        media_array = [_message.document, _message.video, _message.audio]
        for i in media_array:
            if i is not None:
                media = i
                break
        if media is not None:
            with global_lock:
                # For avoiding locking the thread lock for long time unnecessarily
                download = media.file_id not in GLOBAL_GID

            if download:
                self.__onDownloadStart(media.file_name, media.file_size,
                                       media.file_id)
                LOGGER.info(
                    f'Downloading telegram file with id: {media.file_id}')
                threading.Thread(target=self.__download,
                                 args=(_message, path)).start()
            else:
                self.__onDownloadError('File already being downloaded!')
        else:
            self.__onDownloadError('No document in the replied message')

    def cancel_download(self):
        LOGGER.info(f'Cancelling download on user request: {self.gid}')
        self.__is_cancelled = True
Exemple #4
0
def delete_inline_kb(cli: Client, tg_id: int, msg_id: int):
    try:
        msg = cli.get_messages(tg_id, msg_id)
        msg.edit(msg.text)
    except:
        pass
from os import environ
import logging
from pyrogram import Client
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

API_ID = environ.get("TEST_TL_API_ID")
API_HASH = environ.get("TEST_TL_API_HASH")

app = Client("my_account", api_id=API_ID, api_hash=API_HASH)

app.start()
print(app.get_me())

user = "******"
res = app.send_message(user, "/start")
m = app.get_messages(res["chat"]["id"], [res["message_id"] + 1])
print("replies=========\n", m[-1])
app.stop()
Exemple #6
0
            elif media_type == "sticker":
                app.send_sticker(chat_id=chat_id, sticker=ffile, reply_to_message_id=reply_id)
            elif media_type == "video":
                app.send_chat_action(chat_id=chat_id, action=ChatAction.RECORD_VIDEO)
                app.send_video(chat_id=chat_id, video=ffile, reply_to_message_id=reply_id, caption=caption)
            elif media_type == "video_note":
                app.send_chat_action(chat_id=chat_id, action=ChatAction.RECORD_VIDEO_NOTE)
                app.send_video_note(chat_id=chat_id, video_note=ffile, reply_to_message_id=reply_id)
            elif media_type == "voice_note":
                app.send_chat_action(chat_id=chat_id, action=ChatAction.RECORD_AUDIO)
                app.send_voice(chat_id=chat_id, voice=ffile, reply_to_message_id=reply_id, caption=caption)
            else:
                #default
                app.send_chat_action(chat_id=chat_id, action=ChatAction.UPLOAD_DOCUMENT)
                app.send_document(chat_id=chat_id, document=ffile, reply_to_message_id=reply_id, caption=caption)
        except Exception as e:
            app.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
            app.send_message(chat_id=chat_id, text=error_string + media_type + "\n" + str(e))
    elif method == "VARDUMP":
        message_id = int(sys.argv[3])
        msg = app.get_messages(chat_id=chat_id, message_ids=message_id)
        app.send_chat_action(chat_id=chat_id, action=ChatAction.UPLOAD_DOCUMENT)
        app.send_message(chat_id=chat_id, text=str(msg))
finally:
    app.stop()

###CLEAN
shutil.rmtree(workdir)
#deletes the working directory once it's finished
print("END")
class VideoFromChannel:
    def __init__(self, chat_id=None, depth=1):
        self.depth = depth
        self.chat_id = chat_id
        self.user_videos = {}
        print(config["Telegram"]["TOKEN"])
        self.client = Client("Video_parser_bot",
                             api_id=config["Telegram"]["api_id"],
                             api_hash=config["Telegram"]["api_hash"],
                             bot_token=config["Telegram"]["TOKEN"])

    def change_depth(self, new_depth=1):
        self.depth = new_depth
        return self.depth

    def clear_user_data(self):
        self.user_videos = {}

    def pop_user_video(self, file_id=''):
        item = self.user_videos.pop(file_id, None)
        if item:
            return True
        else:
            return False

    def get_video_from_url(self, _url=''):
        counter = 0
        self.client.start()
        url_data = urlparse(_url)
        chat, post_id = None, None
        try:
            if url_data.path:
                chat_and_post = url_data.path.split("/")[1:]
                if chat_and_post and len(chat_and_post) == 2:
                    chat, post_id = chat_and_post
                else:
                    return counter
                if chat and post_id:
                    posts = self.client.get_messages(chat_id=f"@{chat}", message_ids=list(
                        [x for x in range(int(post_id), int(post_id) + self.depth)]))
                else:
                    return counter
                for x in posts:
                    if x.empty:
                        continue
                    video = x.video
                    if video:
                        file_id = video.file_id
                        caption = x.caption or video.file_name
                        bot_caption = f"Разрешение: {video.width}X{video.height}\n{caption}"
                        markup = InlineKeyboardMarkup([[
                            InlineKeyboardButton("✅ Запостить ✅️️", callback_data=f"send_video_{file_id}"),
                            InlineKeyboardButton("❌ Закрыть ❌", callback_data=f"delete_video_{file_id}")]])

                        self.client.send_video(chat_id=self.chat_id, video=file_id, file_ref=video.file_ref,
                                               caption=bot_caption, reply_markup=markup)
                        self.user_videos[file_id] = {"data": file_id, "caption": caption}
                        counter += 1
            else:
                self.client.send_message(chat_id=self.chat_id, text=f"Некоректная ссылка!\nПроверьте: {_url}")
                return counter
        except Exception as e:
            self.client.send_message(chat_id=self.chat_id, text=f"Произошла ошибка при попытке отправки видео: {e}")
            print(e)
            return counter
        finally:
            self.client.stop()
        return counter