2018-08-03 18:51:56 +03:00
|
|
|
import asyncio
|
2020-04-28 22:02:27 +03:00
|
|
|
import functools
|
2020-05-16 10:58:37 +03:00
|
|
|
import inspect
|
2018-08-03 18:51:56 +03:00
|
|
|
import itertools
|
|
|
|
import time
|
|
|
|
|
|
|
|
from .chatgetter import ChatGetter
|
2019-04-13 11:53:33 +03:00
|
|
|
from ... import helpers, utils, errors
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2019-03-11 15:03:10 +03:00
|
|
|
# Sometimes the edits arrive very fast (within the same second).
|
|
|
|
# In that case we add a small delta so that the age is older, for
|
|
|
|
# comparision purposes. This value is enough for up to 1000 messages.
|
|
|
|
_EDIT_COLLISION_DELTA = 0.001
|
|
|
|
|
|
|
|
|
2020-04-28 22:02:27 +03:00
|
|
|
def _checks_cancelled(f):
|
|
|
|
@functools.wraps(f)
|
|
|
|
def wrapper(self, *args, **kwargs):
|
|
|
|
if self._cancelled:
|
|
|
|
raise asyncio.CancelledError('The conversation was cancelled before')
|
|
|
|
|
|
|
|
return f(self, *args, **kwargs)
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
class Conversation(ChatGetter):
|
|
|
|
"""
|
|
|
|
Represents a conversation inside an specific chat.
|
|
|
|
|
|
|
|
A conversation keeps track of new messages since it was
|
|
|
|
created until its exit and easily lets you query the
|
|
|
|
current state.
|
|
|
|
|
|
|
|
If you need a conversation across two or more chats,
|
|
|
|
you should use two conversations and synchronize them
|
|
|
|
as you better see fit.
|
|
|
|
"""
|
|
|
|
_id_counter = 0
|
2018-08-05 02:55:41 +03:00
|
|
|
_custom_counter = 0
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
def __init__(self, client, input_chat,
|
|
|
|
*, timeout, total_timeout, max_messages,
|
2018-10-12 23:17:07 +03:00
|
|
|
exclusive, replies_are_responses):
|
2019-05-12 15:00:12 +03:00
|
|
|
# This call resets the client
|
|
|
|
ChatGetter.__init__(self, input_chat=input_chat)
|
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
self._id = Conversation._id_counter
|
|
|
|
Conversation._id_counter += 1
|
|
|
|
|
|
|
|
self._client = client
|
|
|
|
self._timeout = timeout
|
2018-08-04 16:35:04 +03:00
|
|
|
self._total_timeout = total_timeout
|
|
|
|
self._total_due = None
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
self._outgoing = set()
|
|
|
|
self._last_outgoing = 0
|
|
|
|
self._incoming = []
|
|
|
|
self._last_incoming = 0
|
|
|
|
self._max_incoming = max_messages
|
|
|
|
self._last_read = None
|
2018-08-05 02:55:41 +03:00
|
|
|
self._custom = {}
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
self._pending_responses = {}
|
|
|
|
self._pending_replies = {}
|
|
|
|
self._pending_edits = {}
|
|
|
|
self._pending_reads = {}
|
|
|
|
|
2018-10-12 23:17:07 +03:00
|
|
|
self._exclusive = exclusive
|
2019-06-03 20:44:43 +03:00
|
|
|
self._cancelled = False
|
2018-10-12 23:17:07 +03:00
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
# The user is able to expect two responses for the same message.
|
|
|
|
# {desired message ID: next incoming index}
|
|
|
|
self._response_indices = {}
|
|
|
|
if replies_are_responses:
|
|
|
|
self._reply_indices = self._response_indices
|
|
|
|
else:
|
|
|
|
self._reply_indices = {}
|
|
|
|
|
2018-08-04 16:35:51 +03:00
|
|
|
self._edit_dates = {}
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2020-04-28 22:02:27 +03:00
|
|
|
@_checks_cancelled
|
2018-08-03 18:51:56 +03:00
|
|
|
async def send_message(self, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Sends a message in the context of this conversation. Shorthand
|
|
|
|
for `telethon.client.messages.MessageMethods.send_message` with
|
|
|
|
``entity`` already set.
|
|
|
|
"""
|
2019-10-22 21:35:08 +03:00
|
|
|
sent = await self._client.send_message(
|
2018-08-03 18:51:56 +03:00
|
|
|
self._input_chat, *args, **kwargs)
|
|
|
|
|
2019-10-22 21:35:08 +03:00
|
|
|
# Albums will be lists, so handle that
|
|
|
|
ms = sent if isinstance(sent, list) else (sent,)
|
|
|
|
self._outgoing.update(m.id for m in ms)
|
|
|
|
self._last_outgoing = ms[-1].id
|
|
|
|
return sent
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2020-04-28 22:02:27 +03:00
|
|
|
@_checks_cancelled
|
2018-08-05 00:21:19 +03:00
|
|
|
async def send_file(self, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Sends a file in the context of this conversation. Shorthand
|
|
|
|
for `telethon.client.uploads.UploadMethods.send_file` with
|
|
|
|
``entity`` already set.
|
|
|
|
"""
|
2019-10-22 21:35:08 +03:00
|
|
|
sent = await self._client.send_file(
|
2018-08-05 00:21:19 +03:00
|
|
|
self._input_chat, *args, **kwargs)
|
|
|
|
|
2019-10-22 21:35:08 +03:00
|
|
|
# Albums will be lists, so handle that
|
|
|
|
ms = sent if isinstance(sent, list) else (sent,)
|
|
|
|
self._outgoing.update(m.id for m in ms)
|
|
|
|
self._last_outgoing = ms[-1].id
|
|
|
|
return sent
|
2018-08-05 00:21:19 +03:00
|
|
|
|
2020-04-28 22:02:27 +03:00
|
|
|
@_checks_cancelled
|
2018-08-06 17:30:25 +03:00
|
|
|
def mark_read(self, message=None):
|
2018-08-05 00:21:19 +03:00
|
|
|
"""
|
|
|
|
Marks as read the latest received message if ``message is None``.
|
|
|
|
Otherwise, marks as read until the given message (or message ID).
|
|
|
|
|
|
|
|
This is equivalent to calling `client.send_read_acknowledge
|
|
|
|
<telethon.client.messages.MessageMethods.send_read_acknowledge>`.
|
|
|
|
"""
|
|
|
|
if message is None:
|
|
|
|
if self._incoming:
|
|
|
|
message = self._incoming[-1].id
|
|
|
|
else:
|
|
|
|
message = 0
|
|
|
|
elif not isinstance(message, int):
|
|
|
|
message = message.id
|
|
|
|
|
2018-08-06 17:30:25 +03:00
|
|
|
return self._client.send_read_acknowledge(
|
2018-08-05 00:21:19 +03:00
|
|
|
self._input_chat, max_id=message)
|
|
|
|
|
2019-08-13 19:11:02 +03:00
|
|
|
def get_response(self, message=None, *, timeout=None):
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2020-06-22 14:21:45 +03:00
|
|
|
Gets the next message that responds to a previous one. This is
|
|
|
|
the method you need most of the time, along with `get_edit`.
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
Args:
|
2019-01-12 15:06:14 +03:00
|
|
|
message (`Message <telethon.tl.custom.message.Message>` | `int`, optional):
|
2018-08-03 18:51:56 +03:00
|
|
|
The message (or the message ID) for which a response
|
|
|
|
is expected. By default this is the last sent message.
|
|
|
|
|
|
|
|
timeout (`int` | `float`, optional):
|
2019-03-18 19:30:45 +03:00
|
|
|
If present, this `timeout` (in seconds) will override the
|
2018-08-03 18:51:56 +03:00
|
|
|
per-action timeout defined for the conversation.
|
2020-06-22 14:21:45 +03:00
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
async with client.conversation(...) as conv:
|
|
|
|
await conv.send_message('Hey, what is your name?')
|
|
|
|
|
|
|
|
response = await conv.get_response()
|
|
|
|
name = response.text
|
|
|
|
|
|
|
|
await conv.send_message('Nice to meet you, {}!'.format(name))
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2019-08-13 19:11:02 +03:00
|
|
|
return self._get_message(
|
2018-08-03 18:51:56 +03:00
|
|
|
message, self._response_indices, self._pending_responses, timeout,
|
|
|
|
lambda x, y: True
|
|
|
|
)
|
|
|
|
|
2019-08-13 19:11:02 +03:00
|
|
|
def get_reply(self, message=None, *, timeout=None):
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2019-05-07 22:25:55 +03:00
|
|
|
Gets the next message that explicitly replies to a previous one.
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2019-08-13 19:11:02 +03:00
|
|
|
return self._get_message(
|
2018-08-03 18:51:56 +03:00
|
|
|
message, self._reply_indices, self._pending_replies, timeout,
|
|
|
|
lambda x, y: x.reply_to_msg_id == y
|
|
|
|
)
|
|
|
|
|
2019-05-27 15:23:42 +03:00
|
|
|
def _get_message(
|
2018-08-03 18:51:56 +03:00
|
|
|
self, target_message, indices, pending, timeout, condition):
|
|
|
|
"""
|
|
|
|
Gets the next desired message under the desired condition.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
target_message (`object`):
|
|
|
|
The target message for which we want to find another
|
|
|
|
response that applies based on `condition`.
|
|
|
|
|
|
|
|
indices (`dict`):
|
|
|
|
This dictionary remembers the last ID chosen for the
|
|
|
|
input `target_message`.
|
|
|
|
|
|
|
|
pending (`dict`):
|
|
|
|
This dictionary remembers {msg_id: Future} to be set
|
|
|
|
once `condition` is met.
|
|
|
|
|
|
|
|
timeout (`int`):
|
2019-03-18 19:30:45 +03:00
|
|
|
The timeout (in seconds) override to use for this operation.
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
condition (`callable`):
|
|
|
|
The condition callable that checks if an incoming
|
|
|
|
message is a valid response.
|
|
|
|
"""
|
2018-08-06 17:31:15 +03:00
|
|
|
start_time = time.time()
|
2018-08-03 18:51:56 +03:00
|
|
|
target_id = self._get_message_id(target_message)
|
|
|
|
|
|
|
|
# If there is no last-chosen ID, make sure to pick one *after*
|
|
|
|
# the input message, since we don't want responses back in time
|
|
|
|
if target_id not in indices:
|
2018-08-05 13:28:54 +03:00
|
|
|
for i, incoming in enumerate(self._incoming):
|
2018-08-03 18:51:56 +03:00
|
|
|
if incoming.id > target_id:
|
|
|
|
indices[target_id] = i
|
|
|
|
break
|
|
|
|
else:
|
2018-08-05 13:28:54 +03:00
|
|
|
indices[target_id] = len(self._incoming)
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2019-02-10 13:45:25 +03:00
|
|
|
# We will always return a future from here, even if the result
|
|
|
|
# can be set immediately. Otherwise, needing to await only
|
|
|
|
# sometimes is an annoying edge case (i.e. we would return
|
|
|
|
# a `Message` but `get_response()` always `await`'s).
|
|
|
|
future = self._client.loop.create_future()
|
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
# If there are enough responses saved return the next one
|
|
|
|
last_idx = indices[target_id]
|
|
|
|
if last_idx < len(self._incoming):
|
|
|
|
incoming = self._incoming[last_idx]
|
|
|
|
if condition(incoming, target_id):
|
|
|
|
indices[target_id] += 1
|
2019-02-10 13:45:25 +03:00
|
|
|
future.set_result(incoming)
|
|
|
|
return future
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
# Otherwise the next incoming response will be the one to use
|
2019-05-27 15:23:42 +03:00
|
|
|
#
|
|
|
|
# Note how we fill "pending" before giving control back to the
|
|
|
|
# event loop through "await". We want to register it as soon as
|
|
|
|
# possible, since any other task switch may arrive with the result.
|
2018-08-03 18:51:56 +03:00
|
|
|
pending[target_id] = future
|
2019-05-27 15:23:42 +03:00
|
|
|
return self._get_result(future, start_time, timeout, pending, target_id)
|
2018-08-04 16:35:51 +03:00
|
|
|
|
2019-08-13 19:11:02 +03:00
|
|
|
def get_edit(self, message=None, *, timeout=None):
|
2018-08-04 16:35:51 +03:00
|
|
|
"""
|
|
|
|
Awaits for an edit after the last message to arrive.
|
|
|
|
The arguments are the same as those for `get_response`.
|
|
|
|
"""
|
2018-08-06 17:31:15 +03:00
|
|
|
start_time = time.time()
|
2018-08-04 16:35:51 +03:00
|
|
|
target_id = self._get_message_id(message)
|
|
|
|
|
|
|
|
target_date = self._edit_dates.get(target_id, 0)
|
|
|
|
earliest_edit = min(
|
|
|
|
(x for x in self._incoming
|
2018-08-14 19:42:16 +03:00
|
|
|
if x.edit_date
|
|
|
|
and x.id > target_id
|
|
|
|
and x.edit_date.timestamp() > target_date
|
|
|
|
),
|
|
|
|
key=lambda x: x.edit_date.timestamp(),
|
2018-08-04 16:35:51 +03:00
|
|
|
default=None
|
|
|
|
)
|
|
|
|
|
2019-10-31 12:43:42 +03:00
|
|
|
future = self._client.loop.create_future()
|
2018-08-14 19:42:16 +03:00
|
|
|
if earliest_edit and earliest_edit.edit_date.timestamp() > target_date:
|
|
|
|
self._edit_dates[target_id] = earliest_edit.edit_date.timestamp()
|
2019-10-31 12:43:42 +03:00
|
|
|
future.set_result(earliest_edit)
|
|
|
|
return future # we should always return something we can await
|
2018-08-04 16:35:51 +03:00
|
|
|
|
|
|
|
# Otherwise the next incoming response will be the one to use
|
|
|
|
self._pending_edits[target_id] = future
|
2019-08-13 19:11:02 +03:00
|
|
|
return self._get_result(future, start_time, timeout, self._pending_edits, target_id)
|
2018-08-04 16:35:51 +03:00
|
|
|
|
2019-08-13 19:11:02 +03:00
|
|
|
def wait_read(self, message=None, *, timeout=None):
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2019-05-07 22:25:55 +03:00
|
|
|
Awaits for the sent message to be marked as read. Note that
|
|
|
|
receiving a response doesn't imply the message was read, and
|
|
|
|
this action will also trigger even without a response.
|
2018-08-03 18:51:56 +03:00
|
|
|
"""
|
2018-08-06 17:31:15 +03:00
|
|
|
start_time = time.time()
|
2018-08-21 13:22:06 +03:00
|
|
|
future = self._client.loop.create_future()
|
2018-08-03 18:51:56 +03:00
|
|
|
target_id = self._get_message_id(message)
|
|
|
|
|
|
|
|
if self._last_read is None:
|
|
|
|
self._last_read = target_id - 1
|
|
|
|
|
|
|
|
if self._last_read >= target_id:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._pending_reads[target_id] = future
|
2019-08-13 19:11:02 +03:00
|
|
|
return self._get_result(future, start_time, timeout, self._pending_reads, target_id)
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2018-08-14 19:41:13 +03:00
|
|
|
async def wait_event(self, event, *, timeout=None):
|
2018-08-05 02:55:41 +03:00
|
|
|
"""
|
|
|
|
Waits for a custom event to occur. Timeouts still apply.
|
|
|
|
|
2019-09-24 17:19:35 +03:00
|
|
|
.. note::
|
|
|
|
|
2020-06-22 14:21:45 +03:00
|
|
|
**Only use this if there isn't another method available!**
|
2019-09-24 17:19:35 +03:00
|
|
|
For example, don't use `wait_event` for new messages,
|
|
|
|
since `get_response` already exists, etc.
|
|
|
|
|
2018-08-05 02:55:41 +03:00
|
|
|
Unless you're certain that your code will run fast enough,
|
|
|
|
generally you should get a "handle" of this special coroutine
|
2020-06-22 14:21:45 +03:00
|
|
|
before acting. In this example you will see how to wait for a user
|
|
|
|
to join a group with proper use of `wait_event`:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from telethon import TelegramClient, events
|
|
|
|
|
|
|
|
client = TelegramClient(...)
|
|
|
|
group_id = ...
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
# Could also get the user id from an event; this is just an example
|
|
|
|
user_id = ...
|
|
|
|
|
|
|
|
async with client.conversation(user_id) as conv:
|
|
|
|
# Get a handle to the future event we'll wait for
|
|
|
|
handle = conv.wait_event(events.ChatAction(
|
|
|
|
group_id,
|
|
|
|
func=lambda e: e.user_joined and e.user_id == user_id
|
|
|
|
))
|
|
|
|
|
|
|
|
# Perform whatever action in between
|
|
|
|
await conv.send_message('Please join this group before speaking to me!')
|
|
|
|
|
|
|
|
# Wait for the event we registered above to fire
|
|
|
|
event = await handle
|
|
|
|
|
|
|
|
# Continue with the conversation
|
|
|
|
await conv.send_message('Thanks!')
|
2018-08-05 02:55:41 +03:00
|
|
|
|
|
|
|
This way your event can be registered before acting,
|
|
|
|
since the response may arrive before your event was
|
|
|
|
registered. It depends on your use case since this
|
|
|
|
also means the event can arrive before you send
|
|
|
|
a previous action.
|
|
|
|
"""
|
2018-08-06 17:31:15 +03:00
|
|
|
start_time = time.time()
|
2018-08-05 02:55:41 +03:00
|
|
|
if isinstance(event, type):
|
|
|
|
event = event()
|
|
|
|
|
2018-10-05 14:42:07 +03:00
|
|
|
await event.resolve(self._client)
|
2018-08-21 12:08:08 +03:00
|
|
|
|
2018-08-05 02:55:41 +03:00
|
|
|
counter = Conversation._custom_counter
|
|
|
|
Conversation._custom_counter += 1
|
|
|
|
|
2019-05-27 15:23:42 +03:00
|
|
|
future = self._client.loop.create_future()
|
2018-08-21 12:08:08 +03:00
|
|
|
self._custom[counter] = (event, future)
|
2019-05-27 15:23:42 +03:00
|
|
|
return await self._get_result(future, start_time, timeout, self._custom, counter)
|
2018-08-05 02:55:41 +03:00
|
|
|
|
2019-05-01 18:07:12 +03:00
|
|
|
async def _check_custom(self, built):
|
2019-06-15 22:36:06 +03:00
|
|
|
for key, (ev, fut) in list(self._custom.items()):
|
2018-08-05 02:55:41 +03:00
|
|
|
ev_type = type(ev)
|
2019-05-01 18:07:12 +03:00
|
|
|
inst = built[ev_type]
|
2020-05-16 10:58:37 +03:00
|
|
|
|
|
|
|
if inst:
|
|
|
|
filter = ev.filter(inst)
|
|
|
|
if inspect.isawaitable(filter):
|
|
|
|
filter = await filter
|
|
|
|
|
|
|
|
if filter:
|
|
|
|
fut.set_result(inst)
|
|
|
|
del self._custom[key]
|
2018-08-05 02:55:41 +03:00
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
def _on_new_message(self, response):
|
2018-08-14 19:42:16 +03:00
|
|
|
response = response.message
|
2018-08-03 18:51:56 +03:00
|
|
|
if response.chat_id != self.chat_id or response.out:
|
|
|
|
return
|
|
|
|
|
|
|
|
if len(self._incoming) == self._max_incoming:
|
2018-08-05 14:15:19 +03:00
|
|
|
self._cancel_all(ValueError('Too many incoming messages'))
|
2018-08-03 18:51:56 +03:00
|
|
|
return
|
|
|
|
|
|
|
|
self._incoming.append(response)
|
2018-08-04 16:35:51 +03:00
|
|
|
|
2019-06-15 22:36:06 +03:00
|
|
|
# Most of the time, these dictionaries will contain just one item
|
|
|
|
# TODO In fact, why not make it be that way? Force one item only.
|
|
|
|
# How often will people want to wait for two responses at
|
|
|
|
# the same time? It's impossible, first one will arrive
|
|
|
|
# and then another, so they can do that.
|
|
|
|
for msg_id, future in list(self._pending_responses.items()):
|
2018-08-03 18:51:56 +03:00
|
|
|
self._response_indices[msg_id] = len(self._incoming)
|
2019-05-27 15:23:42 +03:00
|
|
|
future.set_result(response)
|
2019-06-15 22:36:06 +03:00
|
|
|
del self._pending_responses[msg_id]
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2019-06-15 22:36:06 +03:00
|
|
|
for msg_id, future in list(self._pending_replies.items()):
|
2018-08-03 18:51:56 +03:00
|
|
|
if msg_id == response.reply_to_msg_id:
|
|
|
|
self._reply_indices[msg_id] = len(self._incoming)
|
2019-05-27 15:23:42 +03:00
|
|
|
future.set_result(response)
|
2019-06-15 22:36:06 +03:00
|
|
|
del self._pending_replies[msg_id]
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
def _on_edit(self, message):
|
2018-08-14 19:42:16 +03:00
|
|
|
message = message.message
|
2018-08-03 18:51:56 +03:00
|
|
|
if message.chat_id != self.chat_id or message.out:
|
|
|
|
return
|
|
|
|
|
2019-10-31 12:40:22 +03:00
|
|
|
# We have to update our incoming messages with the new edit date
|
|
|
|
for i, m in enumerate(self._incoming):
|
|
|
|
if m.id == message.id:
|
|
|
|
self._incoming[i] = message
|
|
|
|
break
|
|
|
|
|
2019-06-15 22:36:06 +03:00
|
|
|
for msg_id, future in list(self._pending_edits.items()):
|
2018-08-14 19:42:16 +03:00
|
|
|
if msg_id < message.id:
|
2019-03-11 15:03:10 +03:00
|
|
|
edit_ts = message.edit_date.timestamp()
|
|
|
|
|
|
|
|
# We compare <= because edit_ts resolution is always to
|
|
|
|
# seconds, but we may have increased _edit_dates before.
|
|
|
|
# Since the dates are ever growing this is not a problem.
|
|
|
|
if edit_ts <= self._edit_dates.get(msg_id, 0):
|
|
|
|
self._edit_dates[msg_id] += _EDIT_COLLISION_DELTA
|
|
|
|
else:
|
|
|
|
self._edit_dates[msg_id] = message.edit_date.timestamp()
|
2018-08-04 16:35:51 +03:00
|
|
|
|
2019-05-27 15:23:42 +03:00
|
|
|
future.set_result(message)
|
2019-06-15 22:36:06 +03:00
|
|
|
del self._pending_edits[msg_id]
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
def _on_read(self, event):
|
|
|
|
if event.chat_id != self.chat_id or event.inbox:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._last_read = event.max_id
|
|
|
|
|
|
|
|
remove_reads = []
|
2019-06-15 22:36:06 +03:00
|
|
|
for msg_id, pending in list(self._pending_reads.items()):
|
2018-08-03 18:51:56 +03:00
|
|
|
if msg_id >= self._last_read:
|
|
|
|
remove_reads.append(msg_id)
|
|
|
|
pending.set_result(True)
|
2019-06-15 22:36:06 +03:00
|
|
|
del self._pending_reads[msg_id]
|
2018-08-03 18:51:56 +03:00
|
|
|
|
|
|
|
for to_remove in remove_reads:
|
|
|
|
del self._pending_reads[to_remove]
|
|
|
|
|
|
|
|
def _get_message_id(self, message):
|
2019-04-29 09:53:04 +03:00
|
|
|
if message is not None: # 0 is valid but false-y, check for None
|
2018-08-03 18:51:56 +03:00
|
|
|
return message if isinstance(message, int) else message.id
|
|
|
|
elif self._last_outgoing:
|
|
|
|
return self._last_outgoing
|
|
|
|
else:
|
|
|
|
raise ValueError('No message was sent previously')
|
|
|
|
|
2020-04-28 22:02:27 +03:00
|
|
|
@_checks_cancelled
|
2019-08-13 19:11:02 +03:00
|
|
|
def _get_result(self, future, start_time, timeout, pending, target_id):
|
2018-08-03 18:51:56 +03:00
|
|
|
due = self._total_due
|
|
|
|
if timeout is None:
|
|
|
|
timeout = self._timeout
|
|
|
|
|
|
|
|
if timeout is not None:
|
2018-08-06 17:22:11 +03:00
|
|
|
due = min(due, start_time + timeout)
|
|
|
|
|
2019-06-15 22:36:06 +03:00
|
|
|
# NOTE: We can't try/finally to pop from pending here because
|
|
|
|
# the event loop needs to get back to us, but it might
|
|
|
|
# dispatch another update before, and in that case a
|
|
|
|
# response could be set twice. So responses must be
|
|
|
|
# cleared when their futures are set to a result.
|
2019-08-13 19:11:02 +03:00
|
|
|
return asyncio.wait_for(
|
2019-06-15 22:36:06 +03:00
|
|
|
future,
|
|
|
|
timeout=None if due == float('inf') else due - time.time(),
|
|
|
|
loop=self._client.loop
|
|
|
|
)
|
2018-08-03 18:51:56 +03:00
|
|
|
|
2018-08-05 14:15:19 +03:00
|
|
|
def _cancel_all(self, exception=None):
|
2019-06-03 20:44:43 +03:00
|
|
|
self._cancelled = True
|
2018-08-05 14:15:19 +03:00
|
|
|
for pending in itertools.chain(
|
|
|
|
self._pending_responses.values(),
|
|
|
|
self._pending_replies.values(),
|
2018-08-14 19:42:16 +03:00
|
|
|
self._pending_edits.values()):
|
2018-08-05 14:15:19 +03:00
|
|
|
if exception:
|
|
|
|
pending.set_exception(exception)
|
|
|
|
else:
|
|
|
|
pending.cancel()
|
|
|
|
|
2018-11-12 10:21:18 +03:00
|
|
|
for _, fut in self._custom.values():
|
2018-08-05 14:15:19 +03:00
|
|
|
if exception:
|
|
|
|
fut.set_exception(exception)
|
|
|
|
else:
|
|
|
|
fut.cancel()
|
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
async def __aenter__(self):
|
|
|
|
self._input_chat = \
|
|
|
|
await self._client.get_input_entity(self._input_chat)
|
|
|
|
|
|
|
|
self._chat_peer = utils.get_peer(self._input_chat)
|
2018-10-12 23:17:07 +03:00
|
|
|
|
|
|
|
# Make sure we're the only conversation in this chat if it's exclusive
|
|
|
|
chat_id = utils.get_peer_id(self._chat_peer)
|
2019-06-03 20:41:22 +03:00
|
|
|
conv_set = self._client._conversations[chat_id]
|
|
|
|
if self._exclusive and conv_set:
|
2018-10-12 23:17:07 +03:00
|
|
|
raise errors.AlreadyInConversationError()
|
|
|
|
|
2019-06-03 20:41:22 +03:00
|
|
|
conv_set.add(self)
|
2019-06-03 20:44:43 +03:00
|
|
|
self._cancelled = False
|
2018-10-12 23:17:07 +03:00
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
self._last_outgoing = 0
|
|
|
|
self._last_incoming = 0
|
2018-08-05 14:15:19 +03:00
|
|
|
for d in (
|
|
|
|
self._outgoing, self._incoming,
|
|
|
|
self._pending_responses, self._pending_replies,
|
|
|
|
self._pending_edits, self._response_indices,
|
|
|
|
self._reply_indices, self._edit_dates, self._custom):
|
|
|
|
d.clear()
|
|
|
|
|
2018-08-04 16:35:04 +03:00
|
|
|
if self._total_timeout:
|
|
|
|
self._total_due = time.time() + self._total_timeout
|
|
|
|
else:
|
|
|
|
self._total_due = float('inf')
|
|
|
|
|
2018-08-03 18:51:56 +03:00
|
|
|
return self
|
|
|
|
|
2018-10-25 16:37:36 +03:00
|
|
|
def cancel(self):
|
2019-06-03 20:28:22 +03:00
|
|
|
"""
|
|
|
|
Cancels the current conversation. Pending responses and subsequent
|
|
|
|
calls to get a response will raise ``asyncio.CancelledError``.
|
|
|
|
|
|
|
|
This method is synchronous and should not be awaited.
|
|
|
|
"""
|
|
|
|
self._cancel_all()
|
2018-10-25 16:37:36 +03:00
|
|
|
|
2019-06-03 20:41:22 +03:00
|
|
|
async def cancel_all(self):
|
|
|
|
"""
|
|
|
|
Calls `cancel` on *all* conversations in this chat.
|
|
|
|
|
|
|
|
Note that you should ``await`` this method, since it's meant to be
|
|
|
|
used outside of a context manager, and it needs to resolve the chat.
|
|
|
|
"""
|
|
|
|
chat_id = await self._client.get_peer_id(self._input_chat)
|
|
|
|
for conv in self._client._conversations[chat_id]:
|
|
|
|
conv.cancel()
|
|
|
|
|
2018-10-25 16:37:36 +03:00
|
|
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
2018-10-12 23:17:07 +03:00
|
|
|
chat_id = utils.get_peer_id(self._chat_peer)
|
2019-06-03 20:41:22 +03:00
|
|
|
conv_set = self._client._conversations[chat_id]
|
|
|
|
conv_set.discard(self)
|
|
|
|
if not conv_set:
|
|
|
|
del self._client._conversations[chat_id]
|
2018-10-12 23:17:07 +03:00
|
|
|
|
2018-08-05 14:15:19 +03:00
|
|
|
self._cancel_all()
|
2018-10-25 16:37:36 +03:00
|
|
|
|
2019-04-13 11:53:33 +03:00
|
|
|
__enter__ = helpers._sync_enter
|
|
|
|
__exit__ = helpers._sync_exit
|