This commit is contained in:
Timothy Jaeryang Baek 2024-12-26 22:35:58 -08:00
parent a4f5df535b
commit e0efa290d6
3 changed files with 63 additions and 73 deletions

View File

@ -1,45 +1,61 @@
import asyncio
import socketio import socketio
from env import WEBUI_URL, TOKEN from env import WEBUI_URL, TOKEN
from utils import send_message from utils import send_message, send_typing
# Create a Socket.IO client instance # Create an asynchronous Socket.IO client instance
sio = socketio.Client(logger=False, engineio_logger=False) sio = socketio.AsyncClient(logger=False, engineio_logger=False)
# Event handlers # Event handlers
@sio.event @sio.event
def connect(): async def connect():
print("Connected!") print("Connected!")
@sio.event @sio.event
def disconnect(): async def disconnect():
print("Disconnected from the server!") print("Disconnected from the server!")
def events(sio, user_id): # Define a function to handle channel events
def events(user_id):
@sio.on("channel-events") @sio.on("channel-events")
def channel_events(data): async def channel_events(data):
if data["user"]["id"] == user_id: if data["user"]["id"] == user_id:
# Ignore events from the bot itself # Ignore events from the bot itself
return return
print("Channel events:", data) if data["data"]["type"] == "message":
send_message(data["channel_id"], "Pong!") print(f'{data["user"]["name"]}: {data["data"]["data"]["content"]}')
await send_typing(sio, data["channel_id"])
await asyncio.sleep(1) # Simulate a delay
await send_message(data["channel_id"], "Pong!")
try: # Define an async function for the main workflow
async def main():
try:
print(f"Connecting to {WEBUI_URL}...") print(f"Connecting to {WEBUI_URL}...")
sio.connect(WEBUI_URL, socketio_path="/ws/socket.io", transports=["websocket"]) await sio.connect(
WEBUI_URL, socketio_path="/ws/socket.io", transports=["websocket"]
)
print("Connection established!") print("Connection established!")
except Exception as e: except Exception as e:
print(f"Failed to connect: {e}") print(f"Failed to connect: {e}")
return
# Callback function for user-join
async def join_callback(data):
events(data["id"]) # Attach the event handlers dynamically
# Authenticate with the server
await sio.emit("user-join", {"auth": {"token": TOKEN}}, callback=join_callback)
# Wait indefinitely to keep the connection open
await sio.wait()
def join_callback(data): # Actually run the async `main` function using `asyncio`
events(sio, data["id"]) if __name__ == "__main__":
asyncio.run(main())
# Authenticate with the server
sio.emit("user-join", {"auth": {"token": TOKEN}}, callback=join_callback)
sio.wait()

View File

@ -1,45 +0,0 @@
import socketio
from env import WEBUI_URL, TOKEN
from utils import send_message
# Create a Socket.IO client instance
sio = socketio.Client(logger=False, engineio_logger=False)
# Event handlers
@sio.event
def connect():
print("Connected!")
@sio.event
def disconnect():
print("Disconnected from the server!")
def events(sio, user_id):
@sio.on("channel-events")
def channel_events(data):
if data["user"]["id"] == user_id:
# Ignore events from the bot itself
return
print(f'{data["user"]["name"]}: {data["data"]["data"]["content"]}')
send_message(data["channel_id"], "Pong!")
try:
print(f"Connecting to {WEBUI_URL}...")
sio.connect(WEBUI_URL, socketio_path="/ws/socket.io", transports=["websocket"])
print("Connection established!")
except Exception as e:
print(f"Failed to connect: {e}")
def join_callback(data):
events(sio, data["id"])
# Authenticate with the server
sio.emit("user-join", {"auth": {"token": TOKEN}}, callback=join_callback)
sio.wait()

View File

@ -1,14 +1,33 @@
import requests import aiohttp
import socketio
from env import WEBUI_URL, TOKEN from env import WEBUI_URL, TOKEN
def send_message(channel_id: str, message: str): async def send_message(channel_id: str, message: str):
url = f"{WEBUI_URL}/api/v1/channels/{channel_id}/messages/post" url = f"{WEBUI_URL}/api/v1/channels/{channel_id}/messages/post"
headers = {"Authorization": f"Bearer {TOKEN}"} headers = {"Authorization": f"Bearer {TOKEN}"}
data = {"content": message} data = {"content": message}
response = requests.post(url, headers=headers, json=data) async with aiohttp.ClientSession() as session:
response.raise_for_status() async with session.post(url, headers=headers, json=data) as response:
if response.status != 200:
# Raise an exception if the request fails
raise aiohttp.ClientResponseError(
request_info=response.request_info,
history=response.history,
status=response.status,
message=await response.text(),
headers=response.headers,
)
# Return response JSON if successful
return await response.json()
return response.json()
async def send_typing(sio: socketio.AsyncClient, channel_id: str):
await sio.emit(
"channel-events",
{
"channel_id": channel_id,
"data": {"type": "typing", "data": {"typing": True}},
},
)