import os, asyncio, logging, asyncpg, aiohttp, base64 from aiogram import Bot, Dispatcher from aiogram.filters import Command from aiogram.types import Message from aiogram.client.session.aiohttp import AiohttpSession logging.basicConfig(level=logging.INFO) dp = Dispatcher() def is_admin(m): return str(m.from_user.id) == str(os.getenv('ADMIN_ID', 0)) async def get_gitea_file(fp): h = {'Authorization': f"token {os.getenv('GITEA_TOKEN')}"} u = f"{os.getenv('GITEA_URL')}/api/v1/repos/agent-qwen/buryan-infra/contents/{fp}?ref=main" async with aiohttp.ClientSession() as s: async with s.get(u, headers=h) as r: if r.status == 200: data = await r.json() return base64.b64decode(data['content']).decode('utf-8') else: return f"Error {r.status}" async def heartbeat(): while True: try: c = await asyncpg.connect(host=os.getenv('PG_HOST'), database=os.getenv('PG_DB'), user=os.getenv('PG_USER'), password=os.getenv('PG_PASSWORD')) await c.execute("INSERT INTO agent_registry (name, domain, status, last_heartbeat) VALUES ('comms-agent', 'comms', 'active', CURRENT_TIMESTAMP) ON CONFLICT (name) DO UPDATE SET status='active', last_heartbeat=CURRENT_TIMESTAMP") await c.close() except Exception as e: logging.error(f"HB: {e}") await asyncio.sleep(30) @dp.message(Command('start')) async def cmd_start(m: Message): if is_admin(m): await m.answer('Hi! Cmds: /status, /issues, /runbook ') else: await m.answer(f'Access denied. ID: {m.from_user.id}') @dp.message(Command('status')) async def cmd_status(m: Message): if not is_admin(m): return try: c = await asyncpg.connect(host=os.getenv('PG_HOST'), database=os.getenv('PG_DB'), user=os.getenv('PG_USER'), password=os.getenv('PG_PASSWORD')) r = await c.fetch('SELECT host, ip, mem, disk FROM host_states ORDER BY host ASC LIMIT 5;') await c.close() await m.answer('Hosts:\n' + '\n'.join([f"{x['host']} ({x['ip']}) RAM: {x['mem'] or '?'}%" for x in r])) except Exception as e: await m.answer(f"DB Error: {e}") @dp.message(Command('issues')) async def cmd_issues(m: Message): if not is_admin(m): return try: h = {'Authorization': 'token ' + os.getenv('GITEA_TOKEN')} u = os.getenv('GITEA_URL') + '/api/v1/repos/agent-qwen/buryan-infra/issues?state=open&limit=3' async with aiohttp.ClientSession() as s: async with s.get(u, headers=h) as resp: if resp.status == 200: issues = await resp.json() await m.answer('Issues:\n' + '\n'.join([f"#{i['number']} {i['title']}" for i in issues]) if issues else 'No open issues') else: await m.answer(f"Gitea Error: {resp.status}") except Exception as e: await m.answer(f"Gitea Error: {e}") @dp.message(Command('runbook')) async def cmd_runbook(m: Message): if not is_admin(m): return args = m.text.split(maxsplit=1) if len(args) < 2: return await m.answer("Use: /runbook ") content = await get_gitea_file(f"services/{args[1].lower()}/runbook.md") if content.startswith("Error"): await m.answer(f"⚠️ {content}\nMake sure the file exists in the 'main' branch.") else: await m.answer(f"📖 **Runbook: {args[1]}**\n\n```\n{content[:3900]}\n```", parse_mode="Markdown") async def main(): logging.info('Starting comms-agent...') session = AiohttpSession(proxy=os.getenv('HTTP_PROXY')) bot = Bot(token=os.getenv('BOT_TOKEN'), session=session) asyncio.create_task(heartbeat()) try: await dp.start_polling(bot) finally: await session.close() if __name__ == '__main__': asyncio.run(main())