Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/tolom/df-slack-py

Slack bot integrating Dialogflow CX natural language processing with client API system, featuring secure OAuth and Firebase token management
https://github.com/tolom/df-slack-py

chatbot dialogflow-cx firebase oauth2 openapi python slack-api slack-bot

Last synced: 3 days ago
JSON representation

Slack bot integrating Dialogflow CX natural language processing with client API system, featuring secure OAuth and Firebase token management

Awesome Lists containing this project

README

        

# Dialogflow CX Slack Bot

A powerful Slack bot that integrates Dialogflow CX for natural language processing with client's API. Features GPT for enhanced text processing and secure token management through Firebase.

## Overview

This bot allows users to:
- Install the bot in their Slack workspace
- Authenticate with the client's system
- Interact with resources through natural language
- Receive real-time notifications
- Execute API commands through chat

## Requirements

- Python 3.8+
- pip (Python package manager)
- Slack account
- Firebase/Dialogflow CX project
- OpenAI account (for GPT access)

## Installation

1. Clone the repository:
```bash
git clone
cd
```

2. Create and activate virtual environment:
```bash
python -m venv venv
source venv/bin/activate # for Linux/Mac
# or
.\venv\Scripts\activate # for Windows
```

3. Install dependencies:
```bash
pip install -r requirements.txt
```

4. Set up environment variables:
`.env`

## Configuration

### 1. OpenAI API Setup

1. Create an account at [OpenAI Platform](https://platform.openai.com)
2. Get an API key with GPT access
3. Add the key to `.env`:
```
OPENAI_API_KEY=your-api-key
```

Used models:
- GPT-4o (`gpt-4o`) for text generation
- Text Embeddings 3 Large (`text-embedding-3-large`) for embeddings

### 2. Slack App Configuration

1. Create a new app at [api.slack.com](https://api.slack.com/apps)
2. Under "OAuth & Permissions", add these scopes:
- `app_mentions:read`
- `chat:write`
- `im:history`
- `im:read`
- `im:write`
3. Set OAuth Redirect URL: `https://your-domain.com/slack/oauth/callback`
4. Get and save:
- Bot User OAuth Token (`SLACK_BOT_TOKEN`)
- App-Level Token (`SLACK_APP_TOKEN`)
- Signing Secret (`SLACK_SIGNING_SECRET`)
- Client ID (`SLACK_CLIENT_ID`)
- Client Secret (`SLACK_CLIENT_SECRET`)

### 3. Dialogflow CX Setup

1. Create a project in [Google Cloud Console](https://console.cloud.google.com)
2. Enable Dialogflow CX API
3. Create an agent in [Dialogflow CX Console](https://dialogflow.cloud.google.com/cx)
4. Get and save:
- Project ID (`DIALOGFLOW_PROJECT_ID`)
- Location (`DIALOGFLOW_LOCATION`)
- Agent ID (`DIALOGFLOW_AGENT_ID`)
5. Create a service account and download JSON key
6. Rename the key to `firebase-credentials.json`

### 4. Client API Integration

1. Get the client's OpenAPI specification
2. Save it as `openapi-spec.yaml`
3. Get authentication URL (`CLIENT_AUTH_URL`)
4. Get base API URL (`CLIENT_API_URL`)

## Usage

### Bot Installation

1. Users visit: `https://your-domain.com/slack/install`
2. Select their Slack workspace
3. Grant required permissions
4. Authenticate with the client's system

### Command Examples

1. Mention bot in channel:
```
@bot_name show resource 12345
```

Response:
```
Here's what I found:

ID: 12345
Name: Example Resource
Status: Active

API Response:
{
"id": 12345,
"name": "Example Resource",
"status": "active",
"created_at": "2024-01-21T12:00:00Z"
}
```

2. Direct message to bot:
```
create resource named "Test Resource"
```

Response:
```
Resource created successfully:

ID: 67890
Name: Test Resource
Status: Pending

API Response:
{
"id": 67890,
"name": "Test Resource",
"status": "pending",
"created_at": "2024-01-21T15:30:00Z"
}
```

### Webhook Integration

Send notifications via webhook:
```bash
curl -X POST https://your-domain.com/webhook/notify \
-H "Content-Type: application/json" \
-H "X-Webhook-Secret: your-webhook-secret" \
-d '{
"title": "New Notification",
"message": "Resource #12345 updated",
"channel": "#notifications"
}'
```

## Project Structure

```
.
├── src/
│ ├── app.py # Main application file
│ ├── config/ # Configurations
│ │ └── database.py # Database configuration
│ ├── models/ # Data models
│ │ └── user_mapping.py # User mapping model
│ ├── routes/ # API routes
│ │ ├── auth.py # Authentication
│ │ ├── slack.py # Slack events
│ │ ├── slack_oauth.py # Slack OAuth
│ │ └── webhook.py # Webhooks
│ └── services/ # Services
│ ├── dialogflow_service.py # Dialogflow CX integration
│ ├── client_api_service.py # Client API integration
│ └── slack_service.py # Slack service
├── .env # Environment variables
├── .gitignore # Git ignore rules
├── firebase-credentials.json # Firebase credentials
├── openapi-spec.yaml # Client API OpenAPI spec
├── requirements.txt # Python dependencies
└── README.md # Documentation
```

## Development

### Adding New Commands

1. Create a new intent in Dialogflow CX
2. Add training phrases and parameters
3. Configure fulfillment in `dialogflow_webhook.py`:
```python
api_mapping = {
'your_intent_name': {
'path': '/api/endpoint',
'method': 'POST',
'body': {
'param1': params.get('param1'),
'param2': params.get('param2')
}
}
}
```

### Testing

Run tests:
```bash
pytest tests/
```

## Security Features

- Token storage in Firebase
- OAuth 2.0 implementation
- Slack signature verification
- OpenAPI spec validation
- Secure environment variable handling
- Request validation and sanitization

## Error Handling

The bot implements comprehensive error handling:
1. API request validation
2. Token verification
3. Request signature verification
4. Rate limiting
5. Timeout handling
6. Error logging and monitoring

## Monitoring and Logging

- Request/response logging
- Error tracking
- Performance metrics
- User interaction analytics
- System health monitoring

## Troubleshooting

If you encounter issues:
1. Check application logs
2. Verify environment variables
3. Check token permissions
4. Create an issue in the repository

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request

## License

MIT

## Support

For support:
1. Check the documentation
2. Review error logs
3. Contact system administrators
4. Create an issue in the repository

## Installation for Users

1. Visit the bot installation link: `https://your-domain.com/slack/install`
2. Authorize the bot in your Slack workspace
3. You will be redirected to the client application authentication page
4. Log in to your client application account
5. After successful authentication, the bot will be ready to use in your Slack workspace

## Environment Variables

```env
# Slack Configuration
SLACK_SIGNING_SECRET=your_signing_secret
SLACK_CLIENT_ID=your_client_id
SLACK_CLIENT_SECRET=your_client_secret
SLACK_APP_TOKEN=your_app_token

# Client App Configuration
CLIENT_AUTH_URL=https://client-app.com/auth

# Firebase Configuration
FIREBASE_CREDENTIALS=path/to/credentials.json

# Dialogflow Configuration
DIALOGFLOW_PROJECT_ID=your_project_id
```

## Architecture

See [ARCHITECTURE.md](ARCHITECTURE.md) for detailed information about the system architecture.

## Development

1. Install dependencies:
```bash
pip install -r requirements.txt
```

2. Start the server:
```bash
python src/app.py
```

## Testing

```bash
pytest tests/
```