mirror of
https://github.com/open-webui/bot
synced 2025-05-13 09:02:41 +00:00
refac
This commit is contained in:
parent
a4f5df535b
commit
e0efa290d6
48
bot/main.py
48
bot/main.py
@ -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!")
|
||||||
|
|
||||||
|
|
||||||
|
# Define an async function for the main workflow
|
||||||
|
async def main():
|
||||||
try:
|
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
|
||||||
def join_callback(data):
|
async def join_callback(data):
|
||||||
events(sio, data["id"])
|
events(data["id"]) # Attach the event handlers dynamically
|
||||||
|
|
||||||
|
|
||||||
# Authenticate with the server
|
# Authenticate with the server
|
||||||
sio.emit("user-join", {"auth": {"token": TOKEN}}, callback=join_callback)
|
await sio.emit("user-join", {"auth": {"token": TOKEN}}, callback=join_callback)
|
||||||
sio.wait()
|
|
||||||
|
# Wait indefinitely to keep the connection open
|
||||||
|
await sio.wait()
|
||||||
|
|
||||||
|
|
||||||
|
# Actually run the async `main` function using `asyncio`
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
|
@ -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()
|
|
31
bot/utils.py
31
bot/utils.py
@ -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}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Loading…
Reference in New Issue
Block a user