Routes

CRUD for AI Chat

A set of API endpoints that allow you to create, read, update, and delete objects related to AI chat integrated into your projects and services.

Example of Chatbot code in a telegram working through our AI assistant API. (Insert your TELEGRAM_TOKEN and AI_API_KEY)

import logging
import httpx
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes

# 🔑 Insert your keys here
TELEGRAM_TOKEN = "76502#####:######-6StZ7Ogb7GpAW7WdZ4sy0R31J3m8"
AI_API_KEY = "######Zete6f6edaks####"

# 🌐 AI assistant endpoint
AI_API_URL = "https://b2b.api.arbitragescanner.io/api/ai-assistant/v1/invoke_assistant"

# 🧠 Handle incoming messages
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    message = update.message
    if not message or not message.text:
        return
    # 🔍 Log incoming message for debugging
    print("📥 Message received:")
    print("chat.type:", message.chat.type)
    print("text:", message.text)
    print("message_thread_id:", message.message_thread_id)
    print("is_topic_message:", message.is_topic_message)

    bot_username = context.bot.username

    # Check if bot is mentioned in a group chat
    if message.chat.type in ["group", "supergroup"]:
        if f"@{bot_username}" not in message.text:
            return
        # Remove mention from text
        user_input = message.text.replace(f"@{bot_username}", "").strip()
    else:
        # In private chat — just take the text
        user_input = message.text.strip()

    payload = {
        "message": user_input
        # "chat_id": user_id  # Use Telegram ID as chat_id
    }

    try:
      async with httpx.AsyncClient() as client:
		response = await client.post(
            AI_API_URL,
            json=payload,
            headers={
                "accept": "application/json",
                "content-type": "application/json",
                "X-API-Key": AI_API_KEY
            }
        )
       response.raise_for_status()
        data = response.json()
        ai_reply = data.get("content", "🤖 Failed to get a response from the assistant.")
    except Exception as e:
        logging.error(f"AI API error: {e}")
        ai_reply = "⚠️ Error while contacting the AI assistant."

    await message.reply_text(
        ai_reply,
        message_thread_id=message.message_thread_id if message.is_topic_message else None
    )

# 🚀 Launch the Telegram bot
def main():
    logging.basicConfig(level=logging.INFO)
    app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    app.run_polling()

if __name__ == "__main__":
    main()