]> git.aero2k.de Git - urlbot-v3.git/commitdiff
add some intelligence
authorThorsten S <mail@aero2k.de>
Wed, 8 Mar 2023 08:55:59 +0000 (09:55 +0100)
committerThorsten S <mail@aero2k.de>
Wed, 8 Mar 2023 08:55:59 +0000 (09:55 +0100)
distbot/plugins/fun.py
distbot/plugins/openai.py [new file with mode: 0644]

index cf1403b3cbec7374972375addb5243e1c22ee7a5..94e0df8578b33d87e5bd6ba1c33256280241ce2f 100644 (file)
@@ -9,6 +9,7 @@ from distbot.common.action import Action
 from distbot.common.config import conf_get
 from distbot.common.message import get_nick_from_message, get_words
 from distbot.common.utils import giphy
+from distbot.plugins.openai import ask_chatgpt, get_openai_session
 
 logger = logging.getLogger(__name__)
 
@@ -163,7 +164,17 @@ class Selfreaction(Worker):
 
     def parse_body(self, msg):
         sender = get_nick_from_message(msg)
-        if sender in conf_get("meanies"):
+
+        try:
+            api_key = conf_get("openai_api_key")
+            session = get_openai_session(api_key)
+            response = ask_chatgpt(msg["body"], session)
+            return Action(msg='{}: {}'.format(sender, response))
+        except:
+            pass
+
+        meanies = conf_get("meanies") or []
+        if sender in meanies:
             replys = self.insults
         else:
             replys = self.me_replies
diff --git a/distbot/plugins/openai.py b/distbot/plugins/openai.py
new file mode 100644 (file)
index 0000000..7c5311b
--- /dev/null
@@ -0,0 +1,57 @@
+import requests
+import hashlib
+import os
+import json
+
+
+API_URL = "https://api.openai.com/v1/chat/completions"
+
+
+def get_openai_session(api_key=None):
+    session = requests.session()
+    if not api_key:
+        api_key = os.environ.get("OPENAI_API_KEY")
+    if not api_key:
+        raise RuntimeError("no OPENAI_API_KEY set")
+    session.headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
+    return session
+
+def hash_user(username):
+    username = username or "anonymous"
+    hashed_val = hashlib.sha256()
+    hashed_val.update(username.encode("utf-8"))
+    return hashed_val.hexdigest()
+
+
+def ask_chatgpt(line, session=None, sender=None):
+    session = session if session else get_openai_session()
+    req = {
+        "model": "gpt-3.5-turbo",
+        "messages": [
+            {"role": "system", "content": "You are a sassy little chat bot with low intent to help, but to humor. Your name is urlbug. Respond in the language being talked to. Avoid multiple lines in your response."},
+            {"role": "user", "content": line}
+        ],
+        "max_api_keys": 150,
+        "user": hash_user(sender)
+    }
+    resp = session.post(API_URL, json=req)
+    resp.raise_for_status()
+    response = resp.json()
+    cost = response["usage"]["total_tokens"]
+    # TODO dump cost somewhere
+    print(json.dumps(response, indent=2))
+    message = response["choices"][0]
+    stop_reason = message["finish_reason"]
+    if stop_reason == "content_filter":
+        print("warning: redacted, you're getting on the naughty list soon.")
+    return message["message"]["content"]
+
+
+def main():
+    line = "/me glaubt, urlbug hat wieder zuviel Maschinenöl geschnüffelt"
+    print(ask_in_chat(line))
+
+
+if __name__ == "__main__":
+    main()
+