Git Product home page Git Product logo

psslack's Introduction

Build status

PSSlack

This is a quick and dirty module to interact with the Slack API.

Pull requests and other contributions would be welcome!

Instructions

# One time setup
    # Download the repository
    # Unblock the zip
    # Extract the PSSlack folder to a module path (e.g. $env:USERPROFILE\Documents\WindowsPowerShell\Modules\)
# Or, with PowerShell 5 or later or PowerShellGet:
    Install-Module PSSlack

# Import the module.
    Import-Module PSSlack    #Alternatively, Import-Module \\Path\To\PSSlack

# Get commands in the module
    Get-Command -Module PSSlack

# Get help
    Get-Help Send-SlackMessage -Full
    Get-Help about_PSSlack

Prerequisites

Examples

Send a Simple Slack Message

# This example shows a crudely crafted message without any attachments,
# using parameters from Send-SlackMessage to construct the message.

#Previously set up Uri from https://<YOUR TEAM>.slack.com/apps/A0F7XDUAZ
$Uri = "Some incoming webhook uri from Slack"

Send-SlackMessage -Uri $Uri `
                  -Channel '@wframe' `
                  -Parse full `
                  -Text 'Hello @wframe, join me in #devnull!'

# Send a message to @wframe (not a channel), parsing the text to linkify usernames and channels

      Simple Send-SlackMessage

Search for a Slack Message

# Search for a message containing PowerShell, sorting results by timestamp

Find-SlackMessage -Token $Token `
                  -Query 'PowerShell' `
                  -SortBy timestamp

      Find Message

# Search for a message containing PowerShell
# Results are sorted by best match by default
# Notice the extra properties and previous/next messages

Find-SlackMessage -Token $Token `
                  -Query 'PowerShell' |
    Select-Object -Property *

      Find Message Select All

You could use this simply to search Slack from the CLI, or in an automated solution that might avoid posting if certain content is already found in Slack.

Send a Richer Slack Message

# This is a simple example illustrating some common options
# when constructing a message attachment
# giving you a richer message

$Token = 'A token. maybe from https://api.slack.com/docs/oauth-test-tokens'

New-SlackMessageAttachment -Color $([System.Drawing.Color]::red) `
                           -Title 'The System Is Down' `
                           -TitleLink https://www.youtube.com/watch?v=TmpRs7xN06Q `
                           -Text 'Please Do The Needful' `
                           -Pretext 'Everything is broken' `
                           -AuthorName 'SCOM Bot' `
                           -AuthorIcon 'http://ramblingcookiemonster.github.io/images/tools/wrench.png' `
                           -Fallback 'Your client is bad' |
    New-SlackMessage -Channel '@wframe' `
                     -IconEmoji :bomb: |
    Send-SlackMessage -Token $Token

      Rich messages

Notice that the title is clickable. You might link to...

  • The alert in question
  • A logging solution query
  • A dashboard
  • Some other contextual link
  • Strongbad

Send Multiple Slack Attachments

# This example demonstrates that you can chain new attachments
# together to form a multi-attachment message

$Token = 'A token. maybe from https://api.slack.com/docs/oauth-test-tokens'

New-SlackMessageAttachment -Color $_PSSlackColorMap.red `
                           -Title 'The System Is Down' `
                           -TitleLink https://www.youtube.com/watch?v=TmpRs7xN06Q `
                           -Text 'Everybody panic!' `
                           -Pretext 'Everything is broken' `
                           -Fallback 'Your client is bad' |
    New-SlackMessageAttachment -Color $([System.Drawing.Color]::Orange) `
                               -Title 'The Other System Is Down' `
                               -TitleLink https://www.youtube.com/watch?v=TmpRs7xN06Q `
                               -Text 'Please Do The Needful' `
                               -Fallback 'Your client is bad' |
    New-SlackMessage -Channel '@wframe' `
                     -IconEmoji :bomb: `
                     -AsUser `
                     -Username 'SCOM Bot' |
    Send-SlackMessage -Token $Token

      Multiple Attachments

Notice that we can chain multiple New-SlackMessageAttachments together.

