Skip to content

Chats Service

Handling one-to-one and group chats.

teams_lib_pzsp2_z1.services.chats.ChatsService

Bases: BaseService

Service for managing Microsoft Teams chats via the Go backend.

This class acts as a high-level wrapper, delegating operations to the underlying Go library. It handles One-on-One chats, Group chats, messages, and membership management.

Concepts: * Chat Types: Chats are distinct entities, either One-on-One (between two users) or Group (multiple users, has a topic). * References: * recipient_ref / user_ref: Can be a User ID (UUID) or an Email. * group_chat_ref: Can be the Chat ID or the Group Topic (if unique). * chat_ref (Object): A specific model ChatRef containing the ID/Name and the ChatType. * Permissions: Some operations (like list_all_messages) require Application Permissions and will not work in Delegated (user context) mode.

Source code in teams_lib_pzsp2_z1/services/chats.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
class ChatsService(BaseService):
    """Service for managing Microsoft Teams chats via the Go backend.

    This class acts as a high-level wrapper, delegating operations to the
    underlying Go library. It handles One-on-One chats, Group chats, messages,
    and membership management.

    **Concepts:**
    * **Chat Types**: Chats are distinct entities, either **One-on-One** (between two users)
      or **Group** (multiple users, has a topic).
    * **References**:
        * `recipient_ref` / `user_ref`: Can be a User ID (UUID) or an Email.
        * `group_chat_ref`: Can be the Chat ID or the Group Topic (if unique).
        * `chat_ref` (Object): A specific model `ChatRef` containing the ID/Name and the `ChatType`.
    * **Permissions**: Some operations (like `list_all_messages`) require Application Permissions
      and will not work in Delegated (user context) mode.
    """

    def create_one_on_one(self, recipient_ref: str) -> Chat:
        """Creates a One-on-One chat with a specific user.

        The authenticated user is automatically added to the chat.

        Args:
            recipient_ref (str): The reference to the other user (User ID or Email).

        Returns:
            Chat: The created chat object.
        """
        response = self.client.execute(
            cmd_type="request",
            method="createOneOnOneChat",
            params={
                "recipientRef": recipient_ref,
            },
        )

        return Chat(
            id=response["ID"],
            type=ChatType(response["Type"]),
            is_hidden=(True if response["IsHidden"] else False),
            topic=response["Topic"],
        )

    def create_group_chat(
        self, recipient_refs: list[str], topic: str, include_me: bool
    ) -> Chat:
        """Creates a Group Chat with multiple participants.

        Args:
            recipient_refs (list[str]): A list of user references (IDs or Emails) to include.
            topic (str): The subject/topic of the group chat.
            include_me (bool): If True, the authenticated user is added to the group.

        Returns:
            Chat: The created group chat object.
        """
        response = self.client.execute(
            cmd_type="request",
            method="createGroupChat",
            params={
                "recipientRefs": recipient_refs,
                "topic": topic,
                "includeMe": include_me,
            },
        )

        return Chat(
            id=response["ID"],
            type=ChatType(response["Type"]),
            is_hidden=(True if response["IsHidden"] else False),
            topic=response["Topic"],
        )

    def get_chat(self, chat_ref: ChatRef) -> Chat:
        """
        Retrieves a chat by its reference.

        Args:
            chat_ref (ChatRef): The chat reference object containing the ID/Name and ChatType.

        Returns:
            Chat: The requested chat object.
        """
        response = self.client.execute(
            cmd_type="request",
            method="getChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
            },
        )

        return Chat(
            id=response["ID"],
            type=ChatType(response["Type"]),
            is_hidden=(True if response["IsHidden"] else False),
            topic=response["Topic"],
        )

    def add_member_to_group_chat(self, group_chat_ref: str, user_ref: str) -> Member:
        """Adds a user to an existing Group Chat.

        Args:
            group_chat_ref (str): The reference to the group chat (ID or Topic).
            user_ref (str): The user to add (User ID or Email).

        Returns:
            Member: The newly added member details.
        """
        member = self.client.execute(
            cmd_type="request",
            method="addMemberToGroupChat",
            params={
                "groupChatRef": group_chat_ref,
                "userRef": user_ref,
            },
        )

        return Member(
            id=member["ID"],
            display_name=member["DisplayName"],
            user_id=member["UserID"],
            role=member["Role"],
            email=member["Email"],
        )

    def remove_member_from_group_chat(
        self, group_chat_ref: str, member_ref: str
    ) -> bool:
        """Removes a member from a Group Chat.

        Args:
            group_chat_ref (str): The reference to the group chat (ID or Topic).
            member_ref (str): The user reference to remove (User ID or Email).

        Returns:
            bool: True if the member was successfully removed.
        """
        result = self.client.execute(
            cmd_type="request",
            method="removeMemberFromGroupChat",
            params={
                "groupChatRef": group_chat_ref,
                "userRef": member_ref,
            },
        )

        return result == "removed"

    def list_group_chat_members(self, group_chat_ref: str) -> list[Member]:
        """Lists all members of a Group Chat.

        Args:
            group_chat_ref (str): The reference to the group chat (ID or Topic).

        Returns:
            list[Member]: A list of members in the chat.
        """
        members = self.client.execute(
            cmd_type="request",
            method="listMembersInGroupChat",
            params={
                "groupChatRef": group_chat_ref,
            },
        )

        return [
            Member(
                id=member["ID"],
                display_name=member["DisplayName"],
                user_id=member["UserID"],
                role=member["Role"],
                email=member["Email"],
            )
            for member in members
        ]

    def update_group_chat_topic(self, group_chat_ref: str, new_topic: str) -> Chat:
        """Updates the topic of a Group Chat.

        Args:
            group_chat_ref (str): The reference to the group chat (ID or old Topic).
            new_topic (str): The new topic string.

        Returns:
            Chat: The updated chat object.
        """
        response = self.client.execute(
            cmd_type="request",
            method="updateGroupChatTopic",
            params={
                "groupChatRef": group_chat_ref,
                "topic": new_topic,
            },
        )

        return Chat(
            id=response["ID"],
            type=ChatType(response["Type"]),
            is_hidden=(True if response["IsHidden"] else False),
            topic=response["Topic"],
        )

    def list_messages(
        self,
        chat_ref: ChatRef,
        include_system_messages: bool = False,
        next_link: str | None = None,
    ) -> list[Message]:
        """Retrieves messages from a specific chat.

        Args:
            chat_ref (ChatRef): The chat reference object containing the ID/Name and ChatType.
            include_system_messages (bool): If True, includes system-generated messages. Defaults to False.
            next_link (str | None): A link for pagination to fetch the next set of messages. Defaults to None.

        Returns:
            list[Message]: A list of messages from the chat history.
        """
        messages = self.client.execute(
            cmd_type="request",
            method="listMessagesInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "includeSystem": include_system_messages,
                "nextLink": next_link,
            },
        )

        return MessageCollection(
            messages=[
                Message(
                    id=msg["ID"],
                    content=msg["Content"],
                    content_type=MessageContentType(msg["ContentType"]),
                    created_date_time=msg["CreatedDateTime"],
                    sender=MessageFrom(
                        user_id=msg["From"]["UserID"],
                        display_name=msg["From"]["DisplayName"],
                    ),
                    reply_count=msg["ReplyCount"],
                )
                for msg in messages["Messages"]
            ],
            next_link=messages.get("NextLink"),
        )

    def send_message(self, chat_ref: ChatRef, body: MessageBody) -> Message:
        """Sends a message to a chat.

        Args:
            chat_ref (ChatRef): The chat reference object.
            body (MessageBody): The message payload (content, type, mentions).

        Returns:
            Message: The created message object.
        """
        message = self.client.execute(
            cmd_type="request",
            method="sendMessageInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "body": {
                    "content": body.content,
                    "contentType": body.content_type.value,
                },
            },
        )

        return Message(
            id=message["ID"],
            content=message["Content"],
            content_type=MessageContentType(message["ContentType"]),
            sender=MessageFrom(
                user_id=message["From"]["UserID"],
                display_name=message["From"]["DisplayName"],
            ),
            created_date_time=message["CreatedDateTime"],
            reply_count=message["ReplyCount"],
        )

    def delete_message(self, chat_ref: ChatRef, message_id: str) -> bool:
        """Soft-deletes a message from a chat.

        This action is reversible via the Graph API (though not exposed here).

        Args:
            chat_ref (ChatRef): The chat reference object.
            message_id (str): The unique identifier of the message to delete.

        Returns:
            bool: True if the message was successfully deleted.
        """
        result = self.client.execute(
            cmd_type="request",
            method="deleteMessageInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "messageID": message_id,
            },
        )

        return result == "deleted"

    def get_message(self, chat_ref: ChatRef, message_id: str) -> Message:
        """Retrieves a single message by its ID.

        Args:
            chat_ref (ChatRef): The chat reference object.
            message_id (str): The unique identifier of the message.

        Returns:
            Message: The requested message object.
        """
        message = self.client.execute(
            cmd_type="request",
            method="getMessageInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "messageID": message_id,
            },
        )

        return Message(
            id=message["ID"],
            content=message["Content"],
            content_type=MessageContentType(message["ContentType"]),
            sender=MessageFrom(
                user_id=message["From"]["UserID"],
                display_name=message["From"]["DisplayName"],
            ),
            created_date_time=message["CreatedDateTime"],
            reply_count=message["ReplyCount"],
        )

    def list_my_joined(self, chat_type: ChatType | None = None) -> list[Chat]:
        """Lists all chats the authenticated user is part of.

        Args:
            chat_type (ChatType | None, optional): Filter by chat type (e.g., only OneOnOne).
                Defaults to None (return all).

        Returns:
            list[Chat]: A list of chat objects.
        """
        params = {}
        if chat_type:
            params["chatType"] = chat_type.value

        chats = self.client.execute(
            cmd_type="request",
            method="listMyChats",
            params=params,
        )

        return [
            Chat(
                id=chat["ID"],
                type=ChatType(chat["Type"]),
                is_hidden=(True if chat["IsHidden"] else False),
                topic=chat["Topic"],
            )
            for chat in chats
        ]

    def list_all_messages(
        self, start_time: datetime, end_time: datetime, top: int
    ) -> list[Message]:
        """Retrieves messages across ALL chats within a time range.

        Note:
            This operation typically requires **Application Permissions** and may not
            work with standard Delegated (User) credentials depending on the organization's policy.

        Args:
            start_time (datetime): The start of the time range.
            end_time (datetime): The end of the time range.
            top (int): Maximum number of messages to retrieve.

        Returns:
            list[Message]: A list of messages from all chats.
        """
        messages = self.client.execute(
            cmd_type="request",
            method="listMyChatMessages",
            params={
                "startTime": start_time.isoformat(),
                "endTime": end_time.isoformat(),
                "top": top,
            },
        )

        return [
            Message(
                id=message["ID"],
                content=message["Content"],
                content_type=MessageContentType(message["ContentType"]),
                sender=MessageFrom(
                    user_id=message["From"]["UserID"],
                    display_name=message["From"]["DisplayName"],
                ),
                created_date_time=message["CreatedDateTime"],
                reply_count=message["ReplyCount"],
            )
            for message in messages
        ]

    def list_pinned_messages(self, chat_ref: ChatRef) -> list[Message]:
        """Lists all pinned messages in a specific chat.

        Args:
            chat_ref (ChatRef): The chat reference object.

        Returns:
            list[Message]: A list of pinned messages.
        """
        messages = self.client.execute(
            cmd_type="request",
            method="listPinnedMessagesInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
            },
        )

        return [
            Message(
                id=message["ID"],
                content=message["Content"],
                content_type=MessageContentType(message["ContentType"]),
                sender=MessageFrom(
                    user_id=message["From"]["UserID"],
                    display_name=message["From"]["DisplayName"],
                ),
                created_date_time=message["CreatedDateTime"],
                reply_count=message["ReplyCount"],
            )
            for message in messages
        ]

    def pin_message(self, chat_ref: ChatRef, message_id: str) -> bool:
        """Pins a message in the chat.

        Args:
            chat_ref (ChatRef): The chat reference object.
            message_id (str): The ID of the message to pin.

        Returns:
            bool: True if the message was successfully pinned.
        """
        result = self.client.execute(
            cmd_type="request",
            method="pinMessageInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "messageID": message_id,
            },
        )

        return result == "pinned"

    def unpin_message(self, chat_ref: ChatRef, message_id: str) -> bool:
        """Unpins a message in the chat.

        Args:
            chat_ref (ChatRef): The chat reference object.
            message_id (str): The ID of the message to unpin.

        Returns:
            bool: True if the message was successfully unpinned.
        """
        result = self.client.execute(
            cmd_type="request",
            method="unpinMessageInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "messageID": message_id,
            },
        )

        return result == "unpinned"

    def get_mentions(self, chat_ref: ChatRef, raw_mentions: list[str]) -> list[Mention]:
        """Resolves raw mention strings into formal Mention objects.

        This helps in processing @mentions within message content before sending.

        Args:
            chat_ref (ChatRef): The chat reference object.
            raw_mentions (list[str]): A list of raw strings to resolve.
                Supported formats:
                * **Email/User ID**: Resolves to a specific user.
                * **'Everyone'**: Mentions all members (Group Chats only).

        Returns:
            list[Mention]: A list of resolved Mention objects.
        """
        mentions = self.client.execute(
            cmd_type="request",
            method="getMentionsInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "rawMentions": raw_mentions,
            },
        )

        return [
            Mention(
                kind=mention["Kind"],
                at_id=mention["AtID"],
                text=mention["Text"],
                target_id=mention["TargetID"],
            )
            for mention in mentions
        ]

    def search_messages(self, chat_ref: ChatRef, options: SearchMessagesOptions, config: SearchConfig) -> SearchResults:
        """Searches for messages in a chat based on various criteria.

        Args:
            chat_ref (ChatRef): The chat reference object.
            options (SearchMessagesOptions): The search options and filters.
            config (SearchConfig): Configuration for the search operation.

        Returns:
            SearchResults: The results of the search operation.
        """
        response = self.client.execute(
            cmd_type="request",
            method="searchMessagesInChat",
            params={
                "chatRef": {
                    "ref": chat_ref.ref,
                    "type": chat_ref.type.value,
                },
                "searchMessagesOptions": options.__dict__(),
                "searchConfig": config.__dict__(),
            },
        )

        return SearchResults(
            messages=[
                SearchResult(
                    message=Message(
                        id=msg["Message"]["ID"],
                        content=msg["Message"]["Content"],
                        content_type=MessageContentType(msg["Message"]["ContentType"]),
                        created_date_time=msg["Message"]["CreatedDateTime"],
                        sender=MessageFrom(
                            user_id=msg["Message"]["From"]["UserID"],
                            display_name=msg["Message"]["From"]["DisplayName"],
                        ),
                        reply_count=msg["Message"]["ReplyCount"],
                    ),
                    channel_id=msg.get("ChannelID"),
                    team_id=msg.get("TeamID"),
                    chat_id=msg.get("ChatID"),
                )
                for msg in response["Messages"]
            ] if response.get("Messages") else [],
            next_from=response.get("NextFrom"),
        )

