Skip to content

Commit b6826da

Browse files
Add support for direct messages
A little update :)
1 parent 565c9a1 commit b6826da

36 files changed

+843
-81
lines changed

compiler/docs/compiler.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ def get_title_list(s: str) -> list:
300300
delete_chat_photo
301301
set_chat_title
302302
set_chat_description
303+
set_chat_direct_messages_group
303304
set_chat_permissions
304305
pin_chat_message
305306
unpin_chat_message
@@ -312,6 +313,8 @@ def get_title_list(s: str) -> list:
312313
get_chat_members_count
313314
get_dialogs
314315
get_dialogs_count
316+
get_direct_messages_topics_by_id
317+
get_direct_messages_topics
315318
set_chat_username
316319
archive_chats
317320
unarchive_chats
@@ -693,6 +696,8 @@ def get_title_list(s: str) -> list:
693696
PaidMediaPreview
694697
PaidMessagesRefunded
695698
PaidMessagesPriceChanged
699+
DirectMessagePriceChanged
700+
DirectMessagesTopic
696701
PaymentForm
697702
ChatBoost
698703
ContactRegistered

compiler/errors/source/400_BAD_REQUEST.tsv

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,13 @@ BROADCAST_CALLS_DISABLED Broadcast calls disabled.
6060
BROADCAST_ID_INVALIDThe channel is invalid.
6161
BROADCAST_PUBLIC_VOTERS_FORBIDDENPolls with public voters cannot be sent in channels.
6262
BROADCAST_REQUIREDThis method can only be used with a channel.
63-
BUSINESS_BOT_MISSINGBusiness bot missing.
63+
BUSINESS_BOT_MISSINGThe business bot is missing.
6464
BUSINESS_CONNECTION_INVALIDThe business connection is invalid.
6565
BUSINESS_CONNECTION_NOT_ALLOWEDThis business connection is not allowed.
6666
BUSINESS_PEER_INVALIDMessages can't be set to the specified peer through the current [business connection](https://core.telegram.org/api/business#connected-bots).
6767
BUSINESS_PEER_USAGE_MISSINGYou cannot send a message to a user through a [business connection](https://core.telegram.org/api/business#connected-bots) if the user hasn't recently contacted us.
6868
BUSINESS_RECIPIENTS_EMPTYYou didn't set any flag in inputBusinessBotRecipients, thus the bot cannot work with *any* peer.
69+
BUSINESS_RECIPIENTS_INVALIDThe specified inputBusinessBotRecipients is invalid.
6970
BUSINESS_WORK_HOURS_EMPTYNo work hours were specified.
7071
BUSINESS_WORK_HOURS_PERIOD_INVALIDThe specified work hours are invalid, see [here »](https://core.telegram.org/api/business#opening-hours) for the exact requirements.
7172
BUTTON_COPY_TEXT_INVALIDThe specified [keyboardButtonCopy](https://core.telegram.org/constructor/keyboardButtonCopy).`copy_text` is invalid.
@@ -91,6 +92,7 @@ CHANNEL_BANNED The channel is banned.
9192
CHANNEL_FORUM_MISSINGThis supergroup is not a forum.
9293
CHANNEL_ID_INVALIDThe specified supergroup ID is invalid.
9394
CHANNEL_INVALIDThe provided channel is invalid.
95+
CHANNEL_MONOFORUM_UNSUPPORTEDYou cannot use this method in direct chats.
9496
CHANNEL_PARICIPANT_MISSINGThe current user is not in the channel.
9597
CHANNEL_PRIVATEYou haven't joined this channel/supergroup.
9698
CHANNEL_TOO_BIGThis channel is too big.
@@ -150,6 +152,7 @@ DATE_EMPTY The date argument is empty.
150152
DC_ID_INVALIDThe provided dc_id is invalid.
151153
DH_G_A_INVALIDThe g_a parameter is invalid.
152154
DOCUMENT_INVALIDThe specified document is invalid.
155+
EFFECT_ID_INVALIDThe specified effect id is invalid.
153156
EMAIL_HASH_EXPIREDThe email hash expired and cannot be used to verify it.
154157
EMAIL_INVALIDThe specified email is invalid.
155158
EMAIL_NOT_ALLOWEDThe specified email cannot be used to complete the operation.
@@ -219,6 +222,7 @@ FORUM_ENABLED You can't execute the specified action because the group is a [for
219222
FRESH_CHANGE_ADMINS_FORBIDDENYou can't change administrator settings in this chat because your session was logged-in recently.
220223
FROM_MESSAGE_BOT_DISABLEDBots can't use fromMessage min constructors.
221224
FROM_PEER_INVALIDThe specified from_id is invalid.
225+
FROZEN_PARTICIPANT_MISSINGThe account is frozen and cannot access the chat participant.
222226
GAME_BOT_INVALIDYou cannot send that game with the current bot.
223227
GENERAL_MODIFY_ICON_FORBIDDENYou can't modify the icon of the "General" topic.
224228
GEO_POINT_INVALIDInvalid geo point provided.
@@ -354,7 +358,7 @@ PEER_TYPES_INVALID The passed [keyboardButtonSwitchInline](https://core.telegram
354358
PERSISTENT_TIMESTAMP_EMPTYThe pts argument is empty.
355359
PERSISTENT_TIMESTAMP_INVALIDThe persistent timestamp is invalid.
356360
PHONE_CODE_EMPTYThe phone code is missing.
357-
PHONE_CODE_EXPIREDThe provided confirmation code has expired.
361+
PHONE_CODE_EXPIREDThe provided confirmation code has expired. Make sure you haven't sent it to anyone else and use the code on the same connection.
358362
PHONE_CODE_HASH_EMPTYThe phone code hash is missing.
359363
PHONE_CODE_INVALIDThe provided confirmation code is invalid.
360364
PHONE_HASH_EXPIREDAn invalid or expired phone code hash was provided.
@@ -389,6 +393,7 @@ POLL_OPTION_INVALID IA poll option used invalid data (the data may be too long).
389393
POLL_QUESTION_INVALIDThe poll question is invalid.
390394
POLL_UNSUPPORTEDThis layer does not support polls in the invoked method.
391395
POLL_VOTE_REQUIREDCast a vote in the poll before calling this method.
396+
PRECHECKOUT_FAILEDPrecheckout failed.
392397
PREMIUM_ACCOUNT_REQUIREDA premium account is required to execute this action.
393398
PREMIUM_GIFTCODE_WAS_REFUNDEDThis gift code can't be redeemed because the giveaway organizer requested a refund.
394399
PRICING_CHAT_INVALIDThe pricing for the [subscription](https://core.telegram.org/api/subscriptions) is invalid, the maximum price is specified in the [`stars_subscription_amount_max` config key »](https://core.telegram.org/api/config#stars-subscription-amount-max).
@@ -425,6 +430,7 @@ REPLY_MARKUP_TOO_LONG The specified reply markup is too long.
425430
REPLY_MESSAGES_TOO_MUCHEach shortcut can contain a maximum of [appConfig.`quick_reply_messages_limit`](https://core.telegram.org/api/config#quick-reply-messages-limit) messages, the limit was reached.
426431
REPLY_MESSAGE_ID_INVALIDThe specified reply message id is invalid.
427432
REPLY_TO_INVALIDThe specified `reply_to` field is invalid.
433+
REPLY_TO_MONOFORUM_PEER_INVALIDThe specified `reply_to` field is invalid.
428434
REPLY_TO_USER_INVALIDThe replied-to user is invalid.
429435
REQUEST_TOKEN_INVALIDThe master DC did not accept the `request_token` from the CDN DC. Continue downloading the file from the master DC using upload.getFile.
430436
RESET_REQUEST_MISSINGNo password reset is in progress.
@@ -439,6 +445,7 @@ RINGTONE_INVALID The specified ringtone is invalid.
439445
RINGTONE_MIME_INVALIDThe MIME type for the ringtone is invalid.
440446
RSA_DECRYPT_FAILEDInternal RSA decryption failed.
441447
SAVED_DIALOGS_UNSUPPORTEDYou cannot use this method.
448+
SAVED_PEER_INVALIDThe saved peer is invalid.
442449
SCHEDULE_BOT_NOT_ALLOWEDBots are not allowed to schedule messages.
443450
SCHEDULE_DATE_INVALIDInvalid schedule date provided.
444451
SCHEDULE_DATE_TOO_LATEThe date you tried to schedule is too far in the future (more than one year).
@@ -471,6 +478,7 @@ STARGIFT_ALREADY_CONVERTED The provided star gift already converted to stars.
471478
STARGIFT_ALREADY_UPGRADEDThis star gift was already upgraded before.
472479
STARGIFT_CONVERT_TOO_OLDThis gift can no longer be converted into stars.
473480
STARGIFT_INVALIDThe passed [inputInvoiceStarGift](https://core.telegram.org/constructor/inputInvoiceStarGift) is invalid.
481+
STARGIFT_MESSAGE_INVALIDThe provided message for this gift is invalid.
474482
STARGIFT_NOT_FOUNDThe specified star gift was not found.
475483
STARGIFT_NOT_OWNERYou can't control this gift because it doesn't belong to you.
476484
STARGIFT_RESELL_NOT_ALLOWEDYou can't buy this gift. Someone else may have already bought it.
@@ -480,8 +488,11 @@ STARGIFT_UPGRADE_UNAVAILABLE Gift is not available for upgrade yet.
480488
STARGIFT_USAGE_LIMITEDThe gift is sold out.
481489
STARREF_AWAITING_ENDThe previous referral program was terminated less than 24 hours ago: further changes can be made after the date specified in userFull.starref_program.end_date.
482490
STARREF_HASH_REVOKEDThe specified affiliate link was already revoked.
491+
STARREF_MONTHS_TOO_LOWThe `duration_months` parameter must be between 0 and 36.
483492
STARREF_PERMILLE_INVALIDThe specified commission_permille is invalid: the minimum and maximum values for this parameter are contained in the [starref_min_commission_permille](https://core.telegram.org/api/config#starref-min-commission-permille) and [starref_max_commission_permille](https://core.telegram.org/api/config#starref-max-commission-permille) client configuration parameters.
484493
STARREF_PERMILLE_TOO_LOWThe specified commission_permille is too low: the minimum and maximum values for this parameter are contained in the [starref_min_commission_permille](https://core.telegram.org/api/config#starref-min-commission-permille) and [starref_max_commission_permille](https://core.telegram.org/api/config#starref-max-commission-permille) client configuration parameters.
494+
STARS_AMOUNT_INVALIDThe specified `paid_stars` amount is invalid.
495+
STARS_FORM_AMOUNT_MISMATCHThe stars form amount mismatch.
485496
STARS_INVOICE_INVALIDThe specified Telegram Star invoice is invalid.
486497
STARS_PAYMENT_REQUIREDTo import this chat invite link, you must first [pay for the associated Telegram Star subscription »](https://core.telegram.org/api/subscriptions#channel-subscriptions).
487498
START_PARAM_EMPTYThe start parameter is empty.

compiler/errors/source/403_FORBIDDEN.tsv

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ id message
22
ALLOW_PAYMENT_REQUIRED_XThe user has enabled paid messages with {value} stars.
33
ANONYMOUS_REACTIONS_DISABLEDSorry, anonymous administrators cannot leave reactions or participate in polls.
44
BOT_ACCESS_FORBIDDENYou can't access this bot.
5+
BOT_OWNER_REQUIREDYou must be the owner of the bot to perform this action.
56
BROADCAST_FORBIDDENThis request can't be used in channels.
67
CHANNEL_PUBLIC_GROUP_NAThe channel/supergroup is not available.
78
CHAT_ACTION_FORBIDDENYou cannot execute this action.

pyrogram/enums/chat_type.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,8 @@ class ChatType(AutoName):
3939
CHANNEL = auto()
4040
"Chat is a channel"
4141

42+
FORUM = auto()
43+
"Chat is a forum"
44+
4245
DIRECT = auto()
4346
"Chat is a direct with a channel"

pyrogram/enums/message_service_type.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,5 +174,8 @@ class MessageServiceType(AutoName):
174174
PAID_MESSAGES_REFUNDED = auto()
175175
"Refunded paid messages"
176176

177-
PAID_MESSAGES_PRICE = auto()
177+
PAID_MESSAGES_PRICE_CHANGED = auto()
178178
"Paid messages price"
179+
180+
DIRECT_MESSAGE_PRICE_CHANGED = auto()
181+
"Direct message price"

pyrogram/filters.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ async def private_filter(_, __, m: Message):
549549

550550
# region group_filter
551551
async def group_filter(_, __, m: Message):
552-
return bool(m.chat and m.chat.type in {enums.ChatType.GROUP, enums.ChatType.SUPERGROUP})
552+
return bool(m.chat and m.chat.type in {enums.ChatType.GROUP, enums.ChatType.SUPERGROUP, enums.ChatType.FORUM})
553553

554554

555555
group = create(group_filter)
@@ -567,6 +567,17 @@ async def channel_filter(_, __, m: Message):
567567
"""Filter messages sent in channels."""
568568

569569

570+
# endregion
571+
572+
# region direct_filter
573+
async def direct_filter(_, __, m: Message):
574+
return bool(m.chat and m.chat.type == enums.ChatType.DIRECT)
575+
576+
577+
direct = create(direct_filter)
578+
"""Filter messages sent in direct."""
579+
580+
570581
# endregion
571582

572583
# region forum_filter

pyrogram/methods/bots/send_inline_bot_result.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ async def send_inline_bot_result(
3333
result_id: str,
3434
disable_notification: Optional[bool] = None,
3535
message_thread_id: Optional[int] = None,
36+
direct_messages_chat_topic_id: int = None,
3637
reply_parameters: Optional["types.ReplyParameters"] = None,
3738
paid_message_star_count: int = None,
3839
schedule_date: datetime = None,
@@ -68,7 +69,11 @@ async def send_inline_bot_result(
6869
6970
message_thread_id (``int``, *optional*):
7071
Unique identifier of a message thread to which the message belongs.
71-
For supergroups only.
72+
For forums only.
73+
74+
direct_messages_chat_topic_id (``int``, *optional*):
75+
Unique identifier of the topic in a channel direct messages chat administered by the current user.
76+
For directs only only.
7277
7378
reply_parameters (:obj:`~pyrogram.types.ReplyParameters`, *optional*):
7479
Describes reply parameters for the message that is being sent.
@@ -153,7 +158,8 @@ async def send_inline_bot_result(
153158
reply_to=await utils.get_reply_to(
154159
self,
155160
reply_parameters,
156-
message_thread_id
161+
message_thread_id,
162+
direct_messages_chat_topic_id
157163
),
158164
schedule_date=utils.datetime_to_timestamp(schedule_date),
159165
allow_paid_stars=paid_message_star_count

pyrogram/methods/chats/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343
from .get_similar_channels import GetSimilarChannels
4444
from .get_suitable_discussion_chats import GetSuitableDiscussionChats
4545
from .get_dialogs import GetDialogs
46+
from .get_direct_messages_topics_by_id import GetDirectMessagesTopicsByID
47+
from .get_direct_messages_topics import GetDirectMessagesTopics
4648
from .get_dialogs_count import GetDialogsCount
4749
from .get_folders import GetFolders
4850
from .get_forum_topics import GetForumTopics
@@ -60,6 +62,7 @@
6062
from .restrict_chat_member import RestrictChatMember
6163
from .set_administrator_title import SetAdministratorTitle
6264
from .set_chat_description import SetChatDescription
65+
from .set_chat_direct_messages_group import SetChatDirectMessagesGroup
6366
from .set_chat_permissions import SetChatPermissions
6467
from .set_chat_discussion_group import SetChatDiscussionGroup
6568
from .set_chat_photo import SetChatPhoto
@@ -102,6 +105,7 @@ class Chats(
102105
SetChatTitle,
103106
SetChatTTL,
104107
SetChatDescription,
108+
SetChatDirectMessagesGroup,
105109
PinChatMessage,
106110
UnpinChatMessage,
107111
PinForumTopic,
@@ -110,6 +114,8 @@ class Chats(
110114
UpdateColor,
111115
EditFolder,
112116
GetDialogs,
117+
GetDirectMessagesTopicsByID,
118+
GetDirectMessagesTopics,
113119
GetChatMembersCount,
114120
SetChatUsername,
115121
SetChatPermissions,
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# Pyrogram - Telegram MTProto API Client Library for Python
2+
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
3+
#
4+
# This file is part of Pyrogram.
5+
#
6+
# Pyrogram is free software: you can redistribute it and/or modify
7+
# it under the terms of the GNU Lesser General Public License as published
8+
# by the Free Software Foundation, either version 3 of the License, or
9+
# (at your option) any later version.
10+
#
11+
# Pyrogram is distributed in the hope that it will be useful,
12+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
# GNU Lesser General Public License for more details.
15+
#
16+
# You should have received a copy of the GNU Lesser General Public License
17+
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
18+
19+
from typing import AsyncGenerator, Optional, Union
20+
21+
import pyrogram
22+
from pyrogram import raw, types, utils
23+
24+
25+
class GetDirectMessagesTopics:
26+
async def get_direct_messages_topics(
27+
self: "pyrogram.Client",
28+
chat_id: Union[int, str],
29+
limit: int = 0,
30+
exclude_pinned: Optional[bool] = None
31+
) -> AsyncGenerator["types.DirectMessagesTopic", None]:
32+
"""Get one or more topic from a direct messages channel chat.
33+
34+
.. include:: /_includes/usable-by/users.rst
35+
36+
Parameters:
37+
chat_id (``int`` | ``str``):
38+
Unique identifier (int) or username (str) of the target chat.
39+
40+
limit (``int``, *optional*):
41+
Limits the number of topics to be retrieved.
42+
By default, no limit is applied and all topics are returned.
43+
44+
exclude_pinned (``bool``, *optional*):
45+
Exclude pinned topics.
46+
47+
Returns:
48+
``Generator``: A generator yielding :obj:`~pyrogram.types.DirectMessagesTopic` objects.
49+
50+
Example:
51+
.. code-block:: python
52+
53+
# Iterate through all topics
54+
async for topic in app.get_direct_messages_topics(chat_id):
55+
print(topic)
56+
"""
57+
current = 0
58+
total = limit or (1 << 31) - 1
59+
limit = min(100, total)
60+
61+
offset_date = 0
62+
offset_id = 0
63+
offset_peer = raw.types.InputPeerEmpty()
64+
65+
while True:
66+
r = await self.invoke(
67+
raw.functions.messages.GetSavedDialogs(
68+
offset_date=offset_date,
69+
offset_id=offset_id,
70+
offset_peer=offset_peer,
71+
limit=limit,
72+
hash=0,
73+
exclude_pinned=exclude_pinned,
74+
parent_peer=await self.resolve_peer(chat_id)
75+
)
76+
)
77+
78+
users = {i.id: i for i in r.users}
79+
chats = {i.id: i for i in r.chats}
80+
81+
messages = {}
82+
83+
for message in r.messages:
84+
if isinstance(message, raw.types.MessageEmpty):
85+
continue
86+
87+
messages[message.id] = await types.Message._parse(self, message, users, chats)
88+
89+
topics = []
90+
91+
for topic in r.dialogs:
92+
topics.append(types.DirectMessagesTopic._parse(topic, messages, users, chats))
93+
94+
if not topics:
95+
return
96+
97+
last = topics[-1]
98+
99+
offset_id = last.last_message.id
100+
offset_date = utils.datetime_to_timestamp(last.last_message.date)
101+
offset_peer = await self.resolve_peer(last.id)
102+
103+
for topic in topics:
104+
yield topic
105+
106+
current += 1
107+
108+
if current >= total:
109+
return

0 commit comments

Comments
 (0)