From fd069a9615ca32b63d80dd48651e7616b7837cd5 Mon Sep 17 00:00:00 2001 From: Rykov7 Date: Sat, 25 Feb 2023 19:33:39 +0300 Subject: [PATCH] add database --- Stan.txt | 8 +----- app/bot.py | 18 ++++++------ app/config.py | 3 +- app/database.py | 13 +++++++++ app/models.py | 30 ++++++++++++++++++++ app/stan.py | 70 ++++++++++++++++++++++------------------------- requirements.txt | Bin 576 -> 600 bytes 7 files changed, 88 insertions(+), 54 deletions(-) create mode 100644 app/database.py create mode 100644 app/models.py diff --git a/Stan.txt b/Stan.txt index f1f3131..9b289b1 100644 --- a/Stan.txt +++ b/Stan.txt @@ -147,7 +147,6 @@ I'm not hear for jokes, strictly business. уже не весело, когда знаешь что внутри робота человек как в сколково где мы свернули не туда? о, экспертов биржетрейдеров завезли -Люди код на низкоуровневых языках пишут, покупают штучные процессоры на аукционах, сервера подключают к дорогим каналам бирж, лишь бы лишнюю миллисекунду выйграть при высокочастотном трейдинге. А тут на питоне парни к успеху идут. Как-то так да. Та ну ты совсем уже? В браузер вставь К субботе готов Ну можно гит клон попробовать @@ -166,14 +165,11 @@ I'm not hear for jokes, strictly business. не мог до завтра дотерпеть? одмену пожалуюсь хипстер? -ну, такие примеры, как у них анимировано, только нубы пишут... а для рефакторинга нормального кода мне и в пайчарме средств хватает лишь бы доку не читать я что-то такое тоже хотел уточнить, но передумал -не стоит изучать эту тему. Ты программист, со стройной логикой, написание ООП кода дается легко. Это не то. Это не Лисп и даже не архивы фортрана. Сюда лучше не лезть. Серьезно, любой успешный из программист будет жалеть. Лучше закрой учебник и забудь, как писалась гипергеометрическая функция. Я вполне понимаю, что данным сообщением вызову дополнительный интерес, но хочу сразу предостеречь пытливых - стоп. Остальные просто не вытянут. ифелсе форева!! Это резольвента. Мы её тензорно умножили на саму себя. Но в градуированном смысле. чо еще проще-то??? -Вот теория групп хотя бы имеет связь с реальностью через квантомеханические представления, колебания осцилляторов и симметрии(будь проклято это слово) кристаллов/молекул/атомов. Кстати с теорией групп - разработана Галуа, который прожил всего 20 лет. Какой нормальный человек может всё это понимать не страдай... наслаждайся нормальной жизнью @@ -196,7 +192,6 @@ I'm not hear for jokes, strictly business. По моему тебе просто неохота из зоны комфорта выходить. Где-то всю жизнь по пальмам лазят да листами жопу прикрывают. И не нужны им айфоны и теслы Та у них просто розеток на пальмах нет, заряжать айфон и теслу -Другой вопрос, когда вроде и комфортно, но хочется большего. И тогда зона комфорта превращается в вонючее теплое болотце весь вопрос в наличии целей - есть цели и идешь к ним по шагам - ничего в ничего не превращается ему б н азаводике попахать годок другой за копеечки лучше обоев зобанеть @@ -353,7 +348,6 @@ facepalm.jpg да штош это, блин, такое не спится человеку, курлит с утра не бережешь ты себя, золотой ты человек -🦔 наш человек че там хренасси год начинается, в чате питон обсуждают Кто ищет - тот всегда найдёт @@ -362,4 +356,4 @@ facepalm.jpg сие зело меня печалит у каждого был такой знакомый... Гвидо наносит ответный удар -If you are new to anything, follow tutorials +If you are new to something, follow tutorials diff --git a/app/bot.py b/app/bot.py index 3783304..2064fca 100644 --- a/app/bot.py +++ b/app/bot.py @@ -57,8 +57,8 @@ def start(message: types.Message): send_or_reply(message, "Начни с прочтения", reply_markup=markup) -@bot.message_handler(commands=["rules", "rule", "r", "правила", "правило", "п"]) -def send_rules(message): +@bot.message_handler(commands=["rules", "rule", f"r", "правила", "правило", "п"]) +def send_rules(message: types.Message): markup = types.InlineKeyboardMarkup([[RULES]], 1) args = message.text.split() if len(args) > 1 and args[-1].isdigit() and 0 < int(args[-1]): @@ -72,19 +72,19 @@ def send_rules(message): @bot.message_handler(commands=["faq", "чзв"]) -def send_faq(message): +def send_faq(message: types.Message): markup = types.InlineKeyboardMarkup([[FAQ]], 1) send_or_reply(message, "...", reply_markup=markup) @bot.message_handler(commands=["lib", "library", "books", "книги", "библиотека"]) -def send_lib(message): +def send_lib(message: types.Message): markup = types.InlineKeyboardMarkup([[LIB]], 1) send_or_reply(message, "...", reply_markup=markup) @bot.message_handler(commands=["lutz", "лутц"]) -def send_lutz(message): +def send_lutz(message: types.Message): bot.send_document( message.chat.id, document="BQACAgQAAxkBAAPBYsWJG9Ml0fPrnbU9UyzTQiQSuHkAAjkDAAIstCxSkuRbXAlcqeQpBA", @@ -93,7 +93,7 @@ def send_lutz(message): @bot.message_handler(commands=["bdmtss", "бдмтсс"]) -def send_bdmtss_audio(message): +def send_bdmtss_audio(message: types.Message): bot.send_voice( message.chat.id, "AwACAgIAAxkBAAIJrWOg2WUvLwrf7ahyJxQHB8_nqllwAAL5JQAC2_IJSbhfQIO5YnVmLAQ", @@ -101,7 +101,7 @@ def send_bdmtss_audio(message): @bot.message_handler(commands=["tr", "тр"]) -def translate_layout(message): +def translate_layout(message: types.Message): if message.reply_to_message and message.reply_to_message.text: if message.reply_to_message.text[0] in RUS: bot.send_message( @@ -114,8 +114,8 @@ def translate_layout(message): @bot.message_handler(commands=["quote", "цитата"]) -def stan_speak(message): - bot.send_message(message.chat.id, stan.speak(0)) +def stan_speak(message: types.Message): + bot.send_message(message.chat.id, stan.speak(0, message.chat.id)) @bot.message_handler(commands=["tsya", "тся", "ться"]) diff --git a/app/config.py b/app/config.py index 9dcecd9..a11363e 100644 --- a/app/config.py +++ b/app/config.py @@ -23,6 +23,7 @@ bot = TeleBot( allow_sending_without_reply=True, colorful_logs=True, ) +basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) @@ -70,7 +71,7 @@ FAQ = types.InlineKeyboardButton( ) LIB = types.InlineKeyboardButton("📚 Книги", url="https://telegra.ph/what-to-read-10-06") -SPAM = ["me.sv/", "tg.sv/", "goo.by/", "go.sv/", "intim.video/", "uclck.ru/"] +SPAM = ["me.sv/", "tg.sv/", "goo.by/", "go.sv/", "intim.video/", "uclck.ru/", 'П0 ВСЕМ В0ПР0С0М'] NON_GRATA = ["дудар", "хауди", "dudar"] BAN_WORDS = ["GREEN"] diff --git a/app/database.py b/app/database.py new file mode 100644 index 0000000..ccd17f8 --- /dev/null +++ b/app/database.py @@ -0,0 +1,13 @@ +import os +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from .models import Base +basedir = os.path.abspath(os.path.dirname(__file__)) + +engine = create_engine('sqlite:///' + os.path.join(basedir, 'db/db.sqlite')) + + +Base.metadata.create_all(engine) + +Session = sessionmaker(bind=engine) +session = Session() diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..9ef5b34 --- /dev/null +++ b/app/models.py @@ -0,0 +1,30 @@ +from sqlalchemy import Column, String, Integer, Boolean, ForeignKey +from sqlalchemy.orm import relationship, declarative_base + +Base = declarative_base() + + +class Quote(Base): + __tablename__ = "quotes" + id = Column(Integer, primary_key=True) + chat_id = Column(Integer, ForeignKey('chats.chat_id')) + text = Column(String) + + def __repr__(self): + return f"Quote({self.text=}, {self.chat_id=})" + + +class Chat(Base): + __tablename__ = "chats" + id = Column(Integer, primary_key=True) + chat_id = Column(Integer, unique=True) + title = Column(String) + + # Settings + quotes = relationship('Quote', backref='chat') + antispam = Column(Boolean) + report = Column(Boolean) + reminder = Column(Boolean) + + def __repr__(self): + return f'Chat({self.chat_id=}, {self.title=})' diff --git a/app/stan.py b/app/stan.py index 223da9c..35d44ba 100644 --- a/app/stan.py +++ b/app/stan.py @@ -4,14 +4,14 @@ import threading from time import sleep from .config import bot, types from .filters import is_white, is_nongrata +from .database import session +from .models import Quote -def speak(chance_of): +def speak(chance_of, group_id): number = random.randint(0, chance_of) if number == 0: - return random.choice( - [i.rstrip() for i in open("Stan.txt", "r", encoding="utf8") if i] - ) + return random.choice([i[0] for i in session.query(Quote.text).filter(Quote.chat_id == group_id).all()]) def send_quote(after_sec, message, quote): @@ -25,8 +25,8 @@ def send_quote(after_sec, message, quote): bot.send_message(message.chat.id, quote) -def act(message): - quote = speak(50) +def act(message: types.Message): + quote = speak(50, message.chat.id) if quote: threading.Thread( target=send_quote, args=(len(quote) * 0.13, message, quote) @@ -34,49 +34,45 @@ def act(message): @bot.message_handler(func=is_white, commands=["add"]) -def add_stan_quote(message): +def add_stan_quote(message: types.Message): if message.reply_to_message and message.reply_to_message.text: - with open("Stan.txt", "a", encoding="utf8") as stan_quotes: - if message.reply_to_message.text not in ( - i.rstrip() for i in open("Stan.txt", "r", encoding="utf8") - ): - stan_quotes.write( - message.reply_to_message.text.replace("\n", " ") + "\n" - ) - bot.send_message( + if message.reply_to_message.text not in [i[0] for i in session.query(Quote.text).all()]: + session.add(Quote(chat_id=message.chat.id, text=message.reply_to_message.text.replace("\n", " "))) + session.commit() + bot.send_message( message.chat.id, "✅ Добавил\n └ " + message.reply_to_message.text.replace("\n", " ") + "", ) - else: - bot.send_message( - message.chat.id, - f"⛔️ Не добавил, есть токое\n └ {message.reply_to_message.text}", - ) - - -@bot.message_handler(func=is_white, commands=["remove"]) -def remove_stan_quote(message): - if message.reply_to_message and message.reply_to_message.text: - if message.reply_to_message.text in ( - i.rstrip() for i in open("Stan.txt", "r", encoding="utf8") - ): - quotes = list(open("Stan.txt", "r", encoding="utf8")) - with open("Stan.txt", "w", encoding="utf8") as stan_quotes: - quotes.remove(message.reply_to_message.text + "\n") - stan_quotes.writelines(quotes) - bot.send_message( - message.chat.id, - f"✅ Удалил\n └ {message.reply_to_message.text}", - ) else: bot.send_message( message.chat.id, - f"⛔️ Нет такого\n └ {message.reply_to_message.text}", + f"⛔️ Не добавил, есть токое\n └ {message.reply_to_message.text}", ) +# @bot.message_handler(func=is_white, commands=["remove"]) +# def remove_stan_quote(message): +# if message.reply_to_message and message.reply_to_message.text: +# if message.reply_to_message.text in ( +# i.rstrip() for i in open("Stan.txt", "r", encoding="utf8") +# ): +# quotes = list(open("Stan.txt", "r", encoding="utf8")) +# with open("Stan.txt", "w", encoding="utf8") as stan_quotes: +# quotes.remove(message.reply_to_message.text + "\n") +# stan_quotes.writelines(quotes) +# bot.send_message( +# message.chat.id, +# f"✅ Удалил\n └ {message.reply_to_message.text}", +# ) +# else: +# bot.send_message( +# message.chat.id, +# f"⛔️ Нет такого\n └ {message.reply_to_message.text}", +# ) + + @bot.message_handler(func=is_nongrata) def tease_nongrata(message: types.Message): """Reply to non grata mentions.""" diff --git a/requirements.txt b/requirements.txt index 26ca76ba291aa0cc8b2c9e1e96ec71ea4021834e..778377a418f01b35cf6a010886998e9890dec30f 100644 GIT binary patch delta 32 ncmX@Wa)V`q1CsgCj!@Lo!1KLn=cqLnQ+McCH3> delta 7 Ocmcb?a)4!n0}}uYX#$e~