def send_me(message, person): """Присылает человеку его запись в БД""" LOG.log(str(message.from_user.id) + ": send_me invoked") database = Database() system = database.get('chats', ('id', message.chat.id))['system'] chat_config = get_system_configs(system) money_name = chat_config['money_name'] money_name_word = get_word_object(money_name, 'ru') member_update(system, person) # Update person's messages, nickname and username person_entry = get_person(message, person, system, database, system_configs=chat_config) appointments = [x['appointment'] for x in database.get_many('appointments', ('id', person.id), ('system', system))] messages_here = 0 if database.get('messages', ('person_id', person.id), ('chat_id', message.chat.id)): messages_here = database.get('messages', ('person_id', person.id), ('chat_id', message.chat.id))['messages'] msg = 'ID: {}\n'.format(person_entry['id']) msg += 'Юзернейм: {}\n'.format(person_entry['username']) msg += 'Никнейм: {}\n'.format(person_entry['nickname']) msg += 'Ранг: {}\n'.format(person_entry['rank']) msg += 'Кол-во сообщений в этом чате: {}\n'.format(messages_here) if person_entry['messages']: msg += 'Кол-во сообщений во всей системе: {}\n'.format(person_entry['messages']) msg += 'Кол-во предупреждений: {}\n'.format(person_entry['warns']) if chat_config['money']: msg += 'Кол-во {}: {}\n'.format(money_name_word.genitive_plural(), person_entry['money']) if appointments: msg += 'Должности: ' + ', '.join(appointments) reply(message, msg)
def admins(message): """@-mention all admins""" database = Database() chat = database.get('chats', ('id', message.chat.id)) system = chat['system'] chat_config = get_system_configs(system) boss = chat_config['commands']['boss'] ranks = chat_config['ranks'] admins_username = [] if isinstance(boss, list): all_ranks = ranks[ranks.index(boss[0]):ranks.index(boss[1]) + 1] for rank in all_ranks: admins_username += [ '@' + x['username'] for x in database.get_many('members', ('rank', rank), ('system', system)) ] elif isinstance(boss, str): admins_id = [ admin['id'] for admin in database.get_many('appointments', ('appointment', boss)) ] admins_username = [ '@' + database.get('members', ('id', admin), ('system', system))['username'] for admin in admins_id ] reply(message, 'Вызываю сюда админов: ' + ', '.join(admins_username))
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 send_short_top(message, language, format_string, start='', sort_key=lambda x: True): """Send a short version of a top for non-admins""" database = Database() # Declaring variables system = database.get('chats', ('id', message.chat.id))['system'] formating_dict = {'m_emo': get_system_configs(system)['money_emoji'], 'bot_money': database.get('systems', ('id', system))['money']} text = start.format(**formating_dict) members = database.get_many('members', ('system', system)) members = list(filter(lambda x: sort_key(x) != 0, members)) members.sort(key=sort_key, reverse=True) person_index = 0 for person_index in range(1, len(members) + 1): if members[person_index - 1]['id'] == message.from_user.id: break # Main loop for index in range(1, len(members) + 1): member = members[index - 1] p_link = link_text_wrapper(html_cleaner(member["nickname"]), f't.me/{member["username"]}') formating_dict.update(member) formating_dict.update({'index': index, 'p_link': p_link, 'day': member['day_birthday']}) if '{month}' in format_string: formating_dict['month'] = MONTHS_GENITIVE[member['month_birthday'] - 1][language] if index <= 5 or abs(index - person_index) <= 2: text += format_string.format(**formating_dict) elif '.\n.\n.\n' not in text and person_index >= 9: text += '.\n.\n.\n' if text: send(message.chat.id, text, parse_mode='HTML') else: reply(message, "Ничего нет!")
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 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 send_some_top(message, language, format_string, start='', sort_key=lambda x: True): """Send a full version of a top for admins""" database = Database() # Declaring variables sent = False system = database.get('chats', ('id', message.chat.id))['system'] formating_dict = { 'm_emo': get_system_configs(system)['money_emoji'], 'bot_money': database.get('systems', ('id', system))['money'] } text = start.format(**formating_dict) members = database.get_many('members', ('system', system)) members = list(filter(lambda x: sort_key(x) != 0, members)) members.sort(key=sort_key, reverse=True) if len(members) > 50: target_chat = message.from_user.id else: target_chat = message.chat.id # Main loop for index in range(1, len(members) + 1): member = members[index - 1] p_link = link_text_wrapper(html_cleaner(member["nickname"]), f't.me/{member["username"]}') formating_dict.update(member) formating_dict.update({ 'index': index, 'p_link': p_link, 'day': member['day_birthday'] }) if '{month}' in format_string: formating_dict['month'] = MONTHS_GENITIVE[member['month_birthday'] - 1][language] text += format_string.format(**formating_dict) if index % 50 == 0: sent = send(target_chat, text, parse_mode='HTML') text = '' sent = send(target_chat, text, parse_mode='HTML') or sent if len(members) > 50: if sent: reply(message, "Выслал инфу в личку") else: reply(message, "Сначала запусти меня в личных сообщениях") elif not sent: 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 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 new_member(message, member): """Реагирует на вход в чат""" database = Database() # Declaring variables text = '' keyboard = None captcha = False sent = None name = html_cleaner(member.first_name) system = database.get('chats', ('id', message.chat.id))['system'] chat_configs = get_system_configs(system) if database.get('members', ('id', member.id), ('rank', chat_configs['ranks'][0]), ('system', system)) and \ feature_is_available(message.chat.id, system, 'violators_ban'): kick(message.chat.id, member.id) elif not cooldown(message, "entrance", timeout=database.get('systems', ('id', system))['entrance_cooldown'], notify=False, individual=False): kick_and_unban(message.chat.id, member.id) elif is_suitable(message, member, 'uber', loud=False) and feature_is_available( message.chat.id, system, 'admins_promote'): promote(message.chat.id, member.id, can_change_info=True, can_delete_messages=True, can_invite_users=True, can_restrict_members=True, can_pin_messages=True, can_promote_members=True) text += chat_configs['greetings']['full_admin'].format(name=name) elif is_suitable(message, member, 'boss', loud=False) and feature_is_available( message.chat.id, system, 'admins_promote'): promote(message.chat.id, member.id, can_change_info=False, can_delete_messages=True, can_invite_users=True, can_restrict_members=True, can_pin_messages=True, can_promote_members=False) text += chat_configs['greetings']['admin'].format(name=name) elif feature_is_available(message.chat.id, system, 'newbies_captched') and \ member.id == message.from_user.id and time() - message.date < 60: text = chat_configs['greetings']['captcha'].format(name=name) keyboard = create_captcha_keyboard() captcha = True else: text = chat_configs['greetings']['standard'].format(name=name) if feature_is_available(message.chat.id, system, 'moves_delete') and not feature_is_available( message.chat.id, system, 'newbies_captched'): delete(message.chat.id, message.message_id) else: sent = reply(message, text, reply_markup=keyboard, parse_mode='HTML') # Notify admins if admin's chat exists admin_place = database.get('systems', ('id', system))['admin_place'] if admin_place: text = f'{person_info_in_html(member)} теперь в {chat_info_in_html(message.chat)}' send(admin_place, text, parse_mode="HTML") if captcha: restrict(message.chat.id, member.id, until_date=time() + 300) captcha_ban = CaptchaBan(message, sent) captcha_ban.start()
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))