From 01bc3094decc8fe452010511ef3444aac08604db Mon Sep 17 00:00:00 2001 From: AMEE WORK Date: Mon, 25 Jul 2022 15:33:42 +0300 Subject: [PATCH 1/6] Fix Teams Backend LoadUsers() --- .../Implementations/Teams/TeamsBackend.ps1 | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/PoshBot/Implementations/Teams/TeamsBackend.ps1 b/PoshBot/Implementations/Teams/TeamsBackend.ps1 index 2cd0105..09104ab 100644 --- a/PoshBot/Implementations/Teams/TeamsBackend.ps1 +++ b/PoshBot/Implementations/Teams/TeamsBackend.ps1 @@ -540,14 +540,42 @@ class TeamsBackend : Backend { if (-not [string]::IsNullOrEmpty($this.ServiceUrl)) { $this.LogDebug('Getting Teams users') - $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/members/" + $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/pagedmembers?pageSize=500" $headers = @{ Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" } - $members = Invoke-RestMethod -Uri $uri -Headers $headers + + $members = @() + do { + $Results = '' + $StatusCode = '' + do { + try { + $Results = Invoke-RestMethod -Headers $headers -Uri $Uri -UseBasicParsing -Method 'GET' -ContentType 'application/json' + + $StatusCode = $Results.StatusCode + } catch { + $StatusCode = $_.Exception.Response.StatusCode.value__ + + if ($StatusCode -eq 429) { + $this.LogDebug('Got throttled by Microsoft. Sleeping for 45 seconds...') + Start-Sleep -Seconds 45 + } else { + $this.LogDebug("Error Populating the list of users for the team: $($_.Exception.Message)") + } + } + } while ($StatusCode -eq 429) + if ($Results.continuationToken) { + $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/pagedmembers?pageSize=500&continuationToken=$($Results.continuationToken)" + $members += $Results.members + } else { + $members += $Results.members + } + } while ($Results.continuationToken) + $this.LogDebug('Finished getting Teams users') - $members | Foreach-Object { + $members | ForEach-Object { $user = [TeamsPerson]::new() $user.Id = $_.id $user.FirstName = $_.givenName @@ -559,7 +587,7 @@ class TeamsBackend : Backend { if (-not $this.Users.ContainsKey($_.ID)) { $this.LogDebug("Adding user [$($_.ID):$($_.Name)]") - $this.Users[$_.ID] = $user + $this.Users[$_.ID] = $user } } From c87184c3d69bd1523f09b50d2aa3e2a3ba8b7595 Mon Sep 17 00:00:00 2001 From: Andriy Golubenkov FUIB VM Date: Mon, 31 Jul 2023 13:29:58 +0300 Subject: [PATCH 2/6] Slack reply to Thread --- PoshBot/Classes/Bot.ps1 | 6 ++--- .../Implementations/Slack/SlackBackend.ps1 | 17 +++++++++++-- PoshBot/PoshBot.psd1 | 24 ++++++++----------- PoshBot/Public/New-PoshBotCardResponse.ps1 | 5 +++- PoshBot/Public/New-PoshBotTextResponse.ps1 | 5 +++- requirements.psd1 | 2 +- 6 files changed, 37 insertions(+), 22 deletions(-) diff --git a/PoshBot/Classes/Bot.ps1 b/PoshBot/Classes/Bot.ps1 index 1da1bf1..5f6b7fd 100644 --- a/PoshBot/Classes/Bot.ps1 +++ b/PoshBot/Classes/Bot.ps1 @@ -62,9 +62,9 @@ class Bot : BaseLogger { # Disable $PSStyle output rendering so ANSI escape sequences # don't get sent back to the chat backend - if ($global:PSStyle) { - $global:PSStyle.OutputRendering = [Management.Automation.OutputRendering]::Host - } + # if ($global:PSStyle) { + # $global:PSStyle.OutputRendering = [Management.Automation.OutputRendering]::Host + # } # Attach the logger to the backend $this.Backend.Logger = $this.Logger diff --git a/PoshBot/Implementations/Slack/SlackBackend.ps1 b/PoshBot/Implementations/Slack/SlackBackend.ps1 index 5e9df7f..f7985ba 100644 --- a/PoshBot/Implementations/Slack/SlackBackend.ps1 +++ b/PoshBot/Implementations/Slack/SlackBackend.ps1 @@ -368,6 +368,11 @@ class SlackBackend : Backend { $sendTo = "@$($this.UserIdToUsername($Response.MessageFrom))" } + $threadId = [string]::Empty + if ($customResponse.TH) { + $threadId = "@$($Response.OriginalMessage.RawMessage.ts)" + } + switch -Regex ($customResponse.PSObject.TypeNames[0]) { '(.*?)PoshBot\.Card\.Response' { $this.LogDebug('Custom response is [PoshBot.Card.Response]') @@ -420,7 +425,11 @@ class SlackBackend : Backend { $attParams.Text = [string]::Empty } $att = New-SlackMessageAttachment @attParams - $msg = $att | New-SlackMessage -Channel $sendTo -AsUser + if([string]::IsNullOrEmpty($threadId)){ + $msg = $att | New-SlackMessage -Channel $sendTo -AsUser + }else{ + $msg = $att | New-SlackMessage -Channel $sendTo -AsUser -Thread $threadId + } $this.LogDebug("Sending card response back to Slack channel [$sendTo]", $att) $msg | Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Verbose:$false > $null } @@ -436,7 +445,11 @@ class SlackBackend : Backend { $t = $chunk } $this.LogDebug("Sending text response back to Slack channel [$sendTo]", $t) - Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $sendTo -Text $t -Verbose:$false -AsUser > $null + if([string]::IsNullOrEmpty($threadId)){ + Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $sendTo -Text $t -Verbose:$false -AsUser > $null + }else{ + Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $sendTo -Text $t -Verbose:$false -AsUser -Thread $threadId > $null + } } break } diff --git a/PoshBot/PoshBot.psd1 b/PoshBot/PoshBot.psd1 index f7243f2..a11e97e 100644 --- a/PoshBot/PoshBot.psd1 +++ b/PoshBot/PoshBot.psd1 @@ -1,10 +1,6 @@ # # Module manifest for module 'PoshBot' # -# Generated by: brand -# -# Generated on: 12/18/2016 -# @{ @@ -12,7 +8,7 @@ RootModule = 'PoshBot.psm1' # Version number of this module. -ModuleVersion = '0.14.0' +ModuleVersion = '0.14.31' # Supported PSEditions # CompatiblePSEditions = @() @@ -21,16 +17,16 @@ ModuleVersion = '0.14.0' GUID = '7bfb126c-b432-4921-989a-9802f525693f' # Author of this module -Author = 'Brandon Olin' +Author = 'Andrew V. Golubenkoff' # Company or vendor of this module -CompanyName = 'Community' +CompanyName = 'FUIB' # Copyright statement for this module -Copyright = '(c) Brandon Olin. All rights reserved.' +Copyright = '(c) Andrew V. Golubenkoff.' # Description of the functionality provided by this module -Description = 'A Powershell-based bot framework for ChatOps. PowerShell modules are loaded into PoshBot and instantly become available as bot commands. PoshBot currently supports connecting to Slack to provide you with awesome ChatOps goodness. Bot commands can optionally be secured via permissions, roles, and groups to control who can execute what.' +Description = 'FUIB Powershell-based bot. PowerShell modules are loaded into PoshBot and instantly become available as bot commands.' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '5.0' @@ -53,7 +49,7 @@ PowerShellVersion = '5.0' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @( @{ModuleName = 'Configuration'; ModuleVersion = '1.3.1'} - @{ModuleName = 'PSSlack'; ModuleVersion = '1.0.2'} + @{ModuleName = 'PSSlack'; ModuleVersion = '1.0.6'} ) # Assemblies that must be loaded prior to importing this module @@ -125,16 +121,16 @@ PrivateData = @{ Tags = @('PoshBot', 'ChatOps', 'Bot') # A URL to the license for this module. - LicenseUri = 'https://raw.githubusercontent.com/poshbotio/PoshBot/master/LICENSE' + LicenseUri = 'https://raw.githubusercontent.com/golubenkoff/PoshBot/master/LICENSE' # A URL to the main website for this project. - ProjectUri = 'https://github.com/poshbotio/PoshBot' + ProjectUri = 'https://github.com/golubenkoff/PoshBot' # A URL to an icon representing this module. - IconUri = 'https://raw.githubusercontent.com/poshbotio/PoshBot/master/Media/poshbot_logo_thumb_256.png' + IconUri = 'https://raw.githubusercontent.com/golubenkoff/PoshBot/master/Media/poshbot_logo_thumb_256.png' # ReleaseNotes of this module - ReleaseNotes = 'https://raw.githubusercontent.com/poshbotio/PoshBot/master/CHANGELOG.md' + ReleaseNotes = 'https://raw.githubusercontent.com/golubenkoff/PoshBot/master/CHANGELOG.md' } # End of PSData hashtable } # End of PrivateData hashtable diff --git a/PoshBot/Public/New-PoshBotCardResponse.ps1 b/PoshBot/Public/New-PoshBotCardResponse.ps1 index 78a17f8..c91ec00 100644 --- a/PoshBot/Public/New-PoshBotCardResponse.ps1 +++ b/PoshBot/Public/New-PoshBotCardResponse.ps1 @@ -132,7 +132,9 @@ function New-PoshBotCardResponse { })] [string]$Color = '#D3D3D3', - [object]$CustomData + [object]$CustomData, + + [switch]$TH ) $response = [ordered]@{ @@ -141,6 +143,7 @@ function New-PoshBotCardResponse { Text = $Text.Trim() Private = $PSBoundParameters.ContainsKey('Private') DM = $PSBoundParameters['DM'] + TH = $PSBoundParameters['TH'] } if ($PSBoundParameters.ContainsKey('Title')) { $response.Title = $Title diff --git a/PoshBot/Public/New-PoshBotTextResponse.ps1 b/PoshBot/Public/New-PoshBotTextResponse.ps1 index bb3fb5e..a04c7ce 100644 --- a/PoshBot/Public/New-PoshBotTextResponse.ps1 +++ b/PoshBot/Public/New-PoshBotTextResponse.ps1 @@ -42,7 +42,9 @@ function New-PoshBotTextResponse { [switch]$AsCode, - [switch]$DM + [switch]$DM, + + [switch]$TH ) process { @@ -52,6 +54,7 @@ function New-PoshBotTextResponse { Text = $item.Trim() AsCode = $PSBoundParameters.ContainsKey('AsCode') DM = $PSBoundParameters.ContainsKey('DM') + TH = $PSBoundParameters.ContainsKey('TH') } } } diff --git a/requirements.psd1 b/requirements.psd1 index 209468e..54cdce9 100644 --- a/requirements.psd1 +++ b/requirements.psd1 @@ -7,6 +7,6 @@ Configuration = '1.3.1' Pester = '4.9.0' PSScriptAnalyzer = '1.18.3' - PSSlack = '1.0.2' + PSSlack = '1.0.6' platyPS = '0.14.0' } From eefed7c8490522df03b5dcf53cff944ce0828615 Mon Sep 17 00:00:00 2001 From: Andriy Golubenkov FUIB VM Date: Thu, 2 May 2024 14:36:33 +0300 Subject: [PATCH 3/6] UPD --- .../functions/Get-PoshBotStatefulData.md | 105 --- .../functions/New-PoshBotDiscordBackend.md | 65 -- .../functions/New-PoshBotFileUpload.md | 246 ------ .../functions/New-PoshBotMiddlewareHook.md | 79 -- .../functions/New-PoshBotTeamsBackend.md | 70 -- docs/reference/functions/PoshBot.md | 67 -- .../functions/Remove-PoshBotStatefulData.md | 136 ---- .../functions/Set-PoshBotStatefulData.md | 155 ---- docs/reference/functions/get-poshbot.md | 83 -- .../functions/get-poshbotconfiguration.md | 115 --- .../functions/new-poshbotcardresponse.md | 250 ------ .../functions/new-poshbotconfiguration.md | 728 ------------------ .../functions/new-poshbotinstance.md | 170 ---- .../functions/new-poshbotscheduledtask.md | 195 ----- .../functions/new-poshbotslackbackend.md | 60 -- .../functions/new-poshbottextresponse.md | 106 --- .../functions/save-poshbotconfiguration.md | 158 ---- docs/reference/functions/start-poshbot.md | 166 ---- docs/reference/functions/stop-poshbot.md | 118 --- 19 files changed, 3072 deletions(-) delete mode 100644 docs/reference/functions/Get-PoshBotStatefulData.md delete mode 100644 docs/reference/functions/New-PoshBotDiscordBackend.md delete mode 100644 docs/reference/functions/New-PoshBotFileUpload.md delete mode 100644 docs/reference/functions/New-PoshBotMiddlewareHook.md delete mode 100644 docs/reference/functions/New-PoshBotTeamsBackend.md delete mode 100644 docs/reference/functions/PoshBot.md delete mode 100644 docs/reference/functions/Remove-PoshBotStatefulData.md delete mode 100644 docs/reference/functions/Set-PoshBotStatefulData.md delete mode 100644 docs/reference/functions/get-poshbot.md delete mode 100644 docs/reference/functions/get-poshbotconfiguration.md delete mode 100644 docs/reference/functions/new-poshbotcardresponse.md delete mode 100644 docs/reference/functions/new-poshbotconfiguration.md delete mode 100644 docs/reference/functions/new-poshbotinstance.md delete mode 100644 docs/reference/functions/new-poshbotscheduledtask.md delete mode 100644 docs/reference/functions/new-poshbotslackbackend.md delete mode 100644 docs/reference/functions/new-poshbottextresponse.md delete mode 100644 docs/reference/functions/save-poshbotconfiguration.md delete mode 100644 docs/reference/functions/start-poshbot.md delete mode 100644 docs/reference/functions/stop-poshbot.md diff --git a/docs/reference/functions/Get-PoshBotStatefulData.md b/docs/reference/functions/Get-PoshBotStatefulData.md deleted file mode 100644 index 511969c..0000000 --- a/docs/reference/functions/Get-PoshBotStatefulData.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Get-PoshBotStatefulData - -## SYNOPSIS -Get stateful data previously exported from a PoshBot command - -## SYNTAX - -``` -Get-PoshBotStatefulData [[-Name] ] [-ValueOnly] [[-Scope] ] [] -``` - -## DESCRIPTION -Get stateful data previously exported from a PoshBot command - -Reads data from the PoshBot ConfigurationDirectory. - -## EXAMPLES - -### EXAMPLE 1 -``` -$ModuleData = Get-PoshBotStatefulData -``` - -Get all stateful data for the PoshBot plugin this runs from - -### EXAMPLE 2 -``` -$Something = Get-PoshBotStatefulData -Name 'Something' -ValueOnly -Scope Global -``` - -Set $Something to the value of the 'Something' property from Poshbot's global stateful data - -## PARAMETERS - -### -Name -If specified, retrieve only this property from the stateful data - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: * -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ValueOnly -If specified, return only the value of the specified property Name - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Scope -Get stateful data from this scope: - Module: Data scoped to this plugin - Global: Data available to any Poshbot plugin - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: Module -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS - -[Set-PoshBotStatefulData]() - -[Remove-PoshBotStatefulData]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/New-PoshBotDiscordBackend.md b/docs/reference/functions/New-PoshBotDiscordBackend.md deleted file mode 100644 index 1e35d08..0000000 --- a/docs/reference/functions/New-PoshBotDiscordBackend.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotDiscordBackend - -## SYNOPSIS -Create a new instance of a Discord backend - -## SYNTAX - -``` -New-PoshBotDiscordBackend [-Configuration] [] -``` - -## DESCRIPTION -Create a new instance of a Discord backend - -## EXAMPLES - -### EXAMPLE 1 -``` -$backendConfig = @{ - Name = 'DiscordBackend' - Token = '' - ClientId = '' - GuildId = '' -} -PS C:\> $backend = New-PoshBotDiscordBackend -Configuration $backendConfig -``` - -Create a Discord backend using the specified connection information. - -## PARAMETERS - -### -Configuration -The hashtable containing backend-specific properties on how to create the Discord backend instance. - -```yaml -Type: Hashtable[] -Parameter Sets: (All) -Aliases: BackendConfiguration - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Hashtable -## OUTPUTS - -### DiscordBackend -## NOTES - -## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotFileUpload.md b/docs/reference/functions/New-PoshBotFileUpload.md deleted file mode 100644 index e2f5f62..0000000 --- a/docs/reference/functions/New-PoshBotFileUpload.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotFileUpload - -## SYNOPSIS -Tells PoshBot to upload a file to the chat network. - -## SYNTAX - -### Path (Default) -``` -New-PoshBotFileUpload [-Path] [-Title ] [-DM] [-KeepFile] [] -``` - -### LiteralPath -``` -New-PoshBotFileUpload [-LiteralPath] [-Title ] [-DM] [-KeepFile] [] -``` - -### Content -``` -New-PoshBotFileUpload -Content [-FileType ] [-FileName ] [-Title ] [-DM] - [-KeepFile] [] -``` - -## DESCRIPTION -Returns a custom object back to PoshBot telling it to upload the given file to the chat network. -The custom object -can also tell PoshBot to redirect the file upload to a DM channel with the calling user. -This could be useful if -the contents the bot command returns are sensitive and should not be visible to all users in the channel. - -## EXAMPLES - -### EXAMPLE 1 -``` -function Do-Stuff { - [cmdletbinding()] - param() -``` - -$myObj = \[pscustomobject\]@{ - value1 = 'foo' - value2 = 'bar' - } - - $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" - $myObj | Export-Csv -Path $csv -NoTypeInformation - - New-PoshBotFileUpload -Path $csv -} - -Export a CSV file and tell PoshBot to upload the file back to the channel that initiated this command. - -### EXAMPLE 2 -``` -function Get-SecretPlan { - [cmdletbinding()] - param() -``` - -$myObj = \[pscustomobject\]@{ - Title = 'Secret moon base' - Description = 'Plans for secret base on the dark side of the moon' - } - - $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" - $myObj | Export-Csv -Path $csv -NoTypeInformation - - New-PoshBotFileUpload -Path $csv -Title 'YourEyesOnly.csv' -DM -} - -Export a CSV file and tell PoshBot to upload the file back to a DM channel with the calling user. - -### EXAMPLE 3 -``` -function Do-Stuff { - [cmdletbinding()] - param() -``` - -$myObj = \[pscustomobject\]@{ - value1 = 'foo' - value2 = 'bar' - } - - $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" - $myObj | Export-Csv -Path $csv -NoTypeInformation - - New-PoshBotFileUpload -Path $csv -KeepFile -} - -Export a CSV file and tell PoshBot to upload the file back to the channel that initiated this command. -Keep the file after uploading it. - -## PARAMETERS - -### -Path -The path(s) to one or more files to upload. -Wildcards are permitted. - -```yaml -Type: String[] -Parameter Sets: Path -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` - -### -LiteralPath -Specifies the path(s) to the current location of the file(s). -Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation -marks tell PowerShell not to interpret any characters as escape sequences. - -```yaml -Type: String[] -Parameter Sets: LiteralPath -Aliases: PSPath - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName) -Accept wildcard characters: False -``` - -### -Content -The content of the file to send. - -```yaml -Type: String -Parameter Sets: Content -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -FileType -If specified, override the file type determined by the filename. - -```yaml -Type: String -Parameter Sets: Content -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -FileName -The name to call the uploaded file - -```yaml -Type: String -Parameter Sets: Content -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Title -The title for the uploaded file. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: [string]::Empty -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -DM -Tell PoshBot to redirect the file upload to a DM channel. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -KeepFile -If specified, keep the source file after calling Send-SlackFile. -The source file is deleted without this - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String -## OUTPUTS - -### PSCustomObject -## NOTES - -## RELATED LINKS - -[New-PoshBotCardResponse]() - -[New-PoshBotTextResponse]() - diff --git a/docs/reference/functions/New-PoshBotMiddlewareHook.md b/docs/reference/functions/New-PoshBotMiddlewareHook.md deleted file mode 100644 index 0e9eadc..0000000 --- a/docs/reference/functions/New-PoshBotMiddlewareHook.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotMiddlewareHook - -## SYNOPSIS -Creates a PoshBot middleware hook object. - -## SYNTAX - -``` -New-PoshBotMiddlewareHook [-Name] [-Path] [] -``` - -## DESCRIPTION -PoshBot can execute custom scripts during various stages of the command processing lifecycle. -These scripts -are defined using New-PoshBotMiddlewareHook and added to the bot configuration object under the MiddlewareConfiguration section. -Hooks are added to the PreReceive, PostReceive, PreExecute, PostExecute, PreResponse, and PostResponse properties. -Middleware gets executed in the order in which it is added under each property. - -## EXAMPLES - -### EXAMPLE 1 -``` -$userDropHook = New-PoshBotMiddlewareHook -Name 'dropuser' -Path 'c:/poshbot/middleware/dropuser.ps1' -PS C:\> $config.MiddlewareConfiguration.Add($userDropHook, 'PreReceive') -``` - -Creates a middleware hook called 'dropuser' and adds it to the 'PreReceive' middleware lifecycle stage. - -## PARAMETERS - -### -Name -The name of the middleware hook. -Must be unique in each middleware lifecycle stage. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -The file path the the PowerShell script to execute as a middleware hook. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 2 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -### MiddlewareHook -## NOTES - -## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotTeamsBackend.md b/docs/reference/functions/New-PoshBotTeamsBackend.md deleted file mode 100644 index 8476afe..0000000 --- a/docs/reference/functions/New-PoshBotTeamsBackend.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotTeamsBackend - -## SYNOPSIS -Create a new instance of a Microsoft Teams backend - -## SYNTAX - -``` -New-PoshBotTeamsBackend [-Configuration] [] -``` - -## DESCRIPTION -Create a new instance of a Microsoft Teams backend - -## EXAMPLES - -### EXAMPLE 1 -``` -$backendConfig = @{ - Name = 'TeamsBackend' - Credential = [pscredential]::new( - '', - ('' | ConvertTo-SecureString -AsPlainText -Force) - ) - ServiceBusNamespace = '' - QueueName = '' - AccessKeyName = '' - AccessKey = '' | ConvertTo-SecureString -AsPlainText -Force -} -PS C:\> $$backend = New-PoshBotTeamsBackend -Configuration $backendConfig -``` - -Create a Microsoft Teams backend using the specified Bot Framework credentials and Service Bus information - -## PARAMETERS - -### -Configuration -The hashtable containing backend-specific properties on how to create the instance. - -```yaml -Type: Hashtable[] -Parameter Sets: (All) -Aliases: BackendConfiguration - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Hashtable -## OUTPUTS - -### TeamsBackend -## NOTES - -## RELATED LINKS diff --git a/docs/reference/functions/PoshBot.md b/docs/reference/functions/PoshBot.md deleted file mode 100644 index ede4c6a..0000000 --- a/docs/reference/functions/PoshBot.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -Module Name: PoshBot -Module Guid: 7bfb126c-b432-4921-989a-9802f525693f -Download Help Link: {{ Update Download Link }} -Help Version: {{ Please enter version of help manually (X.X.X.X) format }} -Locale: en-US ---- - -# PoshBot Module -## Description -{{ Fill in the Description }} - -## PoshBot Cmdlets -### [Get-PoshBot](Get-PoshBot.md) -{{ Fill in the Description }} - -### [Get-PoshBotConfiguration](Get-PoshBotConfiguration.md) -{{ Fill in the Description }} - -### [Get-PoshBotStatefulData](Get-PoshBotStatefulData.md) -{{ Fill in the Description }} - -### [New-PoshBotCardResponse](New-PoshBotCardResponse.md) -{{ Fill in the Description }} - -### [New-PoshBotConfiguration](New-PoshBotConfiguration.md) -{{ Fill in the Description }} - -### [New-PoshBotDiscordBackend](New-PoshBotDiscordBackend.md) -{{ Fill in the Description }} - -### [New-PoshBotFileUpload](New-PoshBotFileUpload.md) -{{ Fill in the Description }} - -### [New-PoshBotInstance](New-PoshBotInstance.md) -{{ Fill in the Description }} - -### [New-PoshBotMiddlewareHook](New-PoshBotMiddlewareHook.md) -{{ Fill in the Description }} - -### [New-PoshBotScheduledTask](New-PoshBotScheduledTask.md) -{{ Fill in the Description }} - -### [New-PoshBotSlackBackend](New-PoshBotSlackBackend.md) -{{ Fill in the Description }} - -### [New-PoshBotTeamsBackend](New-PoshBotTeamsBackend.md) -{{ Fill in the Description }} - -### [New-PoshBotTextResponse](New-PoshBotTextResponse.md) -{{ Fill in the Description }} - -### [Remove-PoshBotStatefulData](Remove-PoshBotStatefulData.md) -{{ Fill in the Description }} - -### [Save-PoshBotConfiguration](Save-PoshBotConfiguration.md) -{{ Fill in the Description }} - -### [Set-PoshBotStatefulData](Set-PoshBotStatefulData.md) -{{ Fill in the Description }} - -### [Start-PoshBot](Start-PoshBot.md) -{{ Fill in the Description }} - -### [Stop-Poshbot](Stop-Poshbot.md) -{{ Fill in the Description }} - diff --git a/docs/reference/functions/Remove-PoshBotStatefulData.md b/docs/reference/functions/Remove-PoshBotStatefulData.md deleted file mode 100644 index 124ab61..0000000 --- a/docs/reference/functions/Remove-PoshBotStatefulData.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Remove-PoshBotStatefulData - -## SYNOPSIS -Remove existing stateful data - -## SYNTAX - -``` -Remove-PoshBotStatefulData [-Name] [[-Scope] ] [[-Depth] ] [-WhatIf] [-Confirm] - [] -``` - -## DESCRIPTION -Remove existing stateful data - -## EXAMPLES - -### EXAMPLE 1 -``` -Remove-PoshBotStatefulData -Name 'ToUse' -``` - -Removes the 'ToUse' property from stateful data for the PoshBot plugin you are currently running this from. - -### EXAMPLE 2 -``` -Remove-PoshBotStatefulData -Name 'Something' -Scope Global -``` - -Removes the 'Something' property from PoshBot's global stateful data - -## PARAMETERS - -### -Name -Property to remove from the stateful data file - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Scope -Sets the scope of stateful data to remove: - Module: Remove stateful data from the current module's data - Global: Remove stateful data from the global PoshBot data - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: Module -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Depth -Specifies how many levels of contained objects are included in the XML representation. -The default value is 2 - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: 2 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS - -[Get-PoshBotStatefulData]() - -[Set-PoshBotStatefulData]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/Set-PoshBotStatefulData.md b/docs/reference/functions/Set-PoshBotStatefulData.md deleted file mode 100644 index 08aeaff..0000000 --- a/docs/reference/functions/Set-PoshBotStatefulData.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Set-PoshBotStatefulData - -## SYNOPSIS -Save stateful data to use in another PoshBot command - -## SYNTAX - -``` -Set-PoshBotStatefulData [-Name] [-Value] [[-Scope] ] [[-Depth] ] [-WhatIf] - [-Confirm] [] -``` - -## DESCRIPTION -Save stateful data to use in another PoshBot command - -Stores data in clixml format, in the PoshBot ConfigurationDirectory. - -If \ property exists in current stateful data file, it is overwritten - -## EXAMPLES - -### EXAMPLE 1 -``` -Set-PoshBotStatefulData -Name 'ToUse' -Value 'Later' -``` - -Adds a 'ToUse' property to the stateful data for the PoshBot plugin you are currently running this from. - -### EXAMPLE 2 -``` -$Anything | Set-PoshBotStatefulData -Name 'Something' -Scope Global -``` - -Adds a 'Something' property to PoshBot's global stateful data, with the value of $Anything - -## PARAMETERS - -### -Name -Property to add to the stateful data file - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Value -Value to set for the Name property in the stateful data file - -```yaml -Type: Object[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 2 -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: False -``` - -### -Scope -Sets the scope of stateful data to set: - Module: Allow only this plugin to access the stateful data you save - Global: Allow any plugin to access the stateful data you save - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: Module -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Depth -Specifies how many levels of contained objects are included in the XML representation. -The default value is 2 - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 4 -Default value: 2 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -## RELATED LINKS - -[Get-PoshBotStatefulData]() - -[Remove-PoshBotStatefulData]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/get-poshbot.md b/docs/reference/functions/get-poshbot.md deleted file mode 100644 index d97cef1..0000000 --- a/docs/reference/functions/get-poshbot.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Get-PoshBot - -## SYNOPSIS -Gets any currently running instances of PoshBot that are running as background jobs. - -## SYNTAX - -``` -Get-PoshBot [[-Id] ] [] -``` - -## DESCRIPTION -PoshBot can be run in the background with PowerShell jobs. -This function returns -any currently running PoshBot instances. - -## EXAMPLES - -### EXAMPLE 1 -``` -Get-PoshBot -``` - -Id : 5 -Name : PoshBot_3ddfc676406d40fca149019d935f065d -State : Running -InstanceId : 3ddfc676406d40fca149019d935f065d -Config : BotConfiguration - -### EXAMPLE 2 -``` -Get-PoshBot -Id 100 -``` - -Id : 100 -Name : PoshBot_eab96f2ad147489b9f90e110e02ad805 -State : Running -InstanceId : eab96f2ad147489b9f90e110e02ad805 -Config : BotConfiguration - -Gets the PoshBot job instance with ID 100. - -## PARAMETERS - -### -Id -One or more job IDs to retrieve. - -```yaml -Type: Int32[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: @() -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.Int32 -## OUTPUTS - -### PSCustomObject -## NOTES - -## RELATED LINKS - -[Start-PoshBot]() - -[Stop-PoshBot]() - diff --git a/docs/reference/functions/get-poshbotconfiguration.md b/docs/reference/functions/get-poshbotconfiguration.md deleted file mode 100644 index 40bc25e..0000000 --- a/docs/reference/functions/get-poshbotconfiguration.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Get-PoshBotConfiguration - -## SYNOPSIS -Gets a PoshBot configuration from a file. - -## SYNTAX - -### Path (Default) -``` -Get-PoshBotConfiguration [-Path] [] -``` - -### LiteralPath -``` -Get-PoshBotConfiguration [-LiteralPath] [] -``` - -## DESCRIPTION -PoshBot configurations can be stored on the filesytem in PowerShell data (.psd1) files. -This functions will load that file and return a \[BotConfiguration\] object. - -## EXAMPLES - -### EXAMPLE 1 -``` -Get-PoshBotConfiguration -Path C:\Users\joeuser\.poshbot\Cherry2000.psd1 -``` - -Name : Cherry2000 -ConfigurationDirectory : C:\Users\joeuser\.poshbot -LogDirectory : C:\Users\joeuser\.poshbot\Logs -PluginDirectory : C:\Users\joeuser\.poshbot -PluginRepository : {PSGallery} -ModuleManifestsToLoad : {} -LogLevel : Debug -BackendConfiguration : {Token, Name} -PluginConfiguration : {} -BotAdmins : {joeuser} -CommandPrefix : ! -AlternateCommandPrefixes : {bender, hal} -AlternateCommandPrefixSeperators : {:, ,, ;} -SendCommandResponseToPrivate : {} -MuteUnknownCommand : False -AddCommandReactions : True - -Gets the bot configuration located at \[C:\Users\joeuser\.poshbot\Cherry2000.psd1\]. - -### EXAMPLE 2 -``` -$botConfig = 'C:\Users\joeuser\.poshbot\Cherry2000.psd1' | Get-PoshBotConfiguration -``` - -Gets the bot configuration located at \[C:\Users\brand\.poshbot\Cherry2000.psd1\]. - -## PARAMETERS - -### -Path -One or more paths to a PoshBot configuration file. - -```yaml -Type: String[] -Parameter Sets: Path -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` - -### -LiteralPath -Specifies the path(s) to the current location of the file(s). -Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation -marks tell PowerShell not to interpret any characters as escape sequences. - -```yaml -Type: String[] -Parameter Sets: LiteralPath -Aliases: PSPath - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName) -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String -## OUTPUTS - -### BotConfiguration -## NOTES - -## RELATED LINKS - -[New-PoshBotConfiguration]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/new-poshbotcardresponse.md b/docs/reference/functions/new-poshbotcardresponse.md deleted file mode 100644 index 04e2792..0000000 --- a/docs/reference/functions/new-poshbotcardresponse.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotCardResponse - -## SYNOPSIS -Tells PoshBot to send a specially formatted response. - -## SYNTAX - -``` -New-PoshBotCardResponse [[-Type] ] [-DM] [[-Text] ] [[-Title] ] - [[-ThumbnailUrl] ] [[-ImageUrl] ] [[-LinkUrl] ] [[-Fields] ] - [[-Color] ] [[-CustomData] ] [] -``` - -## DESCRIPTION -Responses from PoshBot commands can either be plain text or formatted. -Returning a response with New-PoshBotRepsonse will tell PoshBot -to craft a specially formatted message when sending back to the chat network. - -## EXAMPLES - -### EXAMPLE 1 -``` -function Do-Something { - [cmdletbinding()] - param( - [parameter(mandatory)] - [string]$MyParam - ) -``` - -New-PoshBotCardResponse -Type Normal -Text 'OK, I did something.' -ThumbnailUrl 'https://www.streamsports.com/images/icon_green_check_256.png' -} - -Tells PoshBot to send a formatted response back to the chat network. -In Slack for example, this response will be a message attachment -with a green border on the left, some text and a green checkmark thumbnail image. - -### EXAMPLE 2 -``` -function Do-Something { - [cmdletbinding()] - param( - [parameter(mandatory)] - [string]$ComputerName - ) -``` - -$info = Get-ComputerInfo -ComputerName $ComputerName -ErrorAction SilentlyContinue - if ($info) { - $fields = \[ordered\]@{ - Name = $ComputerName - OS = $info.OSName - Uptime = $info.Uptime - IPAddress = $info.IPAddress - } - New-PoshBotCardResponse -Type Normal -Fields $fields - } else { - New-PoshBotCardResponse -Type Error -Text 'Something bad happended :(' -ThumbnailUrl 'http://p1cdn05.thewrap.com/images/2015/06/don-draper-shrug.jpg' - } -} - -Attempt to retrieve some information from a given computer and return a card response back to PoshBot. -If the command fails for some reason, -return a card response specified the error and a sad image. - -## PARAMETERS - -### -Type -Specifies a preset color for the card response. -If the \[Color\] parameter is specified as well, it will override this parameter. - -| Type | Color | Hex code | -|---------|--------|----------| -| Normal | Greed | #008000 | -| Warning | Yellow | #FFA500 | -| Error | Red | #FF0000 | - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: Normal -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -DM -Tell PoshBot to redirect the response to a DM channel. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Text -The text response from the command. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: [string]::empty -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Title -The title of the response. -This will be the card title in chat networks like Slack. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ThumbnailUrl -A URL to a thumbnail image to display in the card response. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 4 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ImageUrl -A URL to an image to display in the card response. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 5 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LinkUrl -Will turn the title into a hyperlink - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 6 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Fields -A hashtable to display as a table in the card response. - -```yaml -Type: IDictionary -Parameter Sets: (All) -Aliases: - -Required: False -Position: 7 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Color -The hex color code to use for the card response. -In Slack, this will be the color of the left border in the message attachment. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 8 -Default value: #D3D3D3 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -CustomData -Any additional custom data you'd like to pass on. -Useful for custom backends, in case you want to pass a specifically formatted response -in the Data stream of the responses received by the backend. -Any data sent here will be skipped by the built-in backends provided with PoshBot itself. - -```yaml -Type: Object -Parameter Sets: (All) -Aliases: - -Required: False -Position: 9 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -### PSCustomObject -## NOTES - -## RELATED LINKS - -[New-PoshBotTextResponse]() - diff --git a/docs/reference/functions/new-poshbotconfiguration.md b/docs/reference/functions/new-poshbotconfiguration.md deleted file mode 100644 index 46b4725..0000000 --- a/docs/reference/functions/new-poshbotconfiguration.md +++ /dev/null @@ -1,728 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotConfiguration - -## SYNOPSIS -Creates a new PoshBot configuration object. - -## SYNTAX - -``` -New-PoshBotConfiguration [[-Name] ] [[-ConfigurationDirectory] ] [[-LogDirectory] ] - [[-PluginDirectory] ] [[-PluginRepository] ] [[-ModuleManifestsToLoad] ] - [[-LogLevel] ] [[-MaxLogSizeMB] ] [[-MaxLogsToKeep] ] [[-LogCommandHistory] ] - [[-CommandHistoryMaxLogSizeMB] ] [[-CommandHistoryMaxLogsToKeep] ] - [[-BackendConfiguration] ] [[-PluginConfiguration] ] [[-BotAdmins] ] - [[-CommandPrefix] ] [[-AlternateCommandPrefixes] ] - [[-AlternateCommandPrefixSeperators] ] [[-SendCommandResponseToPrivate] ] - [[-MuteUnknownCommand] ] [[-AddCommandReactions] ] [[-ApprovalExpireMinutes] ] - [-DisallowDMs] [[-FormatEnumerationLimitOverride] ] [[-ApprovalCommandConfigurations] ] - [[-ChannelRules] ] [[-PreReceiveMiddlewareHooks] ] - [[-PostReceiveMiddlewareHooks] ] [[-PreExecuteMiddlewareHooks] ] - [[-PostExecuteMiddlewareHooks] ] [[-PreResponseMiddlewareHooks] ] - [[-PostResponseMiddlewareHooks] ] [] -``` - -## DESCRIPTION -Creates a new PoshBot configuration object. - -## EXAMPLES - -### EXAMPLE 1 -``` -New-PoshBotConfiguration -Name Cherry2000 -AlternateCommandPrefixes @('Cherry', 'Sam') -``` - -Name : Cherry2000 -ConfigurationDirectory : C:\Users\brand\.poshbot -LogDirectory : C:\Users\brand\.poshbot -PluginDirectory : C:\Users\brand\.poshbot -PluginRepository : {PSGallery} -ModuleManifestsToLoad : {} -LogLevel : Verbose -BackendConfiguration : {} -PluginConfiguration : {} -BotAdmins : {} -CommandPrefix : ! -AlternateCommandPrefixes : {Cherry, Sam} -AlternateCommandPrefixSeperators : {:, ,, ;} -SendCommandResponseToPrivate : {} -MuteUnknownCommand : False -AddCommandReactions : True -ApprovalConfiguration : ApprovalConfiguration - -Create a new PoshBot configuration with default values except for the bot name and alternate command prefixes that it will listen for. - -### EXAMPLE 2 -``` -$backend = @{Name = 'SlackBackend'; Token = 'xoxb-569733935137-njOPkyBThqOTTUnCZb7tZpKK'} -PS C:\> $botParams = @{ - Name = 'HAL9000' - LogLevel = 'Info' - BotAdmins = @('JoeUser') - BackendConfiguration = $backend - } -PS C:\> $myBotConfig = New-PoshBotConfiguration @botParams -PS C:\> $myBotConfig -``` - -Name : HAL9000 -ConfigurationDirectory : C:\Users\brand\.poshbot -LogDirectory : C:\Users\brand\.poshbot -PluginDirectory : C:\Users\brand\.poshbot -PluginRepository : {MyLocalRepo} -ModuleManifestsToLoad : {} -LogLevel : Info -BackendConfiguration : {} -PluginConfiguration : {} -BotAdmins : {JoeUser} -CommandPrefix : ! -AlternateCommandPrefixes : {poshbot} -AlternateCommandPrefixSeperators : {:, ,, ;} -SendCommandResponseToPrivate : {} -MuteUnknownCommand : False -AddCommandReactions : True -ApprovalConfiguration : ApprovalConfiguration - -PS C:\\\> $myBotConfig | Start-PoshBot -AsJob - -Create a new PoshBot configuration with a Slack backend. -Slack's backend only requires a bot token to be specified. -Ensure the person -with Slack handle 'JoeUser' is a bot admin. - -## PARAMETERS - -### -Name -The name the bot instance will be known as. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: PoshBot -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ConfigurationDirectory -The directory when PoshBot configuration data will be written to. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: $script:defaultPoshBotDir -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogDirectory -The log directory logs will be written to. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 3 -Default value: $script:defaultPoshBotDir -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PluginDirectory -The directory PoshBot will look for PowerShell modules. -This path will be prepended to your $env:PSModulePath. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 4 -Default value: $script:defaultPoshBotDir -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PluginRepository -One or more PowerShell repositories to look in when installing new plugins (modules). -These will be the repository name(s) as found in Get-PSRepository. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 5 -Default value: @('PSGallery') -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ModuleManifestsToLoad -One or more paths to module manifest (.psd1) files. -These modules will be automatically -loaded when PoshBot starts. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 6 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogLevel -The level of logging that PoshBot will do. - -```yaml -Type: LogLevel -Parameter Sets: (All) -Aliases: -Accepted values: Info, Verbose, Debug - -Required: False -Position: 7 -Default value: Verbose -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MaxLogSizeMB -The maximum log file size in megabytes. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 8 -Default value: 10 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MaxLogsToKeep -The maximum number of logs to keep. -Once this value is reached, logs will start rotating. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 9 -Default value: 5 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -LogCommandHistory -Enable command history to be logged to a separate file for convenience. -The default it $true - -```yaml -Type: Boolean -Parameter Sets: (All) -Aliases: - -Required: False -Position: 10 -Default value: True -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -CommandHistoryMaxLogSizeMB -The maximum log file size for the command history - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 11 -Default value: 10 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -CommandHistoryMaxLogsToKeep -The maximum number of logs to keep for command history. -Once this value is reached, the logs will start rotating. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 12 -Default value: 5 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -BackendConfiguration -A hashtable of configuration options required by the backend chat network implementation. - -```yaml -Type: Hashtable -Parameter Sets: (All) -Aliases: - -Required: False -Position: 13 -Default value: @{} -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PluginConfiguration -A hashtable of configuration options used by the various plugins (modules) that are installed in PoshBot. -Each key in the hashtable must be the name of a plugin. -The value of that hashtable item will be another hashtable -with each key matching a parameter name in one or more commands of that module. -A plugin command can specifiy that a -parameter gets its value from this configuration by applying the custom attribute \[PoshBot.FromConfig()\] on -the parameter. - -The function below is stating that the parameter $MyParam will get its value from the plugin configuration. -The user -running this command in PoshBot does not need to specify this parameter. -PoshBot will dynamically resolve and apply -the matching value from the plugin configuration when the command is executed. - -function Get-Foo { - \[cmdletbinding()\] - param( - \[PoshBot.FromConfig()\] - \[parameter(mandatory)\] - \[string\]$MyParam - ) - - Write-Output $MyParam -} - -If the function below was part of the Demo plugin, PoshBot will look in the plugin configuration for a key matching Demo -and a child key matching $MyParam. - -Example plugin configuration: -@{ - Demo = @{ - MyParam = 'bar' - } -} - -```yaml -Type: Hashtable -Parameter Sets: (All) -Aliases: - -Required: False -Position: 14 -Default value: @{} -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -BotAdmins -An array of chat handles that will be granted admin rights in PoshBot. -Any user in this array will have full rights in PoshBot. -At startup, -PoshBot will resolve these handles into IDs given by the chat network. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 15 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -CommandPrefix -The prefix (single character) that must be specified in front of a command in order for PoshBot to recognize the chat message as a bot command. - -!get-foo --value bar - -```yaml -Type: Char -Parameter Sets: (All) -Aliases: - -Required: False -Position: 16 -Default value: ! -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AlternateCommandPrefixes -Some users may want to specify alternate prefixes when calling bot comamnds. -Use this parameter to specify an array of words that PoshBot -will also check when parsing a chat message. - -bender get-foo --value bar - -hal open-doors --type pod - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 17 -Default value: @('poshbot') -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AlternateCommandPrefixSeperators -An array of characters that can also ben used when referencing bot commands. - -bender, get-foo --value bar - -hal; open-doors --type pod - -```yaml -Type: Char[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 18 -Default value: @(':', ',', ';') -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -SendCommandResponseToPrivate -A list of fully qualified (\:\) plugin commands that will have their responses redirected back to a direct message -channel with the calling user rather than a shared channel. - -@( - demo:get-foo - network:ping -) - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 19 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MuteUnknownCommand -Instead of PoshBot returning a warning message when it is unable to find a command, use this to parameter to tell PoshBot to return nothing. - -```yaml -Type: Boolean -Parameter Sets: (All) -Aliases: - -Required: False -Position: 20 -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AddCommandReactions -Add reactions to a chat message indicating the command is being executed, has succeeded, or failed. - -```yaml -Type: Boolean -Parameter Sets: (All) -Aliases: - -Required: False -Position: 21 -Default value: True -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ApprovalExpireMinutes -The amount of time (minutes) that a command the requires approval will be pending until it expires. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 22 -Default value: 30 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -DisallowDMs -Disallow DMs (direct messages) with the bot. -If a user tries to DM the bot it will be ignored. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -FormatEnumerationLimitOverride -Set $FormatEnumerationLimit to this. -Defaults to unlimited (-1) - -Determines how many enumerated items are included in a display. -This variable does not affect the underlying objects; just the display. -When the value of $FormatEnumerationLimit is less than the number of enumerated items, PowerShell adds an ellipsis (...) to indicate items not shown. - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 23 -Default value: -1 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ApprovalCommandConfigurations -Array of hashtables containing command approval configurations. - -@( - @{ - Expression = 'MyModule:Execute-Deploy:*' - Groups = 'platform-admins' - PeerApproval = $true - } - @{ - Expression = 'MyModule:Deploy-HRApp:*' - Groups = @('platform-managers', 'hr-managers') - PeerApproval = $true - } -) - -```yaml -Type: Hashtable[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 24 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ChannelRules -Array of channels rules that control what plugin commands are allowed in a channel. -Wildcards are supported. -Channel names that match against this list will be allowed to have Poshbot commands executed in them. - -Internally this uses the \`-like\` comparison operator, not \`-match\`. -Regexes are not allowed. - -For best results, list channels and commands from most specific to least specific. -PoshBot will -evaluate the first match found. - -Note that the bot will still receive messages from all channels it is a member of. -These message MAY -be logged depending on your configured logging level. - -Example value: -@( - # Only allow builtin commands in the 'botadmin' channel - @{ - Channel = 'botadmin' - IncludeCommands = @('builtin:*') - ExcludeCommands = @() - } - # Exclude builtin commands from any "projectX" channel - @{ - Channel = '*projectx*' - IncludeCommands = @('*') - ExcludeCommands = @('builtin:*') - } - # It's the wild west in random, except giphy :) - @{ - Channel = 'random' - IncludeCommands = @('*') - ExcludeCommands = @('*giphy*') - } - # All commands are otherwise allowed - @{ - Channel = '*' - IncludeCommands = @('*') - ExcludeCommands = @() - } -) - -```yaml -Type: Hashtable[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 25 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PreReceiveMiddlewareHooks -Array of middleware scriptblocks that will run before PoshBot "receives" the message from the backend implementation. -This middleware will receive the original message sent from the chat network and have a chance to modify, analyze, and optionally drop the message before PoshBot continues processing it. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 26 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PostReceiveMiddlewareHooks -Array of middleware scriptblocks that will run after a message is "received" from the backend implementation. -This middleware runs after messages have been parsed and matched with a registered command in PoshBot. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 27 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PreExecuteMiddlewareHooks -Array of middleware scriptblocks that will run before a command is executed. -This middleware is a good spot to run extra authentication or validation processes before commands are executed. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 28 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PostExecuteMiddlewareHooks -Array of middleware scriptblocks that will run after PoshBot commands have been executed. -This middleware is a good spot for custom logging solutions to write command history to a custom location. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 29 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PreResponseMiddlewareHooks -Array of middleware scriptblocks that will run before command responses are sent to the backend implementation. -This middleware is a good spot for modifying or sanitizing responses before they are sent to the chat network. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 30 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PostResponseMiddlewareHooks -Array of middleware scriptblocks that will run after command responses have been sent to the backend implementation. -This middleware runs after all processing is complete for a command and is a good spot for additional custom logging. - -```yaml -Type: MiddlewareHook[] -Parameter Sets: (All) -Aliases: - -Required: False -Position: 31 -Default value: @() -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -### BotConfiguration -## NOTES - -## RELATED LINKS - -[Get-PoshBotConfiguration]() - -[Save-PoshBotConfiguration]() - -[New-PoshBotInstance]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/new-poshbotinstance.md b/docs/reference/functions/new-poshbotinstance.md deleted file mode 100644 index 756c54a..0000000 --- a/docs/reference/functions/new-poshbotinstance.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotInstance - -## SYNOPSIS -Creates a new instance of PoshBot - -## SYNTAX - -### path (Default) -``` -New-PoshBotInstance -Backend [] -``` - -### Path -``` -New-PoshBotInstance [-Path] -Backend [] -``` - -### LiteralPath -``` -New-PoshBotInstance [-LiteralPath] -Backend [] -``` - -### config -``` -New-PoshBotInstance -Configuration -Backend [] -``` - -## DESCRIPTION -Creates a new instance of PoshBot from an existing configuration (.psd1) file or a configuration object. - -## EXAMPLES - -### EXAMPLE 1 -``` -New-PoshBotInstance -Path 'C:\Users\joeuser\.poshbot\Cherry2000.psd1' -Backend $backend -``` - -Name : Cherry2000 -Backend : SlackBackend -Storage : StorageProvider -PluginManager : PluginManager -RoleManager : RoleManager -Executor : CommandExecutor -MessageQueue : {} -Configuration : BotConfiguration - -Create a new PoshBot instance from configuration file \[C:\Users\joeuser\.poshbot\Cherry2000.psd1\] and Slack backend object \[$backend\]. - -### EXAMPLE 2 -``` -$botConfig = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\Cherry2000.psd1') -PS C:\> $backend = New-PoshBotSlackBackend -Configuration $botConfig.BackendConfiguration -PS C:\> $myBot = $botConfig | New-PoshBotInstance -Backend $backend -PS C:\> $myBot | Format-List -``` - -Name : Cherry2000 -Backend : SlackBackend -Storage : StorageProvider -PluginManager : PluginManager -RoleManager : RoleManager -Executor : CommandExecutor -MessageQueue : {} -Configuration : BotConfiguration - -Gets a bot configuration from the filesytem, creates a chat backend object, and then creates a new bot instance. - -### EXAMPLE 3 -``` -$botConfig = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\Cherry2000.psd1') -PS C:\> $backend = $botConfig | New-PoshBotSlackBackend -PS C:\> $myBotJob = $botConfig | New-PoshBotInstance -Backend $backend | Start-PoshBot -AsJob -PassThru -``` - -Gets a bot configuration, creates a Slack backend from it, then creates a new PoshBot instance and starts it as a background job. - -## PARAMETERS - -### -Path -The path to a PowerShell data (.psd1) file to create a new instance from. - -```yaml -Type: String[] -Parameter Sets: Path -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` - -### -LiteralPath -Specifies the path(s) to the current location of the file(s). -Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation -marks tell PowerShell not to interpret any characters as escape sequences. - -```yaml -Type: String[] -Parameter Sets: LiteralPath -Aliases: PSPath - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName) -Accept wildcard characters: False -``` - -### -Configuration -The bot configuration object to create a new instance from. - -```yaml -Type: BotConfiguration[] -Parameter Sets: config -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -Backend -The backend object that hosts logic for receiving and sending messages to a chat network. - -```yaml -Type: Backend -Parameter Sets: (All) -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String -### BotConfiguration -## OUTPUTS - -### Bot -## NOTES - -## RELATED LINKS - -[Get-PoshBotConfiguration]() - -[New-PoshBotSlackBackend]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/new-poshbotscheduledtask.md b/docs/reference/functions/new-poshbotscheduledtask.md deleted file mode 100644 index 3f1c8e4..0000000 --- a/docs/reference/functions/new-poshbotscheduledtask.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotScheduledTask - -## SYNOPSIS -Creates a new scheduled task to run PoshBot in the background. - -## SYNTAX - -``` -New-PoshBotScheduledTask [[-Name] ] [[-Description] ] [-Path] - [-Credential] [-PassThru] [-Force] [-WhatIf] [-Confirm] [] -``` - -## DESCRIPTION -Creates a new scheduled task to run PoshBot in the background. -The scheduled task will always be configured -to run on startup and to not stop after any time period. - -## EXAMPLES - -### EXAMPLE 1 -``` -$cred = Get-Credential -PS C:\> New-PoshBotScheduledTask -Name PoshBot -Path C:\PoshBot\myconfig.psd1 -Credential $cred -``` - -Creates a new scheduled task to start PoshBot using the configuration file located at C:\PoshBot\myconfig.psd1 -and the specified credential. - -### EXAMPLE 2 -``` -$cred = Get-Credential -PC C:\> $params = @{ - Name = 'PoshBot' - Path = 'C:\PoshBot\myconfig.psd1' - Credential = $cred - Description = 'Awesome ChatOps bot' - PassThru = $true -} -PS C:\> $task = New-PoshBotScheduledTask @params -PS C:\> $task | Start-ScheduledTask -``` - -Creates a new scheduled task to start PoshBot using the configuration file located at C:\PoshBot\myconfig.psd1 -and the specified credential then starts the task. - -## PARAMETERS - -### -Name -The name for the scheduled task - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: PoshBot -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Description -The description for the scheduled task - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: Start PoshBot -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -The path to the PoshBot configuration file to load and execute - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 3 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Credential -The credential to run the scheduled task under. - -```yaml -Type: PSCredential -Parameter Sets: (All) -Aliases: - -Required: True -Position: 4 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PassThru -Return the newly created scheduled task object - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Overwrite a previously created scheduled task - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -### Microsoft.Management.Infrastructure.CimInstance#root/Microsoft/Windows/TaskScheduler/MSFT_ScheduledTask -## NOTES - -## RELATED LINKS - -[Get-PoshBotConfiguration]() - -[New-PoshBotConfiguration]() - -[Save-PoshBotConfiguration]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/new-poshbotslackbackend.md b/docs/reference/functions/new-poshbotslackbackend.md deleted file mode 100644 index 3b49aed..0000000 --- a/docs/reference/functions/new-poshbotslackbackend.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotSlackBackend - -## SYNOPSIS -Create a new instance of a Slack backend - -## SYNTAX - -``` -New-PoshBotSlackBackend [-Configuration] [] -``` - -## DESCRIPTION -Create a new instance of a Slack backend - -## EXAMPLES - -### EXAMPLE 1 -``` -$backendConfig = @{Name = 'SlackBackend'; Token = ''} -PS C:\> $backend = New-PoshBotSlackBackend -Configuration $backendConfig -``` - -Create a Slack backend using the specified API token - -## PARAMETERS - -### -Configuration -The hashtable containing backend-specific properties on how to create the Slack backend instance. - -```yaml -Type: Hashtable[] -Parameter Sets: (All) -Aliases: BackendConfiguration - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Hashtable -## OUTPUTS - -### SlackBackend -## NOTES - -## RELATED LINKS diff --git a/docs/reference/functions/new-poshbottextresponse.md b/docs/reference/functions/new-poshbottextresponse.md deleted file mode 100644 index 2f783ab..0000000 --- a/docs/reference/functions/new-poshbottextresponse.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# New-PoshBotTextResponse - -## SYNOPSIS -Tells PoshBot to handle the text response from a command in a special way. - -## SYNTAX - -``` -New-PoshBotTextResponse [-Text] [-AsCode] [-DM] [] -``` - -## DESCRIPTION -Responses from PoshBot commands can be sent back to the channel they were posted from (default) or redirected to a DM channel with the -calling user. -This could be useful if the contents the bot command returns are sensitive and should not be visible to all users -in the channel. - -## EXAMPLES - -### EXAMPLE 1 -``` -function Get-Foo { - [cmdletbinding()] - param( - [parameter(mandatory)] - [string]$MyParam - ) -``` - -New-PoshBotTextResponse -Text $MyParam -DM -} - -When Get-Foo is executed by PoshBot, the text response will be sent back to the calling user as a DM rather than back in the channel the -command was called from. -This could be useful if the contents the bot command returns are sensitive and should not be visible to all users -in the channel. - -## PARAMETERS - -### -Text -The text response from the command. - -```yaml -Type: String[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -AsCode -Format the text in a code block if the backend supports it. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -DM -Tell PoshBot to redirect the response to a DM channel. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### String -## OUTPUTS - -### PSCustomObject -## NOTES - -## RELATED LINKS - -[New-PoshBotCardResponse]() - diff --git a/docs/reference/functions/save-poshbotconfiguration.md b/docs/reference/functions/save-poshbotconfiguration.md deleted file mode 100644 index 407b386..0000000 --- a/docs/reference/functions/save-poshbotconfiguration.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Save-PoshBotConfiguration - -## SYNOPSIS -Saves a PoshBot configuration object to the filesystem in the form of a PowerShell data (.psd1) file. - -## SYNTAX - -``` -Save-PoshBotConfiguration [-InputObject] [[-Path] ] [-Force] [-PassThru] [-WhatIf] - [-Confirm] [] -``` - -## DESCRIPTION -PoshBot configurations can be stored on the filesytem in PowerShell data (.psd1) files. -This function will save a previously created configuration object to the filesystem. - -## EXAMPLES - -### EXAMPLE 1 -``` -Save-PoshBotConfiguration -InputObject $botConfig -``` - -Saves the PoshBot configuration. -If now -Path is specified, the configuration will be saved to $env:USERPROFILE\.poshbot\PoshBot.psd1. - -### EXAMPLE 2 -``` -$botConfig | Save-PoshBotConfig -Path c:\mybot\mybot.psd1 -``` - -Saves the PoshBot configuration to \[c:\mybot\mybot.psd1\]. - -### EXAMPLE 3 -``` -$configFile = $botConfig | Save-PoshBotConfig -Path c:\mybot\mybot.psd1 -Force -PassThru -``` - -Saves the PoshBot configuration to \[c:\mybot\mybot.psd1\] and Overwrites existing file. -The new file will be returned. - -## PARAMETERS - -### -InputObject -The bot configuration object to save to the filesystem. - -```yaml -Type: BotConfiguration -Parameter Sets: (All) -Aliases: Configuration - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -Path -The path to a PowerShell data (.psd1) file to save the configuration to. - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: 2 -Default value: (Join-Path -Path $script:defaultPoshBotDir -ChildPath 'PoshBot.psd1') -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Force -Overwrites an existing configuration file. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PassThru -Returns the configuration file path. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### BotConfiguration -## OUTPUTS - -### System.IO.FileInfo -## NOTES - -## RELATED LINKS - -[Get-PoshBotConfiguration]() - -[Start-PoshBot]() - diff --git a/docs/reference/functions/start-poshbot.md b/docs/reference/functions/start-poshbot.md deleted file mode 100644 index d3775e2..0000000 --- a/docs/reference/functions/start-poshbot.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: poshbot -online version: -schema: 2.0.0 ---- - -# Start-PoshBot - -## SYNOPSIS -Starts a new instance of PoshBot interactively or in a job. - -## SYNTAX - -### bot (Default) -``` -Start-PoshBot -InputObject [-AsJob] [-PassThru] [] -``` - -### config -``` -Start-PoshBot -Configuration [-AsJob] [-PassThru] [] -``` - -### path -``` -Start-PoshBot -Path [-AsJob] [-PassThru] [] -``` - -## DESCRIPTION -Starts a new instance of PoshBot interactively or in a job. - -## EXAMPLES - -### EXAMPLE 1 -``` -Start-PoshBot -Bot $bot -``` - -Runs an instance of PoshBot that has already been created interactively in the shell. - -### EXAMPLE 2 -``` -$bot | Start-PoshBot -Verbose -``` - -Runs an instance of PoshBot that has already been created interactively in the shell. - -### EXAMPLE 3 -``` -$config = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\MyPoshBot.psd1') -PS C:\> Start-PoshBot -Config $config -``` - -Gets a PoshBot configuration from file and starts the bot interactively. - -### EXAMPLE 4 -``` -Get-PoshBot -Id 100 -``` - -Id : 100 -Name : PoshBot_eab96f2ad147489b9f90e110e02ad805 -State : Running -InstanceId : eab96f2ad147489b9f90e110e02ad805 -Config : BotConfiguration - -Gets the PoshBot job instance with ID 100. - -## PARAMETERS - -### -InputObject -An existing PoshBot instance to start. - -```yaml -Type: Bot -Parameter Sets: bot -Aliases: Bot - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: False -``` - -### -Configuration -A PoshBot configuration object to use to start the bot instance. - -```yaml -Type: BotConfiguration -Parameter Sets: config -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: False -``` - -### -Path -The path to a PoshBot configuration file. -A new instance of PoshBot will be created from this file. - -```yaml -Type: String -Parameter Sets: path -Aliases: - -Required: True -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -AsJob -Run the PoshBot instance in a background job. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -PassThru -Return the PoshBot instance Id that is running as a job. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### Bot -### BotConfiguration -### String -## OUTPUTS - -### PSCustomObject -## NOTES - -## RELATED LINKS - -[Start-PoshBot]() - -[Stop-PoshBot]() - diff --git a/docs/reference/functions/stop-poshbot.md b/docs/reference/functions/stop-poshbot.md deleted file mode 100644 index 045ee3e..0000000 --- a/docs/reference/functions/stop-poshbot.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -external help file: PoshBot-help.xml -Module Name: PoshBot -online version: -schema: 2.0.0 ---- - -# Stop-Poshbot - -## SYNOPSIS -Stop a currently running PoshBot instance that is running as a background job. - -## SYNTAX - -``` -Stop-Poshbot [-Id] [-Force] [-WhatIf] [-Confirm] [] -``` - -## DESCRIPTION -PoshBot can be run in the background with PowerShell jobs. -This function stops -a currently running PoshBot instance. - -## EXAMPLES - -### EXAMPLE 1 -``` -Stop-PoshBot -Id 101 -``` - -Stop the bot instance with Id 101. - -### EXAMPLE 2 -``` -Get-PoshBot | Stop-PoshBot -``` - -Gets all running PoshBot instances and stops them. - -## PARAMETERS - -### -Id -The job Id of the bot to stop. - -```yaml -Type: Int32[] -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False -``` - -### -Force -Stop PoshBot instance without prompt - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -### System.Int32 -## OUTPUTS - -## NOTES - -## RELATED LINKS - -[Get-PoshBot]() - -[Start-PoshBot]() - From 4c311900a553bcdd629a65c1437ecb1cc0ceb3da Mon Sep 17 00:00:00 2001 From: Andriy Golubenkov FUIB VM Date: Tue, 21 May 2024 11:05:37 +0300 Subject: [PATCH 4/6] Teams Offline cache and users Load() --- .../Implementations/Teams/TeamsBackend.ps1 | 261 ++++--- docs/reference/functions/Get-PoshBot.md | 83 ++ .../functions/Get-PoshBotConfiguration.md | 115 +++ .../functions/Get-PoshBotStatefulData.md | 105 +++ .../functions/New-PoshBotCardResponse.md | 267 +++++++ .../functions/New-PoshBotConfiguration.md | 729 ++++++++++++++++++ .../functions/New-PoshBotDiscordBackend.md | 66 ++ .../functions/New-PoshBotFileUpload.md | 249 ++++++ .../functions/New-PoshBotInstance.md | 172 +++++ .../functions/New-PoshBotMiddlewareHook.md | 80 ++ .../functions/New-PoshBotScheduledTask.md | 197 +++++ .../functions/New-PoshBotSlackBackend.md | 61 ++ .../functions/New-PoshBotTeamsBackend.md | 71 ++ .../functions/New-PoshBotTextResponse.md | 122 +++ docs/reference/functions/PoshBot.md | 67 ++ .../functions/Remove-PoshBotStatefulData.md | 136 ++++ .../functions/Save-PoshBotConfiguration.md | 158 ++++ .../functions/Set-PoshBotStatefulData.md | 155 ++++ docs/reference/functions/Start-PoshBot.md | 167 ++++ docs/reference/functions/Stop-Poshbot.md | 118 +++ psakeFile.ps1 | 1 + 21 files changed, 3259 insertions(+), 121 deletions(-) create mode 100644 docs/reference/functions/Get-PoshBot.md create mode 100644 docs/reference/functions/Get-PoshBotConfiguration.md create mode 100644 docs/reference/functions/Get-PoshBotStatefulData.md create mode 100644 docs/reference/functions/New-PoshBotCardResponse.md create mode 100644 docs/reference/functions/New-PoshBotConfiguration.md create mode 100644 docs/reference/functions/New-PoshBotDiscordBackend.md create mode 100644 docs/reference/functions/New-PoshBotFileUpload.md create mode 100644 docs/reference/functions/New-PoshBotInstance.md create mode 100644 docs/reference/functions/New-PoshBotMiddlewareHook.md create mode 100644 docs/reference/functions/New-PoshBotScheduledTask.md create mode 100644 docs/reference/functions/New-PoshBotSlackBackend.md create mode 100644 docs/reference/functions/New-PoshBotTeamsBackend.md create mode 100644 docs/reference/functions/New-PoshBotTextResponse.md create mode 100644 docs/reference/functions/PoshBot.md create mode 100644 docs/reference/functions/Remove-PoshBotStatefulData.md create mode 100644 docs/reference/functions/Save-PoshBotConfiguration.md create mode 100644 docs/reference/functions/Set-PoshBotStatefulData.md create mode 100644 docs/reference/functions/Start-PoshBot.md create mode 100644 docs/reference/functions/Stop-Poshbot.md diff --git a/PoshBot/Implementations/Teams/TeamsBackend.ps1 b/PoshBot/Implementations/Teams/TeamsBackend.ps1 index 09104ab..fdfa3ac 100644 --- a/PoshBot/Implementations/Teams/TeamsBackend.ps1 +++ b/PoshBot/Implementations/Teams/TeamsBackend.ps1 @@ -9,12 +9,12 @@ class TeamsBackend : Backend { 'message' ) - [string]$TeamId = $null + [string]$TeamId = $null [string]$ServiceUrl = 'https://smba.trafficmanager.net/amer/' - [string]$BotId = $null - [string]$BotName = $null - [string]$TenantId = $null - [bool]$Initialized = $false + [string]$BotId = $null + [string]$BotName = $null + [string]$TenantId = $null + [bool]$Initialized = $false [hashtable]$DMConverations = @{} @@ -72,7 +72,7 @@ class TeamsBackend : Backend { $msg.RawMessage = $teamsMessage $this.LogDebug('Raw message', $teamsMessage) - if ($teamsMessage.text) { + if ($teamsMessage.text) { # When commands are directed to PoshBot, the bot must be "at" mentioned. # This will show up in the text of the message received. We don't need it so strip it out. $msg.Text = $teamsMessage.text.Replace("$($this.Connection.Config.BotName) ", '') -Replace '\n', '' @@ -82,7 +82,7 @@ class TeamsBackend : Backend { } if ($teamsMessage.from) { - $msg.From = $teamsMessage.from.id + $msg.From = $teamsMessage.from.id $msg.FromName = $teamsMessage.from.name } @@ -127,14 +127,14 @@ class TeamsBackend : Backend { # Send a message [void]SendMessage([Response]$Response) { - $baseUrl = $Response.OriginalMessage.RawMessage.serviceUrl - $fromId = $Response.OriginalMessage.RawMessage.from.id - $fromName = $Response.OriginalMessage.RawMessage.from.name - $recipientId = $Response.OriginalMessage.RawMessage.recipient.id - $recipientName = $Response.OriginalMessage.RawMessage.recipient.name + $baseUrl = $Response.OriginalMessage.RawMessage.serviceUrl + $fromId = $Response.OriginalMessage.RawMessage.from.id + $fromName = $Response.OriginalMessage.RawMessage.from.name + $recipientId = $Response.OriginalMessage.RawMessage.recipient.id + $recipientName = $Response.OriginalMessage.RawMessage.recipient.name $conversationId = $Response.OriginalMessage.RawMessage.conversation.id - $activityId = $Response.OriginalMessage.RawMessage.id - $responseUrl = "$($baseUrl)v3/conversations/$conversationId/activities/$activityId" + $activityId = $Response.OriginalMessage.RawMessage.id + $responseUrl = "$($baseUrl)v3/conversations/$conversationId/activities/$activityId" $headers = @{ Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" } @@ -159,26 +159,26 @@ class TeamsBackend : Backend { $this.LogDebug('Custom response is [PoshBot.Card.Response]') $cardBody = @{ - type = 'message' - from = @{ + type = 'message' + from = @{ id = $fromId name = $fromName } conversation = @{ id = $conversationId } - recipient = @{ - id = $recipientId + recipient = @{ + id = $recipientId name = $recipientName } - attachments = @( + attachments = @( @{ contentType = 'application/vnd.microsoft.teams.card.o365connector' - content = @{ - "@type" = 'MessageCard' - "@context" = 'http://schema.org/extensions' + content = @{ + '@type' = 'MessageCard' + '@context' = 'http://schema.org/extensions' themeColor = $customResponse.Color -replace '#', '' - sections = @( + sections = @( @{ } @@ -186,7 +186,7 @@ class TeamsBackend : Backend { } } ) - replyToId = $activityId + replyToId = $activityId } # Thumbnail @@ -216,7 +216,7 @@ class TeamsBackend : Backend { $cardBody.attachments[0].content.sections[0].facts = @() foreach ($field in $customResponse.Fields.GetEnumerator()) { $cardBody.attachments[0].content.sections[0].facts += @{ - name = $field.Name + name = $field.Name value = $field.Value.ToString() } } @@ -265,20 +265,20 @@ class TeamsBackend : Backend { } $cardBody = @{ - type = 'message' - from = @{ + type = 'message' + from = @{ id = $fromId name = $fromName } conversation = @{ id = $conversationId } - recipient = @{ - id = $recipientId + recipient = @{ + id = $recipientId name = $recipientName } - text = $cardText - textFormat = $textFormat + text = $cardText + textFormat = $textFormat # attachments = @( # @{ # contentType = 'application/vnd.microsoft.teams.card.o365connector' @@ -290,7 +290,7 @@ class TeamsBackend : Backend { # } # } # ) - replyToId = $activityId + replyToId = $activityId } $body = $cardBody | ConvertTo-Json -Depth 15 @@ -319,21 +319,21 @@ class TeamsBackend : Backend { # Teams doesn't support generic file uploads yet :( # Send a message informing the user of this sad fact $jsonResponse = @{ - type = 'message' - from = @{ - id = $recipientId + type = 'message' + from = @{ + id = $recipientId name = $recipientName } conversation = @{ - id = $conversationId + id = $conversationId name = '' } - recipient = @{ - id = $fromId + recipient = @{ + id = $fromId name = $fromName } - text = "I don't know how to upload files to Teams yet but I'm learning." - replyToId = $activityId + text = "I don't know how to upload files to Teams yet but I'm learning." + replyToId = $activityId } | ConvertTo-Json # $jsonResponse | Out-File -FilePath "$script:moduleBase/responses.json" -Append @@ -538,51 +538,70 @@ class TeamsBackend : Backend { # Populate the list of users the team [void]LoadUsers() { if (-not [string]::IsNullOrEmpty($this.ServiceUrl)) { - $this.LogDebug('Getting Teams users') + $this.LogInfo('Getting Teams users') + #Load Members from Teams $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/pagedmembers?pageSize=500" $headers = @{ Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" } - $members = @() - do { - $Results = '' - $StatusCode = '' - do { - try { - $Results = Invoke-RestMethod -Headers $headers -Uri $Uri -UseBasicParsing -Method 'GET' -ContentType 'application/json' + #Load Members from Cached File - $StatusCode = $Results.StatusCode - } catch { - $StatusCode = $_.Exception.Response.StatusCode.value__ + $poshBotDirTeams = Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot.teams' + $OfflineTeamsUsersFileName = 'OfflineTeamsUsers.xml' + $offlineTeamsUsersFile = Join-Path $poshBotDirTeams $OfflineTeamsUsersFileName - if ($StatusCode -eq 429) { - $this.LogDebug('Got throttled by Microsoft. Sleeping for 45 seconds...') - Start-Sleep -Seconds 45 - } else { - $this.LogDebug("Error Populating the list of users for the team: $($_.Exception.Message)") + if ((Test-Path $offlineTeamsUsersFile ) -and ((Get-ChildItem $offlineTeamsUsersFile).LastWriteTime -gt $(Get-Date).AddDays(-7)) -and ((Get-ChildItem $offlineTeamsUsersFile).Length -gt 1024)) { + #if (Test-Path $offlineTeamsUsersFile ) { + $this.LogInfo('[Teams] Getting Users (XML) - OFFLINE') + $members = @() + $members = Import-Clixml $offlineTeamsUsersFile + } else { + $this.LogInfo('[Teams] Getting Users (Teams) - Online') + + $members = @() + do { + $Results = '' + $StatusCode = '' + do { + try { + $Results = Invoke-RestMethod -Headers $headers -Uri $Uri -UseBasicParsing -Method 'GET' -ContentType 'application/json' + + $StatusCode = $Results.StatusCode + } catch { + $StatusCode = $_.Exception.Response.StatusCode.value__ + + if ($StatusCode -eq 429) { + $this.LogDebug('Got throttled by Microsoft. Sleeping for 45 seconds...') + Start-Sleep -Seconds 45 + } else { + $this.LogDebug("Error Populating the list of users for the team: $($_.Exception.Message)") + } } + } while ($StatusCode -eq 429) + if ($Results.continuationToken) { + $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/pagedmembers?pageSize=500&continuationToken=$($Results.continuationToken)" + $members += $Results.members + } else { + $members += $Results.members } - } while ($StatusCode -eq 429) - if ($Results.continuationToken) { - $uri = "$($this.ServiceUrl)v3/conversations/$($this.TeamId)/pagedmembers?pageSize=500&continuationToken=$($Results.continuationToken)" - $members += $Results.members - } else { - $members += $Results.members - } - } while ($Results.continuationToken) + } while ($Results.continuationToken) + $members | Export-Clixml $offlineTeamsUsersFile + } + + $this.LogInfo('[Teams] Users: ' + $members.count) $this.LogDebug('Finished getting Teams users') $members | ForEach-Object { $user = [TeamsPerson]::new() - $user.Id = $_.id - $user.FirstName = $_.givenName - $user.LastName = $_.surname - $user.NickName = $_.userPrincipalName - $user.FullName = "$($_.givenName) $($_.surname)" - $user.Email = $_.email + $user.Id = $_.id + $user.FirstName = $_.givenName + $user.LastName = $_.surname + $user.NickName = $_.userPrincipalName + $user.FullName = "$($_.givenName) $($_.surname)" + $user.Email = $_.email $user.UserPrincipalName = $_.userPrincipalName if (-not $this.Users.ContainsKey($_.ID)) { @@ -603,30 +622,30 @@ class TeamsBackend : Backend { # Populate the list of channels in the team [void]LoadRooms() { #if (-not [string]::IsNullOrEmpty($this.TeamId)) { - $this.LogDebug('Getting Teams channels') + $this.LogDebug('Getting Teams channels') - $uri = "$($this.ServiceUrl)v3/teams/$($this.TeamId)/conversations" - $headers = @{ - Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" + $uri = "$($this.ServiceUrl)v3/teams/$($this.TeamId)/conversations" + $headers = @{ + Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" + } + $channels = Invoke-RestMethod -Uri $uri -Headers $headers + + if ($channels.conversations) { + $channels.conversations | ForEach-Object { + $channel = [TeamsChannel]::new() + $channel.Id = $_.id + $channel.Name = $_.name + $this.LogDebug("Adding channel: $($_.id):$($_.name)") + $this.Rooms[$_.id] = $channel } - $channels = Invoke-RestMethod -Uri $uri -Headers $headers - - if ($channels.conversations) { - $channels.conversations | ForEach-Object { - $channel = [TeamsChannel]::new() - $channel.Id = $_.id - $channel.Name = $_.name - $this.LogDebug("Adding channel: $($_.id):$($_.name)") - $this.Rooms[$_.id] = $channel - } - foreach ($key in $this.Rooms.Keys) { - if ($key -notin $channels.conversations.ID) { - $this.LogDebug("Removing outdated channel [$key]") - $this.Rooms.Remove($key) - } + foreach ($key in $this.Rooms.Keys) { + if ($key -notin $channels.conversations.ID) { + $this.LogDebug("Removing outdated channel [$key]") + $this.Rooms.Remove($key) } } + } #} } @@ -654,7 +673,7 @@ class TeamsBackend : Backend { # Get a user Id by their name [string]UsernameToUserId([string]$Username) { $Username = $Username.TrimStart('@') - $user = $this.Users.Values | Where-Object {$_.Nickname -eq $Username} + $user = $this.Users.Values | Where-Object { $_.Nickname -eq $Username } $id = $null if ($user) { $id = $user.Id @@ -663,7 +682,7 @@ class TeamsBackend : Backend { # Refresh it and try again $this.LogDebug([LogSeverity]::Warning, "User [$Username] not found. Refreshing users") $this.LoadUsers() - $user = $this.Users.Values | Where-Object {$_.Nickname -eq $Username} + $user = $this.Users.Values | Where-Object { $_.Nickname -eq $Username } if (-not $user) { $id = $null } else { @@ -761,7 +780,7 @@ class TeamsBackend : Backend { if ([string]::IsNullOrEmpty($this.BotId)) { if ($Message.recipient) { - $this.BotId = $Message.recipient.Id + $this.BotId = $Message.recipient.Id $this.BotName = $Message.recipient.name } } @@ -776,10 +795,10 @@ class TeamsBackend : Backend { } hidden [void]SendTeamsMessaage([Response]$Response) { - $baseUrl = $Response.OriginalMessage.RawMessage.serviceUrl + $baseUrl = $Response.OriginalMessage.RawMessage.serviceUrl $conversationId = $Response.OriginalMessage.RawMessage.conversation.id - $activityId = $Response.OriginalMessage.RawMessage.id - $responseUrl = "$($baseUrl)v3/conversations/$conversationId/activities/$activityId" + $activityId = $Response.OriginalMessage.RawMessage.id + $responseUrl = "$($baseUrl)v3/conversations/$conversationId/activities/$activityId" $headers = @{ Authorization = "Bearer $($this.Connection._AccessTokenInfo.access_token)" } @@ -787,21 +806,21 @@ class TeamsBackend : Backend { if ($Response.Text.Count -gt 0) { foreach ($text in $Response.Text) { $jsonResponse = @{ - type = 'message' - from = @{ - id = $Response.OriginalMessage.RawMessage.recipient.id + type = 'message' + from = @{ + id = $Response.OriginalMessage.RawMessage.recipient.id name = $Response.OriginalMessage.RawMessage.recipient.name } conversation = @{ - id = $Response.OriginalMessage.RawMessage.conversation.id + id = $Response.OriginalMessage.RawMessage.conversation.id name = '' } - recipient = @{ - id = $Response.OriginalMessage.RawMessage.from.id + recipient = @{ + id = $Response.OriginalMessage.RawMessage.from.id name = $Response.OriginalMessage.RawMessage.from.name } - text = $text - replyToId = $activityId + text = $text + replyToId = $activityId } | ConvertTo-Json # $jsonResponse | Out-File -FilePath "$script:moduleBase/responses.json" -Append @@ -834,11 +853,11 @@ class TeamsBackend : Backend { } $conversationParams = @{ - bot = @{ - id = $this.BotId + bot = @{ + id = $this.BotId name = $this.BotName } - members = @( + members = @( @{ id = $UserId } @@ -872,8 +891,8 @@ class TeamsBackend : Backend { hidden [hashtable]_GetCardStub() { return @{ - type = 'message' - from = @{ + type = 'message' + from = @{ id = $null name = $null } @@ -881,37 +900,37 @@ class TeamsBackend : Backend { id = $null #name = '' } - recipient = @{ - id = $null + recipient = @{ + id = $null name = $null } - attachments = @( + attachments = @( @{ contentType = 'application/vnd.microsoft.card.adaptive' - content = @{ - type = 'AdaptiveCard' - version = '1.0' + content = @{ + type = 'AdaptiveCard' + version = '1.0' fallbackText = $null - body = @( + body = @( @{ - type = 'Container' + type = 'Container' spacing = 'none' - items = @( + items = @( # # Title & Thumbnail row @{ - type = 'ColumnSet' + type = 'ColumnSet' spacing = 'none' columns = @() } # Text & image row @{ - type = 'ColumnSet' + type = 'ColumnSet' spacing = 'none' columns = @() } # Facts row @{ - type = 'FactSet' + type = 'FactSet' facts = @() } ) @@ -920,7 +939,7 @@ class TeamsBackend : Backend { } } ) - replyToId = $null + replyToId = $null } } diff --git a/docs/reference/functions/Get-PoshBot.md b/docs/reference/functions/Get-PoshBot.md new file mode 100644 index 0000000..d97cef1 --- /dev/null +++ b/docs/reference/functions/Get-PoshBot.md @@ -0,0 +1,83 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Get-PoshBot + +## SYNOPSIS +Gets any currently running instances of PoshBot that are running as background jobs. + +## SYNTAX + +``` +Get-PoshBot [[-Id] ] [] +``` + +## DESCRIPTION +PoshBot can be run in the background with PowerShell jobs. +This function returns +any currently running PoshBot instances. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-PoshBot +``` + +Id : 5 +Name : PoshBot_3ddfc676406d40fca149019d935f065d +State : Running +InstanceId : 3ddfc676406d40fca149019d935f065d +Config : BotConfiguration + +### EXAMPLE 2 +``` +Get-PoshBot -Id 100 +``` + +Id : 100 +Name : PoshBot_eab96f2ad147489b9f90e110e02ad805 +State : Running +InstanceId : eab96f2ad147489b9f90e110e02ad805 +Config : BotConfiguration + +Gets the PoshBot job instance with ID 100. + +## PARAMETERS + +### -Id +One or more job IDs to retrieve. + +```yaml +Type: Int32[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: @() +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Int32 +## OUTPUTS + +### PSCustomObject +## NOTES + +## RELATED LINKS + +[Start-PoshBot]() + +[Stop-PoshBot]() + diff --git a/docs/reference/functions/Get-PoshBotConfiguration.md b/docs/reference/functions/Get-PoshBotConfiguration.md new file mode 100644 index 0000000..40bc25e --- /dev/null +++ b/docs/reference/functions/Get-PoshBotConfiguration.md @@ -0,0 +1,115 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Get-PoshBotConfiguration + +## SYNOPSIS +Gets a PoshBot configuration from a file. + +## SYNTAX + +### Path (Default) +``` +Get-PoshBotConfiguration [-Path] [] +``` + +### LiteralPath +``` +Get-PoshBotConfiguration [-LiteralPath] [] +``` + +## DESCRIPTION +PoshBot configurations can be stored on the filesytem in PowerShell data (.psd1) files. +This functions will load that file and return a \[BotConfiguration\] object. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-PoshBotConfiguration -Path C:\Users\joeuser\.poshbot\Cherry2000.psd1 +``` + +Name : Cherry2000 +ConfigurationDirectory : C:\Users\joeuser\.poshbot +LogDirectory : C:\Users\joeuser\.poshbot\Logs +PluginDirectory : C:\Users\joeuser\.poshbot +PluginRepository : {PSGallery} +ModuleManifestsToLoad : {} +LogLevel : Debug +BackendConfiguration : {Token, Name} +PluginConfiguration : {} +BotAdmins : {joeuser} +CommandPrefix : ! +AlternateCommandPrefixes : {bender, hal} +AlternateCommandPrefixSeperators : {:, ,, ;} +SendCommandResponseToPrivate : {} +MuteUnknownCommand : False +AddCommandReactions : True + +Gets the bot configuration located at \[C:\Users\joeuser\.poshbot\Cherry2000.psd1\]. + +### EXAMPLE 2 +``` +$botConfig = 'C:\Users\joeuser\.poshbot\Cherry2000.psd1' | Get-PoshBotConfiguration +``` + +Gets the bot configuration located at \[C:\Users\brand\.poshbot\Cherry2000.psd1\]. + +## PARAMETERS + +### -Path +One or more paths to a PoshBot configuration file. + +```yaml +Type: String[] +Parameter Sets: Path +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: True +``` + +### -LiteralPath +Specifies the path(s) to the current location of the file(s). +Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. +No characters are interpreted as wildcards. +If the path includes escape characters, enclose it in single quotation marks. +Single quotation +marks tell PowerShell not to interpret any characters as escape sequences. + +```yaml +Type: String[] +Parameter Sets: LiteralPath +Aliases: PSPath + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### String +## OUTPUTS + +### BotConfiguration +## NOTES + +## RELATED LINKS + +[New-PoshBotConfiguration]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/Get-PoshBotStatefulData.md b/docs/reference/functions/Get-PoshBotStatefulData.md new file mode 100644 index 0000000..511969c --- /dev/null +++ b/docs/reference/functions/Get-PoshBotStatefulData.md @@ -0,0 +1,105 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Get-PoshBotStatefulData + +## SYNOPSIS +Get stateful data previously exported from a PoshBot command + +## SYNTAX + +``` +Get-PoshBotStatefulData [[-Name] ] [-ValueOnly] [[-Scope] ] [] +``` + +## DESCRIPTION +Get stateful data previously exported from a PoshBot command + +Reads data from the PoshBot ConfigurationDirectory. + +## EXAMPLES + +### EXAMPLE 1 +``` +$ModuleData = Get-PoshBotStatefulData +``` + +Get all stateful data for the PoshBot plugin this runs from + +### EXAMPLE 2 +``` +$Something = Get-PoshBotStatefulData -Name 'Something' -ValueOnly -Scope Global +``` + +Set $Something to the value of the 'Something' property from Poshbot's global stateful data + +## PARAMETERS + +### -Name +If specified, retrieve only this property from the stateful data + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: * +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ValueOnly +If specified, return only the value of the specified property Name + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +Get stateful data from this scope: + Module: Data scoped to this plugin + Global: Data available to any Poshbot plugin + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Module +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Set-PoshBotStatefulData]() + +[Remove-PoshBotStatefulData]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/New-PoshBotCardResponse.md b/docs/reference/functions/New-PoshBotCardResponse.md new file mode 100644 index 0000000..1ac6794 --- /dev/null +++ b/docs/reference/functions/New-PoshBotCardResponse.md @@ -0,0 +1,267 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotCardResponse + +## SYNOPSIS +Tells PoshBot to send a specially formatted response. + +## SYNTAX + +``` +New-PoshBotCardResponse [[-Type] ] [-DM] [[-Text] ] [[-Title] ] + [[-ThumbnailUrl] ] [[-ImageUrl] ] [[-LinkUrl] ] [[-Fields] ] + [[-Color] ] [[-CustomData] ] [-TH] [] +``` + +## DESCRIPTION +Responses from PoshBot commands can either be plain text or formatted. +Returning a response with New-PoshBotRepsonse will tell PoshBot +to craft a specially formatted message when sending back to the chat network. + +## EXAMPLES + +### EXAMPLE 1 +``` +function Do-Something { +``` + +\[cmdletbinding()\] + param( + \[parameter(mandatory)\] + \[string\]$MyParam + ) + + New-PoshBotCardResponse -Type Normal -Text 'OK, I did something.' -ThumbnailUrl 'https://www.streamsports.com/images/icon_green_check_256.png' +} + +Tells PoshBot to send a formatted response back to the chat network. +In Slack for example, this response will be a message attachment +with a green border on the left, some text and a green checkmark thumbnail image. + +### EXAMPLE 2 +``` +function Do-Something { +``` + +\[cmdletbinding()\] + param( + \[parameter(mandatory)\] + \[string\]$ComputerName + ) + + $info = Get-ComputerInfo -ComputerName $ComputerName -ErrorAction SilentlyContinue + if ($info) { + $fields = \[ordered\]@{ + Name = $ComputerName + OS = $info.OSName + Uptime = $info.Uptime + IPAddress = $info.IPAddress + } + New-PoshBotCardResponse -Type Normal -Fields $fields + } else { + New-PoshBotCardResponse -Type Error -Text 'Something bad happended :(' -ThumbnailUrl 'http://p1cdn05.thewrap.com/images/2015/06/don-draper-shrug.jpg' + } +} + +Attempt to retrieve some information from a given computer and return a card response back to PoshBot. +If the command fails for some reason, +return a card response specified the error and a sad image. + +## PARAMETERS + +### -Type +Specifies a preset color for the card response. +If the \[Color\] parameter is specified as well, it will override this parameter. + +| Type | Color | Hex code | +|---------|--------|----------| +| Normal | Greed | #008000 | +| Warning | Yellow | #FFA500 | +| Error | Red | #FF0000 | + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: Normal +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DM +Tell PoshBot to redirect the response to a DM channel. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Text +The text response from the command. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: [string]::empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Title +The title of the response. +This will be the card title in chat networks like Slack. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ThumbnailUrl +A URL to a thumbnail image to display in the card response. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ImageUrl +A URL to an image to display in the card response. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LinkUrl +Will turn the title into a hyperlink + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Fields +A hashtable to display as a table in the card response. + +```yaml +Type: IDictionary +Parameter Sets: (All) +Aliases: + +Required: False +Position: 7 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Color +The hex color code to use for the card response. +In Slack, this will be the color of the left border in the message attachment. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: #D3D3D3 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CustomData +Any additional custom data you'd like to pass on. +Useful for custom backends, in case you want to pass a specifically formatted response +in the Data stream of the responses received by the backend. +Any data sent here will be skipped by the built-in backends provided with PoshBot itself. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TH +{{ Fill TH Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### PSCustomObject +## NOTES + +## RELATED LINKS + +[New-PoshBotTextResponse]() + diff --git a/docs/reference/functions/New-PoshBotConfiguration.md b/docs/reference/functions/New-PoshBotConfiguration.md new file mode 100644 index 0000000..229b5ba --- /dev/null +++ b/docs/reference/functions/New-PoshBotConfiguration.md @@ -0,0 +1,729 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotConfiguration + +## SYNOPSIS +Creates a new PoshBot configuration object. + +## SYNTAX + +``` +New-PoshBotConfiguration [[-Name] ] [[-ConfigurationDirectory] ] [[-LogDirectory] ] + [[-PluginDirectory] ] [[-PluginRepository] ] [[-ModuleManifestsToLoad] ] + [[-LogLevel] ] [[-MaxLogSizeMB] ] [[-MaxLogsToKeep] ] [[-LogCommandHistory] ] + [[-CommandHistoryMaxLogSizeMB] ] [[-CommandHistoryMaxLogsToKeep] ] + [[-BackendConfiguration] ] [[-PluginConfiguration] ] [[-BotAdmins] ] + [[-CommandPrefix] ] [[-AlternateCommandPrefixes] ] + [[-AlternateCommandPrefixSeperators] ] [[-SendCommandResponseToPrivate] ] + [[-MuteUnknownCommand] ] [[-AddCommandReactions] ] [[-ApprovalExpireMinutes] ] + [-DisallowDMs] [[-FormatEnumerationLimitOverride] ] [[-ApprovalCommandConfigurations] ] + [[-ChannelRules] ] [[-PreReceiveMiddlewareHooks] ] + [[-PostReceiveMiddlewareHooks] ] [[-PreExecuteMiddlewareHooks] ] + [[-PostExecuteMiddlewareHooks] ] [[-PreResponseMiddlewareHooks] ] + [[-PostResponseMiddlewareHooks] ] [] +``` + +## DESCRIPTION +Creates a new PoshBot configuration object. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-PoshBotConfiguration -Name Cherry2000 -AlternateCommandPrefixes @('Cherry', 'Sam') +``` + +Name : Cherry2000 +ConfigurationDirectory : C:\Users\brand\.poshbot +LogDirectory : C:\Users\brand\.poshbot +PluginDirectory : C:\Users\brand\.poshbot +PluginRepository : {PSGallery} +ModuleManifestsToLoad : {} +LogLevel : Verbose +BackendConfiguration : {} +PluginConfiguration : {} +BotAdmins : {} +CommandPrefix : ! +AlternateCommandPrefixes : {Cherry, Sam} +AlternateCommandPrefixSeperators : {:, ,, ;} +SendCommandResponseToPrivate : {} +MuteUnknownCommand : False +AddCommandReactions : True +ApprovalConfiguration : ApprovalConfiguration + +Create a new PoshBot configuration with default values except for the bot name and alternate command prefixes that it will listen for. + +### EXAMPLE 2 +``` +$backend = @{Name = 'SlackBackend'; Token = 'xoxb-569733935137-njOPkyBThqOTTUnCZb7tZpKK'} +``` + +PS C:\\\> $botParams = @{ + Name = 'HAL9000' + LogLevel = 'Info' + BotAdmins = @('JoeUser') + BackendConfiguration = $backend + } +PS C:\\\> $myBotConfig = New-PoshBotConfiguration @botParams +PS C:\\\> $myBotConfig + +Name : HAL9000 +ConfigurationDirectory : C:\Users\brand\.poshbot +LogDirectory : C:\Users\brand\.poshbot +PluginDirectory : C:\Users\brand\.poshbot +PluginRepository : {MyLocalRepo} +ModuleManifestsToLoad : {} +LogLevel : Info +BackendConfiguration : {} +PluginConfiguration : {} +BotAdmins : {JoeUser} +CommandPrefix : ! +AlternateCommandPrefixes : {poshbot} +AlternateCommandPrefixSeperators : {:, ,, ;} +SendCommandResponseToPrivate : {} +MuteUnknownCommand : False +AddCommandReactions : True +ApprovalConfiguration : ApprovalConfiguration + +PS C:\\\> $myBotConfig | Start-PoshBot -AsJob + +Create a new PoshBot configuration with a Slack backend. +Slack's backend only requires a bot token to be specified. +Ensure the person +with Slack handle 'JoeUser' is a bot admin. + +## PARAMETERS + +### -Name +The name the bot instance will be known as. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: PoshBot +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConfigurationDirectory +The directory when PoshBot configuration data will be written to. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: $script:defaultPoshBotDir +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogDirectory +The log directory logs will be written to. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: $script:defaultPoshBotDir +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PluginDirectory +The directory PoshBot will look for PowerShell modules. +This path will be prepended to your $env:PSModulePath. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: $script:defaultPoshBotDir +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PluginRepository +One or more PowerShell repositories to look in when installing new plugins (modules). +These will be the repository name(s) as found in Get-PSRepository. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: @('PSGallery') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ModuleManifestsToLoad +One or more paths to module manifest (.psd1) files. +These modules will be automatically +loaded when PoshBot starts. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogLevel +The level of logging that PoshBot will do. + +```yaml +Type: LogLevel +Parameter Sets: (All) +Aliases: +Accepted values: Info, Verbose, Debug + +Required: False +Position: 7 +Default value: Verbose +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxLogSizeMB +The maximum log file size in megabytes. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: 10 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MaxLogsToKeep +The maximum number of logs to keep. +Once this value is reached, logs will start rotating. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 9 +Default value: 5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogCommandHistory +Enable command history to be logged to a separate file for convenience. +The default it $true + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 10 +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CommandHistoryMaxLogSizeMB +The maximum log file size for the command history + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 11 +Default value: 10 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CommandHistoryMaxLogsToKeep +The maximum number of logs to keep for command history. +Once this value is reached, the logs will start rotating. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 12 +Default value: 5 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BackendConfiguration +A hashtable of configuration options required by the backend chat network implementation. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 13 +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PluginConfiguration +A hashtable of configuration options used by the various plugins (modules) that are installed in PoshBot. +Each key in the hashtable must be the name of a plugin. +The value of that hashtable item will be another hashtable +with each key matching a parameter name in one or more commands of that module. +A plugin command can specifiy that a +parameter gets its value from this configuration by applying the custom attribute \[PoshBot.FromConfig()\] on +the parameter. + +The function below is stating that the parameter $MyParam will get its value from the plugin configuration. +The user +running this command in PoshBot does not need to specify this parameter. +PoshBot will dynamically resolve and apply +the matching value from the plugin configuration when the command is executed. + +function Get-Foo { + \[cmdletbinding()\] + param( + \[PoshBot.FromConfig()\] + \[parameter(mandatory)\] + \[string\]$MyParam + ) + + Write-Output $MyParam +} + +If the function below was part of the Demo plugin, PoshBot will look in the plugin configuration for a key matching Demo +and a child key matching $MyParam. + +Example plugin configuration: +@{ + Demo = @{ + MyParam = 'bar' + } +} + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: 14 +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -BotAdmins +An array of chat handles that will be granted admin rights in PoshBot. +Any user in this array will have full rights in PoshBot. +At startup, +PoshBot will resolve these handles into IDs given by the chat network. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 15 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CommandPrefix +The prefix (single character) that must be specified in front of a command in order for PoshBot to recognize the chat message as a bot command. + +!get-foo --value bar + +```yaml +Type: Char +Parameter Sets: (All) +Aliases: + +Required: False +Position: 16 +Default value: ! +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AlternateCommandPrefixes +Some users may want to specify alternate prefixes when calling bot comamnds. +Use this parameter to specify an array of words that PoshBot +will also check when parsing a chat message. + +bender get-foo --value bar + +hal open-doors --type pod + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 17 +Default value: @('poshbot') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AlternateCommandPrefixSeperators +An array of characters that can also ben used when referencing bot commands. + +bender, get-foo --value bar + +hal; open-doors --type pod + +```yaml +Type: Char[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 18 +Default value: @(':', ',', ';') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SendCommandResponseToPrivate +A list of fully qualified (\:\) plugin commands that will have their responses redirected back to a direct message +channel with the calling user rather than a shared channel. + +@( + demo:get-foo + network:ping +) + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 19 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MuteUnknownCommand +Instead of PoshBot returning a warning message when it is unable to find a command, use this to parameter to tell PoshBot to return nothing. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 20 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AddCommandReactions +Add reactions to a chat message indicating the command is being executed, has succeeded, or failed. + +```yaml +Type: Boolean +Parameter Sets: (All) +Aliases: + +Required: False +Position: 21 +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ApprovalExpireMinutes +The amount of time (minutes) that a command the requires approval will be pending until it expires. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 22 +Default value: 30 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisallowDMs +Disallow DMs (direct messages) with the bot. +If a user tries to DM the bot it will be ignored. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FormatEnumerationLimitOverride +Set $FormatEnumerationLimit to this. +Defaults to unlimited (-1) + +Determines how many enumerated items are included in a display. +This variable does not affect the underlying objects; just the display. +When the value of $FormatEnumerationLimit is less than the number of enumerated items, PowerShell adds an ellipsis (...) to indicate items not shown. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 23 +Default value: -1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ApprovalCommandConfigurations +Array of hashtables containing command approval configurations. + +@( + @{ + Expression = 'MyModule:Execute-Deploy:*' + Groups = 'platform-admins' + PeerApproval = $true + } + @{ + Expression = 'MyModule:Deploy-HRApp:*' + Groups = @('platform-managers', 'hr-managers') + PeerApproval = $true + } +) + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 24 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChannelRules +Array of channels rules that control what plugin commands are allowed in a channel. +Wildcards are supported. +Channel names that match against this list will be allowed to have Poshbot commands executed in them. + +Internally this uses the \`-like\` comparison operator, not \`-match\`. +Regexes are not allowed. + +For best results, list channels and commands from most specific to least specific. +PoshBot will +evaluate the first match found. + +Note that the bot will still receive messages from all channels it is a member of. +These message MAY +be logged depending on your configured logging level. + +Example value: +@( + # Only allow builtin commands in the 'botadmin' channel + @{ + Channel = 'botadmin' + IncludeCommands = @('builtin:*') + ExcludeCommands = @() + } + # Exclude builtin commands from any "projectX" channel + @{ + Channel = '*projectx*' + IncludeCommands = @('*') + ExcludeCommands = @('builtin:*') + } + # It's the wild west in random, except giphy :) + @{ + Channel = 'random' + IncludeCommands = @('*') + ExcludeCommands = @('*giphy*') + } + # All commands are otherwise allowed + @{ + Channel = '*' + IncludeCommands = @('*') + ExcludeCommands = @() + } +) + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 25 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PreReceiveMiddlewareHooks +Array of middleware scriptblocks that will run before PoshBot "receives" the message from the backend implementation. +This middleware will receive the original message sent from the chat network and have a chance to modify, analyze, and optionally drop the message before PoshBot continues processing it. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 26 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PostReceiveMiddlewareHooks +Array of middleware scriptblocks that will run after a message is "received" from the backend implementation. +This middleware runs after messages have been parsed and matched with a registered command in PoshBot. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 27 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PreExecuteMiddlewareHooks +Array of middleware scriptblocks that will run before a command is executed. +This middleware is a good spot to run extra authentication or validation processes before commands are executed. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 28 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PostExecuteMiddlewareHooks +Array of middleware scriptblocks that will run after PoshBot commands have been executed. +This middleware is a good spot for custom logging solutions to write command history to a custom location. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 29 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PreResponseMiddlewareHooks +Array of middleware scriptblocks that will run before command responses are sent to the backend implementation. +This middleware is a good spot for modifying or sanitizing responses before they are sent to the chat network. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 30 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PostResponseMiddlewareHooks +Array of middleware scriptblocks that will run after command responses have been sent to the backend implementation. +This middleware runs after all processing is complete for a command and is a good spot for additional custom logging. + +```yaml +Type: MiddlewareHook[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 31 +Default value: @() +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### BotConfiguration +## NOTES + +## RELATED LINKS + +[Get-PoshBotConfiguration]() + +[Save-PoshBotConfiguration]() + +[New-PoshBotInstance]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/New-PoshBotDiscordBackend.md b/docs/reference/functions/New-PoshBotDiscordBackend.md new file mode 100644 index 0000000..865d6fc --- /dev/null +++ b/docs/reference/functions/New-PoshBotDiscordBackend.md @@ -0,0 +1,66 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotDiscordBackend + +## SYNOPSIS +Create a new instance of a Discord backend + +## SYNTAX + +``` +New-PoshBotDiscordBackend [-Configuration] [] +``` + +## DESCRIPTION +Create a new instance of a Discord backend + +## EXAMPLES + +### EXAMPLE 1 +``` +$backendConfig = @{ +``` + +Name = 'DiscordBackend' + Token = '\' + ClientId = '\' + GuildId = '\' +} +PS C:\\\> $backend = New-PoshBotDiscordBackend -Configuration $backendConfig + +Create a Discord backend using the specified connection information. + +## PARAMETERS + +### -Configuration +The hashtable containing backend-specific properties on how to create the Discord backend instance. + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: BackendConfiguration + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Hashtable +## OUTPUTS + +### DiscordBackend +## NOTES + +## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotFileUpload.md b/docs/reference/functions/New-PoshBotFileUpload.md new file mode 100644 index 0000000..65ad568 --- /dev/null +++ b/docs/reference/functions/New-PoshBotFileUpload.md @@ -0,0 +1,249 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotFileUpload + +## SYNOPSIS +Tells PoshBot to upload a file to the chat network. + +## SYNTAX + +### Path (Default) +``` +New-PoshBotFileUpload [-Path] [-Title ] [-DM] [-KeepFile] [] +``` + +### LiteralPath +``` +New-PoshBotFileUpload [-LiteralPath] [-Title ] [-DM] [-KeepFile] [] +``` + +### Content +``` +New-PoshBotFileUpload -Content [-FileType ] [-FileName ] [-Title ] [-DM] + [-KeepFile] [] +``` + +## DESCRIPTION +Returns a custom object back to PoshBot telling it to upload the given file to the chat network. +The custom object +can also tell PoshBot to redirect the file upload to a DM channel with the calling user. +This could be useful if +the contents the bot command returns are sensitive and should not be visible to all users in the channel. + +## EXAMPLES + +### EXAMPLE 1 +``` +function Do-Stuff { +``` + +\[cmdletbinding()\] + param() + + $myObj = \[pscustomobject\]@{ + value1 = 'foo' + value2 = 'bar' + } + + $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" + $myObj | Export-Csv -Path $csv -NoTypeInformation + + New-PoshBotFileUpload -Path $csv +} + +Export a CSV file and tell PoshBot to upload the file back to the channel that initiated this command. + +### EXAMPLE 2 +``` +function Get-SecretPlan { +``` + +\[cmdletbinding()\] + param() + + $myObj = \[pscustomobject\]@{ + Title = 'Secret moon base' + Description = 'Plans for secret base on the dark side of the moon' + } + + $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" + $myObj | Export-Csv -Path $csv -NoTypeInformation + + New-PoshBotFileUpload -Path $csv -Title 'YourEyesOnly.csv' -DM +} + +Export a CSV file and tell PoshBot to upload the file back to a DM channel with the calling user. + +### EXAMPLE 3 +``` +function Do-Stuff { +``` + +\[cmdletbinding()\] + param() + + $myObj = \[pscustomobject\]@{ + value1 = 'foo' + value2 = 'bar' + } + + $csv = Join-Path -Path $env:TEMP -ChildPath "$((New-Guid).ToString()).csv" + $myObj | Export-Csv -Path $csv -NoTypeInformation + + New-PoshBotFileUpload -Path $csv -KeepFile +} + +Export a CSV file and tell PoshBot to upload the file back to the channel that initiated this command. +Keep the file after uploading it. + +## PARAMETERS + +### -Path +The path(s) to one or more files to upload. +Wildcards are permitted. + +```yaml +Type: String[] +Parameter Sets: Path +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: True +``` + +### -LiteralPath +Specifies the path(s) to the current location of the file(s). +Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. +No characters are interpreted as wildcards. +If the path includes escape characters, enclose it in single quotation marks. +Single quotation +marks tell PowerShell not to interpret any characters as escape sequences. + +```yaml +Type: String[] +Parameter Sets: LiteralPath +Aliases: PSPath + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Content +The content of the file to send. + +```yaml +Type: String +Parameter Sets: Content +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileType +If specified, override the file type determined by the filename. + +```yaml +Type: String +Parameter Sets: Content +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FileName +The name to call the uploaded file + +```yaml +Type: String +Parameter Sets: Content +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Title +The title for the uploaded file. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: [string]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DM +Tell PoshBot to redirect the file upload to a DM channel. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KeepFile +If specified, keep the source file after calling Send-SlackFile. +The source file is deleted without this + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### String +## OUTPUTS + +### PSCustomObject +## NOTES + +## RELATED LINKS + +[New-PoshBotCardResponse]() + +[New-PoshBotTextResponse]() + diff --git a/docs/reference/functions/New-PoshBotInstance.md b/docs/reference/functions/New-PoshBotInstance.md new file mode 100644 index 0000000..0f018e8 --- /dev/null +++ b/docs/reference/functions/New-PoshBotInstance.md @@ -0,0 +1,172 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotInstance + +## SYNOPSIS +Creates a new instance of PoshBot + +## SYNTAX + +### path (Default) +``` +New-PoshBotInstance -Backend [] +``` + +### Path +``` +New-PoshBotInstance [-Path] -Backend [] +``` + +### LiteralPath +``` +New-PoshBotInstance [-LiteralPath] -Backend [] +``` + +### config +``` +New-PoshBotInstance -Configuration -Backend [] +``` + +## DESCRIPTION +Creates a new instance of PoshBot from an existing configuration (.psd1) file or a configuration object. + +## EXAMPLES + +### EXAMPLE 1 +``` +New-PoshBotInstance -Path 'C:\Users\joeuser\.poshbot\Cherry2000.psd1' -Backend $backend +``` + +Name : Cherry2000 +Backend : SlackBackend +Storage : StorageProvider +PluginManager : PluginManager +RoleManager : RoleManager +Executor : CommandExecutor +MessageQueue : {} +Configuration : BotConfiguration + +Create a new PoshBot instance from configuration file \[C:\Users\joeuser\.poshbot\Cherry2000.psd1\] and Slack backend object \[$backend\]. + +### EXAMPLE 2 +``` +$botConfig = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\Cherry2000.psd1') +``` + +PS C:\\\> $backend = New-PoshBotSlackBackend -Configuration $botConfig.BackendConfiguration +PS C:\\\> $myBot = $botConfig | New-PoshBotInstance -Backend $backend +PS C:\\\> $myBot | Format-List + +Name : Cherry2000 +Backend : SlackBackend +Storage : StorageProvider +PluginManager : PluginManager +RoleManager : RoleManager +Executor : CommandExecutor +MessageQueue : {} +Configuration : BotConfiguration + +Gets a bot configuration from the filesytem, creates a chat backend object, and then creates a new bot instance. + +### EXAMPLE 3 +``` +$botConfig = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\Cherry2000.psd1') +``` + +PS C:\\\> $backend = $botConfig | New-PoshBotSlackBackend +PS C:\\\> $myBotJob = $botConfig | New-PoshBotInstance -Backend $backend | Start-PoshBot -AsJob -PassThru + +Gets a bot configuration, creates a Slack backend from it, then creates a new PoshBot instance and starts it as a background job. + +## PARAMETERS + +### -Path +The path to a PowerShell data (.psd1) file to create a new instance from. + +```yaml +Type: String[] +Parameter Sets: Path +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: True +``` + +### -LiteralPath +Specifies the path(s) to the current location of the file(s). +Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. +No characters are interpreted as wildcards. +If the path includes escape characters, enclose it in single quotation marks. +Single quotation +marks tell PowerShell not to interpret any characters as escape sequences. + +```yaml +Type: String[] +Parameter Sets: LiteralPath +Aliases: PSPath + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Configuration +The bot configuration object to create a new instance from. + +```yaml +Type: BotConfiguration[] +Parameter Sets: config +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Backend +The backend object that hosts logic for receiving and sending messages to a chat network. + +```yaml +Type: Backend +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### String +### BotConfiguration +## OUTPUTS + +### Bot +## NOTES + +## RELATED LINKS + +[Get-PoshBotConfiguration]() + +[New-PoshBotSlackBackend]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/New-PoshBotMiddlewareHook.md b/docs/reference/functions/New-PoshBotMiddlewareHook.md new file mode 100644 index 0000000..c3ca573 --- /dev/null +++ b/docs/reference/functions/New-PoshBotMiddlewareHook.md @@ -0,0 +1,80 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotMiddlewareHook + +## SYNOPSIS +Creates a PoshBot middleware hook object. + +## SYNTAX + +``` +New-PoshBotMiddlewareHook [-Name] [-Path] [] +``` + +## DESCRIPTION +PoshBot can execute custom scripts during various stages of the command processing lifecycle. +These scripts +are defined using New-PoshBotMiddlewareHook and added to the bot configuration object under the MiddlewareConfiguration section. +Hooks are added to the PreReceive, PostReceive, PreExecute, PostExecute, PreResponse, and PostResponse properties. +Middleware gets executed in the order in which it is added under each property. + +## EXAMPLES + +### EXAMPLE 1 +``` +$userDropHook = New-PoshBotMiddlewareHook -Name 'dropuser' -Path 'c:/poshbot/middleware/dropuser.ps1' +``` + +PS C:\\\> $config.MiddlewareConfiguration.Add($userDropHook, 'PreReceive') + +Creates a middleware hook called 'dropuser' and adds it to the 'PreReceive' middleware lifecycle stage. + +## PARAMETERS + +### -Name +The name of the middleware hook. +Must be unique in each middleware lifecycle stage. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +The file path the the PowerShell script to execute as a middleware hook. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### MiddlewareHook +## NOTES + +## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotScheduledTask.md b/docs/reference/functions/New-PoshBotScheduledTask.md new file mode 100644 index 0000000..e4e93c0 --- /dev/null +++ b/docs/reference/functions/New-PoshBotScheduledTask.md @@ -0,0 +1,197 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotScheduledTask + +## SYNOPSIS +Creates a new scheduled task to run PoshBot in the background. + +## SYNTAX + +``` +New-PoshBotScheduledTask [[-Name] ] [[-Description] ] [-Path] + [-Credential] [-PassThru] [-Force] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Creates a new scheduled task to run PoshBot in the background. +The scheduled task will always be configured +to run on startup and to not stop after any time period. + +## EXAMPLES + +### EXAMPLE 1 +``` +$cred = Get-Credential +``` + +PS C:\\\> New-PoshBotScheduledTask -Name PoshBot -Path C:\PoshBot\myconfig.psd1 -Credential $cred + +Creates a new scheduled task to start PoshBot using the configuration file located at C:\PoshBot\myconfig.psd1 +and the specified credential. + +### EXAMPLE 2 +``` +$cred = Get-Credential +``` + +PC C:\\\> $params = @{ + Name = 'PoshBot' + Path = 'C:\PoshBot\myconfig.psd1' + Credential = $cred + Description = 'Awesome ChatOps bot' + PassThru = $true +} +PS C:\\\> $task = New-PoshBotScheduledTask @params +PS C:\\\> $task | Start-ScheduledTask + +Creates a new scheduled task to start PoshBot using the configuration file located at C:\PoshBot\myconfig.psd1 +and the specified credential then starts the task. + +## PARAMETERS + +### -Name +The name for the scheduled task + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: PoshBot +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +The description for the scheduled task + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Start PoshBot +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +The path to the PoshBot configuration file to load and execute + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Credential +The credential to run the scheduled task under. + +```yaml +Type: PSCredential +Parameter Sets: (All) +Aliases: + +Required: True +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Return the newly created scheduled task object + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force +Overwrite a previously created scheduled task + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Management.Infrastructure.CimInstance#root/Microsoft/Windows/TaskScheduler/MSFT_ScheduledTask +## NOTES + +## RELATED LINKS + +[Get-PoshBotConfiguration]() + +[New-PoshBotConfiguration]() + +[Save-PoshBotConfiguration]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/New-PoshBotSlackBackend.md b/docs/reference/functions/New-PoshBotSlackBackend.md new file mode 100644 index 0000000..5dfc438 --- /dev/null +++ b/docs/reference/functions/New-PoshBotSlackBackend.md @@ -0,0 +1,61 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotSlackBackend + +## SYNOPSIS +Create a new instance of a Slack backend + +## SYNTAX + +``` +New-PoshBotSlackBackend [-Configuration] [] +``` + +## DESCRIPTION +Create a new instance of a Slack backend + +## EXAMPLES + +### EXAMPLE 1 +``` +$backendConfig = @{Name = 'SlackBackend'; Token = ''} +``` + +PS C:\\\> $backend = New-PoshBotSlackBackend -Configuration $backendConfig + +Create a Slack backend using the specified API token + +## PARAMETERS + +### -Configuration +The hashtable containing backend-specific properties on how to create the Slack backend instance. + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: BackendConfiguration + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Hashtable +## OUTPUTS + +### SlackBackend +## NOTES + +## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotTeamsBackend.md b/docs/reference/functions/New-PoshBotTeamsBackend.md new file mode 100644 index 0000000..f544834 --- /dev/null +++ b/docs/reference/functions/New-PoshBotTeamsBackend.md @@ -0,0 +1,71 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotTeamsBackend + +## SYNOPSIS +Create a new instance of a Microsoft Teams backend + +## SYNTAX + +``` +New-PoshBotTeamsBackend [-Configuration] [] +``` + +## DESCRIPTION +Create a new instance of a Microsoft Teams backend + +## EXAMPLES + +### EXAMPLE 1 +``` +$backendConfig = @{ +``` + +Name = 'TeamsBackend' + Credential = \[pscredential\]::new( + '\', + ('\' | ConvertTo-SecureString -AsPlainText -Force) + ) + ServiceBusNamespace = '\' + QueueName = '\' + AccessKeyName = '\' + AccessKey = '\' | ConvertTo-SecureString -AsPlainText -Force +} +PS C:\\\> $$backend = New-PoshBotTeamsBackend -Configuration $backendConfig + +Create a Microsoft Teams backend using the specified Bot Framework credentials and Service Bus information + +## PARAMETERS + +### -Configuration +The hashtable containing backend-specific properties on how to create the instance. + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: BackendConfiguration + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Hashtable +## OUTPUTS + +### TeamsBackend +## NOTES + +## RELATED LINKS diff --git a/docs/reference/functions/New-PoshBotTextResponse.md b/docs/reference/functions/New-PoshBotTextResponse.md new file mode 100644 index 0000000..7cd38b8 --- /dev/null +++ b/docs/reference/functions/New-PoshBotTextResponse.md @@ -0,0 +1,122 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotTextResponse + +## SYNOPSIS +Tells PoshBot to handle the text response from a command in a special way. + +## SYNTAX + +``` +New-PoshBotTextResponse [-Text] [-AsCode] [-DM] [-TH] [] +``` + +## DESCRIPTION +Responses from PoshBot commands can be sent back to the channel they were posted from (default) or redirected to a DM channel with the +calling user. +This could be useful if the contents the bot command returns are sensitive and should not be visible to all users +in the channel. + +## EXAMPLES + +### EXAMPLE 1 +``` +function Get-Foo { +``` + +\[cmdletbinding()\] + param( + \[parameter(mandatory)\] + \[string\]$MyParam + ) + + New-PoshBotTextResponse -Text $MyParam -DM +} + +When Get-Foo is executed by PoshBot, the text response will be sent back to the calling user as a DM rather than back in the channel the +command was called from. +This could be useful if the contents the bot command returns are sensitive and should not be visible to all users +in the channel. + +## PARAMETERS + +### -Text +The text response from the command. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -AsCode +Format the text in a code block if the backend supports it. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DM +Tell PoshBot to redirect the response to a DM channel. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TH +{{ Fill TH Description }} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### String +## OUTPUTS + +### PSCustomObject +## NOTES + +## RELATED LINKS + +[New-PoshBotCardResponse]() + diff --git a/docs/reference/functions/PoshBot.md b/docs/reference/functions/PoshBot.md new file mode 100644 index 0000000..ede4c6a --- /dev/null +++ b/docs/reference/functions/PoshBot.md @@ -0,0 +1,67 @@ +--- +Module Name: PoshBot +Module Guid: 7bfb126c-b432-4921-989a-9802f525693f +Download Help Link: {{ Update Download Link }} +Help Version: {{ Please enter version of help manually (X.X.X.X) format }} +Locale: en-US +--- + +# PoshBot Module +## Description +{{ Fill in the Description }} + +## PoshBot Cmdlets +### [Get-PoshBot](Get-PoshBot.md) +{{ Fill in the Description }} + +### [Get-PoshBotConfiguration](Get-PoshBotConfiguration.md) +{{ Fill in the Description }} + +### [Get-PoshBotStatefulData](Get-PoshBotStatefulData.md) +{{ Fill in the Description }} + +### [New-PoshBotCardResponse](New-PoshBotCardResponse.md) +{{ Fill in the Description }} + +### [New-PoshBotConfiguration](New-PoshBotConfiguration.md) +{{ Fill in the Description }} + +### [New-PoshBotDiscordBackend](New-PoshBotDiscordBackend.md) +{{ Fill in the Description }} + +### [New-PoshBotFileUpload](New-PoshBotFileUpload.md) +{{ Fill in the Description }} + +### [New-PoshBotInstance](New-PoshBotInstance.md) +{{ Fill in the Description }} + +### [New-PoshBotMiddlewareHook](New-PoshBotMiddlewareHook.md) +{{ Fill in the Description }} + +### [New-PoshBotScheduledTask](New-PoshBotScheduledTask.md) +{{ Fill in the Description }} + +### [New-PoshBotSlackBackend](New-PoshBotSlackBackend.md) +{{ Fill in the Description }} + +### [New-PoshBotTeamsBackend](New-PoshBotTeamsBackend.md) +{{ Fill in the Description }} + +### [New-PoshBotTextResponse](New-PoshBotTextResponse.md) +{{ Fill in the Description }} + +### [Remove-PoshBotStatefulData](Remove-PoshBotStatefulData.md) +{{ Fill in the Description }} + +### [Save-PoshBotConfiguration](Save-PoshBotConfiguration.md) +{{ Fill in the Description }} + +### [Set-PoshBotStatefulData](Set-PoshBotStatefulData.md) +{{ Fill in the Description }} + +### [Start-PoshBot](Start-PoshBot.md) +{{ Fill in the Description }} + +### [Stop-Poshbot](Stop-Poshbot.md) +{{ Fill in the Description }} + diff --git a/docs/reference/functions/Remove-PoshBotStatefulData.md b/docs/reference/functions/Remove-PoshBotStatefulData.md new file mode 100644 index 0000000..124ab61 --- /dev/null +++ b/docs/reference/functions/Remove-PoshBotStatefulData.md @@ -0,0 +1,136 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Remove-PoshBotStatefulData + +## SYNOPSIS +Remove existing stateful data + +## SYNTAX + +``` +Remove-PoshBotStatefulData [-Name] [[-Scope] ] [[-Depth] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Remove existing stateful data + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-PoshBotStatefulData -Name 'ToUse' +``` + +Removes the 'ToUse' property from stateful data for the PoshBot plugin you are currently running this from. + +### EXAMPLE 2 +``` +Remove-PoshBotStatefulData -Name 'Something' -Scope Global +``` + +Removes the 'Something' property from PoshBot's global stateful data + +## PARAMETERS + +### -Name +Property to remove from the stateful data file + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +Sets the scope of stateful data to remove: + Module: Remove stateful data from the current module's data + Global: Remove stateful data from the global PoshBot data + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: Module +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Depth +Specifies how many levels of contained objects are included in the XML representation. +The default value is 2 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: 2 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Get-PoshBotStatefulData]() + +[Set-PoshBotStatefulData]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/Save-PoshBotConfiguration.md b/docs/reference/functions/Save-PoshBotConfiguration.md new file mode 100644 index 0000000..407b386 --- /dev/null +++ b/docs/reference/functions/Save-PoshBotConfiguration.md @@ -0,0 +1,158 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Save-PoshBotConfiguration + +## SYNOPSIS +Saves a PoshBot configuration object to the filesystem in the form of a PowerShell data (.psd1) file. + +## SYNTAX + +``` +Save-PoshBotConfiguration [-InputObject] [[-Path] ] [-Force] [-PassThru] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +PoshBot configurations can be stored on the filesytem in PowerShell data (.psd1) files. +This function will save a previously created configuration object to the filesystem. + +## EXAMPLES + +### EXAMPLE 1 +``` +Save-PoshBotConfiguration -InputObject $botConfig +``` + +Saves the PoshBot configuration. +If now -Path is specified, the configuration will be saved to $env:USERPROFILE\.poshbot\PoshBot.psd1. + +### EXAMPLE 2 +``` +$botConfig | Save-PoshBotConfig -Path c:\mybot\mybot.psd1 +``` + +Saves the PoshBot configuration to \[c:\mybot\mybot.psd1\]. + +### EXAMPLE 3 +``` +$configFile = $botConfig | Save-PoshBotConfig -Path c:\mybot\mybot.psd1 -Force -PassThru +``` + +Saves the PoshBot configuration to \[c:\mybot\mybot.psd1\] and Overwrites existing file. +The new file will be returned. + +## PARAMETERS + +### -InputObject +The bot configuration object to save to the filesystem. + +```yaml +Type: BotConfiguration +Parameter Sets: (All) +Aliases: Configuration + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Path +The path to a PowerShell data (.psd1) file to save the configuration to. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: (Join-Path -Path $script:defaultPoshBotDir -ChildPath 'PoshBot.psd1') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force +Overwrites an existing configuration file. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns the configuration file path. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### BotConfiguration +## OUTPUTS + +### System.IO.FileInfo +## NOTES + +## RELATED LINKS + +[Get-PoshBotConfiguration]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/Set-PoshBotStatefulData.md b/docs/reference/functions/Set-PoshBotStatefulData.md new file mode 100644 index 0000000..08aeaff --- /dev/null +++ b/docs/reference/functions/Set-PoshBotStatefulData.md @@ -0,0 +1,155 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Set-PoshBotStatefulData + +## SYNOPSIS +Save stateful data to use in another PoshBot command + +## SYNTAX + +``` +Set-PoshBotStatefulData [-Name] [-Value] [[-Scope] ] [[-Depth] ] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +Save stateful data to use in another PoshBot command + +Stores data in clixml format, in the PoshBot ConfigurationDirectory. + +If \ property exists in current stateful data file, it is overwritten + +## EXAMPLES + +### EXAMPLE 1 +``` +Set-PoshBotStatefulData -Name 'ToUse' -Value 'Later' +``` + +Adds a 'ToUse' property to the stateful data for the PoshBot plugin you are currently running this from. + +### EXAMPLE 2 +``` +$Anything | Set-PoshBotStatefulData -Name 'Something' -Scope Global +``` + +Adds a 'Something' property to PoshBot's global stateful data, with the value of $Anything + +## PARAMETERS + +### -Name +Property to add to the stateful data file + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Value +Value to set for the Name property in the stateful data file + +```yaml +Type: Object[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Scope +Sets the scope of stateful data to set: + Module: Allow only this plugin to access the stateful data you save + Global: Allow any plugin to access the stateful data you save + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: Module +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Depth +Specifies how many levels of contained objects are included in the XML representation. +The default value is 2 + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: 2 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Get-PoshBotStatefulData]() + +[Remove-PoshBotStatefulData]() + +[Start-PoshBot]() + diff --git a/docs/reference/functions/Start-PoshBot.md b/docs/reference/functions/Start-PoshBot.md new file mode 100644 index 0000000..5fe9059 --- /dev/null +++ b/docs/reference/functions/Start-PoshBot.md @@ -0,0 +1,167 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Start-PoshBot + +## SYNOPSIS +Starts a new instance of PoshBot interactively or in a job. + +## SYNTAX + +### bot (Default) +``` +Start-PoshBot -InputObject [-AsJob] [-PassThru] [] +``` + +### config +``` +Start-PoshBot -Configuration [-AsJob] [-PassThru] [] +``` + +### path +``` +Start-PoshBot -Path [-AsJob] [-PassThru] [] +``` + +## DESCRIPTION +Starts a new instance of PoshBot interactively or in a job. + +## EXAMPLES + +### EXAMPLE 1 +``` +Start-PoshBot -Bot $bot +``` + +Runs an instance of PoshBot that has already been created interactively in the shell. + +### EXAMPLE 2 +``` +$bot | Start-PoshBot -Verbose +``` + +Runs an instance of PoshBot that has already been created interactively in the shell. + +### EXAMPLE 3 +``` +$config = Get-PoshBotConfiguration -Path (Join-Path -Path $env:USERPROFILE -ChildPath '.poshbot\MyPoshBot.psd1') +``` + +PS C:\\\> Start-PoshBot -Config $config + +Gets a PoshBot configuration from file and starts the bot interactively. + +### EXAMPLE 4 +``` +Get-PoshBot -Id 100 +``` + +Id : 100 +Name : PoshBot_eab96f2ad147489b9f90e110e02ad805 +State : Running +InstanceId : eab96f2ad147489b9f90e110e02ad805 +Config : BotConfiguration + +Gets the PoshBot job instance with ID 100. + +## PARAMETERS + +### -InputObject +An existing PoshBot instance to start. + +```yaml +Type: Bot +Parameter Sets: bot +Aliases: Bot + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Configuration +A PoshBot configuration object to use to start the bot instance. + +```yaml +Type: BotConfiguration +Parameter Sets: config +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Path +The path to a PoshBot configuration file. +A new instance of PoshBot will be created from this file. + +```yaml +Type: String +Parameter Sets: path +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AsJob +Run the PoshBot instance in a background job. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Return the PoshBot instance Id that is running as a job. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Bot +### BotConfiguration +### String +## OUTPUTS + +### PSCustomObject +## NOTES + +## RELATED LINKS + +[Start-PoshBot]() + +[Stop-PoshBot]() + diff --git a/docs/reference/functions/Stop-Poshbot.md b/docs/reference/functions/Stop-Poshbot.md new file mode 100644 index 0000000..045ee3e --- /dev/null +++ b/docs/reference/functions/Stop-Poshbot.md @@ -0,0 +1,118 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# Stop-Poshbot + +## SYNOPSIS +Stop a currently running PoshBot instance that is running as a background job. + +## SYNTAX + +``` +Stop-Poshbot [-Id] [-Force] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +PoshBot can be run in the background with PowerShell jobs. +This function stops +a currently running PoshBot instance. + +## EXAMPLES + +### EXAMPLE 1 +``` +Stop-PoshBot -Id 101 +``` + +Stop the bot instance with Id 101. + +### EXAMPLE 2 +``` +Get-PoshBot | Stop-PoshBot +``` + +Gets all running PoshBot instances and stops them. + +## PARAMETERS + +### -Id +The job Id of the bot to stop. + +```yaml +Type: Int32[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Force +Stop PoshBot instance without prompt + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### System.Int32 +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[Get-PoshBot]() + +[Start-PoshBot]() + diff --git a/psakeFile.ps1 b/psakeFile.ps1 index 2a334af..25da206 100644 --- a/psakeFile.ps1 +++ b/psakeFile.ps1 @@ -57,6 +57,7 @@ task Analyze -Depends Build { } -description 'Run PSScriptAnalyzer' task Pester -Depends Build { + Import-Module Pester -RequiredVersion 3.4.0 Push-Location Set-Location -PassThru $outputModDir if(-not $ENV:BHProjectPath) { From 904109a12b27a9146040ba761940756aeadd62ee Mon Sep 17 00:00:00 2001 From: Andriy Golubenkov FUIB VM Date: Tue, 1 Oct 2024 17:59:35 +0300 Subject: [PATCH 5/6] New Slack App Backend - Socket Mode --- .../SlackAppSM/SlackAppSMBackend.ps1 | 901 ++++++++++++++++++ .../SlackAppSM/SlackAppSMConnection.ps1 | 238 +++++ PoshBot/PoshBot.psd1 | 2 +- 3 files changed, 1140 insertions(+), 1 deletion(-) create mode 100644 PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 create mode 100644 PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 diff --git a/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 b/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 new file mode 100644 index 0000000..059f1b6 --- /dev/null +++ b/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 @@ -0,0 +1,901 @@ + +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Scope='Class', Target='*')] +class SlackAppSMBackend : Backend { + + # The types of message that we care about from Slack + # All othere will be ignored + [string[]]$MessageTypes = @( + 'channel_rename' + 'member_joined_channel' + 'member_left_channel' + 'message' + 'pin_added' + 'pin_removed' + 'presence_change' + 'reaction_added' + 'reaction_removed' + 'star_added' + 'star_removed' + 'goodbye' + ) + + [int]$MaxMessageLength = 3900 + + # Import some color defs. + hidden [hashtable]$_PSSlackColorMap = @{ + aliceblue = "#F0F8FF" + antiquewhite = "#FAEBD7" + aqua = "#00FFFF" + aquamarine = "#7FFFD4" + azure = "#F0FFFF" + beige = "#F5F5DC" + bisque = "#FFE4C4" + black = "#000000" + blanchedalmond = "#FFEBCD" + blue = "#0000FF" + blueviolet = "#8A2BE2" + brown = "#A52A2A" + burlywood = "#DEB887" + cadetblue = "#5F9EA0" + chartreuse = "#7FFF00" + chocolate = "#D2691E" + coral = "#FF7F50" + cornflowerblue = "#6495ED" + cornsilk = "#FFF8DC" + crimson = "#DC143C" + darkblue = "#00008B" + darkcyan = "#008B8B" + darkgoldenrod = "#B8860B" + darkgray = "#A9A9A9" + darkgreen = "#006400" + darkkhaki = "#BDB76B" + darkmagenta = "#8B008B" + darkolivegreen = "#556B2F" + darkorange = "#FF8C00" + darkorchid = "#9932CC" + darkred = "#8B0000" + darksalmon = "#E9967A" + darkseagreen = "#8FBC8F" + darkslateblue = "#483D8B" + darkslategray = "#2F4F4F" + darkturquoise = "#00CED1" + darkviolet = "#9400D3" + deeppink = "#FF1493" + deepskyblue = "#00BFFF" + dimgray = "#696969" + dodgerblue = "#1E90FF" + firebrick = "#B22222" + floralwhite = "#FFFAF0" + forestgreen = "#228B22" + fuchsia = "#FF00FF" + gainsboro = "#DCDCDC" + ghostwhite = "#F8F8FF" + gold = "#FFD700" + goldenrod = "#DAA520" + gray = "#808080" + green = "#008000" + greenyellow = "#ADFF2F" + honeydew = "#F0FFF0" + hotpink = "#FF69B4" + indianred = "#CD5C5C" + indigo = "#4B0082" + ivory = "#FFFFF0" + khaki = "#F0E68C" + lavender = "#E6E6FA" + lavenderblush = "#FFF0F5" + lawngreen = "#7CFC00" + lemonchiffon = "#FFFACD" + lightblue = "#ADD8E6" + lightcoral = "#F08080" + lightcyan = "#E0FFFF" + lightgoldenrodyellow = "#FAFAD2" + lightgreen = "#90EE90" + lightgrey = "#D3D3D3" + lightpink = "#FFB6C1" + lightsalmon = "#FFA07A" + lightseagreen = "#20B2AA" + lightskyblue = "#87CEFA" + lightslategray = "#778899" + lightsteelblue = "#B0C4DE" + lightyellow = "#FFFFE0" + lime = "#00FF00" + limegreen = "#32CD32" + linen = "#FAF0E6" + maroon = "#800000" + mediumaquamarine = "#66CDAA" + mediumblue = "#0000CD" + mediumorchid = "#BA55D3" + mediumpurple = "#9370DB" + mediumseagreen = "#3CB371" + mediumslateblue = "#7B68EE" + mediumspringgreen = "#00FA9A" + mediumturquoise = "#48D1CC" + mediumvioletred = "#C71585" + midnightblue = "#191970" + mintcream = "#F5FFFA" + mistyrose = "#FFE4E1" + moccasin = "#FFE4B5" + navajowhite = "#FFDEAD" + navy = "#000080" + oldlace = "#FDF5E6" + olive = "#808000" + olivedrab = "#6B8E23" + orange = "#FFA500" + orangered = "#FF4500" + orchid = "#DA70D6" + palegoldenrod = "#EEE8AA" + palegreen = "#98FB98" + paleturquoise = "#AFEEEE" + palevioletred = "#DB7093" + papayawhip = "#FFEFD5" + peachpuff = "#FFDAB9" + peru = "#CD853F" + pink = "#FFC0CB" + plum = "#DDA0DD" + powderblue = "#B0E0E6" + purple = "#800080" + red = "#FF0000" + rosybrown = "#BC8F8F" + royalblue = "#4169E1" + saddlebrown = "#8B4513" + salmon = "#FA8072" + sandybrown = "#F4A460" + seagreen = "#2E8B57" + seashell = "#FFF5EE" + sienna = "#A0522D" + silver = "#C0C0C0" + skyblue = "#87CEEB" + slateblue = "#6A5ACD" + slategray = "#708090" + snow = "#FFFAFA" + springgreen = "#00FF7F" + steelblue = "#4682B4" + tan = "#D2B48C" + teal = "#008080" + thistle = "#D8BFD8" + tomato = "#FF6347" + turquoise = "#40E0D0" + violet = "#EE82EE" + wheat = "#F5DEB3" + white = "#FFFFFF" + whitesmoke = "#F5F5F5" + yellow = "#FFFF00" + yellowgreen = "#9ACD32" + } + + SlackAppSMBackend ([string]$Token) { + Import-Module PSSlack -Verbose:$false -ErrorAction Stop + + $config = [ConnectionConfig]::new() + $secToken = $Token | ConvertTo-SecureString -AsPlainText -Force + $config.Credential = New-Object System.Management.Automation.PSCredential('asdf', $secToken) + $conn = [SlackAppSMConnection]::New() + $conn.Config = $config + $this.Connection = $conn + } + + # Connect to Slack + [void]Connect() { + $this.LogInfo('Connecting to backend') + $this.LogInfo('Listening for the following message types. All others will be ignored', $this.MessageTypes) + $this.Connection.Connect() + $this.BotId = $this.GetBotIdentity() + $this.LoadUsers() + $this.LoadRooms() + } + + # Receive a message from the websocket + [Message[]]ReceiveMessage() { + $messages = New-Object -TypeName System.Collections.ArrayList + try { + foreach ($slackMessage in $this.Connection.ReadReceiveJob()) { + $this.LogDebug('Received message', (ConvertTo-Json -InputObject $slackMessage -Depth 15 -Compress)) + + # Slack will sometimes send back ephemeral messages from user [SlackBot]. Ignore these + # These are messages like notifing that a message won't be unfurled because it's already + # in the channel in the last hour. Helpful message for some, but not for us. + if ($slackMessage.subtype -eq 'bot_message') { + $this.LogDebug('SubType is [bot_message]. Ignoring') + continue + } + + # Ignore "message_replied" subtypes + # These are message Slack sends to update the client that the original message has a new reply. + # That reply is sent is another message. + # We do this because if the original message that this reply is to is a bot command, the command + # will be executed again so we....need to not do that :) + if ($slackMessage.subtype -eq 'message_replied') { + $this.LogDebug('SubType is [message_replied]. Ignoring') + continue + } + + # We only care about certain message types from Slack + if ($slackMessage.Type -in $this.MessageTypes) { + $msg = [Message]::new() + + # Set the message type and optionally the subtype + #$msg.Type = $slackMessage.type + switch ($slackMessage.type) { + 'channel_rename' { + $msg.Type = [MessageType]::ChannelRenamed + } + 'member_joined_channel' { + $msg.Type = [MessageType]::Message + $msg.SubType = [MessageSubtype]::ChannelJoined + } + 'member_left_channel' { + $msg.Type = [MessageType]::Message + $msg.SubType = [MessageSubtype]::ChannelLeft + } + 'message' { + $msg.Type = [MessageType]::Message + } + 'pin_added' { + $msg.Type = [MessageType]::PinAdded + } + 'pin_removed' { + $msg.Type = [MessageType]::PinRemoved + } + 'presence_change' { + $msg.Type = [MessageType]::PresenceChange + } + 'reaction_added' { + $msg.Type = [MessageType]::ReactionAdded + } + 'reaction_removed' { + $msg.Type = [MessageType]::ReactionRemoved + } + 'star_added' { + $msg.Type = [MessageType]::StarAdded + } + 'star_removed' { + $msg.Type = [MessageType]::StarRemoved + } + 'goodbye' { + # The 'goodbye' event means Slack wants to cease comminication with us + # and they're being nice about it. We need to reestablish the connection. + $this.LogInfo('Received [goodbye] event. Reconnecting to Slack backend...') + $this.Connection.Reconnect() + return $null + } + } + + # The channel the message occured in is sometimes + # nested in an 'item' property + if ($slackMessage.item -and ($slackMessage.item.channel)) { + $msg.To = $slackMessage.item.channel + } + + if ($slackMessage.subtype) { + switch ($slackMessage.subtype) { + 'channel_join' { + $msg.Subtype = [MessageSubtype]::ChannelJoined + } + 'channel_leave' { + $msg.Subtype = [MessageSubtype]::ChannelLeft + } + 'channel_name' { + $msg.Subtype = [MessageSubtype]::ChannelRenamed + } + 'channel_purpose' { + $msg.Subtype = [MessageSubtype]::ChannelPurposeChanged + } + 'channel_topic' { + $msg.Subtype = [MessageSubtype]::ChannelTopicChanged + } + } + } + $this.LogDebug("Message type is [$($msg.Type)`:$($msg.Subtype)]") + + $msg.RawMessage = $slackMessage + $this.LogDebug('Raw message', $slackMessage) + if ($slackMessage.text) { $msg.Text = $slackMessage.text } + if ($slackMessage.channel) { $msg.To = $slackMessage.channel } + if ($slackMessage.user) { $msg.From = $slackMessage.user } + + # Resolve From name + $msg.FromName = $this.ResolveFromName($msg) + + # Resolve channel name + $msg.ToName = $this.ResolveToName($msg) + + # Mark as DM + if ($msg.To -match '^D') { + $msg.IsDM = $true + } + + # Get time of message + $unixEpoch = [datetime]'1970-01-01' + if ($slackMessage.ts) { + $msg.Time = $unixEpoch.AddSeconds($slackMessage.ts) + } elseIf ($slackMessage.event_ts) { + $msg.Time = $unixEpoch.AddSeconds($slackMessage.event_ts) + } else { + $msg.Time = [datetime]::UtcNow + } + + # Sometimes the message is nested in a 'message' subproperty. This could be + # if the message contained a link that was unfurled. We would receive a + # 'message_changed' message and need to look in the 'message' subproperty + # to see who the message was from. Slack is weird + # https://api.slack.com/events/message/message_changed + if ($slackMessage.message) { + if ($slackMessage.message.user) { + $msg.From = $slackMessage.message.user + } + if ($slackMessage.message.text) { + $msg.Text = $slackMessage.message.text + } + } + + # Slack displays @mentions like '@devblackops' but internally in the message + # it is <@U4AM3SYI8> + # Fix that so we actually see the @username + $processed = $this._ProcessMentions($msg.Text) + $msg.Text = $processed + + # ** Important safety tip, don't cross the streams ** + # Only return messages that didn't come from the bot + # else we'd cause a feedback loop with the bot processing + # it's own responses + if (-not $this.MsgFromBot($msg.From)) { + $messages.Add($msg) > $null + } + } else { + $this.LogDebug("Message type is [$($slackMessage.Type)]. Ignoring") + } + + } + } catch { + Write-Error $_ + } + + return $messages + } + + # Send a Slack ping + [void]Ping() { + } + + # Send a message back to Slack + [void]SendMessage([Response]$Response) { + # Process any custom responses + $this.LogDebug("[$($Response.Data.Count)] custom responses") + foreach ($customResponse in $Response.Data) { + + [string]$sendTo = $Response.To + if ($customResponse.DM) { + $sendTo = "@$($this.UserIdToUsername($Response.MessageFrom))" + } + + $threadId = [string]::Empty + if ($customResponse.TH) { + $threadId = "@$($Response.OriginalMessage.RawMessage.ts)" + } + + switch -Regex ($customResponse.PSObject.TypeNames[0]) { + '(.*?)PoshBot\.Card\.Response' { + $this.LogDebug('Custom response is [PoshBot.Card.Response]') + $chunks = $this._ChunkString($customResponse.Text) + $x = 0 + foreach ($chunk in $chunks) { + $attParams = @{ + MarkdownFields = 'text' + Color = $customResponse.Color + } + $fbText = 'no data' + if (-not [string]::IsNullOrEmpty($chunk.Text)) { + $this.LogDebug("Response size [$($chunk.Text.Length)]") + $fbText = $chunk.Text + } + $attParams.Fallback = $fbText + if ($customResponse.Title) { + + # If we chunked up the response, only display the title on the first one + if ($x -eq 0) { + $attParams.Title = $customResponse.Title + } + } + if ($customResponse.ImageUrl) { + $attParams.ImageURL = $customResponse.ImageUrl + } + if ($customResponse.ThumbnailUrl) { + $attParams.ThumbURL = $customResponse.ThumbnailUrl + } + if ($customResponse.LinkUrl) { + $attParams.TitleLink = $customResponse.LinkUrl + } + if ($customResponse.Fields) { + $arr = New-Object System.Collections.ArrayList + foreach ($key in $customResponse.Fields.Keys) { + $arr.Add( + @{ + title = $key; + value = $customResponse.Fields[$key]; + short = $true + } + ) + } + $attParams.Fields = $arr + } + + if (-not [string]::IsNullOrEmpty($chunk)) { + $attParams.Text = '```' + $chunk + '```' + } else { + $attParams.Text = [string]::Empty + } + $att = New-SlackMessageAttachment @attParams + if([string]::IsNullOrEmpty($threadId)){ + $msg = $att | New-SlackMessage -Channel $sendTo -AsUser + }else{ + $msg = $att | New-SlackMessage -Channel $sendTo -AsUser -Thread $threadId + } + $this.LogDebug("Sending card response back to Slack channel [$sendTo]", $att) + $msg | Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Verbose:$false > $null + } + break + } + '(.*?)PoshBot\.Text\.Response' { + $this.LogDebug('Custom response is [PoshBot.Text.Response]') + $chunks = $this._ChunkString($customResponse.Text) + foreach ($chunk in $chunks) { + if ($customResponse.AsCode) { + $t = '```' + $chunk + '```' + } else { + $t = $chunk + } + $this.LogDebug("Sending text response back to Slack channel [$sendTo]", $t) + if([string]::IsNullOrEmpty($threadId)){ + Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $sendTo -Text $t -Verbose:$false -AsUser > $null + }else{ + Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $sendTo -Text $t -Verbose:$false -AsUser -Thread $threadId > $null + } + } + break + } + '(.*?)PoshBot\.File\.Upload' { + $this.LogDebug('Custom response is [PoshBot.File.Upload]') + + $uploadParams = @{ + Token = $this.Connection.Config.Credential.GetNetworkCredential().Password + Channel = $sendTo + } + + if ([string]::IsNullOrEmpty($customResponse.Path) -and (-not [string]::IsNullOrEmpty($customResponse.Content))) { + $uploadParams.Content = $customResponse.Content + if (-not [string]::IsNullOrEmpty($customResponse.FileType)) { + $uploadParams.FileType = $customResponse.FileType + } + if (-not [string]::IsNullOrEmpty($customResponse.FileName)) { + $uploadParams.FileName = $customResponse.FileName + } + } else { + # Test if file exists and send error response if not found + if (-not (Test-Path -Path $customResponse.Path -ErrorAction SilentlyContinue)) { + # Mark command as failed since we could't find the file to upload + $this.RemoveReaction($Response.OriginalMessage, [ReactionType]::Success) + $this.AddReaction($Response.OriginalMessage, [ReactionType]::Failure) + $att = New-SlackMessageAttachment -Color '#FF0000' -Title 'Rut row' -Text "File [$($uploadParams.Path)] not found" -Fallback 'Rut row' + $msg = $att | New-SlackMessage -Channel $sendTo -AsUser + $this.LogDebug("Sending card response back to Slack channel [$sendTo]", $att) + $null = $msg | Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Verbose:$false + break + } + + $this.LogDebug("Uploading [$($customResponse.Path)] to Slack channel [$sendTo]") + $uploadParams.Path = $customResponse.Path + $uploadParams.Title = Split-Path -Path $customResponse.Path -Leaf + } + + if (-not [string]::IsNullOrEmpty($customResponse.Title)) { + $uploadParams.Title = $customResponse.Title + } + + Send-SlackFile @uploadParams -Verbose:$false + if (-not $customResponse.KeepFile -and -not [string]::IsNullOrEmpty($customResponse.Path)) { + Remove-Item -LiteralPath $customResponse.Path -Force + } + break + } + } + } + + if ($Response.Text.Count -gt 0) { + foreach ($t in $Response.Text) { + $this.LogDebug("Sending response back to Slack channel [$($Response.To)]", $t) + Send-SlackMessage -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Channel $Response.To -Text $t -Verbose:$false -AsUser > $null + } + } + } + + # Add a reaction to an existing chat message + [void]AddReaction([Message]$Message, [ReactionType]$Type, [string]$Reaction) { + if ($Message.RawMessage.ts) { + if ($Type -eq [ReactionType]::Custom) { + $emoji = $Reaction + } else { + $emoji = $this._ResolveEmoji($Type) + } + + $body = @{ + name = $emoji + channel = $Message.To + timestamp = $Message.RawMessage.ts + } + $this.LogDebug("Adding reaction [$emoji] to message Id [$($Message.RawMessage.ts)]") + $resp = Send-SlackApi -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Method 'reactions.add' -Body $body -Verbose:$false + if (-not $resp.ok) { + $this.LogInfo([LogSeverity]::Error, 'Error adding reaction to message', $resp) + } + } + } + + # Remove a reaction from an existing chat message + [void]RemoveReaction([Message]$Message, [ReactionType]$Type, [string]$Reaction) { + if ($Message.RawMessage.ts) { + if ($Type -eq [ReactionType]::Custom) { + $emoji = $Reaction + } else { + $emoji = $this._ResolveEmoji($Type) + } + + $body = @{ + name = $emoji + channel = $Message.To + timestamp = $Message.RawMessage.ts + } + $this.LogDebug("Removing reaction [$emoji] from message Id [$($Message.RawMessage.ts)]") + $resp = Send-SlackApi -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Method 'reactions.remove' -Body $body -Verbose:$false + if (-not $resp.ok) { + $this.LogInfo([LogSeverity]::Error, 'Error removing reaction from message', $resp) + } + } + } + + # Resolve a channel name to an Id + [string]ResolveChannelId([string]$ChannelName) { + if ($ChannelName -match '^#') { + $ChannelName = $ChannelName.TrimStart('#') + } + $channelId = ($this.Connection.LoginData.channels | Where-Object name -eq $ChannelName).id + if (-not $ChannelId) { + $channelId = ($this.Connection.LoginData.channels | Where-Object id -eq $ChannelName).id + } + $this.LogDebug("Resolved channel [$ChannelName] to [$channelId]") + return $channelId + } + + # Populate the list of users the Slack team + [void]LoadUsers() { + $this.LogDebug('Getting Slack users') + $allUsers = Get-Slackuser -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Verbose:$false + $this.LogDebug("[$($allUsers.Count)] users returned") + $allUsers | ForEach-Object { + $user = [SlackPerson]::new() + $user.Id = $_.ID + $user.Nickname = $_.Name + $user.FullName = $_.RealName + $user.FirstName = $_.FirstName + $user.LastName = $_.LastName + $user.Email = $_.Email + $user.Phone = $_.Phone + $user.Skype = $_.Skype + $user.IsBot = $_.IsBot + $user.IsAdmin = $_.IsAdmin + $user.IsOwner = $_.IsOwner + $user.IsPrimaryOwner = $_.IsPrimaryOwner + $user.IsUltraRestricted = $_.IsUltraRestricted + $user.Status = $_.Status + $user.TimeZoneLabel = $_.TimeZoneLabel + $user.TimeZone = $_.TimeZone + $user.Presence = $_.Presence + $user.Deleted = $_.Deleted + if (-not $this.Users.ContainsKey($_.ID)) { + $this.LogDebug("Adding user [$($_.ID):$($_.Name)]") + $this.Users[$_.ID] = $user + } + } + + foreach ($key in $this.Users.Keys) { + if ($key -notin $allUsers.ID) { + $this.LogDebug("Removing outdated user [$key]") + $this.Users.Remove($key) + } + } + } + + # Populate the list of channels in the Slack team + [void]LoadRooms() { + $this.LogDebug('Getting Slack channels') + $getChannelParams = @{ + Token = $this.Connection.Config.Credential.GetNetworkCredential().Password + ExcludeArchived = $true + Verbose = $false + Paging = $true + } + $allChannels = Get-SlackChannel @getChannelParams + $this.LogDebug("[$($allChannels.Count)] channels returned") + + $allChannels.ForEach({ + $channel = [SlackChannel]::new() + $channel.Id = $_.ID + $channel.Name = $_.Name + $channel.Topic = $_.Topic + $channel.Purpose = $_.Purpose + $channel.Created = $_.Created + $channel.Creator = $_.Creator + $channel.IsArchived = $_.IsArchived + $channel.IsGeneral = $_.IsGeneral + $channel.MemberCount = $_.MemberCount + foreach ($member in $_.Members) { + $channel.Members.Add($member, $null) + } + $this.LogDebug("Adding channel: $($_.ID):$($_.Name)") + $this.Rooms[$_.ID] = $channel + }) + + foreach ($key in $this.Rooms.Keys) { + if ($key -notin $allChannels.ID) { + $this.LogDebug("Removing outdated channel [$key]") + $this.Rooms.Remove($key) + } + } + } + + # Get the bot identity Id + [string]GetBotIdentity() { + $id = $this.Connection.LoginData.self.id + $this.LogVerbose("Bot identity is [$id]") + return $id + } + + # Determine if incoming message was from the bot + [bool]MsgFromBot([string]$From) { + $frombot = ($this.BotId -eq $From) + if ($fromBot) { + $this.LogDebug("Message is from bot [From: $From == Bot: $($this.BotId)]. Ignoring") + } else { + $this.LogDebug("Message is not from bot [From: $From <> Bot: $($this.BotId)]") + } + return $fromBot + } + + # Get a user by their Id + [SlackPerson]GetUser([string]$UserId) { + $user = $this.Users[$UserId] + if (-not $user) { + $this.LogDebug([LogSeverity]::Warning, "User [$UserId] not found. Refreshing users") + $this.LoadUsers() + $user = $this.Users[$UserId] + } + + if ($user) { + $this.LogDebug("Resolved user [$UserId]", $user) + } else { + $this.LogDebug([LogSeverity]::Warning, "Could not resolve user [$UserId]") + } + return $user + } + + # Get a user Id by their name + [string]UsernameToUserId([string]$Username) { + $Username = $Username.TrimStart('@') + $user = $this.Users.Values | Where-Object {$_.Nickname -eq $Username} + $id = $null + if ($user) { + $id = $user.Id + } else { + # User each doesn't exist or is not in the local cache + # Refresh it and try again + $this.LogDebug([LogSeverity]::Warning, "User [$Username] not found. Refreshing users") + $this.LoadUsers() + $user = $this.Users.Values | Where-Object {$_.Nickname -eq $Username} + if (-not $user) { + $id = $null + } else { + $id = $user.Id + } + } + if ($id) { + $this.LogDebug("Resolved [$Username] to [$id]") + } else { + $this.LogDebug([LogSeverity]::Warning, "Could not resolve user [$Username]") + } + return $id + } + + # Get a user name by their Id + [string]UserIdToUsername([string]$UserId) { + $name = $null + if ($this.Users.ContainsKey($UserId)) { + $name = $this.Users[$UserId].Nickname + } else { + $this.LogDebug([LogSeverity]::Warning, "User [$UserId] not found. Refreshing users") + $this.LoadUsers() + $name = $this.Users[$UserId].Nickname + } + if ($name) { + $this.LogDebug("Resolved [$UserId] to [$name]") + } else { + $this.LogDebug([LogSeverity]::Warning, "Could not resolve user [$UserId]") + } + return $name + } + + # Get the channel name by Id + [string]ChannelIdToName([string]$ChannelId) { + $name = $null + if ($this.Rooms.ContainsKey($ChannelId)) { + $name = $this.Rooms[$ChannelId].Name + } else { + $this.LogDebug([LogSeverity]::Warning, "Channel [$ChannelId] not found. Refreshing channels") + $this.LoadRooms() + $name = $this.Rooms[$ChannelId].Name + } + if ($name) { + $this.LogDebug("Resolved [$ChannelId] to [$name]") + } else { + $this.LogDebug([LogSeverity]::Warning, "Could not resolve channel [$ChannelId]") + } + return $name + } + + # Resolve From name + [string]ResolveFromName([Message]$Message) { + $fromName = $null + if ($Message.From) { + $fromName = $this.UserIdToUsername($Message.From) + } + return $fromName + } + + # Resolve To name + [string]ResolveToName([Message]$Message) { + # Skip DM channels, they won't have names + $toName = $null + if ($Message.To -and $Message.To -notmatch '^D') { + $toName = $this.ChannelIdToName($Message.To) + } + return $toName + } + + # Get all user info by their ID + [hashtable]GetUserInfo([string]$UserId) { + $user = $null + if ($this.Users.ContainsKey($UserId)) { + $user = $this.Users[$UserId] + } else { + $this.LogDebug([LogSeverity]::Warning, "User [$UserId] not found. Refreshing users") + $this.LoadUsers() + $user = $this.Users[$UserId] + } + + if ($user) { + $this.LogDebug("Resolved [$UserId] to [$($user.Nickname)]") + return $user.ToHash() + } else { + $this.LogDebug([LogSeverity]::Warning, "Could not resolve channel [$UserId]") + return $null + } + } + + # Remove extra characters that Slack decorates urls with + hidden [string] _SanitizeURIs([string]$Text) { + $sanitizedText = $Text -replace '<([^\|>]+)\|([^\|>]+)>', '$2' + $sanitizedText = $sanitizedText -replace '<(http([^>]+))>', '$1' + return $sanitizedText + } + + # Break apart a string by number of characters + # This isn't a very efficient method but it splits the message cleanly on + # whole lines and produces better output + hidden [Collections.Generic.List[string]] _ChunkString([string]$Text) { + + # Don't bother chunking an empty string + if ([string]::IsNullOrEmpty($Text)) { + return $text + } + + $chunks = [Collections.Generic.List[string]]::new() + $currentChunkLength = 0 + $currentChunk = '' + $array = $Text -split [Environment]::NewLine + + foreach ($line in $array) { + if (($currentChunkLength + $line.Length) -lt $this.MaxMessageLength) { + $currentChunkLength += $line.Length + $currentChunk += ($line + [Environment]::NewLine) + } else { + $chunks.Add($currentChunk + [Environment]::NewLine) + $currentChunk = ($line + [Environment]::NewLine) + $currentChunkLength = $line.Length + } + } + $chunks.Add($currentChunk) + + return $chunks + } + + # Resolve a reaction type to an emoji + hidden [string]_ResolveEmoji([ReactionType]$Type) { + $emoji = [string]::Empty + Switch ($Type) { + 'Success' { return 'white_check_mark' } + 'Failure' { return 'exclamation' } + 'Processing' { return 'gear' } + 'Warning' { return 'warning' } + 'ApprovalNeeded' { return 'closed_lock_with_key'} + 'Cancelled' { return 'no_entry_sign'} + 'Denied' { return 'x'} + } + return $emoji + } + + # Translate formatted @mentions like <@U4AM3SYI8> into @devblackops + hidden [string]_ProcessMentions([string]$Text) { + $processed = $Text + + $mentions = $processed | Select-String -Pattern '(?<@[^>]*>*)' -AllMatches | ForEach-Object { + $_.Matches | ForEach-Object { + [pscustomobject]@{ + FormattedId = $_.Value + UnformattedId = $_.Value.TrimStart('<@').TrimEnd('>') + } + } + } + $mentions | ForEach-Object { + if ($name = $this.UserIdToUsername($_.UnformattedId)) { + $processed = $processed -replace $_.FormattedId, "@$name" + $this.LogDebug($processed) + } else { + $this.LogDebug([LogSeverity]::Warning, "Unable to translate @mention [$($_.FormattedId)] into a username") + } + } + + return $processed + } +} + +function New-PoshBotSlackAppSMBackend { + <# + .SYNOPSIS + Create a new instance of a Slack backend + .DESCRIPTION + Create a new instance of a Slack backend + .PARAMETER Configuration + The hashtable containing backend-specific properties on how to create the Slack backend instance. + .EXAMPLE + PS C:\> $backendConfig = @{Name = 'SlackBackend'; Token = ''} + PS C:\> $backend = New-PoshBotSlackBackend -Configuration $backendConfig + + Create a Slack backend using the specified API token + .INPUTS + Hashtable + .OUTPUTS + SlackBackend + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='*')] + [cmdletbinding()] + param( + [parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [Alias('BackendConfiguration')] + [hashtable[]]$Configuration + ) + + process { + foreach ($item in $Configuration) { + if (-not $item.Token) { + throw 'Configuration is missing [Token] parameter' + } else { + Write-Verbose 'Creating new Slack backend instance' + $backend = [SlackAppSMBackend]::new($item.Token) + if ($item.Name) { + $backend.Name = $item.Name + } + $backend + } + } + } +} + +Export-ModuleMember -Function 'New-PoshBotSlackAppSMBackend' diff --git a/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 b/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 new file mode 100644 index 0000000..63baab2 --- /dev/null +++ b/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 @@ -0,0 +1,238 @@ +class SlackAppSMConnection : Connection { + [pscustomobject]$LoginData + [string]$UserName + [string]$Domain + [string]$WebSocketUrl + [bool]$Connected + [object]$ReceiveJob = $null + + [void]Connect() { + if ($null -eq $this.ReceiveJob -or $this.ReceiveJob.State -ne 'Running') { + $this.LogDebug('Connecting to Slack Real Time API') + $this.RtmConnect() + $this.StartReceiveJob() + } else { + $this.LogDebug([LogSeverity]::Warning, 'Receive job is already running') + } + } + + # Log in to Slack with the bot token and get a URL to connect to via websockets + [void]RtmConnect() { + $token = $this.Config.Credential.GetNetworkCredential().Password # xapp-... + # $url = "https://slack.com/api/rtm.connect?token=$($token)&pretty=1" + $url = 'https://slack.com/api/apps.connections.open' + + try { + + $r = Invoke-RestMethod -Method POST -Uri $url -Verbose:$false -Headers @{ + 'Content-type' = 'application/x-www-form-urlencoded' + Authorization = "Bearer $token" + } + + # $r = Invoke-RestMethod -Uri $url -Method Get -Verbose:$false + $this.LoginData = $r + if ($r.ok) { + $this.LogInfo('Successfully authenticated to Slack Real Time API') + $this.WebSocketUrl = $r.url + $this.Domain = $r.team.domain + $this.UserName = $r.self.name + } else { + throw $r + } + } catch { + $this.LogInfo([LogSeverity]::Error, 'Error connecting to Slack Real Time API', [ExceptionFormatter]::Summarize($_)) + } + } + + # Setup the websocket receive job + [void]StartReceiveJob() { + $recv = { + [cmdletbinding()] + param( + [parameter(mandatory)] + $url + ) + + # To keep track of ping messages + $pingIntervalSeconds = 10 + $lastMsgId = 0 + + $InformationPreference = 'Continue' + $VerbosePreference = 'Continue' + $DebugPreference = 'Continue' + $ErrorActionPreference = 'Continue' + + # Timer for sending pings + $stopWatch = [Diagnostics.Stopwatch]::new() + $stopWatch.Start() + + # Remove extra characters that Slack decorates urls with + function SanitizeURIs { + param( + [Parameter(mandatory)] + [string]$Text + ) + + $sanitizedText = $Text -replace '<([^\|>]+)\|([^\|>]+)>', '$2' + $sanitizedText = $sanitizedText -replace '<(http([^>]+))>', '$1' + $sanitizedText + } + + # Messages sent via RTM should have a unique, incrementing ID + # https://api.slack.com/rtm + function Get-NextMsgId { + $script:lastMsgId += 1 + $script:lastMsgId + } + + function Send-Ping() { + $json = @{ + id = Get-NextMsgId + type = 'ping' + } | ConvertTo-Json + + [ArraySegment[byte]]$bytes = [Text.Encoding]::UTF8.GetBytes($json) + $webSocket.SendAsync($bytes, [Net.WebSockets.WebSocketMessageType]::Text, $true, $ct).GetAwaiter().GetResult() > $null + } + + # Slack enforces TLS12 on the websocket API + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + + # Connect to websocket + $redactedUrl = "$(Split-Path $url -Parent)\REDACTED" + Write-Verbose "Connecting to websocket at [$($redactedUrl)]" + if ($PSVersionTable.PSVersion.Major -lt 6) { + # In PowerShell 5.1 (and probably 5.0), there is a bug where the websocket conenction will disconenct after 100 seconds + # The workaround is to change the keepalive internval to 0 OR adjust the max service point idel time + # https://stackoverflow.com/questions/40502921/net-websockets-forcibly-closed-despite-keep-alive-and-activity-on-the-connectio + Write-Verbose "PowerShell version is [$($PSVersionTable.PSVersion.ToString())]. Setting [System.Net.ServicePointManager]::MaxServicePointIdleTime to [$([int]::MaxValue.ToString())] to avoid disconnects at 100 seconds." + [System.Net.ServicePointManager]::MaxServicePointIdleTime = [Int]::MaxValue + } + $webSocket = [Net.WebSockets.ClientWebSocket]::new() + $webSocket.Options.KeepAliveInterval = 5 + $cts = [Threading.CancellationTokenSource]::new() + $task = $webSocket.ConnectAsync($url, $cts.Token) + do { [Threading.Thread]::Sleep(10) } + until ($task.IsCompleted) + + # Receive messages and put on output stream so the backend can read them + $buffer = [Net.WebSockets.WebSocket]::CreateClientBuffer(1024,1024) + $ct = [Threading.CancellationToken]::new($false) + $taskResult = $null + + Write-Verbose 'Beginning websocker receive loop' + while ($webSocket.State -eq [Net.WebSockets.WebSocketState]::Open) { + $jsonResult = '' + do { + $taskResult = $webSocket.ReceiveAsync($buffer, $ct) + while (-not $taskResult.IsCompleted -and $webSocket.State -eq [Net.WebSockets.WebSocketState]::Open) { + [Threading.Thread]::Sleep(10) + + # Send "ping" every 5 seconds + if ($stopWatch.Elapsed.Seconds -ge $pingIntervalSeconds) { + Send-Ping + $stopWatch.Restart() + } + } + + if ($webSocket.State -ne [Net.WebSockets.WebSocketState]::Open) { + Write-Error "Websocket error. Connection state is [$($webSocket.State)]" + } + + $jsonResult += [Text.Encoding]::UTF8.GetString($buffer, 0, $taskResult.Result.Count) + } until ( + $webSocket.State -ne [Net.WebSockets.WebSocketState]::Open -or $taskResult.Result.EndOfMessage + ) + + if (-not [string]::IsNullOrEmpty($jsonResult)) { + # Write-Debug "Received JSON: $jsonResult" + $sanitizedJson = SanitizeURIs -Text $jsonResult + + $msgs = ConvertFrom-Json $sanitizedJson | Select-Object -ExpandProperty payload | Select-Object -ExpandProperty event + foreach ($msg in $msgs) { + # Ingore "pong" and "hello" messages as they aren't important to the backend + if ($msg.type -ne 'pong' -and $msg.type -ne 'hello') { + $msg + } + } + } + } + + $socketStatus = [pscustomobject]@{ + State = $webSocket.State + CloseStatus = $webSocket.CloseStatus + CloseStatusDescription = $webSocket.CloseStatusDescription + } + $socketStatusStr = ($socketStatus | Format-List | Out-String).Trim() + Write-Warning -Message "Websocket state is [$($webSocket.State.ToString())].`n$socketStatusStr" + } + + try { + $jobParams = @{ + Name = 'ReceiveRtmMessages' + ScriptBlock = $recv + ArgumentList = $this.WebSocketUrl + } + $this.ReceiveJob = Start-Job @jobParams + $this.Connected = $true + $this.Status = [ConnectionStatus]::Connected + $this.LogInfo("Started websocket receive job [$($this.ReceiveJob.Id)]") + } catch { + $this.LogInfo([LogSeverity]::Error, "$($_.Exception.Message)", [ExceptionFormatter]::Summarize($_)) + } + } + + # Read all available data from the job + [System.Collections.Generic.List[PSCustomObject]]ReadReceiveJob() { + # Read stream info from the job so we can log them + $infoStream = $this.ReceiveJob.ChildJobs[0].Information.ReadAll() + $warningStream = $this.ReceiveJob.ChildJobs[0].Warning.ReadAll() + $errStream = $this.ReceiveJob.ChildJobs[0].Error.ReadAll() + $verboseStream = $this.ReceiveJob.ChildJobs[0].Verbose.ReadAll() + $debugStream = $this.ReceiveJob.ChildJobs[0].Debug.ReadAll() + foreach ($item in $infoStream) { + $this.LogInfo($item.ToString()) + } + foreach ($item in $warningStream) { + $this.LogInfo([LogSeverity]::Warning, $item.ToString()) + } + foreach ($item in $errStream) { + $this.LogInfo([LogSeverity]::Error, $item.ToString()) + } + foreach ($item in $verboseStream) { + $this.LogVerbose($item.ToString()) + } + foreach ($item in $debugStream) { + $this.LogVerbose($item.ToString()) + } + + # The receive job stopped for some reason. Reestablish the connection if the job isn't running + if ($this.ReceiveJob.State -ne 'Running') { + $this.LogInfo([LogSeverity]::Warning, "Receive job state is [$($this.ReceiveJob.State)]. Attempting to reconnect...") + $this.Reconnect() + } + + $messages = [Collections.Generic.List[PSCustomObject]]::new() + if ($this.ReceiveJob.HasMoreData) { + $messages.AddRange($this.ReceiveJob.ChildJobs[0].Output.ReadAll()) + } + return $messages + } + + # Stop the receive thread + [void]Disconnect() { + $this.LogInfo('Closing websocket') + if ($this.ReceiveJob) { + $this.LogInfo("Stopping receive job [$($this.ReceiveJob.Id)]") + $this.ReceiveJob | Stop-Job -Confirm:$false -PassThru | Remove-Job -Force -ErrorAction SilentlyContinue + } + $this.Connected = $false + $this.Status = [ConnectionStatus]::Disconnected + } + + [void]Reconnect() { + $this.Disconnect() + Start-Sleep -Seconds 5 + $this.Connect() + } +} diff --git a/PoshBot/PoshBot.psd1 b/PoshBot/PoshBot.psd1 index a11e97e..ce19bda 100644 --- a/PoshBot/PoshBot.psd1 +++ b/PoshBot/PoshBot.psd1 @@ -8,7 +8,7 @@ RootModule = 'PoshBot.psm1' # Version number of this module. -ModuleVersion = '0.14.31' +ModuleVersion = '0.14.32' # Supported PSEditions # CompatiblePSEditions = @() From 97869e5300b90e844e81d124ac8ff0653f412b9d Mon Sep 17 00:00:00 2001 From: Andriy Golubenkov FUIB VM Date: Wed, 2 Oct 2024 19:19:36 +0300 Subject: [PATCH 6/6] Slack SocketMode - added acknowledgment --- PoshBot/Classes/ConnectionConfig.ps1 | 2 + .../SlackAppSM/SlackAppSMBackend.ps1 | 12 +++- .../SlackAppSM/SlackAppSMConnection.ps1 | 56 +++++++++++++++-- PoshBot/PoshBot.psd1 | 1 + .../functions/New-PoshBotSlackAppSMBackend.md | 61 +++++++++++++++++++ docs/reference/functions/PoshBot.md | 3 + 6 files changed, 128 insertions(+), 7 deletions(-) create mode 100644 docs/reference/functions/New-PoshBotSlackAppSMBackend.md diff --git a/PoshBot/Classes/ConnectionConfig.ps1 b/PoshBot/Classes/ConnectionConfig.ps1 index 8f11820..5c9bfcf 100644 --- a/PoshBot/Classes/ConnectionConfig.ps1 +++ b/PoshBot/Classes/ConnectionConfig.ps1 @@ -7,6 +7,8 @@ class ConnectionConfig { [pscredential]$Credential + [pscredential]$CredentialApp + ConnectionConfig() {} ConnectionConfig([string]$Endpoint, [pscredential]$Credential) { diff --git a/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 b/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 index 059f1b6..903e701 100644 --- a/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 +++ b/PoshBot/Implementations/SlackAppSM/SlackAppSMBackend.ps1 @@ -163,12 +163,17 @@ class SlackAppSMBackend : Backend { yellowgreen = "#9ACD32" } - SlackAppSMBackend ([string]$Token) { + SlackAppSMBackend ([string]$Token,[string]$TokenApp) { Import-Module PSSlack -Verbose:$false -ErrorAction Stop $config = [ConnectionConfig]::new() + $secToken = $Token | ConvertTo-SecureString -AsPlainText -Force + $secTokenApp = $TokenApp | ConvertTo-SecureString -AsPlainText -Force + $config.Credential = New-Object System.Management.Automation.PSCredential('asdf', $secToken) + $config.CredentialApp = New-Object System.Management.Automation.PSCredential('asdf', $secTokenApp) + $conn = [SlackAppSMConnection]::New() $conn.Config = $config $this.Connection = $conn @@ -569,6 +574,9 @@ class SlackAppSMBackend : Backend { [void]LoadUsers() { $this.LogDebug('Getting Slack users') $allUsers = Get-Slackuser -Token $this.Connection.Config.Credential.GetNetworkCredential().Password -Verbose:$false + + # $allUsers = Get-Slackuser -Token $token_bot -Verbose:$false + $this.LogDebug("[$($allUsers.Count)] users returned") $allUsers | ForEach-Object { $user = [SlackPerson]::new() @@ -888,7 +896,7 @@ function New-PoshBotSlackAppSMBackend { throw 'Configuration is missing [Token] parameter' } else { Write-Verbose 'Creating new Slack backend instance' - $backend = [SlackAppSMBackend]::new($item.Token) + $backend = [SlackAppSMBackend]::new($item.Token,$item.TokenApp) if ($item.Name) { $backend.Name = $item.Name } diff --git a/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 b/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 index 63baab2..8e60745 100644 --- a/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 +++ b/PoshBot/Implementations/SlackAppSM/SlackAppSMConnection.ps1 @@ -18,24 +18,47 @@ class SlackAppSMConnection : Connection { # Log in to Slack with the bot token and get a URL to connect to via websockets [void]RtmConnect() { - $token = $this.Config.Credential.GetNetworkCredential().Password # xapp-... + $token_app = $this.Config.CredentialApp.GetNetworkCredential().Password # xapp-... + $token_bot = $this.Config.Credential.GetNetworkCredential().Password # xapp-... # $url = "https://slack.com/api/rtm.connect?token=$($token)&pretty=1" + + # https://api.slack.com/apis/socket-mode $url = 'https://slack.com/api/apps.connections.open' try { $r = Invoke-RestMethod -Method POST -Uri $url -Verbose:$false -Headers @{ 'Content-type' = 'application/x-www-form-urlencoded' - Authorization = "Bearer $token" + Authorization = "Bearer $token_app" } + $rb = Invoke-RestMethod -Method POST -Uri 'https://slack.com/api/auth.test?pretty=1' -Verbose:$false -Headers @{ + 'Content-type' = 'application/x-www-form-urlencoded' + Authorization = "Bearer $token_bot" + } + + $rc = Invoke-RestMethod -Method GET -Uri 'https://slack.com/api/conversations.list' -Headers @{ + 'Content-type' = 'application/x-www-form-urlencoded' + Authorization = "Bearer $token_bot" + } + #$rc.channels + # LoginData.self.id + # $this.Connection.LoginData.channels + # $r = Invoke-RestMethod -Uri $url -Method Get -Verbose:$false - $this.LoginData = $r + # $this.LoginData = $r + $this.LoginData = [PsCustomObject]@{ + channels = $rc.channels + self = [PsCustomObject]@{ + id = $rb.user_id + } + } + if ($r.ok) { $this.LogInfo('Successfully authenticated to Slack Real Time API') $this.WebSocketUrl = $r.url - $this.Domain = $r.team.domain - $this.UserName = $r.self.name + $this.Domain = $rb.team #$rb.team.domain + $this.UserName = $rb.user #$r.self.name } else { throw $r } @@ -144,7 +167,30 @@ class SlackAppSMConnection : Connection { $webSocket.State -ne [Net.WebSockets.WebSocketState]::Open -or $taskResult.Result.EndOfMessage ) + + if (-not [string]::IsNullOrEmpty($jsonResult)) { + + #region acknowledgment + # Prepare the acknowledgment message + $ackPayload = @{ + envelope_id = ($jsonResult | convertfrom-json).envelope_id + } | ConvertTo-Json + + # Convert the message to bytes + $ackBytes = [System.Text.Encoding]::UTF8.GetBytes($ackPayload) + + # Send the acknowledgment + $sendBuffer = [ArraySegment[byte]]$ackBytes + # Send - v1 + # $sendTask = $webSocket.SendAsync($sendBuffer, [Net.WebSockets.WebSocketMessageType]::Text, $true, $ct) + # $sendTask.Wait() + + # Send - v2 + $webSocket.SendAsync($sendBuffer, [Net.WebSockets.WebSocketMessageType]::Text, $true, $ct).GetAwaiter().GetResult() > $null + + #endregion acknowledgment + # Write-Debug "Received JSON: $jsonResult" $sanitizedJson = SanitizeURIs -Text $jsonResult diff --git a/PoshBot/PoshBot.psd1 b/PoshBot/PoshBot.psd1 index ce19bda..9ba8f43 100644 --- a/PoshBot/PoshBot.psd1 +++ b/PoshBot/PoshBot.psd1 @@ -83,6 +83,7 @@ FunctionsToExport = @( 'New-PoshBotMiddlewareHook' 'New-PoshBotScheduledTask' 'New-PoshBotSlackBackend' + 'New-PoshBotSlackAppSMBackend' 'New-PoshBotTeamsBackend' 'New-HelloPlugin' 'New-PoshBotCardResponse' diff --git a/docs/reference/functions/New-PoshBotSlackAppSMBackend.md b/docs/reference/functions/New-PoshBotSlackAppSMBackend.md new file mode 100644 index 0000000..23bc73a --- /dev/null +++ b/docs/reference/functions/New-PoshBotSlackAppSMBackend.md @@ -0,0 +1,61 @@ +--- +external help file: PoshBot-help.xml +Module Name: PoshBot +online version: +schema: 2.0.0 +--- + +# New-PoshBotSlackAppSMBackend + +## SYNOPSIS +Create a new instance of a Slack backend + +## SYNTAX + +``` +New-PoshBotSlackAppSMBackend [-Configuration] [] +``` + +## DESCRIPTION +Create a new instance of a Slack backend + +## EXAMPLES + +### EXAMPLE 1 +``` +$backendConfig = @{Name = 'SlackBackend'; Token = ''} +``` + +PS C:\\\> $backend = New-PoshBotSlackBackend -Configuration $backendConfig + +Create a Slack backend using the specified API token + +## PARAMETERS + +### -Configuration +The hashtable containing backend-specific properties on how to create the Slack backend instance. + +```yaml +Type: Hashtable[] +Parameter Sets: (All) +Aliases: BackendConfiguration + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Hashtable +## OUTPUTS + +### SlackBackend +## NOTES + +## RELATED LINKS diff --git a/docs/reference/functions/PoshBot.md b/docs/reference/functions/PoshBot.md index ede4c6a..da89c44 100644 --- a/docs/reference/functions/PoshBot.md +++ b/docs/reference/functions/PoshBot.md @@ -41,6 +41,9 @@ Locale: en-US ### [New-PoshBotScheduledTask](New-PoshBotScheduledTask.md) {{ Fill in the Description }} +### [New-PoshBotSlackAppSMBackend](New-PoshBotSlackAppSMBackend.md) +{{ Fill in the Description }} + ### [New-PoshBotSlackBackend](New-PoshBotSlackBackend.md) {{ Fill in the Description }}