import os
import requests
response = requests.post(
"https://slack.com/api/chat.postMessage",
headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
data={"channel": "C12345678", "text": "Hello from cURL"}
)
response.raise_for_status()
print(response.json())
import os
import httpx
response = httpx.post(
"https://slack.com/api/chat.postMessage",
headers={"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"},
data={"channel": "C12345678", "text": "Hello from cURL"}
)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import { env } from 'process';
(async () => {
const response = await fetch('https://slack.com/api/chat.postMessage', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.SLACK_BOT_TOKEN}`
},
body: new URLSearchParams({
channel: 'C12345678',
text: 'Hello from cURL'
})
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
console.log(await response.json());
})();
import axios from 'axios';
import { env } from 'process';
(async () => {
const response = await axios.post(
'https://slack.com/api/chat.postMessage',
new URLSearchParams({
channel: 'C12345678',
text: 'Hello from cURL'
}),
{
headers: {
'Authorization': `Bearer ${env.SLACK_BOT_TOKEN}`
}
}
);
console.log(response.data);
})();
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
token := os.Getenv("SLACK_BOT_TOKEN")
if token == "" {
log.Fatal("SLACK_BOT_TOKEN environment variable not set")
}
form := url.Values{}
form.Add("channel", "C12345678")
form.Add("text", "Hello from cURL")
req, err := http.NewRequest(
"POST",
"https://slack.com/api/chat.postMessage",
strings.NewReader(form.Encode()),
)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("HTTP error! status: %s", resp.Status)
}
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
<?php
$token = getenv('SLACK_BOT_TOKEN');
if (empty($token)) {
die('SLACK_BOT_TOKEN environment variable not set');
}
$ch = curl_init('https://slack.com/api/chat.postMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'channel' => 'C12345678',
'text' => 'Hello from cURL'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
die('Curl error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
die("HTTP error! status: $httpCode");
}
$json = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
die('JSON decode error: ' . json_last_error_msg());
}
print_r($json);
require 'net/http'
require 'uri'
require 'json'
token = ENV.fetch('SLACK_BOT_TOKEN')
uri = URI.parse('https://slack.com/api/chat.postMessage')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{token}"
request.set_form_data({
'channel' => 'C12345678',
'text' => 'Hello from cURL'
})
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
guard let token = ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] else {
fatalError("SLACK_BOT_TOKEN environment variable not set")
}
let url = URL(string: "https://slack.com/api/chat.postMessage")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let body = "channel=C12345678&text=Hello from cURL"
request.httpBody = body.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
fatalError("Request failed: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse else {
fatalError("Invalid response")
}
guard (200...299).contains(httpResponse.statusCode) else {
fatalError("HTTP error! status: \(httpResponse.statusCode)")
}
guard let data = data else {
fatalError("No data received")
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
} catch {
fatalError("JSON decode error: \(error)")
}
}
task.resume()
RunLoop.main.run()
use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = env::var("SLACK_BOT_TOKEN")?;
let client = Client::new();
let mut headers = header::HeaderMap::new();
headers.insert(
"Authorization",
header::HeaderValue::from_str(&format!("Bearer {}", token))?,
);
headers.insert(
"Content-Type",
header::HeaderValue::from_static("application/x-www-form-urlencoded"),
);
let mut form = HashMap::new();
form.insert("channel", "C12345678");
form.insert("text", "Hello from cURL");
let response = client
.post("https://slack.com/api/chat.postMessage")
.headers(headers)
.form(&form)
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error! status: {}", response.status()).into());
}
let json: serde_json::Value = response.json()?;
println!("{:?}", json);
Ok(())
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
class Program
{
static async Task Main()
{
var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
if (string.IsNullOrEmpty(token))
{
Console.Error.WriteLine("SLACK_BOT_TOKEN environment variable not set");
return;
}
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var form = new Dictionary<string, string>
{
{ "channel", "C12345678" },
{ "text", "Hello from cURL" }
};
var response = await client.PostAsync(
"https://slack.com/api/chat.postMessage",
new FormUrlEncodedContent(form)
);
if (!response.IsSuccessStatusCode)
{
Console.Error.WriteLine($"HTTP error! status: {response.StatusCode}");
return;
}
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<System.Text.Json.JsonElement>(json);
Console.WriteLine(result);
}
}