diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..c3b69284 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at dan@pyrogram.org. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 00000000..e721fd98 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1 @@ +# How to Contribute diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..e0556d54 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,21 @@ +--- +name: Bug Report +about: Create a bug report affecting the library +labels: "bug" +--- + + + +## 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/develop.zip` and reproduced the issue using the latest development version. + +## Description +A clear and concise description of the problem. + +## Steps to Reproduce +[A minimal, complete and verifiable example](https://stackoverflow.com/help/mcve). + +## Traceback +The full traceback (if applicable). \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..70a39192 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,14 @@ +--- +name: Feature Request +about: Suggest ideas, new features or enhancements +labels: "enhancement" +--- + + + +## Checklist +- [ ] I believe the idea is awesome and would benefit the library. +- [ ] I have searched in the issue tracker for similar requests, including closed ones. + +## Description +A detailed description of the request. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000..737304d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,15 @@ +--- +name: Ask Question +about: Ask a Pyrogram related question +title: For Q&A purposes, please read this template body +labels: "question" +--- + + + +# Important +This place is for issues about Pyrogram, it's **not a forum**. + +If you'd like to post a question, please move to https://stackoverflow.com or join the Telegram community by following the description in https://t.me/pyrogram. + +Thanks. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in index 80c061ff..97d04588 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,5 @@ ## Include -include COPYING COPYING.lesser NOTICE requirements.txt +include README.md COPYING COPYING.lesser NOTICE requirements.txt recursive-include compiler *.py *.tl *.tsv *.txt recursive-include pyrogram mime.types diff --git a/README.md b/README.md new file mode 100644 index 00000000..4e758b5a --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +
+
+
+
+
+ Telegram MTProto API Framework for Python
+
+
+ Documentation
+
+ •
+
+ Releases
+
+ •
+
+ Community
+
+

