OPenAI initial setup
This commit is contained in:
@@ -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
|
||||
|
||||
38
main.py
38
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,
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
matrix-nio[e2e]>=0.25.0
|
||||
python-dotenv>=1.0.0
|
||||
python-dotenv>=1.0.0
|
||||
openai
|
||||
Reference in New Issue
Block a user