W1xced commited on
Commit
c9b0131
·
verified ·
1 Parent(s): dbc6c59

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +21 -68
main.py CHANGED
@@ -1,21 +1,13 @@
1
- # CollapseBot - Telegram Inline Bot
2
- # Author: dest4590, w1xced
3
- # Version: 1.1
4
- # Description: Telegram Inline Bot for snippets
5
-
6
  import asyncio
7
  import logging
8
  import yaml
9
  import os
10
- import subprocess
11
  import re
12
  import html
13
- import socket
14
  from aiogram import Bot, Dispatcher, types, F
15
  from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
16
  from aiogram.filters import CommandStart
17
- from aiogram.client.session.aiohttp import AiohttpSession
18
- from aiohttp import web, TCPConnector
19
  from config import BOT_TOKEN
20
 
21
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@@ -26,34 +18,31 @@ async def health_check(request):
26
 
27
  def load_snippets():
28
  if not os.path.exists("snippets.yaml"):
29
- logger.error("snippets.yaml not found!")
30
  return {}
31
  with open("snippets.yaml", "r", encoding="utf-8") as f:
32
  try:
33
  return yaml.safe_load(f) or {}
34
- except yaml.YAMLError as e:
35
- logger.error(f"Error parsing snippets.yaml: {e}")
36
  return {}
37
 
38
  snippets = load_snippets()
39
 
40
- dp = Dispatcher()
41
- bot = None # Будет инициализирован в main()
42
-
43
- # ... (остальной код safe_format и обработчиков остается прежним) ...
44
-
45
  def safe_format(text):
46
  text = html.escape(text)
47
  text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text)
48
  text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
49
  return text
50
 
 
 
 
51
  @dp.message(CommandStart())
52
  async def cmd_start(message: types.Message):
53
- bot_info = await bot.get_me()
54
- await message.answer(
55
- f"Helllo! I am an inline bot. Type @{bot_info.username} in any chat to see my snippets."
56
- )
 
57
 
58
  @dp.inline_query()
59
  async def inline_query_handler(query: types.InlineQuery):
@@ -66,70 +55,34 @@ async def inline_query_handler(query: types.InlineQuery):
66
  description = content.split("\n")[0] if content else "No content"
67
  if len(description) > 50:
68
  description = description[:47] + "..."
69
- formatted_content = safe_format(content)
70
  results.append(
71
  InlineQueryResultArticle(
72
  id=key, title=title, description=description,
73
- input_message_content=InputTextMessageContent(message_text=formatted_content, parse_mode="HTML"),
74
  )
75
  )
76
  await query.answer(results[:50], cache_time=1)
77
 
78
- from aiohttp import web, TCPConnector
79
-
80
- class StaticResolver:
81
- async def resolve(self, host, port=0, family=socket.AF_INET):
82
- if host == "api.telegram.org":
83
- # Официальный IP адрес Telegram (один из основных)
84
- return [{"hostname": host, "host": "149.154.167.220", "port": port, "family": family, "proto": 0, "flags": 0}]
85
- return await asyncio.get_event_loop().getaddrinfo(host, port, family=family)
86
-
87
  async def main():
88
- global bot
89
-
90
- # Создаем сессию с нашим статическим резолвером
91
- connector = TCPConnector(resolver=StaticResolver())
92
- session = AiohttpSession(connector=connector)
93
- bot = Bot(token=BOT_TOKEN, session=session)
94
-
95
  app = web.Application()
96
  app.router.add_get("/", health_check)
97
  runner = web.AppRunner(app)
98
  await runner.setup()
99
- site = web.TCPSite(runner, "0.0.0.0", 7860)
100
- await site.start()
101
 
102
- max_retries = 20
103
- for attempt in range(1, max_retries + 1):
104
  try:
105
  bot_info = await bot.get_me()
106
- logger.info(f"Connected! Bot: @{bot_info.username}")
 
107
  break
