Initial commit

This commit is contained in:
Andre Beging
2025-10-07 12:51:31 +02:00
commit c7f694d820
18 changed files with 1683 additions and 0 deletions

0
app/__init__.py Normal file
View File

32
app/config.py Normal file
View File

@@ -0,0 +1,32 @@
from functools import lru_cache
from pathlib import Path
from typing import Optional
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
populate_by_name=True,
extra="ignore",
)
api_id: int = Field(..., alias="TELEGRAM_API_ID")
api_hash: str = Field(..., alias="TELEGRAM_API_HASH")
phone_number: Optional[str] = Field(default=None, alias="TELEGRAM_PHONE")
session_name: str = Field(default="telegram", alias="TELEGRAM_SESSION_NAME")
session_path: Path = Field(default=Path("data") / "telegram.session", alias="TELEGRAM_SESSION_PATH")
database_path: Path = Field(default=Path("data") / "hooks.json", alias="DATABASE_PATH")
base_url: str = Field(default="http://localhost:8000", alias="BASE_URL")
hook_id_length: int = Field(default=8, alias="HOOK_ID_LENGTH")
@lru_cache
def get_settings() -> Settings:
settings = Settings()
settings.session_path.parent.mkdir(parents=True, exist_ok=True)
settings.database_path.parent.mkdir(parents=True, exist_ok=True)
return settings

184
app/main.py Normal file
View File

@@ -0,0 +1,184 @@
from contextlib import asynccontextmanager
from pathlib import Path
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from .config import get_settings
from .models import (
HookCreate,
HookResponse,
HookUpdateId,
LoginStartRequest,
LoginVerifyRequest,
MessageTriggerResponse,
StatusResponse,
)
from .storage import (
create_hook_async,
delete_hook_async,
get_hook_async,
list_hooks_async,
update_hook_id_async,
)
from .telegram_service import telegram_service
settings = get_settings()
@asynccontextmanager
async def lifespan(_: FastAPI):
await telegram_service.ensure_connected()
try:
yield
finally:
await telegram_service.disconnect()
app = FastAPI(title="Telegram Message Hook", lifespan=lifespan)
static_directory = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=static_directory), name="static")
index_path = Path(__file__).parent / "templates" / "index.html"
@app.get("/", response_class=HTMLResponse)
async def index() -> HTMLResponse:
if not index_path.exists():
raise HTTPException(status_code=500, detail="Frontend not found")
return HTMLResponse(index_path.read_text(encoding="utf-8"))
@app.get("/api/status", response_model=StatusResponse)
async def status() -> StatusResponse:
authorized = await telegram_service.is_authorized()
user = await telegram_service.get_user() if authorized else None
login_state = telegram_service.get_login_state()
return StatusResponse(
authorized=authorized,
user=user,
session_active=telegram_service.is_connected(),
phone_number=login_state.phone_number,
code_sent=login_state.code_sent,
)
@app.post("/api/login/start", response_model=StatusResponse)
async def login_start(payload: LoginStartRequest) -> StatusResponse:
try:
await telegram_service.start_login(payload.phone_number)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
login_state = telegram_service.get_login_state()
return StatusResponse(
authorized=False,
user=None,
session_active=telegram_service.is_connected(),
phone_number=login_state.phone_number,
code_sent=login_state.code_sent,
)
@app.post("/api/login/verify", response_model=StatusResponse)
async def login_verify(payload: LoginVerifyRequest) -> StatusResponse:
try:
await telegram_service.verify_code(
code=payload.code,
password=payload.password,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=400, detail=str(exc)) from exc
authorized = await telegram_service.is_authorized()
user = await telegram_service.get_user() if authorized else None
login_state = telegram_service.get_login_state()
return StatusResponse(
authorized=authorized,
user=user,
session_active=telegram_service.is_connected(),
phone_number=login_state.phone_number,
code_sent=login_state.code_sent,
)
@app.post("/api/logout", response_model=StatusResponse)
async def logout() -> StatusResponse:
await telegram_service.logout()
login_state = telegram_service.get_login_state()
return StatusResponse(
authorized=False,
user=None,
session_active=telegram_service.is_connected(),
phone_number=login_state.phone_number,
code_sent=login_state.code_sent,
)
@app.get("/api/hooks", response_model=List[HookResponse])
async def list_hooks() -> List[HookResponse]:
hooks = await list_hooks_async()
return [
HookResponse(
hook_id=hook.hook_id,
chat_id=hook.chat_id,
message=hook.message,
created_at=hook.created_at,
action_url=f"{settings.base_url}{hook.action_path}",
)
for hook in hooks
]
@app.post("/api/hooks", response_model=HookResponse, status_code=201)
async def create_hook(payload: HookCreate) -> HookResponse:
hook = await create_hook_async(payload)
return HookResponse(
hook_id=hook.hook_id,
chat_id=hook.chat_id,
message=hook.message,
created_at=hook.created_at,
action_url=f"{settings.base_url}{hook.action_path}",
)
@app.delete("/api/hooks/{hook_id}", status_code=204)
async def delete_hook(hook_id: str) -> None:
deleted = await delete_hook_async(hook_id)
if not deleted:
raise HTTPException(status_code=404, detail="Hook not found")
@app.patch("/api/hooks/{hook_id}", response_model=HookResponse)
async def update_hook(hook_id: str, payload: HookUpdateId) -> HookResponse:
try:
updated = await update_hook_id_async(hook_id, payload.hook_id)
except KeyError as exc:
raise HTTPException(status_code=404, detail="Hook not found") from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return HookResponse(
hook_id=updated.hook_id,
chat_id=updated.chat_id,
message=updated.message,
created_at=updated.created_at,
action_url=f"{settings.base_url}{updated.action_path}",
)
@app.get("/action/{hook_id}", response_model=MessageTriggerResponse)
async def trigger_hook(hook_id: str) -> MessageTriggerResponse:
hook = await get_hook_async(hook_id)
if not hook:
raise HTTPException(status_code=404, detail="Hook not found")
try:
await telegram_service.send_message(hook.chat_id, hook.message)
except PermissionError as exc:
raise HTTPException(status_code=401, detail=str(exc)) from exc
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=500, detail=str(exc)) from exc
return MessageTriggerResponse(status="sent", hook_id=hook.hook_id, chat_id=hook.chat_id)