Functions

add_member_to_group_chat(group_chat_ref, user_ref)

Adds a user to an existing Group Chat.

Parameters:

Name Type Description Default
group_chat_ref str

The reference to the group chat (ID or Topic).

required
user_ref str

The user to add (User ID or Email).

required

Returns:

Name Type Description
Member Member

The newly added member details.

Source code in teams_lib_pzsp2_z1/services/chats.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def add_member_to_group_chat(self, group_chat_ref: str, user_ref: str) -> Member:
    """Adds a user to an existing Group Chat.

    Args:
        group_chat_ref (str): The reference to the group chat (ID or Topic).
        user_ref (str): The user to add (User ID or Email).

    Returns:
        Member: The newly added member details.
    """
    member = self.client.execute(
        cmd_type="request",
        method="addMemberToGroupChat",
        params={
            "groupChatRef": group_chat_ref,
            "userRef": user_ref,
        },
    )

    return Member(
        id=member["ID"],
        display_name=member["DisplayName"],
        user_id=member["UserID"],
        role=member["Role"],
        email=member["Email"],
    )

create_group_chat(recipient_refs, topic, include_me)

Creates a Group Chat with multiple participants.

Parameters:

Name Type Description Default
recipient_refs list[str]

A list of user references (IDs or Emails) to include.

