Repository: SigachevAV/CapitallProphet
Pull request #1: Syntax & grammar fixes
Author: login: belinmikh
Created: 2025-03-16T22:32:16Z | Merged: 2025-03-30T10:22:45Z



Diff:
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..bf41cf5
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,2 @@
+TELEGRAM_TOKEN=your_token
+LOG_LEVEL=INFO
\ No newline at end of file
diff --git a/index.py b/index.py
index 1f0c6b6..2a010d2 100644
--- a/index.py
+++ b/index.py
@@ -1,68 +1,117 @@
+import logging
+import os
+import random
+import re
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
-    html = BeautifulSoup(res.content, "lxml")
-    list = []
-    i = 2
-    for element in html.findAll("p"):
-        if(i>0):
-            i-=1
-            continue
-        if(element.text == '\xa0'):
-            continue
-        list.append(element.text)
-    _st-=1
-    if(_st < 0):
-        _st = 0
-    elif(_st>len(list)):
-        _st=len(list)-1
-    if(len(list[_st])>4090):
-        list[_st]=len[_st][0:4090]
-    return list[_st]
-
-bot = telebot.TeleBot(os.environ["TELEGRAM_TOKEN"])
-
-@bot.message_handler(commands=['random'])
-def randomProphet(message):
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def Req(_page: int, _line: int):
+    if (_page > 66):
+        _page = 66
+    elif (_page < 1):
+        _page = 1
     try:
-        bot.send_message(message.chat.id, Req(random.randint(1, 66), random.randint(0, 100)))
-    except:
-        bot.send_message(message.chat.id, "Будущеее туманно")
-
-@bot.message_handler(commands=['prophet'])
-def prophet(message):
-    text =re.findall('[0-9]*', message.text)
-    page = 0
-    stringg = 0
+        res = requests.get(
+            "https://www.marxists.org/russkij/marx/1867/capital_vol1/"
+            f"{_page:02d}.htm"
+        )
+        html = BeautifulSoup(res.content, "lxml")
+        lst = []
+        i = 2
+        for element in html.find_all("p"):
+            if (i > 0):
+                i -= 1
+                continue
+            if (element.text == "\xa0"):
+                continue
+            lst.append(element.text)
+        _line -= 1
+        if (_line < 0):
+            _line = 0
+        elif (_line > len(lst)):
+            _line = len(lst) - 1
+        if (len(lst[_line]) > 4090):
+            lst[_line] = lst[_line][0:4090]
+        logging.info("request resolved")
+        return lst[_line]
+    except Exception as ex:
+        logging.error(f"request failed: {ex}")
+        raise ReqException(ex)
+
+
+load_dotenv()
+bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
+log_level = os.getenv("LOG_LEVEL")
+logging.basicConfig(
+    level=log_level,
+    format='%(asctime)s - %(levelname)s - %(message)s'
+)
+
+
+@bot.message_handler(commands=["random"])
+def RandomProphetCmd(_message):
     try:
-        stringg=int(text[11])
-        page=int(text[9])
-    except:
-        bot.send_message(message.chat.id, "Запрос задан неверно")
-        return
+        bot.send_message(
+            _message.chat.id, Req(random.randint(1, 66), random.randint(0, 100))
+        )
+        logging.info("/random executed")
+    except Exception as ex:
+        bot.send_message(_message.chat.id, "Будущее туманно")
+        logging.error(f"/random failed: {ex}")
+
+
+@bot.message_handler(commands=["prophet"])
+def ProphetCmd(_message):
+    text = re.findall("[0-9]*", _message.text)
     try:
