Skip to content

Commit

Permalink
Merge pull request #70 from OWASP-BLT/revert-66-Chat_bot
Browse files Browse the repository at this point in the history
  • Loading branch information
DonnieBLT authored Jul 29, 2024
2 parents a468f13 + 7b8db76 commit 5f82096
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 162 deletions.
77 changes: 8 additions & 69 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
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 @@ -30,17 +27,6 @@
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 @@ -140,6 +126,7 @@ 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 @@ -153,61 +140,13 @@ 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":
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

user = message["user"] # The user ID of the person who sent the message
text = message.get("text", "") # The text of the message
try:
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}")
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:
logging.error(f"Error sending message to Slack: {e.response['error']}")
print(f"Error sending response: {e.response['error']}")
117 changes: 26 additions & 91 deletions poetry.lock

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

2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ 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 5f82096

Please sign in to comment.