required
topic str

The subject/topic of the group chat.

required
include_me bool

If True, the authenticated user is added to the group.

required

Returns:

Name Type Description
Chat Chat

The created group chat object.

Source code in teams_lib_pzsp2_z1/services/chats.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def create_group_chat(
    self, recipient_refs: list[str], topic: str, include_me: bool
) -> Chat:
    """Creates a Group Chat with multiple participants.

    Args:
        recipient_refs (list[str]): A list of user references (IDs or Emails) to include.
        topic (str): The subject/topic of the group chat.
        include_me (bool): If True, the authenticated user is added to the group.

    Returns:
        Chat: The created group chat object.
    """
    response = self.client.execute(
        cmd_type="request",
        method="createGroupChat",
        params={
            "recipientRefs": recipient_refs,
            "topic": topic,
            "includeMe": include_me,
        },
    )

    return Chat(
        id=response["ID"],
        type=ChatType(response["Type"]),
        is_hidden=(True if response["IsHidden"] else False),
        topic=response["Topic"],
    )

create_one_on_one(recipient_ref)

Creates a One-on-One chat with a specific user.

The authenticated user is automatically added to the chat.

Parameters:

Name Type Description Default
recipient_ref str

The reference to the other user (User ID or Email).

required

Returns:

Name Type Description
Chat Chat