Send a Table of Key Value Pairs

# This example illustrates a pattern where you might
# want to send output from a script; you might
# include errors, successful items, or other output

# Pretend we're in a script, and caught an exception of some sort
$Fail = [pscustomobject]@{
    samaccountname = 'bob'
    operation = 'Remove privileges'
    status = "An error message"
    timestamp = (Get-Date).ToString()
}

# Create an array from the properties in our fail object
$Fields = @()
foreach($Prop in $Fail.psobject.Properties.Name)
{
    $Fields += @{
        title = $Prop
        value = $Fail.$Prop
        short = $true
    }
}

$Token = 'A token. maybe from https://api.slack.com/docs/oauth-test-tokens'

# Construct and send the message!
New-SlackMessageAttachment -Color $([System.Drawing.Color]::Orange) `
                           -Title 'Failed to process account' `
                           -Fields $Fields `
                           -Fallback 'Your client is bad' |
    New-SlackMessage -Channel 'devnull' |
    Send-SlackMessage -Uri $uri

# We build up a pretend error object, and send each property to a 'Fields' array
# Creates an attachment with the fields from our error
# Creates a message fromthat attachment and sents it with a uri

      Fields

Store and Retrieve Configs

To save time and typing, you can save a token or uri to a config file (protected via DPAPI) and a module variable.

This is used as the default for commands, and is reloaded if you open a new PowerShell session.

# Save a Uri and Token.
# If both are specified, token takes precedence.
Set-PSSlackConfig -Uri 'SomeSlackUri' -Token 'SomeSlackToken'

# Read the current cofig
Get-PSSlackConfig

Notes

Currently evaluating .NET Core / Cross-platform functionality. The following will not work initially:

  • Serialization of URIs and tokens via Set-PSSlackConfig. Set these values per-session if needed
  • [System.Drawing.Color]::SomeColor shortcut. Use the provided $_PSSlackColorMap hash to simplify this. E.g. $_PSSlackColorMap.red

There are a good number of Slack functions out there, including jgigler's PowerShell.Slack and Steven Murawski's Slack. We borrowed some ideas and code from these - thank you!

If you want to go beyond interacting with the Slack API, you might consider using a bot

psslack's People

Contributors

adbertram avatar devblackops avatar dwof avatar gabeech avatar hmmwhatsthisdo avatar joshcorr avatar kanjibates avatar kenerwin88 avatar kittzus avatar magallz1 avatar nathanthorpe avatar nmbro avatar pauljordan avatar ramblingcookiemonster avatar rukas avatar terrapinstation avatar webbexpert avatar wsmelton avatar xoph avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psslack's Issues

Newlines showing as literal '\n'

According to the Slack API for multi-line messages (which was taken from Get-Help Send-SlackMessage -Parameter Text) you send a multi-line message by adding \n. However when adding this to text the actual \n is shown in the next.

The code I used was from the README:

> Send-SlackMessage -Uri $Uri `
                   -Channel '#test' `
                   -Parse full `
                   -Text 'Hello @pauby,\njoin me in #general!'

