Skip to content

Commit

Permalink
Merge pull request OWASP-BLT#66 from Sarthak5598/Chat_bot
Browse files Browse the repository at this point in the history
added the chatbot
  • Loading branch information
Sarthak5598 authored Jul 4, 2024
2 parents 1a8422f + b90b286 commit a468f13
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 34 deletions.
77 changes: 69 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import logging
import os
from datetime import datetime, timezone
from pathlib import Path

import git
from cachetools import TTLCache
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from openai import OpenAI
from slack import WebClient
from slack_sdk.errors import SlackApiError
from slackeventsapi import SlackEventAdapter
Expand All @@ -27,6 +30,17 @@
client = WebClient(token=os.environ["SLACK_TOKEN"])
client.chat_postMessage(channel=DEPLOYS_CHANNEL_NAME, text="bot started v1.9 240611-1 top")

template = """
You're a Software Engineer (Mentor) at OWASP,
Your job is to provide help to contributors with a short message.
Contributor' Question :{Doubt}
"""


openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

cache = TTLCache(maxsize=100, ttl=86400)


@app.route("/slack/events", methods=["POST"])
def slack_events():
Expand Down Expand Up @@ -126,7 +140,6 @@ def handle_message(payload):
):
user = message.get("user")
channel = message.get("channel")
logging.info(f"detected contribute sending to channel: {channel}")
response = client.chat_postMessage(
channel=channel,
text=(
Expand All @@ -140,13 +153,61 @@ def handle_message(payload):
text=f"Error sending message: {response['error']}",
)
logging.error(f"Error sending message: {response['error']}")
# if message.get("channel_type") == "im":
# user = message["user"] # The user ID of the person who sent the message
# text = message.get("text", "") # The text of the message
# try:
# if message.get("user") != bot_user_id:
# client.chat_postMessage(channel=JOINS_CHANNEL_ID, text=f"<@{user}> said {text}")
# # Respond to the direct message
# client.chat_postMessage(channel=user, text=f"Hello <@{user}>, you said: {text}")
# except SlackApiError as e:
# print(f"Error sending response: {e.response['error']}")


@slack_events_adapter.on("message")
def gpt_bot(payload):
token_limit = 1000
token_per_prompt = 100
user = "D078YQ93TSL"
message = payload.get("event", {})

if message.get("channel_type") == "im":
user = message["user"] # The user ID of the person who sent the message
text = message.get("text", "") # The text of the message
doubt = message.get("text", "")
prompt = template.format(doubt=doubt)

today = datetime.now(timezone.utc).date()
rate_limit_key = f"global_daily_request_{today}"
total_token_used = cache.get(rate_limit_key, 0)
doubt_limit = 50
if len(doubt) >= doubt_limit:
client.chat_postMessage(channel=user, text="Please enter less than 50 characters")
return

if total_token_used + token_per_prompt > token_limit:
client.chat_postMessage(channel=user, text="Exceeds Token Limit")
return

try:
response = openai_client.Completion.create(
messages=[{"role": "user", "content": prompt}],
model="gpt-3.5-turbo-0125",
max_tokens=20,
)
answer = response.choices[0].message.content
except Exception as e:
logging.error(f"OpenAI API request failed: {e}")
client.chat_postMessage(
channel=user, text="An error occurred while processing your request."
)
return

try:
if message.get("user") != bot_user_id:
client.chat_postMessage(channel=JOINS_CHANNEL_ID, text=f"<@{user}> said {text}")
# Respond to the direct message
client.chat_postMessage(channel=user, text=f"Hello <@{user}>, you said: {text}")
client.chat_postMessage(channel=user, text=f"{answer}")
cache[rate_limit_key] = total_token_used + token_per_prompt

# Log the user's question and GPT's answer
logging.info(f"User's Question: {doubt}")
logging.info(f"GPT's Answer: {answer}")
except SlackApiError as e:
print(f"Error sending response: {e.response['error']}")
logging.error(f"Error sending message to Slack: {e.response['error']}")
117 changes: 91 additions & 26 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ gitpython = "^3.1.43"
slack-machine = { git = "https://github.com/Owasp-blt/slack-machine" }
slackeventsapi = "^3.0.1"
slack-sdk = "^3.27.2"
openai = "^1.35.7"
cachetools = "^5.3.3"

[tool.poetry.group.dev.dependencies]
pytest = "^8.2.2"
Expand Down

0 comments on commit a468f13

Please sign in to comment.