Giter Site home page Giter Site logo

slack.webhooks's People

Contributors

asizikov avatar benelliottbv avatar dependabot[bot] avatar domwilliamsredweb avatar fullofquarks avatar jchannon avatar jhofker avatar jlnpinheiro avatar mrb0nj avatar mteper avatar pleb avatar pmacca avatar synthetik avatar tylerssmith avatar wattsk09 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

slack.webhooks's Issues

Doesn't seem to work with RestSharp > 104.4.0.0

I just updated my RestSharp to 106.0.1 and now the SlackClient constructor is throwing the following exception:

Could not load file or assembly 'RestSharp, Version=104.4.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

It looks like my version of Slack.Webhooks (0.1.8) is pegged to RestSharp 104.4.0.0 - can this be changed?

Invalid empty Emoji icon text

Attribute "[EnumMember(Value = null)]" seems not working properly for member "None = 0," of enum Emoji, because playload contains the folowing property: "icon_emoji": "None",

Please update Conditional serialization of IconEmoji like this:

    /// <summary>
    /// Conditional serialization of IconEmoji
    /// Overidden by the presence of IconUrl
    /// </summary>
    /// <returns>false when IconUrl is present otherwise true.</returns>
    public bool ShouldSerializeIconEmoji()
    {
        return IconUrl == null && IconEmoji != Emoji.None;
    }

Deserializing Webhooks

Hi @mrb0nj -
How do I deserialize a slack event so I can process it? For example, when a message is posted to a slack room, I get the following JSON:

{
  "team_id": "T6Q4W5TQR",
  "api_app_id": "A8DDL8RUY",
  "event": {
    "client_msg_id": "ba299014-e3ba-4817-88f7-01658ee25466",
    "type": "message",
    "text": "test",
    "user": "U6QNA62CC",
    "ts": "1578520850.002100",
    "team": "T6Q4W5TQR",
    "blocks": [
      {
        "type": "rich_text",
        "block_id": "bImul",
        "elements": [
          {
            "type": "rich_text_section",
            "elements": [
              {
                "type": "text",
                "text": "test"
              }
            ]
          }
        ]
      }
    ],
    "channel": "CSEL7QT7S",
    "event_ts": "1578520850.002100",
    "channel_type": "channel"
  },
  "type": "event_callback",
  "event_id": "EvS4FD9M17",
  "event_time": 1578520850,
  "authed_users": [
    "U6QNA62CC"
  ]
}

How do I turn this into the appropriate object?

Add Response_Type to options

Hi, I see you've added response_Type in 2017 to v0.1.8, however I'm missing this option in the current version. Could you please add this option?

Get `ts` of posted message, so it is possible to reply to it

Consider the following use case:
A bot wants to post subsequent messages into a single thread within a slack channel.
So the first message would be a normal message, further messages would be thread replies to that message.

For this to work - as far as I can tell - you would need to get the identifier (which seems to be the ts property) of the first posted message. The slack API returns this information (see the documentation) in the form of "ts": "1503435956.000247".

If I had the value of that property then I could construct message objects with theirThreadId property set to the value returned by the first posted message, but this wrapper does not seems to expose that returned property.

The Post methods only seem to return with a bool (or a Task<bool>) and it seems that they do not modify the passed SlackMessage object, so the returned ts value is simply discarded. Is it so or am I missing something?

Would it be possible to somehow expose the ts property of a message once posted? Either via returning it from the Post methods or maybe storing it in the message object passed to the methods - so mutating the passed argument?

Or is there any workaround I can use? (Apart from using the slack API directly - which is of course a solution to my problem.)

Thanks in advance.

Unsigned Package

Greetings and Happy New Year!

It looks like when the package was uploaded to NuGet, it was not signed by the developer or by an organization. The public token = null.

Powershell:
([system.reflection.assembly]::loadfile("~\Slack.Webhooks.dll")).FullName
Output:
Slack.Webhooks, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null

Post doesn't convert \n in text to multiline

