def unwarn(message, person, parameters_dictionary: dict): """Снимает с участника предупреждение""" database = Database() unwarns = parameters_dictionary['value'] chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] value = database.get('members', ('id', person.id), ('system', system))['warns'] - unwarns if value >= 0: database.change(value, 'warns', 'members', ('id', person.id), ('system', system)) adm_place = admin_place(message, database) if adm_place: text = "#warns\n\n" text += "Пользователь {} потерял(а) {} варн(а) и их стало {}\n".format( person_info_in_html(person), unwarns, value) text += "Варн(ы) снят(ы) пользователем {}\n".format( person_info_in_html(message.from_user)) if 'comment' in parameters_dictionary.keys(): text += "Комментарий: {}".format( parameters_dictionary['comment']) send(adm_place, text, parse_mode='HTML') reply(message, "Варн(ы) снят(ы). Теперь их {}".format(value)) if 3 - unwarns <= value < 3: chat_configs = get_system_configs(system) unban_user(person) database.change(chat_configs['ranks'][1], 'rank', 'members', ('id', person.id), ('system', system)) else: reply(message, "Нельзя сделать отрицательное количество предупреждений")
def money_give(message, person, parameters_dictionary: dict): """Функция обмена деньгами между людьми""" LOG.log(f"money_give invoked to person {person.id}") database = Database() getter = person giver = message.from_user money = parameters_dictionary['value'] system = database.get('chats', ('id', message.chat.id))['system'] value_getter = get_person(message, getter, system, database)['money'] value_giver = get_person(message, giver, system, database)['money'] money_name_word = get_word_object( get_system_configs(system)['money_name'], 'Russian') money_name = money_name_word.cased_by_number(abs(money), if_one_then_accusative=True) if money < 0: reply(message, "Я вам запрещаю воровать") elif money == 0: reply(message, "Я вам запрещаю делать подобные бессмысленные запросы") else: if money > value_giver: reply(message, "Не хватает {}".format(money_name_word.genitive_plural())) else: value_getter += money value_giver -= money giv_m = send(giver.id, "#Финансы\n\nВы успешно перевели {} {} на счёт {}. " "Теперь у вас их {}".format(money, money_name, person_link(getter), value_giver), parse_mode='HTML') get_m = send( getter.id, "#Финансы\n\nНа ваш счёт переведено {} {} со счёта {}. " "Теперь у вас их {}".format(money, money_name, person_link(giver), value_getter), parse_mode='HTML') if get_m: get_m = "🔔 уведомлён(а)" else: get_m = "🔕 не уведомлён(а)" if giv_m: giv_m = "🔔 уведомлён(а)" else: giv_m = "🔕 не уведомлён(а)" reply(message, "{} передал(а) {} {} {}!".format(person_link(giver), person_link(getter), money, money_name), parse_mode='HTML') send( admin_place(message, database), f"#Финансы #f{getter.id} #f{giver.id}\n\n" f"{person_link(getter)} [{value_getter - money} --> {value_getter}] {get_m}\n" f"{person_link(giver)} [{value_giver + money} --> {value_giver}] {giv_m}\n", parse_mode='HTML') database.change(value_getter, 'money', 'members', ('id', getter.id), ('system', system)) database.change(value_giver, 'money', 'members', ('id', giver.id), ('system', system))
def cooldown(message, command, timeout=3600, notify=True, individual=True): """Checks if the function is ready to be used again""" if message.chat.id > 0: # Command is used in PM's return True database = Database() person_id = 0 if individual: person_id = message.from_user.id entry = database.get('cooldown', ('person_id', person_id), ('command', command), ('chat_id', message.chat.id)) if not entry: # Person uses this command for the first time database.append((person_id, command, message.chat.id, message.date), 'cooldown') return True # The command is already used time_passed = message.date - entry['time'] if time_passed < timeout: # Кулдаун не прошёл seconds = timeout - time_passed minutes = seconds // 60 seconds %= 60 if notify: if individual: answer = "Воу, придержи коней, ковбой. Ты сможешь воспользоваться этой командой только " answer += f"через {minutes} минут и {seconds} секунд 🤠" else: answer = "Воу, придержите коней, ковбои. Вы сможете воспользоваться этой командой только " answer += f"через {minutes} минут и {seconds} секунд 🤠" reply(message, answer) return False # Кулдаун прошёл database.change(message.date, 'time', 'cooldown', ('person_id', person_id), ('command', command), ('chat_id', message.chat.id)) return True
def language_setter(message): """Sets the language of the chat""" database = Database() original_languages = ['Русский', 'English'] english_languages = ['Russian', 'English'] language = message.text[6:].title() if language in original_languages + english_languages: if language in original_languages: language = (language, ORIGINAL_TO_ENGLISH[language]) else: # language in english_languages language = (ENGLISH_TO_ORIGINAL[language], language) if database.get('languages', ('id', message.chat.id)): database.change(language[1], 'language', 'languages', ('id', message.chat.id)) else: database.append((message.chat.id, language[1]), 'languages') if language[0] == language[1]: reply(message, f"✅ {language[0]} ✅") else: reply(message, f"✅ {language[0]} | {language[1]} ✅") else: answer = '' answer += "Если вы говорите на русском, напишите '/lang Русский'\n\n" answer += "If you speak English, type '/lang English'\n\n" reply(message, answer)
def cooldown(message, command, timeout=3600): """Checks if the function is ready to be used again""" if message.chat.id > 0: # Command is used in PM's return True database = Database() # Получаем наименование необходимой команды entry = database.get('cooldown', ('person_id', message.from_user.id), ('command', command), ('chat_id', message.chat.id)) if not entry: # Чел впервые пользуется коммандой database.append( (message.from_user.id, command, message.chat.id, message.date), 'cooldown') return True # Чел уже пользовался командой time_passed = message.date - entry['time'] if time_passed < timeout: # Кулдаун не прошёл seconds = timeout - time_passed minutes = seconds // 60 seconds %= 60 answer = "Воу, придержи коней, ковбой. Ты сможешь воспользоваться этой командой только " answer += f"через {minutes} минут и {seconds} секунд 🤠" reply(message, answer) return False # Кулдаун прошёл database.change(message.date, 'time', 'cooldown', ('person_id', message.from_user.id), ('command', command), ('chat_id', message.chat.id)) return True
def warn(message, person, parameters_dictionary): """Даёт участнику предупреждение""" database = Database() warns = parameters_dictionary['value'] chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] value = database.get('members', ('id', person.id), ('system', system))['warns'] + warns database.change(value, 'warns', 'members', ('id', person.id), ('system', system)) reply(message, "Варн(ы) выдан(ы). Теперь их {}".format(value)) adm_place = admin_place(message, database) if adm_place: send(adm_place, "Пользователь {} получил(а) {} варн(а) и их стало {}".format( person_info_in_html(person), warns, value), parse_mode='HTML') blowout = database.get('channels', ('name', 'Проколы'))['id'] how_many = 10 # Сколько пересылает сообщений end_forwarding = message.reply_to_message.message_id start_forwarding = end_forwarding - how_many send(blowout, "В чате {} случилось нарушение участником {} Прысылаю {} сообщений". format(chat_info_in_html(message.chat), person_info_in_html(person), how_many), parse_mode='HTML') for msg_id in range(start_forwarding, end_forwarding + 1): forward(blowout, message.chat.id, msg_id) if value >= 3: ban(message, person)
def month_set(message, month): """Set the month of person's birthday""" database = Database() reply( message, "Ставлю человеку с ID {} месяц рождения {}".format( message.from_user.id, month)) database.change(month, 'month_birthday', 'members', ('id', message.from_user.id))
def counter(message, person): """Подсчитывает сообщения, отправленные челом""" database = Database() if not database.get('messages', ('person_id', person.id), ('chat_id', message.chat.id)): database.append((person.id, message.chat.id, 0), 'messages') messages = database.get('messages', ('person_id', person.id), ('chat_id', message.chat.id))['messages'] database.change(messages + 1, 'messages', 'messages', ('person_id', person.id), ('chat_id', message.chat.id))
def day_set(message, day, language): """Set the day of person's birthday""" days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) database = Database() month = database.get('members', ('id', message.from_user.id))['month_birthday'] - 1 if not month: reply(message, "Сначала поставь месяц рождения") elif day > days[month]: month = MONTHS_PREPOSITIONAL[month][language] reply(message, "В {} нет столько дней".format(month.lower())) else: reply(message, "Ставлю человеку с ID {} день рождения {}".format(message.from_user.id, day)) database.change(day, 'day_birthday', 'members', ('id', message.from_user.id))
def deleter_mode(message): """Удалять медиа или нет""" database = Database() delete = int(database.get('config', ('var', 'delete'))['value']) delete = (delete + 1) % 2 # Переводит 0 в 1, а 1 в 0 database.change(delete, 'value', 'config', ('var', 'delete')) if delete: reply( message, 'Окей, господин, теперь я буду удалять медиа, которые присланы гостями' ) else: reply(message, 'Окей, гости могут спокойной слать свои медиа')
def money_reset(message): """Take all users' money to a system fund""" database = Database() system = database.get('chats', ('id', message.chat.id))['system'] system_money = database.get('systems', ('id', system))['money'] members = database.get_many('members', ('system', system)) # Get the amount of money of chat members members_money = sum([member['money'] for member in members]) if system_money != 'inf': database.increase(members_money, 'money', 'systems', ('id', system)) database.change(0, 'money', 'members', ('system', system)) reply(message, "OK")
def rank_changer(message, person): """Changes person's rank""" database = Database() chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] chat_configs = get_system_configs(system) command = message.text.split()[0].split(sep='@')[0] adm_place = admin_place(message, database) if command in chat_configs["ranks_commands"]: rank_index = chat_configs["ranks_commands"].index(command) rank = chat_configs["ranks"][rank_index] database.change(rank, "rank", 'members', ('id', person.id), ('system', system)) reply(message, f"Теперь это {rank} по званию!") if adm_place: send(adm_place, "Пользователь {} получил(а) звание {}".format( person_info_in_html(person), rank), parse_mode='HTML') elif command in chat_configs["appointment_adders"]: appointment_index = chat_configs["appointment_adders"].index(command) appointment = chat_configs["appointments"][appointment_index] if not database.get('appointments', ('id', person.id), ('system', system), ('appointment', appointment)): database.append((person.id, system, appointment), "appointments") reply( message, f"Теперь это {appointment}. Поздравим человека с повышением!") if adm_place: send(adm_place, "Пользователь {} получил(а) должность {}".format( person_info_in_html(person), appointment), parse_mode='HTML') else: reply(message, "У этого человека и так есть эта должность") elif command in chat_configs["appointment_removers"]: appointment_index = chat_configs["appointment_removers"].index(command) appointment = chat_configs["appointments"][appointment_index] database.remove("appointments", ('id', person.id), ('system', system), ('appointment', appointment)) reply(message, f"Теперь это не {appointment}") if adm_place: send(adm_place, "Пользователь {} потерял(а) должность {}".format( person_info_in_html(person), appointment), parse_mode='HTML') unban_user(person) if is_suitable(message, person, 'boss', loud=False): give_admin(message, person, loud=False) else: del_admin(message, person, loud=False)
def add_admin_place(message): """Add admin place to system""" database = Database() chat = database.get('chats', ('id', message.chat.id)) if chat: system = chat["system"] database.change(message.chat.id, "admin_place", "systems", ('id', system)) reply( message, "Теперь это чат админов. Я сюда буду присылать различные уведомления!" ) else: reply(message, "Произошла ошибка!")
def system_options(message): """Optimize current system""" database = Database() text = message.text.split(sep='@')[0] last_word = text.split(sep='_')[-1] if last_word == 'on': mode = 2 text = text[3:-3] else: # last_word == 'off' mode = 1 text = text[3:-4] system = database.get('chats', ('id', message.chat.id))['system'] database.change(mode, text, 'systems', ('id', system)) reply(message, "ОК!")
def message_change(message, person, parameters_dictionary): """Меняет запись в БД о количестве сообщений чела""" LOG.log(f"message_change invoked to person {person.id}") database = Database() p_id = person.id ch_id = message.chat.id value = parameters_dictionary['value'] reply( message, "Ставлю этому человеку в этот чат количество сообщений {}".format( value)) if not database.get('messages', ('person_id', p_id), ('chat_id', ch_id)): database.append((p_id, ch_id, value), 'messages') else: database.change(value, 'messages', 'messages', ('person_id', p_id), ('chat_id', ch_id))
def chat_options(message): """Optimize current chat""" database = Database() text = message.text.split(sep='@')[0] last_word = text.split(sep='_')[-1] if last_word == 'default': mode = 2 text = text[1:-8] elif last_word == 'on': mode = 1 text = text[1:-3] else: # last_word == 'off' mode = 0 text = text[1:-4] database.change(mode, text, 'chats', ('id', message.chat.id)) reply(message, "ОК!")
def money_fund(message, parameters_dictionary): """Transfer money to the chat fund""" database = Database() giver = message.from_user money = parameters_dictionary['value'] chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] value_giver = database.get('members', ('id', giver.id), ('system', system))['money'] value_system = database.get('systems', ('id', system))['money'] money_name_word = get_word_object( get_system_configs(system)['money_name'], 'Russian') money_name = money_name_word.cased_by_number(abs(money), if_one_then_accusative=True) if money < 0: reply(message, "Я вам запрещаю воровать") elif money == 0: reply(message, "Я вам запрещаю делать подобные бессмысленные запросы") else: if money > value_giver: reply(message, "Не хватает {}".format(money_name_word.genitive_plural())) else: if value_system != 'inf': value_system = int(value_system) value_system += money value_giver -= money text = f"#Финансы\n\nВы успешно перевели {money} {money_name} в фонд чата. " \ f"Теперь у вас их {value_giver}" giv_m = value_marker(send(giver.id, text), "🔔 уведомлён(а)", "🔕 не уведомлён(а)") reply(message, "{} заплатил(а) в банк {} {}!".format( person_link(giver), money, money_name), parse_mode='HTML') answer = f"#Финансы #f{giver.id}\n\n" if value_system != 'inf': answer += f"#Бюджет [{value_system - money} --> {value_system}]\n" answer += f"{person_link(giver)} [{value_giver + money} --> {value_giver}] {giv_m}\n" send(admin_place(message, database), answer, parse_mode='HTML') database.change(value_giver, 'money', 'members', ('id', giver.id), ('system', system)) database.change(value_system, 'money', 'systems', ('id', system))
def chat_check(message): """Show which options are chosen in chat""" database = Database() database.change(message.chat.title, 'name', 'chats', ('id', message.chat.id)) if message.chat.username: database.change('public', 'type', 'chats', ('id', message.chat.id)) database.change(message.chat.username, 'link', 'chats', ('id', message.chat.id)) else: database.change('private', 'type', 'chats', ('id', message.chat.id)) database.change('None', 'link', 'chats', ('id', message.chat.id)) # Здесь конец chat = database.get('chats', ('id', message.chat.id)) system = database.get('systems', ('id', chat['system'])) text = 'Настройки этого чата:\n\n' for feature in FEATURES: mark = '' microtext = '' system_property = system[feature] chat_property = chat[feature] if system_property: # Feature is suggested if chat_property == 2: # Feature is set default mark += '⚙' microtext += ' (по умолчанию)' chat_property = system_property - 1 if chat_property: mark = '✅' + mark microtext = 'Работает' + microtext else: mark = '❌' + mark microtext = 'Не работает' + microtext text += f"{FEATURES_TEXTS['Russian'][FEATURES.index(feature)]}: \n{mark} {microtext}\n" if '⚙' in mark or '❌' in mark: text += f"/{feature}_on Включить на постоянку\n" if '⚙' in mark or '✅' in mark: text += f"/{feature}_off Выключить на постоянку\n" if '⚙' not in mark: text += f"/{feature}_default Поставить значение по умолчанию\n" text += '\n' reply(message, text)
def ban(message, person, comment=True, unban_then=False): """Даёт участнику бан""" database = Database() blowout = database.get('channels', ('name', 'Проколы'))['id'] how_many = 3 # Сколько пересылает сообщений if not unban_then: end_forwarding = get_target_message(message).message_id start_forwarding = end_forwarding - how_many send(blowout, "В чате {} забанили участника {}. Прысылаю {} сообщений".format( chat_info_in_html(message.chat), person_info_in_html(person), how_many), parse_mode='HTML') for msg_id in range(start_forwarding, end_forwarding + 1): forward(blowout, message.chat.id, msg_id) if comment: send( message.chat.id, "Ну всё, этому челу " + "бан" * (not unban_then) + "кик" * unban_then) chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] chat_configs = get_system_configs(system) if not unban_then: database.change(chat_configs['ranks'][0], 'rank', 'members', ('id', person.id), ('system', system)) for chat in full_chat_list(database, system): kick(chat['id'], person.id) for channel in channel_list(database): kick(channel['id'], person.id) adm_place = admin_place(message, database) if adm_place: send(adm_place, "Пользователь {} получил(а) бан".format( person_info_in_html(person) + ', но сразу и разбан' * unban_then), parse_mode='HTML') if unban_then: unban_user(person)
def member_update(system, person): """Updates nickname, username and messages columns in database""" database = Database() chats_ids = [ x['id'] for x in database.get_many('chats', ('messages_count', 2), ('system', system)) ] msg_count = 0 for chat_id in chats_ids: if feature_is_available(chat_id, system, 'messages_count'): msg_entry = database.get('messages', ('person_id', person.id), ('chat_id', chat_id)) if msg_entry: msg_count += msg_entry['messages'] database.change(person.username, 'username', 'members', ('id', person.id)) database.change(person.first_name, 'nickname', 'members', ('id', person.id)) database.change(msg_count, 'messages', 'members', ('id', person.id), ('system', system))
def money_mode_change(message): """Change the money mode in system. Infinite, finite or no money""" database = Database() mode = message.text.split()[0].split(sep='@')[0].split(sep='_')[-1] chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] update_systems_json(system, mode == 'on', 'money') if mode == 'on': all_money = message.text.split()[-1] if all_money.isdecimal(): all_money = int(all_money) people = list(database.get_many('members', ('system', system))) people = list( filter(lambda x: x['money'] != 0 and x['id'] != BOT_ID, people)) money = 0 for person in people: money += person['money'] all_money -= money if all_money < 0: reply( message, "Казна выходит отрицательная, ставлю бесконечную валюту") database.change('inf', 'money', 'systems', ('id', system)) else: reply( message, f"В казне выходит {all_money} денег. Спасибо за сотрудничество!" ) database.change(all_money, 'money', 'systems', ('id', system)) else: database.change('inf', 'money', 'systems', ('id', system)) reply(message, "Бесконечная валюта поставлена") else: reply(message, "Валюта выключена")
def money_pay(message, person, parameters_dictionary): """Платит человеку деньги из бюджета чата""" LOG.log(f"money pay invoked to person {person.id}") database = Database() chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] bot_money = database.get('systems', ('id', system))['money'] if bot_money != 'inf': bot_money = int(bot_money) p_id = person.id money = parameters_dictionary['value'] money_name_word = get_word_object( get_system_configs(system)['money_name'], 'Russian') money_name = money_name_word.cased_by_number(abs(money), if_one_then_accusative=True) person_money = get_person(message, person, system, database)['money'] if money == 0: reply(message, "Я вам запрещаю делать подобные бессмысленные запросы") elif money < 0: money = -int(money) # Делаем из отрицательного числа положительное if person_money - money >= 0: person_money -= money if bot_money != 'inf': bot_money += money sent = send( p_id, "#Финансы\n\n" f"С вашего счёта было снято {money} {money_name} в банк. " f"Теперь у вас {person_money}") sent = cf.value_marker(sent, "🔔 уведомлён(а)", "🔕 не уведомлён(а)") reply(message, 'У {} забрали {} {} в банк!'.format(person_link(person), money, money_name), parse_mode='HTML') answer = "#Финансы " + f"#f{p_id}\n\n" if bot_money != 'inf': answer += f"#Бюджет [{bot_money - money} --> {bot_money}]\n" answer += f"{person_link(person)} [{person_money + money} --> {person_money}] {sent}" send(admin_place(message, database), answer, parse_mode='HTML') else: reply( message, "У людей число {} должно быть больше нуля".format( money_name_word.genitive_plural())) else: if bot_money != 'inf' and bot_money < money: reply( message, "У нас нет столько {} в банке".format( money_name_word.genitive_plural())) else: person_money += money sent = send( p_id, "#Финансы\n\n" f"На ваш счёт было переведено {money} {money_name} из банка. " f"Теперь у вас {person_money}") sent = cf.value_marker(sent, "🔔 уведомлён(а)", "🔕 не уведомлён(а)") reply(message, '{} получил(а) из банка {} {}!'.format( person_link(person), money, money_name), parse_mode='HTML') answer = "#Финансы " + f"#f{p_id}\n\n" if bot_money != 'inf': bot_money -= money answer += f"#Бюджет [{bot_money + money} --> {bot_money}]\n" answer += f"{person_link(person)} [{person_money - money} --> {person_money}] {sent}" send(admin_place(message, database), answer, parse_mode='HTML') database.change(person_money, 'money', 'members', ('id', p_id), ('system', system)) if bot_money != 'inf': database.change(bot_money, 'money', 'systems', ('id', system))