mrb0nj / slack.webhooks Goto Github PK
View Code? Open in Web Editor NEWEven simpler integration with Slack's Incoming and Outgoing webhooks
License: MIT License
Even simpler integration with Slack's Incoming and Outgoing webhooks
License: MIT License
Shouldn't the text be able to tag users? What's the syntax?
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?
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;
}
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?
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?
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.
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
The BlockType enum in your library does not contain the Header Block Type (https://api.slack.com/reference/block-kit/blocks#:~:text=Fields%20%20%20%20Field%20%20%20,acting%20as%20a%20unique%20identifier%20f%20...%20)
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.
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)
By default Slack doesn't linkify user names, but we can enable this behaviour providing link_names=1 inside payload.
Please have a look at the docs (Parsing modes section)
Interesting discussion about this issue on google groups
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
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.
Looks like the Emoji is always picked up and the Image URL is never user for the posted 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.
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.
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:
A couple of fields for message replies are missing. See my PR here: #53
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.
SUGGESTION: How about making string SerializePayload(SlackMessage slackMessage)
an instance method on SlackMessage
? Alternatively just make that static method public?
Cheers
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:
In the Message Attachments area we can find this:
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 ?
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
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?
Hey,
Can you add Blocks in SlackAttachment, please ?
ref : https://api.slack.com/messaging/composing/layouts#adding-blocks
Thanks
You're doing an amazing job
Request to have the Header block type added
Reference: Slack Header Block
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.
http://nerdfury.redrabbits.co.uk has been down for several hours. I know this isnt the proper place, but i have no other way of contacting you.
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?
Regards,
Sven
So that instead of writing:
new Section
{
Text = new TextObject("Some text")
},
you could write:
new Section
{
Text = "Some text"
},
Hi,
FYI I'm unable to post a Block with a PlainTextInput because the MultiLine property gets serialized as multi_line
due to the SnakeCaseNamingStrategy, but the Slack API is expecting multiline
. The API responds with invalid_blocks
.
See https://api.slack.com/reference/block-kit/block-elements#input
Happy to provide a test if you need it
forked it here for my needs for now
https://github.com/circuitrider/Slack.Webhooks
Not sure how to handle this version cutover cleanly with NuGet considerations, which I would rather use than my own local repo.
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
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:");
Hello.
Your wrapper is really useful, thanks.
I want to include an excel file in the slack message, could you guide me?
Can the build assembly have a strong name? It will make it able to include it in strong named projects.
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:
SlackClient
which they reuse through out the life of the applicationHttpClient
which they reuse through out the life of the application and inject into a new SlackClient
when needed.SlackClient
at a fake instance of a slack web api using either Owin or AspNetCore's TestServer.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?
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
I want to use Slack.Webhooks on .NET 3.5 under windows server 2003.
Could you support older environment?
card_file_box and card_index_dividers emojis seem to be missing from the library
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.
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:
Should I avoid chinese words in message?
the url is http://files.fivedegrees.co.uk/Slack.Webhooks/webhook.png but that doesn't go anywhere
It would be helpful for the purpose of unit testing to have SlackClient methods be virtual.
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
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.
public class SlackMessage
{
...
public List<SlackMessage> ReplyList { get; set;}
}
Are you planning to add support to message buttons?
https://api.slack.com/docs/message-buttons
It needs to set callback_id in the attachmens and add actions field, to enable options
Hi, I checked the documentation but it doesn't mention slash commands and modals. Wondering if this is supported?
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.