Skip to content

Bot frontend #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Bot/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from fastapi.security import OAuth2AuthorizationCodeBearer
from google.auth.transport.requests import Request as GoogleRequest
from google.oauth2.credentials import Credentials
from starlette.middleware.cors import CORSMiddleware
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
import datetime
Expand Down Expand Up @@ -81,6 +82,14 @@ class ScheduleBotRequest(BaseModel):
meeting_end_time: str

app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all HTTP methods
allow_headers=["*"], # Allows all headers
)

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
CLIENT_SECRETS_FILE = 'credentials.json'
REDIRECT_URI = "http://localhost:8000/auth/google/callback"
Expand Down
10 changes: 7 additions & 3 deletions Bot/app/api/meetings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@
class LingoRequest(BaseModel):
key: str

class ScheduleMeeting(BaseModel):
refresh_token: str
bot_name: str


@router.get("/")
def get_meetings(token: str = Depends(OAUTH2_SCHEME), refresh_token: str = Body(..., embed=True)):
def get_meetings(body: ScheduleMeeting, token: str = Depends(OAUTH2_SCHEME)):
logger.info("Received request to fetch and schedule meetings")
creds = Credentials(
token=token,
refresh_token=refresh_token,
refresh_token=body.refresh_token,
token_uri=token_uri,
client_id=client_id,
client_secret=client_secret
Expand Down Expand Up @@ -86,7 +90,7 @@ def get_meetings(token: str = Depends(OAUTH2_SCHEME), refresh_token: str = Body(
headers={"Content-Type": "application/json"},
json={
"meeting_url": meeting_url,
"bot_name": "My Bot",
"bot_name": body.bot_name,
"meeting_time": meeting_time,
"meeting_end_time": meeting_end_time
}
Expand Down
8 changes: 8 additions & 0 deletions Bot/app/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from fastapi import FastAPI
from app.api import auth, meetings, scheduler
from app.core.scheduler import scheduler as apscheduler
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all HTTP methods
allow_headers=["*"], # Allows all headers
)

@app.on_event("startup")
def startup_event():
Expand Down
65 changes: 65 additions & 0 deletions Bot/meeting_scheduler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env python3

import asyncio
import asyncpg
import aiohttp

# --- Configuration ---
PG_USER = "postgres"
PG_PASS = "postgres"
PG_HOST = "localhost"
PG_PORT = "5432"
DB_NAME = "lingo_ai"
API_URL = "http://localhost:8001/meetings/"
SQL_QUERY = 'SELECT "accessToken", "refreshToken", "botName" FROM bot;'
PG_CONN_STRING = f"postgresql://{PG_USER}:{PG_PASS}@{PG_HOST}:{PG_PORT}/{DB_NAME}"


# Fetch access tokens asynchronously
async def fetch_data():
try:
conn = await asyncpg.connect(PG_CONN_STRING)
rows = await conn.fetch(SQL_QUERY)
await conn.close()
return [
{
"access_token": row["accessToken"],
"refresh_token": row["refreshToken"],
"bot_name": row["botName"],
}
for row in rows
]
except Exception as e:
print(f"[ERROR] Database error: {e}")
return []


# Make one request
async def make_request(session, data):
headers = {
"Authorization": f"Bearer {data["access_token"]}",
"Content-Type": "application/json",
}
body = {"refresh_token": data["refresh_token"], "bot_name": data["bot_name"]}
try:
async with session.get(
API_URL, headers=headers, json=body, timeout=10
) as response:
status = response.status
# text = await response.text()
print(f"[INFO] Token: {data['bot_name']}: -> Status: {status}")
except Exception as e:
print(f"[ERROR] Token {data['bot_name']}: failed: {e}")


# Main async workflow
async def main():
tokens = await fetch_data()
async with aiohttp.ClientSession() as session:
tasks = [make_request(session, token) for token in tokens]
await asyncio.gather(*tasks)


# Entry point
if __name__ == "__main__":
asyncio.run(main())
18 changes: 18 additions & 0 deletions app/migrations/0009_eminent_the_leader.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS "bot" (
"id" text PRIMARY KEY NOT NULL,
"user_id" text NOT NULL,
"botName" text,
"botEmail" text,
"botHd" text,
"botPicture" text,
"accessToken" text,
"refreshToken" text,
"createdAt" timestamp DEFAULT now(),
"updatedAt" timestamp DEFAULT now()
);
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "bot" ADD CONSTRAINT "bot_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE no action ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
Loading