نمونه کد
نمونههای آماده
چند نمونه کوتاه برای cURL، Python، Node.js و n8n.
اگر از کد یا workflow تلگرامی موجود مهاجرت میکنید، راهنمای کاملتر را در مهاجرت از تلگرام به یونیوم ببینید.
cURL
curl -X POST "https://api.uniom.ir/bot<API_KEY>/sendMessage" \
-H "Content-Type: application/json" \
-d '{"chat_id":"@username","text":"پیام از cURL"}'
Python با httpx
import httpx
API_KEY = "<API_KEY>"
BASE_URL = f"https://api.uniom.ir/bot{API_KEY}"
payload = {
"chat_id": "@username",
"text": "پیام از Python",
}
response = httpx.post(f"{BASE_URL}/sendMessage", json=payload, timeout=30)
response.raise_for_status()
print(response.json())
استفاده با python-telegram-bot
اگر پروژه شما با python-telegram-bot نوشته شده، در سناریوهای رایج کافی است token را با API key یونیوم جایگزین کنید و base URL را روی یونیوم بگذارید.
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
API_KEY = "<UNIOM_API_KEY>"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message:
await update.message.reply_text("سلام، این ربات از طریق یونیوم اجرا میشود.")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message and update.message.text:
await update.message.reply_text(f"دریافت شد: {update.message.text}")
application = (
ApplicationBuilder()
.token(API_KEY)
.base_url("https://api.uniom.ir/bot")
.base_file_url("https://api.uniom.ir/file/bot")
.build()
)
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
application.run_polling()
اگر فقط متن میفرستید، base_file_url حیاتی نیست؛ اما برای فایل و media بهتر است از همان ابتدا تنظیمش کنید.
Node.js با fetch
const apiKey = "<API_KEY>";
const response = await fetch(`https://api.uniom.ir/bot${apiKey}/sendMessage`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
chat_id: "@username",
text: "پیام از Node.js"
})
});
console.log(await response.json());
n8n
در node نوع HTTP Request این مقادیر را بگذارید:
| گزینه | مقدار |
|---|---|
| Method | POST |
| URL | https://api.uniom.ir/bot<API_KEY>/sendMessage |
| Body Content Type | JSON |
| Body | {"chat_id":"@username","text":"متن پیام"} |
برای webhook، یک Webhook node بسازید و URL آن را در setWebhook ثبت کنید.
اگر node تلگرامی شما امکان تعریف endpoint سفارشی ندارد، از HTTP Request استفاده کنید و همان body فعلی را به https://api.uniom.ir/bot<API_KEY>/METHOD_NAME بفرستید.