-        bot.send_message(message.chat.id, Req(page, stringg))
-    except:
-         bot.send_message(message.chat.id, "Боюсь на эту часть книги пролили кофе")   
-            
-@bot.message_handler(commands=['help'])
-def help(message):
-    bot.send_message(message.chat.id, "/prophet {глава} {строка}\nвведите после команды 2 числа через пробел которые будут означать главу капиталла (от 1 до 66) и строку в ней\nНекоторые строки являються таблицами и по этому предсказания по ним не будет.\n/random\nдаёт вам случайную строку")
-         
-@bot.message_handler(command=['start'])
-def start(message):
-    bot.send_message(message.chat.id, "Этот бот будет гадать на капиталле")
-    help(message=message)
-
-bot.polling(none_stop=True)
+        line = int(text[11])
+        page = int(text[9])
+        bot.send_message(_message.chat.id, Req(page, line))
+        logging.info("/prophet executed")
+    except ReqException as rex:
+        bot.send_message(
+            _message.chat.id,
+            "Боюсь, на эту часть книги пролили кофе"
+        )
+        logging.error(f"/prophet failed at request: {rex}")
+    except Exception as ex:
+        bot.send_message(_message.chat.id, "Запрос задан неверно")
+        logging.error(f"/prophet failed: {ex}")
+
+
+@bot.message_handler(commands=["help"])
+def HelpCmd(_message, _cascade: bool = False):
+    bot.send_message(
+        _message.chat.id,
+        "/prophet {глава} {строка}\n\n"
+        " - введите после названия команды 2 числа через пробел: "
+        "номер главы и номер строки\n"
+        "Некоторые строки являются таблицами, "
+        "поэтому предсказание осуществимо не всегда!\n\n"
+        "/random\n\n"
+        " - даёт вам случайную строку",
+    )
+    if not _cascade:
+        logging.info("/help executed")
+
+
+@bot.message_handler(commands=["start"])
+def StartCmd(_message):
+    bot.send_message(
+        _message.chat.id,
+        'Этот бот гадает на "Капитале" К. Маркса'
+    )
+    logging.info("/start executed")
+    HelpCmd(_message=_message, _cascade=True)
+
+
+if __name__ == "__main__":
+    logging.info("polling started")
+    bot.polling(non_stop=True)
diff --git a/requirements.txt b/requirements.txt
index 21dbd3a..557ed78 100644
Binary files a/requirements.txt and b/requirements.txt differ


Reviews:
user: login: SigachevAV
state: CHANGES_REQUESTED
author_association: OWNER
submitted_at: 2025-03-16T23:55:02Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:11:25Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:11:34Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:11:40Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:12:27Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:12:44Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:13:09Z
user: login: SigachevAV
state: COMMENTED
author_association: OWNER
submitted_at: 2025-03-17T01:30:05Z
user: login: SigachevAV
state: APPROVED
author_association: OWNER
submitted_at: 2025-03-17T01:38:10Z
user: login: belinmikh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T01:39:28Z

Review comments:
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
+    if page > 66:
+        page = 66
+    elif page < 1:
+        page = 1
+    res = requests.get(
+        "https://www.marxists.org/russkij/marx/1867/capital_vol1/"
+        f"{page:02d}.htm"
+    )
     html = BeautifulSoup(res.content, "lxml")
-    list = []
+    lst = []
     i = 2
-    for element in html.findAll("p"):
-        if(i>0):
path: index.py
user: login: SigachevAV
body: Скобочки обязательные
created_at: 2025-03-16T23:47:26Z
author_association: OWNER
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
+    if page > 66:
+        page = 66
+    elif page < 1:
+        page = 1
+    res = requests.get(
+        "https://www.marxists.org/russkij/marx/1867/capital_vol1/"
+        f"{page:02d}.htm"
+    )
     html = BeautifulSoup(res.content, "lxml")
-    list = []
+    lst = []
     i = 2
