{
  "slug": "How-to-Make-Python-Telegram-Bot-for-Conversational-AI-370d8e2c82bf",
  "title": "How to Make Python Telegram Bot for Conversational AI",
  "subtitle": "This report outlines the steps involved in creating a conversational AI Telegram bot using Python.",
  "excerpt": "This report outlines the steps involved in creating a conversational AI Telegram bot using Python.",
  "date": "2024-06-10",
  "tags": [
    "Design Rag System",
    "Python",
    "Machine Learning"
  ],
  "readingTime": "2 min",
  "url": "https://medium.com/@mobinshaterian/how-making-python-telegram-bot-for-conversational-ai-370d8e2c82bf",
  "hero": "https://cdn-images-1.medium.com/max/800/1*JzsxGpWnDeemRB8PE-6Naw.jpeg",
  "content": [
    {
      "type": "paragraph",
      "html": "This report outlines the steps involved in creating a conversational AI Telegram bot using Python."
    },
    {
      "type": "paragraph",
      "html": "<strong>1. Creating a Telegram Bot:</strong>"
    },
    {
      "type": "list",
      "ordered": false,
      "items": [
        "Visit the BotFather account on Telegram ([link to BotFather ON Telegram t.me]).",
        "Use the <code>/newbot</code> command to create a new bot. Follow the prompts to set a name and username.",
        "BotFather will provide a unique token, which is essential for authentication."
      ]
    },
    {
      "type": "paragraph",
      "html": "<strong>2. Setting Up the Python Environment:</strong>"
    },
    {
      "type": "list",
      "ordered": false,
      "items": [
        "Install the <code>python-telegram-bot</code> library using <code>pip install python-telegram-bot --upgrade</code>."
      ]
    },
    {
      "type": "paragraph",
      "html": "<strong>3. Writing the Python Code:</strong>"
    },
    {
      "type": "list",
      "ordered": false,
      "items": [
        "Import necessary libraries like <code>logging</code>, <code>Update</code>, and <code>CommandHandler</code> from the <code>telegram</code> and <code>telegram.ext</code> modules.",
        "Configure logging for informative messages.",
        "Define an asynchronous function <code>start</code> that sends a greeting message when the user types <code>/start</code>.",
        "Within the <code>__main__</code> block:",
        "Create an application instance using <code>ApplicationBuilder</code> and provide your bot's token.",
        "Define a command handler for <code>/start</code> using <code>CommandHandler</code> and link it to the <code>start</code> function.",
        "Add the handler to the application.",
        "Start the bot using <code>application.run_polling()</code>."
      ]
    },
    {
      "type": "paragraph",
      "html": "<strong>4. Integrating the AI Model (placeholder):</strong>"
    },
    {
      "type": "list",
      "ordered": false,
      "items": [
        "Define an asynchronous function <code>ai_model</code> to handle user input and interact with an AI model (placeholder function in the provided code).",
        "This function sends a waiting message and retrieves the user’s message.",
        "The placeholder <code>ai_curl</code> function (not shown) would typically send a POST request to an AI service with the user's message and receive its response.",
        "The bot then sends the AI’s response back to the user."
      ]
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*JzsxGpWnDeemRB8PE-6Naw.jpeg",
      "alt": "How to Make Python Telegram Bot for Conversational AI",
      "caption": "",
      "width": 1024,
      "height": 1024
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Make bot account with https://t.me/BotFather"
    },
    {
      "type": "code",
      "lang": "text",
      "code": "/newbot"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Python telegram"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Install"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "pip install python-telegram-bot --upgrade"
    },
    {
      "type": "paragraph",
      "html": "So, <em>let’s get started!</em>. Paste the following into your file:"
    },
    {
      "type": "code",
      "lang": "python",
      "code": "import logging\nfrom telegram\nimport Update\nfrom telegram.ext\nimport ApplicationBuilder, ContextTypes, CommandHandlerlogging.basicConfig(\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n    level=logging.INFO)async\ndef start(update: Update, context: ContextTypes.DEFAULT_TYPE):\n    await context.bot.send_message(chat_id=update.effective_chat.id,\n    text=\"I'm a bot, please talk to me!\")if __name__ == '__main__':\n    application = ApplicationBuilder().token('TOKEN').build()        start_handler =\n    CommandHandler('start', start)\n    application.add_handler(start_handler)        application.run_polling()"
    },
    {
      "type": "paragraph",
      "html": "Replace ‘Token’ with the token you get on the telegram bot."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Add AI part for ask AI model"
    },
    {
      "type": "code",
      "lang": "python",
      "code": "async def ai_model(update: Update, context: ContextTypes.DEFAULT_TYPE):  print(\"please wait\")  await\ncontext.bot.send_message(chat_id=update.effective_chat.id, text=\"⚠️ please wait ⚠️\")  message =\nupdate.message.text  ai_response, similar_answer = ai_curl(message)      await\ncontext.bot.send_message(chat_id=update.effective_chat.id, text=ai_response)"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "send a Post request to get a response from AI"
    },
    {
      "type": "code",
      "lang": "python",
      "code": "def ai_curl(message : str ) :\n    my_obj = {'text': message}\n    x =  requests.post(os.environ.get(\"AI_URL\"), json = my_obj)\n    if x.status_code != 200:        print(\"Error: \", x.status_code)        return \"Error: \" +\n    str(x.status_code)\n    json_message = json.loads(x.text)\n    return json_message['message']"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Stackademic 🎓"
    },
    {
      "type": "paragraph",
      "html": "Thank you for reading until the end. Before you go:"
    },
    {
      "type": "list",
      "ordered": false,
      "items": [
        "Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏",
        "Follow us <a href=\"https://twitter.com/stackademichq\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>X</strong></a> | <a href=\"https://www.linkedin.com/company/stackademic\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>LinkedIn</strong></a> | <a href=\"https://www.youtube.com/c/stackademic\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>YouTube</strong></a> | <a href=\"https://discord.gg/in-plain-english-709094664682340443\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Discord</strong></a>",
        "Visit our other platforms: <a href=\"https://plainenglish.io/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>In Plain English</strong></a> | <a href=\"https://cofeed.app/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>CoFeed</strong></a> | <a href=\"https://differ.blog/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Differ</strong></a>",
        "More content at <a href=\"https://stackademic.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Stackademic.com</strong></a>"
      ]
    }
  ]
}
