W1xced commited on
Commit
67bedca
·
verified ·
1 Parent(s): 229bf89

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +25 -32
main.py CHANGED
@@ -8,11 +8,15 @@ import logging
8
  import yaml
9
  import os
10
  import subprocess
 
 
 
11
  from aiogram import Bot, Dispatcher, types, F
12
  from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
13
  from aiogram.filters import CommandStart
 
 
14
  from config import BOT_TOKEN
15
- from aiohttp import web
16
 
17
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
18
  logger = logging.getLogger(__name__)
@@ -33,18 +37,14 @@ def load_snippets():
33
 
34
  snippets = load_snippets()
35
 
36
- bot = Bot(token=BOT_TOKEN)
 
 
 
 
37
  dp = Dispatcher()
38
 
39
- @dp.message(CommandStart())
40
- async def cmd_start(message: types.Message):
41
- bot_info = await bot.get_me()
42
- await message.answer(
43
- f"Hello! I am an inline bot. Type @{bot_info.username} in any chat to see my snippets."
44
- )
45
-
46
- import re
47
- import html
48
 
49
  def safe_format(text):
50
  text = html.escape(text)
@@ -52,38 +52,31 @@ def safe_format(text):
52
  text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
53
  return text
54
 
 
 
 
 
 
 
 
55
  @dp.inline_query()
56
  async def inline_query_handler(query: types.InlineQuery):
57
  query_text = query.query.lower().strip()
58
  results = []
59
-
60
  for key, data in snippets.items():
61
  title = data.get("title", key)
62
  content = data.get("content", "")
63
-
64
- if (
65
- not query_text
66
- or query_text in key.lower()
67
- or query_text in title.lower()
68
- or query_text in content.lower()
69
- ):
70
  description = content.split("\n")[0] if content else "No content"
71
  if len(description) > 50:
72
  description = description[:47] + "..."
73
-
74
  formatted_content = safe_format(content)
75
-
76
  results.append(
77
  InlineQueryResultArticle(
78
- id=key,
79
- title=title,
80
- description=description,
81
- input_message_content=InputTextMessageContent(
82
- message_text=formatted_content, parse_mode="HTML"
83
- ),
84
  )
85
  )
86
-
87
  await query.answer(results[:50], cache_time=1)
88
 
89
  async def main():
@@ -94,17 +87,17 @@ async def main():
94
  site = web.TCPSite(runner, "0.0.0.0", 7860)
95
  await site.start()
96
 
97
- max_retries = 10
98
  for attempt in range(1, max_retries + 1):
99
  try:
100
  bot_info = await bot.get_me()
101
- logger.info(f"Connected to Telegram! Starting bot @{bot_info.username}")
102
  break
103
  except Exception as e:
104
  if attempt == max_retries:
105
- logger.error(f"Failed to connect to Telegram after {max_retries} attempts. Exiting.")
106
  return
107
- logger.warning(f"Network not ready (Attempt {attempt}/{max_retries}). Retrying in 5s... Error: {e}")
108
  await asyncio.sleep(5)
109
 
110
  await dp.start_polling(bot)
 
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')
22
  logger = logging.getLogger(__name__)
 
37
 
38
  snippets = load_snippets()
39
 
40
+ # Создаем сессию с принудительным IPv4
41
+ session = AiohttpSession(
42
+ connector=TCPConnector(family=socket.AF_INET, use_dns_cache=False)
43
+ )
44
+ bot = Bot(token=BOT_TOKEN, session=session)
45
  dp = Dispatcher()
46
 
47
+ # ... (остальной код safe_format и обработчиков остается прежним) ...
 
 
 
 
 
 
 
 
48
 
49
  def safe_format(text):
50
  text = html.escape(text)
 
52
  text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
53
  return text
54
 
55
+ @dp.message(CommandStart())
56
+ async def cmd_start(message: types.Message):
57
+ bot_info = await bot.get_me()
58
+ await message.answer(
59
+ f"Helllo! I am an inline bot. Type @{bot_info.username} in any chat to see my snippets."
60
+ )
61
+
62
  @dp.inline_query()
63
  async def inline_query_handler(query: types.InlineQuery):
64
  query_text = query.query.lower().strip()
65
  results = []
 
66
  for key, data in snippets.items():
67
  title = data.get("title", key)
68
  content = data.get("content", "")
69
+ if not query_text or query_text in key.lower() or query_text in title.lower() or query_text in content.lower():
 
 
 
 
 
 
70
  description = content.split("\n")[0] if content else "No content"
71
  if len(description) > 50:
72
  description = description[:47] + "..."
 
73
  formatted_content = safe_format(content)
 
74
  results.append(
75
  InlineQueryResultArticle(
76
+ id=key, title=title, description=description,
77
+ input_message_content=InputTextMessageContent(message_text=formatted_content, parse_mode="HTML"),
 
 
 
 
78
  )
79
  )
 
80
  await query.answer(results[:50], cache_time=1)
81
 
82
  async def main():
 
87
  site = web.TCPSite(runner, "0.0.0.0", 7860)
88
  await site.start()
89
 
90
+ max_retries = 20 # Увеличим количество попыток
91
  for attempt in range(1, max_retries + 1):
92
  try:
93
  bot_info = await bot.get_me()
94
+ logger.info(f"Connected to Telegram! Bot: @{bot_info.username}")
95
  break
96
  except Exception as e:
97
  if attempt == max_retries:
98
+ logger.error("Failed to connect. Exiting.")
99
  return
100
+ logger.warning(f"Attempt {attempt} failed, retrying... ({e})")
101
  await asyncio.sleep(5)
102
 
103
  await dp.start_polling(bot)