Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
Β·
fdb3a70
1
Parent(s):
b2ef8c6
Refactor prepare_tables function to use psycopg2 for PostgreSQL connection and table creation
Browse files
app.py
CHANGED
@@ -7,6 +7,8 @@ import queue
|
|
7 |
import re
|
8 |
import json
|
9 |
import requests
|
|
|
|
|
10 |
|
11 |
from fastapi import FastAPI, Request, HTTPException
|
12 |
from fastapi.responses import PlainTextResponse, JSONResponse
|
@@ -25,18 +27,21 @@ GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.
|
|
25 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
26 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
27 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
28 |
-
BOT_GROUP_CHAT = os.getenv("BOT_GROUP_CHAT")
|
29 |
IMAGE_DIR = "/tmp/images"
|
30 |
AUDIO_DIR = "/tmp/audio"
|
31 |
|
32 |
-
# Supabase
|
33 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
34 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
35 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
36 |
|
|
|
|
|
|
|
37 |
if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE,
|
38 |
WEBHOOK_AUTH_TOKEN, BOT_GROUP_CHAT,
|
39 |
-
SUPABASE_URL, SUPABASE_KEY]):
|
40 |
raise ValueError("One or more environment variables are not set properly")
|
41 |
|
42 |
# Queues & stores
|
@@ -47,20 +52,30 @@ last_message_time = time.time()
|
|
47 |
|
48 |
app = FastAPI()
|
49 |
|
50 |
-
# βββββ
|
51 |
def prepare_tables():
|
52 |
"""
|
53 |
-
|
54 |
-
Uses postgrest.raw() to execute raw SQL.
|
55 |
"""
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
CREATE TABLE IF NOT EXISTS users (
|
58 |
id SERIAL PRIMARY KEY,
|
59 |
chat_id TEXT UNIQUE NOT NULL,
|
60 |
created_at BIGINT NOT NULL
|
61 |
);
|
62 |
-
"""
|
63 |
-
|
64 |
CREATE TABLE IF NOT EXISTS images (
|
65 |
id SERIAL PRIMARY KEY,
|
66 |
chat_id TEXT NOT NULL,
|
@@ -68,9 +83,9 @@ def prepare_tables():
|
|
68 |
url TEXT NOT NULL,
|
69 |
created_at BIGINT NOT NULL
|
70 |
);
|
71 |
-
"""
|
72 |
-
|
73 |
-
|
74 |
|
75 |
# βββββ Inactivity Monitor βββββ
|
76 |
def inactivity_monitor():
|
@@ -316,8 +331,7 @@ async def whatsapp_webhook(request: Request):
|
|
316 |
send_message(mid, chat_id, f"β¨ {generate_llm('Give me an inspirational quote.')}")
|
317 |
return {"success": True}
|
318 |
|
319 |
-
# trivia,
|
320 |
-
# just queue tasks as before
|
321 |
|
322 |
if low.startswith("/meme "):
|
323 |
prompt = body[len("/meme "):].strip()
|
@@ -340,7 +354,7 @@ def index():
|
|
340 |
return "Eve is running! π"
|
341 |
|
342 |
if __name__ == "__main__":
|
343 |
-
# 1)
|
344 |
prepare_tables()
|
345 |
|
346 |
# 2) start background threads
|
|
|
7 |
import re
|
8 |
import json
|
9 |
import requests
|
10 |
+
import psycopg2
|
11 |
+
from urllib.parse import urlparse
|
12 |
|
13 |
from fastapi import FastAPI, Request, HTTPException
|
14 |
from fastapi.responses import PlainTextResponse, JSONResponse
|
|
|
27 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
28 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
29 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
30 |
+
BOT_GROUP_CHAT = os.getenv("BOT_GROUP_CHAT") # must be a group chat ID
|
31 |
IMAGE_DIR = "/tmp/images"
|
32 |
AUDIO_DIR = "/tmp/audio"
|
33 |
|
34 |
+
# Supabase client (for data ops)
|
35 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
36 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
37 |
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
38 |
|
39 |
+
# Postgres URL for psycopg2 (same as SUPABASE_URL)
|
40 |
+
DATABASE_URL = os.getenv("DATABASE_URL") or SUPABASE_URL
|
41 |
+
|
42 |
if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE,
|
43 |
WEBHOOK_AUTH_TOKEN, BOT_GROUP_CHAT,
|
44 |
+
SUPABASE_URL, SUPABASE_KEY, DATABASE_URL]):
|
45 |
raise ValueError("One or more environment variables are not set properly")
|
46 |
|
47 |
# Queues & stores
|
|
|
52 |
|
53 |
app = FastAPI()
|
54 |
|
55 |
+
# βββββ Schema Provisioning via psycopg2 βββββ
|
56 |
def prepare_tables():
|
57 |
"""
|
58 |
+
Connect via psycopg2 and ensure the 'users' and 'images' tables exist.
|
|
|
59 |
"""
|
60 |
+
# Parse DATABASE_URL
|
61 |
+
result = urlparse(DATABASE_URL)
|
62 |
+
conn = psycopg2.connect(
|
63 |
+
dbname=result.path.lstrip("/"),
|
64 |
+
user=result.username,
|
65 |
+
password=result.password,
|
66 |
+
host=result.hostname,
|
67 |
+
port=result.port
|
68 |
+
)
|
69 |
+
conn.autocommit = True
|
70 |
+
cur = conn.cursor()
|
71 |
+
cur.execute("""
|
72 |
CREATE TABLE IF NOT EXISTS users (
|
73 |
id SERIAL PRIMARY KEY,
|
74 |
chat_id TEXT UNIQUE NOT NULL,
|
75 |
created_at BIGINT NOT NULL
|
76 |
);
|
77 |
+
""")
|
78 |
+
cur.execute("""
|
79 |
CREATE TABLE IF NOT EXISTS images (
|
80 |
id SERIAL PRIMARY KEY,
|
81 |
chat_id TEXT NOT NULL,
|
|
|
83 |
url TEXT NOT NULL,
|
84 |
created_at BIGINT NOT NULL
|
85 |
);
|
86 |
+
""")
|
87 |
+
cur.close()
|
88 |
+
conn.close()
|
89 |
|
90 |
# βββββ Inactivity Monitor βββββ
|
91 |
def inactivity_monitor():
|
|
|
331 |
send_message(mid, chat_id, f"β¨ {generate_llm('Give me an inspirational quote.')}")
|
332 |
return {"success": True}
|
333 |
|
334 |
+
# β¦ trivia, polls omitted for brevity β¦
|
|
|
335 |
|
336 |
if low.startswith("/meme "):
|
337 |
prompt = body[len("/meme "):].strip()
|
|
|
354 |
return "Eve is running! π"
|
355 |
|
356 |
if __name__ == "__main__":
|
357 |
+
# 1) provision schema
|
358 |
prepare_tables()
|
359 |
|
360 |
# 2) start background threads
|