An advanced Filter Bot with nearly unlimitted filters

Overview

Pyrogram
Telegram MTProto API Framework for Python
Documentation Releases Community

Pyrogram

from pyrogram import Client, filters

app = Client("my_account")


@app.on_message(filters.private)
async def hello(client, message):
    await message.reply_text(f"Hello {message.from_user.mention}")


app.run()

Pyrogram is a modern, elegant and easy-to-use Telegram client library framework written from the ground up in Python and C. It enables you to easily create custom Telegram client applications for both user and bot identities (bot API alternative) via the MTProto API.

Features

  • Easy: You can install Pyrogram with pip and start building your applications right away.
  • Elegant: Low-level details are abstracted and re-presented in a much nicer and easier way.
  • Fast: Crypto parts are boosted up by TgCrypto, a high-performance library written in pure C.
  • Asynchronous: Allows both synchronous and asynchronous models to fit all usage needs.
  • Documented: API methods, types and public interfaces are all well documented.
  • Type-hinted: Types and methods are all type-hinted, enabling excellent editor support.
  • Updated, to make use of the latest Telegram API version and features.
  • Bot API-like: Similar to the Bot API in its simplicity, but much more powerful and detailed.
  • Pluggable: The Smart Plugin system allows to write components with minimal boilerplate code.
  • Comprehensive: Execute any advanced action an official client is able to do, and even more.

Requirements

Installing

pip3 install pyrogram

Resources

Copyright & License