The created chat object.

Source code in teams_lib_pzsp2_z1/services/chats.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def create_one_on_one(self, recipient_ref: str) -> Chat:
    """Creates a One-on-One chat with a specific user.

    The authenticated user is automatically added to the chat.

    Args:
        recipient_ref (str): The reference to the other user (User ID or Email).

    Returns:
        Chat: The created chat object.
    """
    response = self.client.execute(
        cmd_type="request",
        method="createOneOnOneChat",
        params={
            "recipientRef": recipient_ref,
        },
    )

    return Chat(
        id=response["ID"],
        type=ChatType(response["Type"]),
        is_hidden=(True if response["IsHidden"] else False),
        topic=response["Topic"],
    )

delete_message(chat_ref, message_id)

Soft-deletes a message from a chat.

This action is reversible via the Graph API (though not exposed here).

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
message_id str

The unique identifier of the message to delete.

required

Returns:

Name Type Description
bool bool

True if the message was successfully deleted.

Source code in teams_lib_pzsp2_z1/services/chats.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def delete_message(self, chat_ref: ChatRef, message_id: str) -> bool:
    """Soft-deletes a message from a chat.

    This action is reversible via the Graph API (though not exposed here).

    Args:
        chat_ref (ChatRef): The chat reference object.
        message_id (str): The unique identifier of the message to delete.

    Returns:
        bool: True if the message was successfully deleted.
    """
    result = self.client.execute(
        cmd_type="request",
        method="deleteMessageInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "messageID": message_id,
        },
    )

    return result == "deleted"

