add blacklist
This commit is contained in:
71
db.py
71
db.py
@@ -1,7 +1,10 @@
|
|||||||
|
import datetime
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import configparser
|
import configparser
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import logging
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
config_path = os.path.join(sys.path[0], 'settings.ini')
|
config_path = os.path.join(sys.path[0], 'settings.ini')
|
||||||
config = configparser.ConfigParser()
|
config = configparser.ConfigParser()
|
||||||
@@ -9,6 +12,34 @@ config.read(config_path)
|
|||||||
LOGS = config.getboolean('Settings', 'logs')
|
LOGS = config.getboolean('Settings', 'logs')
|
||||||
IMPORTANT_LOGS = config.get('Telegram', 'important_logs')
|
IMPORTANT_LOGS = config.get('Telegram', 'important_logs')
|
||||||
|
|
||||||
|
# Инициализация логгера
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# Формат записи логов
|
||||||
|
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s')
|
||||||
|
|
||||||
|
# Получение сегодняшней даты для имени файла
|
||||||
|
today = datetime.date.today().strftime('%Y-%m-%d')
|
||||||
|
filename = f'helper_bot_{today}.log'
|
||||||
|
|
||||||
|
# Создание обработчика для файла логов
|
||||||
|
file_handler = RotatingFileHandler(
|
||||||
|
filename,
|
||||||
|
mode='a',
|
||||||
|
maxBytes=10 * 1024 * 1024, # Максимальный размер файла (10 МБ)
|
||||||
|
backupCount=3 # Количество резервных файлов
|
||||||
|
)
|
||||||
|
file_handler.setFormatter(formatter)
|
||||||
|
|
||||||
|
# Добавление обработчика к логгеру
|
||||||
|
logger.addHandler(file_handler)
|
||||||
|
|
||||||
|
# Добавление стандартного обработчика
|
||||||
|
# чтобы сообщения также отображались на консоли
|
||||||
|
console_handler = logging.StreamHandler()
|
||||||
|
console_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(console_handler)
|
||||||
|
|
||||||
class BotDB:
|
class BotDB:
|
||||||
|
|
||||||
@@ -200,7 +231,45 @@ class BotDB:
|
|||||||
except sqlite3.Error as error:
|
except sqlite3.Error as error:
|
||||||
print(error)
|
print(error)
|
||||||
|
|
||||||
|
def get_users_blacklist(self):
|
||||||
|
"""Возвращает список пользователей в черном списке"""
|
||||||
|
try:
|
||||||
|
result = self.cursor.execute("SELECT user_id, user_name FROM `blacklist`")
|
||||||
|
fetch_all = result.fetchall()
|
||||||
|
list_of_users = {}
|
||||||
|
for i in fetch_all:
|
||||||
|
list_of_users[i[0]] = i[1]
|
||||||
|
return list_of_users
|
||||||
|
except sqlite3.Error as error:
|
||||||
|
print(error)
|
||||||
|
|
||||||
|
|
||||||
|
def get_blacklist_users_by_filters(self):
|
||||||
|
"""Возвращает список пользователей в черном списке по фильтру"""
|
||||||
|
return None
|
||||||
|
|
||||||
|
def set_user_blacklist(self, user_id, user_name=None, message_for_user=None, date_to_unban=None):
|
||||||
|
"""Добавляет пользователя в черный список"""
|
||||||
|
try:
|
||||||
|
result = self.cursor.execute("INSERT INTO 'blacklist' ('user_id', 'user_name',"
|
||||||
|
" 'message_for_user', 'date_to_unban') VALUES (?, ?, ?, ?)",
|
||||||
|
(user_id, user_name, message_for_user, date_to_unban,))
|
||||||
|
return self.conn.commit()
|
||||||
|
except sqlite3.Error as error:
|
||||||
|
print(error)
|
||||||
|
|
||||||
|
def delete_user_blacklist(self, user_id):
|
||||||
|
"""Удаляет пользователя из черного списка"""
|
||||||
|
try:
|
||||||
|
#TODO: Функция всегда возвращает true, даже если такого id нет в таблице
|
||||||
|
self.cursor.execute("DELETE FROM blacklist WHERE user_id = ?", (user_id,))
|
||||||
|
self.conn.commit()
|
||||||
|
logger.info(f"User with ID {user_id} successfull delete.")
|
||||||
|
return True
|
||||||
|
except sqlite3.Error as error:
|
||||||
|
logger.error(f"Error delete user with ID {user_id} from blacklist table: {error}")
|
||||||
|
return False
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
"""Закрываем соединение с БД"""
|
"""Закрываем соединение с БД"""
|
||||||
self.conn.close()
|
self.conn.close()
|
||||||
|
|
||||||
|
|||||||
34
main.py
34
main.py
@@ -3,6 +3,8 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from time import sleep
|
from time import sleep
|
||||||
|
|
||||||
|
import db
|
||||||
from db import BotDB
|
from db import BotDB
|
||||||
import telebot
|
import telebot
|
||||||
import random
|
import random
|
||||||
@@ -35,9 +37,39 @@ BotDB = BotDB('tg-bot-database')
|
|||||||
|
|
||||||
|
|
||||||
def telegram_bot():
|
def telegram_bot():
|
||||||
|
# Черный список
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['admin'], user_id=842766148)
|
||||||
|
def admin_panel(message):
|
||||||
|
try:
|
||||||
|
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
|
||||||
|
item1 = types.KeyboardButton("Забанить пользователя из списка")
|
||||||
|
item2 = types.KeyboardButton("Забанить пользователя по ID")
|
||||||
|
markup.add(item1, item2)
|
||||||
|
bot.send_message(message.chat.id,"Добро пожаловать в админку. Выбери что хочешь:", reply_markup=markup)
|
||||||
|
bot.register_next_step_handler(message, ban_user)
|
||||||
|
except Exception as e:
|
||||||
|
bot.register_next_step_handler(message, admin_panel)
|
||||||
|
|
||||||
|
|
||||||
|
def ban_user(message):
|
||||||
|
# проверяем, что ID передан правильно
|
||||||
|
#TODO: остановился где-то тут, функция не дописана. Хотел сделать админку + бан пользователей
|
||||||
|
try:
|
||||||
|
if message.text == "Забанить пользователя из списка":
|
||||||
|
pass
|
||||||
|
elif message.text == "Забанить пользователя по ID":
|
||||||
|
bot.send_message(message.chat.id, "Пришли ID юзера")
|
||||||
|
BotDB.set_user_blacklist(ban_user_id)
|
||||||
|
bot.reply_to(message, f"Пользователь {ban_user_id} заблокирован.")
|
||||||
|
except Exception as e:
|
||||||
|
bot.reply_to(message, f"Укажи ID пользователя. Ошибка\n\n {e}")
|
||||||
|
bot.register_next_step_handler(message, ban_user)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@bot.message_handler(commands=['start'])
|
@bot.message_handler(commands=['start'])
|
||||||
def send_welcome(message):
|
def send_welcome(message):
|
||||||
# TODO: Здесь переписать через randint
|
|
||||||
# TODO: Тексты приветствий вынести в отдельный файл
|
# TODO: Тексты приветствий вынести в отдельный файл
|
||||||
try:
|
try:
|
||||||
name_stick_hello = list(Path('Stick').rglob('Hello_*'))
|
name_stick_hello = list(Path('Stick').rglob('Hello_*'))
|
||||||
|
|||||||
Reference in New Issue
Block a user