pizda-bot/main.py
Administrator 4dd6eaa729 refactor
2023-02-20 19:30:25 +03:00

125 lines
4.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from random import randrange
import telebot
from cachetools import TTLCache
from telebot.types import Message
import settings
from mongo import mongo
bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
all_letters = "йцукенгшщзхъёфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪЁФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890 "
answers = [
[{"да", "дa"}, "Пизда!"],
[{"da", "dа"}, "Pizda!"],
[{'нет', 'нeт', 'hет', 'heт'}, "Пидора ответ!"],
[{"net", "nеt"}, "Pidora otvet!"],
[{"где", "гдe"}, "В пизде!"],
[{"gde", "gdе"}, "V pizde!"],
[{"300", "триста"}, "Отсоси у тракториста!"],
[{"a", "а"}, "Хуй на!"],
[{"че", "чё", "чe", "чо", "чo"}, "Хуй через плечо!"],
[{"ага", "ога"}, "В жопе нога!"],
[{"как"}, "Жопой об косяк!"],
[{"кто"}, "Конь в пальто!"],
[{"200", "двести"}, "Отсоси на месте!"],
[{"слышь", "слыш"}, "За углом поссышь!"],
[{"здрасте", "здрасьте"}, "Пизду покрасьте!"],
[{"ладно"}, "Прохладно!"]
]
cache = TTLCache(settings.CACHE_SIZE, settings.CACHE_TTL)
def get_chat_info(chat_id: int) -> dict:
cached_info = cache.get(chat_id)
if cached_info is not None:
return cached_info
mongo_info = mongo.chats_collection.find_one({"chat_id": chat_id})
if mongo_info is not None:
cache[chat_id] = mongo_info
return mongo_info
chat_info = {"chat_id": chat_id, "state": "default", "probability": 100}
mongo.chats_collection.insert_one(chat_info)
cache[chat_id] = chat_info
return chat_info
def set_values(chat_id: int, **values):
cached_info = cache.get(chat_id)
if cached_info is None:
mongo_info = mongo.chats_collection.find_one({"chat_id": chat_id})
if mongo_info is None:
chat_info = {"chat_id": chat_id, "state": "default", "probability": 100}
chat_info.update(values)
mongo.chats_collection.insert_one(chat_info)
cache[chat_id] = chat_info
else:
mongo.chats_collection.update_one({"chat_id": chat_id}, {"$set": values})
mongo_info = dict(mongo_info)
mongo_info.update(values)
cache[chat_id] = mongo_info
else:
cached_info.update(values)
mongo.chats_collection.update_one({"chat_id": chat_id}, {"$set": values})
@bot.message_handler(commands=['setprobability'])
def set_probability(message: Message):
bot.send_message(message.chat.id, "Отправь одно число - вероятность парирования")
set_values(message.chat.id, state="set_probability")
@bot.message_handler(commands=['rating'])
def show_rating(message: Message):
rating = list(mongo.counter_collection.find({"chat_id": message.chat.id}).sort("count", -1))
if not rating:
bot.send_message(message.chat.id, "В этом чате я пока никому не парировал")
return
text = "Вот кому я парировал:\n"
rating_arr = list(enumerate(rating))
total = 0
for _, value in rating_arr:
total += value['count']
for index, value in rating_arr:
text += f"{index + 1}. @{value['username']} - {value['count']} ({int(value['count'] / total * 100)}%)\n"
bot.send_message(message.chat.id, text)
@bot.message_handler()
def do_action(message: Message):
info = get_chat_info(message.chat.id)
if info['state'] == "set_probability":
try:
value = int(message.text)
if value < 0 or value > 100:
bot.reply_to(message, "Число не попадает в диапозон от 0 до 100!")
else:
set_values(message.chat.id, probability=value, state="default")
bot.reply_to(message, "Ок! Установил")
except ValueError:
bot.reply_to(message, "Это не число!")
return
convert_text = ''.join([letter for letter in message.text if letter in all_letters]).lower().split()
if len(convert_text) > 0:
convert_text = convert_text[-1]
else:
return
ans = None
for key, value in answers:
if convert_text in key:
ans = value
break
if ans is not None and randrange(1, 101) <= info["probability"]:
bot.reply_to(message, ans)
mongo.inc(message.from_user.username, message.chat.id)
bot.polling()