get_chat(chat_ref)

Retrieves a chat by its reference.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object containing the ID/Name and ChatType.

required

Returns:

Name Type Description
Chat Chat

The requested chat object.

Source code in teams_lib_pzsp2_z1/services/chats.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def get_chat(self, chat_ref: ChatRef) -> Chat:
    """
    Retrieves a chat by its reference.

    Args:
        chat_ref (ChatRef): The chat reference object containing the ID/Name and ChatType.

    Returns:
        Chat: The requested chat object.
    """
    response = self.client.execute(
        cmd_type="request",
        method="getChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
        },
    )

    return Chat(
        id=response["ID"],
        type=ChatType(response["Type"]),
        is_hidden=(True if response["IsHidden"] else False),
        topic=response["Topic"],
    )

get_mentions(chat_ref, raw_mentions)

Resolves raw mention strings into formal Mention objects.

This helps in processing @mentions within message content before sending.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
raw_mentions list[str]

A list of raw strings to resolve. Supported formats: * Email/User ID: Resolves to a specific user. * 'Everyone': Mentions all members (Group Chats only).

required

Returns:

Type Description
list[Mention]

list[Mention]: A list of resolved Mention objects.

Source code in teams_lib_pzsp2_z1/services/chats.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def get_mentions(self, chat_ref: ChatRef, raw_mentions: list[str]) -> list[Mention]:
    """Resolves raw mention strings into formal Mention objects.

    This helps in processing @mentions within message content before sending.

    Args:
        chat_ref (ChatRef): The chat reference object.
        raw_mentions (list[str]): A list of raw strings to resolve.
            Supported formats:
            * **Email/User ID**: Resolves to a specific user.
            * **'Everyone'**: Mentions all members (Group Chats only).

    Returns:
        list[Mention]: A list of resolved Mention objects.
    """
    mentions = self.client.execute(
        cmd_type="request",
        method="getMentionsInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "rawMentions": raw_mentions,
        },
    )

    return [
        Mention(
            kind=mention["Kind"],
            at_id=mention["AtID"],
            text=mention["Text"],
            target_id=mention["TargetID"],
        )
        for mention in mentions
    ]

get_message(chat_ref, message_id)

Retrieves a single message by its ID.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
message_id str

The unique identifier of the message.

required

Returns:

Name Type Description
Message Message

The requested message object.

