-
Notifications
You must be signed in to change notification settings - Fork 214
/
Teams.ps1
1508 lines (1272 loc) · 52.2 KB
/
Teams.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file contains functions for Teams
# Gets a skype token using Teams accesstoken
# Oct 3rd 2020
function Get-SkypeToken
{
<#
.SYNOPSIS
Gets SkypeToken.
.DESCRIPTION
Gets SkypeToken.
.Parameter AccessToken
The access token used to get the token
.EXAMPLE
PS\:>Get-AADIntAccessTokenForTeams -SaveToCache
PS\:>$skypeToken = Get-AADIntSkypeToken
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
$response = Get-TeamsUserSettings -AccessToken $AccessToken
$response.tokens.SkypeToken
}
}
# Sets user's availability status
# Oct 3rd 2020
function Set-TeamsAvailability
{
<#
.SYNOPSIS
Sets the availability status of the user.
.DESCRIPTION
Sets the availability status of the user.
.Parameter AccessToken
The access token used to set the availability
.Parameter Status
The status, one of Available, Busy, DoNotDisturb, BeRightBack, or Away
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS\:>Set-AADIntTeamsAvailability -Status Busy
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet("Available","Busy","DoNotDisturb","BeRightBack","Away")]
[String]$Status="Available"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
$body="{""availability"":""$Status""}"
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
}
Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://presence.teams.microsoft.com/v1/me/forceavailability/" -Headers $headers -Body $body -ContentType "application/json"
}
}
# Sets user's Teams statusmessage
# Oct 3rd 2020
function Set-TeamsStatusMessage
{
<#
.SYNOPSIS
Sets the Teams status message status of the user.
.DESCRIPTION
Sets the Teams status message status of the user.
.Parameter AccessToken
The access token used to set the status message
.Parameter Message
The status message
.Parameter Expires
Expiration time of the message
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS\:>Set-AADIntTeamsStatusMessage -Message "Out of office til noon"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$Message,
[Parameter(Mandatory=$False)]
[DateTime]$Expires
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
if($Expires)
{
$expiry = $Expires.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z"
}
else
{
$expiry = "9999-12-31T08:00:00.000Z"
}
$body=[ordered]@{
"message" = $Message
"expiry" = $expiry
}
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
}
Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://presence.teams.microsoft.com/v1/me/publishnote" -Headers $headers -Body ($body | ConvertTo-Json -Compress) -ContentType "application/json;charset=utf-8"
}
}
# Searches a teams user
# Oct 3rd 2020
function Search-TeamsUser
{
<#
.SYNOPSIS
Searhes users with the given searchstring.
.DESCRIPTION
Searhes users with the given searchstring.
.Parameter AccessToken
The access token used to perform the search
.Parameter SearchString
Search string.
.EXAMPLE
Get-AADIntAccessTokenForTeams -Resource https://outlook.com -SaveToCache
PS C:\>Search-AADIntTeamsUser -SearchString "user" | Format-Table UserPrincipalName,DisplayName
UserPrincipalName DisplayName
----------------- -----------
first.user@company.com First User
second.user@company.com Second User
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$SearchString
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
$body=@"
{
"EntityRequests": [{
"Query": {
"QueryString": "$SearchString",
"DisplayQueryString": ""
},
"EntityType": "People",
"Provenances": ["Mailbox", "Directory"],
"From": 0,
"Size": 500,
"Fields": ["Id", "DisplayName", "EmailAddresses", "CompanyName", "JobTitle", "ImAddress", "UserPrincipalName", "ExternalDirectoryObjectId", "PeopleType", "PeopleSubtype", "ConcatenatedId", "Phones", "MRI"],
}
],
"Cvid": "$((New-Guid).ToString())",
"AppName": "Microsoft Teams",
"Scenario": {
"Name": "staticbrowse"
}
}
"@
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
}
$response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://substrate.office.com/search/api/v1/suggestions" -Headers $headers -Body $body -ContentType "application/json"
$response.Groups.Suggestions
}
}
# Sends a message using teams
# Oct 16th 2020
function Send-TeamsMessage
{
<#
.SYNOPSIS
Sends a Teams message to given recipients..
.DESCRIPTION
Sends a Teams message to given recipients.
.Parameter AccessToken
The access token used to send the message.
.Parameter Recipients
Email addresses of the recipients
.Parameter Message
Message to be sent. If in html, use -Html switch
.Parameter ClientMessageId
The client message id of the message. If exists, the content is replaced with the given message.
.Parameter Thread
The conversation thread of existing chat or channel.
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS C:\>Send-AADIntTeamsMessage -Recipients user@company.com -Message "Hi user!"
Sent ClientMessageID
---- ---------
16/10/2020 14.40.23 132473328207053858
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS C:\>Get-AADIntTeamsMessages | Select Link
Link
----
19:a84fdc0c-519c-4467-b2e6-323a48ce09af_4d40755a-020b-422b-b9cf-2f1f50602377@unq.gbl.spaces
19:a84fdc0c-519c-4467-b2e6-323a48ce09af_4d40755a-020b-422b-b9cf-2f1f50602377@unq.gbl.spaces
19:292f1d53677d45ff9d61d333cb0b4853@thread.tacv2
19:292f1d53677d45ff9d61d333cb0b4853@thread.tacv2
19:292f1d53677d45ff9d61d333cb0b4853@thread.tacv2
PS C:\>Send-AADIntTeamsMessage -Thread 19:292f1d53677d45ff9d61d333cb0b4853@thread.tacv2 -Message "Hi there!"
Sent ClientMessageID
---- ---------
16/10/2020 14.40.23 132473328207053858
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName = "New", Mandatory=$True)]
[String[]]$Recipients,
[Parameter(Mandatory=$True)]
[String]$Message,
[switch]$Html,
[Parameter(ParameterSetName = "Existing", Mandatory=$True)]
[String]$ClientMessageId,
[Parameter(ParameterSetName = "Thread", Mandatory=$True)]
[String]$Thread,
[bool]$External = $false,
[bool]$FakeInternal = $false
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
if($Html)
{
$messagetype = "RichText/Html"
$contenttype = "text"
}
else
{
$messagetype = "Text"
$contenttype = "text"
}
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$chatService = $teamsSettings.regionGtms.chatService
$apiUrl = $teamsSettings.regionGtms.middleTier
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"Authentication" = "skypetoken=$skypeToken"
"x-ms-client-version" = "27/1.0.0.2020101241"
}
# Parse AccessToken to get sender details
$parsedToken = Read-Accesstoken $AccessToken
# If the client message is given, find the message and corresponding id
if($ClientMessageId)
{
$response = Get-TeamsMessage -AccessToken $AccessToken -ClientMessageId $ClientMessageId
if(!$response)
{
throw "Message ($ClientMessageId) not found! Check the ClientMessageId and try again."
}
$thread = $response.Link
}
elseif($Thread) # Thread is given, so post message to there
{
$ClientMessageId=(Get-Date).ToFileTimeUtc()
}
else # A new message
{
$ClientMessageId=(Get-Date).ToFileTimeUtc()
$msgRecipients = @()
if($External)
{
foreach($recipient in $Recipients)
{
try
{
if(![string]::IsNullOrEmpty($recipient))
{
$msgRecipients += Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://teams.microsoft.com/api/mt/part/emea-02/beta/users/$recipient/externalsearchv3" -Headers $headers }
}
catch
{
# Okay, federation doesn't exists etc.
}
}
}
else
{
$msgRecipients = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $Recipients
}
if(!$msgRecipients.Count)
{
# Just one found so create an array
$newRecipients = @($msgRecipients)
Remove-Variable "msgRecipients"
$msgRecipients = $newRecipients
}
elseif($msgRecipients.Count -lt 1)
{
Throw "Recipient not found"
}
# Get a new thread for the conversation
$members=@(
@{
"id" = "8:orgid:$($parsedToken.oid)"
"role" = "Admin"
}
)
foreach($recipient in $msgRecipients)
{
$members += @{
"id" = $recipient.mri
"role" = "Admin"
}
}
if($External -and !$FakeInternal)
{
$threadBody = @{
"members" = $members
"properties" = @{
"threadType" = "sfbinteropchat"
"chatFilesIndexId" = "2"
"isFederated" = "true"
"uniquerosterthread" = ($members.Count -eq 2).ToString().ToLower()
"fixedRoster" = "true"
}
}
}
else
{
$threadBody = @{
"members" = $members
"properties" = @{
"threadType" = "chat"
"chatFilesIndexId" = "2"
"uniquerosterthread" = ($members.Count -eq 2).ToString().ToLower()
"fixedRoster" = "true"
}
}
}
$threadResponse = Invoke-WebRequest2 -Method Post -Uri "$chatService/v1/threads" -Headers $headers -Body ($threadBody | ConvertTo-Json) -ContentType "application/json" -MaximumRedirection 0
$threadUrl = $threadResponse.Headers["location"]
$thread = $threadUrl.Substring($threadUrl.LastIndexOf("/")+1)
}
# Links
$links=@()
# Check if we have any links
if($Html -and $Message.IndexOf("href") -gt -1)
{
# Try to convert to xml for parsing..
try
{
[xml]$xmlHtml = $Message
$messageLinks = Select-Xml -Xml $xmlHtml -XPath "//a"
for($a = 0; $a -lt $messageLinks.Count ; $a++)
{
$linkUrl = $messageLinks[$a].Node.href
$links += @{
"@type" = "http://schema.skype.com/HyperLink"
"itemid"= $a
"url"= $linkUrl
"previewenabled" = "false"
"preview" = @{
"previewurl" = ""
"previewmeta" = ""
"title" = ""
"description" = ""
"isLinkUnsafe" = "false"
}
}
}
}
catch
{
Write-Warning "The message contains link(s), but it was not well-formed html. Check the syntax of the message!"
}
}
# Send the message
$messageBody=@{
"content" = $Message
"messagetype"= $messagetype
"contenttype"= $contenttype
"amsreferences" = @()
"clientmessageid" = $ClientMessageId
"imdisplayname" = $parsedToken.name
"properties" = @{
"importance" = "";
"subject"= $null;
"links" = $links
}
}
if($External -and !$FakeInternal)
{
$messageBody["properties"]["interopType"]="receiverSfB"
$messageBody["fromSipUri"] = $parsedToken.upn
$messageBody["toSipUri"] = $msgRecipients | Select-Object -ExpandProperty email
}
if($FakeInternal)
{
# Fake internal by removing the "fed." from the thread
# This allows sending rich text to external users too.
$Thread = $Thread.Replace("@fed.","@")
}
$response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$chatService/v1/users/ME/conversations/$thread/messages" -Headers $headers -Body ($messageBody | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
$posted=$epoch.AddMilliseconds($response.OriginalArrivalTime)
return New-Object psobject -Property @{"ClientMessageID" = $ClientMessageId; "Sent" = $posted}
}
}
# Get the latest Teams messages
# Oct 16th 2020
function Get-TeamsMessages
{
<#
.SYNOPSIS
Gets user's latest Teams messages.
.DESCRIPTION
Gets user's latest Teams messages.
.Parameter AccessToken
The access token used to get the messages
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName
Id Content DeletionTime MessageType Type DisplayName
-- ------- ------------ ----------- ---- -----------
1602842299338 1602846853687 RichText/Html MessageUpdate Bad User
1602844861358 1602858789696 RichText/Html MessageUpdate Bad User
1602846167606 1602858792943 Text MessageUpdate Bad User
1602846853687 1602858795517 Text MessageUpdate Bad User
1602833251951 1602833251951 Text MessageUpdate Bad User
1602833198442 1602833198442 Text MessageUpdate Bad User
1602859223294 Hola User! Text NewMessage Bad User
1602859423019 Hi User! Text NewMessage Bad User
1602859423019 Hi User! Text MessageUpdate Bad User
1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User
1602859484420 Hey User! Text NewMessage Bad User
1602859528028 Hy User! Text NewMessage Bad User
1602859484420 Hey User! Text MessageUpdate Bad User
1602859590916 Hi User! Text NewMessage Bad User
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Endpoint
$endPoint = (New-Guid).ToString()
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$chatService = $teamsSettings.regionGtms.chatService
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"Authentication" = "skypetoken=$skypeToken"
}
$conversations = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations" -Headers $headers
foreach($conversation in $conversations.conversations)
{
$id = $conversation.id
try
{
if($id.startsWith("19:"))
{
$chatMessages = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations/$id/messages?startTime=0&view=msnp24Equivalent" -Headers $headers
}
foreach($message in $chatMessages.messages)
{
if($message.type -like "*Message*" -and $message.contenttype -eq "text")
{
$attributes = [ordered]@{
"ClientMessageId" = $message.clientmessageid
"Id" = $message.id
"MessageType" = $message.messageType
"DisplayName" = $message.imdisplayname
"ArrivalTime" = $message.originalarrivaltime
"DeletionTime" = $message.properties.deletetime
"Link" = $message.conversationid
"Content" = $message.content
"Type" = $message.type
}
New-Object psobject -Property $attributes
}
}
}
catch
{
Write-Verbose "$(($_.ErrorDetails.Message | ConvertFrom-Json).message)"
}
}
}
}
# Deletes Teams messages
# Oct 16th 2020
function Remove-TeamsMessages
{
<#
.SYNOPSIS
Deletes given Teams messages.
.DESCRIPTION
Deletes given Teams messages.
.Parameter AccessToken
The access token used to get the messages
.Parameter MessageIDs
List of IDs of the messages to be deleted
.Parameter DeleteType
Deletion type, can be either SoftDelete or HardDelete. Defaults to HardDelete. Soft deleted messages can be restored from the UI.
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName
Id Content DeletionTime MessageType Type DisplayName
-- ------- ------------ ----------- ---- -----------
1602842299338 1602846853687 RichText/Html MessageUpdate Bad User
1602844861358 1602858789696 RichText/Html MessageUpdate Bad User
1602846167606 1602858792943 Text MessageUpdate Bad User
1602846853687 1602858795517 Text MessageUpdate Bad User
1602833251951 1602833251951 Text MessageUpdate Bad User
1602833198442 1602833198442 Text MessageUpdate Bad User
1602859223294 Hola User! Text NewMessage Bad User
1602859423019 Hi User! Text NewMessage Bad User
1602859423019 Hi User! Text MessageUpdate Bad User
1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User
1602859484420 Hey User! Text NewMessage Bad User
1602859528028 Hy User! Text NewMessage Bad User
1602859484420 Hey User! Text MessageUpdate Bad User
1602859590916 Hi User! Text NewMessage Bad User
PS C:\>Remove-AADIntTeamsMessages -MessageIDs 1602859590916,1602859484420
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String[]]$MessageIDs,
[Parameter(Mandatory=$False)]
[ValidateSet("HardDelete","SoftDelete")]
[String]$DeleteType="HardDelete"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$chatService = $teamsSettings.regionGtms.chatService
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"Authentication" = "skypetoken=$skypeToken"
}
# Get the latest messages
$messages = Get-TeamsMessages -AccessToken $AccessToken
# Loop through the messages and delete when the correct ones if found
foreach($message in $messages)
{
if($MessageIDs -contains $message.Id)
{
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Delete -Uri "$chatService/v1/users/ME/conversations/$($message.Link)/messages/$($message.Id)`?behavior=$DeleteType" -Headers $headers -ErrorAction SilentlyContinue
}
catch{
Write-Warning "MessageId $($message.Id):`n$(($_.ErrorDetails.Message | ConvertFrom-Json).message)"
}
}
}
}
}
# Sets the emotion for the given message
# Oct 26th 2020
function Set-TeamsMessageEmotion
{
<#
.SYNOPSIS
Sets emotion for the given Teams message.
.DESCRIPTION
Sets emotion for the given Teams message.
.Parameter AccessToken
The access token used to get the messages
.Parameter MessageID
The id of the message
.Parameter ConversationID
The id of the message conversation
.Parameter Clear
Clear the given emotion.
.Parameter Emotion
The emotion to be added. One of like, heart, laugh, surprised, sad, or angry
.EXAMPLE
Get-AADIntAccessTokenForTeams -SaveToCache
PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName
Id Content DeletionTime MessageType Type DisplayName
-- ------- ------------ ----------- ---- -----------
1602842299338 1602846853687 RichText/Html MessageUpdate Bad User
1602844861358 1602858789696 RichText/Html MessageUpdate Bad User
1602846167606 1602858792943 Text MessageUpdate Bad User
1602846853687 1602858795517 Text MessageUpdate Bad User
1602833251951 1602833251951 Text MessageUpdate Bad User
1602833198442 1602833198442 Text MessageUpdate Bad User
1602859223294 Hola User! Text NewMessage Bad User
1602859423019 Hi User! Text NewMessage Bad User
1602859423019 Hi User! Text MessageUpdate Bad User
1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User
1602859484420 Hey User! Text NewMessage Bad User
1602859528028 Hy User! Text NewMessage Bad User
1602859484420 Hey User! Text MessageUpdate Bad User
1602859590916 Hi User! Text NewMessage Bad User
PS C:\>Set-AADIntTeamsMessageEmotion -MessageID 1602859223294 -Emotion like
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$MessageID,
[Parameter(Mandatory=$False)]
[String]$ConversationID,
[Parameter(Mandatory=$False)]
[psobject]$TeamsSettings,
[Parameter(Mandatory=$True)]
[ValidateSet("like","heart","laugh","surprised","sad","angry")]
[String]$Emotion,
[switch]$Clear
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Get the settings
if(!$TeamsSettings)
{
$TeamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
}
$chatService = $TeamsSettings.regionGtms.chatService
$skypeToken = $TeamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"Authentication" = "skypetoken=$skypeToken"
}
# If conversation id not given, try to find one
if([String]::IsNullOrEmpty($ConversationID))
{
$conversations = Invoke-RestMethod -Method Get -Uri "$chatService/v1/users/ME/conversations" -Headers $headers
foreach($conversation in $conversations.conversations)
{
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations/$($conversation.id)/messages/$MessageID" -Headers $headers -ErrorAction SilentlyContinue
$ConversationID = $conversation.id
break
}
catch{
# Okay, not a correct conversation
}
}
}
try
{
if($Clear)
{
$headers["x-ms-client-caller"] = "updateMessageReactionRemove"
$body = "{""emotions"":""{\""key\"":\""$Emotion\""}""}"
$method = "Delete"
}
else
{
$headers["x-ms-client-caller"] = "updateMessageReactionAdd"
$body = "{""emotions"":""{\""key\"":\""$Emotion\"",\""value\"":$([long]((Get-Date)-$epoch).TotalMilliseconds)}""}"
$method = "Put"
}
$continue = $true
while($continue)
{
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method $method -Uri "$chatService/v1/users/ME/conversations/$ConversationID/messages/$MessageID/properties?name=emotions" -Headers $headers -Body $body
$continue = $false
}
catch
{
if($_.Exception.Response.StatusCode -eq 429)
{
if($_.Exception.Response.Headers["Retry-After"])
{
$retryAfter = ([datetime]$_.Exception.Response.Headers["Retry-After"]).Second
Write-Warning "Retrying after $($retryAfter)s"
Start-Sleep -Seconds $retryAfter
}
else
{
throw $_
}
}
else
{
throw $_
}
}
}
}
catch{
Throw $_
}
}
}
# Get a teams message with clientmessageid
# Oct 26th 2020
function Get-TeamsMessage
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ClientMessageId
)
Process
{
$messages = Get-TeamsMessages -AccessToken $AccessToken
foreach($message in $messages)
{
if($message.clientmessageid -eq $ClientMessageId)
{
return $message
}
}
}
}
# Get user's Teams memberships (Teams' and chats)
# May 11th 2021
function Get-TeamsMemberships
{
[cmdletbinding()]
Param()
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Try to get a new access token for chat service using cached refreshtoken
$refreshToken = Get-RefreshTokenFromCache -ClientID "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -Resource "https://api.spaces.skype.com"
if(!$refreshToken)
{
Throw "No refresh token found!"
}
$AccessToken2 = Get-AccessTokenWithRefreshToken -Resource "https://chatsvcagg.teams.microsoft.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -RefreshToken $refreshToken -TenantId (Read-Accesstoken $AccessToken).tid
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken2"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"x-skypetoken" = "$skypeToken"
}
$membershipInfo = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://teams.microsoft.com/api/csa/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true" -Headers $headers
return $membershipInfo
}
}
# Removes a teams member from a given thread
# May 11th 2021
function Remove-TeamsMember
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$User,
[Parameter(Mandatory=$True)]
[String]$Thread
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$teamsAndChannelsService = $teamsSettings.regionGtms.teamsAndChannelsService
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"X-Skypetoken" = $skypeToken
"Accept" = "application/json"
}
# Get the recipient info
$recipient = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $User
$body = @{
"teamMri" = $Thread
"userMri" = $recipient.Mri
"updateType" = "Left"
}
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$teamsAndChannelsService/beta/teams/$Thread/members?allowBotsInChannel=true" -Headers $headers -Body ($body|ConvertTo-Json) -ContentType "application/json"
}
}
# Adds a new teams member to the given thread
# May 11th 2021
function Add-TeamsMember
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$User,
[Parameter(Mandatory=$True)]
[String]$Thread
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$teamsAndChannelsService = $teamsSettings.regionGtms.teamsAndChannelsService
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"X-Skypetoken" = $skypeToken
"Accept" = "application/json"
}
# Get the recipient info
$recipient = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $User
$body = @{ "users" = @(@{
"mri" = $recipient.mri
"role" = 2
})}
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$teamsAndChannelsService/beta/teams/$Thread/bulkUpdateRoledMembers?allowBotsInChannel=true" -Headers $headers -Body ($body|ConvertTo-Json) -ContentType "application/json"