Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[V2] add inlinecallback to buttoncallback event #4252

Open
wants to merge 13 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 125 additions & 13 deletions client/src/telethon/_impl/client/events/queries.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Dict, Optional, Self
import struct
import typing
from typing import TYPE_CHECKING, Dict, Optional, Self, Union

from ...tl import abcs, functions, types
from ..types import Chat, Message
from ..types import Chat, Message, Channel
from .event import Event
from ..types.chat import peer_id
from ..client.messages import CherryPickedList
Expand All @@ -22,7 +24,7 @@ class ButtonCallback(Event):
def __init__(
self,
client: Client,
update: types.UpdateBotCallbackQuery,
update: Union[types.UpdateBotCallbackQuery, types.UpdateInlineBotCallbackQuery],
chat_map: Dict[int, Chat],
):
self._client = client
Expand All @@ -33,7 +35,13 @@ def __init__(
def _try_from_update(
cls, client: Client, update: abcs.Update, chat_map: Dict[int, Chat]
) -> Optional[Self]:
if isinstance(update, types.UpdateBotCallbackQuery) and update.data is not None:
if (
isinstance(
update,
(types.UpdateBotCallbackQuery, types.UpdateInlineBotCallbackQuery),
)
and update.data is not None
):
return cls._create(client, update, chat_map)
else:
return None
Expand All @@ -43,6 +51,71 @@ def data(self) -> bytes:
assert self._raw.data is not None
return self._raw.data

@property
def via_inline(self) -> bool:
"""
Whether the button was clicked in an inline message.

If it was, most likely bot is not in chat, and the :meth:`chat` property will return :data:`None`,
same for :meth:`get_message` method, however editing the message, using :meth:`message_id` property
and :meth:`answer` method will work.
apepenkov marked this conversation as resolved.
Show resolved Hide resolved
"""
return isinstance(self._raw, types.UpdateInlineBotCallbackQuery)

@property
def message_id(self) -> typing.Union[int, abcs.InputBotInlineMessageId]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should never return abcs to the user. They're in a private package.

"""
The ID of the message containing the button that was clicked.
apepenkov marked this conversation as resolved.
Show resolved Hide resolved

If the message is inline, :class:`abcs.InputBotInlineMessageId` will be returned.
You can use it in :meth:`~telethon._tl.functions.messages.edit_inline_bot_message` to edit the message.

Else, usual message ID will be returned.
"""
return self._raw.msg_id

@property
def chat(self) -> Optional[Chat]:
"""
The :term:`chat` where the button was clicked.

This will be :data:`None` if the message with the button was sent from a user's inline query, except in channel.
apepenkov marked this conversation as resolved.
Show resolved Hide resolved
"""
if isinstance(self._raw, types.UpdateInlineBotCallbackQuery):
owner_id = None
if isinstance(self._raw.msg_id, types.InputBotInlineMessageId):
_, owner_id = struct.unpack("<ii", struct.pack("<q", self._raw.msg_id.id))
elif isinstance(self._raw.msg_id, types.InputBotInlineMessageId64):
_ = self._raw.msg_id.id
owner_id = self._raw.msg_id.owner_id

if owner_id is None:
return None

if owner_id > 0:
# We can't know if it's really a chat with user, or an ID of the user who issued the inline query.
# So it's better to return None, then to return wrong chat.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo then -> than.

Still a bit weird that there's no way to tell. Does the update type not contain any other hint elsewhere?

return None

owner_id = -owner_id

access_hash = 0
packed = self.client._chat_hashes.get(owner_id)
if packed:
access_hash = packed.access_hash

return Channel._from_raw(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not check the chat_map with the owner_id first?

types.ChannelForbidden(
broadcast=True,
megagroup=False,
id=owner_id,
access_hash=access_hash,
title="",
until_date=None,
)
)
return self._chat_map.get(peer_id(self._raw.peer))

async def answer(
self,
text: Optional[str] = None,
Expand Down Expand Up @@ -75,20 +148,59 @@ async def get_message(self) -> Optional[Message]:
"""
Get the :class:`~telethon.types.Message` containing the button that was clicked.

If the message is too old and is no longer accessible, :data:`None` is returned instead.
If the message is inline, or too old and is no longer accessible, :data:`None` is returned instead.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But isn't the purpose of using InputMessageCallbackQuery the fact that it can work? functions.messages.get_messages doesn't need a chat. CherryPickedList does require one, so I see the problem.

But we should be able to fetch the message without a chat. So maybe we need to rethink this method's implementation.

"""
chat = None

if isinstance(self._raw, types.UpdateInlineBotCallbackQuery):
# for that type of update, the msg_id and owner_id are present, however bot is not guaranteed
# to have "access" to the owner_id.
if isinstance(self._raw.msg_id, types.InputBotInlineMessageId):
# telegram used to pack msg_id and peer_id into InputBotInlineMessageId.id
# I assume this is for the chats with IDs, fitting into 32-bit integer.
msg_id, owner_id = struct.unpack(
"<ii", struct.pack("<q", self._raw.msg_id.id)
)
elif isinstance(self._raw.msg_id, types.InputBotInlineMessageId64):
msg_id = self._raw.msg_id.id
owner_id = self._raw.msg_id.owner_id
else:
return None
apepenkov marked this conversation as resolved.
Show resolved Hide resolved

msg = types.InputMessageCallbackQuery(
id=msg_id, query_id=self._raw.query_id
)
if owner_id < 0:
# that means update's owner_id actually is the peer (channel), where the button was clicked.
# if it was positive, it'd be the user who issued the inline query.
try:
chat = await self._client._resolve_to_packed(-owner_id)
except ValueError:
pass
else:
pid = peer_id(self._raw.peer)
msg = types.InputMessageCallbackQuery(
id=self._raw.msg_id, query_id=self._raw.query_id
)

pid = peer_id(self._raw.peer)
chat = self._chat_map.get(pid)
if not chat:
chat = await self._client._resolve_to_packed(pid)
chat = self._chat_map.get(pid)
if not chat:
chat = await self._client._resolve_to_packed(pid)

lst = CherryPickedList(self._client, chat, [])
lst._ids.append(types.InputMessageCallbackQuery(id=self._raw.msg_id, query_id=self._raw.query_id))
if chat:
lst = CherryPickedList(self._client, chat, [])
lst._ids.append(msg)

message = (await lst)[0]
res = await lst
if res:
return res[0] or None

return message or None
res = await self._client(
functions.messages.get_messages(
id=[msg],
)
)
return res.messages[0] if res.messages else None


class InlineQuery(Event):
Expand Down
9 changes: 6 additions & 3 deletions client/src/telethon/_impl/client/types/chat/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,13 @@ def pack(self) -> Optional[PackedChat]:
if self._raw.access_hash is None:
return None
else:
ty = PackedType.BROADCAST
if getattr(self._raw, "megagroup", False):
ty = PackedType.MEGAGROUP
elif getattr(self._raw, "gigagroup", False):
ty = PackedType.GIGAGROUP
apepenkov marked this conversation as resolved.
Show resolved Hide resolved
return PackedChat(
ty=PackedType.GIGAGROUP
if getattr(self._raw, "gigagroup", False)
else PackedType.BROADCAST,
ty=ty,
id=self._raw.id,
access_hash=self._raw.access_hash,
)
Expand Down
2 changes: 1 addition & 1 deletion client/src/telethon/_impl/client/types/chat/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def pack(self) -> Optional[PackedChat]:
return None
else:
return PackedChat(
ty=PackedType.MEGAGROUP,
ty=PackedType.GIGAGROUP if getattr(self._raw, "gigagroup", False) else PackedType.MEGAGROUP,
id=self._raw.id,
access_hash=self._raw.access_hash,
)
Expand Down
2 changes: 1 addition & 1 deletion client/src/telethon/_impl/client/types/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def _from_raw(
@property
def chat(self) -> Chat:
"""
The chat where messages are sent in this dialog.
The :term:`chat` where messages are sent in this dialog.
"""
return self._chat_map[peer_id(self._raw.peer)]

Expand Down
2 changes: 1 addition & 1 deletion client/src/telethon/_impl/client/types/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _from_raw(
@property
def chat(self) -> Chat:
"""
The chat where the draft is saved.
The :term:`chat` where the draft is saved.

This is also the chat where the message will be sent to by :meth:`send`.
"""
Expand Down