Source code in teams_lib_pzsp2_z1/services/chats.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def get_message(self, chat_ref: ChatRef, message_id: str) -> Message:
    """Retrieves a single message by its ID.

    Args:
        chat_ref (ChatRef): The chat reference object.
        message_id (str): The unique identifier of the message.

    Returns:
        Message: The requested message object.
    """
    message = self.client.execute(
        cmd_type="request",
        method="getMessageInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "messageID": message_id,
        },
    )

    return Message(
        id=message["ID"],
        content=message["Content"],
        content_type=MessageContentType(message["ContentType"]),
        sender=MessageFrom(
            user_id=message["From"]["UserID"],
            display_name=message["From"]["DisplayName"],
        ),
        created_date_time=message["CreatedDateTime"],
        reply_count=message["ReplyCount"],
    )

list_all_messages(start_time, end_time, top)

Retrieves messages across ALL chats within a time range.

Note

This operation typically requires Application Permissions and may not work with standard Delegated (User) credentials depending on the organization's policy.

Parameters:

Name Type Description Default
start_time datetime

The start of the time range.

required
end_time datetime

The end of the time range.

required
top int

Maximum number of messages to retrieve.

required

Returns:

Type Description
list[Message]

list[Message]: A list of messages from all chats.

Source code in teams_lib_pzsp2_z1/services/chats.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def list_all_messages(
    self, start_time: datetime, end_time: datetime, top: int
) -> list[Message]:
    """Retrieves messages across ALL chats within a time range.

    Note:
        This operation typically requires **Application Permissions** and may not
        work with standard Delegated (User) credentials depending on the organization's policy.

    Args:
        start_time (datetime): The start of the time range.
        end_time (datetime): The end of the time range.
        top (int): Maximum number of messages to retrieve.

    Returns:
        list[Message]: A list of messages from all chats.
    """
    messages = self.client.execute(
        cmd_type="request",
        method="listMyChatMessages",
        params={
            "startTime": start_time.isoformat(),
            "endTime": end_time.isoformat(),
            "top": top,
        },
    )

    return [
        Message(
            id=message["ID"],
            content=message["Content"],
            content_type=MessageContentType(message["ContentType"]),
            sender=MessageFrom(
                user_id=message["From"]["UserID"],
                display_name=message["From"]["DisplayName"],
            ),
            created_date_time=message["CreatedDateTime"],
            reply_count=message["ReplyCount"],
        )
        for message in messages
    ]

list_group_chat_members(group_chat_ref)

Lists all members of a Group Chat.

Parameters:

Name Type Description Default
group_chat_ref str

The reference to the group chat (ID or Topic).

required

Returns:

Type Description
list[Member]

list[Member]: A list of members in the chat.

Source code in teams_lib_pzsp2_z1/services/chats.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def list_group_chat_members(self, group_chat_ref: str) -> list[Member]:
    """Lists all members of a Group Chat.

    Args:
        group_chat_ref (str): The reference to the group chat (ID or Topic).

    Returns:
        list[Member]: A list of members in the chat.
    """
    members = self.client.execute(
        cmd_type="request",
        method="listMembersInGroupChat",
        params={
            "groupChatRef": group_chat_ref,
        },
    )

    return [
        Member(
            id=member["ID"],
            display_name=member["DisplayName"],
            user_id=member["UserID"],
            role=member["Role"],
            email=member["Email"],
        )
        for member in members
    ]

list_messages(chat_ref, include_system_messages=False, next_link=None)

Retrieves messages from a specific chat.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object containing the ID/Name and ChatType.

required
include_system_messages bool

If True, includes system-generated messages. Defaults to False.

False
next_link str | None

A link for pagination to fetch the next set of messages. Defaults to None.

None

Returns:

Type Description
list[Message]

list[Message]: A list of messages from the chat history.

Source code in teams_lib_pzsp2_z1/services/chats.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def list_messages(
    self,
    chat_ref: ChatRef,
    include_system_messages: bool = False,
    next_link: str | None = None,
) -> list[Message]:
    """Retrieves messages from a specific chat.

    Args:
        chat_ref (ChatRef): The chat reference object containing the ID/Name and ChatType.
        include_system_messages (bool): If True, includes system-generated messages. Defaults to False.
        next_link (str | None): A link for pagination to fetch the next set of messages. Defaults to None.

    Returns:
        list[Message]: A list of messages from the chat history.
    """
    messages = self.client.execute(
        cmd_type="request",
        method="listMessagesInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "includeSystem": include_system_messages,
            "nextLink": next_link,
        },
    )

    return MessageCollection(
        messages=[
            Message(
                id=msg["ID"],
                content=msg["Content"],
                content_type=MessageContentType(msg["ContentType"]),
                created_date_time=msg["CreatedDateTime"],
                sender=MessageFrom(
                    user_id=msg["From"]["UserID"],
                    display_name=msg["From"]["DisplayName"],
                ),
                reply_count=msg["ReplyCount"],
            )
            for msg in messages["Messages"]
        ],
        next_link=messages.get("NextLink"),
    )

