{"id":61926,"date":"2025-04-25T10:17:46","date_gmt":"2025-04-25T10:17:46","guid":{"rendered":"https:\/\/dev.outrightcrm.in\/dev\/store\/?p=61926"},"modified":"2025-05-05T04:33:37","modified_gmt":"2025-05-05T04:33:37","slug":"whatsapp-chatbot-with-twilio-and-python","status":"publish","type":"post","link":"https:\/\/dev.outrightcrm.in\/dev\/store\/blog\/whatsapp-chatbot-with-twilio-and-python\/","title":{"rendered":"Building a WhatsApp Chatbot with Twilio and Python"},"content":{"rendered":"\n<p>WhatsApp Chatbot with Twilio and Python: In the competitive digital world of today, developers and businesses are consistently searching for creative ways to communicate more effectively with users. WhatsApp, having approximately 2+ billion active users, provides a great opportunity to connect with the audience on a platform where they spend most of their time. Integrating the powerful communication features of Twilio with the inherent flexibility of Python ensures the right foundation for developing responsive and smart WhatsApp chatbots.<\/p>\n\n\n\n<BR\/>\n\n\n\n<p>In this guide, let us go through the user-friendly process of generating a WhatsApp chatbot with Twilio and Python. Using this guide, you will be able to create engaged automated conversations. These automated conversations are essentially helpful while managing customer inquiries, imparting information to the clients, or processing straightforward requests. Imagine converting one of the most famous messaging platforms into an automated channel of customer communication.<\/p>\n\n\n\n<br\/>\n\n\n\n<div class=\"video-container\">\n        <iframe loading=\"lazy\" width=\"853\" height=\"480\" \n                src=\"https:\/\/www.youtube.com\/embed\/dsJgse8gc2o\" \n                title=\"Building a WhatsApp Chatbot with Twilio and Python (2025)\" \n                frameborder=\"0\" \n                allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" \n                referrerpolicy=\"strict-origin-when-cross-origin\" \n                allowfullscreen>\n        <\/iframe>\n    <\/div>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">Advantages of Creating a WhatsApp Chatbot<\/h2>\n\n\n\n<br\/>\n\n\n\n<p>Since this blog is focused on building a WhatsApp Chatbot with Twilio and Python, it involves understanding a lot of code. Before going straight to the codes, it is worthwhile to recognize the advantages of developing a robust WhatsApp chatbot:<\/p>\n\n\n\n<br\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Access to Global Audience: Approximately 2+ billion users in 180+ countries utilize WhatsApp for daily communication.<br><br><\/li>\n\n\n\n<li>Improving Engagement: One of the most notable advantages of WhatsApp is its high open rate. Its open rate is as high as 98% compared to other channels like emails, which have an open rate of only 20%.<br><br><\/li>\n\n\n\n<li>Communicate Using Different Media: WhatsApp supports different media formats. You can easily receive images, location data, documents, and more.<br><br><\/li>\n\n\n\n<li>Comprehensive Encryption: WhatsApp is a well-protected platform with end-to-end encryption. Through this platform, you can communicate securely and comprehensively protect confidential information.<br><br><\/li>\n\n\n\n<li>24\/7 Availability: Ensure immediate responses to customers, irrespective of where you are.<br><br><\/li>\n\n\n\n<li>Cost Effectiveness: Minimize overhead in customer services, enhancing response times.<\/li>\n<\/ul>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">What Do You Need?<\/h2>\n\n\n\n<br\/>\n\n\n\n<p>To understand the codes and steps mentioned in the blog, you need a few prerequisites mentioned as follows:<\/p>\n\n\n\n<br\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Make sure that you have Python 3.6 or higher installed.<br><br><\/li>\n\n\n\n<li>You also need to have a Twilio account.<br><br><\/li>\n\n\n\n<li>You can proceed to the Twilio website (Twilio.com) and sign up for absolutely no cost.<br><br><\/li>\n\n\n\n<li>Pip package manager.<br><br><\/li>\n\n\n\n<li>Basic understanding and knowledge of the Flash web framework.<br><br><\/li>\n\n\n\n<li>A Uniform Resource Locator for your <strong><a href=\"https:\/\/dev.outrightcrm.in\/dev\/store\/blog\/what-are-webhooks\/\" target=\"_blank\" rel=\"noreferrer noopener\">webhook<\/a><\/strong>, which can be accessed publicly.<br><br><\/li>\n\n\n\n<li>For development, we will use ngrok here.<br><br><\/li>\n\n\n\n<li>A valid phone number is enabled on WhatsApp.<\/li>\n<\/ul>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">Configuring Your WhatsApp Sandbox on Twilio<\/h2>\n\n\n\n<br\/>\n\n\n\n<p>Before generating code, you need to make sure that your Twilio environment is up and running:<\/p>\n\n\n\n<p><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Sign in to your Twilio account, and if you don\u2019t have one, you can create one at the Twilio website.<br><br><\/li>\n\n\n\n<li>Now, proceed to enter the Twilio Console and enter the WhatsApp Sandbox.<br><br><\/li>\n\n\n\n<li>Complete the instructions to ensure the connection between your WhatsApp account and the Sandbox.<br><br><\/li>\n\n\n\n<li>Note down your Auth Token and Twilio Account SID. You will require these later on.<\/li>\n<\/ol>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">Developing Your WhatsApp Chatbot<\/h2>\n\n\n\n<br\/>\n\n\n\n<h3 class=\"wp-block-heading\">1. Configuring Your Python Environment<\/h3>\n\n\n\n<br\/>\n\n\n\n<p>Let us begin by creating a fresh project directory and establishing a virtual environment:<\/p>\n\n\n\n<br\/>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code># Create a project directory \nmkdir WhatsApp-chatbot \ncd whatsapp-chatbot \n \n# Create and activate a virtual environment \npython -m venv venv \nsource venv\/bin\/activate  # On Windows, use venv\\Scripts\\activate \n \n# Install required packages \npip install flask twilio python-dotenv \n<\/code><\/pre>\n\n\n\n<br\/>\n\n\n\n<h3 class=\"wp-block-heading\">2. Developing the Flask Application<\/h3>\n\n\n\n<br\/>\n\n\n\n<p>Now, let us proceed to creating a standard Flash application that can manage all incoming messages on WhatsApp simply:<\/p>\n\n\n\n<br\/>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code># app.py \nimport os \nfrom flask import Flask, request, Response \nfrom twilio.twiml.messaging_response import MessagingResponse \nfrom dotenv import load_dotenv \n \n# Load environment variables \nload_dotenv() \n \napp = Flask(__name__) \n \n@app.route(\"\/webhook\", methods=&#91;\"POST\"]) \ndef webhook(): \n    # Get incoming message details \n    incoming_msg = request.values.get('Body', '').strip().lower() \n    sender = request.values.get('From', '') \n     \n    # Create a response object \n    resp = MessagingResponse() \n     \n    # Handle different user inputs \n    if 'hello' in incoming_msg: \n        resp.message(\"Hi there! I'm your WhatsApp bot. How can I help you today?\") \n    elif 'help' in incoming_msg: \n        resp.message(\"I can assist with:\\n- Product information\\n- Business hours\\n- Contact details\\n\\nJust ask me what you need!\") \n    elif 'hours' in incoming_msg: \n        resp.message(\"We're open Monday-Friday, 9am-5pm.\") \n    else: \n        resp.message(\"I didn't understand that. Try asking for 'help' to see what I can do.\") \n     \n    return str(resp) \n \nif __name__ == \"__main__\": \n    app.run(debug=True) \n<\/code><\/pre>\n\n\n\n<br\/>\n\n\n\n<h3 class=\"wp-block-heading\">3. Ensuring Accessibility of Your Webhook<\/h3>\n\n\n\n<br\/>\n\n\n\n<p>To make Twilio capable of transferring all incoming WhatsApp messages to your applications, it is important to ensure public accessibility of your webhook. During the stage of development, you need to leverage ngrok:<\/p>\n\n\n\n<br\/>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code># Install ngrok if you haven't already \n# Then start it on the same port as your Flask app \nngrok http 5000 \n<\/code><\/pre>\n\n\n\n<br\/>\n\n\n\n<p>Now, closely observe the HTTPS uniform resource locator that ngrok gives (e.g., https:\/\/a1b2c3d4.ngrok.io). You must set up this URL in the WhatsApp Sandbox in your <strong><a href=\"https:\/\/dev.outrightcrm.in\/dev\/store\/blog\/what-is-twilio-platform-how-it-will-enhance-your-experience\/\" target=\"_blank\" rel=\"noreferrer noopener\">Twilio platform<\/a><\/strong>. It will be followed by the route that you have already defined. (e.g., https:\/\/a1b2c3d4.ngrok.io\/webhook).<\/p>\n\n\n\n<br\/>\n\n\n\n<h3 class=\"wp-block-heading\">4. Improving Your Chatbot with Natural Language Processing<\/h3>\n\n\n\n<br\/>\n\n\n\n<p>Let us make our <strong><a href=\"https:\/\/www.outrightcrm.com\/blog\/what-is-ai-chatbot\/\" target=\"_blank\" rel=\"noreferrer noopener\">chatbot<\/a><\/strong> more intelligent by adding a few NLP capabilities as shown below:<\/p>\n\n\n\n<br\/>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code># Add this after your imports \nfrom fuzzywuzzy import fuzz \nimport random \n \n# Install with: pip install fuzzywuzzy \ndef process_message(message): \n    # Define some intents and their respective responses \n    intents = { \n        \"greeting\": &#91;\"hello\", \"hi\", \"hey\", \"howdy\", \"greetings\"], \n        \"farewell\": &#91;\"bye\", \"goodbye\", \"see you\", \"later\"], \n        \"thanks\": &#91;\"thank\", \"thanks\", \"appreciate\", \"grateful\"], \n        \"hours\": &#91;\"hour\", \"open\", \"close\", \"time\", \"schedule\"], \n        \"products\": &#91;\"product\", \"offer\", \"sell\", \"item\"], \n        \"price\": &#91;\"price\", \"cost\", \"how much\", \"pricing\"] \n    } \n\n    responses = { \n        \"greeting\": &#91; \n            \"Hello! How can I assist you today?\", \n            \"Hi there! What can I help you with?\", \n            \"Hey! What brings you here today?\" \n        ], \n        \"farewell\": &#91; \n            \"Goodbye! Feel free to message again if you need anything.\", \n            \"See you later! Have a great day!\", \n            \"Take care! I'm here if you need more help.\" \n        ], \n        \"thanks\": &#91; \n            \"You're welcome! Is there anything else I can help with?\", \n            \"Glad I could help! Let me know if you need anything more.\", \n            \"My pleasure! Don't hesitate to reach out again.\" \n        ], \n\"hours\": &#91; \n            \"Our business hours are Monday-Friday, 9am-5pm.\", \n            \"We're open weekdays from 9am to 5pm.\", \n            \"You can visit us between 9am and 5pm, Monday through Friday.\" \n        ], \n        \"products\": &#91; \n            \"We offer a range of digital solutions including website development, mobile apps, and AI integration.\", \n            \"Our product line includes software solutions for businesses of all sizes.\", \n            \"We specialize in custom software, mobile applications, and enterprise solutions.\" \n        ], \n        \"price\": &#91; \n            \"Our pricing varies based on project requirements. Would you like to speak with a sales representative?\", \n            \"We offer custom quotes based on your specific needs. Can I collect some information about your project?\", \n            \"Pricing depends on features and scale. I'd be happy to connect you with our sales team for a quote.\" \n        ] \n    } \n     \n    # Find the best matching intent \n    best_match = None \n    highest_score = 0 \n     \n    for intent, phrases in intents.items(): \n        for phrase in phrases: \n            score = fuzz.partial_ratio(message, phrase) \n            if score &gt; highest_score and score &gt; 70:  # 70% match threshold \n                highest_score = score \n                best_match = intent \n     \n    if best_match: \n        return random.choice(responses&#91;best_match]) \n    else: \n        return \"I'm not sure I understand. Could you rephrase or ask\n\"hours\": &#91; \n            \"Our business hours are Monday-Friday, 9am-5pm.\", \n            \"We're open weekdays from 9am to 5pm.\", \n            \"You can visit us between 9am and 5pm, Monday through Friday.\" \n        ], \n        \"products\": &#91; \n            \"We offer a range of digital solutions including website development, mobile apps, and AI integration.\", \n            \"Our product line includes software solutions for businesses of all sizes.\", \n            \"We specialize in custom software, mobile applications, and enterprise solutions.\" \n        ], \n        \"price\": &#91; \n            \"Our pricing varies based on project requirements. Would you like to speak with a sales representative?\", \n            \"We offer custom quotes based on your specific needs. Can I collect some information about your project?\", \n            \"Pricing depends on features and scale. I'd be happy to connect you with our sales team for a quote.\" \n        ] \n    } \n     \n    # Find the best matching intent \n    best_match = None \n    highest_score = 0 \n     \n    for intent, phrases in intents.items(): \n        for phrase in phrases: \n            score = fuzz.partial_ratio(message, phrase) \n            if score &gt; highest_score and score &gt; 70:  # 70% match threshold \n                highest_score = score \n                best_match = intent \n     \n    if best_match: \n        return random.choice(responses&#91;best_match]) \n    else: \n        return \"I'm not sure I understand. Could you rephrase or ask<\/code><\/pre>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">Implementing Your WhatsApp Chatbot<\/h2>\n\n\n\n<br\/>\n\n\n\n<p>For production, you must deploy the Flask application you have created for a web server. Here, you have options such as<\/p>\n\n\n\n<br\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Heroku:<\/strong> Easy deployment with a free tier for small applications<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>AWS Elastic Beanstalk:<\/strong> A Scalable option with AWS infrastructure<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Google Cloud Run:<\/strong> Serverless container deployment<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>DigitalOcean App Platform:<\/strong> Simple deployment with predictable pricing<\/li>\n<\/ul>\n\n\n\n<br\/>\n\n\n\n<p>Irrespective of the platform you have selected, you need to make sure to<\/p>\n\n\n\n<br\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Securely configure all the environment variables.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set up your Twilio webhook uniform resource locator to direct to your production endpoint.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Execute logging and error handling correctly.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You can also think about including a database to ensure storage of your conversation history.<\/li>\n<\/ul>\n\n\n\n<br\/>\n\n\n\n<h2 class=\"wp-block-heading has-text-align-center has-very-light-gray-to-cyan-bluish-gray-gradient-background has-background\">Conclusion<\/h2>\n\n\n\n<br\/>\n\n\n\n<p>So, this was it! You have just learned an easy way of developing a WhatsApp chatbot with Twilio and Python. Now, you can further work on this foundation and expand it with advanced features such as<\/p>\n\n\n\n<br\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Incorporate databases to store important user details and the entire conversation history.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensure connectivity with the external Application Programming Interface for real-time information (stock prices, weather, etc.)<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Deployment of more advanced NLP via libraries such as spaCy or sophisticated frameworks such as Rasa.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Add capabilities for media responses, i.e., making the WhatsApp bot capable of sharing documents, images, or location sharing.<br><br><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Incorporate it with your operational <strong><a href=\"https:\/\/dev.outrightcrm.in\/dev\/store\/product\/twilio-sms-for-suitecrm\/\" target=\"_blank\" rel=\"noreferrer noopener\">CRM tool<\/a><\/strong> or other customer service solutions.<\/li>\n<\/ul>\n\n\n\n<br\/>\n\n\n\n<p>In an intensely connected world, the role of messaging cannot be overlooked in online communication. WhatsApp chatbots present themselves as a valuable solution for businesses looking to interact with customers on the platform where they come daily and spend a substantial amount of time. The integration of Python\u2019s versatility and the robust API of Twilio ensures that deploying these solutions is easy, even for developers with less experience.<\/p>\n\n\n\n<br\/>\n\n\n\n<p>Begin small, prioritize solving particular user problems, and consistently fine-tune your bot depending on real-time conversation data. With more upgrades and integrations, you can easily make your WhatsApp chatbot an intrinsic part of your overall customer engagement strategy.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>WhatsApp Chatbot with Twilio and Python: In the competitive digital world of today, developers and businesses are consistently searching for [&hellip;]<\/p>\n","protected":false},"author":17772,"featured_media":61937,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[57,63],"tags":[623],"class_list":["post-61926","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-api","category-twilio","tag-whatsapp-chatbot-with-twilio-and-python"],"acf":[],"_links":{"self":[{"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/posts\/61926","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/users\/17772"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/comments?post=61926"}],"version-history":[{"count":7,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/posts\/61926\/revisions"}],"predecessor-version":[{"id":62070,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/posts\/61926\/revisions\/62070"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/media\/61937"}],"wp:attachment":[{"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/media?parent=61926"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/categories?post=61926"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.outrightcrm.in\/dev\/store\/wp-json\/wp\/v2\/tags?post=61926"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}