Message API
message_api.py
py / 61 lines
FastAPI endpoints that receive internal messages, system messages and media uploads.
from fastapi import FastAPI, File, HTTPException, UploadFile, status
from telegram import Bot
from model.fastapi_internal import Message, SystemMessage
app = FastAPI()
api_path_v1 = "/homebot/api/v1"
telegram_bot = Bot(token=settings["bot_token"])
admin_chat_id = settings["admin_chat_id"]
@app.post(f"{api_path_v1}/msg", status_code=status.HTTP_200_OK)
async def send_message(msg: Message):
await telegram_bot.send_message(
chat_id=admin_chat_id,
text=f"{msg.type}:\n{msg.text}",
)
return "Message is sent successfully"
@app.post(f"{api_path_v1}/sys_msg", status_code=status.HTTP_200_OK)
async def send_system_message(msg: SystemMessage):
await telegram_bot.send_message(
chat_id=admin_chat_id,
text=f"{msg.type}:\n{msg.text}",
)
return "Message is sent successfully"
@app.post(f"{api_path_v1}/media", status_code=status.HTTP_200_OK)
async def upload_media(file: UploadFile | None = File(...)):
accepted_photo_types = [
"image/png",
"image/jpeg",
"image/jpg",
"image/heic",
"image/heif",
"image/heics",
]
if file.content_type is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="No file was uploaded",
)
if file.content_type not in accepted_photo_types:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail="Unsupported file type",
)
await telegram_bot.send_photo(
chat_id=admin_chat_id,
photo=file.file,
)
return "Photo was uploaded successfully"