list_my_joined(chat_type=None)

Lists all chats the authenticated user is part of.

Parameters:

Name Type Description Default
chat_type ChatType | None

Filter by chat type (e.g., only OneOnOne). Defaults to None (return all).

None

Returns:

Type Description
list[Chat]

list[Chat]: A list of chat objects.

Source code in teams_lib_pzsp2_z1/services/chats.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def list_my_joined(self, chat_type: ChatType | None = None) -> list[Chat]:
    """Lists all chats the authenticated user is part of.

    Args:
        chat_type (ChatType | None, optional): Filter by chat type (e.g., only OneOnOne).
            Defaults to None (return all).

    Returns:
        list[Chat]: A list of chat objects.
    """
    params = {}
    if chat_type:
        params["chatType"] = chat_type.value

    chats = self.client.execute(
        cmd_type="request",
        method="listMyChats",
        params=params,
    )

    return [
        Chat(
            id=chat["ID"],
            type=ChatType(chat["Type"]),
            is_hidden=(True if chat["IsHidden"] else False),
            topic=chat["Topic"],
        )
        for chat in chats
    ]

list_pinned_messages(chat_ref)

Lists all pinned messages in a specific chat.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required

Returns:

Type Description
list[Message]

list[Message]: A list of pinned messages.

Source code in teams_lib_pzsp2_z1/services/chats.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def list_pinned_messages(self, chat_ref: ChatRef) -> list[Message]:
    """Lists all pinned messages in a specific chat.

    Args:
        chat_ref (ChatRef): The chat reference object.

    Returns:
        list[Message]: A list of pinned messages.
    """
    messages = self.client.execute(
        cmd_type="request",
        method="listPinnedMessagesInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
        },
    )

    return [
        Message(
            id=message["ID"],
            content=message["Content"],
            content_type=MessageContentType(message["ContentType"]),
            sender=MessageFrom(
                user_id=message["From"]["UserID"],
                display_name=message["From"]["DisplayName"],
            ),
            created_date_time=message["CreatedDateTime"],
            reply_count=message["ReplyCount"],
        )
        for message in messages
    ]

pin_message(chat_ref, message_id)

Pins a message in the chat.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
message_id str

The ID of the message to pin.

required

Returns:

Name Type Description
bool bool

True if the message was successfully pinned.

Source code in teams_lib_pzsp2_z1/services/chats.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def pin_message(self, chat_ref: ChatRef, message_id: str) -> bool:
    """Pins a message in the chat.

    Args:
        chat_ref (ChatRef): The chat reference object.
        message_id (str): The ID of the message to pin.

    Returns:
        bool: True if the message was successfully pinned.
    """
    result = self.client.execute(
        cmd_type="request",
        method="pinMessageInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "messageID": message_id,
        },
    )

    return result == "pinned"

remove_member_from_group_chat(group_chat_ref, member_ref)

Removes a member from a Group Chat.

Parameters:

Name Type Description Default
group_chat_ref str

The reference to the group chat (ID or Topic).

required
member_ref str

The user reference to remove (User ID or Email).

required

Returns:

Name Type Description
bool bool

True if the member was successfully removed.

Source code in teams_lib_pzsp2_z1/services/chats.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def remove_member_from_group_chat(
    self, group_chat_ref: str, member_ref: str
) -> bool:
    """Removes a member from a Group Chat.

    Args:
        group_chat_ref (str): The reference to the group chat (ID or Topic).
        member_ref (str): The user reference to remove (User ID or Email).

    Returns:
        bool: True if the member was successfully removed.
    """
    result = self.client.execute(
        cmd_type="request",
        method="removeMemberFromGroupChat",
        params={
            "groupChatRef": group_chat_ref,
            "userRef": member_ref,
        },
    )

    return result == "removed"

search_messages(chat_ref, options, config)

Searches for messages in a chat based on various criteria.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
options SearchMessagesOptions

The search options and filters.

required
config SearchConfig

Configuration for the search operation.

required

Returns:

Name Type Description
SearchResults SearchResults

The results of the search operation.

