import os
import requests
url = "https://slack.com/api/conversations.create"
headers = {
"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
data = {
"name": "new-channel",
"is_private": False
}
response = requests.post(url, headers=headers, json=data)
if response.status_code != 200:
raise Exception(f"Request failed with status {response.status_code}")
print(response.json())
import os
import httpx
url = "https://slack.com/api/conversations.create"
headers = {
"Authorization": f"Bearer {os.environ['SLACK_BOT_TOKEN']}"
}
data = {
"name": "new-channel",
"is_private": False
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
if response.status_code != 200:
raise Exception(f"Request failed with status {response.status_code}")
print(response.json())
import fetch from 'node-fetch';
import { config } from 'dotenv';
config();
const url = 'https://slack.com/api/conversations.create';
const headers = {
'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const body = JSON.stringify({
name: 'new-channel',
is_private: false
});
fetch(url, {
method: 'POST',
headers,
body
})
.then(res => {
if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
return res.json();
})
.then(console.log)
.catch(console.error);
import axios from 'axios';
import { config } from 'dotenv';
config();
const url = 'https://slack.com/api/conversations.create';
const headers = {
'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
};
const data = {
name: 'new-channel',
is_private: false
};
axios.post(url, data, { headers })
.then(res => {
if (res.status !== 200) throw new Error(`Request failed with status ${res.status}`);
console.log(res.data);
})
.catch(console.error);
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
url := "https://slack.com/api/conversations.create"
token := os.Getenv("SLACK_BOT_TOKEN")
if token == "" {
panic("SLACK_BOT_TOKEN environment variable not set")
}
body := map[string]interface{}{
"name": "new-channel",
"is_private": false,
}
jsonBody, _ := json.Marshal(body)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, string(body)))
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
<?php
$url = 'https://slack.com/api/conversations.create';
$token = getenv('SLACK_BOT_TOKEN');
if (empty($token)) {
die('SLACK_BOT_TOKEN environment variable not set');
}
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
];
$data = [
'name' => 'new-channel',
'is_private' => false
];
$options = [
'http' => [
'header' => $headers,
'method' => 'POST',
'content' => json_encode($data),
'ignore_errors' => true
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
die('Request failed with status ' . $http_response_header[0]);
}
$json = json_decode($response, true);
print_r($json);
require 'net/http'
require 'json'
require 'uri'
url = URI.parse('https://slack.com/api/conversations.create')
token = ENV.fetch('SLACK_BOT_TOKEN')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.path)
request['Authorization'] = "Bearer #{token}"
request['Content-Type'] = 'application/json'
request.body = { name: 'new-channel', is_private: false }.to_json
response = http.request(request)
unless response.code == '200'
raise "Request failed with status #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let url = URL(string: "https://slack.com/api/conversations.create")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SLACK_BOT_TOKEN"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"name": "new-channel",
"is_private": false
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
}
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
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 url = "https://slack.com/api/conversations.create";
let token = env::var("SLACK_BOT_TOKEN")?;
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/json"),
);
let body: HashMap<&str, serde_json::Value> = HashMap::from([
("name", serde_json::Value::String("new-channel".to_string())),
("is_private", serde_json::Value::Bool(false)),
]);
let client = Client::new();
let response = client
.post(url)
.headers(headers)
.json(&body)
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed with 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.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "https://slack.com/api/conversations.create";
var token = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN");
if (string.IsNullOrEmpty(token))
{
throw new Exception("SLACK_BOT_TOKEN environment variable not set");
}
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var body = new Dictionary<string, object>
{
{ "name", "new-channel" },
{ "is_private", false }
};
var response = await client.PostAsJsonAsync(url, body);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Request failed with status {response.StatusCode}");
}
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
}