Skip to content

Commit

Permalink
feat: Implement OAuth and enhance message handling for Slack bot
Browse files Browse the repository at this point in the history
  • Loading branch information
AbdullahSuri committed Oct 20, 2024
1 parent f0bb3cd commit 75e7bdb
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 0 deletions.
Binary file added SlackChatbot/.DS_Store
Binary file not shown.
3 changes: 3 additions & 0 deletions SlackChatbot/ClientID_Secret.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CLIENT_ID = '7855184757495.7892528086800'
CLIENT_SECRET = '918fec90decd47b23d25fe58e02a73e1'
BOT_TOKEN='xoxb-7855184757495-7855216149575-kPNmwbhC4mlAyVyUT7QXWpkJ'
3 changes: 3 additions & 0 deletions SlackChatbot/Commands
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Activate virtual env : source venv/bin/activate
Start server : python3 slack_oauth.py
Check if server is running by going to this URL http://127.0.0.1:3000/
35 changes: 35 additions & 0 deletions SlackChatbot/slack_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from flask import Flask, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token='xoxb-7855184757495-7855216149575-kPNmwbhC4mlAyVyUT7QXWpkJ')

def send_message(channel, message):
try:
response = client.chat_postMessage(channel=channel, text=message)
print("Message sent successfully:", response["message"]["text"])
except SlackApiError as e:
print("Error sending message:", e.response["error"])

app = Flask(__name__)

@app.route('/slack/events', methods=['POST'])
def slack_events():
data = request.json
if 'challenge' in data:
return jsonify({'challenge': data['challenge']})
elif 'event' in data:
event = data['event']
if event['type'] == 'message' and 'subtype' not in event:
# Check the message text and respond appropriately
user_message = event['text'].lower()
if "hello" in user_message:
send_message(event['channel'], "Hello there! How can I help you?")
elif "help" in user_message:
send_message(event['channel'], "Here's a list of commands you can use...")
else:
send_message(event['channel'], "I'm not sure how to respond to that.")
return jsonify({'status': 'ok'})

if __name__ == '__main__':
app.run(port=3000, debug=True)
21 changes: 21 additions & 0 deletions SlackChatbot/slack_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/slack/events', methods=['POST'])
def slack_events():
data = request.json
# Slack sends a challenge parameter when verifying the request URL
if 'challenge' in data:
return jsonify({'challenge': data['challenge']})
# Your logic for other events
elif 'event' in data:
event = data['event']
if event['type'] == 'message' and 'subtype' not in event:
# Logic to handle incoming messages
# Respond to messages or other interactions here
pass
return jsonify({'status': 'ok'})

if __name__ == '__main__':
app.run(port=3000, debug=True)
48 changes: 48 additions & 0 deletions SlackChatbot/slack_oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from flask import Flask, request, redirect, url_for
import requests
import os

app = Flask(__name__)

# Load credentials from environment variables
CLIENT_ID = '7855184757495.7892528086800'
CLIENT_SECRET = '918fec90decd47b23d25fe58e02a73e1'

@app.route('/')
def home():
return "Welcome to the Slack OAuth Handler! Ready to authenticate."

@app.route('/oauth/callback')
def oauth_callback():
# Retrieve the code from the query string
code = request.args.get('code')
if not code:
return 'Error: Missing authorization code.', 400

# Prepare the request data for exchanging the code for a token
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'code': code
}

# Make a POST request to Slack's OAuth API to exchange the code for an access token
response = requests.post('https://slack.com/api/oauth.v2.access', data=data)

# Check if the request was successful
response_json = response.json()
if response.status_code == 200 and response_json.get('ok'):
# Extract the token from the response
token = response_json.get('access_token')
# Log or store the token securely (e.g., in a database)
return redirect(url_for('success'))
else:
error_message = response_json.get('error', 'Unknown error')
return f"Failed to retrieve access token: {error_message}", 400

@app.route('/success')
def success():
return "OAuth flow completed successfully!"

if __name__ == '__main__':
app.run(port=3000, debug=True)

0 comments on commit 75e7bdb

Please sign in to comment.