Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: crate should have example for sending messages #166

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
864 changes: 858 additions & 6 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,5 @@ serde_json = "^1"
lazy_static = "1.4.0"
mox = "0.12"
pretty_assertions = "0.7.2"
tokio = {version = "1", features = ["full"]}
reqwest = "0.11"
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,29 @@ let section = blox! {
};
```

Then you can send the block to Slack's API, for example:

```rust
let blocks: Vec<Block> = vec![section.into()]; // using section from examples above

reqwest::Client::new()
.post("https://slack.com/api/chat.postMessage")
.header("Content-Type", "application/json")
.bearer_auth("<api token here>")
.body(serde_json::json!({
"channel": "<a channel id>",
"blocks": blocks
}).to_string())
.send();
```

There is also a crate example (`./examples/reqwest.rs`) that can be run like so:
```sh
> export SLACK_API_TOKEN=foo
> export SLACK_API_TOKEN=bar
> cargo run --all-features --example reqwest
```

[Block Kit 🔗]: https://api.slack.com/block-kit
[`cargo-make`]: https://github.com/sagiegurari/cargo-make/
[issues]: https://github.com/cakekindel/slack-blocks-rs/issues/
Expand Down
54 changes: 54 additions & 0 deletions examples/reqwest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use reqwest::Client;
use slack_blocks::blox::*;

#[tokio::main]
async fn main() {
let client = Client::new();
let block: slack_blocks::Block = blox! {
<section_block>
<text kind=mrkdwn>"Hello!"</text>
</section_block>
}.into();

let api_token = env!(
"SLACK_API_TOKEN",
r#"environment variable SLACK_API_TOKEN not defined
Head over to https://api.slack.com/authentication/basics for a guide on how to create a bot user and authenticate it."#
);

let channel_id = env!(
"SLACK_CHANNEL_ID",
"environment variable SLACK_CHANNEL_ID not defined\nThis example requires a channel ID to send a message to."
);

let req = client.post("https://slack.com/api/chat.postMessage")
.header("Content-Type", "application/json")
.bearer_auth(api_token)
.body(serde_json::json!({
"channel": channel_id,
"blocks": [block]
}).to_string())
.build()
.unwrap();

let req_body_bytes = req.body()
.expect("body was definitely set")
.as_bytes()
.unwrap();

fn to_json<'a>(s: impl Into<std::borrow::Cow<'a, str>>) -> serde_json::Value {
serde_json::from_str(&s.into()).expect("assume `s` is valid json")
}

let req_body_json = to_json(String::from_utf8_lossy(req_body_bytes));

println!("Request body: {:#?}", req_body_json);

let res = client.execute(req)
.await
.expect("http should definitely succeed");

let res_body_json =
to_json(&res.text().await.expect("response _should_ contain a body"));
println!("Response body: {:#?}", res_body_json);
}
12 changes: 4 additions & 8 deletions src/blocks/section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,14 +328,10 @@ mod validate {

pub(super) fn fields(texts: &Cow<[text::Text]>) -> ValidatorResult {
below_len("Section.fields", 10, texts.as_ref()).and(
texts.iter()
.map(|text| {
below_len(
"Section.fields",
2000,
text.as_ref())
})
.collect(),
texts
.iter()
.map(|text| below_len("Section.fields", 2000, text.as_ref()))
.collect(),
)
}
}
24 changes: 14 additions & 10 deletions src/elems/select/static_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,13 @@ pub mod build {
ActionId,
Set<(method::options, StaticOpt<'a>)>>;
fn add_to(self,
builder: StaticBuilder<'a,
Multi,
Placeholder,
ActionId,
RequiredMethodNotCalled<method::options>>)
builder: StaticBuilder<
'a,
Multi,
Placeholder,
ActionId,
RequiredMethodNotCalled<method::options>,
>)
-> Self::Output {
builder.option(self)
}
Expand All @@ -250,11 +252,13 @@ pub mod build {
ActionId,
Set<(method::options, StaticOptGroup<'a>)>>;
fn add_to(self,
builder: StaticBuilder<'a,
Multi,
Placeholder,
ActionId,
RequiredMethodNotCalled<method::options>>)
builder: StaticBuilder<
'a,
Multi,
Placeholder,
ActionId,
RequiredMethodNotCalled<method::options>,
>)
-> Self::Output {
builder.option_group(self)
}
Expand Down
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,39 @@
//! };
//! ```
//!
//! Then you can send the block to Slack's API, for example:
//!
//! ```
//! # use slack_blocks::{Block, text::ToSlackMarkdown, blocks::Section, elems::DatePicker};
//! # let section = Section::builder()
//! # .text("*Sally* has requested you set the deadline for the Nano launch project".markdown())
//! # .accessory(DatePicker::builder()
//! # .action_id("datepicker123")
//! # .initial_date((28, 4, 1990))
//! # .placeholder("Select a date")
//! # .build()
//! # )
//! # .build();
//! let blocks: Vec<Block> = vec![section.into()]; // using section from examples above
//!
//! reqwest::Client::new()
//! .post("https://slack.com/api/chat.postMessage")
//! .header("Content-Type", "application/json")
//! .bearer_auth("<api token here>")
//! .body(serde_json::json!({
//! "channel": "<a channel id>",
//! "blocks": blocks
//! }).to_string())
//! .send();
//! ```
//!
//! There is also a crate example (`./examples/reqwest.rs`) that can be run like so:
//! ```sh
//! > export SLACK_API_TOKEN=foo
//! > export SLACK_API_TOKEN=bar
//! > cargo run --all-features --example reqwest
//! ```
//!
//! [Block Kit 🔗]: https://api.slack.com/block-kit
//! [`cargo-make`]: https://github.com/sagiegurari/cargo-make/
//! [issues]: https://github.com/cakekindel/slack-blocks-rs/issues/
Expand Down
7 changes: 3 additions & 4 deletions tests/json/compose/conversation_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ use slack_blocks::compose::ConversationFilter;
#[test]
pub fn docs_ex_1() {
use slack_blocks::compose::conversation_filter::ConversationKind as Kind;
let confirm =
ConversationFilter::new().include_conversation_kinds(vec![Kind::PublicChannel,
Kind::GroupDm])
.exclude_bot_users();
let confirm = ConversationFilter::new()
.include_conversation_kinds(vec![Kind::PublicChannel, Kind::GroupDm])
.exclude_bot_users();
let actual = serde_json::to_value(confirm).unwrap();
let expected = json!({
"include": [
Expand Down
2 changes: 1 addition & 1 deletion tests/json/compose/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn groups_docs_ex_1() {
<option_group label="Group 2">
<option value="value-3" text_plain="*this is plain_text text*" />
</option_group>
}];
},];
let actual = serde_json::to_value(groups).unwrap();
let expected = json!(
[
Expand Down