58
app/models.py Normal file
View File

@@ -0,0 +1,58 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class HookCreate(BaseModel):
message: str = Field(..., min_length=1, description="Message body supporting Markdown")
chat_id: str = Field(..., min_length=1, description="Target chat ID or username")
class HookRead(BaseModel):
hook_id: str
message: str
chat_id: str
created_at: datetime
@property
def action_path(self) -> str:
return f"/action/{self.hook_id}"
class HookResponse(HookRead):
action_url: str
class HookUpdateId(BaseModel):
hook_id: str = Field(
...,
min_length=3,
max_length=64,
pattern=r"^[A-Za-z0-9_-]+$",
description="New hook identifier",
)
class LoginStartRequest(BaseModel):
phone_number: Optional[str] = None
class LoginVerifyRequest(BaseModel):
code: str
phone_number: Optional[str] = None
password: Optional[str] = None
class MessageTriggerResponse(BaseModel):
status: str
hook_id: str
chat_id: str
class StatusResponse(BaseModel):
authorized: bool
user: Optional[str]
session_active: bool
phone_number: Optional[str]
code_sent: bool = False

298
app/static/app.js Normal file
View File

@@ -0,0 +1,298 @@
const sessionStatusEl = document.querySelector("#session-status");
const sessionUserEl = document.querySelector("#session-user");
const loginFeedbackEl = document.querySelector("#login-feedback");
const startLoginForm = document.querySelector("#start-login-form");
const verifyLoginForm = document.querySelector("#verify-login-form");
const logoutButton = document.querySelector("#logout-button");
const hooksCountEl = document.querySelector("#hooks-count");
const hooksListEl = document.querySelector("#hooks-list");
const hookTemplate = document.querySelector("#hook-template");
const createHookForm = document.querySelector("#create-hook-form");
const toggleCreateBtn = document.querySelector("#toggle-create");
let createFormVisible = false;
let createFormTouched = false;
function setCreateFormVisibility(show, { fromUser = false } = {}) {
if (!toggleCreateBtn) return;
createFormVisible = show;
if (fromUser) {
createFormTouched = true;
}
createHookForm.classList.toggle("hidden", !show);
toggleCreateBtn.setAttribute("aria-expanded", String(show));
toggleCreateBtn.textContent = show ? "Hide form" : "New Hook";
if (show) {
const chatInput = document.querySelector("#hook-chat-id");
if (chatInput) {
chatInput.focus();
}
}
}
if (toggleCreateBtn) {
toggleCreateBtn.addEventListener("click", () => {
setCreateFormVisibility(!createFormVisible, { fromUser: true });
});
setCreateFormVisibility(false);
}
async function fetchJSON(url, options = {}) {
const response = await fetch(url, {
headers: { "Content-Type": "application/json" },
...options,
});
if (!response.ok) {
const message = await response.text();
throw new Error(message || "Request failed");
}
return response.status === 204 ? null : response.json();
}
function updateSessionUI(status) {
if (status.authorized) {
sessionStatusEl.textContent = "Authorized";
sessionStatusEl.style.background = "rgba(100, 221, 155, 0.12)";
sessionStatusEl.style.color = "#64dd9b";
sessionUserEl.textContent = `Logged in as ${status.user}`;
loginFeedbackEl.textContent = "Session ready. You can trigger hooks.";
startLoginForm.classList.add("hidden");
verifyLoginForm.classList.add("hidden");
logoutButton.classList.remove("hidden");
} else {
sessionStatusEl.textContent = status.code_sent ? "Awaiting code" : "Not authorized";
sessionStatusEl.style.background = "rgba(79, 140, 255, 0.15)";
sessionStatusEl.style.color = "#4f8cff";
sessionUserEl.textContent = status.phone_number
? `Phone number: ${status.phone_number}`
: "Set a phone number to begin";
logoutButton.classList.add("hidden");
if (status.code_sent) {
verifyLoginForm.classList.remove("hidden");
loginFeedbackEl.textContent = "Code sent. Check your Telegram messages.";
} else {
verifyLoginForm.classList.add("hidden");
loginFeedbackEl.textContent = "Start by sending a login code to your phone.";
}
startLoginForm.classList.remove("hidden");
}
}
async function refreshAll() {
try {
const status = await fetchJSON("/api/status");
updateSessionUI(status);
} catch (error) {
loginFeedbackEl.textContent = `Failed to refresh status: ${error.message}`;
}
await loadHooks();
}
async function loadHooks() {
try {
const hooks = await fetchJSON("/api/hooks");
hooksCountEl.textContent = hooks.length;
hooksListEl.innerHTML = "";
if (!hooks.length) {
if (!createFormTouched) {
setCreateFormVisibility(true);
}
const empty = document.createElement("p");
empty.className = "feedback";
empty.textContent = "No hooks yet. Use the New Hook button above to create one.";
hooksListEl.appendChild(empty);
return;
}
hooks.forEach((hook) => {
const node = hookTemplate.content.cloneNode(true);
node.querySelector("h3").textContent = hook.chat_id;
node.querySelector(".hook-date").textContent = new Date(hook.created_at).toLocaleString();
node.querySelector(".hook-message").textContent = hook.message;
node.querySelector(".hook-url").textContent = hook.action_url;
node.querySelector(".hook-id").textContent = hook.hook_id;
const feedbackEl = node.querySelector(".hook-feedback");
const copyBtn = node.querySelector(".copy");
copyBtn.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(hook.action_url);
copyBtn.textContent = "Copied!";
setTimeout(() => {
copyBtn.textContent = "Copy URL";
}, 2000);
} catch (err) {
copyBtn.textContent = "Copy failed";
setTimeout(() => {
copyBtn.textContent = "Copy URL";
}, 2000);
}
});
const triggerBtn = node.querySelector(".trigger");
triggerBtn.addEventListener("click", async () => {
const originalText = triggerBtn.textContent;
triggerBtn.disabled = true;
triggerBtn.textContent = "Sending…";
feedbackEl.textContent = "";
try {
const result = await fetchJSON(`/action/${hook.hook_id}`);
triggerBtn.textContent = "Sent";
feedbackEl.textContent = `Status: ${result.status}`;
feedbackEl.style.color = "#64dd9b";
} catch (err) {
triggerBtn.textContent = "Retry";
feedbackEl.textContent = `Failed: ${err.message}`;
feedbackEl.style.color = "#ffbac7";
} finally {
setTimeout(() => {
triggerBtn.textContent = originalText;
triggerBtn.disabled = false;
feedbackEl.style.color = "";
}, 2000);
}
});
const editIdBtn = node.querySelector(".edit-id");
const editIconMarkup = editIdBtn.innerHTML;
editIdBtn.addEventListener("click", async () => {
const newId = prompt("Enter new hook ID", hook.hook_id);
if (newId === null) {
return;
}
const sanitized = newId.trim();
if (!sanitized || sanitized === hook.hook_id) {
return;
}
editIdBtn.disabled = true;
editIdBtn.textContent = "Saving…";
feedbackEl.textContent = "";
try {
await fetchJSON(`/api/hooks/${hook.hook_id}`, {
method: "PATCH",
body: JSON.stringify({ hook_id: sanitized }),
});
feedbackEl.textContent = "Hook ID updated.";
feedbackEl.style.color = "#64dd9b";
await loadHooks();
} catch (err) {
feedbackEl.textContent = `Update failed: ${err.message}`;
feedbackEl.style.color = "#ffbac7";
} finally {
editIdBtn.disabled = false;
editIdBtn.innerHTML = editIconMarkup;
setTimeout(() => {
feedbackEl.textContent = "";
feedbackEl.style.color = "";
}, 2500);
}
});
const deleteBtn = node.querySelector(".delete");
deleteBtn.addEventListener("click", async () => {
if (!confirm("Delete this hook?")) return;
try {
await fetchJSON(`/api/hooks/${hook.hook_id}`, { method: "DELETE" });
await loadHooks();
} catch (err) {
alert(`Failed to delete hook: ${err.message}`);
}
});
hooksListEl.appendChild(node);
});
} catch (error) {
hooksListEl.innerHTML = "";
const para = document.createElement("p");
para.className = "feedback";
para.textContent = `Failed to load hooks: ${error.message}`;
hooksListEl.appendChild(para);
}
}
startLoginForm.addEventListener("submit", async (event) => {
event.preventDefault();
const phoneNumber = document.querySelector("#phone-number").value || null;
loginFeedbackEl.textContent = "Sending code…";
try {
const status = await fetchJSON("/api/login/start", {
method: "POST",
body: JSON.stringify({ phone_number: phoneNumber }),
});
updateSessionUI(status);
loginFeedbackEl.textContent = "Code sent successfully.";
} catch (error) {
loginFeedbackEl.textContent = `Failed to send code: ${error.message}`;
}
});
verifyLoginForm.addEventListener("submit", async (event) => {
event.preventDefault();
const code = document.querySelector("#verification-code").value;
const password = document.querySelector("#twofactor-password").value || null;
loginFeedbackEl.textContent = "Verifying…";
try {
const status = await fetchJSON("/api/login/verify", {
method: "POST",
body: JSON.stringify({ code, password }),
});
updateSessionUI(status);
loginFeedbackEl.textContent = status.authorized
? "Login completed."
: "Enter your password to finish.";
} catch (error) {
loginFeedbackEl.textContent = `Verification failed: ${error.message}`;
}
});
logoutButton.addEventListener("click", async () => {
try {
const status = await fetchJSON("/api/logout", { method: "POST" });
updateSessionUI(status);
loginFeedbackEl.textContent = "Logged out.";
} catch (error) {
loginFeedbackEl.textContent = `Logout failed: ${error.message}`;
}
});
createHookForm.addEventListener("submit", async (event) => {
event.preventDefault();
const chatId = document.querySelector("#hook-chat-id").value.trim();
const message = document.querySelector("#hook-message").value.trim();
if (!chatId || !message) {
alert("Chat ID and message are required.");
return;
}
const submitBtn = createHookForm.querySelector("button[type='submit']");
const originalText = submitBtn.textContent;
submitBtn.disabled = true;
submitBtn.textContent = "Creating…";
try {
await fetchJSON("/api/hooks", {
method: "POST",
body: JSON.stringify({ chat_id: chatId, message }),
});
createHookForm.reset();
await loadHooks();
} catch (error) {
alert(`Failed to create hook: ${error.message}`);
} finally {
submitBtn.disabled = false;
submitBtn.textContent = originalText;
}
});
window.addEventListener("DOMContentLoaded", async () => {
await refreshAll();
try {
const status = await fetchJSON("/api/status");
const phoneInput = document.querySelector("#phone-number");
if (status.phone_number && !phoneInput.value) {
phoneInput.value = status.phone_number;
}
} catch (err) {
console.warn("Unable to preload phone number", err);
}
});

