← Blog
Creer un bot Telegram propulse par l'IA
22/04/20265 min
Qu'est-ce qu'un bot Telegram propulsé par l'IA ?
Un bot Telegram alimenté par l'intelligence artificielle peut répondre aux questions, effectuer des recherches sur le web, générer des images, analyser des fichiers et bien plus encore. Grâce à l'API de ShadowRoot AI, vous pouvez créer un bot conversationnel intelligent en quelques minutes, capable de comprendre et répondre dans plus de 30 langues.
Dans ce guide, nous allons vous montrer comment créer, configurer et déployer un bot Telegram connecté à ShadowRoot AI, avec des exemples de code concrets en Python.
Ce que votre bot peut faire
- Répondre aux questions : conversations naturelles sur n'importe quel sujet
- Recherche web : accès aux informations en temps réel via la recherche intégrée
- Génération d'images : création d'images à partir de descriptions textuelles
- Analyse de fichiers : lecture et analyse de documents PDF, images, code
- Mémoire conversationnelle : le bot se souvient du contexte de chaque conversation
- Support multilingue : détection automatique de la langue et réponse native
Étape 1 : Créer le bot avec BotFather
Ouvrez Telegram et recherchez @BotFather. Envoyez la commande /newbot, donnez-lui un nom et un username. BotFather vous fournira un token API que vous garderez précieusement.
# Token fourni par BotFather (exemple)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Étape 2 : Obtenir votre clé API ShadowRoot AI
Connectez-vous à votre tableau de bord sur shadowroot.ai et copiez votre clé API depuis la section "API Keys". Si vous n'avez pas encore de compte, l'essai gratuit de 7 jours vous donne un accès complet.
Étape 3 : Le code Python complet
Installez les dépendances nécessaires :
pip install python-telegram-bot requests
Voici le code complet du bot :
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
# Store conversation history per user
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Hello! I am powered by ShadowRoot AI. Ask me anything!"
)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
# Maintain conversation history
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
# Call ShadowRoot AI API
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Fonctionnalités avancées
Mémoire persistante : stockez l'historique des conversations dans une base de données Redis ou SQLite pour que le bot se souvienne des échanges précédents même après un redémarrage.
Contexte personnalisé : ajoutez un message système pour définir la personnalité et le rôle de votre bot (assistant technique, service client, tuteur linguistique).
Multi-langue automatique : ShadowRoot AI détecte automatiquement la langue de l'utilisateur et répond dans la même langue, sans configuration supplémentaire.
Cas d'utilisation concrets
- Support client : répondez aux questions fréquentes 24h/24 avec un bot qui connaît vos produits
- Assistant de contenu : générez des articles, des résumés et des traductions à la demande
- Assistant de recherche : effectuez des recherches web et synthétisez les résultats
- Bot éducatif : créez un tuteur IA pour l'apprentissage des langues ou des matières scolaires
Déploiement
Pour un déploiement en production, utilisez un serveur VPS ou un service cloud. Avec l'hébergement ShadowRoot AI, vous pouvez déployer votre bot directement sur nos serveurs optimisés.
# Avec Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
# Ou avec systemd
sudo systemctl enable telegram-bot
sudo systemctl start telegram-bot
Conclusion
Créer un bot Telegram intelligent avec ShadowRoot AI est simple, rapide et puissant. En quelques lignes de code, vous obtenez un assistant conversationnel capable de gérer des milliers de conversations simultanées, dans 30+ langues, avec recherche web et génération d'images intégrées.
What Is an AI-Powered Telegram Bot?
An AI-powered Telegram bot can answer questions, perform web searches, generate images, analyze files, and much more. With the ShadowRoot AI API, you can create an intelligent conversational bot in minutes, capable of understanding and responding in over 30 languages.
In this guide, we will show you how to create, configure, and deploy a Telegram bot connected to ShadowRoot AI, with concrete Python code examples.
What Your Bot Can Do
- Answer questions: natural conversations on any topic
- Web search: access real-time information via integrated search
- Image generation: create images from text descriptions
- File analysis: read and analyze PDF documents, images, code
- Conversational memory: the bot remembers the context of each conversation
- Multilingual support: automatic language detection and native response
Step 1: Create the Bot with BotFather
Open Telegram and search for @BotFather. Send the /newbot command, give it a name and username. BotFather will provide you with an API token that you should keep safe.
# Token provided by BotFather (example)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Step 2: Get Your ShadowRoot AI API Key
Log in to your dashboard at shadowroot.ai and copy your API key from the "API Keys" section. If you don't have an account yet, the 7-day free trial gives you full access.
Step 3: The Complete Python Code
Install the required dependencies:
pip install python-telegram-bot requests
Here is the complete bot code:
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
# Store conversation history per user
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Hello! I am powered by ShadowRoot AI. Ask me anything!"
)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
# Maintain conversation history
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
# Call ShadowRoot AI API
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Advanced Features
Persistent memory: store conversation history in a Redis or SQLite database so the bot remembers previous exchanges even after a restart.
Custom context: add a system message to define your bot's personality and role (technical assistant, customer service, language tutor).
Automatic multi-language: ShadowRoot AI automatically detects the user's language and responds in the same language, with no additional configuration.
Real-World Use Cases
- Customer support: answer FAQs 24/7 with a bot that knows your products
- Content assistant: generate articles, summaries, and translations on demand
- Research assistant: perform web searches and synthesize results
- Educational bot: create an AI tutor for language learning or school subjects
Deployment
For production deployment, use a VPS server or cloud service. With ShadowRoot AI hosting, you can deploy your bot directly on our optimized servers.
# With Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
# Or with systemd
sudo systemctl enable telegram-bot
sudo systemctl start telegram-bot
Conclusion
Creating an intelligent Telegram bot with ShadowRoot AI is simple, fast, and powerful. In just a few lines of code, you get a conversational assistant capable of handling thousands of simultaneous conversations, in 30+ languages, with integrated web search and image generation.
什么是AI驱动的Telegram机器人?
AI驱动的Telegram机器人可以回答问题、执行网络搜索、生成图像、分析文件等。通过ShadowRoot AI API,您可以在几分钟内创建一个智能对话机器人,能够理解和回复30多种语言。
在本指南中,我们将向您展示如何创建、配置和部署连接到ShadowRoot AI的Telegram机器人,并提供具体的Python代码示例。
您的机器人能做什么
- 回答问题:就任何话题进行自然对话
- 网络搜索:通过集成搜索访问实时信息
- 图像生成:根据文本描述创建图像
- 文件分析:读取和分析PDF文档、图像、代码
- 对话记忆:机器人记住每次对话的上下文
- 多语言支持:自动语言检测和原生回复
步骤1:使用BotFather创建机器人
打开Telegram并搜索@BotFather。发送/newbot命令,为其取名和用户名。BotFather会提供一个API令牌,请妥善保管。
# BotFather提供的令牌(示例)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
步骤2:获取ShadowRoot AI API密钥
登录shadowroot.ai的控制面板,从"API Keys"部分复制您的API密钥。如果还没有账户,7天免费试用可提供完整访问权限。
步骤3:完整的Python代码
安装所需依赖:
pip install python-telegram-bot requests
以下是完整的机器人代码:
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello! I am powered by ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
高级功能
持久记忆:将对话历史存储在Redis或SQLite数据库中,使机器人即使重启后也能记住之前的交流。
自定义上下文:添加系统消息来定义机器人的个性和角色。
自动多语言:ShadowRoot AI自动检测用户语言并以相同语言回复。
实际应用场景
- 客户支持:用了解您产品的机器人全天候回答常见问题
- 内容助手:按需生成文章、摘要和翻译
- 研究助手:执行网络搜索并综合结果
- 教育机器人:创建用于语言学习或学科辅导的AI教师
部署
# 使用Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
结论
使用ShadowRoot AI创建智能Telegram机器人简单、快速且强大。只需几行代码,您就能获得一个能够处理数千个同时对话的对话助手,支持30多种语言,集成网络搜索和图像生成。
¿Qué es un bot de Telegram con IA?
Un bot de Telegram impulsado por inteligencia artificial puede responder preguntas, realizar búsquedas web, generar imágenes, analizar archivos y mucho más. Con la API de ShadowRoot AI, puedes crear un bot conversacional inteligente en minutos, capaz de entender y responder en más de 30 idiomas.
En esta guía, te mostraremos cómo crear, configurar y desplegar un bot de Telegram conectado a ShadowRoot AI, con ejemplos de código concretos en Python.
Lo que tu bot puede hacer
- Responder preguntas: conversaciones naturales sobre cualquier tema
- Búsqueda web: acceso a información en tiempo real
- Generación de imágenes: creación de imágenes a partir de descripciones de texto
- Análisis de archivos: lectura y análisis de documentos PDF, imágenes, código
- Memoria conversacional: el bot recuerda el contexto de cada conversación
- Soporte multilingüe: detección automática del idioma y respuesta nativa
Paso 1: Crear el bot con BotFather
Abre Telegram y busca @BotFather. Envía el comando /newbot, dale un nombre y un username. BotFather te dará un token API que debes guardar de forma segura.
# Token proporcionado por BotFather (ejemplo)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Paso 2: Obtener tu clave API de ShadowRoot AI
Inicia sesión en tu panel en shadowroot.ai y copia tu clave API desde la sección "API Keys".
Paso 3: El código Python completo
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hola! Soy un bot con ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Funciones avanzadas
Memoria persistente: almacena el historial de conversaciones en Redis o SQLite para que el bot recuerde intercambios anteriores.
Contexto personalizado: añade un mensaje de sistema para definir la personalidad y el rol del bot.
Multi-idioma automático: ShadowRoot AI detecta el idioma del usuario y responde en el mismo idioma automáticamente.
Casos de uso reales
- Soporte al cliente: responde preguntas frecuentes 24/7
- Asistente de contenido: genera artículos, resúmenes y traducciones
- Asistente de investigación: realiza búsquedas web y sintetiza resultados
- Bot educativo: crea un tutor IA para aprendizaje de idiomas
Despliegue
# Con Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
Conclusión
Crear un bot inteligente de Telegram con ShadowRoot AI es simple, rápido y potente. Con pocas líneas de código, obtienes un asistente conversacional que maneja miles de conversaciones simultáneas en más de 30 idiomas.
AI-संचालित Telegram बॉट क्या है?
AI-संचालित Telegram बॉट सवालों का जवाब दे सकता है, वेब सर्च कर सकता है, इमेज जनरेट कर सकता है, फाइलों का विश्लेषण कर सकता है और बहुत कुछ। ShadowRoot AI API के साथ, आप कुछ ही मिनटों में एक बुद्धिमान संवादात्मक बॉट बना सकते हैं जो 30 से अधिक भाषाओं में समझ और जवाब दे सकता है।
आपका बॉट क्या कर सकता है
- सवालों के जवाब: किसी भी विषय पर प्राकृतिक बातचीत
- वेब सर्च: एकीकृत खोज के माध्यम से रियल-टाइम जानकारी
- इमेज जनरेशन: टेक्स्ट विवरण से इमेज बनाना
- फाइल विश्लेषण: PDF दस्तावेज, इमेज, कोड पढ़ना और विश्लेषण करना
- संवाद स्मृति: बॉट प्रत्येक बातचीत का संदर्भ याद रखता है
- बहुभाषी समर्थन: स्वचालित भाषा पहचान और मूल भाषा में जवाब
चरण 1: BotFather के साथ बॉट बनाएं
Telegram खोलें और @BotFather खोजें। /newbot कमांड भेजें, नाम और username दें। BotFather एक API टोकन देगा।
# BotFather द्वारा दिया गया टोकन (उदाहरण)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
चरण 2: ShadowRoot AI API कुंजी प्राप्त करें
shadowroot.ai पर अपने डैशबोर्ड में लॉगिन करें और "API Keys" सेक्शन से अपनी API कुंजी कॉपी करें।
चरण 3: पूर्ण Python कोड
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Namaste! Main ShadowRoot AI se chalta hoon.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
उन्नत सुविधाएं
स्थायी स्मृति: बातचीत इतिहास को Redis या SQLite में संग्रहीत करें ताकि बॉट रीस्टार्ट के बाद भी याद रखे।
कस्टम संदर्भ: बॉट की व्यक्तित्व और भूमिका को परिभाषित करने के लिए सिस्टम मैसेज जोड़ें।
स्वचालित बहुभाषी: ShadowRoot AI स्वचालित रूप से भाषा पहचानता है और उसी भाषा में जवाब देता है।
वास्तविक उपयोग के मामले
- ग्राहक सहायता: 24/7 सामान्य प्रश्नों का उत्तर दें
- कंटेंट असिस्टेंट: लेख, सारांश और अनुवाद बनाएं
- रिसर्च असिस्टेंट: वेब सर्च करें और परिणामों को संश्लेषित करें
- शैक्षिक बॉट: भाषा सीखने के लिए AI ट्यूटर बनाएं
डिप्लॉयमेंट
# Docker के साथ
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
निष्कर्ष
ShadowRoot AI के साथ एक बुद्धिमान Telegram बॉट बनाना सरल, तेज़ और शक्तिशाली है। कोड की कुछ पंक्तियों में, आपको 30+ भाषाओं में हजारों एक साथ बातचीत संभालने में सक्षम एक संवादात्मक सहायक मिलता है।
ما هو بوت تليغرام المدعوم بالذكاء الاصطناعي؟
يمكن لبوت تليغرام المدعوم بالذكاء الاصطناعي الإجابة على الأسئلة وإجراء عمليات بحث على الويب وتوليد الصور وتحليل الملفات وأكثر من ذلك بكثير. مع واجهة برمجة تطبيقات ShadowRoot AI، يمكنك إنشاء بوت محادثة ذكي في دقائق، قادر على الفهم والرد بأكثر من 30 لغة.
ما يمكن لبوتك فعله
- الإجابة على الأسئلة: محادثات طبيعية حول أي موضوع
- البحث على الويب: الوصول إلى المعلومات في الوقت الفعلي
- توليد الصور: إنشاء صور من أوصاف نصية
- تحليل الملفات: قراءة وتحليل مستندات PDF والصور والكود
- ذاكرة المحادثة: يتذكر البوت سياق كل محادثة
- دعم متعدد اللغات: كشف تلقائي للغة والرد بها
الخطوة 1: إنشاء البوت مع BotFather
افتح تليغرام وابحث عن @BotFather. أرسل الأمر /newbot، وأعطه اسماً واسم مستخدم. سيوفر لك BotFather رمز API يجب حفظه بأمان.
# الرمز المقدم من BotFather (مثال)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
الخطوة 2: الحصول على مفتاح API الخاص بـ ShadowRoot AI
سجل الدخول إلى لوحة التحكم على shadowroot.ai وانسخ مفتاح API من قسم "API Keys".
الخطوة 3: كود Python الكامل
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("مرحباً! أنا مدعوم بـ ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
الميزات المتقدمة
الذاكرة المستمرة: خزّن سجل المحادثات في قاعدة بيانات Redis أو SQLite.
السياق المخصص: أضف رسالة نظام لتحديد شخصية البوت ودوره.
تعدد اللغات التلقائي: يكتشف ShadowRoot AI لغة المستخدم تلقائياً ويرد بنفس اللغة.
حالات الاستخدام الواقعية
- دعم العملاء: الرد على الأسئلة الشائعة على مدار الساعة
- مساعد المحتوى: إنشاء مقالات وملخصات وترجمات
- مساعد البحث: إجراء عمليات بحث على الويب وتلخيص النتائج
- بوت تعليمي: إنشاء معلم ذكاء اصطناعي لتعلم اللغات
النشر
# مع Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
الخلاصة
إنشاء بوت تليغرام ذكي مع ShadowRoot AI بسيط وسريع وقوي. ببضعة أسطر من الكود، تحصل على مساعد محادثة قادر على التعامل مع آلاف المحادثات المتزامنة بأكثر من 30 لغة.
O que é um bot de Telegram com IA?
Um bot de Telegram alimentado por inteligência artificial pode responder perguntas, realizar buscas na web, gerar imagens, analisar arquivos e muito mais. Com a API do ShadowRoot AI, você pode criar um bot conversacional inteligente em minutos, capaz de entender e responder em mais de 30 idiomas.
O que seu bot pode fazer
- Responder perguntas: conversas naturais sobre qualquer assunto
- Busca na web: acesso a informações em tempo real
- Geração de imagens: criação de imagens a partir de descrições textuais
- Análise de arquivos: leitura e análise de documentos PDF, imagens, código
- Memória conversacional: o bot lembra do contexto de cada conversa
- Suporte multilingual: detecção automática de idioma e resposta nativa
Passo 1: Criar o bot com BotFather
Abra o Telegram e procure @BotFather. Envie o comando /newbot, dê um nome e username. O BotFather fornecerá um token API.
# Token fornecido pelo BotFather (exemplo)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Passo 2: Obter sua chave API do ShadowRoot AI
Faça login no painel em shadowroot.ai e copie sua chave API da seção "API Keys".
Passo 3: O código Python completo
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Ola! Sou alimentado pelo ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Recursos avançados
Memória persistente: armazene o histórico de conversas em Redis ou SQLite.
Contexto personalizado: adicione uma mensagem de sistema para definir a personalidade do bot.
Multi-idioma automático: ShadowRoot AI detecta o idioma do usuário e responde automaticamente no mesmo idioma.
Casos de uso reais
- Suporte ao cliente: responda perguntas frequentes 24/7
- Assistente de conteúdo: gere artigos, resumos e traduções
- Assistente de pesquisa: realize buscas web e sintetize resultados
- Bot educacional: crie um tutor IA para aprendizado de idiomas
Implantação
# Com Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
Conclusão
Criar um bot inteligente de Telegram com ShadowRoot AI é simples, rápido e poderoso. Com poucas linhas de código, você obtém um assistente conversacional capaz de lidar com milhares de conversas simultâneas em mais de 30 idiomas.
Что такое Telegram-бот на основе ИИ?
Telegram-бот на основе искусственного интеллекта может отвечать на вопросы, выполнять поиск в интернете, генерировать изображения, анализировать файлы и многое другое. С API ShadowRoot AI вы можете создать интеллектуального разговорного бота за считанные минуты, способного понимать и отвечать на более чем 30 языках.
Что может ваш бот
- Отвечать на вопросы: естественные разговоры на любую тему
- Поиск в вебе: доступ к информации в реальном времени
- Генерация изображений: создание изображений по текстовому описанию
- Анализ файлов: чтение и анализ PDF-документов, изображений, кода
- Память разговора: бот запоминает контекст каждого диалога
- Мультиязычная поддержка: автоматическое определение языка и ответ на нём
Шаг 1: Создание бота через BotFather
Откройте Telegram и найдите @BotFather. Отправьте команду /newbot, задайте имя и username. BotFather предоставит API-токен.
# Токен от BotFather (пример)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Шаг 2: Получите API-ключ ShadowRoot AI
Войдите в панель управления на shadowroot.ai и скопируйте API-ключ из раздела "API Keys".
Шаг 3: Полный код на Python
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Привет! Я работаю на ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Продвинутые функции
Постоянная память: храните историю разговоров в Redis или SQLite.
Пользовательский контекст: добавьте системное сообщение для определения личности и роли бота.
Автоматическая мультиязычность: ShadowRoot AI автоматически определяет язык пользователя и отвечает на нём.
Реальные сценарии использования
- Поддержка клиентов: ответы на частые вопросы 24/7
- Контент-ассистент: генерация статей, резюме и переводов
- Исследовательский ассистент: веб-поиск и синтез результатов
- Образовательный бот: ИИ-репетитор для изучения языков
Развёртывание
# С Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
Заключение
Создание интеллектуального Telegram-бота с ShadowRoot AI — это просто, быстро и мощно. Всего несколько строк кода — и у вас разговорный ассистент, способный обрабатывать тысячи одновременных диалогов на 30+ языках.
AI搭載Telegramボットとは?
AI搭載のTelegramボットは、質問への回答、ウェブ検索、画像生成、ファイル分析など多くのことができます。ShadowRoot AI APIを使えば、30以上の言語で理解・応答できるインテリジェントな会話ボットを数分で作成できます。
ボットでできること
- 質問への回答:あらゆるトピックについての自然な会話
- ウェブ検索:統合検索によるリアルタイム情報へのアクセス
- 画像生成:テキスト説明からの画像作成
- ファイル分析:PDFドキュメント、画像、コードの読み取りと分析
- 会話メモリ:ボットが各会話のコンテキストを記憶
- 多言語サポート:自動言語検出とネイティブ応答
ステップ1:BotFatherでボットを作成
Telegramを開き@BotFatherを検索します。/newbotコマンドを送信し、名前とユーザー名を設定します。BotFatherがAPIトークンを提供します。
# BotFatherから提供されたトークン(例)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
ステップ2:ShadowRoot AI APIキーを取得
shadowroot.aiのダッシュボードにログインし、「API Keys」セクションからAPIキーをコピーします。
ステップ3:完全なPythonコード
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("こんにちは!ShadowRoot AIで動いています。")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
高度な機能
永続メモリ:会話履歴をRedisやSQLiteに保存し、再起動後も記憶を維持。
カスタムコンテキスト:システムメッセージでボットの個性と役割を定義。
自動多言語対応:ShadowRoot AIがユーザーの言語を自動検出し同じ言語で応答。
実際のユースケース
- カスタマーサポート:24時間365日よくある質問に回答
- コンテンツアシスタント:記事、要約、翻訳をオンデマンドで生成
- リサーチアシスタント:ウェブ検索と結果の統合
- 教育ボット:語学学習用AIチューター
デプロイメント
# Dockerで
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
結論
ShadowRoot AIでインテリジェントなTelegramボットを作成するのは、シンプルで高速かつパワフルです。わずか数行のコードで、30以上の言語で数千の同時会話を処理できる会話アシスタントが手に入ります。
บอท Telegram ที่ขับเคลื่อนด้วย AI คืออะไร?
บอท Telegram ที่ขับเคลื่อนด้วย AI สามารถตอบคำถาม ค้นหาเว็บ สร้างรูปภาพ วิเคราะห์ไฟล์ และอื่นๆ อีกมากมาย ด้วย API ของ ShadowRoot AI คุณสามารถสร้างบอทสนทนาอัจฉริยะได้ภายในไม่กี่นาที สามารถเข้าใจและตอบกลับได้มากกว่า 30 ภาษา
สิ่งที่บอทของคุณทำได้
- ตอบคำถาม: สนทนาธรรมชาติในทุกหัวข้อ
- ค้นหาเว็บ: เข้าถึงข้อมูลแบบเรียลไทม์
- สร้างรูปภาพ: สร้างภาพจากคำอธิบายข้อความ
- วิเคราะห์ไฟล์: อ่านและวิเคราะห์เอกสาร PDF รูปภาพ โค้ด
- ความจำการสนทนา: บอทจำบริบทของแต่ละการสนทนา
- รองรับหลายภาษา: ตรวจจับภาษาอัตโนมัติและตอบกลับในภาษาเดียวกัน
ขั้นตอนที่ 1: สร้างบอทด้วย BotFather
เปิด Telegram และค้นหา @BotFather ส่งคำสั่ง /newbot ตั้งชื่อและ username BotFather จะให้โทเค็น API
# โทเค็นจาก BotFather (ตัวอย่าง)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
ขั้นตอนที่ 2: รับ API Key ของ ShadowRoot AI
เข้าสู่ระบบแดชบอร์ดที่ shadowroot.ai และคัดลอก API key จากส่วน "API Keys"
ขั้นตอนที่ 3: โค้ด Python เต็มรูปแบบ
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("สวัสดี! ฉันขับเคลื่อนด้วย ShadowRoot AI")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
ฟีเจอร์ขั้นสูง
หน่วยความจำถาวร: เก็บประวัติการสนทนาใน Redis หรือ SQLite เพื่อให้บอทจำการสนทนาก่อนหน้าได้
บริบทที่กำหนดเอง: เพิ่มข้อความระบบเพื่อกำหนดบุคลิกและบทบาทของบอท
หลายภาษาอัตโนมัติ: ShadowRoot AI ตรวจจับภาษาของผู้ใช้โดยอัตโนมัติและตอบกลับในภาษาเดียวกัน
กรณีการใช้งานจริง
- ซัพพอร์ตลูกค้า: ตอบคำถามที่พบบ่อย 24/7
- ผู้ช่วยคอนเทนต์: สร้างบทความ สรุป และการแปล
- ผู้ช่วยวิจัย: ค้นหาเว็บและสังเคราะห์ผลลัพธ์
- บอทการศึกษา: สร้างติวเตอร์ AI สำหรับการเรียนรู้ภาษา
การ Deploy
# ด้วย Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
สรุป
การสร้างบอท Telegram อัจฉริยะด้วย ShadowRoot AI นั้นง่าย รวดเร็ว และทรงพลัง ด้วยโค้ดเพียงไม่กี่บรรทัด คุณจะได้ผู้ช่วยสนทนาที่สามารถจัดการการสนทนาพร้อมกันหลายพันรายการใน 30+ ภาษา
Bot Telegram hỗ trợ AI là gì?
Bot Telegram được hỗ trợ bởi trí tuệ nhân tạo có thể trả lời câu hỏi, tìm kiếm web, tạo hình ảnh, phân tích tệp và nhiều hơn nữa. Với API của ShadowRoot AI, bạn có thể tạo bot trò chuyện thông minh trong vài phút, có khả năng hiểu và phản hồi bằng hơn 30 ngôn ngữ.
Bot của bạn có thể làm gì
- Trả lời câu hỏi: hội thoại tự nhiên về mọi chủ đề
- Tìm kiếm web: truy cập thông tin thời gian thực
- Tạo hình ảnh: tạo ảnh từ mô tả văn bản
- Phân tích tệp: đọc và phân tích PDF, hình ảnh, mã nguồn
- Bộ nhớ hội thoại: bot nhớ ngữ cảnh của mỗi cuộc trò chuyện
- Hỗ trợ đa ngôn ngữ: tự động phát hiện ngôn ngữ và phản hồi bằng ngôn ngữ đó
Bước 1: Tạo bot với BotFather
Mở Telegram và tìm @BotFather. Gửi lệnh /newbot, đặt tên và username. BotFather sẽ cung cấp token API.
# Token từ BotFather (ví dụ)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
Bước 2: Lấy API Key của ShadowRoot AI
Đăng nhập vào bảng điều khiển tại shadowroot.ai và sao chép API key từ phần "API Keys".
Bước 3: Mã Python đầy đủ
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Xin chao! Toi chay bang ShadowRoot AI.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
Tính năng nâng cao
Bộ nhớ lâu dài: Lưu lịch sử hội thoại trong Redis hoặc SQLite.
Ngữ cảnh tùy chỉnh: Thêm thông điệp hệ thống để định nghĩa tính cách và vai trò của bot.
Đa ngôn ngữ tự động: ShadowRoot AI tự động phát hiện ngôn ngữ và trả lời bằng ngôn ngữ đó.
Trường hợp sử dụng thực tế
- Hỗ trợ khách hàng: Trả lời câu hỏi thường gặp 24/7
- Trợ lý nội dung: Tạo bài viết, tóm tắt và bản dịch
- Trợ lý nghiên cứu: Tìm kiếm web và tổng hợp kết quả
- Bot giáo dục: Tạo gia sư AI học ngôn ngữ
Triển khai
# Với Docker
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
Kết luận
Tạo bot Telegram thông minh với ShadowRoot AI thật đơn giản, nhanh chóng và mạnh mẽ. Chỉ với vài dòng mã, bạn có một trợ lý hội thoại có thể xử lý hàng nghìn cuộc trò chuyện cùng lúc bằng 30+ ngôn ngữ.
AI-চালিত Telegram বট কী?
AI-চালিত Telegram বট প্রশ্নের উত্তর দিতে, ওয়েব সার্চ করতে, ছবি তৈরি করতে, ফাইল বিশ্লেষণ করতে এবং আরও অনেক কিছু করতে পারে। ShadowRoot AI API দিয়ে, আপনি কয়েক মিনিটে একটি বুদ্ধিমান কথোপকথন বট তৈরি করতে পারেন যা 30+ ভাষায় বুঝতে ও উত্তর দিতে পারে।
আপনার বট কী করতে পারে
- প্রশ্নের উত্তর: যেকোনো বিষয়ে স্বাভাবিক কথোপকথন
- ওয়েব সার্চ: রিয়েল-টাইম তথ্য অ্যাক্সেস
- ছবি তৈরি: টেক্সট বর্ণনা থেকে ছবি তৈরি
- ফাইল বিশ্লেষণ: PDF, ছবি, কোড পড়া ও বিশ্লেষণ
- কথোপকথনের স্মৃতি: বট প্রতিটি কথোপকথনের প্রসঙ্গ মনে রাখে
- বহুভাষিক সমর্থন: স্বয়ংক্রিয় ভাষা সনাক্তকরণ ও নেটিভ প্রতিক্রিয়া
ধাপ 1: BotFather দিয়ে বট তৈরি
Telegram খুলুন এবং @BotFather খুঁজুন। /newbot কমান্ড পাঠান, নাম ও username দিন। BotFather একটি API টোকেন দেবে।
# BotFather থেকে প্রাপ্ত টোকেন (উদাহরণ)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
ধাপ 2: ShadowRoot AI API কী পান
shadowroot.ai-এর ড্যাশবোর্ডে লগইন করুন এবং "API Keys" থেকে আপনার API কী কপি করুন।
ধাপ 3: সম্পূর্ণ Python কোড
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("হ্যালো! আমি ShadowRoot AI দ্বারা চালিত।")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
উন্নত বৈশিষ্ট্য
স্থায়ী স্মৃতি: Redis বা SQLite-তে কথোপকথনের ইতিহাস সংরক্ষণ করুন।
কাস্টম প্রসঙ্গ: বটের ব্যক্তিত্ব ও ভূমিকা নির্ধারণ করতে সিস্টেম বার্তা যোগ করুন।
স্বয়ংক্রিয় বহুভাষিক: ShadowRoot AI স্বয়ংক্রিয়ভাবে ভাষা সনাক্ত করে এবং একই ভাষায় উত্তর দেয়।
বাস্তব ব্যবহারের ক্ষেত্র
- গ্রাহক সহায়তা: 24/7 সাধারণ প্রশ্নের উত্তর দিন
- কন্টেন্ট সহায়ক: নিবন্ধ, সারাংশ ও অনুবাদ তৈরি করুন
- গবেষণা সহায়ক: ওয়েব সার্চ ও ফলাফল সংশ্লেষণ
- শিক্ষামূলক বট: ভাষা শেখার জন্য AI টিউটর তৈরি করুন
ডিপ্লয়মেন্ট
# Docker দিয়ে
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
উপসংহার
ShadowRoot AI দিয়ে একটি বুদ্ধিমান Telegram বট তৈরি করা সহজ, দ্রুত এবং শক্তিশালী। কোডের কয়েকটি লাইনে, আপনি 30+ ভাষায় হাজার হাজার একসাথে কথোপকথন পরিচালনা করতে সক্ষম একটি সংলাপ সহায়ক পাবেন।
AI 기반 Telegram 봇이란?
AI 기반 Telegram 봇은 질문에 답하고, 웹 검색을 수행하고, 이미지를 생성하고, 파일을 분석하는 등 다양한 작업을 수행할 수 있습니다. ShadowRoot AI API를 사용하면 30개 이상의 언어로 이해하고 응답할 수 있는 지능형 대화 봇을 몇 분 만에 만들 수 있습니다.
봇이 할 수 있는 것
- 질문 답변: 모든 주제에 대한 자연스러운 대화
- 웹 검색: 통합 검색을 통한 실시간 정보 접근
- 이미지 생성: 텍스트 설명에서 이미지 생성
- 파일 분석: PDF 문서, 이미지, 코드 읽기 및 분석
- 대화 기억: 봇이 각 대화의 컨텍스트를 기억
- 다국어 지원: 자동 언어 감지 및 네이티브 응답
1단계: BotFather로 봇 생성
Telegram을 열고 @BotFather를 검색합니다. /newbot 명령을 보내고 이름과 username을 설정합니다. BotFather가 API 토큰을 제공합니다.
# BotFather에서 제공한 토큰 (예시)
TELEGRAM_TOKEN = "7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxx"
2단계: ShadowRoot AI API 키 받기
shadowroot.ai 대시보드에 로그인하여 "API Keys" 섹션에서 API 키를 복사합니다.
3단계: 완전한 Python 코드
pip install python-telegram-bot requests
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
SR_API_KEY = os.getenv("SR_API_KEY")
SR_API_URL = "https://shadowroot.ai/v1/chat"
conversations = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("안녕하세요! ShadowRoot AI로 구동됩니다.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
user_msg = update.message.text
if user_id not in conversations:
conversations[user_id] = []
conversations[user_id].append({"role": "user", "content": user_msg})
response = requests.post(SR_API_URL, json={
"messages": conversations[user_id],
"model": "shadowroot-v2",
"web_search": True
}, headers={"Authorization": f"Bearer {SR_API_KEY}"})
reply = response.json()["choices"][0]["message"]["content"]
conversations[user_id].append({"role": "assistant", "content": reply})
await update.message.reply_text(reply)
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
고급 기능
영구 메모리: Redis 또는 SQLite에 대화 기록을 저장하여 재시작 후에도 이전 대화를 기억합니다.
커스텀 컨텍스트: 시스템 메시지를 추가하여 봇의 성격과 역할을 정의합니다.
자동 다국어: ShadowRoot AI가 사용자의 언어를 자동으로 감지하고 같은 언어로 응답합니다.
실제 사용 사례
- 고객 지원: 24/7 자주 묻는 질문에 답변
- 콘텐츠 어시스턴트: 기사, 요약, 번역 생성
- 리서치 어시스턴트: 웹 검색 및 결과 종합
- 교육용 봇: 언어 학습을 위한 AI 튜터 생성
배포
# Docker로
docker build -t my-telegram-bot .
docker run -d --env-file .env my-telegram-bot
결론
ShadowRoot AI로 지능형 Telegram 봇을 만드는 것은 간단하고 빠르며 강력합니다. 단 몇 줄의 코드로 30개 이상의 언어로 수천 개의 동시 대화를 처리할 수 있는 대화형 어시스턴트를 얻을 수 있습니다.