CollapseBot / main.py
W1xced's picture
Upload main.py
61aaa78 verified
Raw
History Blame Contribute Delete
3.48 kB
import asyncio
import logging
import yaml
import os
import re
import html
import subprocess
from aiogram import Bot, Dispatcher, types, F
from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
from aiogram.filters import CommandStart
from aiohttp import web
from config import BOT_TOKEN
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
async def health_check(request):
return web.Response(text="Bot is running!")
def load_snippets():
if not os.path.exists("snippets.yaml"):
return {}
with open("snippets.yaml", "r", encoding="utf-8") as f:
try:
return yaml.safe_load(f) or {}
except:
return {}
snippets = load_snippets()
def safe_format(text):
text = html.escape(text)
text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text)
text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
return text
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
@dp.message(CommandStart())
async def cmd_start(message: types.Message):
try:
bot_info = await bot.get_me()
await message.answer(f"Hello! I am an inline bot. Type @{bot_info.username} in any chat to see my snippets.")
except:
await message.answer("Hello! I am an inline bot.")
@dp.inline_query()
async def inline_query_handler(query: types.InlineQuery):
query_text = query.query.lower().strip()
results = []
for key, data in snippets.items():
title = data.get("title", key)
content = data.get("content", "")
if not query_text or query_text in key.lower() or query_text in title.lower() or query_text in content.lower():
description = content.split("\n")[0] if content else "No content"
if len(description) > 50:
description = description[:47] + "..."
results.append(
InlineQueryResultArticle(
id=key, title=title, description=description,
input_message_content=InputTextMessageContent(message_text=safe_format(content), parse_mode="HTML"),
)
)
await query.answer(results[:50], cache_time=1)
async def main():
app = web.Application()
app.router.add_get("/", health_check)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "0.0.0.0", 7860).start()
logger.info("Attempting to connect to Telegram...")
for attempt in range(1, 11):
try:
bot_info = await bot.get_me()
logger.info(f"Connected! Bot: @{bot_info.username}")
await dp.start_polling(bot)
break
except Exception as e:
if attempt == 10:
logger.error("Final connection attempt failed.")
return
logger.warning(f"Attempt {attempt} failed, retrying in 5s...")
await asyncio.sleep(5)
if __name__ == "__main__":
import sys
if "--worker" in sys.argv or os.name != 'nt' or os.environ.get("DOCKER_ENV"):
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logger.info("Bot stopped!")
else:
try:
subprocess.Popen([sys.executable, "manager.py"], creationflags=subprocess.CREATE_NEW_CONSOLE)
except:
asyncio.run(main())