curl -X POST https://www.heangblackcyberfree.online/api/v1/gpt/chat \
-H "Content-Type: application/json" \
-H "heang-API-Key: e5af7b18d6c35aee93d710b6f92c8bb4dafdc1c339b0be02ffd065574c361a90" \
-d '{
"prompt": "Hello HeaNg! Explain how worm-chat engine works.",
"session_id": "test-user-1",
"mode": "default",
"stream": false
}'
import requests
import sys
import json
import requests
API_URL = "https://www.heangblackcyberfree.online/api/v1/gpt/chat"
API_KEY = "YOUR_API_KEY_HERE" # <-- put your API key here
headers = {
"Content-Type": "application/json",
"Accept": "text/event-stream",
"heang-API-Key": API_KEY,
}
payload = {
"prompt": "Write a secure AES-256 encryption helper in Python",
"session_id": "py-client-101",
"mode": "coder", # default | cyber_security | coder | teacher
"stream": True,
}
try:
with requests.post(
API_URL, headers=headers, json=payload, stream=True, timeout=120
) as r:
r.encoding = "utf-8"
if r.status_code != 200:
sys.stderr.write(f"HTTP {r.status_code}: {r.text[:300]}\n")
sys.exit(1)
for line in r.iter_lines(decode_unicode=True):
if not line:
continue
if "[DONE]" in line:
break
if not line.startswith("data: "):
continue
try:
chunk = json.loads(line[6:])
except json.JSONDecodeError as e:
sys.stderr.write(f"\n[parse error] {e}: {line[:120]}\n")
continue
content = chunk.get("content") or chunk.get("data", {}).get("content")
if content:
print(content, end="", flush=True)
print()
except requests.Timeout:
sys.exit("\nRequest timed out after 120 seconds")
except requests.RequestException as e:
sys.exit(f"\nNetwork error: {e}")
// Standard Fetch (Node.js 18+ or Browser)
// Run with: node app.js
const API_URL = "https://www.heangblackcyberfree.online/api/v1/gpt/chat";
const API_KEY = "YOUR_API_KEY_HERE"; // <-- put your API key here
async function chatWithHeang(userPrompt, sessionId = `web-${crypto.randomUUID()}`) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 60_000);
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"heang-API-Key": API_KEY,
},
body: JSON.stringify({
prompt: userPrompt,
session_id: sessionId,
mode: "default",
}),
signal: controller.signal,
});
const text = await response.text();
console.log("API status:", response.status, "| body:", text.slice(0, 300));
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${text.slice(0, 200)}`);
}
let json;
try {
json = JSON.parse(text);
} catch {
throw new Error(`API returned invalid JSON: ${text.slice(0, 200)}`);
}
if (json.status && json.status !== "success") {
throw new Error(json.message || json.error || "API returned non-success status");
}
const reply = json.data?.reply;
if (!reply) {
throw new Error(`Missing data.reply in response: ${text.slice(0, 200)}`);
}
console.log("AI:", reply);
return reply;
} catch (err) {
if (err.name === "AbortError") {
throw new Error("Request timed out after 60 seconds");
}
throw err;
} finally {
clearTimeout(timer);
}
}
// Example
chatWithHeang("Hello, who are you?")
.then(r => console.log("Success:", r))
.catch(e => console.error("Failed:", e.message));
# pip install python-telegram-bot requests
# pip install python-telegram-bot httpx
import httpx
import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
API_URL = "https://www.heangblackcyberfree.online/api/v1/gpt/chat"
API_KEY = "YOUR_API_KEY_HERE" # put your API key here (do not expose publicly)
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE" # put your Telegram bot token here
# Use a single client to reuse connections
client = httpx.AsyncClient(timeout=60.0)
async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message or not update.message.text:
return
user_id = str(update.effective_user.id)
await context.bot.send_chat_action(
chat_id=update.effective_chat.id, action="typing"
)
try:
res = await client.post(
API_URL,
headers={
"Content-Type": "application/json",
"heang-API-Key": API_KEY,
},
json={
"prompt": update.message.text,
"session_id": f"tg_{user_id}",
"mode": "default",
},
)
logger.info("API status: %s | body: %s", res.status_code, res.text[:200])
if res.status_code == 200:
data = res.json()
reply = data.get("data", {}).get("reply")
if reply:
await update.message.reply_text(reply)
else:
await update.message.reply_text("ā ļø API returned an invalid format.")
else:
await update.message.reply_text(
f"ā ļø API error ({res.status_code}): {res.text[:200]}"
)
except httpx.TimeoutException:
await update.message.reply_text("ā±ļø API took too long, please try again.")
except Exception as e:
logger.exception("Handler error")
await update.message.reply_text(f"ā Something went wrong: {e}")
async def on_shutdown(app):
await client.aclose()
if __name__ == "__main__":
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, reply_handler))
app.post_shutdown = on_shutdown
print("Bot is running...")
app.run_polling()