Version 1.0
87
base.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
# ДАННЫЕ БОТА
|
||||
TOKEN = "1791246735:AAF3f6tb4T2Rk8atewn-2-2vQ6Q-DVy41Fc"
|
||||
|
||||
# РИКРОЛЛ
|
||||
RICKROLL_1 = 'https://vk.cc/8U7VuC' # https://www.youtube.com/watch?v=dQw4w9WgXcQ
|
||||
RICKROLL_2 = 'https://vk.cc/3A9NI7' # https://youtu.be/dQw4w9WgXcQ
|
||||
|
||||
# ОБРАЩЕНИЯ К ПОЛЬЗОВАТЕЛЯМ
|
||||
KILL_LIST = ["побить", "отмудохать", "избить", "уебать", "отметелить"]
|
||||
TMOK_LIST = ["поцеловать", "чмокнуть", "соснуть", "лайкнуть"]
|
||||
QUAT_LIST = [['дай', 'дайте'], ['ахуенный', 'ахуеный', 'охуеный', 'охуенный', 'блять', 'сука'], ['совет', 'совета']]
|
||||
|
||||
# ФРАЗЫ ИВЕНТ ДРАКИ
|
||||
VAR_WIN = ["опустив его ниже плинтуса!", "поставив его на место!"]
|
||||
VAR_LOSE = ["Кунг - Фу!", "магии!", "резинового члена!", "банды цапель!"]
|
||||
|
||||
# ПЕРЕВОДЧИК СЛОВ
|
||||
ERR = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';',
|
||||
"'", 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '`']
|
||||
ERR_ = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':',
|
||||
'"', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', '~']
|
||||
TRU = ['й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ', 'з', 'х', 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л', 'д', 'ж',
|
||||
'э', 'я', 'ч', 'с', 'м', 'и', 'т', 'ь', 'б', 'ю', '.']
|
||||
TRU_ = ['Й', 'Ц', 'У', 'К', 'Е', 'Н', 'Г', 'Ш', 'Щ', 'З', 'Х', 'Ъ', 'Ф', 'Ы', 'В', 'А', 'П', 'Р', 'О', 'Л', 'Д', 'Ж',
|
||||
'Э', 'Я', 'Ч', 'С', 'М', 'И', 'Т', 'Ь', 'Б', 'Ю', ',']
|
||||
|
||||
ALB = ['а', 'у', 'о', 'ы', 'и', 'э', 'я', 'ю', 'ё', 'е', 'А', 'У', 'О', 'Ы', 'И', 'Э', 'Я', 'Ю', 'Ё', 'Е']
|
||||
|
||||
|
||||
|
||||
# НА ВСЯКИЙ СЛУЧАЙ
|
||||
|
||||
'''
|
||||
# from filters import IsAdminFilter
|
||||
# activate filters
|
||||
dp.filters_factory.bind(IsAdminFilter)
|
||||
|
||||
# await call.message.answer(str(randint(1, 10)))
|
||||
|
||||
# await message.answer_sticker(r'CAACAgIAAxkBAAECmDFg8_fMoE0ZFAYxOh5KRyB2Y7VGZwACfQ0AAtMv4ElQpS-ysl5_6SAE') # ФУГА ДУМАЕТ
|
||||
|
||||
# state = dp.current_state(chat=config.GROUP_ID, user=message.from_user.id)
|
||||
# await state.set_state(User.accepted)
|
||||
|
||||
# ОСУЖДАЮ
|
||||
for word in base.BAN_LIST:
|
||||
if word in txt:
|
||||
await message.delete()
|
||||
await message.answer("ОСУЖДАЮ")
|
||||
print(name_group, ">>>", message.text)
|
||||
|
||||
for word in base.BAN_NAME:
|
||||
if word in txt and not "егор" in txt:
|
||||
await message.delete()
|
||||
await message.answer("Для обращений существует имя!")
|
||||
print(name_group, ">>", message.text)
|
||||
|
||||
# бан на минуту
|
||||
if len(original) == 2:
|
||||
if "забанься" in txt:
|
||||
await message.bot.restrict_chat_member(chat_id=id_group, user_id=[base.USERS[i][1] for i in base.USERS if i == no_pct.lower().split()[0]][0],
|
||||
permissions=types.ChatPermissions(),
|
||||
until_date=int(time()) + (31))
|
||||
await message.reply(f'{message.from_user.first_name}, по вашему желанию отлетел дурачок на минуту)')
|
||||
|
||||
# админ бан
|
||||
@dp.message_handler(is_admin=True, commands=['ban'], commands_prefix='!/')
|
||||
async def ban(message: types.Message):
|
||||
if not message.reply_to_message:
|
||||
await message.reply("Эта команда должна быть ответом на сообщение!")
|
||||
return
|
||||
|
||||
await message.bot.delete_message(config.GROUP_ID, message.message_id)
|
||||
await message.bot.kick_chat_member(chat_id=config.GROUP_ID, user_id=message.reply_to_message.from_user.id)
|
||||
|
||||
await message.bot.send_photo(chat_id=config.GROUP_ID, photo="1.jpg", caption="Пользователь унижен!\nПоздравляю ;)")
|
||||
|
||||
# чекер данных фото
|
||||
@dp.message_handler(content_types=['photo'])
|
||||
async def scan_message(msg: types.Message):
|
||||
document_id = msg.photo[0].file_id
|
||||
file_info = await bot.get_file(document_id)
|
||||
print(f'file_id: {file_info.file_id}')
|
||||
print(f'file_path: {file_info.file_path}')
|
||||
print(f'file_size: {file_info.file_size}')
|
||||
print(f'file_unique_id: {file_info.file_unique_id}')
|
||||
'''
|
||||
551
bot.py
Normal file
|
|
@ -0,0 +1,551 @@
|
|||
import logging, random, pymorphy2, requests
|
||||
import asyncio, emoji, base, re
|
||||
|
||||
from sql import SQLighter
|
||||
from datetime import datetime
|
||||
from script import cheker, translator, notice, lang_form, times, autozak, update_stat, revers
|
||||
from aiogram import Bot, Dispatcher, executor, types
|
||||
|
||||
# log level
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
# bot init
|
||||
bot = Bot(token=base.TOKEN)
|
||||
dp = Dispatcher(bot)
|
||||
morph = pymorphy2.MorphAnalyzer()
|
||||
|
||||
# инициализируем соединение с БД
|
||||
db = SQLighter('groups.db')
|
||||
|
||||
|
||||
# events
|
||||
@dp.message_handler(content_types=["new_chat_members"])
|
||||
async def notification(message: types.Message):
|
||||
if not db.group_exists(message.chat.id):
|
||||
db.add_group(message.chat.id)
|
||||
db.add_month_group(message.chat.id)
|
||||
db.created_group(message.chat.id)
|
||||
await bot.send_message(message.chat.id, f'ID <b>[ {message.chat.id} ]</b>\n\nДля того, чтобы уведомления по '
|
||||
f'имени и команда /all нормально функционировали, необходимо чтобы '
|
||||
f'каждый участник группы написал хотя бы одно сообщение в чат! Также '
|
||||
f'для того, чтобы системные сообщения удалялись автоматически, '
|
||||
f'необходимо боту выдать права администратора!', types.ParseMode.HTML)
|
||||
else:
|
||||
try:
|
||||
await message.delete()
|
||||
except Exception:
|
||||
print(f'{message.chat.title} >>> НЕ УДАЛОСЬ УДАЛИТЬ СООБЩЕНИЕ')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['start'])
|
||||
async def helps(message: types.Message):
|
||||
if message.chat.id > 0:
|
||||
id_group, user = message.chat.id, message.from_user.id
|
||||
name_db = re.sub(r'[^\w\s]', '', message.from_user.first_name.lower())
|
||||
try:
|
||||
if not db.user_exists(user, id_group):
|
||||
db.add_user(user, name_db, id_group)
|
||||
else:
|
||||
if user in db.get_users(id_group):
|
||||
db.update_name(user, name_db, id_group)
|
||||
except Exception as e:
|
||||
await message.answer("Вы запустили бота в личном чате! Для работы в группе или в общем чате нечего делать "
|
||||
"не надо, лишь добавить в чат и выдать права на удаление сообщений в чате!\n\n- Для "
|
||||
"введения в обширный функционал бота можете воспользоваться командой /help!")
|
||||
db.add_group(id_group)
|
||||
db.add_month_group(id_group)
|
||||
db.created_group(id_group)
|
||||
db.add_user(user, name_db, id_group)
|
||||
else:
|
||||
return
|
||||
|
||||
|
||||
@dp.message_handler(commands=['help'])
|
||||
async def helps(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
|
||||
buttons = [types.InlineKeyboardButton(text="КОМАНДЫ", callback_data="com"),
|
||||
types.InlineKeyboardButton(text="ИВЕНТЫ", callback_data="even"),
|
||||
types.InlineKeyboardButton(text="ОШИБКИ", callback_data="err"),
|
||||
types.InlineKeyboardButton(text="АВТОР", callback_data="auth"),
|
||||
types.InlineKeyboardButton(text="ФУНКЦИИ", callback_data="fun")]
|
||||
|
||||
keyboard = types.InlineKeyboardMarkup(row_width=2)
|
||||
keyboard.add(*buttons)
|
||||
|
||||
await bot.send_voice(chat_id=message.chat.id, voice=open('data/tts.ogg', 'rb'),
|
||||
caption='*-* Этот АБОБОТ поможет вам приятно провести время в чате с различными командами, '
|
||||
'ивентами и удобными функциями, которые облегчают использование чата)\n\n'
|
||||
'*-* Также прошу если вам понравился бот, оставить отзыв о его использовании на '
|
||||
'команду /report)', parse_mode=types.ParseMode.MARKDOWN, reply_markup=keyboard)
|
||||
|
||||
|
||||
# ИЛАЙН КЛАВИАТУРА HELP
|
||||
@dp.callback_query_handler(text="err")
|
||||
async def error(call: types.CallbackQuery):
|
||||
await call.message.answer(text='*| ОШИБКИ |*\n\n*-* Так как бот разрабатывается одним человеком, все баги и '
|
||||
'недочёты програмы выявить сразу очень трудно, поэтому я буду признателен вам если '
|
||||
'о найденых ошибка вы сообщите по команде /report\n\n*>* Отправить в формате '
|
||||
'*[ /report {сообщение} ]*', parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.callback_query_handler(text="auth")
|
||||
async def function(call: types.CallbackQuery):
|
||||
await call.message.answer(text='*| АВТОР |*\n\n*>>* Официальный телеграмм канал автора *@govnacoder*\n\n*-* Я '
|
||||
'практикуюсь в програмировании разрабатывая ботов и простенькие приложения, если '
|
||||
'интерестно ознокомиться с моими работами, то переходити ко мне в телеграм канал!',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.callback_query_handler(text="fun")
|
||||
async def function(call: types.CallbackQuery):
|
||||
await call.message.answer(text='*| ФУНКЦИИ |*\n\n*1.* Возможность перевода случайно написанного текста на '
|
||||
'транслите\n*2.* Ведение обширной статистики сообщений\n*3.* Упоминание участника '
|
||||
'при написании его имени в чате\n*4.* Автоматическое удаление системных сообщений',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.callback_query_handler(text="com")
|
||||
async def commands(call: types.CallbackQuery):
|
||||
await call.message.answer(text='<b>| КОМАНДЫ |</b>\n\n/all - упомянуть всех в чате\n/vote - напишите в начале '
|
||||
'сообщения и создасться простой опрос (Да / Нет)\n/report - жалобы и '
|
||||
'предложения\n/help - полный список функций\n/statistic_group - полная статистика '
|
||||
'группы\n/statistic_user - полная статистика отправителя\n/srednya_statistic - '
|
||||
'средняя статистика группы\n/edit и /back_edit - первая команда даёт возможность '
|
||||
'сменить имя для упоминаний на любое слово, а вторая для возврата динамического '
|
||||
'имени\n/start_bot и /stop_bot - возможность отключения текстовых ивентов\n/like '
|
||||
'и /dislike - даёт возможность оценить то или иное сообщение пользователя',
|
||||
parse_mode=types.ParseMode.HTML)
|
||||
|
||||
|
||||
@dp.callback_query_handler(text="even")
|
||||
async def events(call: types.CallbackQuery):
|
||||
await call.message.answer(text='*| ИВЕНТЫ |*\n\n*"Чмокнуть"* - сделать кому-нибудь приятно\n*"Отмудохать"* - '
|
||||
'выместить злость на кого-нибудь\n*"Число от ... до ..."* - случайное значение из '
|
||||
'диапозона\n*"Подраться с ..."* - повод кого-нибудь побить\n*"Переведи (..) - ..."* '
|
||||
'- перевод слова на керпичный язык\n*"Дай блять совет!"* - даёт рандомный охуенный '
|
||||
'совет\n*"Переверни - ..."* - переворачивает слова в предложении',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['all'], commands_prefix='@/')
|
||||
async def always(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
try:
|
||||
await message.reply(notice(message.from_user.first_name, True, message.chat.id, message.from_user.id),
|
||||
types.ParseMode.HTML)
|
||||
except Exception:
|
||||
await message.reply('В группе состоит менее 3х человек, из-за чего команда не работает!')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['report'])
|
||||
async def answer(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
if len(message.text.split()) > 1:
|
||||
await bot.send_message(chat_id='-1001510980656',
|
||||
text=f'{message.chat.title} >> '
|
||||
f'[{message.from_user.first_name}](tg://user?id={message.from_user.id}) '
|
||||
f'> {message.text}', parse_mode=types.ParseMode.MARKDOWN)
|
||||
await message.answer("Ваше сообщение передано администратору)")
|
||||
else:
|
||||
await message.answer("Заполнять обращение к администратору надо по форме */report { жалоба или предложение }*",
|
||||
types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['statistic_group'])
|
||||
async def stat(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
group = db.stat_element_group(message.chat.id)
|
||||
month = db.stat_element_month_group(message.chat.id)
|
||||
|
||||
try:
|
||||
await message.answer(text=f'*| СТАТИСТИКА ГРУППЫ |*\n\n*>>* В целом сообщений *[ {message.message_id} ]*\n*>>* '
|
||||
f'Сообщений в базе *[ {group[0]} ]*\n*>>* Среднее количество сообщений в месяц - *[ '
|
||||
f'{month[0] // group[8]} ]*\n\n*👍* Лайков *[ {group[10]} ]* / *👎* Дизлайков *[ '
|
||||
f'{group[9]} ]*\n\n*>* Команд *[ {group[2]} ]*\n*>* Ссылок *[ '
|
||||
f'{group[3]} ]*\n*>* Стикеров *[ {group[6]} ]*\n*>* Тик-токов *[ {group[4]} ]*\n*>* Медиа'
|
||||
f' файлов *[ {group[5]} ]*\n*>* Ответов на сообщения *[ {group[1]} ]*\n*>* Голос / Видео '
|
||||
f'сообщений *[ {group[7]} ]*', parse_mode=types.ParseMode.MARKDOWN)
|
||||
except Exception:
|
||||
await message.answer(text=f'*| СТАТИСТИКА ГРУППЫ |*\n\n*>>* В целом сообщений *[ {message.message_id} ]*\n*>>* '
|
||||
f'Сообщений в базе *[ {group[0]} ]*\n\n*👍* Лайков *[ {group[10]} ]* / *👎* Дизлайков *[ '
|
||||
f'{group[9]} ]*\n\n*>* Команд *[ {group[2]} ]*\n*>* Ссылок *[ '
|
||||
f'{group[3]} ]*\n*>* Стикеров *[ {group[6]} ]*\n*>* Тик-токов *[ {group[4]} ]*\n*>* Медиа'
|
||||
f' файлов *[ {group[5]} ]*\n*>* Ответов на сообщения *[ {group[1]} ]*\n*>* Голос / Видео '
|
||||
f'сообщений *[ {group[7]} ]*', parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['statistic_user'])
|
||||
async def stat(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
user = db.stat_element_user(message.from_user.id, message.chat.id)
|
||||
try:
|
||||
name = morph.parse(db.get_name_user(message.from_user.id, message.chat.id))[0]
|
||||
name = name.inflect({"gent"}).word.upper()
|
||||
except Exception:
|
||||
name = message.from_user.first_name.lower().upper()
|
||||
|
||||
try:
|
||||
err = 1 // user[8]
|
||||
await message.answer(text=f'*| СТАТИСТИКА {name} |*\n\n*>>* Всего сообщений *[ '
|
||||
f'{user[0]} ]*\n*>>* Среднее количество сообщений в месяц - *[ {user[0] // user[8]} '
|
||||
f']*\n\n*👍* Лайков *[ {user[10]} ]* / *👎* Дизлайков *[ {user[9]} ]*\n\n*>* Команд *[ '
|
||||
f'{user[2]} ]*\n*>* Ссылок *[ {user[3]} ]*\n*>* Стикеров '
|
||||
f'*[ {user[6]} ]*\n*>* Тик-токов *[ {user[4]} ]*\n*>* Медиа файлов *[ {user[5]} ]*\n*>* '
|
||||
f'Ответов на сообщения *[ {user[1]} ]*\n*>* Голос / Видео сообщений *[ {user[7]} ]*',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
except Exception:
|
||||
await message.answer(text=f'*| СТАТИСТИКА {name} |*\n\n*>>* Всего сообщений *[ '
|
||||
f'{user[0]} ]*\n\n*👍* Лайков *[ {user[10]} ]* / *👎* Дизлайков *[ {user[9]} ]*\n\n*>* '
|
||||
f'Команд *[ {user[2]} ]*\n*>* Ссылок *[ {user[3]} ]*\n*>* Стикеров '
|
||||
f'*[ {user[6]} ]*\n*>* Тик-токов *[ {user[4]} ]*\n*>* Медиа файлов *[ {user[5]} ]*\n*>* '
|
||||
f'Ответов на сообщения *[ {user[1]} ]*\n*>* Голос / Видео сообщений *[ {user[7]} ]*',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['srednya_statistic'])
|
||||
async def stat(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
timer = db.stat_element_group(message.chat.id)[8]
|
||||
month = db.stat_element_month_group(message.chat.id)
|
||||
|
||||
try:
|
||||
if timer != 0:
|
||||
await message.answer(text=f'*| СРЕДНЯЯ СТАТИСТИКА ГРУППЫ |*\n\n*>>* Среднее количество сообщений в месяц - '
|
||||
f'*[ {month[0] // timer} ]*\n\n*👍* Лайков *[ {month[9] // timer} ]* / *👎* Дизлайков *[ {month[8] // timer} '
|
||||
f']*\n\n*>* Команд *[ {month[2] // timer} ]*\n*>* Ссылок *[ {month[3] // timer} ]*\n*>* Стикеров '
|
||||
f'*[ {month[6] // timer} ]*\n*>* Тик-токов *[ {month[4] // timer} ]*\n*>* Медиа файлов *[ {month[5] // timer} ]*\n*>* '
|
||||
f'Ответов на сообщения *[ {month[1] // timer} ]*\n*>* Голос / Видео сообщений *[ {month[7] // timer} ]*',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
else:
|
||||
await message.reply('Статистика не может быть показана, так как с момента добавления бота прошло менее месяца!')
|
||||
except Exception:
|
||||
await message.reply('Вывод стаистики произвёл ошибку, вероятнее всего в вашем чате были использованы не все виды сообщений!')
|
||||
|
||||
|
||||
# ЕЖЕМЕСЕЧНОЕ УВЕДОМЛЕНИЕ
|
||||
async def time(wait_for):
|
||||
while True:
|
||||
await asyncio.sleep(wait_for)
|
||||
|
||||
file = open('month.txt', 'r')
|
||||
data = file.readline()
|
||||
file.close()
|
||||
|
||||
month = datetime.now().date().month
|
||||
day = datetime.now().date().day
|
||||
if int(data) != int(month):
|
||||
for group in db.all_id_group_lst():
|
||||
last = db.month_stat_group(group)
|
||||
await bot.send_message(chat_id=group,
|
||||
text=f'*| СТАТИСТИКА ГРУППЫ ЗА ПРОШЕДШИЙ МЕСЯЦ |*\n\n*>>* В целом сообщений *[ '
|
||||
f'{last[0]} ]*\n\n*👍* Лайков *[ {last[9]} ]* / *👎* Дизлайков *[ '
|
||||
f'{last[8]} ]*\n\n*>* Команд *[ {last[2]} ]*\n*>* Ссылок *[ {last[3]} '
|
||||
f']*\n*>* Стикеров *[ {last[6]} ]*\n*>* Тик-токов *[ {last[4]} ]*\n*>* '
|
||||
f'Медиа файлов *[ {last[5]} ]*\n*>* Ответов на сообщения *[ {last[1]} '
|
||||
f']*\n*>* Голос / Видео сообщений *[ {last[7]} ]*',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
db.statistics_group(group, 0)
|
||||
for user in db.id_lst(group):
|
||||
db.user_statistic(user, group, 0)
|
||||
|
||||
file = open('month.txt', 'w')
|
||||
file.write(str(month))
|
||||
file.close()
|
||||
elif (month == 6) and (day == 28):
|
||||
for group in db.all_id_group_lst():
|
||||
await bot.send_message(chat_id=group,
|
||||
text=f'Уряяя! У меня сегодня день рождения!',
|
||||
parse_mode=types.ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['like'])
|
||||
async def like(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
if message.reply_to_message:
|
||||
update_stat(2, message)
|
||||
love = (message.reply_to_message.from_user.id == message.from_user.id)
|
||||
try:
|
||||
comm = (message.reply_to_message.text[0] == '/')
|
||||
except Exception:
|
||||
comm = False
|
||||
if love is False and comm is False:
|
||||
db.statistics_group(message.chat.id, 10)
|
||||
db.user_statistic(message.reply_to_message.from_user.id, message.chat.id, 10)
|
||||
try:
|
||||
await message.delete()
|
||||
except Exception:
|
||||
pass
|
||||
await bot.send_message(chat_id=message.chat.id, text=emoji.emojize(':thumbs_up:'),
|
||||
reply_to_message_id=message.reply_to_message.message_id)
|
||||
|
||||
else:
|
||||
if love:
|
||||
await message.answer('Ай-яй-яй! За себя голосовать не хорошо!')
|
||||
elif comm:
|
||||
await message.answer('Оценивать команду не рационально!')
|
||||
else:
|
||||
await message.answer('Команда должна быть ответом на сообщение пользователя!')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['dislike'])
|
||||
async def dislike(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
if message.reply_to_message:
|
||||
update_stat(2, message)
|
||||
love = (message.reply_to_message.from_user.id == message.from_user.id)
|
||||
try:
|
||||
comm = (message.reply_to_message.text[0] == '/')
|
||||
except Exception:
|
||||
comm = False
|
||||
if love is False and comm is False:
|
||||
db.statistics_group(message.chat.id, 9)
|
||||
print(">>", message.from_user.first_name, datetime.now())
|
||||
db.user_statistic(message.reply_to_message.from_user.id, message.chat.id, 9)
|
||||
try:
|
||||
await message.delete()
|
||||
except Exception:
|
||||
pass
|
||||
await bot.send_message(chat_id=message.chat.id, text=emoji.emojize(':thumbs_down:'),
|
||||
reply_to_message_id=message.reply_to_message.message_id)
|
||||
|
||||
else:
|
||||
if love:
|
||||
await message.answer('Ай-яй-яй! За себя голосовать не хорошо!')
|
||||
elif comm:
|
||||
await message.answer('Оценивать команду не рационально!')
|
||||
else:
|
||||
await message.answer('Команда должна быть ответом на сообщение пользователя!')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['edit'])
|
||||
async def update(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
text_edit = re.sub(r'[^\w\s]', '', message.text.lower()).split()
|
||||
if len(text_edit) == 2:
|
||||
db.edit_name(message.from_user.id, text_edit[1], message.chat.id, 1)
|
||||
name_edit = db.name_lst(message.chat.id)[db.id_lst(message.chat.id).index(str(message.from_user.id))]
|
||||
await message.reply(f'{name_edit.title()}, ваше имя было успешно изменено)')
|
||||
else:
|
||||
await message.reply(f'Вы не правильно ввели имя! Имя должно быть из одного слова и идти сразу после команды!')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['back_edit'])
|
||||
async def update_return(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
text_name = re.sub(r'[^\w\s]', '', message.from_user.first_name.lower())
|
||||
db.edit_name(message.from_user.id, text_name, message.chat.id, 0)
|
||||
await message.reply(f'{text_name.title()}, вы успешно вернулись к динамическому изменению имени)')
|
||||
|
||||
|
||||
@dp.message_handler(commands=['vote'])
|
||||
async def voting(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
await bot.send_poll(chat_id=message.chat.id, question="Итак, что вы выберите?",
|
||||
options=['Да', 'Нет'], is_anonymous=False, open_period=600,
|
||||
reply_to_message_id=message.message_id)
|
||||
|
||||
|
||||
@dp.message_handler(commands=['start_bot'])
|
||||
async def opening(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
if not db.group_exists(message.chat.id):
|
||||
db.add_group(message.chat.id)
|
||||
await message.answer(
|
||||
"Ваша группа изменила свой статус, из-за чего данные о пользователях были стёрты, "
|
||||
"вам надо снова отправить хотя бы по одному сообщению от каждого пользователя! Текстовые ивенты включены!")
|
||||
else:
|
||||
for group in db.get_group():
|
||||
if str(group[1]) == str(message.chat.id):
|
||||
await message.answer("У вас уже включены текстовые ивенты!")
|
||||
break
|
||||
else:
|
||||
db.update_status_group(message.chat.id, True)
|
||||
await message.answer("Текстовые ивенты включены!")
|
||||
|
||||
|
||||
@dp.message_handler(commands=['stop_bot'])
|
||||
async def closing(message: types.Message):
|
||||
update_stat(3, message, True)
|
||||
if not db.group_exists(message.chat.id):
|
||||
db.add_group(message.chat.id, False)
|
||||
await message.answer(
|
||||
"Ваша группа изменила свой статус, из-за чего данные о пользователях были стёрты, "
|
||||
"вам надо снова отправить хотя бы по одному сообщению от каждого пользователя! Текстовые ивенты отключены!")
|
||||
else:
|
||||
for group in db.get_group():
|
||||
if str(group[1]) == str(message.chat.id):
|
||||
db.update_status_group(message.chat.id, False)
|
||||
await message.answer("Текстовые ивенты отключены!")
|
||||
break
|
||||
else:
|
||||
await message.answer("У вас уже отключены текстовые ивенты!")
|
||||
|
||||
|
||||
@dp.message_handler(
|
||||
content_types=["migrate_to_chat_id", "migrate_from_chat_id", "new_chat_title", "new_chat_photo", "pinned_message",
|
||||
"voice_chat_scheduled", "voice_chat_started", "voice_chat_ended", "voice_chat_participants_invited",
|
||||
"left_chat_member"])
|
||||
async def chat_events(message: types.Message):
|
||||
try:
|
||||
await message.delete()
|
||||
except Exception:
|
||||
print(f'{message.chat.title} >>> НЕ УДАЛОСЬ УДАЛИТЬ СООБЩЕНИЕ')
|
||||
|
||||
|
||||
# СТАТИСТИКА
|
||||
@dp.message_handler(content_types=['location', 'contact', 'video', 'photo', 'audio', 'document'])
|
||||
async def media(message: types.Message):
|
||||
update_stat(6, message, True)
|
||||
|
||||
|
||||
@dp.message_handler(content_types=['voice', 'video_note'])
|
||||
async def mms(message: types.Message):
|
||||
update_stat(8, message, True)
|
||||
|
||||
|
||||
@dp.message_handler(content_types=['sticker'])
|
||||
async def stick(message: types.Message):
|
||||
update_stat(7, message, True)
|
||||
|
||||
|
||||
# ТЕКСТОВЫЕ ИВЕНТЫ
|
||||
@dp.message_handler(content_types=['text'])
|
||||
async def send_events(message: types.Message):
|
||||
id_group, name_group, user = message.chat.id, message.chat.title, message.from_user.id
|
||||
name_db = re.sub(r'[^\w\s]', '', message.from_user.first_name.lower())
|
||||
txt = message.text.lower() # СООБЩЕНИЕ В НИЖНЕМ РЕГИСТРЕ
|
||||
bk = [i for i in txt] # СПИСОК СИМВОЛОВ СООБЩЕНИЯ
|
||||
|
||||
# ПРОВЕРКА ПОЛЬЗОВАТЕЛЯ
|
||||
try:
|
||||
if not db.user_exists(user, id_group):
|
||||
db.add_user(user, name_db, id_group)
|
||||
else:
|
||||
if user in db.get_users(id_group):
|
||||
db.update_name(user, name_db, id_group)
|
||||
except Exception as e:
|
||||
await message.answer(f'<b>Ваша группа [ {name_group} ] изменила свой статус на супергруппу! '
|
||||
f'Из-за этого, список участников был стёрт, и вам необходимо заново отослать '
|
||||
f'хотя бы одно сообщение, для коректного упоминания!</b>', types.ParseMode.HTML)
|
||||
db.add_group(id_group)
|
||||
db.add_month_group(id_group)
|
||||
db.created_group(id_group)
|
||||
db.add_user(user, name_db, id_group)
|
||||
|
||||
# ОБНОВЛЕНИЕ КОЛ-ВО СООБЩЕНИЙ
|
||||
update_stat(1, message)
|
||||
|
||||
# ОБНОВЛЕНИЕ КОЛ-ВО КОМАНД
|
||||
if len(message.text) > 1 and message.text[0] == '/':
|
||||
update_stat(3, message)
|
||||
|
||||
# ОБНОВЛЕНИЕ КОЛ-ВО ОТВЕТОВ НА СООБЩЕНИЯ
|
||||
try:
|
||||
if int(message.reply_to_message.message_id) > 1:
|
||||
update_stat(2, message)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ИВЕНТЫ
|
||||
if str(message.chat.id) in db.id_group_lst():
|
||||
|
||||
# ПЕРЕМЕННЫЕ
|
||||
original = message.text.split() # СПИСОК СЛОВ В СООБЩЕНИИ
|
||||
no_pct = re.sub(r'[^\w\s]', '', txt) # СООБЩЕНИЕ БЕЗ ПУНКТУАЦИИ
|
||||
norm = [morph.parse(i)[0].normal_form for i in no_pct.split()] # СПИСОК СЛОВ В ПЕРВОЙ ФОРМЕ
|
||||
names = [_ for _ in norm if _ in db.name_lst(message.chat.id)] # СПИСОК ИМЕН В СООБЩЕНИИ
|
||||
|
||||
# ПОЛЕЗНЫЕ ФУНКЦИИ
|
||||
if len(original) == 5 and "число от" in txt:
|
||||
await message.answer(text=f"Число <b>[ {random.randint(int(txt.split()[2]), int(txt.split()[4]))} ]</b>",
|
||||
parse_mode=types.ParseMode.HTML)
|
||||
return
|
||||
|
||||
if len(original) > 1 and no_pct.split()[0] == 'переведи':
|
||||
if "переведи - " in txt:
|
||||
await message.answer(lang_form([original[_] for _ in range(len(original)) if _ > 1]))
|
||||
elif f"переведи ({no_pct.split()[1]}) - " in txt:
|
||||
if len(no_pct.split()[1]) == 1:
|
||||
await message.answer(lang_form([original[_] for _ in range(len(original)) if _ > 2],
|
||||
no_pct.split()[1]))
|
||||
return
|
||||
|
||||
if len(original) > 1 and no_pct.split()[0] == 'переверни':
|
||||
if "переверни - " in txt:
|
||||
await message.answer(revers(message.text[12:], True))
|
||||
elif "переверни полностью - " in txt:
|
||||
await message.answer(revers(message.text[22:], False))
|
||||
return
|
||||
|
||||
# РАНДОМ ИВЕНТЫ
|
||||
if len(original) >= 2:
|
||||
if "подраться с" in txt:
|
||||
text = " ".join([original[i] for i in range(len(original)) if i > 1])
|
||||
|
||||
if random.randint(0, 1) == 0:
|
||||
await message.bot.send_photo(chat_id=id_group,
|
||||
photo=open(f"data/fight/({random.randint(1, 8)}).jpg", 'rb'),
|
||||
caption=f"{message.from_user.first_name} ты был унижен {text.title()}"
|
||||
f" с помощью {base.VAR_LOSE[random.randint(0, 3)]}")
|
||||
else:
|
||||
await message.bot.send_photo(chat_id=id_group,
|
||||
photo=open(f"data/fight/({random.randint(1, 8)}).jpg", 'rb'),
|
||||
caption=f"{message.from_user.first_name} ты победил в драке "
|
||||
f"с {text.title()}, {base.VAR_WIN[random.randint(0, 1)]}")
|
||||
|
||||
# ИВЕНТ ВЗАИМОДЕЙСТВИЯ
|
||||
if len(original) >= 2:
|
||||
for word in base.TMOK_LIST:
|
||||
if word in txt:
|
||||
lst = [original[i] for i in range(len(original)) if i != 0]
|
||||
text = " ".join(lst)
|
||||
|
||||
slv = morph.parse(original[0].lower())[0]
|
||||
|
||||
await message.bot.send_photo(chat_id=id_group,
|
||||
photo=open(f"data/tmok/({random.randint(1, 4)}).jpg", 'rb'),
|
||||
caption=f"{message.from_user.first_name} "
|
||||
f"{slv.inflect({'past', 'sing', 'indc'}).word} {text}")
|
||||
|
||||
for word in base.KILL_LIST:
|
||||
if word in txt:
|
||||
lst = [original[i] for i in range(len(original)) if i != 0]
|
||||
text = " ".join(lst)
|
||||
|
||||
slv = morph.parse(original[0].lower())[0]
|
||||
|
||||
await message.bot.send_photo(chat_id=id_group,
|
||||
photo=open(f"data/kill/({random.randint(1, 6)}).jpg", 'rb'),
|
||||
caption=f"{message.from_user.first_name} "
|
||||
f"{slv.inflect({'past', 'sing', 'indc'}).word} {text}")
|
||||
|
||||
for word_1 in base.QUAT_LIST[0]:
|
||||
flag = False
|
||||
for word_2 in base.QUAT_LIST[1]:
|
||||
for word_3 in base.QUAT_LIST[2]:
|
||||
if no_pct == " ".join([word_1, word_2, word_3]):
|
||||
word = (requests.get('http://fucking-great-advice.ru/api/random').text).split('"')[5]
|
||||
await message.reply(word)
|
||||
flag = True
|
||||
if flag:
|
||||
break
|
||||
if flag:
|
||||
break
|
||||
|
||||
# ЛИСТ КОМАНДЫ
|
||||
if names:
|
||||
await message.reply(notice(names, False, id_group, message.from_user.id), types.ParseMode.HTML)
|
||||
return
|
||||
|
||||
# ПЕРЕВОДЧИК СЛОВ
|
||||
if cheker(bk, original, id_group, user) == len(txt):
|
||||
await message.reply(f"[{message.from_user.first_name}](tg://user?id={user}) *>* {translator(original)}",
|
||||
types.ParseMode.MARKDOWN)
|
||||
return
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.create_task(time(21600)) # КАЖДЫЕ 6 ЧАСОВ ПРОВЕРКА
|
||||
executor.start_polling(dp, skip_updates=True)
|
||||
BIN
data/fight/(1).jpg
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
data/fight/(2).jpg
Normal file
|
After Width: | Height: | Size: 67 KiB |
BIN
data/fight/(3).jpg
Normal file
|
After Width: | Height: | Size: 225 KiB |
BIN
data/fight/(4).jpg
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
data/fight/(5).jpg
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
data/fight/(6).jpg
Normal file
|
After Width: | Height: | Size: 287 KiB |
BIN
data/fight/(7).jpg
Normal file
|
After Width: | Height: | Size: 153 KiB |
BIN
data/fight/(8).jpg
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
data/kill/(1).jpg
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
data/kill/(2).jpg
Normal file
|
After Width: | Height: | Size: 45 KiB |
BIN
data/kill/(3).jpg
Normal file
|
After Width: | Height: | Size: 57 KiB |
BIN
data/kill/(4).jpg
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
data/kill/(5).jpg
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
data/kill/(6).jpg
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
data/tmok/(1).jpg
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
data/tmok/(2).jpg
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
data/tmok/(3).jpg
Normal file
|
After Width: | Height: | Size: 36 KiB |
BIN
data/tmok/(4).jpg
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
data/tts.ogg
Normal file
BIN
groups.db
Normal file
1
month.txt
Normal file
|
|
@ -0,0 +1 @@
|
|||
0
|
||||
180
script.py
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
from base import ERR, ERR_, TRU, TRU_, ALB
|
||||
from string import digits, punctuation
|
||||
from datetime import date, datetime
|
||||
from sql import SQLighter
|
||||
import re
|
||||
|
||||
db = SQLighter('groups.db')
|
||||
|
||||
|
||||
def lang_form(text, smbl='г'):
|
||||
for i in range(len(text)):
|
||||
word = []
|
||||
for j in text[i]:
|
||||
if j in ALB:
|
||||
word.append(str(str(j) + str(smbl) + str(j).lower()))
|
||||
else:
|
||||
word.append(str(j))
|
||||
text[i] = ''.join(word)
|
||||
return ' '.join(text)
|
||||
|
||||
|
||||
def times():
|
||||
today = datetime.now().date()
|
||||
sel = date(2021, 2, 2)
|
||||
ext = date(2023, 10, 3)
|
||||
|
||||
itg = str((ext - today).days)
|
||||
if int(itg[-1]) == 1:
|
||||
return f'{itg} день)'
|
||||
elif 1 < int(itg[-1]) < 5:
|
||||
return f'{itg} дня)'
|
||||
else:
|
||||
return f'{itg} дней)'
|
||||
|
||||
|
||||
def autozak(name):
|
||||
num = str(len(name))
|
||||
if int(num[-1]) == 1:
|
||||
return f'{num} минута.'
|
||||
elif 1 < int(num[-1]) < 5:
|
||||
return f'{num} минуты.'
|
||||
else:
|
||||
return f'{num} минут.'
|
||||
|
||||
|
||||
def update_stat(var, message, main=False):
|
||||
db.statistics_group(message.chat.id, var)
|
||||
db.user_statistic(message.from_user.id, message.chat.id, var)
|
||||
if main:
|
||||
db.statistics_group(message.chat.id, 1)
|
||||
db.user_statistic(message.from_user.id, message.chat.id, 1)
|
||||
return
|
||||
|
||||
|
||||
def notice(name, all_users, id_group, id_var):
|
||||
names = db.name_lst(id_group)
|
||||
ids, no_copy = db.id_lst(id_group), []
|
||||
|
||||
if all_users:
|
||||
usr = ["<a href=\""+'tg://user?id='+ids[i]+"\">"+names[i].title()+"</a>" for i in range(len(names))
|
||||
if names[i] != name.lower()]
|
||||
usr.append(f'{usr[-2]} и {usr[-1]}')
|
||||
del usr[-2], usr[-2]
|
||||
return f'{", ".join(usr)} вас вызывает {name}'
|
||||
else:
|
||||
for i in name:
|
||||
if i not in no_copy:
|
||||
no_copy.append(i)
|
||||
|
||||
if len(no_copy) > 1:
|
||||
usr = ["<a href=\""+'tg://user?id='+ids[names.index(_)]+"\">"+_.title()+"</a>" for _ in no_copy
|
||||
if id_var != ids[names.index(_)]]
|
||||
usr.append(f'{usr[-2]} и {usr[-1]}')
|
||||
del usr[-2], usr[-2]
|
||||
return f"{', '.join(usr)} вас упомянули)"
|
||||
else:
|
||||
usr = "<a href=\""+'tg://user?id='+ids[names.index(no_copy[0])].title()+"\">"+no_copy[0].title()+"</a>"
|
||||
return f"{usr}, тебя упомянули)"
|
||||
|
||||
|
||||
def cheker(bk, original, id_group, user):
|
||||
flag = True
|
||||
|
||||
if flag is True:
|
||||
if (len([z for z in bk if (z in digits) or (z in punctuation)]) == len(bk)) or (bk[0] == '/'):
|
||||
flag = False
|
||||
|
||||
if (flag is True) and (len(bk) > 4):
|
||||
for x in range(3, len(bk)):
|
||||
http = "".join([bk[x - 3], bk[x - 2], bk[x - 1], bk[x]])
|
||||
if 'http' in http:
|
||||
db.statistics_group(id_group, 4)
|
||||
db.user_statistic(user, id_group, 4)
|
||||
flag = False
|
||||
break
|
||||
|
||||
if flag is False:
|
||||
if 'tiktok' in "".join(bk).split('.'):
|
||||
db.statistics_group(id_group, 5)
|
||||
db.user_statistic(user, id_group, 5)
|
||||
|
||||
if flag:
|
||||
count, raw = 0, 0
|
||||
for word in original:
|
||||
for smvl in word:
|
||||
raw += 1
|
||||
if (smvl in ERR) or (smvl in ERR_) or (smvl in digits):
|
||||
count += 1
|
||||
return len(bk) - raw + count
|
||||
else:
|
||||
return int('-1')
|
||||
|
||||
|
||||
def translator(original):
|
||||
itg = []
|
||||
for word in original:
|
||||
raw_word = []
|
||||
for smvl in word:
|
||||
if smvl in ERR:
|
||||
count = 0
|
||||
for _ in ERR:
|
||||
if smvl == _:
|
||||
raw_word.append(TRU[count])
|
||||
break
|
||||
count += 1
|
||||
elif smvl in ERR_:
|
||||
count = 0
|
||||
for _ in ERR_:
|
||||
if smvl == _:
|
||||
raw_word.append(TRU_[count])
|
||||
break
|
||||
count += 1
|
||||
elif smvl in NUM:
|
||||
raw_word.append(smvl)
|
||||
itg.append("".join(raw_word))
|
||||
return " ".join(itg)
|
||||
|
||||
|
||||
def revers(message, var):
|
||||
no_pct = re.sub(r'[^\w\s]', '', message)
|
||||
|
||||
if var:
|
||||
sml, pnc, pct, prf = [i for i in message] + [str(0)], [], [], False
|
||||
for i in sml:
|
||||
if i in punctuation or i == ' ':
|
||||
pnc.append(i)
|
||||
prf, flag = True if sml.index(i) == 0 else False, False
|
||||
else:
|
||||
flag = True
|
||||
|
||||
if flag and len(pnc) > 0:
|
||||
pct.append(''.join(pnc))
|
||||
pnc = []
|
||||
|
||||
wrd, rev, lst, txt = no_pct.split(), [], [], []
|
||||
for i in wrd:
|
||||
word, up, itg = [i[-1 - l].lower() for l in range(len(i))], [], []
|
||||
|
||||
for _ in i:
|
||||
up.append(True if _ in TRU_ else False)
|
||||
for j in range(len(up)):
|
||||
itg.append(word[j].upper() if up[j] else word[j])
|
||||
|
||||
rev.append(''.join(itg))
|
||||
|
||||
if prf:
|
||||
for i in range(len(pct)):
|
||||
txt = (txt + [pct[i]]) if (i + 1) == len(pct) and len(pct) > len(rev) else (txt + [pct[i], rev[i]])
|
||||
return ''.join(txt)
|
||||
else:
|
||||
for i in range(len(rev)):
|
||||
if i > 0:
|
||||
txt.append(pct[i - 1])
|
||||
txt.append(rev[i])
|
||||
if (i + 1) == len(rev) and len(pct) == len(rev):
|
||||
txt.append(pct[i])
|
||||
return ''.join(txt)
|
||||
else:
|
||||
sml = [i for i in message]
|
||||
return ''.join([sml[-1 - i] for i in range(len(sml))])
|
||||
262
sql.py
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
import sqlite3
|
||||
|
||||
|
||||
class SQLighter:
|
||||
def __init__(self, database):
|
||||
"""Подключаемся к БД и сохраняем курсор соединения"""
|
||||
self.connection = sqlite3.connect(database)
|
||||
self.cursor = self.connection.cursor()
|
||||
|
||||
# СВЯЗКА ГРУППЫ
|
||||
def group_exists(self, id_group):
|
||||
"""Проверяем, есть ли уже группа в базе"""
|
||||
with self.connection:
|
||||
result = self.cursor.execute('SELECT * FROM `group` WHERE `id_group` = ?', (id_group,)).fetchall()
|
||||
return bool(len(result))
|
||||
|
||||
def add_group(self, id_group, status=True):
|
||||
"""Добавляем новую группу в таблицу"""
|
||||
with self.connection:
|
||||
return self.cursor.execute("INSERT INTO `group` (`id_group`, `status`, `time`, `message`, `reply`, "
|
||||
"`command`, `url`, `tik_tok`, `media`, `sticker`, `voice`, `bool`, `cool`) "
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(id_group, status, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
|
||||
|
||||
def add_month_group(self, id_group):
|
||||
"""Добавляем новую группу в таблицу месяца"""
|
||||
with self.connection:
|
||||
return self.cursor.execute("INSERT INTO `month` (`id_group`, `message`, `reply`, `command`, `url`, "
|
||||
"`tik_tok`, `media`, `sticker`, `voice`, `bool`, `cool`) "
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?)", (id_group, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
|
||||
|
||||
def created_group(self, id_group):
|
||||
"""Создаём новую таблицу"""
|
||||
with self.connection:
|
||||
return self.cursor.execute(f"""CREATE TABLE IF NOT EXISTS [{id_group}] (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id_user VARCHAR (255) NOT NULL,
|
||||
first_name TEXT (40) NOT NULL,
|
||||
edit BOOLEAN NOT NULL
|
||||
DEFAULT (FALSE),
|
||||
time INTEGER NOT NULL
|
||||
DEFAULT (1),
|
||||
message INTEGER NOT NULL,
|
||||
reply INTEGER NOT NULL,
|
||||
command INTEGER NOT NULL,
|
||||
url INTEGER NOT NULL,
|
||||
tik_tok INTEGER NOT NULL,
|
||||
media INTEGER NOT NULL,
|
||||
sticker INTEGER NOT NULL,
|
||||
voice INTEGER NOT NULL,
|
||||
bool INTEGER NOT NULL,
|
||||
cool INTEGER NOT NULL
|
||||
);""")
|
||||
|
||||
def update_status_group(self, id_group, status):
|
||||
"""Обновляем статус группы"""
|
||||
with self.connection:
|
||||
return self.cursor.execute("UPDATE `group` SET `status` = ? WHERE `id_group` = ?", (status, id_group))
|
||||
|
||||
def get_group(self, status=True):
|
||||
"""Получаем все активные группы"""
|
||||
with self.connection:
|
||||
return self.cursor.execute("SELECT * FROM `group` WHERE `status` = ?", (status,)).fetchall()
|
||||
|
||||
def id_group_lst(self, status=True):
|
||||
"""Список айди активных групп"""
|
||||
with self.connection:
|
||||
return [i[1] for i in self.cursor.execute("SELECT * FROM `group` WHERE `status` = ?", (status,)).fetchall()]
|
||||
|
||||
def all_id_group_lst(self):
|
||||
"""Список всех айди групп"""
|
||||
with self.connection:
|
||||
return [i[0] for i in self.cursor.execute(f'SELECT id_group FROM `group`').fetchall()]
|
||||
|
||||
def statistics_group(self, id_group, var):
|
||||
"""Обновляем статистику"""
|
||||
with self.connection:
|
||||
self.cursor.execute("SELECT * FROM `group` WHERE `id_group` = ?", (id_group,))
|
||||
if var == 0:
|
||||
return self.cursor.execute("UPDATE `group` SET `time` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[3] + 1), id_group))
|
||||
elif var == 1:
|
||||
return self.cursor.execute("UPDATE `group` SET `message` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[4] + 1), id_group))
|
||||
elif var == 2:
|
||||
return self.cursor.execute("UPDATE `group` SET `reply` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[5] + 1), id_group))
|
||||
elif var == 3:
|
||||
return self.cursor.execute("UPDATE `group` SET `command` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[6] + 1), id_group))
|
||||
elif var == 4:
|
||||
return self.cursor.execute("UPDATE `group` SET `url` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[7] + 1), id_group))
|
||||
elif var == 5:
|
||||
return self.cursor.execute("UPDATE `group` SET `tik_tok` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[8] + 1), id_group))
|
||||
elif var == 6:
|
||||
return self.cursor.execute("UPDATE `group` SET `media` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[9] + 1), id_group))
|
||||
elif var == 7:
|
||||
return self.cursor.execute("UPDATE `group` SET `sticker` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[10] + 1), id_group))
|
||||
elif var == 8:
|
||||
return self.cursor.execute("UPDATE `group` SET `voice` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[11] + 1), id_group))
|
||||
elif var == 9:
|
||||
return self.cursor.execute("UPDATE `group` SET `bool` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[12] + 1), id_group))
|
||||
elif var == 10:
|
||||
return self.cursor.execute("UPDATE `group` SET `cool` = ? WHERE `id_group` = ?",
|
||||
((self.cursor.fetchone()[13] + 1), id_group))
|
||||
|
||||
def stat_element_group(self, id_group):
|
||||
"""Получение данных группы"""
|
||||
with self.connection:
|
||||
self.cursor.execute("SELECT * FROM `group` WHERE `id_group` = ?", (id_group,))
|
||||
data = self.cursor.fetchone()
|
||||
time, message, reply, command, url = int(data[3]), int(data[4]), int(data[5]), int(data[6]), int(data[7])
|
||||
tik_tok, media, sticker, voice = int(data[8]), int(data[9]), int(data[10]), int(data[11])
|
||||
bol, cool = int(data[12]), int(data[13])
|
||||
return [message, reply, command, url, tik_tok, media, sticker, voice, time, bol, cool]
|
||||
|
||||
def stat_element_month_group(self, id_group):
|
||||
"""Получение месячных данных группы"""
|
||||
with self.connection:
|
||||
self.cursor.execute("SELECT * FROM `month` WHERE `id_group` = ?", (id_group,))
|
||||
data = self.cursor.fetchone()
|
||||
message, reply, command, url = int(data[2]), int(data[3]), int(data[4]), int(data[5])
|
||||
tik_tok, media, sticker, voice = int(data[6]), int(data[7]), int(data[8]), int(data[9])
|
||||
bol, cool = int(data[10]), int(data[11])
|
||||
return [message, reply, command, url, tik_tok, media, sticker, voice, bol, cool]
|
||||
|
||||
def month_stat_group(self, id_group):
|
||||
"""Перезапись месечной статистики"""
|
||||
with self.connection:
|
||||
self.cursor.execute("SELECT * FROM `group` WHERE `id_group` = ?", (id_group,))
|
||||
group = self.cursor.fetchone()
|
||||
|
||||
self.cursor.execute("SELECT * FROM `month` WHERE `id_group` = ?", (id_group,))
|
||||
month = self.cursor.fetchone()
|
||||
|
||||
message, reply, command = (group[4] - month[2]), (group[5] - month[3]), (group[6] - month[4])
|
||||
url, tik_tok, media = (group[7] - month[5]), (group[8] - month[6]), (group[9] - month[7])
|
||||
sticker, voice, bol = (group[10] - month[8]), (group[11] - month[9]), (group[12] - month[10])
|
||||
cool = (group[13] - month[11])
|
||||
|
||||
self.cursor.execute("UPDATE `month` SET `message` = ? WHERE `id_group` = ?", ((group[4]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `reply` = ? WHERE `id_group` = ?", ((group[5]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `command` = ? WHERE `id_group` = ?", ((group[6]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `url` = ? WHERE `id_group` = ?", ((group[7]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `tik_tok` = ? WHERE `id_group` = ?", ((group[8]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `media` = ? WHERE `id_group` = ?", ((group[9]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `sticker` = ? WHERE `id_group` = ?", ((group[10]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `voice` = ? WHERE `id_group` = ?", ((group[11]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `bool` = ? WHERE `id_group` = ?", ((group[12]), id_group))
|
||||
self.cursor.execute("UPDATE `month` SET `cool` = ? WHERE `id_group` = ?", ((group[13]), id_group))
|
||||
|
||||
return [message, reply, command, url, tik_tok, media, sticker, voice, bol, cool]
|
||||
|
||||
# СВЯЗКА ПОЛЬЗОВАТЕЛЯ
|
||||
def user_exists(self, id_user, db):
|
||||
"""Проверяем, есть ли уже пользователь в базе"""
|
||||
with self.connection:
|
||||
result = self.cursor.execute(f'SELECT * FROM `{db}` WHERE `id_user` = ?', (id_user,)).fetchall()
|
||||
return bool(len(result))
|
||||
|
||||
def add_user(self, id_user, name, db):
|
||||
"""Добавляем нового пользователя"""
|
||||
with self.connection:
|
||||
return self.cursor.execute(f"INSERT INTO `{db}` (`id_user`, `first_name`, `edit`, `time`, `message`, "
|
||||
f"`reply`, `command`, `url`, `tik_tok`, `media`, `sticker`, `voice`, `bool`, "
|
||||
f"`cool`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(id_user, name, False, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
|
||||
|
||||
def update_name(self, id_user, name, db):
|
||||
"""Обновляем имя пользователя"""
|
||||
with self.connection:
|
||||
return self.cursor.execute(f"UPDATE `{db}` SET `first_name` = ? WHERE `id_user` = ?", (name, id_user))
|
||||
|
||||
|
||||
def edit_name(self, id_user, name, db, var):
|
||||
"""Заменяем имеющиеся имя на желаемое"""
|
||||
with self.connection:
|
||||
if var == 1:
|
||||
self.cursor.execute(f"UPDATE `{db}` SET `edit` = ? WHERE `id_user` = ?", (True, id_user))
|
||||
return self.cursor.execute(f"UPDATE `{db}` SET `first_name` = ? WHERE `id_user` = ?", (name, id_user))
|
||||
elif var == 0:
|
||||
self.cursor.execute(f"UPDATE `{db}` SET `edit` = ? WHERE `id_user` = ?", (False, id_user))
|
||||
return self.cursor.execute(f"UPDATE `{db}` SET `first_name` = ? WHERE `id_user` = ?", (name, id_user))
|
||||
|
||||
def get_users(self, db, status=True):
|
||||
"""Получаем всех активных пользователей"""
|
||||
with self.connection:
|
||||
return [i[1] for i in self.cursor.execute(f"SELECT * FROM `{db}` WHERE `edit` = ?", (status,)).fetchall()]
|
||||
|
||||
def id_lst(self, db):
|
||||
"""Список айди"""
|
||||
with self.connection:
|
||||
return [i[0] for i in self.cursor.execute(f'SELECT id_user FROM `{db}`').fetchall()]
|
||||
|
||||
def name_lst(self, db):
|
||||
"""Список имён"""
|
||||
with self.connection:
|
||||
return [i[0] for i in self.cursor.execute(f'SELECT first_name FROM `{db}`').fetchall()]
|
||||
|
||||
def user_statistic(self, id_user, id_group, var):
|
||||
"""Обновляем статистику"""
|
||||
with self.connection:
|
||||
self.cursor.execute(f"SELECT * FROM `{id_group}` WHERE `id_user` = ?", (id_user,))
|
||||
if var == 0:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `time` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[4] + 1), id_user))
|
||||
elif var == 1:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `message` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[5] + 1), id_user))
|
||||
elif var == 2:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `reply` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[6] + 1), id_user))
|
||||
elif var == 3:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `command` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[7] + 1), id_user))
|
||||
elif var == 4:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `url` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[8] + 1), id_user))
|
||||
elif var == 5:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `tik_tok` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[9] + 1), id_user))
|
||||
elif var == 6:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `media` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[10] + 1), id_user))
|
||||
elif var == 7:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `sticker` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[11] + 1), id_user))
|
||||
elif var == 8:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `voice` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[12] + 1), id_user))
|
||||
elif var == 9:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `bool` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[13] + 1), id_user))
|
||||
elif var == 10:
|
||||
return self.cursor.execute(f"UPDATE `{id_group}` SET `cool` = ? WHERE `id_user` = ?",
|
||||
((self.cursor.fetchone()[14] + 1), id_user))
|
||||
|
||||
def stat_element_user(self, id_user, id_group):
|
||||
"""Получение данных пользователя"""
|
||||
with self.connection:
|
||||
self.cursor.execute(f"SELECT * FROM `{id_group}` WHERE `id_user` = ?", (id_user,))
|
||||
data = self.cursor.fetchone()
|
||||
time, message, reply, command, url = int(data[4]), int(data[5]), int(data[6]), int(data[7]), int(data[8])
|
||||
tik_tok, media, sticker, voice = int(data[9]), int(data[10]), int(data[11]), int(data[12])
|
||||
bol, cool = int(data[13]), int(data[14])
|
||||
return [message, reply, command, url, tik_tok, media, sticker, voice, time, bol, cool]
|
||||
|
||||
def get_name_user(self, id_user, id_group):
|
||||
"""Получение имени пользователя"""
|
||||
with self.connection:
|
||||
self.cursor.execute(f"SELECT * FROM `{id_group}` WHERE `id_user` = ?", (id_user,))
|
||||
return self.cursor.fetchone()[2]
|
||||
|
||||
def close(self):
|
||||
"""Закрываем соединение с БД"""
|
||||
self.connection.close()
|
||||