Source code in teams_lib_pzsp2_z1/services/chats.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def search_messages(self, chat_ref: ChatRef, options: SearchMessagesOptions, config: SearchConfig) -> SearchResults:
    """Searches for messages in a chat based on various criteria.

    Args:
        chat_ref (ChatRef): The chat reference object.
        options (SearchMessagesOptions): The search options and filters.
        config (SearchConfig): Configuration for the search operation.

    Returns:
        SearchResults: The results of the search operation.
    """
    response = self.client.execute(
        cmd_type="request",
        method="searchMessagesInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "searchMessagesOptions": options.__dict__(),
            "searchConfig": config.__dict__(),
        },
    )

    return SearchResults(
        messages=[
            SearchResult(
                message=Message(
                    id=msg["Message"]["ID"],
                    content=msg["Message"]["Content"],
                    content_type=MessageContentType(msg["Message"]["ContentType"]),
                    created_date_time=msg["Message"]["CreatedDateTime"],
                    sender=MessageFrom(
                        user_id=msg["Message"]["From"]["UserID"],
                        display_name=msg["Message"]["From"]["DisplayName"],
                    ),
                    reply_count=msg["Message"]["ReplyCount"],
                ),
                channel_id=msg.get("ChannelID"),
                team_id=msg.get("TeamID"),
                chat_id=msg.get("ChatID"),
            )
            for msg in response["Messages"]
        ] if response.get("Messages") else [],
        next_from=response.get("NextFrom"),
    )

send_message(chat_ref, body)

Sends a message to a chat.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
body MessageBody

The message payload (content, type, mentions).

required

Returns:

Name Type Description
Message Message

The created message object.

Source code in teams_lib_pzsp2_z1/services/chats.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def send_message(self, chat_ref: ChatRef, body: MessageBody) -> Message:
    """Sends a message to a chat.

    Args:
        chat_ref (ChatRef): The chat reference object.
        body (MessageBody): The message payload (content, type, mentions).

    Returns:
        Message: The created message object.
    """
    message = self.client.execute(
        cmd_type="request",
        method="sendMessageInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "body": {
                "content": body.content,
                "contentType": body.content_type.value,
            },
        },
    )

    return Message(
        id=message["ID"],
        content=message["Content"],
        content_type=MessageContentType(message["ContentType"]),
        sender=MessageFrom(
            user_id=message["From"]["UserID"],
            display_name=message["From"]["DisplayName"],
        ),
        created_date_time=message["CreatedDateTime"],
        reply_count=message["ReplyCount"],
    )

unpin_message(chat_ref, message_id)

Unpins a message in the chat.

Parameters:

Name Type Description Default
chat_ref ChatRef

The chat reference object.

required
message_id str

The ID of the message to unpin.

required

Returns:

Name Type Description
bool bool

True if the message was successfully unpinned.

Source code in teams_lib_pzsp2_z1/services/chats.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def unpin_message(self, chat_ref: ChatRef, message_id: str) -> bool:
    """Unpins a message in the chat.

    Args:
        chat_ref (ChatRef): The chat reference object.
        message_id (str): The ID of the message to unpin.

    Returns:
        bool: True if the message was successfully unpinned.
    """
    result = self.client.execute(
        cmd_type="request",
        method="unpinMessageInChat",
        params={
            "chatRef": {
                "ref": chat_ref.ref,
                "type": chat_ref.type.value,
            },
            "messageID": message_id,
        },
    )

    return result == "unpinned"

update_group_chat_topic(group_chat_ref, new_topic)

Updates the topic of a Group Chat.

Parameters:

Name Type Description Default
group_chat_ref str

The reference to the group chat (ID or old Topic).

required
new_topic str

The new topic string.

required

Returns:

Name Type Description
Chat Chat

The updated chat object.

Source code in teams_lib_pzsp2_z1/services/chats.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def update_group_chat_topic(self, group_chat_ref: str, new_topic: str) -> Chat:
    """Updates the topic of a Group Chat.

    Args:
        group_chat_ref (str): The reference to the group chat (ID or old Topic).
        new_topic (str): The new topic string.

    Returns:
        Chat: The updated chat object.
    """
    response = self.client.execute(
        cmd_type="request",
        method="updateGroupChatTopic",
        params={
            "groupChatRef": group_chat_ref,
            "topic": new_topic,
        },
    )

    return Chat(
        id=response["ID"],
        type=ChatType(response["Type"]),
        is_hidden=(True if response["IsHidden"] else False),
        topic=response["Topic"],
    )