7 LangChain Integrations: Slack, Discord, WhatsApp Bots
Build LangChain chatbots for Slack, Discord, WhatsApp, and Telegram. Step-by-step code for each platform with memory, tools, and deployment patterns.
Get more content like this on Telegram!
Daily AI tips, notes & resources — free
7 LangChain Integrations: Building Chatbots for Slack, Discord, and More
I spent three weeks integrating LangChain bots across every major messaging platform for a client, and the differences between them are... surprisingly annoying. Each platform has its own mental model for how bots work — Slack thinks in terms of events and blocks, Discord thinks in commands and intents, WhatsApp thinks in webhooks. LangChain itself doesn't care about any of this, which is both the strength and the challenge.
This guide covers practical setups for Slack, Discord, WhatsApp, Telegram, and a few others. Every code snippet here is tested. I'll tell you where I got stuck so you don't have to spend three hours debugging the same thing.
In this guide, you'll get working code for 7 platform integrations, a comparison of each platform's free tier and limitations, and architectural patterns for handling memory across multiple users.
Platform Comparison Before You Start
Before picking a platform, know what you're getting into:
| Platform | Free Tier | Monthly Active Users | Bot Complexity | Webhook Needed |
|---|---|---|---|---|
| Slack | 10K messages/month | 200M+ | Medium | Yes (or Socket Mode) |
| Discord | Unlimited | 500M+ | Low | No (Gateway) |
| 1,000 msgs free/month | 2B+ | High | Yes | |
| Telegram | Unlimited | 800M+ | Low | Optional |
| Teams | 25 users free | 300M+ | High | Yes |
| Line | Limited | 200M+ | Medium | Yes |
| Twilio SMS | Trial credits | — | Low | Yes |
Discord and Telegram are the easiest to start with. WhatsApp and Teams are enterprise-grade headaches unless you're doing this professionally.
1. Slack Bot with LangChain
Setup
pip install slack-bolt langchain langchain-openai
# slack_bot.py
import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
app = App(token=os.environ["SLACK_BOT_TOKEN"])
# Per-channel memory store
memory_store: dict = {}
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)
def get_chain(channel_id: str) -> ConversationChain:
if channel_id not in memory_store:
memory_store[channel_id] = ConversationBufferMemory()
return ConversationChain(
llm=llm,
memory=memory_store[channel_id],
verbose=False
)
@app.event("app_mention")
def handle_mention(event, say):
channel = event["channel"]
user_text = event["text"].split(">", 1)[-1].strip() # Remove @mention
chain = get_chain(channel)
response = chain.run(user_text)
say(response)
if __name__ == "__main__":
handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
handler.start()
Required Slack App Settings
In your Slack app manifest:
- Event subscriptions:
app_mention,message.channels - OAuth scopes:
app_mentions:read,chat:write,channels:history - Socket Mode: Enable for local development (no public URL needed)
Adding LangChain Tools to Slack
from langchain.agents import initialize_agent, AgentType
from langchain.tools import DuckDuckGoSearchRun, WikipediaQueryRun
search = DuckDuckGoSearchRun()
tools = [search]
def get_agent(channel_id: str):
if channel_id not in memory_store:
memory_store[channel_id] = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
return initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
memory=memory_store[channel_id],
verbose=False
)
@app.event("app_mention")
def handle_mention(event, say):
channel = event["channel"]
user_text = event["text"].split(">", 1)[-1].strip()
agent = get_agent(channel)
response = agent.run(user_text)
say(response)
One thing I found annoying: Slack has a 3-second response timeout for event acknowledgments. If your LangChain chain is slow, Slack will show an error to the user even though the response eventually comes. Fix it by acknowledging immediately and responding asynchronously:
@app.event("app_mention")
def handle_mention(event, say, ack):
ack() # Immediately acknowledge
# Now process (can take longer than 3s)
channel = event["channel"]
user_text = event["text"].split(">", 1)[-1].strip()
response = get_chain(channel).run(user_text)
say(response)
2. Discord Bot with LangChain
Discord is honestly the easiest platform for this. The discord.py library is mature, and the async model fits LangChain's async methods perfectly.
pip install discord.py langchain langchain-openai
# discord_bot.py
import os
import discord
from discord.ext import commands
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationChain
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)
memory_store: dict = {}
def get_chain(user_id: int) -> ConversationChain:
if user_id not in memory_store:
# Window memory keeps last 10 exchanges — prevents context overflow
memory_store[user_id] = ConversationBufferWindowMemory(k=10)
return ConversationChain(llm=llm, memory=memory_store[user_id])
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command(name="ask")
async def ask(ctx, *, question: str):
"""Ask the AI a question: !ask <your question>"""
async with ctx.typing(): # Shows "Bot is typing..."
chain = get_chain(ctx.author.id)
response = await chain.arun(question)
await ctx.reply(response)
@bot.command(name="reset")
async def reset(ctx):
"""Reset conversation memory"""
memory_store.pop(ctx.author.id, None)
await ctx.reply("Memory cleared.")
bot.run(os.environ["DISCORD_TOKEN"])
Slash Commands (Modern Discord Style)
@bot.tree.command(name="chat", description="Chat with the AI")
async def chat_command(interaction: discord.Interaction, message: str):
await interaction.response.defer() # Acknowledge within 3 seconds
chain = get_chain(interaction.user.id)
response = await chain.arun(message)
await interaction.followup.send(response)
# Sync commands on startup
@bot.event
async def on_ready():
await bot.tree.sync()
print(f"Synced slash commands. Logged in as {bot.user}")
For guild setup you'll need to enable Message Content Intent in the Discord Developer Portal under Bot → Privileged Gateway Intents.
3. WhatsApp Bot via Twilio
WhatsApp is more complex because there's no direct free API. Twilio is the most common path, and their WhatsApp sandbox is free for testing.
pip install twilio flask langchain langchain-openai
# whatsapp_bot.py
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
app = Flask(__name__)
llm = ChatOpenAI(model="gpt-4o-mini")
memory_store: dict = {}
def get_chain(phone_number: str) -> ConversationChain:
if phone_number not in memory_store:
memory_store[phone_number] = ConversationBufferMemory()
return ConversationChain(llm=llm, memory=memory_store[phone_number])
@app.route("/whatsapp", methods=["POST"])
def whatsapp_webhook():
incoming_msg = request.values.get("Body", "").strip()
sender = request.values.get("From", "") # e.g., "whatsapp:+1234567890"
chain = get_chain(sender)
response_text = chain.run(incoming_msg)
resp = MessagingResponse()
resp.message(response_text)
return str(resp)
if __name__ == "__main__":
app.run(port=5000)
Point your Twilio sandbox webhook to your public URL (use ngrok for local dev): https://your-domain.com/whatsapp
The real limitation here: WhatsApp has a 24-hour messaging window. If the user doesn't message within 24 hours, you can't proactively message them without a pre-approved template. Keep this in mind for any notification use case.
4. Telegram Bot with LangChain
Telegram is the smoothest experience. No approval process, instant setup, generous free tier.
pip install python-telegram-bot langchain langchain-openai
# telegram_bot.py
import os
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
llm = ChatOpenAI(model="gpt-4o-mini")
memory_store: dict = {}
def get_chain(chat_id: int) -> ConversationChain:
if chat_id not in memory_store:
memory_store[chat_id] = ConversationBufferMemory()
return ConversationChain(llm=llm, memory=memory_store[chat_id])
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
user_text = update.message.text
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
chain = get_chain(chat_id)
response = await chain.arun(user_text)
await update.message.reply_text(response)
def main():
app = Application.builder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
if __name__ == "__main__":
main()
Get your bot token from @BotFather — takes about 30 seconds.
5. Microsoft Teams via Bot Framework
Teams is enterprise-grade and honestly overkill for personal projects. But if you're building for an organization, it's worth it.
pip install botbuilder-core botbuilder-integration-aiohttp langchain langchain-openai
The Teams integration requires Azure Bot Service registration and is significantly more complex. The key pattern:
from botbuilder.core import ActivityHandler, TurnContext, MessageFactory
class TeamsLangChainBot(ActivityHandler):
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4o-mini")
self.chains = {}
async def on_message_activity(self, turn_context: TurnContext):
user_id = turn_context.activity.from_property.id
chain = self.get_chain(user_id)
response = await chain.arun(turn_context.activity.text)
await turn_context.send_activity(MessageFactory.text(response))
6. Persistent Memory Across Server Restarts
The in-memory dict approach loses all conversation history when your server restarts. For production, use Redis:
from langchain_community.chat_message_histories import RedisChatMessageHistory
from langchain.memory import ConversationBufferMemory
def get_persistent_memory(session_id: str) -> ConversationBufferMemory:
history = RedisChatMessageHistory(
session_id=session_id,
url=os.environ["REDIS_URL"],
ttl=86400 # 24 hour expiry
)
return ConversationBufferMemory(
chat_memory=history,
return_messages=True
)
This works identically across all platform integrations — just swap out the memory initialization.
7. Multi-User Rate Limiting
When your bot goes live, you'll get bursts of messages. Handle it:
import time
from collections import defaultdict
rate_limits: dict = defaultdict(list)
MAX_MESSAGES = 10
WINDOW_SECONDS = 60
def is_rate_limited(user_id: str) -> bool:
now = time.time()
# Remove old timestamps outside the window
rate_limits[user_id] = [t for t in rate_limits[user_id] if now - t < WINDOW_SECONDS]
if len(rate_limits[user_id]) >= MAX_MESSAGES:
return True
rate_limits[user_id].append(now)
return False
# In your message handler:
if is_rate_limited(str(user_id)):
await send_reply("You're sending messages too fast. Please wait a moment.")
return
Architecture: Which Pattern to Use
Simple hobby project → In-memory dict + synchronous LangChain
Team/production use → Redis memory + async LangChain + rate limiting
Multi-workspace → Database-backed sessions + tenant isolation
Enterprise → Azure Bot Framework + managed identity + audit logging
Check out Build AI chatbot Python for the core chatbot patterns, and LangChain tutorial 2025 for the foundational LangChain concepts these integrations depend on. For agent-powered bots that can take actions, Build AI agent with LangChain covers the LangGraph patterns that work well in async messaging environments.
If you want to understand memory management more deeply — which you will need once users start complaining about the bot "forgetting" things — AI agent memory and planning goes into the architectural tradeoffs.
Conclusion
The LangChain part of messaging integrations is actually the easy part. The hard parts are platform-specific: Slack's 3-second acknowledgment window, WhatsApp's 24-hour messaging restriction, Discord's intent configuration. Each platform has one or two gotchas that aren't in the official docs.
My recommendation: start with Telegram or Discord for personal projects. If you're building for a business that already uses Slack, go with Slack from the start — the integration pays off. Avoid WhatsApp unless you have a clear business requirement, because the setup friction and cost structure are aimed at enterprises.
The three things that matter most across all platforms: use async methods, persist memory externally (Redis), and implement rate limiting before you think you need it.
Want to go deeper on the agent side of these bots? Read our guide on AI agents explained to understand how to build bots that do more than just answer questions.
Frequently Asked Questions
Can a LangChain bot handle multiple conversations at once on Slack?
Yes, but you need async execution. Use slack-bolt's async version (from slack_bolt.async_app import AsyncApp) and LangChain's arun()/ainvoke() methods. Each incoming event is processed in its own coroutine, so multiple users can interact simultaneously without blocking each other.
How do I keep the bot's conversation context between Discord server restarts?
Replace the in-memory dict with Redis-backed storage using RedisChatMessageHistory from langchain_community. Set a TTL (time-to-live) on each key so stale conversations expire automatically. This also lets you scale horizontally — multiple bot instances share the same Redis store.
What's the cheapest way to deploy a LangChain Telegram bot? A small VPS ($5–6/month from DigitalOcean or Hetzner) running the bot process with supervisor or systemd is perfectly adequate for personal projects. Railway.app and Fly.io both have generous free tiers if you want zero-cost hosting. The main cost is LLM API calls, not infrastructure.
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
Related Articles
5 AutoGen Agent Roles (Assistant, UserProxy, CodeExecutor)
Understand the 5 core AutoGen agent types — AssistantAgent, UserProxyAgent, CodeExecutorAgent, and more — with code examples and a comparison table for each role.
How to Deploy AutoGen Agents as APIs with FastAPI (2026)
Learn to serve AutoGen multi-agent systems as production REST APIs using FastAPI with async endpoints and real-time streaming responses.
How to Use AutoGen with Azure OpenAI (Enterprise Security)
Connect Microsoft AutoGen to Azure OpenAI for enterprise-grade AI agents. Step-by-step setup with private endpoints, OAI_CONFIG_LIST, and deployment config.
Build a Code Debugging Agent with AutoGen (Auto-Fix PRs)
Build an AutoGen agent that reviews code, analyzes PR diffs, suggests fixes, and automates code quality improvements with a full working implementation.