Public/Get-SlackHistory.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
function Get-SlackHistory {
    <#
    .SYNOPSIS
        Get history from a Slack channel

    .DESCRIPTION
        Get history from a Slack channel

    .PARAMETER Token
        Specify a token for authorization.

        See 'Authentication' section here for more information: https://api.slack.com/web
        Test tokens are a simple way to use this

    .PARAMETER Id
        One or more channel IDs to extract history from.

    .PARAMETER Before
        Return history from before this date

    .PARAMETER After
        Return history from after this date

    .PARAMETER Inclusive
        If specified, include history from the date specified in Before and/or After parameters

    .PARAMETER Count
        Number of messages to return per query. Defaults to 100. Max 1000

    .PARAMETER Paging
        If specified, and more data is available with a given 'Count', continue querying Slack until
            we have retrieved all the data available.

        WARNING: This parameter is experimental

    .PARAMETER MaxQueries
        Limit the count of API queries to this number. Only used if you enable -Paging

    .PARAMETER Raw
        If specified, we provide raw output and do not parse any responses

    .FUNCTIONALITY
        Slack
    #>

    [cmdletbinding()]
    param (
        $Token = $Script:PSSlack.Token,
        [parameter( ValueFromPipelineByPropertyName = $True)] # a bit iffy... ID is common...
        [Alias('ID')]
        [string[]]$ChannelID,

        [ValidateRange(1,1000)]
        [int]$Count = 100,
        [switch]$Inclusive,
        [datetime]$Before,
        [datetime]$After,
        [switch]$Paging,
        [int]$MaxQueries,
        [switch]$Raw

    )
    begin
    {
        function Get-UnixTime {
            param($Date)
            $unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc)
            [int]($Date.ToUniversalTime() - $unixEpochStart).TotalSeconds
        }

        Write-Verbose "$($PSBoundParameters | Out-String)"

        $body = @{
            channel = $null
            count = $count
        }
        if($Paging)
        {
            $PageDirection = 'Backward'
        }
        $BeforeTS = $null
        $AfterTS = $null
        if($PSBoundParameters.ContainsKey('Before'))
        {
            $BeforeTS = Get-UnixTime -Date $Before
            $body.add('latest', $BeforeTS)
        }
        if($PSBoundParameters.ContainsKey('After'))
        {
            $AfterTS = Get-UnixTime -Date $After
            $body.add('oldest', $AfterTS)
            if(-not $PSBoundParameters.ContainsKey('Before') -and $Paging)
            {
                $PageDirection = 'Forward'
            }
        }
        if($Inclusive)
        {
            $body.add('inclusive', 1)
        }
        $params = @{
            Token = $Token
            Method = 'channels.history'
            Body = $body
        }
        $Queries = 1

    }
    process
    {
        foreach($ID in $ChannelID)
        {
            $has_more = $false
            $Params.body.channel = $ID
            do
            {
                if($has_more)
                {
                    if($Params.Body.oldest)
                    {
                        [void]$Params.Body.remove('oldest')
                    }
                    if($Params.Body.latest)
                    {
                        [void]$Params.Body.remove('latest')
                    }
                    if($PageDirection -eq 'Forward')
                    {

                        $ts = $response.messages.ts | sort | Select -last 1
                        $Params.body.oldest = $ts
                        Write-Debug "Paging Forward.`n$(
                            [pscustomobject]@{
                                After = $After
                                Before = $Before
                                LastTS = $response.messages[-1].ts
                                SortLast = $response.messages.ts | sort | Select -last 1
                                SortFirst = $response.messages.ts | sort | Select -first 1
                                ts = $ts
                            } | Out-String
                        )"

                    }
                    elseif($PageDirection -eq 'Backward')
                    {
                        $ts = $response.messages[-1].ts
                        if($AfterTS -and $ts -lt $AfterTS)
                        {
                            Write-Debug "TS is less than AfterTS, breaking!"
                            break
                        }
                        $Params.body.latest = $ts
                        Write-Debug "Paging Forward.`n$(
                            [pscustomobject]@{
                                After = $After
                                Before = $Before
                                LastTS = $response.messages[-1].ts
                                SortLast = $response.messages.ts | sort | Select -last 1
                                SortFirst = $response.messages.ts | sort | Select -first 1
                                ts = $ts
                            } | Out-String
                        )"

                    }

                    $has_more = $false
                    Write-Debug "Body is now:$($params.body | out-string)"
                }
                $response = Send-SlackApi @params

                Write-Debug "$($Response | Format-List -Property * | Out-String)"

                if ($response.ok)
                {

                    if($response.psobject.properties.name -contains 'has_more' -and $response.has_more)
                    {
                        Write-Debug 'Paging engaged!'
                        $has_more = $true
                    }

                    if($Raw)
                    {
                        $link = "$($Script:PSSlack.ArchiveUri)/$($response.channel)/p$($response.ts -replace '\.')"
                        $response | Add-Member -MemberType NoteProperty -Name link -Value $link
                        $response
                    }
                    else
                    {
                        #Order our messages appropriately according to page direction
                        if($Paging -and $PageDirection -eq 'Forward')
                        {
                            Parse-SlackMessage -InputObject $Response | Sort TimeStamp
                        }
                        else
                        {
                            Parse-SlackMessage -InputObject $Response
                        }
                    }
                }
                else 
                {
                    $response
                }
                $Queries++
            }
            until (
                -not $Paging -or
                -not $has_more -or
                ($MaxQueries -and $Queries -gt $MaxQueries)
            )
        }
    }
}