-    for element in html.findAll("p"):
-        if(i>0):
-            i-=1
+    for element in html.find_all("p"):
path: index.py
user: login: SigachevAV
body: Расскажи, в чём разница между этими двумя методами?
created_at: 2025-03-16T23:47:58Z
author_association: OWNER
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
path: index.py
user: login: SigachevAV
body: Входные аргументы должны начинаться с нижнего подчёркивания. Функции должны начинаться с большой буквы, если они не являются членами класса.
created_at: 2025-03-16T23:49:49Z
author_association: OWNER
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
path: index.py
user: login: SigachevAV
body: Пустую строчку убери, между импортами не должно быть пустых строчек.
created_at: 2025-03-16T23:50:47Z
author_association: OWNER
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
path: index.py
user: login: SigachevAV
body: Исключение объявлено, но нигде не выкидывается, зачем?!
created_at: 2025-03-16T23:53:28Z
author_association: OWNER
path: requirements.txt
user: login: SigachevAV
body: Ты уверен что нужные все эти зависимости?
created_at: 2025-03-16T23:54:58Z
author_association: OWNER
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
path: index.py
user: login: belinmikh
body: Уберу, но пустая строчка ставится между дефолтными и установленными библиотеками
created_at: 2025-03-17T01:11:25Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
path: index.py
user: login: belinmikh
body: Исправлено
created_at: 2025-03-17T01:11:33Z
author_association: CONTRIBUTOR
path: requirements.txt
user: login: belinmikh
body: Исправлено
created_at: 2025-03-17T01:11:40Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
path: index.py
user: login: belinmikh
body: Исправлено, но грубо не соответствует PEP
created_at: 2025-03-17T01:12:27Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
+    if page > 66:
+        page = 66
+    elif page < 1:
+        page = 1
+    res = requests.get(
+        "https://www.marxists.org/russkij/marx/1867/capital_vol1/"
+        f"{page:02d}.htm"
+    )
     html = BeautifulSoup(res.content, "lxml")
-    list = []
+    lst = []
     i = 2
-    for element in html.findAll("p"):
-        if(i>0):
-            i-=1
+    for element in html.find_all("p"):
path: index.py
user: login: belinmikh
body: findAll is deprecated
created_at: 2025-03-17T01:12:44Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,68 +1,101 @@
+import logging
+import os
+import random
+import re
+
 import requests
 import telebot
 from bs4 import BeautifulSoup
-import random
-import re
-import os
-def Req(_page : int, _st : int):
-    if(_page>66):
-        _page=66
-    elif(_page<1):
-        _page=1
-    if(_page<10):
-        _page="0"+str(_page)
-    res = requests.get("https://www.marxists.org/russkij/marx/1867/capital_vol1/"+ str(_page) + ".htm")
+from dotenv import load_dotenv
+
+
+class ReqException(Exception):
+    pass
+
+
+def req(page: int, line: int):
+    if page > 66:
+        page = 66
+    elif page < 1:
+        page = 1
+    res = requests.get(
+        "https://www.marxists.org/russkij/marx/1867/capital_vol1/"
+        f"{page:02d}.htm"
+    )
     html = BeautifulSoup(res.content, "lxml")
-    list = []
+    lst = []
     i = 2
-    for element in html.findAll("p"):
-        if(i>0):
path: index.py
user: login: belinmikh
body: Исправлено, но не соответствует PEP
created_at: 2025-03-17T01:13:09Z
author_association: CONTRIBUTOR
path: requirements.txt
user: login: SigachevAV
body: требуются пояснения к каждой новой зависимости.
created_at: 2025-03-17T01:30:05Z
author_association: OWNER
path: requirements.txt
user: login: belinmikh
body: Новая зависимость python-dotenv - каноничная работа с переменными окружения в python. Подзависимости исключены
created_at: 2025-03-17T01:39:28Z
author_association: CONTRIBUTOR

PR comments:
user: login: SigachevAV
created_at: 2025-03-16T23:58:38Z
body: Дополнительные вопросы.

1. ты проверил работоспособность в докер контейнере?
2. Почему мы логируем ошибки но не логируем успешные запросы? не порядок
author_association: OWNER
user: login: belinmikh
created_at: 2025-03-26T20:40:43Z
body: В докер контейнере работает
author_association: CONTRIBUTOR