From 2df7e18916ca4b8cac48cc5eb68a683fceecfd28 Mon Sep 17 00:00:00 2001 From: Joao Figueiredo Date: Thu, 1 May 2025 00:47:41 +0100 Subject: [PATCH] OPenAI initial setup --- .env.example | 4 +++- main.py | 38 ++++++++++++++++++++++++++++++++++++++ requirements.txt | 3 ++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index 12d6506..7280ffe 100644 --- a/.env.example +++ b/.env.example @@ -5,4 +5,6 @@ LOG_LEVEL=INFO HOMESERVER_URL = "https://matrix.org" USER_ID = "@botbot_user:matrix.org" PASSWORD = "botbot_password" -LOG_LEVEL=INFO + +# OpenAI API Key +OPENAI_API_KEY=your_openai_api_key_here diff --git a/main.py b/main.py index 7259a8f..2d0b637 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,7 @@ import os import asyncio import logging +import openai from dotenv import load_dotenv from nio import AsyncClient, AsyncClientConfig, MatrixRoom, RoomMessageText, InviteMemberEvent from nio.responses import LoginResponse @@ -11,6 +12,11 @@ HOMESERVER_URL = os.getenv("HOMESERVER_URL") USER_ID = os.getenv("USER_ID") PASSWORD = os.getenv("PASSWORD") LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper() +OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") + +if not OPENAI_API_KEY: + raise RuntimeError("OPENAI_API_KEY is not set in environment") +openai.api_key = OPENAI_API_KEY # --- Logging Setup --- # Convert string level to numeric @@ -39,6 +45,38 @@ async def message_callback(room: MatrixRoom, event: RoomMessageText): content={"msgtype": "m.text", "body": "Pong!"} ) logger.info("Replied with Pong! to %s", event.sender) + elif body.startswith("!ask"): + question = body[5:].strip() + if not question: + await client.room_send( + room_id=room.room_id, + message_type="m.room.message", + content={"msgtype": "m.text", "body": "Please provide a question after !ask."} + ) + return + + # Call OpenAI API + logger.info("Asking OpenAI: %s", question) + try: + response = openai.ChatCompletion.create( + model="gpt-3.5-turbo", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": question}, + ], + max_tokens=150 + ) + answer = response.choices[0].message.content.strip() + except Exception as e: + logger.error("OpenAI API error: %s", e) + answer = "Sorry, I encountered an error while contacting the AI service." + + await client.room_send( + room_id=room.room_id, + message_type="m.room.message", + content={"msgtype": "m.text", "body": answer} + ) + logger.info("Replied to %s with OpenAI response", event.sender) elif body== "hello botbot": await client.room_send( room_id=room.room_id, diff --git a/requirements.txt b/requirements.txt index 3dae8f6..b634f8a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ matrix-nio[e2e]>=0.25.0 -python-dotenv>=1.0.0 \ No newline at end of file +python-dotenv>=1.0.0 +openai \ No newline at end of file