☁️
worker-rsからSlackに投稿する
use worker::*;
use reqwest;
use std::collections::HashMap;
async fn post_slack(channel: &str, token: &str, message: &str) -> Result<Response> {
let url = "https://slack.com/api/chat.postMessage";
let mut payload = HashMap::new();
payload.insert("channel", channel);
payload.insert("text", message);
let payload_json = serde_json::to_string(&payload).unwrap();
let client = reqwest::Client::new();
let response = client
.post(url)
.header("Content-Type", "application/json; charset=UTF-8")
.header("Authorization", &format!("Bearer {}", token))
.body(payload_json)
.send()
.await
.map_err(|e| Error::from(format!("Request failed: {:?}", e)))?;
let body = response.text().await
.map_err(|e| Error::from(format!("Failed to read response body: {:?}", e)))?;
Ok(Response::ok(body)?)
}
#[event(fetch)]
async fn main(req: Request, env: Env, ctx: Context) -> Result<Response> {
let channel = env.var("SLACK_CHANNEL")?.to_string();
let oauth_token = env.var("SLACK_OAUTH_TOKEN")?.to_string();
post_slack(&channel, &oauth_token, "Hello from Cloudflare Workers .").await?;
Ok(Response::ok("hello")?)
}
Discussion