Comments
  • Pyrogram v1.2.9 auth not working. [406 Not Acceptable]: [406 UPDATE_APP_TO_LOGIN]

    Pyrogram v1.2.9 auth not working. [406 Not Acceptable]: [406 UPDATE_APP_TO_LOGIN]

    Checklist

    • [✔️ ] I am sure the error is coming from Pyrogram's code and not elsewhere.
    • [ ✔️] I have searched in the issue tracker for similar bug reports, including closed ones.
    • [ ✔️] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/master.zip and reproduced the issue using the latest development version.

    Description

    I tried to get session string for my music bot. Then this happened

    from pyrogram import Client
    
    with Client("Jaindu", api_id=api_id, api_hash=api_hash) as bot_:
        first_name = (bot_.get_me()).first_name
        string_session_ = f"<b>String Session For {first_name}</b>\n<code>{bot_.export_session_string()}</code>"
        bot_.send_message("me", string_session_, parse_mode="html")
        print(f"String Has Been Sent To Your Saved Message : {first_name}")
    

    Traceback

    Traceback (most recent call last):
      File "sesgen.py", line 65, in <module>
        api_hash=input("Enter API HASH: ")) as pyrogram:
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/client.py", line 249, in __enter__
        return self.start()
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/sync.py", line 56, in async_to_sync_wrap
        return loop.run_until_complete(coroutine)
      File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
        return future.result()
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/methods/utilities/start.py", line 57, in start
        await self.authorize()
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/client.py", line 303, in authorize
        sent_code = await self.send_code(self.phone_number)
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/methods/auth/send_code.py", line 54, in send_code
        settings=raw.types.CodeSettings()
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/methods/advanced/send.py", line 81, in send
        else self.sleep_threshold)
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/session/session.py", line 425, in send
        return await self._send(data, timeout=timeout)
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/session/session.py", line 395, in _send
        RPCError.raise_it(result, type(data))
      File "/home/jaindu2015/.local/lib/python3.7/site-packages/pyrogram/errors/rpc_error.py", line 73, in raise_it
        is_unknown=True)
    pyrogram.errors.exceptions.not_acceptable_406.NotAcceptable: [406 Not Acceptable]: [406 UPDATE_APP_TO_LOGIN] (caused by "auth.SendCode")
    
    opened by charindithjaindu 26
  • client.download_media consistently fails for photos for big channels -503 Timeout

    client.download_media consistently fails for photos for big channels -503 Timeout

    Checklist

    • [X] I am sure the error is coming from Pyrogram's code and not elsewhere.
    • [X] I have searched in the issue tracker for similar bug reports, including closed ones.
    • [X] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/master.zip and reproduced the issue using the latest development version.

    Description

    Im using pyrogram to forward messages to another system, using a raw handler to process the messages and also download corresponding media (mostly images). Im using the client.download_media method. This works for almost all messages but for some it just wont download the images and return None as a path. I could not figure out why it happens but identified some messages for which it consistently happens.

    I made a small testcase that fetches one of these messages from a channel and tries to download the media.

    The message looks like this:

    {
        "_": "Message",
        "message_id": 5869,
        "sender_chat": {
            "_": "Chat",
            "id": -1001133587448,
            "type": "channel",
            "is_verified": false,
            "is_restricted": false,
            "is_creator": false,
            "is_scam": false,
            "is_fake": false,
            "title": "Klondike (Crypto Rush) ⚠️",
            "username": "CryptoKlondike",
            "photo": {
                "_": "ChatPhoto",
                "small_file_id": "AQADBAATtJV9J10AAwIAAwjEyecW____ZkFiWLn_WDe_GwQAAR4E",
                "small_photo_unique_id": "AQADtJV9J10AA78bBAAB",
                "big_file_id": "AQADBAATtJV9J10AAwMAAwjEyecW____ZkFiWLn_WDfBGwQAAR4E",
                "big_photo_unique_id": "AQADtJV9J10AA8EbBAAB"
            },
            "dc_id": 4
        },
        "date": "2021-02-19 10:35:42",
        "chat": {
            "_": "Chat",
            "id": -1001133587448,
            "type": "channel",
            "is_verified": false,
            "is_restricted": false,
            "is_creator": false,
            "is_scam": false,
            "is_fake": false,
            "title": "Klondike (Crypto Rush) ⚠️",
            "username": "CryptoKlondike",
            "photo": {
                "_": "ChatPhoto",
                "small_file_id": "AQADBAATtJV9J10AAwIAAwjEyecW____ZkFiWLn_WDe_GwQAAR4E",
                "small_photo_unique_id": "AQADtJV9J10AA78bBAAB",
                "big_file_id": "AQADBAATtJV9J10AAwMAAwjEyecW____ZkFiWLn_WDfBGwQAAR4E",
                "big_photo_unique_id": "AQADtJV9J10AA8EbBAAB"
            },
            "dc_id": 4
        },
        "mentioned": false,
        "scheduled": false,
        "from_scheduled": false,
        "media": true,
        "author_signature": "Robert Mercer 🔥",
        "caption_entities": [
            {
                "_": "MessageEntity",
                "type": "bold",
                "offset": 0,
                "length": 15
            },
            {
                "_": "MessageEntity",
                "type": "bold",
                "offset": 36,
                "length": 7
            },
            {
                "_": "MessageEntity",
                "type": "bold",
                "offset": 44,
                "length": 4
            },
            {
                "_": "MessageEntity",
                "type": "bold",
                "offset": 114,
                "length": 6
            }
        ],
        "photo": {
            "_": "Photo",
            "file_id": "AgACAgQAAx0CQ5Er-AACFu1gcwc0j8RpzQcWvVFQOom1Zz4iLwACtbgxG8ydgVEdyclzkLTMRe9xGypdAAMBAAMCAAN5AAPDxAIAAR4E",
            "file_unique_id": "AQAD73EbKl0AA8PEAgAB",
            "width": 1280,
            "height": 782,
            "file_size": 83252,
            "date": "2021-02-19 10:35:42",
            "thumbs": [
                {
                    "_": "Thumbnail",
                    "file_id": "AgACAgQAAx0CQ5Er-AACFu1gcwc0j8RpzQcWvVFQOom1Zz4iLwACtbgxG8ydgVEdyclzkLTMRe9xGypdAAMBAAMCAANtAAPExAIAAR4E",
                    "file_unique_id": "AQAD73EbKl0AA8TEAgAB",
                    "width": 320,
                    "height": 196,
                    "file_size": 14143
                },
                {
                    "_": "Thumbnail",
                    "file_id": "AgACAgQAAx0CQ5Er-AACFu1gcwc0j8RpzQcWvVFQOom1Zz4iLwACtbgxG8ydgVEdyclzkLTMRe9xGypdAAMBAAMCAAN4AAPFxAIAAR4E",
                    "file_unique_id": "AQAD73EbKl0AA8XEAgAB",
                    "width": 800,
                    "height": 489,
                    "file_size": 52220
                }
            ]
        },
        "caption": "🐝 BTC UPDATE\n\nWe just stick to our initial plan and holding a big bag of Bitcoin. The target is still the same - $60000.",
        "views": 14444,
        "outgoing": false
    }
    
    

    Steps to Reproduce

    This is my test code to fetch the message and download the media photo:

    
    from pyrogram import Client, filters, idle
    from pyrogram.handlers import MessageHandler
    import time
    import logging
    
    client = Client(
        '',
        api_id='',
        api_hash=''
    )
    
    def handle_new_impl(client:Client, message):
        print(f"New message: {str(message)}")
    
    
    def handle_new(client, message):
        return handle_new_impl(client, message)
    
    def main():
        # Pyrogram setup
        client.add_handler(MessageHandler(handle_new)) 
        client.start()
        m = client.get_messages(-1001133587448, 5869, replies=0)
        path = None
        print(f'Found message: {str(m)}')
        path = client.download_media(m, file_name="test1.jpg", block=False)
        print(f'Downloaded to: {str(path)}')
        idle()
        client.stop()
    
    if __name__ == '__main__':
        main()
    
    

    Ive tried with block=False and block=True When using block=True I get a getFile timeout error from the network code. When I use block=False I just get None as a path. Ive also tried using the file reference, adding a filename, basically trying all the different parameters of downloade_media with no luck. Its not a huge image either. It works when I try to download the same image if posted in another channel for example.

    Traceback

    This is the traceback for using block=True

    [520 Unknown error]: [-503 Timeout] (caused by "upload.GetFile")
    Traceback (most recent call last):
      File "/home/workspace/telegram/github_pyrogram/pyrogram/client.py", line 939, in get_file
        r = await session.send(
      File "/home/workspace/telegram/github_pyrogram/pyrogram/session/session.py", line 425, in send
        return await self._send(data, timeout=timeout)
      File "/home/workspace/telegram/github_pyrogram/pyrogram/session/session.py", line 395, in _send
        RPCError.raise_it(result, type(data))
      File "/home/workspace/telegram/github_pyrogram/pyrogram/errors/rpc_error.py", line 59, in raise_it
        raise UnknownError(
    pyrogram.errors.rpc_error.UnknownError: [520 Unknown error]: [-503 Timeout] (caused by "upload.GetFile")
    Downloaded to: None
    
    

    Just for the sake of reproducing above code, the channel I used it on is this https://t.me/CryptoKlondike (remove it if links are not allowed plz) Its a very big channel, maybe it has something to do with it. But it does happen with other channels aswell.

    Any pointers on how to fix this would be much appreciated!

    opened by righteon 21
  • Question: get_messages || GetChats

    Question: get_messages || GetChats

    In what format to specify the id of the chat?

    pycli.get_messages(chat_id=-1001004766182, message_ids=list(range(100)))
    pycli.resolve_peer(-1001004766182)
    # pyrogram.api.errors.exceptions.bad_request_400.PeerIdInvalid: [400 PEER_ID_INVALID]: The id/access_hash combination is invalid
    
    pycli.send(
        functions.messages.GetChats([-1001004766182])
    )
    # OverflowError: int too big to convert
    
    pycli.get_messages(chat_id=pycli.resolve_peer("coding_ru"), message_ids=list(range(141180, 141280)))
    # TypeError: unhashable type: 'InputPeerChannel'
    

    (Bot API)

    enhancement 
    opened by sviat9440 18
  • More flexible media downloads with client.download_(media/photo) and client.get_file

    More flexible media downloads with client.download_(media/photo) and client.get_file

    These changes would allow client.get_file to write to a given file name or file like object directly via a new file_out parameter.

    file_out can be a string or file/file like object that implements at least .write.

    The parameter is optional, and if not specified the old behavior of creating a file in the current working directory with a generated .temp name is kept.


    client.download_media is reworked to allow downloading files to specific locations instead of only the downloads folder. The function can still generate a file name for you the way it did prior if desired.

    client.download_media would no longer make use of a temporary file, as it uses client.get_files new ability to write directly to a file object.

    the change in the behavior of file_name is breaking for things expecting files to always end up in the "downloads" folder under the current working directory. And also for things expecting the block parameter to be next after file_name.

    Below is a short test which gives an overview of how the usage would change, and some examples of how client.download_media could be used with the changes.

    To try this code you can install the version over at:

    pip install git+https://github.com/EriHoss/[email protected]_media_downloads --upgrade

    from pyrogram import Client
    from pyrogram.api import types
    
    # This test assumes that the bot user is sending a jpg photo, or jpg file attachment.
    # It uses the sent photo or file in the message update to test the new behavior.
    
    def update_handler(client, update, users, chats):
    
        if isinstance(update, (types.UpdateNewChannelMessage, types.UpdateNewMessage)):
            message = update.message
            
            if isinstance(message, types.Message) and client.get_me().user.id == message.from_id:
                
                # file_dir has also been added to "client.download_photo", which inherits the
                # behavior of "client.download_media"
                
                # download directly to "direct/test.jpg"
                # directory trees used in file_name are created for you if they do not exist
                client.download_media(message, file_name='direct/test.jpg')
                
                # download to "downloads" in the current directory (the default).
                # folder is created if it does not exist.
                # file has a generated name.
                client.download_media(message)
    
                # download to the current working directory with a generated name
                client.download_media(message, file_dir='.')
                
                # download to 'custom_dir/custom_dir2' in the current directory.
                # folder tree is created if it does not exist.
                # file has a generated name.
                client.download_media(message, file_dir='custom_dir/custom_dir2')
                
                try:
                    # The two arguments cannot be used simultaneously
                    client.download_media(message, file_name='test2', file_dir='bad')
                except ValueError:
                    print('file_name and file_dir are mutually exclusive')
    
                # this works because "client.get_file" can now write to file objects, 
                # and "client.download_media" accounts for this.
                # This includes file like objects that only implement .write
                # "client.download_media" will not close the file for you, you must close
                # it since your in control of the file object
                with open('file_object.jpg', 'wb') as f:
                    client.download_media(message, file_name=f)
                
    
                # Test writing to "fake" file objects
    
                class DummyFile:
                    def __init__(self):
                        self._write_cnt = 0
    
                    def write(self, data):
                        # Required
                        self._write_cnt += 1
    
                    def flush(self):
                        # Optional, will be called if it exists
                        print("Write count {}".format(self._write_cnt))
    
                client.download_media(message, file_name=DummyFile())
                
                # Check if fileno gets used when implemented
    
                class WrappedFile:
                    def __init__(self, filename):
                        self._f = open(filename, 'wb')
    
                    def write(self, data):
                        # Required
                        self._f.write(data)
    
                    def flush(self):
                        # Optional, will be called if it exists
                        self._f.flush()
    
                    def fileno(self):
                       print('fileno called!')
                       return self._f.fileno()
                    
                    def __enter__(self):
                        return self
                        
                    def __exit__(self, exception_type, exception_value, traceback):
                        self._f.close()
                
                with WrappedFile('wrapped_file.jpg') as f:
                    client.download_media(message, file_name=f)
    
    
    def main():
        client = Client("example")
        client.set_update_handler(update_handler)
        client.start()
        client.idle()
    
    
    if __name__ == "__main__":
        main()
    
    opened by Teriks 18
  • message.download() raise  400 FILE_REFERENCE_EMPTY

    message.download() raise 400 FILE_REFERENCE_EMPTY

    Checklist

    • [x] I am sure the error is coming from Pyrogram's code and not elsewhere.
    • [x] I have searched in the issue tracker for similar bug reports, including closed ones.
    • [x] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/develop.zip and reproduced the issue using the latest development version.

    Description

    When I want to do download a file, I always get FILE_REFERENCE_EMPTY error. for example:

    client = Client(
                    telegram_session_string,
                    telegram_api_id,
                    telegram_api_hash,
                )
    with client:
        for message in client.iter_history('channel'):
            if message.empty or message.mentioned:
                continue
    
            if message.media:
                    file = message.download()
    
    

    unfortunately, I can't find anything in the error reference page https://docs.pyrogram.org/api/errors#badrequest

    Traceback

    [2019-09-14 17:32:28,190: DEBUG/ForkPoolWorker-2] PingThread started
    [2019-09-14 17:32:28,190: INFO/ForkPoolWorker-2] Session initialized: Layer 102
    [2019-09-14 17:32:28,191: INFO/ForkPoolWorker-2] Device: CPython 3.7.4 - Pyrogram 0.15.1
    [2019-09-14 17:32:28,191: INFO/ForkPoolWorker-2] System: Darwin 18.7.0 (EN)
    [2019-09-14 17:32:28,191: DEBUG/ForkPoolWorker-2] Session started
    [2019-09-14 17:32:28,534: DEBUG/ForkPoolWorker-2] {
        "_": "Message",
        "msg_id": 6736580390664272897,
        "seq_no": 5,
        "length": 140,
        "body": {
            "_": "types.RpcResult",
            "req_msg_id": 6736580389837039616,
            "result": {
                "_": "types.auth.Authorization",
                "user": {
                    "_": "types.User",
                    "id": 74509408,
                    "is_self": true,
                    "contact": false,
                    "mutual_contact": false,
                    "deleted": false,
                    "bot": false,
                    "bot_chat_history": false,
                    "bot_nochats": false,
                    "verified": false,
                    "restricted": false,
                    "min": false,
                    "bot_inline_geo": false,
                    "support": false,
                    "scam": false,
                    "access_hash": *,
                    "first_name": "*",
                    "last_name": "*",
                    "username": "*",
                    "phone": "*",
                    "photo": {
                        "_": "types.UserProfilePhoto",
                        "photo_id": *,
                        "photo_small": {
                            "_": "types.FileLocationToBeDeprecated",
                            "volume_id": 455205387,
                            "local_id": 399324
                        },
                        "photo_big": {
                            "_": "types.FileLocationToBeDeprecated",
                            "volume_id": 455205387,
                            "local_id": 399326
                        },
                        "dc_id": 4
                    },
                    "status": {
                        "_": "types.UserStatusOffline",
                        "was_online": 1568482250
                    }
                }
            }
        }
    }
    [2019-09-14 17:32:28,836: DEBUG/ForkPoolWorker-2] {
        "_": "Message",
        "msg_id": 6736580392068740097,
        "seq_no": 7,
        "length": 44,
        "body": {
            "_": "types.RpcResult",
            "req_msg_id": 6736580391311489024,
            "result": {
                "_": "types.RpcError",
                "error_code": 400,
                "error_message": "FILE_REFERENCE_EXPIRED"
            }
        }
    }
    [2019-09-14 17:32:28,846: ERROR/ForkPoolWorker-2] [400 Bad Request]: [400 FILE_REFERENCE_EXPIRED] (caused by "upload.GetFile")
    Traceback (most recent call last):
      File "/Users/ahmad/Projects/self/content_hub/venv/lib/python3.7/site-packages/pyrogram/client/client.py", line 1539, in get_file
        limit=limit
      File "/Users/ahmad/Projects/self/content_hub/venv/lib/python3.7/site-packages/pyrogram/session/session.py", line 437, in send
        return self._send(data, timeout=timeout)
      File "/Users/ahmad/Projects/self/content_hub/venv/lib/python3.7/site-packages/pyrogram/session/session.py", line 424, in _send
        RPCError.raise_it(result, type(data))
      File "/Users/ahmad/Projects/self/content_hub/venv/lib/python3.7/site-packages/pyrogram/errors/rpc_error.py", line 73, in raise_it
        is_unknown=True)
    pyrogram.errors.exceptions.bad_request_400.BadRequest: [400 Bad Request]: [400 FILE_REFERENCE_EXPIRED] (caused by "upload.GetFile")
    
    opened by ahmadly 15
  • sqlite3.OperationalError: database is locked

    sqlite3.OperationalError: database is locked

    Great Library. I am using it and its ok. in many times i get " sqlite3.OperationalError: database is locked " errors and it stops working. in there any way to solve this?

    question 
    opened by shamloo 15
  • Session threads left running after Client.stop, occurs in long running process

    Session threads left running after Client.stop, occurs in long running process

    Threads created in Session.start() appear to be left running in a loop after stopping a client that has been running for some time.

    On CTRL-C this causes the program to hang, because the threads are not deamon threads and continue to keep the program alive.

    It appears that new threads might be getting created before the previous successfully exited when session reconnects while running?

    In my project I have added something like this for debugging:

    client.start()
    client.idle()
    time.sleep(5)
    for i in (x for x in threading.enumerate() if x.name != 'MainThread'):
        print(i.name)
    

    Occasionally after a long run I get this output on CTRL-C (put some debug prints in Syncer.remove because I thought it might be a deadlock there but it is not):

    Syncer.remove lock before
    Syncer.remove cls.sync(client) after
    Syncer.remove cls.stop() before
    Syncer.stop cls.event.set() before
    Syncer.stop cls.event.set() after
    Syncer.remove cls.stop() after
    Syncer.remove lock after
    NetWorker#1
    RecvThread
    NextSaltThread
    PingThread
    
    ... program hangs ...
    

    I think the problem might be in Session.start() itself but I am not certain.

    bug 
    opened by Teriks 13
  • continue from incoming updates while bot is off

    continue from incoming updates while bot is off

    Checklist

    • [X] I believe the idea is awesome and would benefit the framework
    • [X] I have searched in the issue tracker for similar requests, including closed ones

    Description

    When the bot is closed, it ignores all incoming user messages and continues updates after it is turned on, especially when uploading updates to my bot I frequently reset and my users are badly affected

    enhancement 
    opened by Eikosa 12
  • Error: [17] msg_id too high, the client time has to be synchronized

    Error: [17] msg_id too high, the client time has to be synchronized

      File "/usr/local/lib/python3.5/dist-packages/pyrogram/client/client.py", line 216, in start
        self.session.start()
      File "/usr/local/lib/python3.5/dist-packages/pyrogram/session/session.py", line 164, in start
        raise e
      File "/usr/local/lib/python3.5/dist-packages/pyrogram/session/session.py", line 134, in start
        self.current_salt = self._send(functions.GetFutureSalts(1)).salts[0]
      File "/usr/local/lib/python3.5/dist-packages/pyrogram/session/session.py", line 404, in _send
        "Error code {}".format(result.error_code)
    Exception: [17] msg_id too high, the client time has to be synchronized
    

    its first start!

    question 
    opened by i-Naji 12
  • Can't forward messages to anyone but myself

    Can't forward messages to anyone but myself

    I'm trying to forward a message to a group but it doesn't allow me to do it. The only chat I'm able to forward messages is my own chat (saved messages).

    What I've tried: client.forward_messages(-100129xxxxxxx, chat_id, msg_ids) to a group, doesn't work. client.forward_messages(446xxx, chat_id, msg_ids) to my friend, doesn't work. client.forward_messages("@myfriendusername", chat_id, msg_ids) to my friend, doesn't work. Same without the @.

    The log file shows this error (it's similare between al cases, changes only the KeyError):

    INFO:pyrogram.connection.connection:Connecting...
    INFO:pyrogram.connection.transport.tcp.tcp_abridged:Connected!
    INFO:pyrogram.session.session:Connection inited: Layer 74
    INFO:pyrogram.client.client:Dialogs count: 12
    ERROR:pyrogram.session.session:[400 PEER_ID_INVALID]: The id/access_hash combination is invalid
    Traceback (most recent call last):
      File "/home/dreadtank27/.local/lib/python3.5/site-packages/pyrogram/client/client.py", line 441, in resolve_peer
        else self.peers_by_id[chat_id]
    KeyError: -100129xxxxxxx
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/home/dreadtank27/.local/lib/python3.5/site-packages/pyrogram/session/session.py", line 237, in worker
        self.unpack_dispatch_and_ack(packet)
      File "/home/dreadtank27/.local/lib/python3.5/site-packages/pyrogram/session/session.py", line 284, in unpack_dispatch_and_ack
        self.update_handler(i.body)
      File "channels_forwarder.py", line 12, in callback
        client.forward_messages(-100129xxxxxxx, chat_id, msg_ids)
      File "/home/dreadtank27/.local/lib/python3.5/site-packages/pyrogram/client/client.py", line 538, in forward_messages
        to_peer=self.resolve_peer(chat_id),
      File "/home/dreadtank27/.local/lib/python3.5/site-packages/pyrogram/client/client.py", line 444, in resolve_peer
        raise PeerIdInvalid
    pyrogram.api.errors.exceptions.bad_request_400.PeerIdInvalid: [400 PEER_ID_INVALID]: The id/access_hash combination is invalid
    

    Also, I'm an administrator in the destination group, my friend hasn't blocked me and the key/access_hash is correct. I'm using Pyrogram V.0.3.3

    bug 
    opened by IvanMazzoli 12
  • Receiving `TypeError` on send a raw update.

    Receiving `TypeError` on send a raw update.

    Checklist

    • [X] I am sure the error is coming from Pyrogram's code and not elsewhere
    • [X] I have searched in the issue tracker for similar bug reports, including closed ones
    • [X] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/master.zip and reproduced the issue using the latest development version

    Description

    I am trying to send a raw update using await client.send() but it is generating an TypeError. I have provided all the necessary things required to send.

    Steps to reproduce

    1. Start a client
    2. Try to send any raw update using await client.send()

    Code example

    No response

    Logs

    2022-02-02T12:47:28.183762+00:00 app[web.1]: TypeError: write() missing 1 required positional argument: 'client'
    2022-02-02T12:47:51.844500+00:00 app[web.1]: 2022-02-02 12:47:51,844 - pyrogram.dispatcher - ERROR - write() missing 1 required positional argument: 'client'
    2022-02-02T12:47:51.844506+00:00 app[web.1]: Traceback (most recent call last):
    2022-02-02T12:47:51.844507+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/dispatcher.py", line 226, in handler_worker
    2022-02-02T12:47:51.844507+00:00 app[web.1]:     await handler.callback(self.client, *args)
    2022-02-02T12:47:51.844508+00:00 app[web.1]:   File "/app/Captcha-Bot/plugins/__main__.py", line 237, in demo_callback_handlers
    2022-02-02T12:47:51.844509+00:00 app[web.1]:     await poll_demo(bot, cb)
    2022-02-02T12:47:51.844509+00:00 app[web.1]:   File "/app/Captcha-Bot/plugins/demo.py", line 200, in poll_demo
    2022-02-02T12:47:51.844509+00:00 app[web.1]:     sent_poll = await client.send(
    2022-02-02T12:47:51.844510+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/methods/advanced/send.py", line 77, in send
    2022-02-02T12:47:51.844510+00:00 app[web.1]:     r = await self.session.send(
    2022-02-02T12:47:51.844510+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/session/session.py", line 362, in send
    2022-02-02T12:47:51.844511+00:00 app[web.1]:     return await self._send(data, timeout=timeout)
    2022-02-02T12:47:51.844511+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/session/session.py", line 291, in _send
    2022-02-02T12:47:51.844512+00:00 app[web.1]:     message = self.msg_factory(data)
    2022-02-02T12:47:51.844512+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/session/internals/msg_factory.py", line 37, in __call__
    2022-02-02T12:47:51.844513+00:00 app[web.1]:     len(body)
    2022-02-02T12:47:51.844513+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/raw/core/tl_object.py", line 76, in __len__
    2022-02-02T12:47:51.844513+00:00 app[web.1]:     return len(self.write())
    2022-02-02T12:47:51.844513+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/raw/functions/messages/send_media.py", line 133, in write
    2022-02-02T12:47:51.844514+00:00 app[web.1]:     b.write(self.reply_markup.write())
    2022-02-02T12:47:51.844514+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/pyrogram/sync.py", line 38, in async_to_sync_wrap
    2022-02-02T12:47:51.844514+00:00 app[web.1]:     coroutine = function(*args, **kwargs)
    2022-02-02T12:47:51.844514+00:00 app[web.1]: TypeError: write() missing 1 required positional argument: 'client'
    
    invalid 
    opened by MrBotDeveloper 11
  • ValueError: <class 'pyrogram.raw.types.auth.sent_code_type_email_code.SentCodeTypeEmailCode'>  is not a valid SentCodeType

    ValueError: is not a valid SentCodeType

    Checklist

    • [X] I am sure the error is coming from Pyrogram's code and not elsewhere
    • [X] I have searched in the issue tracker for similar bug reports, including closed ones
    • [X] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/master.zip and reproduced the issue using the latest development version

    Description

    ValueError: <class 'pyrogram.raw.types.auth.sent_code_type_email_code.SentCodeTypeEmailCode'> is not a valid SentCodeType

    Steps to reproduce

    1. Run python telegram_service.py
    2. Input phone number
    3. Enter y
    4. I get an error and a telegram code in the mail

    Code example

    from pyrogram import Client
    
    api_id = **
    api_hash = "***"
    
    app = Client("my_account", api_id=api_id, api_hash=api_hash)
    
    app.run()
    

    Logs

    Traceback (most recent call last):
      File "/home/maxim/Desktop/**/backend/app/services/telegram_service.py", line 10, in <m
    odule>
        app.run()
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/methods/utilities/run.py", line 84, in run
        self.start()
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/sync.py", line 66, in async_to_sync_wrap
        return loop.run_until_complete(coroutine)
      File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
        return future.result()
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/methods/utilities/start.py", line 62, in start
        await self.authorize()
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/client.py", line 347, in authorize
        sent_code = await self.send_code(self.phone_number)
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/methods/auth/send_code.py", line 79, in send_code
        return types.SentCode._parse(r)
      File "/home/maxim/.cache/pypoetry/virtualenvs/**-QvaYT4s1-py3.10/lib/python3.1
    0/site-packages/pyrogram/types/authorization/sent_code.py", line 58, in _parse
        type=enums.SentCodeType(type(sent_code.type)),
      File "/usr/lib/python3.10/enum.py", line 385, in __call__
        return cls.__new__(cls, value)
      File "/usr/lib/python3.10/enum.py", line 710, in __new__
        raise ve_exc
    ValueError: <class 'pyrogram.raw.types.auth.sent_code_type_email_code.SentCodeTypeEmailCode'>
     is not a valid SentCodeType
    
    opened by maximyurevich 3
  • Control the number of cached messages via message_cache in Client

    Control the number of cached messages via message_cache in Client

    This commit adds the optional parameter message_cache to Client to control the number of cached messages. This can significantly help low-end machines control their memory usage.

    See #1172.

    opened by xk4rim 2
  • The file_name option is ignored when the url in reply_document

    The file_name option is ignored when the url in reply_document

    Checklist

    • [X] I am sure the error is coming from Pyrogram's code and not elsewhere
    • [X] I have searched in the issue tracker for similar bug reports, including closed ones
    • [X] I ran pip3 install -U https://github.com/pyrogram/pyrogram/archive/master.zip and reproduced the issue using the latest development version

    Description

    I use reply_document function to send images. For this, I use the URL of the image. When the image is sent, the end of the url is used as the file name in Telegram, but I used file_name to rewrite it, but this does not apply.

    Steps to reproduce

    1. Make a function with pyrogram
    2. use bellow code
    3. wait for upload

    Code example

    url = "https://cn.bing.com/th?id=OHR.PoinsettiaDay_EN-US2361694439_UHD.jpg"
    message.reply_document(document=url, file_name="test")
    

    Logs

    No response

    opened by MrCapsLock 0
Releases(v2.0.0)
Owner
Pyrogram
Telegram MTProto API Client Library and Framework for Python
Pyrogram
A script that writes automatic instagram comments under a post

Send automatic messages under a post on instagram Instagram will rate limit you after some time. From there on you can only post 1 comment every 40 se

Maximilian Freitag 3 Apr 28, 2022
Telegram Group Chat Statistics With Python

Telegram Group Chat Statistics How to Run First add PYTHONPATH in repository root directory enviroment variable by running: export PYTHONPATH=${PWD}

Sina Nazem 3 Apr 18, 2022
just a program i made cuz a friend got tokenlogged and spammed me with these scam/phishing links so i made a programm to spam these websides with fake logins

scam-webside-spammer just a program i made cuz a friend got tokenlogged and spammed me with these scam/phishing links so i made a programm to spam the

TerrificTable 3 Sep 23, 2022
A Sublime Text plugin that displays inline images for single-line comments formatted like `// ![](example.png)`.

Inline Images Sometimes ASCII art is not enough. Sometimes an image says more than a thousand words. This Sublime Text plugin can display images inlin

Andreas Haferburg 8 Jul 01, 2022
Discord-Lite - A light weight discord client written in Python, for developers, by developers.

Discord-Lite - A light weight discord client written in Python, for developers, by developers.

Sachit 142 Jan 07, 2023
The official Magenta Voice Skill SDK used to develop skills for the Magenta Voice Assistant using Voice Platform!

Magenta Voice Skill SDK Development • Support • Contribute • Contributors • Licensing Magenta Voice Skill SDK for Python is a package that assists in

Telekom Open Source Software 18 Nov 19, 2022
A multi-tenant multi-client scalable product categorising demo stack

Better Categories 4All: A multi-tenant multi-client product categorising stack The steps to reproduce training and inference are in the end of this fi

7 Feb 15, 2022
A discord self bot that replies to messages using cleverbot

cleverbot-discord-self A discord self bot that replies to messages using cleverbot Bot will respond to DMs and channels in the channels list. Need to

0 Jan 11, 2022
This is a simple Telegram bot to Delete User Messages based on Groupmembers Votes. Heroku deployable

ibCleaner Bot This is a simple Telegram bot to Delete User Messages based on Groupmembers Votes. Deploy to Heroku Deploy locally Edit config.py and ad

8 Oct 21, 2022
Make WhatsApp ChatBot and use WhatsApp API to send the WhatsApp messages in python .

Ultramsg.com WhatsApp Bot using WhatsApp API and ultramsg Demo WhatsApp API ChatBot using Ultramsg API with python. Opportunities and tasks: The outpu

Ultramsg 64 Dec 29, 2022
Force-Subscribe-Bot - A Telegram Bot to force users to join a specific channel before sending messages in a group

Introduction A Telegram Bot to force users to join a specific channel before sen

LG Bot Updates 0 Jan 16, 2022
CDBEC: Catware DataBase Encryption Client

CDBEC: Catware DataBase Encryption Client Описание CDBEC - клиент для создания, просмотра и редактирования .db-catencrypted списков, шифруемых при пом

Catware-Foundation 2 Nov 03, 2022
ClearML - Auto-Magical Suite of tools to streamline your ML workflow. Experiment Manager, MLOps and Data-Management

ClearML - Auto-Magical Suite of tools to streamline your ML workflow Experiment Manager, MLOps and Data-Management ClearML Formerly known as Allegro T

ClearML 3.9k Jan 01, 2023
A Python wrapper for the Yelp API v2

python-yelp-v2 A Python wrapper for the Yelp API v2. The structure for this was inspired by the python-twitter library, and some internal methods are

Matthew Conlen 12 Oct 24, 2017
TuShare is a utility for crawling historical data of China stocks

TuShare Tushare Pro版已发布,请访问新的官网了解和查询数据接口! https://tushare.pro TuShare是实现对股票/期货等金融数据从数据采集、清洗加工 到 数据存储过程的工具,满足金融量化分析师和学习数据分析的人在数据获取方面的需求,它的特点是数据覆盖范围广,接口

挖地兔 11.9k Dec 30, 2022
Python package and CLI for user-friendly integration with SAS Viya

sasctl A user-friendly Python interface for SAS Viya. Full documentation: https://sassoftware.github.io/python-sasctl Table of Contents Overview Prere

SAS Software 30 Dec 14, 2022
Status-embed - Cool open source profile embed for Discord

Current Status : Incomplete Status Embed Status Embed is an awesome open source

Ritabrata Das 2 Feb 17, 2022
Unlimited Filter Telegram Bot 2

Mother NAther Bot Features Auto Filter Manuel Filter IMDB Admin Commands Broadcast Index IMDB search Inline Search Random pics ids and User info Stats

LɪᴏɴKᴇᴛᴛʏUᴅ 1 Oct 30, 2021
A Python app which retrieves the rank and players' equipped skins during a match

VALORANT rank yoinker About The Project Usage Contributing Contact Acknowledgements Disclaimer About The Project Their Queue Current Skin Current Rank

Isaac Kenyon 270 Jan 04, 2023
Python client for Vektonn

Python client for Vektonn Installation Install the latest version: $ pip install vektonn Install specific version: $ pip install vektonn==1.2.3 Upgrad

Vektonn 16 Dec 09, 2022