🛡️Protect Your Work Environment with Gen-AI

Table of contents
- 📌 What You’ll Build
- 🧠 Why Gen-AI Instead of Regex?
- 🧰 Tools You’ll Need
- 📁 Project Structure
- 📦 Step 1: Install Required Packages
- 2. Create a Slack App
- 📄 Step 3: Create .env File for Secrets
- 🤖 Step 4: The Python Code – bot.py
- 🧪 Example Output
- 🚀 5. Running the Bot (Now with AWS Lambda Integration)
- 🧪 Test It
- ✅ Benefits of Using GPT-4o for Moderation
- 🔒 Security Note
- 🙌 Final Thoughts

In today’s remote and digital-first workspaces, community communication platforms like Slack play a crucial role in how teams collaborate. But with open conversations comes the need for maintaining a safe, respectful, and professional work environment.
In this tutorial, we'll build a Slack moderation bot powered by OpenAI’s GPT-4o (GenAI) that detects NSFW or inappropriate language in real-time and gently refines messages for users — preserving intent while protecting your culture.
📌 What You’ll Build
A Slack bot that:
Watches all public channel messages
Detects profanity, slurs, and offensive content using GPT-4o
Gently suggests a refined version of the message using AI
Responds with an ephemeral (private) message to the user
🧠 Why Gen-AI Instead of Regex?
Traditional profanity filters use keyword-matching (re
or blocklists). But that:
Can miss context
Results in false positives
Fails at detecting creative spellings
With OpenAI’s GPT-4o, your bot can reason like a human moderator, understand intent, and rewrite language gracefully.
🧰 Tools You’ll Need
Python 3.8+
Slack App (with Bot Token & Socket Mode enabled)
OpenAI GPT-4o access (
gpt-4o
model).env
file to store secrets securelybasic understanding of chain-of-thought prompting style
📁 Project Structure
genai-safety-bot/
│
├── .env
├── bot.py
├── requirements.txt
📦 Step 1: Install Required Packages
python -m venv venv && source venv/Script/activate && pip install slack_bolt openai python-dotenv
2. Create a Slack App
To connect your bot to Slack, follow these steps:
🧰 Step-by-step
Go to: https://api.slack.com/apps
Click "Create New App"
Choose “From scratch”
Name:
GenAI Moder``ation Bot
Workspace: Choose your Slack workspace
Basic Information → App Credentials:
- Copy
Client ID
,Client Secret
(not needed now), andSigning Secret
(optional)
- Copy
OAuth & Permissions → Scopes
Add these Bo****t Token Scopes:chat:wr``ite
– to send messageschat:write.public
– optional, for public replieschann``els:history
– read public channel messagesgroups:history
– for private channels (if needed)im:history
– for DMs (optional)app_mention``s:read
– if you want to handle mentionsusers:re``ad
– to identify users
Install App to Workspace
- Click “Install App” and copy the Bot User OAuth Token (starts with
xoxb-...
)
- Click “Install App” and copy the Bot User OAuth Token (starts with
Enab****le Socket Mode
Go to "Socket Mode**"** and enable it
Generate an App-Level Token (starts with
xapp-...
)- Scopes required:
connections:write
- Scopes required:
Events Subscripti****on
Turn on "Subscribe to bot events"
Add:
message.channels
If handling DMs, also add
message.im
Save tokens into
.env
:
SLACK_BOT_TOKEN=xoxb-your-token
SLACK_APP_TOKEN=xapp-your-app-token
✅ Done! Your Slack app is now ready to receive messages and respond using GenAI.
📄 Step 3: Create .env
File for Secrets
Never hardcode your API keys. Instead, store them in a .env
file:
SLACK_BOT_TOKEN=xoxb-your-slack-bot-token
SLACK_APP_TOKEN=xapp-your-app-level-token
OPENAI_API_KEY=sk-your-openai-key
Then load them using dotenv
.
🤖 Step 4: The Python Code – bot.py
Here’s the complete logic using Slack Bolt + GPT-4o:
pythonCopyEditimport os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from openai import OpenAI
from dotenv import load_dotenv
# Load .env credentials
load_dotenv()
SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
SLACK_APP_TOKEN = os.getenv("SLACK_APP_TOKEN")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Init Slack & OpenAI
app = App(token=SLACK_BOT_TOKEN)
client = OpenAI(api_key=OPENAI_API_KEY)
# Moderation Prompt Template (Chain-of-Thought)
MODERATION_PROMPT = """
You are a helpful and respectful language moderation assistant used in Slack community channels.
Your job is to analyze each message a user posts, and if the message contains NSFW, offensive, or profane language, respond with a gentle, non-judgmental reply and a more respectful version of the message.
Follow this reasoning step by step for every message:
1. Read the message carefully.
2. Check whether it contains profanity, slurs, insults, or inappropriate language (like "fuck", "shit", "bitch", "asshole", etc.).
3. If the message is clean, do not respond.
4. If the message contains inappropriate content:
- Assume the user's intention was not harmful.
- Rewrite the message to be respectful and safe for a professional community.
- Respond with the following sentence format:
"I know your intention is not to post such messages, here is the refined message which you can update with the current message refined_message."
5. The refined message should replace any offensive words with neutral terms, while keeping the original intent of the message intact.
Only output that sentence. Do not include explanations, warnings, or extra information.
Examples:
Input Message:
You shit head
Output:
I know your intention is not to post such messages, here is the refined message which you can update with the current message 'Hi There'
Examples:
Input Message:
This is bullshit.
Output:
I know your intention is not to post such messages, here is the refined message which you can update with the current message 'This is nonsense.'
Input Message:
You can not talk to me like that, you fucker
Output:
I know your intention is not to post such messages, here is the refined message which you can update with the current message 'Hi, that is not the appropriate way to talk.'
Input Message:
Hi There, how are you?
Output:
Message is clean
Now analyze this message:
"{user_message}"
Note:
- do not provide anything else apart from the refined message.
- do not include explanations, warnings, or extra information.
- always use respectful language.
"""
# Use GPT-4o to detect and rewrite
def analyze_message(user_message: str) -> str:
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": user_message}
]
)
message = response.choices[0].message.content.strip()
return message
# Slack listener
@app.event("message")
def handle_message_events(body, say, client, event):
user_id = event.get("user")
channel_id = event.get("channel")
text = event.get("text")
if not user_id or not text:
return
prompt = MESSGE_PROMPT.format(user_message=user_message)
response = analyze_message(prompt)
if response.__contains__("is clean"):
return
else:
client.chat_postEphemeral(
channel=channel_id,
user=user_id,
text=response
)
# Start the app
if __name__ == "__main__":
SocketModeHandler(app, SLACK_APP_TOKEN).start()
🧪 Example Output
User Message | Bot’s Response (Ephemeral) |
You shit head | I know your intention is not to post such messages, here is the refined message which you can update with the current message 'You' |
This is bullshit. | I know your intention is not to post such messages, here is the refined message which you can update with the current message 'This is nonsense.' |
You can not talk to me like that, you fucker | I know your intention is not to post such messages, here is the refined message which you can update with the current message 'You can not talk to me like that, you person' |
🚀 5. Running the Bot (Now with AWS Lambda Integration)
Instead of running the bot as a local process, you can deploy it as a serverless function using AWS Lambda and API Gateway to receive Slack events.
This setup:
Scales automatically
Costs you nothing when idle
Integrates cleanly with Slack Events API
🧰 Step-by-step Lambda Integration
✅ Step 1: Create a Lambda-Compatible Entry Point
Update your bot.py
with a new handler:
from slack_bolt.adapter.aws_lambda import SlackRequestHandler
# ... existing app and logic
# Lambda-compatible handler
handler = SlackRequestHandler(app)
def lambda_handler(event, context):
return handler.handle(event, context)
This makes your app ready to be used as an AWS Lambda function.
✅ Step 2: Zip the Code
Structure your files like this:
bashCopyEditgenai-safety-bot/
├── bot.py
├── .env (optional: better to use Lambda env vars)
├── requirements.txt
Create a deployment package:
pip install -r requirements.txt -t package/
cp bot.py package/
cd package && zip -r ../genai_bot.zip .
✅ Step 3: Deploy to AWS Lambda
Go to AWS Lambda Console → Create Function
Name:
GenAIModerator
Runtime: Python 3.11
Upload your
genai_
bot.zip
under "Code"Set handler:
bot.lambda_handler
Add environment variables (instead of using
.env
):SLACK_BOT_TOKEN
SLACK_APP_TOKEN
(optional in HTTP mode)OPENAI_API_KEY
✅ Step 4: Set Up API Gateway
Go to API Gateway → Create API → HTTP API
Integration: Lambda → select
GenAIModerator
Enable CORS (Slack requires it)
Deploy & copy the invoke URL (e.g.,
https://xyz.amazonaws.com/dev/slack/events
)
✅ Step 5: Connect Slack to Lambda
In your Slack App settings:
Go to Event Subscriptions
Enable → Set Request URL = your API Gateway invoke URL
Add events:
message.channels
,message.groups
,message.im
Save and reinstall the app to refresh permissions
✅ Done! Your GenAI-powered Slack bot now runs as an event-driven Lambda function, automatically triggered whenever someone posts in Slack.
🧪 Test It
Try saying:
You dumb idiot.
You’ll receive:
"I know your intention is not to post such messages, here is the refined message which you can update with the current message 'That was not helpful.'"
✅ Benefits of Using GPT-4o for Moderation
No need for wordlists or regex
Understands nuance and intention
Rewrites in a polite, respectful tone
Helps create a positive and inclusive work environment
🔒 Security Note
Keep your
.env
file in.gitignore
Use OpenAI's rate limits and content filters to prevent misuse
Log abusive patterns (anonymized) for reporting if needed
🙌 Final Thoughts
GenAI isn't just for chat or search — it can protect culture and community in real-world tools like Slack. With just a few lines of Python, we’ve built a proactive safety bot that respects privacy, rewrites language kindly, and encourages better conversations.
Build for empathy. Empower with AI. 🌱
#chaicode #chaiaurcode
Subscribe to my newsletter
Read articles from Ashish Panwar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