> New-SlackMessageAttachment -Color $([System.Drawing.Color]::red) `
                            -Title 'The System Is Down' `
                            -TitleLink https://www.youtube.com/watch?v=TmpRs7xN06Q `
                            -Text 'Please\nDo The Needful' `
                            -Pretext 'Everything is broken' `
                            -AuthorName 'SCOM Bot' `
                            -AuthorIcon 'http://ramblingcookiemonster.github.io/images/tools/wrench.png' `
                            -Fallback 'Your client is bad' |
     New-SlackMessage -Channel '#test' `
                      -IconEmoji :bomb: |
     Send-SlackMessage -Uri $Uri
``

Results in:

![image](https://user-images.githubusercontent.com/12760779/49687366-b4af7b00-faf9-11e8-996b-b0f0619bb025.png)

I've tried this from two different computers and posting to two different slack groups and different slack channels all with the same results.

Is this an issue, expected behaviour or something else?

Add support for posting interactive messages

I'm starting to brainstorm how I can add support for interactive messages in PoshBot. Creating a interactive message using PSSlack with a bit of extra properties on the attachment object is easy enough but it would be nice if PSSlack supported those constructs natively.

Example of posting interactive message

$tok = '<your-token>'

$attParams = @{
    Text = 'Choose a game to play'
    Fallback = 'You are unable to choose a game'
    Color = '#3AA3E3'
}
$att = New-SlackMessageAttachment @attParams
$att.callback_id = 'wopr_game'
$att.attachment_type = 'default'
$att.actions = @(
    @{
        name = 'game'
        text = 'Chess'
        type = "button"
        value = "chess"
    }
    @{
        name = "game"
        text = "Falken's Maze"
        type = "button"
        value = "maze"
    }
    @{
        name = "game"
        text = "Thermonuclear War"
        style = "danger"
        type = "button"
        value = "war"
        confirm = @{
            title = "Are you sure?"
            text = "Wouldn't you prefer a good game of chess?"
            ok_text = "Yes"
            dismiss_text = "No"
        }
    }
)

$text = 'Would you like to play a game?'
$m = New-SlackMessage -Channel 'testing' -Text $text -AsUser -Attachments $att
$m | Send-SlackMessage -Token $tok -Verbose

Maybe the following new parameters could be added to New-SlackMessageAttachment to support button and menus?

  • callback_id
  • attachment_type
  • actions

New functions for creating the button/menu actions and just a single Actions parameters on New-SlackMessageAttachment could also make sense. Food for thought.

Reference

Interactive Buttons
Interactive Menus

Remove-SlackFile output is confusing

When I'm removing a lot of files, like:

Get-SlackFileInfo -Before 1/1/2017 -Paging | Remove-SlackFile -Force

I get output like this:

Id          ok Raw
--          -- ---
F09P74HUJ True @{ok=True}
...
390 lines ....
...
F09GSG79Q True @{ok=True}
F09GSA6SX True @{ok=True}
F09FX0996 True @{ok=True}
Send-SlackApi : Slack API call failed: The remote server returned an error: (429) Too Many Requests.
At C:\Users\Jaykul\Documents\WindowsPowerShell\Modules\PSSlack\0.0.36\Public\Remove-SlackFile.ps1:59 char:33
+                     $Response = Send-SlackApi @params
+                                 ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WebException
    + FullyQualifiedErrorId : System.Net.WebException,Send-SlackApi
F09FFSHEG True @{ok=True}

Other than the file ID, I'm not sure what the output is supposed to mean, since it says True @{ok=True} even when there's an error!

It's pretty clear that it needs to stop if there's an error, or pause (see #67) and the (limit headers API docs).

Encrypt token and Uri in PSSlack.xml

Use DPAPI to protect this data. Production solutions would ideally pull these secrets from a secret management solution, but would be safer to encrypt to avoid abuse, and enable ad hoc CLI use without storing this data in the clear.

Add authenticated proxy support to PSSlack

Thanks to Alexandru Lazar for this:

I just add (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials at the beginning of the script. this will use the proxy settings and credentials of the user under which the script is ran.

For folks using other credentials, that bit of code should at least get you started in the right direction, feel free to reply here with other solutions

Closing this out for now. Eventually could re-open it and build support into the PSSlack config, but IMHO the workaround is sufficient.

Identify useful Slack API methods

There are a number of methods that could come in handy.

If any in particular catch your eye, open an issue with...

  • A suggested function name
  • A link to the method
  • Example scenarios this might enable

Need support for SecureString for tokens

As a user of a company computer
In order to avoid leaving my token in a log
I need to be able to enter my token -AsSecureString

Please provide a way to Set-PSSlackConfig the token as a SecureString. Currently it "works" with no errors, but it stores "System.Security.SecureString" as the token -- took me running it in Verbose to figure out what was going wrong.

Send-SlackMessage does not specify ContentType.

Test Case

Send a simple message:
$web_hook_addr = "//hooks.slack.com/services/{...}"
Send-SlackMessage -Uri $web_hook_addr -Text 'Atenção'

Expected Behavior

incoming-webhook APP [1:28 PM]
Atenção

Current Behavior

incoming-webhook APP [1:28 PM]
AtenBAD+7BAD+3o

Possible Solution

Create a new parameter ContentType in the file SendSlackMessage.ps1 with default value "text/plain; charset=utf-8".

Use the new contentType parameter:
Invoke-RestMethod @ProxyParam -Method Post -Body $json -Uri $Uri -ContentType $ContentType

Context

I´m use this excelent powershell module to send some backend events to a multi-language team, i have some issues with messages were written in portuguese.

Generic PSSlack.xml causes issues when module is shared between multiple users or computers

Issue frenzy! Lol...

So, I actually have a resolution to this. Since the XML creation process prevents that same config from being synced and used on multiple machines or between multiple users on the same machine (and this is a good thing, tbh), I updated my PSM1 and the Get-/Set-PSSlackConfig functions to use the following format for the config name:

$env:USERNAME-$env:COMPUTERNAME-PSSlack.xml

Q: Unable to connect using webhook

Hello,

I don't do this often but I hope this is OK place to ask qeustion :)

I am using this module and webhook but I am unable to connect using webhook (I have tried token version and I am getting the same error).

So this is my code (nothing was changed from example except for formatting it in one line):

$Uri = "https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX"
Send-SlackMessage -Uri $Uri -Channel '@corfinsat-builds-msbi' -Parse full -Text 'Hello!'

And after running this code I am getting this error:
image
(sorry, I could not paste it as text in a readable way)

So my questions are:
Is this only related to wrong credential or webhook? I use this webhook in Bamboo build to send notifications to it should be working.
Our company is using SingleSignOn to sign in to slack, do I need to add additional parameter?

As mentioned I have tried the example with message with attachment and token but it had the same error as well.

Should the channel name be with # or @ ?
Webhook has specified channel in it, does it matter?

Thanks for any help.
B.

Ephemeral Message Support & Throw on Error Support

Hello,

Source code for potential pull request (more info below): https://github.com/smaglio81/PSSlack/tree/ephemeralthrow

I would like to add support for sending Ephemeral messages and the ability to Throw errors received from the Slack API.

Ephemeral Messages

Slack has added a chat.postEphemeral option which lets you send a private message to a user in a channel. You may have seen slackbot send you messages before that say 'This message is only visible to you'. Those are ephemeral messages.

Throw on Error

Programmatically I wanted to be able to catch the errors that were sent back from Slack. There's probably a better way of doing it, but I'm really used to Try/Catch blocks. Parse-SlackError.ps1 uses Write-Error to deliver the error message which I wasn't able to capture using the methodolgy I was used to. Is there a better way to do this?

Right now, I'm suppressing Write-Error and catching the newly thrown error:

$preEAP = $global:ErrorActionPreference
$global:ErrorActionPreference = 'SilentlyContinue'
try {
	PSSlack\Send-SlackMessage -Text $text -Channel $channel -Token $token -Username $username -Throw | Out-Null
} finally {
	$global:ErrorActionPreference = $preEAP
}

Pull Request

So ... I'm very inexperienced when it comes to contributing to github projects. And, I'm pretty unknowledgable when it comes to git. I tried to follow the Contributing Guidelines as best I could, but there are a couple of issues I ran into which make me feel uncomfortable creating a pull request for the project.

The project is at (branch 'ephemeralthrow'): https://github.com/smaglio81/PSSlack/tree/ephemeralthrow

Issues

  • Whitespace on the end of lines: I have VSCode setup to Trim Trailing Whitespace but git diff --check keeps reporting extra whitespace on the end of changed lines. I tried following this stackoverflow post but I don't think I did it right as the whitespace still appeared.
  • I was unable to run the Pester tests successfully. On my machine (Pester 4.6.0) I receive the below error (I don't run into any problems when I use the module though):
PS D:\Projects\Main\Powershell\PSSlack> invoke-pester
Executing all tests in '.'

Executing script D:\Projects\Main\Powershell\PSSlack\Tests\PSSlack.Tests.ps1
  [-] Error occurred in test script 'D:\Projects\Main\Powershell\PSSlack\Tests\PSSlack.Tests.ps1' 0ms
    ParameterBindingValidationException: Cannot bind argument to parameter 'Path' because it is null.
    at <ScriptBlock>, D:\Projects\Main\Powershell\PSSlack\Tests\PSSlack.Tests.ps1: line 3
    at <ScriptBlock>, D:\Projects\Main\Powershell\Ucsb.Sa.Powershell\Pester\Pester.psm1: line 1095
    at Invoke-Pester<End>, D:\Projects\Main\Powershell\Ucsb.Sa.Powershell\Pester\Pester.psm1: line 1121
Tests completed in 41ms
Tests Passed: 0, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0

$PSVersionTable

PSVersion                      5.1.17134.407
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.407
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

macOS/Linux support

Greeting Starfighter!

There appear to be a few environment variable related things that prevent PSSlack from working fully on macOS/Linux.

> Set-PSSlackConfig
Export-Clixml : Access to the path '/--PSSlack.xml' is denied.
At /Users/brandon/.local/share/powershell/Modules/PSSlack/0.0.31/Public/Set-PSSlackConfig.ps1:77 char:9
+         Export-Clixml -Path $Path -force
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OpenError: (:) [Export-Clixml], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportClixmlCommand

Specifically, these don't exist in PWSH on macOS:
$env:TEMP, $env:USERNAME, $env:COMPUTERNAME

Here is what is available on my machine:

> (Get-ChildItem env:).Name
_
__CF_USER_TEXT_ENCODING
Apple_PubSub_Socket_Render
COLORFGBG
COLORTERM
COMMAND_MODE
HOME
ITERM_PROFILE
ITERM_SESSION_ID
LANG
LOGNAME
PATH
PSModulePath
PWD
SECURITYSESSIONID
SHELL
SHLVL
SSH_AUTH_SOCK
TERM
TERM_PROGRAM
TERM_PROGRAM_VERSION
TERM_SESSION_ID
TMPDIR
USER
XPC_FLAGS
XPC_SERVICE_NAME

I ran into some similar issues with PoshBot when testing on macOS and decided to perform some logic in the PSM1 and come up with my own variables for use by the various functions.

Perhaps PSSlack will need the same and use $env:TMPDIR and $env:USER in place of $env:TEMP and $env:USERNAME. $env:COMPUTERNAME could be replaced with the value from the hostname command.

What do you think?

Proxy config not accounted for in all commands

Several commands do not allow override of a proxy, and do not inherit the $PSSlack.proxy config. For example - using Send-SlackFile -Path...

At the very least, these should check PSSlack.proxy and add a proxy to invoke-webrequest (if they use send-slackapi this already takes place). Ideally, we allow an override for each command

Private channels not returned by Get-SlackChannel

Expected Behavior

Get-SlackChannel to return all channels

Current Behavior

Get-SlackChannel only returns public channels

Possible Solution

Issue caused by slack changing its API and depreciating channels.list for conversations.list

Context

Issues when using the poshbotio/PoshBot script being unable to limit bot to private channels as they are not being returned by the Get-SlackChannel function.

Chaining 3+ attachments causes duplicated text

When you chain 3 or more New-SlackMessageAttachment's together, it causes the attachments to be duplicated when posted to slack.

This code (3 chains):

New-SlackMessageAttachment -Pretext 'Web automation complete!' -Fallback 'Your client is bad' |
    New-SlackMessageAttachment -Text 'succeeded' -Fallback 'nope' |
    New-SlackMessageAttachment -Text 'ignored' -Fallback 'nope' |
    New-SlackMessage -Channel 'general'
    Send-SlackMessage -Token $Token

will result in the final chain ("Ignored" text) being duplicated:

Web automation complete!
Ignored
Succeeded
Ignored

This code (4 chains):

New-SlackMessageAttachment -Pretext 'Web automation complete!' -Fallback 'Your client is bad' |
    New-SlackMessageAttachment -Text 'succeeded' -Fallback 'nope' |
    New-SlackMessageAttachment -Text 'ignored' -Fallback 'nope' |
    New-SlackMessageAttachment -Text 'failed' -Fallback 'nope' |
    New-SlackMessage -Channel 'general'
    Send-SlackMessage -Token $Token

will result in the 3rd chain being duplicated twice ("Ignored" text), and the 4th chain being duplicated 4 times("Failed" text):

Web automation complete!
Failed
Ignored
Failed
Succeeded
Failed
Ignored
Failed

Add function: New-SlackSnippet

This would leverage the files.upload method (https://api.slack.com/methods/files.upload) to add a snippet of code/text/etc. Useful for long error catching, since a simple Slack attachment is typically more direct. Options would include syntax (as defined on the method page), initial comment, etc.

Going to dig through the buildout of the existing functions and see what I can come up with =]

Errors running Set-psslackconfig

Warren,

I'm doing something fundamentally stupid and I can't see it. If I run set-psslackconfig on a newly patched Windows 10 or Server 2012 R2 system I get the following errors:

set-psslackonfig -Uri -Token

The property 'Uri' cannot be found on this object. Verify that the property exists and can be set.
At C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.16\Public\Set-PSSlackConfig.ps1:47 char:16

  •     'Uri'{ $Script:PSSlack.Uri = $Uri }
    
  •            ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : PropertyNotFound

The property 'Token' cannot be found on this object. Verify that the property exists and can be set.
At C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.16\Public\Set-PSSlackConfig.ps1:48 char:18

  •     'Token'{ $Script:PSSlack.Token = $Token }
    
  •              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : PropertyNotFound

It's barfing on your switch statement. This is on a brand-new install. I managed to work around that by pre-creating the PSSlack variable object and setting it to null but I'm worried this some dirty hack. What am I doing wrong please?

Get-SlackFileInfo the Count value

It would be nice to come up with a way that if I pass in a Before or After that it iterates over all possible variables for Count to return them all.

Example:
I need to clean up files in SQLCommunity.slack.com. There are files going back to the beginning so that is almost two years now. In order for me to pull those files and pipe them to Remove-SlackFile I have to run it with -Count 1000 multiple times in order to keep getting files back before the data I'm passing in.

If a data is provided, it would be more efficient to have it return all the files. I would assume this would need some kind of loop to populate all the files because you would have to go over the limit of 1000 items at a time.

Find-SlackMessage error: user_is_bot

When I call Find-SlackMessage, with any query, I always get the same error: "user_is_bot".

Of course the user is a bot - isn't that the point!? lol

Either I'm doing something wrong (I hope!) or the slack API has changed since Find-SlackMessage was written/tested.

Get-PSSLackConfig not populating environment variables correctly?

I am doing something wrong here. I run set-psslackconfig and the xml file is correctly configured and encrypted. If I run get-psslackconfig my correct variables are returned to me on screen. However, everything after that fails because $Script:PSSLack is missing/null. What did I do wrong?

Add support for file storage management

The Slack web UI for file management leaves a lot to be desired - at least for the free tier. It would be very helpful if this module added:

  • Get-SlackFileInfo (for both listing the files and getting info about a specific file)
  • Remove-SlackFile

This would allow folks to manage their limited file storage space much more easily than with the web UI.

See https://api.slack.com/methods#files

Can we get active/inactive status from Get-SlackUser please?

Thank you for the great code! We're using it to run a report, compare against active directory, and see who needs to be removed. It would be really useful to see if the user is active or not, as we'd like to contact active users and see if there is some corner case involved ...

Need to support rate limiting:

As a user of the free Slack service
In order to avoid running out of space
I need to delete old files

And this script worked great, except for one thing:

$Old = "{0:dd/MM/yyyy}" -f (Get-Date).AddYears(-2)
Get-SlackFileInfo -Before $Old -Paging | Remove-SlackFile -Force

The problem was that I ran into the rate limit while deleting.
They obviously allowed me a large burst, and so I know the rate limit is complicated, but there needs to be some way for me to handle it.

*At the very least, you should terminate when you get a rate-limit error code back from the service.

P.S. You should really talk about this as a feature of your module. Maybe write a short blog post about it. From a quick google search, a lot of people need this functionality, and are writing their own scripts, or even using services for it, when it should be that easy -- you could even add a helper to do something like Remove-SlackFile -OlderThan ...

Send-SlackFIle - macOS/linux support

More cross-platform fun 😄

Send-SlackFile is throwing this error on macOS.

> Send-SlackFile -Token $token -Path $f.FullName -Channel general
Invoke-RestMethod : The format of value 'multipart/form-data; boundary="4ade9b52-9513-44c0-a787-3843b95eba20"' is invalid.
At /Users/brandon/.local/share/powershell/Modules/PSSlack/0.0.31/Public/Send-SlackFile.ps1:135 char:29
+ ... $response = Invoke-RestMethod -Uri $uri -Method Post -ContentType "mu ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], FormatException
+ FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Something must be wrong with the value of $bodyLines on macOS/linux.

@markekraus has a nice article on multipart/form-data support. I did some quick tests and this is working on macOS. I also like using .net methods over a bunch of string concatenation as well.

If you agree, I'll submit a PR to fix.

Cheers

Deleting messages from private channel

I have a private channel with an misbehaving bot that filled up the messages. I tried the following:

$token = 'xoxp-.......';
get-slackchannel -token $token -name "privatechannelname" | Get-SlackHistory -Count 1000 | Remove-SlackMessage

unfortunately, this only works with public channels. Is there any way to delete messages from a private channel?

Rate-Limiting is not handled gracefully

Slack's API has a rate-limit of one message per second. PowerShell/PSSlack overruns even the (unspecified) burst-limit rather quickly, and doesn't make any attempt at waiting/re-trying the request.

Even more concerning is that Slack appears to threaten revoking API tokens if an application continues to send messages while being rate-limited.

It would likely be best to augment Send-SlackApi to be mindful of the burst/average rate-limit, and gracefully recover from HTTP 429 API responses.

PSTypeNames Error

When attempting to post a message, you get the following error -

Send-SlackMessage : Cannot bind argument to parameter 'SlackMessage', because PSTypeNames of the argument do not match the PSTypeName required by the parameter: PSSlack.Message.

+ CategoryInfo : InvalidArgument: (:) [Send-SlackMessage], ParameterBindingArgumentTransformationException + FullyQualifiedErrorId : MismatchedPSTypeName,Send-SlackMessage

Not sure what to do here, but if you need anymore information just let me know.

Add function: New-SlackMessageAttachmentField

Maybe don't go as crazy with the name : )

Abstract out creating a set of fields from an arbitrary object (see final example in readme.md). Pipe random objects to this and it spits out a set of fields, keeping the order of properties intact.

Please hide tokens from verbose output

As a user of a company computer
In order to avoid leaving my token in a log
I need to avoid having the token output to the screen (even in the verbose stream).

Currently if I run anything in -Verbose, when Send-SlackAPI is called, it outputs the Get URI (for instance) with the token visible.

I think if you're going to output it, you should obscure the token with **** or something.

Send-SlackAPI Error handler doesn't account for sub-API failures

While testing out #54, it was discovered that the error-handling code from #53 throws a rather unhelpful exception if the API call failed due to issues below the API level (DNS failures, socket failures, no connected NICs available, etc.)

PS C:\Users\Sean Williams\Documents\Repositories\PSSlack> Test-SlackAPI
Cannot bind argument to parameter 'InputObject' because it is null.
At C:\Users\Sean Williams\Documents\Repositories\PSSlack\psslack\Public\Send-SlackAPI.ps1:149 char:39
+             $_.ErrorDetails.Message | ConvertFrom-Json | Parse-SlackE ...
+                                       ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Remove [System.Color] Warning?

Greetings Starfighter!

I'm not sure what specific .Net core version added support for [System.Drawing] but this is working on macOS PS v6.0.1. This was added to CoreFX in #20593

My Google-foo is failing me and I can't seem to find it in the release notes.

screen shot 2018-03-29 at 8 46 38 pm

In any case, perhaps this should be changed to detect the PS version and not present a warning if PS version 6.0.1 or higher?

Add functions: Get and Set-SlackReminder

Add functions: Get and Set-SlackReminder

Thanks to Ramprabhu for the idea!

Private cmdlets use unapproved verbs (PSUseApprovedVerbs)

A number of the private cmdlets are flagged by PSScriptAnalyzer for using an unapproved PowerShell verb:-

RuleName Severity ScriptName Line Message
PSUseApprovedVerbs Warning Color-ToNumber.ps1 1 The cmdlet 'Color-ToNumber' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackChannel.ps1 2 The cmdlet 'Parse-SlackChannel' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackGroup.ps1 1 The cmdlet 'Parse-SlackGroup' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackMessage.ps1 2 The cmdlet 'Parse-SlackMessage' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackMessage.ps1 9 The cmdlet 'Extract-Previous' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackTeam.ps1 2 The cmdlet 'Parse-SlackTeam' uses an unapproved verb.
PSUseApprovedVerbs Warning Parse-SlackUser.ps1 2 The cmdlet 'Parse-SlackUser' uses an unapproved verb.

The easiest way to fix this would be to explicitly suppress the PSUseApprovedVerbs rule for the Private\Parse-Slack* cmdlets by adding something like the below to each.

[Diagnostics.CodeAnalysis.SuppressMessage("PSUseApprovedVerbs", Scope="function")]

IMO, the cleaner way to fix this would be to rename those cmdlets to use an approved verb.

For the Parse- cmdlets, ConvertTo- or New- may be a suitable candidate from the current list of approved verbs, perhaps coupled with an Object or Type suffix (e.g., ConvertTo-SlackTeamObject),

Thoughts? Is a clean bill of health from PSScriptAnalyzer even worth pursuing?

Cannot hide warnings

Hi!

Attempted the following command:
New-SlackMessageAttachment -Pretext "Deployment to /E:$($EnvironmentName)$($testMessage)" -Color Red -Title $NewVersion -TitleLink $BuildInfoUrl -Fields $Fields -Text "Version Info: $($VersionInfoUrl)" -Fallback $NewVersion -WarningAction SilentlyContinue -InformationAction SilentlyContinue -ErrorAction SilentlyContinue | New-SlackMessage -Username 'Bot' -Channel $Channel -IconEmoji :pushpin: -WarningAction SilentlyContinue | Send-SlackMessage -Token $Token -WarningAction SilentlyContinue | Out-Null

Note the usage of -WarningAction SilentlyContinue, however it does not appear to be honored as the script results with the following messages when calling New-SlackMessageAttachment:

WARNING: Did not find config file C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.18\XX-XXX-PSSlack.xml, attempting to create WARNING: Failed to create config file C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.18\XXX-XXX-PSSlack.xml: Access to the path 'C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.18\XXX-XXX-PSSlack.xml' is denied. WARNING: Error importing PSSlack config: Could not find file 'C:\Program Files\WindowsPowerShell\Modules\PSSlack\0.0.18\XXX-XXX-PSSlack.xml'.

The easy way to fix both the error writing to the modules folder would be to move it to %temp% instead. I'm not sure what the purpose of the settings file, but might be safer to place it in a user temp instead of the module folder. Thanks in advance!

New-SlackAttachment Color param not working in Scheduled Task script

Issue: When I use the Color param in a script and run from Powershell or ISE, it sends the message with the appropriately colored attachment. When I run that same script as a scheduled task, however, everything works except the color isn't added to the attachment.

bonus) HUGE thank you for compiling this module! Even the PSM1 itself is amazing (I pulled chunks out of it to rewrite my PSGoogle module in order to allow a saved, encrypted config file =] )

Also, here's a ValidateSet to add to the param that contains all of the X11 colors available via System.Drawing.Color, if you're so inclined!

[ValidateSet("AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenrod","DarkGray","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","Goldenrod","Gray","Green","GreenYellow","Honeydew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenrodYellow","LightGreen","LightGrey","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquamarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenrod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","Seashell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen")]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.