I'm not sure if this is an issue in the Slack API or in this client. Has anyone been able to get multi-line text? Example text = "foo\nbar". That exact text displays in Slack. I've tried setting mrkdwn to true and false as well as trying a number of permutations like \n, , %5c, %255c, \r\n, \n, and other insanity like surrounding the text in spaces. Thanks.

Reflection Error on Emoji.cs

Hit a reflection error on duplicate definitions of Icecream/IceCream. This needs to be spelled differently in some way. Recommend using Icecream/Ice_Cream to follow the EnumMember spellings for transparency.

System.ArgumentException : Duplicate item already exists for 'Icecream' at Newtonsoft.Json.Utilities.BidirectionalDictionary`2.Set(TFirst first, TSecond second)

Customized Name and Icon

as stated in the Slack documentation:

You can also override the bot icon either with icon_url or icon_emoji".

But when using the IconEmoji property of the SlackMessage object the emoji is set to default.
Nicer would it be to have the IconUrl propery added to show other icons

Nuget Install Issues

Created a new ASP.net core web app (.net framework), targeting .net framework 4.6.2 and slack.webhooks 0.1.6.

Error in install:

error: Package ServiceStack.Text 3.9.71 is not compatible with net462 (.NETFramework,Version=v4.6.2). Package ServiceStack.Text 3.9.71 supports:
error: - net35 (.NETFramework,Version=v3.5)
error: - sl4 (Silverlight,Version=v4.0)
error: - sl4-wp71 (Silverlight,Version=v4.0,Profile=WindowsPhone71)
error: - sl5 (Silverlight,Version=v5.0)
error: One or more packages are incompatible with .NETFramework,Version=v4.6.2.

Also the 0.1.6 version fails on install in a class library targeting 4.6.2 - doesn't add a reference to slack web hooks assembly. Don't see the above error though.

Unable to set the 'response_type' for a message

My messages always get sent as 'ephemeral'. I'm using the response url from the slack request to post back to and need to set the 'response_type' on the slack message as 'in_channel'.
Are you able to add this is so we can explicitly set this.

Cloning doesn't clone blocks

While using PostToChannelsAsync and found it showed the Message.Text I set, but not the Message.Blocks. Further investigation lead me to the Message.Clone method where I discovered two things.

First, it seems that copying/cloning of Message.Blocks was not added in the recent work to include blocks.

And secondly, it's not a deep clone as referenced types (Attachments) are copied as-is, although this might not matter.

Suggestion - Move SerializePayload into SlackMessage

Hi - thanks for sharing this project, it's been very useful.

I've been using the project to send messages to Slack and it's working very well 👍.

I am now trying to respond to message buttons and come across a couple of problems:

  1. A couple of fields for message replies are missing. See my PR here: #53

  2. To do a reply, I need to reply to a request, rather than sending a new message. In order to do so, I need to serialize the SlackMessage. Serializing has a tiny bit of configuration relating to snake casing (https://github.com/nerdfury/Slack.Webhooks/blob/master/src/Slack.Webhooks/SlackClient.cs#L60). This method is private in SlackClient, and I'd prefer not to copy it into my own application in case it changes at some point.

Example:
image

SUGGESTION: How about making string SerializePayload(SlackMessage slackMessage) an instance method on SlackMessage? Alternatively just make that static method public?

Cheers

Unfurling links in messages

Hi,

I would like to suggest an enhancement for SlackMesage that would allow us to utilize unfurling links in messages we post. Despite the fact that here is described that:

By default we unfurl all links in any messages posted by users and Slack apps.

Inside the slack app directory for a channel under:

image

In the Message Attachments area we can find this:

image

In an integration we did with a slack webhook, we found that we had to pass also this property to the slack message, in order unfurling of our links to work.

Our quick solution was to do this (since we always wanted unfurling of our links to work):

public class ExtendedSlackMessage : SlackMessage
{
    public bool unfurl_links { get; } = true;
}

and instead of creating instances of SlackMessage, we decided to create instances of ExtendedSlackMessage to post

slackClient.Post(slackMessage);

A more clean solution, it would be to define this as a property in SlackMessage class.

Do you want I open a PR for this enhancment ?

Prevent Deadlocks

        public virtual bool Post(SlackMessage slackMessage)
        {
            var result = PostAsync(slackMessage);
            return result.Result;
        }

Although one would wonder why the synchronous method above would be called from an async task, if where called it could result in a deadlock.
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
Consider rewriting it like this:

        public virtual bool Post(SlackMessage slackMessage)
        {
            var result = PostAsync(slackMessage);
            return result.GetAwaiter().GetResult();
        }
        // Or a one liner :)
        public virtual bool Post(SlackMessage slackMessage)
          => PostAsync(slackMessage).GetAwaiter().GetResult();

https://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html

Missing release versions?

The releases page latest version numbers are 0.1.8, 0.1.7, etc. But the Nuget page has release numbers available of 1.0.0 and higher. Is it just that that some commits have not been tagged with those release numbers yet?

Hide/show a Block? Ability to toggle?

I have seen there's options to make dropdowns for options, but what about for just displaying some information? For example having a Block (or one of its inheritors) with togglable visibility, maybe with a "Show more" kind of functionality.

Post does not return

This is our code:

public static void SendBackendNotification(string channel, string username, string actiontext, string emoji)
        {
            var slackClient = new SlackClient(ConfigurationManager.AppSettings["SLACK_WEBHOOK_URL_CM_NOTIFICATIONS_NEW"]);
            var slackMessage = new SlackMessage
            {
                Channel = channel,
                Username = username,
                Text = actiontext,
                IconEmoji = emoji
            };
            try
            {
                slackClient.Post(slackMessage);
            }
            catch (Exception slackException)
            {
                AiLogger.Log(slackException, new HttpContextWrapper(HttpContext.Current), false, false);
            }
        }

slackClient.Post(slackMessage); does not return to code and does not throw exception. It sends the message but request is pending until timeout occurs (ASP.NET MVC) or we end the application.

With release version 1.0.6 it works, with 1.1.0 or later it does not work.

How can we fix that?

  • channel is "#test_errors" and exists
  • username is "Testuser"
  • actiontext is "Foo"
  • emoji is Emoji.Exclamation
  • slackMessage is "Foo"

Regards,
Sven

throwing notifications to the channel

Good afternoon!

I don't know if call it an issue or not.

I am trying to throw a notification to the channel when publishing a message that includes "@SomeGroup" but no notification is launched. I have tried it in different ways using your package but without good result.

Is it possible? Because maybe it is not.

Thanks!
Eder

Custom emoji

Would it make sense to have the capability to specify custom Emoji? This could be used both for custom emoji defined by individual Slack teams, as well as for missing emoji (e.g. I don't see 🤑 in the Emoji class currently).

Something along the lines of:

var emoji = new Emoji(":money_mouth_face:");

Working with Files

Hello.
Your wrapper is really useful, thanks.

I want to include an excel file in the slack message, could you guide me?

Reuse HttpClient for all calls

The HttpClient is intended to be reused for all calls,

    public async Task<bool> PostAsync(SlackMessage slackMessage)
    {
      string content = slackMessage.AsJson();
      bool flag;
      using (HttpClient httpClient = new HttpClient()
      {
        Timeout = new TimeSpan(0, 0, this._timeout)
      })
      {
        using (HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(this._webhookUri.OriginalString, (HttpContent) new StringContent(content)).ConfigureAwait(false))
          flag = (await httpResponseMessage.Content.ReadAsStringAsync()).Equals("ok", StringComparison.OrdinalIgnoreCase);
      }
      return flag;
    }

I learned this the hard way a long time ago so I am an advocate for addressing the issue. Basically not only will you take a performance hit every time you create a new client but more importantly you stand a chance of consuming all the available ports on a machine.

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

I would love to use this client but as it is we would probably consume all the ports on our machine with in a few minutes.

It would be nice if your implementation had two constructors, one which creates a HttpClient which is reused for the life of the SlackClient and another where you can pass in your own instance.

This would then allow consumers to do any of the following, probably through IoC:

  • Maintain a single instance of a SlackClient which they reuse through out the life of the application
  • Maintain a single instance of a HttpClient which they reuse through out the life of the application and inject into a new SlackClient when needed.
  • Do integration testing and point a SlackClient at a fake instance of a slack web api using either Owin or AspNetCore's TestServer.

SlackMessage.Channel not working

Hi, I have my Webhook URL in api.slack.com set to Channel #general.
Do you know why if I set the SlackMessage.Channel to #random" this channel gets ignored and it continues posting to #general?

Markdown in attachments

In the slack api docs they state that attachments by default have markdown turned off.
The only way to enable them is to pass the mrkdwn_in field and pass an array of the items that should have markdown enabled.

https://api.slack.com/docs/formatting

"attachments": [
        {
            "title": "Title",
            "pretext": "Pretext _supports_ mrkdwn",
            "text": "Testing *right now!*",

            "mrkdwn_in": ["text", "pretext"]
        }
    ]

A basic solution would be to add the Mrkdwn_in variable to SlackAttachment class

public List<string> Mrkdwn_in {get;set;}

To make this better have accessible variables that return the possible fields that markdown can be enabled on pretext, text, fields

Want support .NET 3.5

I want to use Slack.Webhooks on .NET 3.5 under windows server 2003.
Could you support older environment?

Missing emoji

card_file_box and card_index_dividers emojis seem to be missing from the library

Footers and Time Stamps

It looks like the WebHooks API now supports TimeStamps, footer and footer_Icon in the message attachment.
Support for this should probably be added at some stage.

Username and IconUrl sometimes disappear but I can't get the reason

I user this format to send my slack alert, and it worked at first time:

var slackMessage = new SlackMessage
{
    Channel = "#植物病蟲害測試alert",
    Text = "Your message",
    IconUrl= new Uri("https://ruralgis.tari.gov.tw/PpsSurvey/images/logo.png"),
    Username = "植物病蟲害系統"
};

slackMessage.Blocks = new List<Block>
{
    new Header
    {
        Text = new TextObject("有使用者登入了")
    },
    new Section
    {
        Text = new TextObject(
            $"*登入時間:* {time:yyyy-MM-dd hh:mm:ss}\n*使用者名稱:* {user.name}\n*使用者帳號:* {user.account}")
        {
            Type = TextObject.TextType.Markdown
        },
    }
};
slackClient.Post(slackMessage);

After I change my slackMessage.Text to chinese "有使用者登入了", it's icon and username is not show like below img:

image

Should I avoid chinese words in message?

PostAsync not working

Hello,

I get the message code "missing_text_or_fallback_or_attachments" as internal server error when using PostAsync. The same call with the same parameters works fine if I use the non async method.

Can you help? My request contains attachments, if it helps.

Thank you

Footers and Timestamps (redux)

This issue was closed with a fix in August 2017: #30

But the fix seems to have been reverted for some reason here: 4cf716c#diff-a4ceebd58deebfcd981cbf845072191e

Was that an accident, or was there a problem with the fix?

Add an ISlackClient interface for easy mocking

I'd like to be able to use FakeItEasy to mock a SlackClient for tests and because FakeItEasy can only create fakes for interfaces, I really need an ISlackClient interface.

If I do the PR, would you be OK with that?

Cheers,

R.

Block and Attachment Ordering Concrete

I am currently structuring a message that uses the Attachment and Blocks of a Slack message.
I want to have the Attachment to be able to have the color on the message, and then have blocks after to be able to support message expansion (show more).

However when the message is serialized and sent, the blocks list is always at the top. Is there a way that I am missing to be able to have the Blocks appear after Attachments?

I attempted to use the Blocks section of the attachments but it results in a failed post. (I just added a divider to it to test)

Thanks.

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.