- Telegram MTProto API Framework for Python
-
-
-
- Documentation
-
- •
-
- Changelog
-
- •
-
- Community
-
-
-
-
-
-
-
-
-
code, "
""
"for i in range(10):\n"
diff --git a/docs/source/resources/TgCrypto.rst b/docs/source/topics/tgcrypto.rst
similarity index 87%
rename from docs/source/resources/TgCrypto.rst
rename to docs/source/topics/tgcrypto.rst
index 2af09a06..454bf05c 100644
--- a/docs/source/resources/TgCrypto.rst
+++ b/docs/source/topics/tgcrypto.rst
@@ -2,7 +2,7 @@ Fast Crypto
===========
Pyrogram's speed can be *dramatically* boosted up by TgCrypto_, a high-performance, easy-to-install Telegram Crypto
-Library specifically written in C for Pyrogram [#f1]_ as a Python extension.
+Library specifically written in C for Pyrogram [1]_ as a Python extension.
TgCrypto is a replacement for the much slower PyAES and implements the crypto algorithms Telegram requires, namely
**AES-IGE 256 bit** (used in MTProto v2.0) and **AES-CTR 256 bit** (used for CDN encrypted files).
@@ -28,5 +28,5 @@ what you should do next:
.. _TgCrypto: https://github.com/pyrogram/tgcrypto
-.. [#f1] Although TgCrypto is intended for Pyrogram, it is shipped as a standalone package and can thus be used for
+.. [1] Although TgCrypto is intended for Pyrogram, it is shipped as a standalone package and can thus be used for
other Python projects too.
diff --git a/docs/source/resources/VoiceCalls.rst b/docs/source/topics/voice-calls.rst
similarity index 100%
rename from docs/source/resources/VoiceCalls.rst
rename to docs/source/topics/voice-calls.rst
diff --git a/examples/README.md b/examples/README.md
index 643fe56d..b8898a71 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -12,12 +12,12 @@ Example | Description
---: | :---
[**hello_world**](hello_world.py) | Demonstration of basic API usage
[**echobot**](echobot.py) | Echo every private text message
-[**welcome**](welcome.py) | The Welcome Bot in [@PyrogramChat](https://t.me/pyrogramchat)
-[**history**](history.py) | Get the full message history of a chat
-[**chat_members**](chat_members.py) | Get all the members of a chat
-[**dialogs**](dialogs.py) | Get all of your dialog chats
-[**using_inline_bots**](using_inline_bots.py) | Query an inline bot (as user) and send a result to a chat
-[**keyboards**](keyboards.py) | Send normal and inline keyboards using regular bots
-[**callback_queries**](callback_queries.py) | Handle queries coming from inline button presses
-[**inline_queries**](inline_queries.py) | Handle inline queries
+[**welcomebot**](welcomebot.py) | The Welcome Bot in [@PyrogramChat](https://t.me/pyrogramchat)
+[**get_history**](get_history.py) | Get the full message history of a chat
+[**get_chat_members**](get_chat_members.py) | Get all the members of a chat
+[**get_dialogs**](get_dialogs.py) | Get all of your dialog chats
+[**callback_queries**](callback_queries.py) | Handle callback queries (as bot) coming from inline button presses
+[**inline_queries**](inline_queries.py) | Handle inline queries (as bot) and answer with results
+[**use_inline_bots**](use_inline_bots.py) | Query an inline bot (as user) and send a result to a chat
+[**bot_keyboards**](bot_keyboards.py) | Send normal and inline keyboards using regular bots
[**raw_updates**](raw_updates.py) | Handle raw updates (old, should be avoided)
diff --git a/examples/keyboards.py b/examples/bot_keyboards.py
similarity index 96%
rename from examples/keyboards.py
rename to examples/bot_keyboards.py
index 1a1140b6..e1ff1e7e 100644
--- a/examples/keyboards.py
+++ b/examples/bot_keyboards.py
@@ -1,4 +1,4 @@
-"""This example will show you how to send normal and inline keyboards.
+"""This example will show you how to send normal and inline keyboards (as bot).
You must log-in as a regular bot in order to send keyboards (use the token from @BotFather).
Any attempt in sending keyboards with a user account will be simply ignored by the server.
@@ -39,7 +39,7 @@ with app:
),
InlineKeyboardButton( # Opens a web URL
"URL",
- url="https://docs.pyrogram.ml"
+ url="https://docs.pyrogram.org"
),
],
[ # Second row
diff --git a/examples/chat_members.py b/examples/get_chat_members.py
similarity index 100%
rename from examples/chat_members.py
rename to examples/get_chat_members.py
diff --git a/examples/dialogs.py b/examples/get_dialogs.py
similarity index 72%
rename from examples/dialogs.py
rename to examples/get_dialogs.py
index 08c769e2..92da8834 100644
--- a/examples/dialogs.py
+++ b/examples/get_dialogs.py
@@ -1,4 +1,4 @@
-"""This example shows how to get the full dialogs list of a user."""
+"""This example shows how to get the full dialogs list (as user)."""
from pyrogram import Client
diff --git a/examples/history.py b/examples/get_history.py
similarity index 100%
rename from examples/history.py
rename to examples/get_history.py
diff --git a/examples/inline_queries.py b/examples/inline_queries.py
index c1727fe6..d86d90d5 100644
--- a/examples/inline_queries.py
+++ b/examples/inline_queries.py
@@ -22,12 +22,12 @@ def answer(client, inline_query):
input_message_content=InputTextMessageContent(
"Here's how to install **Pyrogram**"
),
- url="https://docs.pyrogram.ml/start/Installation",
+ url="https://docs.pyrogram.org/intro/install",
description="How to install Pyrogram",
thumb_url="https://i.imgur.com/JyxrStE.png",
reply_markup=InlineKeyboardMarkup(
[
- [InlineKeyboardButton("Open website", url="https://docs.pyrogram.ml/start/Installation")]
+ [InlineKeyboardButton("Open website", url="https://docs.pyrogram.org/intro/install")]
]
)
),
@@ -37,12 +37,12 @@ def answer(client, inline_query):
input_message_content=InputTextMessageContent(
"Here's how to use **Pyrogram**"
),
- url="https://docs.pyrogram.ml/start/Usage",
+ url="https://docs.pyrogram.org/start/invoking",
description="How to use Pyrogram",
thumb_url="https://i.imgur.com/JyxrStE.png",
reply_markup=InlineKeyboardMarkup(
[
- [InlineKeyboardButton("Open website", url="https://docs.pyrogram.ml/start/Usage")]
+ [InlineKeyboardButton("Open website", url="https://docs.pyrogram.org/start/invoking")]
]
)
)
diff --git a/examples/use_inline_bots.py b/examples/use_inline_bots.py
new file mode 100644
index 00000000..5681df87
--- /dev/null
+++ b/examples/use_inline_bots.py
@@ -0,0 +1,13 @@
+"""This example shows how to query an inline bot (as user)"""
+
+from pyrogram import Client
+
+# Create a new Client
+app = Client("my_account")
+
+with app:
+ # Get bot results for "Fuzz Universe" from the inline bot @vid
+ bot_results = app.get_inline_bot_results("vid", "Fuzz Universe")
+
+ # Send the first result (bot_results.results[0]) to your own chat (Saved Messages)
+ app.send_inline_bot_result("me", bot_results.query_id, bot_results.results[0].id)
diff --git a/examples/using_inline_bots.py b/examples/using_inline_bots.py
deleted file mode 100644
index c3b48874..00000000
--- a/examples/using_inline_bots.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""This example shows how to query an inline bot"""
-
-from pyrogram import Client
-
-# Create a new Client
-app = Client("my_account")
-
-# Start the Client
-app.start()
-
-# Get bot results for "Fuzz Universe" from the inline bot @vid
-bot_results = app.get_inline_bot_results("vid", "Fuzz Universe")
-# Send the first result (bot_results.results[0]) to your own chat (Saved Messages)
-app.send_inline_bot_result("me", bot_results.query_id, bot_results.results[0].id)
-
-# Stop the client
-app.stop()
diff --git a/examples/welcome.py b/examples/welcomebot.py
similarity index 91%
rename from examples/welcome.py
rename to examples/welcomebot.py
index ab252672..35f72aff 100644
--- a/examples/welcome.py
+++ b/examples/welcomebot.py
@@ -8,7 +8,7 @@ from pyrogram import Client, Emoji, Filters
TARGET = "PyrogramChat" # Target chat. Can also be a list of multiple chat ids/usernames
MENTION = "[{}](tg://user?id={})" # User mention markup
-MESSAGE = "{} Welcome to [Pyrogram](https://docs.pyrogram.ml/)'s group chat {}!" # Welcome message
+MESSAGE = "{} Welcome to [Pyrogram](https://docs.pyrogram.org/)'s group chat {}!" # Welcome message
app = Client("my_account")
diff --git a/pyrogram/__init__.py b/pyrogram/__init__.py
index 4bf8f069..317e9df2 100644
--- a/pyrogram/__init__.py
+++ b/pyrogram/__init__.py
@@ -26,9 +26,7 @@ if sys.version_info[:3] in [(3, 5, 0), (3, 5, 1), (3, 5, 2)]:
__version__ = "0.13.0.async"
__license__ = "GNU Lesser General Public License v3 or later (LGPLv3+)"
-__copyright__ = "Copyright (C) 2017-2019 Dan Tès ".replace(
- "\xe8", "e" if sys.getfilesystemencoding() != "utf-8" else "\xe8"
-)
+__copyright__ = "Copyright (C) 2017-2019 Dan "
try:
import uvloop
diff --git a/pyrogram/api/core/object.py b/pyrogram/api/core/object.py
index a479fb6e..ace7a59a 100644
--- a/pyrogram/api/core/object.py
+++ b/pyrogram/api/core/object.py
@@ -30,43 +30,51 @@ class Object:
QUALNAME = "Base"
@staticmethod
- def read(b: BytesIO, *args):
+ def read(b: BytesIO, *args): # TODO: Rename b -> data
return Object.all[int.from_bytes(b.read(4), "little")].read(b, *args)
def write(self, *args) -> bytes:
pass
+ def __eq__(self, other: "Object") -> bool:
+ for attr in self.__slots__:
+ try:
+ if getattr(self, attr) != getattr(other, attr):
+ return False
+ except AttributeError:
+ return False
+
+ return True
+
def __str__(self) -> str:
+ def default(obj: Object):
+ try:
+ return OrderedDict(
+ [("_", obj.QUALNAME)]
+ + [(attr, getattr(obj, attr))
+ for attr in obj.__slots__
+ if getattr(obj, attr) is not None]
+ )
+ except AttributeError:
+ if isinstance(obj, datetime):
+ return obj.strftime("%d-%b-%Y %H:%M:%S")
+ else:
+ return repr(obj)
+
return dumps(self, indent=4, default=default, ensure_ascii=False)
+ def __repr__(self) -> str:
+ return "pyrogram.api.{}({})".format(
+ self.QUALNAME,
+ ", ".join(
+ "{}={}".format(attr, repr(getattr(self, attr)))
+ for attr in self.__slots__
+ if getattr(self, attr) is not None
+ )
+ )
+
def __len__(self) -> int:
return len(self.write())
def __getitem__(self, item):
return getattr(self, item)
-
-
-def remove_none(obj):
- if isinstance(obj, (list, tuple, set)):
- return type(obj)(remove_none(x) for x in obj if x is not None)
- elif isinstance(obj, dict):
- return type(obj)((remove_none(k), remove_none(v)) for k, v in obj.items() if k is not None and v is not None)
- else:
- return obj
-
-
-def default(o: "Object"):
- try:
- content = {i: getattr(o, i) for i in o.__slots__}
-
- return remove_none(
- OrderedDict(
- [("_", o.QUALNAME)]
- + [i for i in content.items()]
- )
- )
- except AttributeError:
- if isinstance(o, datetime):
- return o.strftime("%d-%b-%Y %H:%M:%S")
- else:
- return repr(o)
diff --git a/pyrogram/client/__init__.py b/pyrogram/client/__init__.py
index d43511d2..f4a954c6 100644
--- a/pyrogram/client/__init__.py
+++ b/pyrogram/client/__init__.py
@@ -17,9 +17,9 @@
# along with Pyrogram. If not, see .
from .client import Client
-from .ext import BaseClient, ChatAction, Emoji, ParseMode
+from .ext import BaseClient, Emoji
from .filters import Filters
__all__ = [
- "Client", "BaseClient", "ChatAction", "Emoji", "ParseMode", "Filters",
+ "Client", "BaseClient", "Emoji", "Filters",
]
diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py
index ce8ae2fd..dd9cc3dd 100644
--- a/pyrogram/client/client.py
+++ b/pyrogram/client/client.py
@@ -61,27 +61,23 @@ log = logging.getLogger(__name__)
class Client(Methods, BaseClient):
- """This class represents a Client, the main mean for interacting with Telegram.
- It exposes bot-like methods for an easy access to the API as well as a simple way to
- invoke every single Telegram API method available.
+ """Pyrogram Client, the main means for interacting with Telegram.
- Args:
+ Parameters:
session_name (``str``):
Name to uniquely identify a session of either a User or a Bot, e.g.: "my_account". This name will be used
to save a file to disk that stores details needed for reconnecting without asking again for credentials.
- Note for bots: You can pass a bot token here, but this usage will be deprecated in next releases.
- Use *bot_token* instead.
api_id (``int``, *optional*):
The *api_id* part of your Telegram API Key, as integer. E.g.: 12345
This is an alternative way to pass it if you don't want to use the *config.ini* file.
api_hash (``str``, *optional*):
- The *api_hash* part of your Telegram API Key, as string. E.g.: "0123456789abcdef0123456789abcdef"
+ The *api_hash* part of your Telegram API Key, as string. E.g.: "0123456789abcdef0123456789abcdef".
This is an alternative way to pass it if you don't want to use the *config.ini* file.
app_version (``str``, *optional*):
- Application version. Defaults to "Pyrogram \U0001f525 vX.Y.Z"
+ Application version. Defaults to "Pyrogram X.Y.Z"
This is an alternative way to set it if you don't want to use the *config.ini* file.
device_model (``str``, *optional*):
@@ -107,10 +103,14 @@ class Client(Methods, BaseClient):
This is an alternative way to setup a proxy if you don't want to use the *config.ini* file.
test_mode (``bool``, *optional*):
- Enable or disable log-in to testing servers. Defaults to False.
+ Enable or disable login to the test servers. Defaults to False.
Only applicable for new sessions and will be ignored in case previously
created sessions are loaded.
+ bot_token (``str``, *optional*):
+ Pass your Bot API token to create a bot session, e.g.: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
+ Only applicable for new sessions.
+
phone_number (``str`` | ``callable``, *optional*):
Pass your phone number as string (with your Country Code prefix included) to avoid entering it manually.
Or pass a callback function which accepts no arguments and must return the correct phone number as string
@@ -144,10 +144,6 @@ class Client(Methods, BaseClient):
a new Telegram account in case the phone number you passed is not registered yet.
Only applicable for new sessions.
- bot_token (``str``, *optional*):
- Pass your Bot API token to create a bot session, e.g.: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
- Only applicable for new sessions.
-
last_name (``str``, *optional*):
Same purpose as *first_name*; pass a Last Name to avoid entering it manually. It can
be an empty string: "". Only applicable for new sessions.
@@ -173,7 +169,7 @@ class Client(Methods, BaseClient):
Defaults to False (updates enabled and always received).
takeout (``bool``, *optional*):
- Pass True to let the client use a takeout session instead of a normal one, implies no_updates.
+ Pass True to let the client use a takeout session instead of a normal one, implies *no_updates=True*.
Useful for exporting your Telegram data. Methods invoked inside a takeout session (such as get_history,
download_media, ...) are less prone to throw FloodWait exceptions.
Only available for users, bots will ignore this parameter.
@@ -194,12 +190,12 @@ class Client(Methods, BaseClient):
ipv6: bool = False,
proxy: dict = None,
test_mode: bool = False,
+ bot_token: str = None,
phone_number: str = None,
phone_code: Union[str, callable] = None,
password: str = None,
recovery_code: callable = None,
force_sms: bool = False,
- bot_token: str = None,
first_name: str = None,
last_name: str = None,
workers: int = BaseClient.WORKERS,
@@ -222,12 +218,12 @@ class Client(Methods, BaseClient):
# TODO: Make code consistent, use underscore for private/protected fields
self._proxy = proxy
self.test_mode = test_mode
+ self.bot_token = bot_token
self.phone_number = phone_number
self.phone_code = phone_code
self.password = password
self.recovery_code = recovery_code
self.force_sms = force_sms
- self.bot_token = bot_token
self.first_name = first_name
self.last_name = last_name
self.workers = workers
@@ -268,12 +264,11 @@ class Client(Methods, BaseClient):
self._proxy.update(value)
async def start(self):
- """Use this method to start the Client after creating it.
- Requires no parameters.
+ """Start the Client.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ConnectionError`` in case you try to start an already started Client.
+ RPCError: In case of a Telegram RPC error.
+ ConnectionError: In case you try to start an already started Client.
"""
if self.is_started:
raise ConnectionError("Client has already been started")
@@ -285,7 +280,7 @@ class Client(Methods, BaseClient):
log.warning('\nWARNING: You are using a bot token as session name!\n'
'This usage will be deprecated soon. Please use a session file name to load '
'an existing session and the bot_token argument to create new sessions.\n'
- 'More info: https://docs.pyrogram.ml/start/Setup#bot-authorization\n')
+ 'More info: https://docs.pyrogram.org/intro/auth#bot-authorization\n')
self.load_config()
await self.load_session()
@@ -351,11 +346,10 @@ class Client(Methods, BaseClient):
return self
async def stop(self):
- """Use this method to manually stop the Client.
- Requires no parameters.
+ """Stop the Client.
Raises:
- ``ConnectionError`` in case you try to stop an already stopped Client.
+ ConnectionError: In case you try to stop an already stopped Client.
"""
if not self.is_started:
raise ConnectionError("Client is already stopped")
@@ -391,25 +385,34 @@ class Client(Methods, BaseClient):
return self
async def restart(self):
- """Use this method to restart the Client.
- Requires no parameters.
+ """Restart the Client.
Raises:
- ``ConnectionError`` in case you try to restart a stopped Client.
+ ConnectionError: In case you try to restart a stopped Client.
"""
await self.stop()
await self.start()
async def idle(self, stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)):
- """Blocks the program execution until one of the signals are received,
- then gently stop the Client by closing the underlying connection.
+ """Block the main script execution until a signal (e.g.: from CTRL+C) is received.
+ Once the signal is received, the client will automatically stop and the main script will continue its execution.
- Args:
+ This is used after starting one or more clients and is useful for event-driven applications only, that are,
+ applications which react upon incoming Telegram updates through handlers, rather than executing a set of methods
+ sequentially.
+
+ The way Pyrogram works, will keep your handlers in a pool of workers, which are executed concurrently outside
+ the main script; calling idle() will ensure the client(s) will be kept alive by not letting the main script to
+ end, until you decide to quit.
+
+ Parameters:
stop_signals (``tuple``, *optional*):
Iterable containing signals the signal handler will listen to.
Defaults to (SIGINT, SIGTERM, SIGABRT).
"""
+ # TODO: Maybe make this method static and don't automatically stop
+
def signal_handler(*args):
log.info("Stop signal received ({}). Exiting...".format(args[0]))
self.is_idle = False
@@ -425,16 +428,18 @@ class Client(Methods, BaseClient):
await self.stop()
def run(self, coroutine=None):
- """Use this method to automatically start and idle a Client.
- If a coroutine is passed as argument this method will start the client, run the coroutine
- until is complete and then stop the client automatically.
+ """Start the Client and automatically idle the main script.
+
+ This is a convenience method that literally just calls :meth:`start` and :meth:`idle`. It makes running a client
+ less verbose, but is not suitable in case you want to run more than one client in a single main script,
+ since :meth:`idle` will block.
Args:
coroutine: (``Coroutine``, *optional*):
Pass a coroutine to run it until is complete.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
run = asyncio.get_event_loop().run_until_complete
@@ -452,13 +457,13 @@ class Client(Methods, BaseClient):
return coroutine
def add_handler(self, handler: Handler, group: int = 0):
- """Use this method to register an update handler.
+ """Register an update handler.
You can register multiple handlers, but at most one handler within a group
will be used for a single update. To handle the same update more than once, register
your handler using a different group id (lower group id == higher priority).
- Args:
+ Parameters:
handler (``Handler``):
The handler to be registered.
@@ -466,7 +471,7 @@ class Client(Methods, BaseClient):
The group identifier, defaults to 0.
Returns:
- A tuple of (handler, group)
+ ``tuple``: A tuple consisting of (handler, group).
"""
if isinstance(handler, DisconnectHandler):
self.disconnect_handler = handler.callback
@@ -476,13 +481,13 @@ class Client(Methods, BaseClient):
return handler, group
def remove_handler(self, handler: Handler, group: int = 0):
- """Removes a previously-added update handler.
+ """Remove a previously-registered update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly.
- Args:
+ Parameters:
handler (``Handler``):
The handler to be removed.
@@ -495,7 +500,7 @@ class Client(Methods, BaseClient):
self.dispatcher.remove_handler(handler, group)
def stop_transmission(self):
- """Use this method to stop downloading or uploading a file.
+ """Stop downloading or uploading a file.
Must be called inside a progress callback function.
"""
raise Client.StopTransmission
@@ -763,9 +768,16 @@ class Client(Methods, BaseClient):
print("Logged in successfully as {}".format(r.user.first_name))
- def fetch_peers(self, entities: List[Union[types.User,
- types.Chat, types.ChatForbidden,
- types.Channel, types.ChannelForbidden]]):
+ def fetch_peers(
+ self,
+ entities: List[
+ Union[
+ types.User,
+ types.Chat, types.ChatForbidden,
+ types.Channel, types.ChannelForbidden
+ ]
+ ]
+ ):
for entity in entities:
if isinstance(entity, types.User):
user_id = entity.id
@@ -1027,14 +1039,20 @@ class Client(Methods, BaseClient):
data: Object,
retries: int = Session.MAX_RETRIES,
timeout: float = Session.WAIT_TIMEOUT):
- """Use this method to send Raw Function queries.
+ """Send raw Telegram queries.
- This method makes possible to manually call every single Telegram API method in a low-level manner.
+ This method makes it possible to manually call every single Telegram API method in a low-level manner.
Available functions are listed in the :obj:`functions ` package and may accept compound
data types from :obj:`types ` as well as bare types such as ``int``, ``str``, etc...
- Args:
- data (``Object``):
+ .. note::
+
+ This is a utility method intended to be used **only** when working with raw
+ :obj:`functions ` (i.e: a Telegram API method you wish to use which is not
+ available yet in the Client class as an easy-to-use method).
+
+ Parameters:
+ data (``RawFunction``):
The API Schema function filled with proper arguments.
retries (``int``):
@@ -1043,8 +1061,11 @@ class Client(Methods, BaseClient):
timeout (``float``):
Timeout in seconds.
+ Returns:
+ ``RawType``: The raw type response generated by the query.
+
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
if not self.is_started:
raise ConnectionError("Client has not been started")
@@ -1075,7 +1096,7 @@ class Client(Methods, BaseClient):
else:
raise AttributeError(
"No API Key found. "
- "More info: https://docs.pyrogram.ml/start/ProjectSetup#configuration"
+ "More info: https://docs.pyrogram.org/intro/setup#configuration"
)
for option in ["app_version", "device_model", "system_version", "lang_code"]:
@@ -1325,23 +1346,26 @@ class Client(Methods, BaseClient):
async def resolve_peer(self,
peer_id: Union[int, str]):
- """Use this method to get the InputPeer of a known peer_id.
+ """Get the InputPeer of a known peer id.
+ Useful whenever an InputPeer type is required.
- This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API
- method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an
- InputPeer type is required.
+ .. note::
- Args:
+ This is a utility method intended to be used **only** when working with raw
+ :obj:`functions ` (i.e: a Telegram API method you wish to use which is not
+ available yet in the Client class as an easy-to-use method).
+
+ Parameters:
peer_id (``int`` | ``str``):
The peer id you want to extract the InputPeer from.
Can be a direct id (int), a username (str) or a phone number (str).
Returns:
- On success, the resolved peer id is returned in form of an InputPeer object.
+ ``InputPeer``: On success, the resolved peer id is returned in form of an InputPeer object.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``KeyError`` in case the peer doesn't exist in the internal database.
+ RPCError: In case of a Telegram RPC error.
+ KeyError: In case the peer doesn't exist in the internal database.
"""
try:
return self.peers_by_id[peer_id]
@@ -1399,14 +1423,18 @@ class Client(Methods, BaseClient):
file_id: int = None,
file_part: int = 0,
progress: callable = None,
- progress_args: tuple = ()):
- """Use this method to upload a file onto Telegram servers, without actually sending the message to anyone.
+ progress_args: tuple = ()
+ ):
+ """Upload a file onto Telegram servers, without actually sending the message to anyone.
+ Useful whenever an InputFile type is required.
- This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API
- method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an
- InputFile type is required.
+ .. note::
- Args:
+ This is a utility method intended to be used **only** when working with raw
+ :obj:`functions ` (i.e: a Telegram API method you wish to use which is not
+ available yet in the Client class as an easy-to-use method).
+
+ Parameters:
path (``str``):
The path of the file you want to upload that exists on your local machine.
@@ -1426,7 +1454,7 @@ class Client(Methods, BaseClient):
a chat_id and a message_id in order to edit a message with the updated progress.
Other Parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the callback function.
current (``int``):
@@ -1440,10 +1468,10 @@ class Client(Methods, BaseClient):
You can either keep *\*args* or add every single extra argument in your function signature.
Returns:
- On success, the uploaded file is returned in form of an InputFile object.
+ ``InputFile``: On success, the uploaded file is returned in form of an InputFile object.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
async def worker(session):
diff --git a/pyrogram/client/ext/__init__.py b/pyrogram/client/ext/__init__.py
index 18c28ac3..917c9e62 100644
--- a/pyrogram/client/ext/__init__.py
+++ b/pyrogram/client/ext/__init__.py
@@ -17,8 +17,6 @@
# along with Pyrogram. If not, see .
from .base_client import BaseClient
-from .chat_action import ChatAction
from .dispatcher import Dispatcher
from .emoji import Emoji
-from .parse_mode import ParseMode
from .syncer import Syncer
diff --git a/pyrogram/client/ext/base_client.py b/pyrogram/client/ext/base_client.py
index 3c2311fe..9377cce8 100644
--- a/pyrogram/client/ext/base_client.py
+++ b/pyrogram/client/ext/base_client.py
@@ -30,7 +30,7 @@ class BaseClient:
class StopTransmission(StopAsyncIteration):
pass
- APP_VERSION = "Pyrogram \U0001f525 {}".format(__version__)
+ APP_VERSION = "Pyrogram {}".format(__version__)
DEVICE_MODEL = "{} {}".format(
platform.python_implementation(),
diff --git a/pyrogram/client/ext/chat_action.py b/pyrogram/client/ext/chat_action.py
deleted file mode 100644
index c0ee0585..00000000
--- a/pyrogram/client/ext/chat_action.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# Pyrogram - Telegram MTProto API Client Library for Python
-# Copyright (C) 2017-2019 Dan Tès
-#
-# This file is part of Pyrogram.
-#
-# Pyrogram is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Lesser General Public License as published
-# by the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# Pyrogram is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with Pyrogram. If not, see .
-
-from enum import Enum
-
-from pyrogram.api import types
-
-
-class ChatAction(Enum):
- """This enumeration provides a convenient access to all Chat Actions available.
- Chat Actions are intended to be used with
- :meth:`send_chat_action() `.
- """
-
- CANCEL = types.SendMessageCancelAction
- """Cancels any chat action currently displayed."""
-
- TYPING = types.SendMessageTypingAction
- """User is typing a text message."""
-
- PLAYING = types.SendMessageGamePlayAction
- """User is playing a game."""
-
- CHOOSE_CONTACT = types.SendMessageChooseContactAction
- """User is choosing a contact to share."""
-
- UPLOAD_PHOTO = types.SendMessageUploadPhotoAction
- """User is uploading a photo."""
-
- RECORD_VIDEO = types.SendMessageRecordVideoAction
- """User is recording a video."""
-
- UPLOAD_VIDEO = types.SendMessageUploadVideoAction
- """User is uploading a video."""
-
- RECORD_AUDIO = types.SendMessageRecordAudioAction
- """User is recording an audio message."""
-
- UPLOAD_AUDIO = types.SendMessageUploadAudioAction
- """User is uploading an audio message."""
-
- UPLOAD_DOCUMENT = types.SendMessageUploadDocumentAction
- """User is uploading a generic document."""
-
- FIND_LOCATION = types.SendMessageGeoLocationAction
- """User is searching for a location on the map."""
-
- RECORD_VIDEO_NOTE = types.SendMessageRecordRoundAction
- """User is recording a round video note."""
-
- UPLOAD_VIDEO_NOTE = types.SendMessageUploadRoundAction
- """User is uploading a round video note."""
-
- @staticmethod
- def from_string(action: str) -> "ChatAction":
- for a in ChatAction:
- if a.name.lower() == action.lower():
- return a
-
- raise ValueError("Invalid ChatAction: '{}'. Possible types are {}".format(
- action, [x.name.lower() for x in ChatAction]
- ))
diff --git a/pyrogram/client/ext/parse_mode.py b/pyrogram/client/ext/parse_mode.py
deleted file mode 100644
index 46ed97e3..00000000
--- a/pyrogram/client/ext/parse_mode.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# Pyrogram - Telegram MTProto API Client Library for Python
-# Copyright (C) 2017-2019 Dan Tès
-#
-# This file is part of Pyrogram.
-#
-# Pyrogram is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Lesser General Public License as published
-# by the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# Pyrogram is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with Pyrogram. If not, see .
-
-
-class ParseMode:
- """This class provides a convenient access to Parse Modes.
- Parse Modes are intended to be used with any method that accepts the optional argument **parse_mode**.
- """
-
- HTML = "html"
- """Set the parse mode to HTML style"""
-
- MARKDOWN = "markdown"
- """Set the parse mode to Markdown style"""
diff --git a/pyrogram/client/filters/filters.py b/pyrogram/client/filters/filters.py
index 4c6f0ce3..169193a0 100644
--- a/pyrogram/client/filters/filters.py
+++ b/pyrogram/client/filters/filters.py
@@ -19,15 +19,15 @@
import re
from .filter import Filter
-from ..types.bots import InlineKeyboardMarkup, ReplyKeyboardMarkup
+from ..types.keyboards import InlineKeyboardMarkup, ReplyKeyboardMarkup
def create(name: str, func: callable, **kwargs) -> type:
- """Use this method to create a Filter.
+ """Create a Filter.
Custom filters give you extra control over which updates are allowed or not to be processed by your handlers.
- Args:
+ Parameters:
name (``str``):
Your filter's name. Can be anything you like.
@@ -35,9 +35,9 @@ def create(name: str, func: callable, **kwargs) -> type:
A function that accepts two arguments *(filter, update)* and returns a Boolean: True if the update should be
handled, False otherwise.
The "update" argument type will vary depending on which `Handler `_ is coming from.
- For example, in a :obj:`MessageHandler ` the update type will be
- a :obj:`Message `; in a :obj:`CallbackQueryHandler ` the
- update type will be a :obj:`CallbackQuery `. Your function body can then access the
+ For example, in a :obj:`MessageHandler` the update type will be
+ a :obj:`Message`; in a :obj:`CallbackQueryHandler` the
+ update type will be a :obj:`CallbackQuery`. Your function body can then access the
incoming update and decide whether to allow it or not.
**kwargs (``any``, *optional*):
@@ -54,7 +54,7 @@ def create(name: str, func: callable, **kwargs) -> type:
class Filters:
"""This class provides access to all library-defined Filters available in Pyrogram.
- The Filters listed here are intended to be used with the :obj:`MessageHandler ` only.
+ The Filters listed here are intended to be used with the :obj:`MessageHandler` only.
At the moment, if you want to filter updates coming from different `Handlers `_ you have to create
your own filters with :meth:`Filters.create` and use them in the same way.
"""
@@ -89,49 +89,49 @@ class Filters:
"""Filter edited messages."""
audio = create("Audio", lambda _, m: bool(m.audio))
- """Filter messages that contain :obj:`Audio ` objects."""
+ """Filter messages that contain :obj:`Audio` objects."""
document = create("Document", lambda _, m: bool(m.document))
- """Filter messages that contain :obj:`Document ` objects."""
+ """Filter messages that contain :obj:`Document` objects."""
photo = create("Photo", lambda _, m: bool(m.photo))
- """Filter messages that contain :obj:`Photo ` objects."""
+ """Filter messages that contain :obj:`Photo` objects."""
sticker = create("Sticker", lambda _, m: bool(m.sticker))
- """Filter messages that contain :obj:`Sticker ` objects."""
+ """Filter messages that contain :obj:`Sticker` objects."""
animation = create("Animation", lambda _, m: bool(m.animation))
- """Filter messages that contain :obj:`Animation ` objects."""
+ """Filter messages that contain :obj:`Animation` objects."""
game = create("Game", lambda _, m: bool(m.game))
- """Filter messages that contain :obj:`Game ` objects."""
+ """Filter messages that contain :obj:`Game` objects."""
video = create("Video", lambda _, m: bool(m.video))
- """Filter messages that contain :obj:`Video ` objects."""
+ """Filter messages that contain :obj:`Video` objects."""
media_group = create("MediaGroup", lambda _, m: bool(m.media_group_id))
"""Filter messages containing photos or videos being part of an album."""
voice = create("Voice", lambda _, m: bool(m.voice))
- """Filter messages that contain :obj:`Voice ` note objects."""
+ """Filter messages that contain :obj:`Voice` note objects."""
video_note = create("VideoNote", lambda _, m: bool(m.video_note))
- """Filter messages that contain :obj:`VideoNote ` objects."""
+ """Filter messages that contain :obj:`VideoNote` objects."""
contact = create("Contact", lambda _, m: bool(m.contact))
- """Filter messages that contain :obj:`Contact ` objects."""
+ """Filter messages that contain :obj:`Contact` objects."""
location = create("Location", lambda _, m: bool(m.location))
- """Filter messages that contain :obj:`Location ` objects."""
+ """Filter messages that contain :obj:`Location` objects."""
venue = create("Venue", lambda _, m: bool(m.venue))
- """Filter messages that contain :obj:`Venue ` objects."""
+ """Filter messages that contain :obj:`Venue` objects."""
web_page = create("WebPage", lambda _, m: m.web_page)
"""Filter messages sent with a webpage preview."""
poll = create("Poll", lambda _, m: m.poll)
- """Filter messages that contain :obj:`Poll ` objects."""
+ """Filter messages that contain :obj:`Poll` objects."""
private = create("Private", lambda _, m: bool(m.chat and m.chat.type == "private"))
"""Filter messages sent in private chats."""
@@ -191,35 +191,19 @@ class Filters:
"""Filter messages sent via inline bots"""
service = create("Service", lambda _, m: bool(m.service))
- """Filter service messages. A service message contains any of the following fields set
+ """Filter service messages.
- - left_chat_member
- - new_chat_title
- - new_chat_photo
- - delete_chat_photo
- - group_chat_created
- - supergroup_chat_created
- - channel_chat_created
- - migrate_to_chat_id
- - migrate_from_chat_id
- - pinned_message
- - game_score"""
+ A service message contains any of the following fields set: *left_chat_member*,
+ *new_chat_title*, *new_chat_photo*, *delete_chat_photo*, *group_chat_created*, *supergroup_chat_created*,
+ *channel_chat_created*, *migrate_to_chat_id*, *migrate_from_chat_id*, *pinned_message*, *game_score*.
+ """
media = create("Media", lambda _, m: bool(m.media))
- """Filter media messages. A media message contains any of the following fields set
+ """Filter media messages.
- - audio
- - document
- - photo
- - sticker
- - video
- - animation
- - voice
- - video_note
- - contact
- - location
- - venue
- - poll"""
+ A media message contains any of the following fields set: *audio*, *document*, *photo*, *sticker*, *video*,
+ *animation*, *voice*, *video_note*, *contact*, *location*, *venue*, *poll*.
+ """
@staticmethod
def command(
@@ -230,12 +214,12 @@ class Filters:
):
"""Filter commands, i.e.: text messages starting with "/" or any other custom prefix.
- Args:
+ Parameters:
commands (``str`` | ``list``):
The command or list of commands as string the filter should look for.
Examples: "start", ["start", "help", "settings"]. When a message text containing
a command arrives, the command itself and its arguments will be stored in the *command*
- field of the :class:`Message `.
+ field of the :class:`Message`.
prefix (``str`` | ``list``, *optional*):
A prefix or a list of prefixes as string the filter should look for.
@@ -275,11 +259,11 @@ class Filters:
def regex(pattern, flags: int = 0):
"""Filter messages that match a given RegEx pattern.
- Args:
+ Parameters:
pattern (``str``):
The RegEx pattern as string, it will be applied to the text of a message. When a pattern matches,
all the `Match Objects `_
- are stored in the *matches* field of the :class:`Message ` itself.
+ are stored in the *matches* field of the :class:`Message` itself.
flags (``int``, *optional*):
RegEx flags.
@@ -298,7 +282,7 @@ class Filters:
You can use `set bound methods `_ to manipulate the
users container.
- Args:
+ Parameters:
users (``int`` | ``str`` | ``list``):
Pass one or more user ids/usernames to filter users.
For you yourself, "me" or "self" can be used as well.
@@ -329,7 +313,7 @@ class Filters:
You can use `set bound methods `_ to manipulate the
chats container.
- Args:
+ Parameters:
chats (``int`` | ``str`` | ``list``):
Pass one or more chat ids/usernames to filter chats.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
diff --git a/pyrogram/client/handlers/callback_query_handler.py b/pyrogram/client/handlers/callback_query_handler.py
index 88ddd5a0..feb46cb0 100644
--- a/pyrogram/client/handlers/callback_query_handler.py
+++ b/pyrogram/client/handlers/callback_query_handler.py
@@ -26,17 +26,17 @@ class CallbackQueryHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_callback_query() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a new CallbackQuery arrives. It takes *(client, callback_query)*
as positional arguments (look at the section below for a detailed description).
- filters (:obj:`Filters `):
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of callback queries to be passed
in your callback function.
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the message handler.
callback_query (:obj:`CallbackQuery `):
diff --git a/pyrogram/client/handlers/deleted_messages_handler.py b/pyrogram/client/handlers/deleted_messages_handler.py
index 52177dcc..f37caaed 100644
--- a/pyrogram/client/handlers/deleted_messages_handler.py
+++ b/pyrogram/client/handlers/deleted_messages_handler.py
@@ -27,20 +27,20 @@ class DeletedMessagesHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_deleted_messages() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when one or more Messages have been deleted.
It takes *(client, messages)* as positional arguments (look at the section below for a detailed description).
- filters (:obj:`Filters `):
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of messages to be passed
in your callback function.
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the message handler.
- messages (:obj:`Messages `):
+ messages (:obj:`Messages`):
The deleted messages.
"""
diff --git a/pyrogram/client/handlers/disconnect_handler.py b/pyrogram/client/handlers/disconnect_handler.py
index 1e88a7ee..b9e6350a 100644
--- a/pyrogram/client/handlers/disconnect_handler.py
+++ b/pyrogram/client/handlers/disconnect_handler.py
@@ -26,13 +26,13 @@ class DisconnectHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_disconnect() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a disconnection occurs. It takes *(client)*
as positional argument (look at the section below for a detailed description).
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself. Useful, for example, when you want to change the proxy before a new connection
is established.
"""
diff --git a/pyrogram/client/handlers/inline_query_handler.py b/pyrogram/client/handlers/inline_query_handler.py
index c64d49c8..98a25652 100644
--- a/pyrogram/client/handlers/inline_query_handler.py
+++ b/pyrogram/client/handlers/inline_query_handler.py
@@ -26,20 +26,20 @@ class InlineQueryHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_inline_query() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a new InlineQuery arrives. It takes *(client, inline_query)*
as positional arguments (look at the section below for a detailed description).
- filters (:obj:`Filters `):
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of inline queries to be passed
in your callback function.
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the inline query handler.
- inline_query (:obj:`InlineQuery `):
+ inline_query (:obj:`InlineQuery`):
The received inline query.
"""
diff --git a/pyrogram/client/handlers/message_handler.py b/pyrogram/client/handlers/message_handler.py
index 67b4587e..10fff479 100644
--- a/pyrogram/client/handlers/message_handler.py
+++ b/pyrogram/client/handlers/message_handler.py
@@ -27,20 +27,20 @@ class MessageHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_message() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a new Message arrives. It takes *(client, message)*
as positional arguments (look at the section below for a detailed description).
- filters (:obj:`Filters `):
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of messages to be passed
in your callback function.
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the message handler.
- message (:obj:`Message `):
+ message (:obj:`Message`):
The received message.
"""
diff --git a/pyrogram/client/handlers/poll_handler.py b/pyrogram/client/handlers/poll_handler.py
index 567fcec0..9e97f2ac 100644
--- a/pyrogram/client/handlers/poll_handler.py
+++ b/pyrogram/client/handlers/poll_handler.py
@@ -27,7 +27,7 @@ class PollHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_poll() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a new poll update arrives. It takes *(client, poll)*
as positional arguments (look at the section below for a detailed description).
diff --git a/pyrogram/client/handlers/raw_update_handler.py b/pyrogram/client/handlers/raw_update_handler.py
index 3a5dea50..f54d59b6 100644
--- a/pyrogram/client/handlers/raw_update_handler.py
+++ b/pyrogram/client/handlers/raw_update_handler.py
@@ -26,14 +26,14 @@ class RawUpdateHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_raw_update() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
A function that will be called when a new update is received from the server. It takes
*(client, update, users, chats)* as positional arguments (look at the section below for
a detailed description).
Other Parameters:
- client (:class:`Client `):
+ client (:class:`Client`):
The Client itself, useful when you want to call other API methods inside the update handler.
update (``Update``):
diff --git a/pyrogram/client/handlers/user_status_handler.py b/pyrogram/client/handlers/user_status_handler.py
index 856ef81d..1250cb19 100644
--- a/pyrogram/client/handlers/user_status_handler.py
+++ b/pyrogram/client/handlers/user_status_handler.py
@@ -26,20 +26,20 @@ class UserStatusHandler(Handler):
For a nicer way to register this handler, have a look at the
:meth:`on_user_status() ` decorator.
- Args:
+ Parameters:
callback (``callable``):
Pass a function that will be called when a new UserStatus update arrives. It takes *(client, user_status)*
as positional arguments (look at the section below for a detailed description).
- filters (:obj:`Filters `):
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of messages to be passed
in your callback function.
Other parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the user status handler.
- user_status (:obj:`UserStatus `):
+ user_status (:obj:`UserStatus`):
The received UserStatus update.
"""
diff --git a/pyrogram/client/methods/bots/answer_callback_query.py b/pyrogram/client/methods/bots/answer_callback_query.py
index 7c8754e2..3dab25d2 100644
--- a/pyrogram/client/methods/bots/answer_callback_query.py
+++ b/pyrogram/client/methods/bots/answer_callback_query.py
@@ -29,10 +29,10 @@ class AnswerCallbackQuery(BaseClient):
url: str = None,
cache_time: int = 0
):
- """Use this method to send answers to callback queries sent from inline keyboards.
+ """Send answers to callback queries sent from inline keyboards.
The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
- Args:
+ Parameters:
callback_query_id (``str``):
Unique identifier for the query to be answered.
@@ -54,10 +54,10 @@ class AnswerCallbackQuery(BaseClient):
Telegram apps will support caching starting in version 3.14. Defaults to 0.
Returns:
- True, on success.
+ ``bool``: True, on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
return await self.send(
functions.messages.SetBotCallbackAnswer(
diff --git a/pyrogram/client/methods/bots/answer_inline_query.py b/pyrogram/client/methods/bots/answer_inline_query.py
index 88a661d0..daf8423b 100644
--- a/pyrogram/client/methods/bots/answer_inline_query.py
+++ b/pyrogram/client/methods/bots/answer_inline_query.py
@@ -34,10 +34,10 @@ class AnswerInlineQuery(BaseClient):
switch_pm_text: str = "",
switch_pm_parameter: str = ""
):
- """Use this method to send answers to an inline query.
+ """Send answers to an inline query.
No more than 50 results per query are allowed.
- Args:
+ Parameters:
inline_query_id (``str``):
Unique identifier for the answered query.
@@ -73,7 +73,10 @@ class AnswerInlineQuery(BaseClient):
where they wanted to use the bot's inline capabilities.
Returns:
- On success, True is returned.
+ ``bool``: True, on success.
+
+ Raises:
+ RPCError: In case of a Telegram RPC error.
"""
written_results = [] # Py 3.5 doesn't support await inside comprehensions
diff --git a/pyrogram/client/methods/bots/get_game_high_scores.py b/pyrogram/client/methods/bots/get_game_high_scores.py
index 40e68dda..a11eaba3 100644
--- a/pyrogram/client/methods/bots/get_game_high_scores.py
+++ b/pyrogram/client/methods/bots/get_game_high_scores.py
@@ -29,10 +29,10 @@ class GetGameHighScores(BaseClient):
user_id: Union[int, str],
chat_id: Union[int, str],
message_id: int = None
- ):
- """Use this method to get data for high score tables.
+ ) -> "pyrogram.GameHighScores":
+ """Get data for high score tables.
- Args:
+ Parameters:
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -49,10 +49,10 @@ class GetGameHighScores(BaseClient):
Required if inline_message_id is not specified.
Returns:
- On success, a :obj:`GameHighScores ` object is returned.
+ :obj:`GameHighScores`: On success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
# TODO: inline_message_id
diff --git a/pyrogram/client/methods/bots/get_inline_bot_results.py b/pyrogram/client/methods/bots/get_inline_bot_results.py
index c523d9a7..d5dbd9f2 100644
--- a/pyrogram/client/methods/bots/get_inline_bot_results.py
+++ b/pyrogram/client/methods/bots/get_inline_bot_results.py
@@ -32,10 +32,10 @@ class GetInlineBotResults(BaseClient):
latitude: float = None,
longitude: float = None
):
- """Use this method to get bot results via inline queries.
+ """Get bot results via inline queries.
You can then send a result using :obj:`send_inline_bot_result `
- Args:
+ Parameters:
bot (``int`` | ``str``):
Unique identifier of the inline bot you want to get results from. You can specify
a @username (str) or a bot ID (int).
@@ -55,11 +55,11 @@ class GetInlineBotResults(BaseClient):
Useful for location-based results only.
Returns:
- On Success, :obj:`BotResults ` is returned.
+ :obj:`BotResults `: On Success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``TimeoutError`` if the bot fails to answer within 10 seconds
+ RPCError: In case of a Telegram RPC error.
+ TimeoutError: In case the bot fails to answer within 10 seconds.
"""
# TODO: Don't return the raw type
diff --git a/pyrogram/client/methods/bots/request_callback_answer.py b/pyrogram/client/methods/bots/request_callback_answer.py
index 6afe8551..86855a92 100644
--- a/pyrogram/client/methods/bots/request_callback_answer.py
+++ b/pyrogram/client/methods/bots/request_callback_answer.py
@@ -27,12 +27,13 @@ class RequestCallbackAnswer(BaseClient):
self,
chat_id: Union[int, str],
message_id: int,
- callback_data: bytes
+ callback_data: Union[str, bytes],
+ timeout: int = 10
):
- """Use this method to request a callback answer from bots.
+ """Request a callback answer from bots.
This is the equivalent of clicking an inline button containing callback data.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -41,23 +42,30 @@ class RequestCallbackAnswer(BaseClient):
message_id (``int``):
The message id the inline keyboard is attached on.
- callback_data (``bytes``):
+ callback_data (``str`` | ``bytes``):
Callback data associated with the inline button you want to get the answer from.
+ timeout (``int``, *optional*):
+ Timeout in seconds.
+
Returns:
The answer containing info useful for clients to display a notification at the top of the chat screen
or as an alert.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``TimeoutError`` if the bot fails to answer within 10 seconds.
+ RPCError: In case of a Telegram RPC error.
+ TimeoutError: In case the bot fails to answer within 10 seconds.
"""
+
+ # Telegram only wants bytes, but we are allowed to pass strings too.
+ data = bytes(callback_data, "utf-8") if isinstance(callback_data, str) else callback_data
+
return await self.send(
functions.messages.GetBotCallbackAnswer(
- peer=self.resolve_peer(chat_id),
+ peer=await self.resolve_peer(chat_id),
msg_id=message_id,
- data=callback_data
+ data=data
),
retries=0,
- timeout=10
+ timeout=timeout
)
diff --git a/pyrogram/client/methods/bots/send_game.py b/pyrogram/client/methods/bots/send_game.py
index 91ce1402..f579630d 100644
--- a/pyrogram/client/methods/bots/send_game.py
+++ b/pyrogram/client/methods/bots/send_game.py
@@ -37,9 +37,9 @@ class SendGame(BaseClient):
"pyrogram.ForceReply"
] = None
) -> "pyrogram.Message":
- """Use this method to send a game.
+ """Send a game.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -60,10 +60,10 @@ class SendGame(BaseClient):
If not empty, the first button must launch the game.
Returns:
- On success, the sent :obj:`Message` is returned.
+ :obj:`Message`: On success, the sent game message is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
r = await self.send(
functions.messages.SendMedia(
diff --git a/pyrogram/client/methods/bots/send_inline_bot_result.py b/pyrogram/client/methods/bots/send_inline_bot_result.py
index a881e8c7..64f90529 100644
--- a/pyrogram/client/methods/bots/send_inline_bot_result.py
+++ b/pyrogram/client/methods/bots/send_inline_bot_result.py
@@ -32,10 +32,10 @@ class SendInlineBotResult(BaseClient):
reply_to_message_id: int = None,
hide_via: bool = None
):
- """Use this method to send an inline bot result.
+ """Send an inline bot result.
Bot results can be retrieved using :obj:`get_inline_bot_results `
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -58,10 +58,10 @@ class SendInlineBotResult(BaseClient):
Sends the message with *via @bot* hidden.
Returns:
- On success, the sent Message is returned.
+ :obj:`Message`: On success, the sent inline result message is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
return await self.send(
functions.messages.SendInlineBotResult(
diff --git a/pyrogram/client/methods/bots/set_game_score.py b/pyrogram/client/methods/bots/set_game_score.py
index 5c871b4b..757eba3f 100644
--- a/pyrogram/client/methods/bots/set_game_score.py
+++ b/pyrogram/client/methods/bots/set_game_score.py
@@ -32,11 +32,11 @@ class SetGameScore(BaseClient):
disable_edit_message: bool = None,
chat_id: Union[int, str] = None,
message_id: int = None
- ):
+ ) -> Union["pyrogram.Message", bool]:
# inline_message_id: str = None): TODO Add inline_message_id
- """Use this method to set the score of the specified user in a game.
+ """Set the score of the specified user in a game.
- Args:
+ Parameters:
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -63,12 +63,11 @@ class SetGameScore(BaseClient):
Required if inline_message_id is not specified.
Returns:
- On success, if the message was sent by the bot, returns the edited :obj:`Message `,
- otherwise returns True.
+ :obj:`Message` | ``bool``: On success, if the message was sent by the bot, the edited message is returned,
+ True otherwise.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- :class:`BotScoreNotModified` if the new score is not greater than the user's current score in the chat and force is False.
+ RPCError: In case of a Telegram RPC error.
"""
r = await self.send(
functions.messages.SetGameScore(
diff --git a/pyrogram/client/methods/chats/__init__.py b/pyrogram/client/methods/chats/__init__.py
index 8db44abe..698255f5 100644
--- a/pyrogram/client/methods/chats/__init__.py
+++ b/pyrogram/client/methods/chats/__init__.py
@@ -22,7 +22,6 @@ from .get_chat import GetChat
from .get_chat_member import GetChatMember
from .get_chat_members import GetChatMembers
from .get_chat_members_count import GetChatMembersCount
-from .get_chat_preview import GetChatPreview
from .get_dialogs import GetDialogs
from .iter_chat_members import IterChatMembers
from .iter_dialogs import IterDialogs
@@ -61,7 +60,6 @@ class Chats(
UnpinChatMessage,
GetDialogs,
GetChatMembersCount,
- GetChatPreview,
IterDialogs,
IterChatMembers,
UpdateChatUsername,
diff --git a/pyrogram/client/methods/chats/delete_chat_photo.py b/pyrogram/client/methods/chats/delete_chat_photo.py
index 1407f7e7..49f8e5fa 100644
--- a/pyrogram/client/methods/chats/delete_chat_photo.py
+++ b/pyrogram/client/methods/chats/delete_chat_photo.py
@@ -27,7 +27,7 @@ class DeleteChatPhoto(BaseClient):
self,
chat_id: Union[int, str]
) -> bool:
- """Use this method to delete a chat photo.
+ """Delete a chat photo.
Photos can't be changed for private chats.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
@@ -35,15 +35,15 @@ class DeleteChatPhoto(BaseClient):
In regular groups (non-supergroups), this method will only work if the "All Members Are Admins"
setting is off.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
``ValueError`` if a chat_id belongs to user.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/export_chat_invite_link.py b/pyrogram/client/methods/chats/export_chat_invite_link.py
index 2744658e..1e533097 100644
--- a/pyrogram/client/methods/chats/export_chat_invite_link.py
+++ b/pyrogram/client/methods/chats/export_chat_invite_link.py
@@ -27,7 +27,7 @@ class ExportChatInviteLink(BaseClient):
self,
chat_id: Union[int, str]
) -> str:
- """Use this method to generate a new invite link for a chat; any previously generated link is revoked.
+ """Generate a new invite link for a chat; any previously generated link is revoked.
You must be an administrator in the chat for this to work and have the appropriate admin rights.
@@ -38,16 +38,16 @@ class ExportChatInviteLink(BaseClient):
using this method – after this the link will become available to the bot via the :meth:`get_chat` method.
If your bot needs to generate a new invite link replacing its previous one, use this method again.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier for the target chat or username of the target channel/supergroup
(in the format @username).
Returns:
- On success, the exported invite link as string is returned.
+ ``str``: On success, the exported invite link is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/get_chat.py b/pyrogram/client/methods/chats/get_chat.py
index dfc1dbbb..37a7ba13 100644
--- a/pyrogram/client/methods/chats/get_chat.py
+++ b/pyrogram/client/methods/chats/get_chat.py
@@ -27,37 +27,37 @@ class GetChat(BaseClient):
async def get_chat(
self,
chat_id: Union[int, str]
- ) -> "pyrogram.Chat":
- """Use this method to get up to date information about the chat.
+ ) -> Union["pyrogram.Chat", "pyrogram.ChatPreview"]:
+ """Get up to date information about a chat.
+
Information include current name of the user for one-on-one conversations, current username of a user, group or
channel, etc.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Unique identifier for the target chat in form of a *t.me/joinchat/* link, identifier (int) or username
of the target channel/supergroup (in the format @username).
Returns:
- On success, a :obj:`Chat ` object is returned.
+ :obj:`Chat` | :obj:`ChatPreview`: On success, if you've already joined the chat, a chat object is returned,
+ otherwise, a chat preview object is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` in case the chat invite link refers to a chat you haven't joined yet.
+ RPCError: In case of a Telegram RPC error.
+ ValueError: In case the chat invite link points to a chat you haven't joined yet.
"""
match = self.INVITE_LINK_RE.match(str(chat_id))
if match:
- h = match.group(1)
-
r = await self.send(
functions.messages.CheckChatInvite(
- hash=h
+ hash=match.group(1)
)
)
if isinstance(r, types.ChatInvite):
- raise ValueError("You haven't joined \"t.me/joinchat/{}\" yet".format(h))
+ return pyrogram.ChatPreview._parse(self, r)
self.fetch_peers([r.chat])
diff --git a/pyrogram/client/methods/chats/get_chat_member.py b/pyrogram/client/methods/chats/get_chat_member.py
index 584f67a0..e0dfc67d 100644
--- a/pyrogram/client/methods/chats/get_chat_member.py
+++ b/pyrogram/client/methods/chats/get_chat_member.py
@@ -30,9 +30,9 @@ class GetChatMember(BaseClient):
chat_id: Union[int, str],
user_id: Union[int, str]
) -> "pyrogram.ChatMember":
- """Use this method to get information about one member of a chat.
+ """Get information about one member of a chat.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -42,10 +42,10 @@ class GetChatMember(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str).
Returns:
- On success, a :obj:`ChatMember ` object is returned.
+ :obj:`ChatMember`: On success, a chat member is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
chat_id = await self.resolve_peer(chat_id)
user_id = await self.resolve_peer(user_id)
diff --git a/pyrogram/client/methods/chats/get_chat_members.py b/pyrogram/client/methods/chats/get_chat_members.py
index 494ea472..28877b6d 100644
--- a/pyrogram/client/methods/chats/get_chat_members.py
+++ b/pyrogram/client/methods/chats/get_chat_members.py
@@ -46,14 +46,14 @@ class GetChatMembers(BaseClient):
query: str = "",
filter: str = Filters.ALL
) -> "pyrogram.ChatMembers":
- """Use this method to get a chunk of the members list of a chat.
+ """Get a chunk of the members list of a chat.
You can get up to 200 chat members at once.
A chat can be either a basic group, a supergroup or a channel.
You must be admin to retrieve the members list of a channel (also known as "subscribers").
For a more convenient way of getting chat members see :meth:`iter_chat_members`.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -86,11 +86,11 @@ class GetChatMembers(BaseClient):
.. [2] A query string is applicable only for *"all"*, *"kicked"* and *"restricted"* filters only.
Returns:
- On success, a :obj:`ChatMembers` object is returned.
+ :obj:`ChatMembers`: On success, an object containing a list of chat members is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` if you used an invalid filter or a chat_id that belongs to a user.
+ RPCError: In case of a Telegram RPC error.
+ ValueError: In case you used an invalid filter or a chat id that belongs to a user.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/get_chat_members_count.py b/pyrogram/client/methods/chats/get_chat_members_count.py
index ff01d359..118ff072 100644
--- a/pyrogram/client/methods/chats/get_chat_members_count.py
+++ b/pyrogram/client/methods/chats/get_chat_members_count.py
@@ -27,18 +27,18 @@ class GetChatMembersCount(BaseClient):
self,
chat_id: Union[int, str]
) -> int:
- """Use this method to get the number of members in a chat.
+ """Get the number of members in a chat.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
- On success, an integer is returned.
+ ``int``: On success, the chat members count is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` if a chat_id belongs to user.
+ RPCError: In case of a Telegram RPC error.
+ ValueError: In case a chat id belongs to user.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/get_chat_preview.py b/pyrogram/client/methods/chats/get_chat_preview.py
deleted file mode 100644
index 9b6c6955..00000000
--- a/pyrogram/client/methods/chats/get_chat_preview.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# Pyrogram - Telegram MTProto API Client Library for Python
-# Copyright (C) 2017-2019 Dan Tès
-#
-# This file is part of Pyrogram.
-#
-# Pyrogram is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Lesser General Public License as published
-# by the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# Pyrogram is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with Pyrogram. If not, see .
-
-import pyrogram
-from pyrogram.api import functions, types
-from ...ext import BaseClient
-
-
-class GetChatPreview(BaseClient):
- def get_chat_preview(
- self,
- invite_link: str
- ):
- """Use this method to get the preview of a chat using the invite link.
-
- This method only returns a chat preview, if you want to join a chat use :meth:`join_chat`
-
- Args:
- invite_link (``str``):
- Unique identifier for the target chat in form of *t.me/joinchat/* links.
-
- Returns:
- Either :obj:`Chat` or :obj:`ChatPreview`, depending on whether you already joined the chat or not.
-
- Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` in case of an invalid invite_link.
- """
- match = self.INVITE_LINK_RE.match(invite_link)
-
- if match:
- r = self.send(
- functions.messages.CheckChatInvite(
- hash=match.group(1)
- )
- )
-
- if isinstance(r, types.ChatInvite):
- return pyrogram.ChatPreview._parse(self, r)
-
- if isinstance(r, types.ChatInviteAlready):
- chat = r.chat
-
- if isinstance(chat, types.Chat):
- return pyrogram.Chat._parse_chat_chat(self, chat)
-
- if isinstance(chat, types.Channel):
- return pyrogram.Chat._parse_channel_chat(self, chat)
- else:
- raise ValueError("The invite_link is invalid")
diff --git a/pyrogram/client/methods/chats/get_dialogs.py b/pyrogram/client/methods/chats/get_dialogs.py
index ef405f71..cf522dc0 100644
--- a/pyrogram/client/methods/chats/get_dialogs.py
+++ b/pyrogram/client/methods/chats/get_dialogs.py
@@ -34,12 +34,12 @@ class GetDialogs(BaseClient):
limit: int = 100,
pinned_only: bool = False
) -> "pyrogram.Dialogs":
- """Use this method to get a chunk of the user's dialogs.
+ """Get a chunk of the user's dialogs.
You can get up to 100 dialogs at once.
For a more convenient way of getting a user's dialogs see :meth:`iter_dialogs`.
- Args:
+ Parameters:
offset_date (``int``):
The offset date in Unix time taken from the top message of a :obj:`Dialog`.
Defaults to 0. Valid for non-pinned dialogs only.
@@ -53,10 +53,10 @@ class GetDialogs(BaseClient):
Defaults to False.
Returns:
- On success, a :obj:`Dialogs` object is returned.
+ :obj:`Dialogs`: On success, an object containing a list of dialogs is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
while True:
diff --git a/pyrogram/client/methods/chats/get_dialogs_count.py b/pyrogram/client/methods/chats/get_dialogs_count.py
index 49e6eff3..5142211e 100644
--- a/pyrogram/client/methods/chats/get_dialogs_count.py
+++ b/pyrogram/client/methods/chats/get_dialogs_count.py
@@ -22,17 +22,17 @@ from ...ext import BaseClient
class GetDialogsCount(BaseClient):
async def get_dialogs_count(self, pinned_only: bool = False) -> int:
- """Use this method to get the total count of your dialogs.
+ """Get the total count of your dialogs.
pinned_only (``bool``, *optional*):
Pass True if you want to count only pinned dialogs.
Defaults to False.
Returns:
- On success, an integer is returned.
+ ``int``: On success, the dialogs count is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
if pinned_only:
diff --git a/pyrogram/client/methods/chats/iter_chat_members.py b/pyrogram/client/methods/chats/iter_chat_members.py
index 7a935cbd..79f5e8c3 100644
--- a/pyrogram/client/methods/chats/iter_chat_members.py
+++ b/pyrogram/client/methods/chats/iter_chat_members.py
@@ -48,13 +48,13 @@ class IterChatMembers(BaseClient):
query: str = "",
filter: str = Filters.ALL
) -> Optional[AsyncGenerator["pyrogram.ChatMember", None]]:
- """Use this method to iterate through the members of a chat sequentially.
+ """Iterate through the members of a chat sequentially.
This convenience method does the same as repeatedly calling :meth:`get_chat_members` in a loop, thus saving you
from the hassle of setting up boilerplate code. It is useful for getting the whole members list of a chat with
a single call.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -78,10 +78,10 @@ class IterChatMembers(BaseClient):
Defaults to *"all"*.
Returns:
- A generator yielding :obj:`ChatMember ` objects.
+ ``Generator``: A generator yielding :obj:`ChatMember` objects.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
current = 0
yielded = set()
diff --git a/pyrogram/client/methods/chats/iter_dialogs.py b/pyrogram/client/methods/chats/iter_dialogs.py
index dfc7543e..e916bd47 100644
--- a/pyrogram/client/methods/chats/iter_dialogs.py
+++ b/pyrogram/client/methods/chats/iter_dialogs.py
@@ -31,12 +31,12 @@ class IterDialogs(BaseClient):
limit: int = 0,
offset_date: int = 0
) -> Optional[AsyncGenerator["pyrogram.Dialog", None]]:
- """Use this method to iterate through a user's dialogs sequentially.
+ """Iterate through a user's dialogs sequentially.
This convenience method does the same as repeatedly calling :meth:`get_dialogs` in a loop, thus saving you from
the hassle of setting up boilerplate code. It is useful for getting the whole dialogs list with a single call.
- Args:
+ Parameters:
limit (``str``, *optional*):
Limits the number of dialogs to be retrieved.
By default, no limit is applied and all dialogs are returned.
@@ -46,10 +46,10 @@ class IterDialogs(BaseClient):
Defaults to 0 (most recent dialog).
Returns:
- A generator yielding :obj:`Dialog ` objects.
+ ``Generator``: A generator yielding :obj:`Dialog` objects.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
current = 0
total = limit or (1 << 31) - 1
diff --git a/pyrogram/client/methods/chats/join_chat.py b/pyrogram/client/methods/chats/join_chat.py
index ce506e74..8e38d4ff 100644
--- a/pyrogram/client/methods/chats/join_chat.py
+++ b/pyrogram/client/methods/chats/join_chat.py
@@ -26,18 +26,18 @@ class JoinChat(BaseClient):
self,
chat_id: str
):
- """Use this method to join a group chat or channel.
+ """Join a group chat or channel.
- Args:
+ Parameters:
chat_id (``str``):
Unique identifier for the target chat in form of a *t.me/joinchat/* link or username of the target
channel/supergroup (in the format @username).
Returns:
- On success, a :obj:`Chat ` object is returned.
+ :obj:`Chat`: On success, a chat object is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
match = self.INVITE_LINK_RE.match(chat_id)
diff --git a/pyrogram/client/methods/chats/kick_chat_member.py b/pyrogram/client/methods/chats/kick_chat_member.py
index b59ea097..72a8b5d0 100644
--- a/pyrogram/client/methods/chats/kick_chat_member.py
+++ b/pyrogram/client/methods/chats/kick_chat_member.py
@@ -30,7 +30,7 @@ class KickChatMember(BaseClient):
user_id: Union[int, str],
until_date: int = 0
) -> Union["pyrogram.Message", bool]:
- """Use this method to kick a user from a group, a supergroup or a channel.
+ """Kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group on their own using
invite links, etc., unless unbanned first. You must be an administrator in the chat for this to work and must
have the appropriate admin rights.
@@ -40,7 +40,7 @@ class KickChatMember(BaseClient):
off in the target group. Otherwise members may only be removed by the group's creator or by the member
that added them.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -54,10 +54,11 @@ class KickChatMember(BaseClient):
considered to be banned forever. Defaults to 0 (ban forever).
Returns:
- On success, either True or a service :obj:`Message ` will be returned (when applicable).
+ :obj:`Message` | ``bool``: On success, a service message will be returned (when applicable), otherwise, in
+ case a message object couldn't be returned, True is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
chat_peer = await self.resolve_peer(chat_id)
user_peer = await self.resolve_peer(user_id)
diff --git a/pyrogram/client/methods/chats/leave_chat.py b/pyrogram/client/methods/chats/leave_chat.py
index aa2aa22e..e2b5cb4b 100644
--- a/pyrogram/client/methods/chats/leave_chat.py
+++ b/pyrogram/client/methods/chats/leave_chat.py
@@ -28,9 +28,9 @@ class LeaveChat(BaseClient):
chat_id: Union[int, str],
delete: bool = False
):
- """Use this method to leave a group chat or channel.
+ """Leave a group chat or channel.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier for the target chat or username of the target channel/supergroup
(in the format @username).
@@ -39,7 +39,7 @@ class LeaveChat(BaseClient):
Deletes the group chat dialog after leaving (for simple group chats, not supergroups).
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/pin_chat_message.py b/pyrogram/client/methods/chats/pin_chat_message.py
index a0d0b831..6023f459 100644
--- a/pyrogram/client/methods/chats/pin_chat_message.py
+++ b/pyrogram/client/methods/chats/pin_chat_message.py
@@ -29,11 +29,11 @@ class PinChatMessage(BaseClient):
message_id: int,
disable_notification: bool = None
) -> bool:
- """Use this method to pin a message in a group, channel or your own chat.
+ """Pin a message in a group, channel or your own chat.
You must be an administrator in the chat for this to work and must have the "can_pin_messages" admin right in
the supergroup or "can_edit_messages" admin right in the channel.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -45,10 +45,10 @@ class PinChatMessage(BaseClient):
message. Notifications are always disabled in channels.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
await self.send(
functions.messages.UpdatePinnedMessage(
diff --git a/pyrogram/client/methods/chats/promote_chat_member.py b/pyrogram/client/methods/chats/promote_chat_member.py
index 232bc62b..c7db62a5 100644
--- a/pyrogram/client/methods/chats/promote_chat_member.py
+++ b/pyrogram/client/methods/chats/promote_chat_member.py
@@ -36,12 +36,12 @@ class PromoteChatMember(BaseClient):
can_pin_messages: bool = False,
can_promote_members: bool = False
) -> bool:
- """Use this method to promote or demote a user in a supergroup or a channel.
+ """Promote or demote a user in a supergroup or a channel.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
Pass False for all boolean parameters to demote a user.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -76,10 +76,10 @@ class PromoteChatMember(BaseClient):
were appointed by him).
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
await self.send(
functions.channels.EditAdmin(
diff --git a/pyrogram/client/methods/chats/restrict_chat.py b/pyrogram/client/methods/chats/restrict_chat.py
index 40d46d34..8e63a9b2 100644
--- a/pyrogram/client/methods/chats/restrict_chat.py
+++ b/pyrogram/client/methods/chats/restrict_chat.py
@@ -36,10 +36,10 @@ class RestrictChat(BaseClient):
can_invite_users: bool = False,
can_pin_messages: bool = False
) -> Chat:
- """Use this method to restrict a chat.
+ """Restrict a chat.
Pass True for all boolean parameters to lift restrictions from a chat.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -70,10 +70,10 @@ class RestrictChat(BaseClient):
Pass True, if the user can pin messages.
Returns:
- On success, a :obj:`Chat ` object is returned.
+ :obj:`Chat`: On success, a chat object is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
send_messages = True
send_media = True
diff --git a/pyrogram/client/methods/chats/restrict_chat_member.py b/pyrogram/client/methods/chats/restrict_chat_member.py
index 6ed4fd68..54d12ecf 100644
--- a/pyrogram/client/methods/chats/restrict_chat_member.py
+++ b/pyrogram/client/methods/chats/restrict_chat_member.py
@@ -38,12 +38,12 @@ class RestrictChatMember(BaseClient):
can_invite_users: bool = False,
can_pin_messages: bool = False
) -> Chat:
- """Use this method to restrict a user in a supergroup.
+ """Restrict a user in a supergroup.
The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights.
Pass True for all boolean parameters to lift restrictions from a user.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -83,10 +83,10 @@ class RestrictChatMember(BaseClient):
Pass True, if the user can pin messages.
Returns:
- On success, a :obj:`Chat ` object is returned.
+ :obj:`Chat`: On success, a chat object is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
send_messages = True
send_media = True
diff --git a/pyrogram/client/methods/chats/set_chat_description.py b/pyrogram/client/methods/chats/set_chat_description.py
index 4c3a13ec..aedc3805 100644
--- a/pyrogram/client/methods/chats/set_chat_description.py
+++ b/pyrogram/client/methods/chats/set_chat_description.py
@@ -28,10 +28,10 @@ class SetChatDescription(BaseClient):
chat_id: Union[int, str],
description: str
) -> bool:
- """Use this method to change the description of a supergroup or a channel.
+ """Change the description of a supergroup or a channel.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -39,10 +39,10 @@ class SetChatDescription(BaseClient):
New chat description, 0-255 characters.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
``ValueError`` if a chat_id doesn't belong to a supergroup or a channel.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/set_chat_photo.py b/pyrogram/client/methods/chats/set_chat_photo.py
index f76c313b..4d2b175a 100644
--- a/pyrogram/client/methods/chats/set_chat_photo.py
+++ b/pyrogram/client/methods/chats/set_chat_photo.py
@@ -31,7 +31,7 @@ class SetChatPhoto(BaseClient):
chat_id: Union[int, str],
photo: str
) -> bool:
- """Use this method to set a new profile photo for the chat.
+ """Set a new profile photo for the chat.
Photos can't be changed for private chats.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
@@ -39,7 +39,7 @@ class SetChatPhoto(BaseClient):
In regular groups (non-supergroups), this method will only work if the "All Members Are Admins"
setting is off.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -47,10 +47,10 @@ class SetChatPhoto(BaseClient):
New chat photo. You can pass a :class:`Photo` id or a file path to upload a new photo.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
``ValueError`` if a chat_id belongs to user.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/set_chat_title.py b/pyrogram/client/methods/chats/set_chat_title.py
index f6453b27..cb6664d1 100644
--- a/pyrogram/client/methods/chats/set_chat_title.py
+++ b/pyrogram/client/methods/chats/set_chat_title.py
@@ -28,7 +28,7 @@ class SetChatTitle(BaseClient):
chat_id: Union[int, str],
title: str
) -> bool:
- """Use this method to change the title of a chat.
+ """Change the title of a chat.
Titles can't be changed for private chats.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.
@@ -36,7 +36,7 @@ class SetChatTitle(BaseClient):
In regular groups (non-supergroups), this method will only work if the "All Members Are Admins"
setting is off.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -44,11 +44,11 @@ class SetChatTitle(BaseClient):
New chat title, 1-255 characters.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` if a chat_id belongs to user.
+ RPCError: In case of a Telegram RPC error.
+ ValueError: In case a chat id belongs to user.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/chats/unban_chat_member.py b/pyrogram/client/methods/chats/unban_chat_member.py
index beeb8163..20af0a85 100644
--- a/pyrogram/client/methods/chats/unban_chat_member.py
+++ b/pyrogram/client/methods/chats/unban_chat_member.py
@@ -28,11 +28,11 @@ class UnbanChatMember(BaseClient):
chat_id: Union[int, str],
user_id: Union[int, str]
) -> bool:
- """Use this method to unban a previously kicked user in a supergroup or channel.
+ """Unban a previously kicked user in a supergroup or channel.
The user will **not** return to the group or channel automatically, but will be able to join via link, etc.
You must be an administrator for this to work.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
@@ -41,10 +41,10 @@ class UnbanChatMember(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str).
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
await self.send(
functions.channels.EditBanned(
diff --git a/pyrogram/client/methods/chats/unpin_chat_message.py b/pyrogram/client/methods/chats/unpin_chat_message.py
index 757f1591..66e03ac1 100644
--- a/pyrogram/client/methods/chats/unpin_chat_message.py
+++ b/pyrogram/client/methods/chats/unpin_chat_message.py
@@ -27,19 +27,19 @@ class UnpinChatMessage(BaseClient):
self,
chat_id: Union[int, str]
) -> bool:
- """Use this method to unpin a message in a group, channel or your own chat.
+ """Unpin a message in a group, channel or your own chat.
You must be an administrator in the chat for this to work and must have the "can_pin_messages" admin
right in the supergroup or "can_edit_messages" admin right in the channel.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
await self.send(
functions.messages.UpdatePinnedMessage(
diff --git a/pyrogram/client/methods/chats/update_chat_username.py b/pyrogram/client/methods/chats/update_chat_username.py
index 12f5fe12..d5cdfac4 100644
--- a/pyrogram/client/methods/chats/update_chat_username.py
+++ b/pyrogram/client/methods/chats/update_chat_username.py
@@ -28,22 +28,22 @@ class UpdateChatUsername(BaseClient):
chat_id: Union[int, str],
username: Union[str, None]
) -> bool:
- """Use this method to update a channel or a supergroup username.
+ """Update a channel or a supergroup username.
To update your own username (for users only, not bots) you can use :meth:`update_username`.
- Args:
+ Parameters:
chat_id (``int`` | ``str``)
Unique identifier (int) or username (str) of the target chat.
username (``str`` | ``None``):
Username to set. Pass "" (empty string) or None to remove the username.
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
- ``ValueError`` if a chat_id belongs to a user or chat.
+ RPCError: In case of a Telegram RPC error.
+ ValueError: In case a chat id belongs to a user or chat.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/contacts/add_contacts.py b/pyrogram/client/methods/contacts/add_contacts.py
index 9ba2308c..fa3a5367 100644
--- a/pyrogram/client/methods/contacts/add_contacts.py
+++ b/pyrogram/client/methods/contacts/add_contacts.py
@@ -28,17 +28,14 @@ class AddContacts(BaseClient):
self,
contacts: List["pyrogram.InputPhoneContact"]
):
- """Use this method to add contacts to your Telegram address book.
+ """Add contacts to your Telegram address book.
- Args:
- contacts (List of :obj:`InputPhoneContact `):
+ Parameters:
+ contacts (List of :obj:`InputPhoneContact`):
The contact list to be added
- Returns:
- On success, the added contacts are returned.
-
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
imported_contacts = await self.send(
functions.contacts.ImportContacts(
diff --git a/pyrogram/client/methods/contacts/delete_contacts.py b/pyrogram/client/methods/contacts/delete_contacts.py
index 1c1e0dac..57850648 100644
--- a/pyrogram/client/methods/contacts/delete_contacts.py
+++ b/pyrogram/client/methods/contacts/delete_contacts.py
@@ -28,18 +28,18 @@ class DeleteContacts(BaseClient):
self,
ids: List[int]
):
- """Use this method to delete contacts from your Telegram address book.
+ """Delete contacts from your Telegram address book.
- Args:
+ Parameters:
ids (List of ``int``):
A list of unique identifiers for the target users.
Can be an ID (int), a username (string) or phone number (string).
Returns:
- True on success.
+ ``bool``: True on success.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
contacts = []
diff --git a/pyrogram/client/methods/contacts/get_contacts.py b/pyrogram/client/methods/contacts/get_contacts.py
index 5e9bff44..329b1a89 100644
--- a/pyrogram/client/methods/contacts/get_contacts.py
+++ b/pyrogram/client/methods/contacts/get_contacts.py
@@ -18,6 +18,7 @@
import asyncio
import logging
+from typing import List
import pyrogram
from pyrogram.api import functions
@@ -28,14 +29,15 @@ log = logging.getLogger(__name__)
class GetContacts(BaseClient):
- async def get_contacts(self):
- """Use this method to get contacts from your Telegram address book.
+ async def get_contacts(self) -> List["pyrogram.User"]:
+ # TODO: Create a Users object and return that
+ """Get contacts from your Telegram address book.
Returns:
- On success, a list of :obj:`User` objects is returned.
+ List of :obj:`User`: On success, a list of users is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
while True:
try:
diff --git a/pyrogram/client/methods/contacts/get_contacts_count.py b/pyrogram/client/methods/contacts/get_contacts_count.py
index f2b6fda0..45a7eb77 100644
--- a/pyrogram/client/methods/contacts/get_contacts_count.py
+++ b/pyrogram/client/methods/contacts/get_contacts_count.py
@@ -22,13 +22,13 @@ from ...ext import BaseClient
class GetContactsCount(BaseClient):
async def get_contacts_count(self) -> int:
- """Use this method to get the total count of contacts from your Telegram address book.
+ """Get the total count of contacts from your Telegram address book.
Returns:
- On success, an integer is returned.
+ ``int``: On success, the contacts count is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
return len((await self.send(functions.contacts.GetContacts(hash=0))).contacts)
diff --git a/pyrogram/client/methods/decorators/on_callback_query.py b/pyrogram/client/methods/decorators/on_callback_query.py
index 3c747c5f..b76655fb 100644
--- a/pyrogram/client/methods/decorators/on_callback_query.py
+++ b/pyrogram/client/methods/decorators/on_callback_query.py
@@ -30,11 +30,12 @@ class OnCallbackQuery(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling callback queries.
+ """Decorator for handling callback queries.
+
This does the same thing as :meth:`add_handler` using the :class:`CallbackQueryHandler`.
- Args:
- filters (:obj:`Filters `):
+ Parameters:
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of callback queries to be passed
in your function.
diff --git a/pyrogram/client/methods/decorators/on_deleted_messages.py b/pyrogram/client/methods/decorators/on_deleted_messages.py
index cf8f9cf2..7637e6eb 100644
--- a/pyrogram/client/methods/decorators/on_deleted_messages.py
+++ b/pyrogram/client/methods/decorators/on_deleted_messages.py
@@ -30,11 +30,12 @@ class OnDeletedMessages(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling deleted messages.
+ """Decorator for handling deleted messages.
+
This does the same thing as :meth:`add_handler` using the :class:`DeletedMessagesHandler`.
- Args:
- filters (:obj:`Filters `):
+ Parameters:
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of messages to be passed
in your function.
diff --git a/pyrogram/client/methods/decorators/on_disconnect.py b/pyrogram/client/methods/decorators/on_disconnect.py
index 515a28c1..9305808e 100644
--- a/pyrogram/client/methods/decorators/on_disconnect.py
+++ b/pyrogram/client/methods/decorators/on_disconnect.py
@@ -23,7 +23,8 @@ from ...ext import BaseClient
class OnDisconnect(BaseClient):
def on_disconnect(self=None) -> callable:
- """Use this decorator to automatically register a function for handling disconnections.
+ """Decorator for handling disconnections.
+
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`.
"""
diff --git a/pyrogram/client/methods/decorators/on_inline_query.py b/pyrogram/client/methods/decorators/on_inline_query.py
index 81f0f676..58837398 100644
--- a/pyrogram/client/methods/decorators/on_inline_query.py
+++ b/pyrogram/client/methods/decorators/on_inline_query.py
@@ -30,10 +30,11 @@ class OnInlineQuery(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling inline queries.
+ """Decorator for handling inline queries.
+
This does the same thing as :meth:`add_handler` using the :class:`InlineQueryHandler`.
- Args:
+ Parameters:
filters (:obj:`Filters `):
Pass one or more filters to allow only a subset of inline queries to be passed
in your function.
diff --git a/pyrogram/client/methods/decorators/on_message.py b/pyrogram/client/methods/decorators/on_message.py
index e6563893..f590fd12 100644
--- a/pyrogram/client/methods/decorators/on_message.py
+++ b/pyrogram/client/methods/decorators/on_message.py
@@ -30,11 +30,12 @@ class OnMessage(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling messages.
+ """Decorator for handling messages.
+
This does the same thing as :meth:`add_handler` using the :class:`MessageHandler`.
- Args:
- filters (:obj:`Filters `):
+ Parameters:
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of messages to be passed
in your function.
diff --git a/pyrogram/client/methods/decorators/on_poll.py b/pyrogram/client/methods/decorators/on_poll.py
index 56dcd757..de1c1d3d 100644
--- a/pyrogram/client/methods/decorators/on_poll.py
+++ b/pyrogram/client/methods/decorators/on_poll.py
@@ -30,10 +30,11 @@ class OnPoll(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling poll updates.
+ """Decorator for handling poll updates.
+
This does the same thing as :meth:`add_handler` using the :class:`PollHandler`.
- Args:
+ Parameters:
filters (:obj:`Filters `):
Pass one or more filters to allow only a subset of polls to be passed
in your function.
diff --git a/pyrogram/client/methods/decorators/on_raw_update.py b/pyrogram/client/methods/decorators/on_raw_update.py
index 1494a319..53a0f4cf 100644
--- a/pyrogram/client/methods/decorators/on_raw_update.py
+++ b/pyrogram/client/methods/decorators/on_raw_update.py
@@ -28,10 +28,11 @@ class OnRawUpdate(BaseClient):
self=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling raw updates.
+ """Decorator for handling raw updates.
+
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
- Args:
+ Parameters:
group (``int``, *optional*):
The group identifier, defaults to 0.
"""
diff --git a/pyrogram/client/methods/decorators/on_user_status.py b/pyrogram/client/methods/decorators/on_user_status.py
index 4d8185b1..e7db7b74 100644
--- a/pyrogram/client/methods/decorators/on_user_status.py
+++ b/pyrogram/client/methods/decorators/on_user_status.py
@@ -30,11 +30,11 @@ class OnUserStatus(BaseClient):
filters=None,
group: int = 0
) -> callable:
- """Use this decorator to automatically register a function for handling user status updates.
+ """Decorator for handling user status updates.
This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`.
- Args:
- filters (:obj:`Filters `):
+ Parameters:
+ filters (:obj:`Filters`):
Pass one or more filters to allow only a subset of UserStatus updated to be passed in your function.
group (``int``, *optional*):
diff --git a/pyrogram/client/methods/messages/delete_messages.py b/pyrogram/client/methods/messages/delete_messages.py
index 9eb42867..e139a270 100644
--- a/pyrogram/client/methods/messages/delete_messages.py
+++ b/pyrogram/client/methods/messages/delete_messages.py
@@ -29,9 +29,9 @@ class DeleteMessages(BaseClient):
message_ids: Iterable[int],
revoke: bool = True
) -> bool:
- """Use this method to delete messages, including service messages.
+ """Delete messages, including service messages.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -48,10 +48,10 @@ class DeleteMessages(BaseClient):
Defaults to True.
Returns:
- True on success, False otherwise.
+ ``bool``: True on success, False otherwise.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
peer = await self.resolve_peer(chat_id)
message_ids = list(message_ids) if not isinstance(message_ids, int) else [message_ids]
diff --git a/pyrogram/client/methods/messages/download_media.py b/pyrogram/client/methods/messages/download_media.py
index 7ebd0fed..b91ac9a4 100644
--- a/pyrogram/client/methods/messages/download_media.py
+++ b/pyrogram/client/methods/messages/download_media.py
@@ -32,10 +32,10 @@ class DownloadMedia(BaseClient):
progress: callable = None,
progress_args: tuple = ()
) -> Union[str, None]:
- """Use this method to download the media from a message.
+ """Download the media from a message.
- Args:
- message (:obj:`Message ` | ``str``):
+ Parameters:
+ message (:obj:`Message` | ``str``):
Pass a Message containing the media, the media itself (message.audio, message.video, ...) or
the file id as string.
@@ -59,7 +59,7 @@ class DownloadMedia(BaseClient):
a chat_id and a message_id in order to edit a message with the updated progress.
Other Parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the callback function.
current (``int``):
@@ -73,11 +73,11 @@ class DownloadMedia(BaseClient):
You can either keep *\*args* or add every single extra argument in your function signature.
Returns:
- On success, the absolute path of the downloaded file as string is returned, None otherwise.
- In case the download is deliberately stopped with :meth:`stop_transmission`, None is returned as well.
+ ``str`` | ``None``: On success, the absolute path of the downloaded file is returned, otherwise, in case
+ the download failed or was deliberately stopped with :meth:`stop_transmission`, None is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
``ValueError`` if the message doesn't contain any downloadable media
"""
error_message = "This message doesn't contain any downloadable media"
diff --git a/pyrogram/client/methods/messages/edit_message_caption.py b/pyrogram/client/methods/messages/edit_message_caption.py
index 8fd89dc6..697623f3 100644
--- a/pyrogram/client/methods/messages/edit_message_caption.py
+++ b/pyrogram/client/methods/messages/edit_message_caption.py
@@ -32,9 +32,9 @@ class EditMessageCaption(BaseClient):
parse_mode: str = "",
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":
- """Use this method to edit captions of messages.
+ """Edit captions of messages.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -47,18 +47,17 @@ class EditMessageCaption(BaseClient):
New caption of the message.
parse_mode (``str``, *optional*):
- Use :obj:`MARKDOWN ` or :obj:`HTML `
- if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your caption.
- Defaults to Markdown.
+ Pass "markdown" or "html" if you want Telegram apps to show bold, italic, fixed-width text or inline
+ URLs in your caption. Defaults to "markdown".
reply_markup (:obj:`InlineKeyboardMarkup`, *optional*):
An InlineKeyboardMarkup object.
Returns:
- On success, the edited :obj:`Message ` is returned.
+ :obj:`Message`: On success, the edited message is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
style = self.html if parse_mode.lower() == "html" else self.markdown
diff --git a/pyrogram/client/methods/messages/edit_message_media.py b/pyrogram/client/methods/messages/edit_message_media.py
index 13f938ae..88c41466 100644
--- a/pyrogram/client/methods/messages/edit_message_media.py
+++ b/pyrogram/client/methods/messages/edit_message_media.py
@@ -40,14 +40,14 @@ class EditMessageMedia(BaseClient):
media: InputMedia,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":
- """Use this method to edit audio, document, photo, or video messages.
+ """Edit audio, document, photo, or video messages.
If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise,
message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
Use previously uploaded file via its file_id or specify a URL. On success, if the edited message was sent
by the bot, the edited Message is returned, otherwise True is returned.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -63,10 +63,10 @@ class EditMessageMedia(BaseClient):
An InlineKeyboardMarkup object.
Returns:
- On success, the edited :obj:`Message ` is returned.
+ :obj:`Message`: On success, the edited message is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
style = self.html if media.parse_mode.lower() == "html" else self.markdown
caption = media.caption
diff --git a/pyrogram/client/methods/messages/edit_message_reply_markup.py b/pyrogram/client/methods/messages/edit_message_reply_markup.py
index 18f2fbb4..b6eba080 100644
--- a/pyrogram/client/methods/messages/edit_message_reply_markup.py
+++ b/pyrogram/client/methods/messages/edit_message_reply_markup.py
@@ -30,9 +30,9 @@ class EditMessageReplyMarkup(BaseClient):
message_id: int,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":
- """Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
+ """Edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -45,11 +45,11 @@ class EditMessageReplyMarkup(BaseClient):
An InlineKeyboardMarkup object.
Returns:
- On success, if edited message is sent by the bot, the edited
- :obj:`Message ` is returned, otherwise True is returned.
+ :obj:`Message` | ``bool``: In case the edited message is sent by the bot, the edited message is returned,
+ otherwise, True is returned in case the edited message is send by the user.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
r = await self.send(
diff --git a/pyrogram/client/methods/messages/edit_message_text.py b/pyrogram/client/methods/messages/edit_message_text.py
index fac74f89..5d2782f9 100644
--- a/pyrogram/client/methods/messages/edit_message_text.py
+++ b/pyrogram/client/methods/messages/edit_message_text.py
@@ -33,9 +33,9 @@ class EditMessageText(BaseClient):
disable_web_page_preview: bool = None,
reply_markup: "pyrogram.InlineKeyboardMarkup" = None
) -> "pyrogram.Message":
- """Use this method to edit text messages.
+ """Edit text messages.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -48,9 +48,8 @@ class EditMessageText(BaseClient):
New text of the message.
parse_mode (``str``, *optional*):
- Use :obj:`MARKDOWN ` or :obj:`HTML `
- if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your message.
- Defaults to Markdown.
+ Pass "markdown" or "html" if you want Telegram apps to show bold, italic, fixed-width text or inline
+ URLs in your message. Defaults to "markdown".
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
@@ -59,10 +58,10 @@ class EditMessageText(BaseClient):
An InlineKeyboardMarkup object.
Returns:
- On success, the edited :obj:`Message ` is returned.
+ :obj:`Message`: On success, the edited message is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
style = self.html if parse_mode.lower() == "html" else self.markdown
diff --git a/pyrogram/client/methods/messages/forward_messages.py b/pyrogram/client/methods/messages/forward_messages.py
index 67f695cc..e8b77a23 100644
--- a/pyrogram/client/methods/messages/forward_messages.py
+++ b/pyrogram/client/methods/messages/forward_messages.py
@@ -28,14 +28,14 @@ class ForwardMessages(BaseClient):
self,
chat_id: Union[int, str],
from_chat_id: Union[int, str],
- message_ids: Iterable[int],
+ message_ids: Union[int, Iterable[int]],
disable_notification: bool = None,
as_copy: bool = False,
remove_caption: bool = False
) -> "pyrogram.Messages":
- """Use this method to forward messages of any kind.
+ """Forward messages of any kind.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -64,13 +64,12 @@ class ForwardMessages(BaseClient):
Defaults to False.
Returns:
- On success and in case *message_ids* was an iterable, the returned value will be a list of the forwarded
- :obj:`Messages ` even if a list contains just one element, otherwise if
- *message_ids* was an integer, the single forwarded :obj:`Message `
- is returned.
+ :obj:`Message` | :obj:`Messages`: In case *message_ids* was an integer, the single forwarded message is
+ returned, otherwise, in case *message_ids* was an iterable, the returned value will be an object containing
+ a list of messages, even if such iterable contained just a single element.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
is_iterable = not isinstance(message_ids, int)
diff --git a/pyrogram/client/methods/messages/get_history.py b/pyrogram/client/methods/messages/get_history.py
index 3392e7fd..069c03e5 100644
--- a/pyrogram/client/methods/messages/get_history.py
+++ b/pyrogram/client/methods/messages/get_history.py
@@ -38,12 +38,12 @@ class GetHistory(BaseClient):
offset_date: int = 0,
reverse: bool = False
) -> "pyrogram.Messages":
- """Use this method to retrieve a chunk of the history of a chat.
+ """Retrieve a chunk of the history of a chat.
You can get up to 100 messages at once.
For a more convenient way of getting a chat history see :meth:`iter_history`.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -67,10 +67,10 @@ class GetHistory(BaseClient):
Pass True to retrieve the messages in reversed order (from older to most recent).
Returns:
- On success, a :obj:`Messages ` object is returned.
+ :obj:`Messages` - On success, an object containing a list of the retrieved messages.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
while True:
diff --git a/pyrogram/client/methods/messages/get_history_count.py b/pyrogram/client/methods/messages/get_history_count.py
index 8883c051..1286fffb 100644
--- a/pyrogram/client/methods/messages/get_history_count.py
+++ b/pyrogram/client/methods/messages/get_history_count.py
@@ -32,7 +32,7 @@ class GetHistoryCount(BaseClient):
self,
chat_id: Union[int, str]
) -> int:
- """Use this method to get the total count of messages in a chat.
+ """Get the total count of messages in a chat.
.. note::
@@ -40,15 +40,15 @@ class GetHistoryCount(BaseClient):
a **private** or a **basic group** chat has with a single method call. To overcome this limitation, Pyrogram
has to iterate over all the messages. Channels and supergroups are not affected by this limitation.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
Returns:
- On success, an integer is returned.
+ ``int``: On success, the chat history count is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
peer = await self.resolve_peer(chat_id)
diff --git a/pyrogram/client/methods/messages/get_messages.py b/pyrogram/client/methods/messages/get_messages.py
index 17f1ef47..ac83a7e4 100644
--- a/pyrogram/client/methods/messages/get_messages.py
+++ b/pyrogram/client/methods/messages/get_messages.py
@@ -36,10 +36,10 @@ class GetMessages(BaseClient):
reply_to_message_ids: Union[int, Iterable[int]] = None,
replies: int = 1
) -> Union["pyrogram.Message", "pyrogram.Messages"]:
- """Use this method to get one or more messages that belong to a specific chat.
+ """Get one or more messages that belong to a specific chat.
You can retrieve up to 200 messages at once.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -55,15 +55,17 @@ class GetMessages(BaseClient):
If *message_ids* is set, this argument will be ignored.
replies (``int``, *optional*):
- The number of subsequent replies to get for each message. Defaults to 1.
+ The number of subsequent replies to get for each message.
+ Pass 0 for no reply at all or -1 for unlimited replies.
+ Defaults to 1.
Returns:
- On success and in case *message_ids* or *reply_to_message_ids* was an iterable, the returned value will be a
- :obj:`Messages ` even if a list contains just one element. Otherwise, if *message_ids* or
- *reply_to_message_ids* was an integer, the single requested :obj:`Message ` is returned.
+ :obj:`Message` | :obj:`Messages`: In case *message_ids* was an integer, the single requested message is
+ returned, otherwise, in case *message_ids* was an iterable, the returned value will be an object containing
+ a list of messages, even if such iterable contained just a single element.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
ids, ids_type = (
(message_ids, types.InputMessageID) if message_ids
@@ -80,6 +82,9 @@ class GetMessages(BaseClient):
ids = list(ids) if is_iterable else [ids]
ids = [ids_type(id=i) for i in ids]
+ if replies < 0:
+ replies = (1 << 31) - 1
+
if isinstance(peer, types.InputPeerChannel):
rpc = functions.channels.GetMessages(channel=peer, id=ids)
else:
diff --git a/pyrogram/client/methods/messages/iter_history.py b/pyrogram/client/methods/messages/iter_history.py
index 52f408ea..7fc81150 100644
--- a/pyrogram/client/methods/messages/iter_history.py
+++ b/pyrogram/client/methods/messages/iter_history.py
@@ -35,12 +35,12 @@ class IterHistory(BaseClient):
offset_date: int = 0,
reverse: bool = False
) -> Optional[AsyncGenerator["pyrogram.Message", None]]:
- """Use this method to iterate through a chat history sequentially.
+ """Iterate through a chat history sequentially.
This convenience method does the same as repeatedly calling :meth:`get_history` in a loop, thus saving you from
the hassle of setting up boilerplate code. It is useful for getting the whole chat history with a single call.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -64,10 +64,10 @@ class IterHistory(BaseClient):
Pass True to retrieve the messages in reversed order (from older to most recent).
Returns:
- A generator yielding :obj:`Message ` objects.
+ ``Generator``: A generator yielding :obj:`Message` objects.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
offset_id = offset_id or (1 if reverse else 0)
current = 0
diff --git a/pyrogram/client/methods/messages/retract_vote.py b/pyrogram/client/methods/messages/retract_vote.py
index 7f48c8ea..490f0ad0 100644
--- a/pyrogram/client/methods/messages/retract_vote.py
+++ b/pyrogram/client/methods/messages/retract_vote.py
@@ -29,9 +29,9 @@ class RetractVote(BaseClient):
chat_id: Union[int, str],
message_id: int
) -> "pyrogram.Poll":
- """Use this method to retract your vote in a poll.
+ """Retract your vote in a poll.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -41,10 +41,10 @@ class RetractVote(BaseClient):
Identifier of the original message with the poll.
Returns:
- On success, the :obj:`Poll ` with the retracted vote is returned.
+ :obj:`Poll`: On success, the poll with the retracted vote is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
r = await self.send(
functions.messages.SendVote(
diff --git a/pyrogram/client/methods/messages/send_animation.py b/pyrogram/client/methods/messages/send_animation.py
index 7dfd0eb9..7c6e7742 100644
--- a/pyrogram/client/methods/messages/send_animation.py
+++ b/pyrogram/client/methods/messages/send_animation.py
@@ -49,9 +49,9 @@ class SendAnimation(BaseClient):
progress: callable = None,
progress_args: tuple = ()
) -> Union["pyrogram.Message", None]:
- """Use this method to send animation files (animation or H.264/MPEG-4 AVC video without sound).
+ """Send animation files (animation or H.264/MPEG-4 AVC video without sound).
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -67,9 +67,8 @@ class SendAnimation(BaseClient):
Animation caption, 0-1024 characters.
parse_mode (``str``, *optional*):
- Use :obj:`MARKDOWN ` or :obj:`HTML `
- if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your caption.
- Defaults to Markdown.
+ Pass "markdown" or "html" if you want Telegram apps to show bold, italic, fixed-width text or inline
+ URLs in your caption. Defaults to "markdown".
duration (``int``, *optional*):
Duration of sent animation in seconds.
@@ -107,7 +106,7 @@ class SendAnimation(BaseClient):
a chat_id and a message_id in order to edit a message with the updated progress.
Other Parameters:
- client (:obj:`Client `):
+ client (:obj:`Client`):
The Client itself, useful when you want to call other API methods inside the callback function.
current (``int``):
@@ -121,11 +120,11 @@ class SendAnimation(BaseClient):
You can either keep *\*args* or add every single extra argument in your function signature.
Returns:
- On success, the sent :obj:`Message ` is returned.
- In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
+ :obj:`Message` | ``None``: On success, the sent animation message is returned, otherwise, in case the upload
+ is deliberately stopped with :meth:`stop_transmission`, None is returned.
Raises:
- :class:`RPCError ` in case of a Telegram RPC error.
+ RPCError: In case of a Telegram RPC error.
"""
file = None
style = self.html if parse_mode.lower() == "html" else self.markdown
diff --git a/pyrogram/client/methods/messages/send_audio.py b/pyrogram/client/methods/messages/send_audio.py
index 81ceb3f3..ba465655 100644
--- a/pyrogram/client/methods/messages/send_audio.py
+++ b/pyrogram/client/methods/messages/send_audio.py
@@ -48,11 +48,11 @@ class SendAudio(BaseClient):
progress: callable = None,
progress_args: tuple = ()
) -> Union["pyrogram.Message", None]:
- """Use this method to send audio files.
+ """Send audio files.
For sending voice messages, use the :obj:`send_voice()` method instead.
- Args:
+ Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
@@ -68,9 +68,8 @@ class SendAudio(BaseClient):
Audio caption, 0-1024 characters.
parse_mode (``str``, *optional*):
- Use :obj:`MARKDOWN ` or :obj:`HTML `
- if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your caption.
- Defaults to Markdown.
+ Pass "markdown" or "html" if you want Telegram apps to show bold, italic, fixed-width text or inline
+ URLs in your caption. Defaults to "markdown".
duration (``int``, *optional*):
Duration of the audio in seconds.
@@ -108,7 +107,7 @@ class SendAudio(BaseClient):
a chat_id and a message_id in order to edit a message with the updated progress.
Other Parameters:
- client (:obj:`Client