303
app/static/style.css Normal file
View File

@@ -0,0 +1,303 @@
:root {
color-scheme: light dark;
--bg: #10131a;
--surface: rgba(255, 255, 255, 0.06);
--surface-light: rgba(10, 14, 25, 0.5);
--text: #f4f6fb;
--muted: #adb5d6;
--accent: #4f8cff;
--accent-dark: #3f6ed6;
--danger: #ff5c7a;
--font-base: "Inter", "Segoe UI", system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
--border-radius: 18px;
--shadow: 0 18px 40px rgba(15, 20, 30, 0.35);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
font-family: var(--font-base);
background: radial-gradient(circle at top, #192040, #0a0d18);
color: var(--text);
display: grid;
grid-template-rows: auto 1fr auto;
}
header,
footer {
padding: 2rem clamp(1rem, 6vw, 4rem);
}
header h1 {
margin: 0;
font-size: clamp(2rem, 5vw, 3.5rem);
letter-spacing: -0.04em;
}
.subtitle {
margin-top: 0.5rem;
color: var(--muted);
max-width: 40rem;
}
main {
display: grid;
gap: 2rem;
padding: 0 clamp(1rem, 6vw, 4rem) 4rem;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
}
.card {
background: linear-gradient(145deg, rgba(23, 30, 50, 0.92), rgba(10, 12, 22, 0.9));
border-radius: var(--border-radius);
padding: clamp(1.5rem, 3vw, 2rem);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
border: 1px solid rgba(255, 255, 255, 0.06);
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1.5rem;
}
.header-actions {
display: inline-flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
justify-content: flex-end;
}
.status-pill {
display: inline-flex;
align-items: center;
padding: 0.35rem 0.9rem;
border-radius: 999px;
background: rgba(79, 140, 255, 0.15);
color: var(--accent);
font-weight: 600;
margin-bottom: 0.75rem;
}
.user-info {
margin-bottom: 1.5rem;
color: var(--muted);
}
.form-grid {
display: grid;
gap: 0.75rem;
margin-bottom: 1.5rem;
}
label {
font-size: 0.9rem;
color: var(--muted);
}
input,
textarea,
button {
font-family: inherit;
font-size: 1rem;
border-radius: 12px;
}
input,
textarea {
border: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(9, 13, 24, 0.65);
color: var(--text);
padding: 0.75rem 1rem;
transition: border 0.2s ease, background 0.2s ease;
}
input:focus,
textarea:focus {
outline: none;
border-color: rgba(79, 140, 255, 0.5);
background: rgba(15, 20, 35, 0.85);
}
textarea {
resize: vertical;
min-height: 150px;
}
button {
padding: 0.8rem 1.2rem;
border: none;
cursor: pointer;
font-weight: 600;
transition: transform 0.18s ease, box-shadow 0.18s ease;
}
button:active {
transform: translateY(2px);
}
.icon-button {
padding: 0.6rem;
min-width: 0;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.25rem;
}
.icon {
width: 1rem;
height: 1rem;
display: block;
fill: currentColor;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.primary {
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
color: white;
box-shadow: 0 14px 30px rgba(79, 140, 255, 0.35);
}
.secondary {
background: rgba(255, 255, 255, 0.08);
color: var(--text);
border: 1px solid rgba(255, 255, 255, 0.06);
}
.danger {
background: rgba(255, 92, 122, 0.2);
color: #ffbac7;
border: 1px solid rgba(255, 92, 122, 0.4);
}
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 2.5rem;
padding: 0.35rem 0.65rem;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.feedback {
min-height: 1.25rem;
color: var(--muted);
}
.hook-list {
display: grid;
gap: 1rem;
}
.hook-card {
padding: 1rem 1.25rem;
background: rgba(10, 13, 24, 0.75);
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.04);
display: grid;
gap: 0.75rem;
}
.hook-id-row {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.hook-id-label {
font-size: 0.85rem;
color: var(--muted);
}
.hook-id {
padding: 0.3rem 0.6rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
}
.hook-meta {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 1rem;
}
.hook-meta h3 {
margin: 0;
font-size: 1rem;
color: var(--text);
}
.hook-date {
font-size: 0.85rem;
color: var(--muted);
}
.hook-message {
white-space: pre-wrap;
font-family: "JetBrains Mono", "Fira Code", monospace;
background: rgba(255, 255, 255, 0.04);
padding: 0.75rem;
border-radius: 12px;
margin: 0;
}
.hook-url {
background: rgba(255, 255, 255, 0.04);
border-radius: 12px;
padding: 0.6rem 0.8rem;
display: inline-block;
user-select: all;
}
.hook-feedback {
margin: 0.35rem 0 0;
min-height: 1rem;
font-size: 0.85rem;
color: var(--muted);
}
.hook-actions {
display: flex;
gap: 0.75rem;
}
.hidden {
display: none !important;
}
.mono {
font-family: "JetBrains Mono", "Fira Code", monospace;
}
@media (max-width: 640px) {
header,
footer {
text-align: center;
}
.hook-actions {
flex-direction: column;
}
}

167
app/storage.py Normal file
View File

@@ -0,0 +1,167 @@
import json
import re
import secrets
import string
import threading
from datetime import UTC, datetime
from pathlib import Path
from typing import List, Optional, Set
from fastapi.concurrency import run_in_threadpool
from .config import get_settings
from .models import HookCreate, HookRead
HOOK_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{3,64}$")
class HookStore:
def __init__(self, storage_path: Path, hook_id_length: int) -> None:
self.storage_path = storage_path
self.hook_id_length = hook_id_length
self._lock = threading.Lock()
self._initialize()
def _initialize(self) -> None:
if not self.storage_path.exists():
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
self.storage_path.write_text("[]\n", encoding="utf-8")
else:
try:
self._load_raw()
except (json.JSONDecodeError, UnicodeDecodeError):
# Corrupted or non-UTF file; back it up and start fresh
backup = self.storage_path.with_suffix(self.storage_path.suffix + ".bak")
self.storage_path.replace(backup)
self.storage_path.write_text("[]\n", encoding="utf-8")
def _load_raw(self) -> List[dict]:
text = self.storage_path.read_text(encoding="utf-8")
data = json.loads(text or "[]")
if not isinstance(data, list):
raise json.JSONDecodeError("Hook store must contain a list", text, 0)
return data
def _save_raw(self, data: List[dict]) -> None:
payload = json.dumps(data, indent=2, ensure_ascii=False)
tmp_path = self.storage_path.with_suffix(self.storage_path.suffix + ".tmp")
tmp_path.write_text(payload + "\n", encoding="utf-8")
tmp_path.replace(self.storage_path)
def _generate_hook_id(self, existing_ids: Set[str]) -> str:
alphabet = string.ascii_lowercase + string.digits
while True:
candidate = "".join(secrets.choice(alphabet) for _ in range(self.hook_id_length))
if candidate not in existing_ids:
return candidate
def list_hooks(self) -> List[HookRead]:
raw_hooks = self._load_raw()
hooks = [
HookRead(
hook_id=item["hook_id"],
chat_id=item["chat_id"],
message=item["message"],
created_at=datetime.fromisoformat(item["created_at"]),
)
for item in raw_hooks
]
hooks.sort(key=lambda h: h.created_at, reverse=True)
return hooks
def create_hook(self, payload: HookCreate) -> HookRead:
created_at = datetime.now(UTC).replace(microsecond=0).isoformat()
with self._lock:
raw_hooks = self._load_raw()
existing_ids = {item["hook_id"] for item in raw_hooks}
hook_id = self._generate_hook_id(existing_ids)
raw_hooks.append(
{
"hook_id": hook_id,
"chat_id": payload.chat_id,
"message": payload.message,
"created_at": created_at,
}
)
self._save_raw(raw_hooks)
return HookRead(
hook_id=hook_id,
chat_id=payload.chat_id,
message=payload.message,
created_at=datetime.fromisoformat(created_at),
)
def get_hook(self, hook_id: str) -> Optional[HookRead]:
raw_hooks = self._load_raw()
for item in raw_hooks:
if item.get("hook_id") == hook_id:
return HookRead(
hook_id=item["hook_id"],
chat_id=item["chat_id"],
message=item["message"],
created_at=datetime.fromisoformat(item["created_at"]),
)
return None
def delete_hook(self, hook_id: str) -> bool:
with self._lock:
raw_hooks = self._load_raw()
new_hooks = [item for item in raw_hooks if item.get("hook_id") != hook_id]
if len(new_hooks) == len(raw_hooks):
return False
self._save_raw(new_hooks)
return True
def update_hook_id(self, current_id: str, new_id: str) -> HookRead:
normalized_new_id = new_id.strip()
if not normalized_new_id:
raise ValueError("Hook ID cannot be empty")
if not HOOK_ID_PATTERN.fullmatch(normalized_new_id):
raise ValueError("Hook ID must be 3-64 characters of letters, numbers, '_' or '-' only")
with self._lock:
raw_hooks = self._load_raw()
exists = next((item for item in raw_hooks if item.get("hook_id") == current_id), None)
if not exists:
raise KeyError("Hook not found")
if normalized_new_id == current_id:
return HookRead(
hook_id=exists["hook_id"],
chat_id=exists["chat_id"],
message=exists["message"],
created_at=datetime.fromisoformat(exists["created_at"]),
)
if any(item.get("hook_id") == normalized_new_id for item in raw_hooks):
raise ValueError("Hook ID already exists")
exists["hook_id"] = normalized_new_id
self._save_raw(raw_hooks)
return HookRead(
hook_id=normalized_new_id,
chat_id=exists["chat_id"],
message=exists["message"],
created_at=datetime.fromisoformat(exists["created_at"]),
)
settings = get_settings()
store = HookStore(settings.database_path, settings.hook_id_length)
async def list_hooks_async() -> List[HookRead]:
return await run_in_threadpool(store.list_hooks)
async def create_hook_async(payload: HookCreate) -> HookRead:
return await run_in_threadpool(store.create_hook, payload)
async def get_hook_async(hook_id: str) -> Optional[HookRead]:
return await run_in_threadpool(store.get_hook, hook_id)
async def delete_hook_async(hook_id: str) -> bool:
return await run_in_threadpool(store.delete_hook, hook_id)
async def update_hook_id_async(current_hook_id: str, new_hook_id: str) -> HookRead:
return await run_in_threadpool(store.update_hook_id, current_hook_id, new_hook_id)

128
app/telegram_service.py Normal file
View File

@@ -0,0 +1,128 @@
import asyncio
from dataclasses import dataclass
from typing import Optional
from telethon import TelegramClient, errors
from .config import get_settings
@dataclass
class LoginState:
phone_number: Optional[str] = None
phone_code_hash: Optional[str] = None
code_sent: bool = False
class TelegramService:
def __init__(self) -> None:
self.settings = get_settings()
self.client = TelegramClient(
str(self.settings.session_path),
self.settings.api_id,
self.settings.api_hash,
)
self._lock = asyncio.Lock()
self._login_state = LoginState(phone_number=self.settings.phone_number)
self._connected = False
async def connect(self) -> None:
async with self._lock:
if not self._connected:
await self.client.connect()
self._connected = True
async def ensure_connected(self) -> None:
if not self.client.is_connected():
async with self._lock:
if not self.client.is_connected():
await self.client.connect()
async def disconnect(self) -> None:
async with self._lock:
if self.client.is_connected():
await self.client.disconnect()
self._connected = False
def is_connected(self) -> bool:
return self.client.is_connected()
async def is_authorized(self) -> bool:
await self.ensure_connected()
result = self.client.is_user_authorized()
if asyncio.iscoroutine(result):
result = await result
return bool(result)
async def get_user(self) -> Optional[str]:
await self.ensure_connected()
authorized = self.client.is_user_authorized()
if asyncio.iscoroutine(authorized):
authorized = await authorized
if not authorized:
return None
me = await self.client.get_me()
if not me:
return None
full_name = " ".join(filter(None, [me.first_name, me.last_name])).strip()
return full_name or me.username or str(me.id)
async def start_login(self, phone_number: Optional[str]) -> None:
phone = phone_number or self.settings.phone_number
if not phone:
raise ValueError("Phone number is required to start login")
await self.ensure_connected()
sent_code = await self.client.send_code_request(phone)
self._login_state = LoginState(
phone_number=phone,
phone_code_hash=sent_code.phone_code_hash,
code_sent=True,
)
async def verify_code(self, code: str, password: Optional[str] = None) -> None:
if not self._login_state.code_sent or not self._login_state.phone_code_hash:
raise ValueError("No login code has been requested")
await self.ensure_connected()
success = False
try:
await self.client.sign_in(
phone=self._login_state.phone_number,
code=code,
phone_code_hash=self._login_state.phone_code_hash,
)
success = True
except errors.SessionPasswordNeededError:
if not password:
raise
await self.client.sign_in(password=password)
success = True
except errors.PhoneCodeInvalidError as exc:
raise ValueError("Invalid verification code") from exc
except errors.PhoneCodeExpiredError as exc:
raise ValueError("Verification code has expired") from exc
finally:
if success:
self._login_state = LoginState(
phone_number=self._login_state.phone_number,
code_sent=False,
)
async def logout(self) -> None:
await self.ensure_connected()
await self.client.log_out()
self._login_state = LoginState(phone_number=self.settings.phone_number)
async def send_message(self, chat_id: str, message: str) -> None:
await self.ensure_connected()
authorized = self.client.is_user_authorized()
if asyncio.iscoroutine(authorized):
authorized = await authorized
if not authorized:
raise PermissionError("Telegram session is not authorized")
await self.client.send_message(entity=chat_id, message=message, parse_mode="md")
def get_login_state(self) -> LoginState:
return self._login_state
telegram_service = TelegramService()

98
app/templates/index.html Normal file
View File

@@ -0,0 +1,98 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Telegram Message Hook</title>
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<header>
<h1>Telegram Message Hook</h1>
<p class="subtitle">Trigger curated messages in your chats via simple webhooks.</p>
</header>
<main>
<section id="session-section" class="card">
<h2>Telegram Session</h2>
<div id="session-status" class="status-pill">Checking status…</div>
<div id="session-user" class="user-info"></div>
<div id="login-forms">
<form id="start-login-form" class="form-grid">
<label for="phone-number">Phone Number</label>
<input type="tel" id="phone-number" name="phone" placeholder="+123456789" />
<button type="submit" class="primary">Send Verification Code</button>
</form>
<form id="verify-login-form" class="form-grid hidden">
<label for="verification-code">Verification Code</label>
<input type="text" id="verification-code" name="code" placeholder="12345" />
<label for="twofactor-password">Password (if 2FA enabled)</label>
<input type="password" id="twofactor-password" name="password" placeholder="Your password" />
<button type="submit" class="primary">Complete Login</button>
</form>
</div>
<button id="logout-button" class="secondary hidden">Log out</button>
<p id="login-feedback" class="feedback"></p>
</section>
<section id="hooks-section" class="card">
<div class="section-header">
<h2>Hooks</h2>
<div class="header-actions">
<span id="hooks-count" class="badge">0</span>
<button type="button" id="toggle-create" class="secondary" aria-expanded="false">
New Hook
</button>
</div>
</div>
<form id="create-hook-form" class="form-grid hidden">
<label for="hook-chat-id">Chat ID or Username</label>
<input type="text" id="hook-chat-id" placeholder="@yourchannel or 123456" required />
<label for="hook-message">Message (Markdown supported)</label>
<textarea id="hook-message" rows="6" placeholder="Write the message to deliver…" required></textarea>
<button type="submit" class="primary">Create Hook</button>
</form>
<div id="hooks-list" class="hook-list"></div>
</section>
</main>
<template id="hook-template">
<article class="hook-card">
<div class="hook-meta">
<h3></h3>
<span class="hook-date"></span>
</div>
<div class="hook-id-row">
<span class="hook-id-label">ID:</span>
<code class="hook-id mono"></code>
<button class="secondary edit-id icon-button" aria-label="Edit hook ID" title="Edit hook ID">
<svg class="icon icon-pen" viewBox="0 0 24 24" aria-hidden="true">
<path
d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zm18.71-10.04a1 1 0 0 0 0-1.41l-2.51-2.51a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 2-1.66z"
/>
</svg>
<span class="sr-only">Edit hook ID</span>
</button>
</div>
<p class="hook-message"></p>
<code class="hook-url"></code>
<p class="hook-feedback"></p>
<div class="hook-actions">
<button class="primary trigger">Play now</button>
<button class="secondary copy">Copy URL</button>
<button class="danger delete">Delete</button>
</div>
</article>
</template>
<footer>
<p>Need to trigger a message manually? Hit <span class="mono">GET /action/&lt;hook-id&gt;</span>.</p>
</footer>
<script src="/static/app.js" defer></script>
</body>
</html>