pyrolisten 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyrolisten/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """pyrolisten - listen() / ask() for Pyrogram, Kurigram and other forks.
2
+
3
+ import pyrolisten.listen # pyromod style
4
+ import pyrolisten # also works
5
+ """
6
+ from . import listen # applies the patches on import
7
+ from .exceptions import (
8
+ ListenerCanceled,
9
+ ListenerCancelled,
10
+ ListenerStopped,
11
+ ListenerTimeout,
12
+ )
13
+
14
+ __all__ = [
15
+ "listen",
16
+ "ListenerCanceled",
17
+ "ListenerCancelled",
18
+ "ListenerStopped",
19
+ "ListenerTimeout",
20
+ ]
@@ -0,0 +1,18 @@
1
+ """Exceptions raised by pyrolisten's listen()/ask()."""
2
+ import asyncio
3
+
4
+
5
+ class ListenerCanceled(Exception):
6
+ """Raised inside listen()/ask() when cancel_listener() cancels the wait."""
7
+
8
+
9
+ # Alternative spellings / names used by other libraries.
10
+ ListenerCancelled = ListenerCanceled # British spelling
11
+ ListenerStopped = ListenerCanceled # pyromod v3 name
12
+
13
+
14
+ class ListenerTimeout(asyncio.TimeoutError):
15
+ """Raised when no matching message arrived in time.
16
+
17
+ Subclasses asyncio.TimeoutError, so `except asyncio.TimeoutError` works too.
18
+ """
pyrolisten/listen.py ADDED
@@ -0,0 +1,216 @@
1
+ """
2
+ pyrolisten.listen - Client.listen(), Client.ask() and Client.cancel_listener()
3
+ for Pyrogram and its forks.
4
+
5
+ Works with anything that installs a `pyrogram` module (Pyrogram, Kurigram,
6
+ WZGram, ...). Methods the installed library already provides are never overridden.
7
+
8
+ Usage: import pyrolisten.listen # (or just `import pyrolisten`) once, at startup
9
+ """
10
+ import asyncio
11
+ import importlib
12
+ import inspect
13
+ from dataclasses import dataclass
14
+ from typing import Any, List, Optional
15
+
16
+ from .exceptions import (
17
+ ListenerCanceled,
18
+ ListenerCancelled,
19
+ ListenerStopped,
20
+ ListenerTimeout,
21
+ )
22
+
23
+ __all__ = [
24
+ "ListenerCanceled",
25
+ "ListenerCancelled",
26
+ "ListenerStopped",
27
+ "ListenerTimeout",
28
+ ]
29
+
30
+ _HANDLER_GROUP = -999
31
+
32
+
33
+ # --------------------------------------------------------------------------- #
34
+ # Find the installed Pyrogram-compatible library
35
+ # --------------------------------------------------------------------------- #
36
+ def _load_backend():
37
+ try:
38
+ return importlib.import_module("pyrogram")
39
+ except ImportError as exc:
40
+ raise ImportError(
41
+ "pyrolisten needs Pyrogram or a compatible fork (kurigram, wzgram, ...). "
42
+ 'Install one, e.g.: pip install "pyrolisten[kurigram]"'
43
+ ) from exc
44
+
45
+
46
+ _pg = _load_backend()
47
+ Client = _pg.Client
48
+ _handlers = importlib.import_module(_pg.__name__ + ".handlers")
49
+ _STOP = getattr(_pg, "StopPropagation", None)
50
+
51
+
52
+ # --------------------------------------------------------------------------- #
53
+ # Internals
54
+ # --------------------------------------------------------------------------- #
55
+ @dataclass(eq=False)
56
+ class _Listener:
57
+ chat_id: Optional[int]
58
+ user_id: Optional[int]
59
+ future: Any
60
+ filters: Any = None
61
+
62
+
63
+ def _store(client) -> List[_Listener]:
64
+ try:
65
+ return client._pyrolisten_listeners
66
+ except AttributeError:
67
+ client._pyrolisten_listeners = []
68
+ return client._pyrolisten_listeners
69
+
70
+
71
+ async def _passes(flt, client, update) -> bool:
72
+ result = flt(client, update)
73
+ if inspect.isawaitable(result):
74
+ result = await result
75
+ return bool(result)
76
+
77
+
78
+ async def _on_message(client, message):
79
+ if getattr(message, "outgoing", False):
80
+ return
81
+ listeners = _store(client)
82
+ if not listeners:
83
+ return
84
+
85
+ chat = getattr(message, "chat", None)
86
+ user = getattr(message, "from_user", None)
87
+ chat_id = chat.id if chat else None
88
+ user_id = user.id if user else None
89
+
90
+ # listeners tied to a specific user win over chat-wide ones
91
+ for listener in sorted(listeners, key=lambda item: item.user_id is None):
92
+ if listener.future.done():
93
+ continue
94
+ if listener.chat_id is not None and listener.chat_id != chat_id:
95
+ continue
96
+ if listener.user_id is not None and listener.user_id != user_id:
97
+ continue
98
+ if listener.filters is not None and not await _passes(
99
+ listener.filters, client, message
100
+ ):
101
+ continue
102
+ if listener.future.done():
103
+ continue
104
+ listener.future.set_result(message)
105
+ if _STOP is not None:
106
+ raise _STOP # keep the answer away from your normal handlers
107
+ return
108
+
109
+
110
+ async def _ensure_handler(client):
111
+ if getattr(client, "_pyrolisten_handler", False):
112
+ return
113
+ client._pyrolisten_handler = True
114
+ client.add_handler(_handlers.MessageHandler(_on_message), group=_HANDLER_GROUP)
115
+ await asyncio.sleep(0) # let the library finish registering it
116
+
117
+
118
+ # --------------------------------------------------------------------------- #
119
+ # Client methods
120
+ # --------------------------------------------------------------------------- #
121
+ async def listen(self, chat_id=None, filters=None, timeout=60, user_id=None):
122
+ """Wait for the next matching message and return it.
123
+
124
+ timeout=None waits forever.
125
+ Raises ListenerTimeout on timeout and ListenerCanceled if cancelled.
126
+ """
127
+ if isinstance(chat_id, str): # @username -> numeric id
128
+ chat_id = (await self.get_chat(chat_id)).id
129
+
130
+ await _ensure_handler(self)
131
+ listener = _Listener(
132
+ chat_id, user_id, asyncio.get_running_loop().create_future(), filters
133
+ )
134
+ store = _store(self)
135
+ store.append(listener)
136
+ try:
137
+ return await asyncio.wait_for(listener.future, timeout)
138
+ except asyncio.TimeoutError:
139
+ raise ListenerTimeout(f"no answer within {timeout}s") from None
140
+ finally:
141
+ try:
142
+ store.remove(listener)
143
+ except ValueError:
144
+ pass
145
+
146
+
147
+ async def ask(self, chat_id, text, filters=None, timeout=60, user_id=None, **send_kwargs):
148
+ """Send `text` to chat_id, then wait for the answer (see listen()).
149
+
150
+ Extra keyword arguments go to send_message(). The sent message is available
151
+ as `response.request` (also `response.sent_message`). A blank `text` skips
152
+ sending and only listens.
153
+ """
154
+ request = None
155
+ if text and str(text).strip():
156
+ request = await self.send_message(chat_id, text, **send_kwargs)
157
+ chat_id = request.chat.id
158
+
159
+ kwargs = {"filters": filters, "timeout": timeout}
160
+ if user_id is not None: # keeps this working with listen() from other libs
161
+ kwargs["user_id"] = user_id
162
+ response = await self.listen(chat_id, **kwargs)
163
+
164
+ if response is not None:
165
+ for attr in ("request", "sent_message"):
166
+ try:
167
+ setattr(response, attr, request)
168
+ except Exception:
169
+ pass
170
+ return response
171
+
172
+
173
+ def cancel_listener(self, chat_id=None, user_id=None) -> int:
174
+ """Cancel pending listeners; their listen()/ask() raises ListenerCanceled.
175
+
176
+ With no arguments every listener of this client is cancelled.
177
+ Returns how many were cancelled.
178
+ """
179
+ cancelled = 0
180
+ for listener in list(_store(self)):
181
+ if chat_id is not None and listener.chat_id != chat_id:
182
+ continue
183
+ if user_id is not None and listener.user_id != user_id:
184
+ continue
185
+ if not listener.future.done():
186
+ listener.future.set_exception(ListenerCanceled())
187
+ cancelled += 1
188
+ return cancelled
189
+
190
+
191
+ def _install(name, func):
192
+ existing = getattr(Client, name, None)
193
+ if existing is not None and not getattr(existing, "_pyrolisten", False):
194
+ return False # the installed library already provides it
195
+ func._pyrolisten = True
196
+ setattr(Client, name, func)
197
+ return True
198
+
199
+
200
+ _install("listen", listen)
201
+ _install("ask", ask)
202
+ _install("cancel_listener", cancel_listener)
203
+ _install("stop_listening", cancel_listener)
204
+
205
+
206
+ # Make the exceptions importable straight from the Pyrogram package, e.g.
207
+ # from pyrogram import ListenerTimeout, ListenerCanceled
208
+ # (never overrides a name the installed library already defines)
209
+ for _name, _exc in (
210
+ ("ListenerTimeout", ListenerTimeout),
211
+ ("ListenerCanceled", ListenerCanceled),
212
+ ("ListenerCancelled", ListenerCanceled),
213
+ ("ListenerStopped", ListenerCanceled),
214
+ ):
215
+ if not hasattr(_pg, _name):
216
+ setattr(_pg, _name, _exc)
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyrolisten
3
+ Version: 0.1.0
4
+ Summary: listen() and ask() for Pyrogram, Kurigram and other Pyrogram forks
5
+ Project-URL: Homepage, https://github.com/ps-updates/pyrolisten
6
+ Project-URL: Issues, https://github.com/ps-updates/pyrolisten/issues
7
+ Author-email: Maharam Ali Khan <psupdates74@gmail.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: ask,conversation,kurigram,listen,pyrogram,telegram
11
+ Requires-Python: >=3.8
12
+ Provides-Extra: kurigram
13
+ Requires-Dist: kurigram; extra == 'kurigram'
14
+ Provides-Extra: pyrogram
15
+ Requires-Dist: pyrogram; extra == 'pyrogram'
16
+ Provides-Extra: wzgram
17
+ Requires-Dist: wzgram; extra == 'wzgram'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # pyrolisten
21
+
22
+ `client.listen()` and `client.ask()` for **Pyrogram, Kurigram and other Pyrogram forks**.
23
+ Methods your library already provides are never overridden.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install git+https://github.com/ps-updates/pyrolisten.git
29
+ ```
30
+
31
+ pyrolisten does not force a Pyrogram library on you, because most forks install the same
32
+ `pyrogram` module and two of them in one environment break each other. If you already have one
33
+ (`pyrogram`, `kurigram`, `wzgram`, ...), you're done. If not, pick one with an extra:
34
+
35
+ ```bash
36
+ pip install "pyrolisten[kurigram] @ git+https://github.com/ps-updates/pyrolisten.git"
37
+ ```
38
+
39
+ Extras: `pyrogram`, `kurigram`, `wzgram`. Choose **one**.
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ import pyrolisten.listen # once, at startup (e.g. main.py), before your plugins load
45
+ from pyrogram import Client, filters, ListenerTimeout, ListenerCanceled
46
+
47
+ app = Client("my_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
48
+
49
+ @app.on_message(filters.command("name"))
50
+ async def name(client, message):
51
+ try:
52
+ reply = await client.ask(
53
+ message.chat.id, "What's your name?",
54
+ user_id=message.from_user.id, timeout=30,
55
+ )
56
+ await reply.reply(f"Hi {reply.text}!")
57
+ except ListenerTimeout:
58
+ await message.reply("Too slow!")
59
+ except ListenerCanceled:
60
+ pass # client.cancel_listener(...) was called
61
+
62
+ app.run()
63
+ ```
64
+
65
+ ## API
66
+
67
+ | Method | Description |
68
+ |---|---|
69
+ | `await client.listen(chat_id=None, filters=None, timeout=60, user_id=None)` | Wait for the next matching message. `timeout=None` waits forever. |
70
+ | `await client.ask(chat_id, text, filters=None, timeout=60, user_id=None, **send_kwargs)` | Send `text`, then wait. The sent message is `response.request`. |
71
+ | `client.cancel_listener(chat_id=None, user_id=None)` | Cancel pending listeners (all if no arguments). Returns the count. Alias: `stop_listening`. |
72
+
73
+ After `import pyrolisten.listen` the exceptions can be imported from `pyrogram` itself
74
+ (`from pyrogram import ListenerTimeout, ListenerCanceled`), or from `pyrolisten`. This needs
75
+ `pyrolisten.listen` to be imported **first**; editors and type checkers won't know about
76
+ these names, so `from pyrolisten import ...` is the safer choice for typed projects.
77
+
78
+ Exceptions: `ListenerTimeout` (also an `asyncio.TimeoutError`) and `ListenerCanceled`
79
+ (aliases: `ListenerCancelled`, `ListenerStopped`).
80
+
81
+ ## Author
82
+
83
+ [Maharam Ali Khan](https://github.com/ps-updates)
84
+
85
+ Based on the idea of [Kurikit](https://github.com/TechifyBots/Kurikit); the `listen`/`ask` API
86
+ is inspired by pyromod. No pyromod code is used.
87
+
88
+ ## License
89
+
90
+ MIT (see `LICENSE`)
@@ -0,0 +1,7 @@
1
+ pyrolisten/__init__.py,sha256=XrSg2cokdrqQ1e0NXEo0jsotVQLnBSFjkZvPiS64irs,462
2
+ pyrolisten/exceptions.py,sha256=LSDlGaUENsTLST3IllOVZ0gfp_HXmzpB6pDj5wdTZ5E,555
3
+ pyrolisten/listen.py,sha256=cmcpxkd1w_FVLpO2pAf53tovEK7AI3Xhvg2RC0QqXmU,6979
4
+ pyrolisten-0.1.0.dist-info/METADATA,sha256=9OQiUl5JJlPa-_Lb951M1-JSS5wNg5-9wAlzUqyNTic,3307
5
+ pyrolisten-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ pyrolisten-0.1.0.dist-info/licenses/LICENSE,sha256=GcDW1XXhuOKXccOqOgxzVYVtUYg68vxZ3CtnCz-EpBQ,1073
7
+ pyrolisten-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maharam Ali Khan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.