108
  except Exception as e:
109
- if attempt == max_retries:
110
- logger.error("Failed to connect. Exiting.")
111
- return
112
- logger.warning(f"Attempt {attempt} failed... ({e})")
113
  await asyncio.sleep(5)
114
-
115
- await dp.start_polling(bot)
116
 
117
  if __name__ == "__main__":
118
- import sys
119
-
120
- if "--worker" in sys.argv or os.name != 'nt' or os.environ.get("DOCKER_ENV"):
121
- try:
122
- if os.name == 'nt':
123
- os.system(f"title CollapseBot Logs")
124
-
125
- asyncio.run(main())
126
- except (KeyboardInterrupt, SystemExit):
127
- logger.info("Bot stopped!")
128
- else:
129
- try:
130
- subprocess.Popen(
131
- [sys.executable, "manager.py"],
132
- creationflags=subprocess.CREATE_NEW_CONSOLE
133
- )
134
- except Exception as e:
135
- asyncio.run(main())
 
 
 
 
 
 
1
  import asyncio
2
  import logging
3
  import yaml
4
  import os
 
5
  import re
6
  import html
 
7
  from aiogram import Bot, Dispatcher, types, F
8
  from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
9
  from aiogram.filters import CommandStart
10
+ from aiohttp import web
 
11
  from config import BOT_TOKEN
12
 
13
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
18
 
19
  def load_snippets():
20
  if not os.path.exists("snippets.yaml"):
 
21
  return {}
22
  with open("snippets.yaml", "r", encoding="utf-8") as f:
23
  try:
24
  return yaml.safe_load(f) or {}
25
+ except:
 
26
  return {}
27
 
28
  snippets = load_snippets()
29
 
 
 
 
 
 
30
  def safe_format(text):
31
  text = html.escape(text)
32
  text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text)
33
  text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
34
  return text
35
 
36
+ bot = Bot(token=BOT_TOKEN)
37
+ dp = Dispatcher()
38
+
39
  @dp.message(CommandStart())
40
  async def cmd_start(message: types.Message):
41
+ try:
42
+ bot_info = await bot.get_me()
43
+ await message.answer(f"Hello! I am an inline bot. Type @{bot_info.username} in any chat to see my snippets.")
44
+ except:
45
+ await message.answer("Hello! I am an inline bot. Type my username in any chat to see my snippets.")
46
 
47
  @dp.inline_query()
48
  async def inline_query_handler(query: types.InlineQuery):
 
55
  description = content.split("\n")[0] if content else "No content"
56
  if len(description) > 50:
57
  description = description[:47] + "..."
 
58
  results.append(
59
  InlineQueryResultArticle(
60
  id=key, title=title, description=description,
61
+ input_message_content=InputTextMessageContent(message_text=safe_format(content), parse_mode="HTML"),
62
  )
63
  )
64
  await query.answer(results[:50], cache_time=1)
65
 
 
 
 
 
 
 
 
 
 
66
  async def main():
 
 
 
 
 
 
 
67
  app = web.Application()
68
  app.router.add_get("/", health_check)
69
  runner = web.AppRunner(app)
70
  await runner.setup()
71
+ await web.TCPSite(runner, "0.0.0.0", 7860).start()
 
72
 
73
+ logger.info("Starting bot connection loop...")
74
+ for attempt in range(1, 21):
75
  try:
76
  bot_info = await bot.get_me()
77
+ logger.info(f"Connected! Starting bot @{bot_info.username}")
78
+ await dp.start_polling(bot)
79
  break
80
  except Exception as e:
81
+ logger.warning(f"Attempt {attempt}/20 failed: {e}")
 
 
 
82
  await asyncio.sleep(5)
 
 
83
 
84
  if __name__ == "__main__":
85
+ try:
86
+ asyncio.run(main())
87
+ except (KeyboardInterrupt, SystemExit):
88
+ logger.info("Bot stopped!")