Example #1
0
def register_participant_group(worker):
    """ Will register chat as a participant group """
    chat = worker.source.message.get("chat")
    tp = get_from_Model(GroupType, name=chat['type'])
    if not chat:
        logging.info("Can't get chat to register.")
        pass
    participant_group = get_from_Model(
        ParticipantGroup, telegram_id=chat['id'])
    if participant_group:
        worker.source.bot.send_message(
            participant_group,
            "This group is already registered.",
            reply_to_message_id=worker.source.message['message_id']
        )  # Maybe add reference to the documentation with this message
    elif not tp:
        worker.source.bot.send_message(
            chat['id'],
            "Unknown type of group, to improve this connect with @KoStard.",
            reply_to_message_id=worker.source.message['message_id'])
    else:
        participant_group = ParticipantGroup(
            telegram_id=chat['id'],
            username=chat.get('username'),
            title=chat.get('title'),
            type=tp)
        participant_group.save()
        binding = BotBinding(bot=worker.source.bot, participant_group=participant_group)
        binding.save()
        worker.source.bot.send_message(
            participant_group,
            """This group is now registered and a binding is created,\
so now the bot will listen to your commands.""",
            reply_to_message_id=worker.source.message['message_id'])
def promote_to_admin(worker):
    """
    Will promote user to admin - has to be replied to that user's message.
    """
    if 'reply_to_message' not in worker.source.message:
        worker.answer_to_the_message(
            "You have to reply to the user's message to promote him/her to admin."
        )
        return False
    user_data = worker.source.message['reply_to_message']['from']
    if user_data['is_bot']:
        worker.answer_to_the_message("Can't register bot as participant.")
        return False
    participant = get_from_Model(Participant, id=user_data['id'])
    if not participant:
        participant = register_participant(user_data)
    gspd = get_from_Model(
        participant.groupspecificparticipantdata_set,
        _mode='direct',
        participant_group=worker.source.administrator_page.participant_group)
    if not gspd:
        gspd = register_groupspecificparticipantdata(
            participant=participant,
            participant_group=worker.source.administrator_page.
            participant_group)
    if gspd.is_admin:
        worker.answer_to_the_message(
            f"The user is already an admin in the {worker.source.administrator_page.participant_group.title}."
        )
        return
    create_participantgroupbinding(gspd, Role.objects.get(value='admin'))
    worker.answer_to_the_message(
        f"Congratulations, {participant.name} is now an admin.")
Example #3
0
def register_participant_group_new_members(worker) -> list:
    """
    Will register all participant group new members
    """
    new_members = []
    for new_member_data in safe_getter(worker.source,
                                       'message.new_chat_members',
                                       default=[],
                                       mode='DICT'):
        participant = get_from_Model(Participant, id=new_member_data['id'])
        if not participant:
            participant = user_registry.register_participant(new_member_data)
        gspd = get_from_Model(participant.groupspecificparticipantdata_set,
                              participant_group=worker['participant_group'],
                              _mode='direct')
        if not gspd:
            gspd = user_registry.register_groupspecificparticipantdata(
                participant=participant,
                participant_group=worker['participant_group'],
                joined=datetime.fromtimestamp(
                    worker['message']["date"],
                    tz=timezone.get_current_timezone()),
            )
        new_members.append((participant, gspd))
    worker.source.new_members_models = new_members
    return new_members
Example #4
0
def handle_message_from_user(worker):
    """ Handling message from user
    [Saving]
    - text
    - command
    - participant_group
    - is_superadmin
    - is_administrator_page
    - administrator_page
    """
    worker.source.raw_text = worker.source.message.get(
        "text") or worker.source.message.get('caption')

    # This won't work with multiargumental commands
    worker.source.command = worker.source.raw_text[1:].split(" ")[0].split('@')[0] if worker.source.raw_text and \
                                                                                      worker.source.raw_text[
                                                                                          0] == '/' else ''

    if worker.source.command:
        worker.source.command_model = get_from_Model(TelegramCommand,
                                                     command=worker.command)
        worker.source.command_argv = worker.source.raw_text.split(' ')[1:]
    else:
        worker.source.command_model = None
        worker.source.command_argv = None

    worker.source.text = worker.source.raw_text if not worker.source.command else None

    # Checking if the group is registered
    worker.source.participant_group = get_from_Model(
        ParticipantGroup, telegram_id=worker.source.message["chat"]["id"])

    if worker.source.participant_group:
        worker.source.pg_adm_page = worker.source.participant_group.get_administrator_page(
        )

    # Checking if is a superadmin
    worker.source.is_superadmin = not not SuperAdmin.objects.filter(
        user__id=worker.source.message['from']['id'])

    # Checking if in an administrator page
    worker.source.administrator_page = get_from_Model(
        AdministratorPage, telegram_id=worker.source.message['chat']['id'])
    worker.source.is_administrator_page = not not worker.source.administrator_page

    if worker.participant_group:
        # If the participant group is already registered
        user_pg_message_handler.handle_message_from_participant_group(worker)
    elif worker.source.is_administrator_page:
        # If the message is in the administrator page
        user_admp_message_handler.handle_message_from_administrator_page(
            worker)
    elif worker.source.is_superadmin or worker.source.message['chat'][
            'type'] in ('private', 'group', 'supergroup'):
        # If the user if superadmin but is sending a message not in a registered group
        user_unrgp_message_handler.handle_message_from_unregistered_target(
            worker)
    else:
        print("Don't know what to do... :/")
def handle_entities(worker) -> bool:
    """ Will handle entities from worker's message """
    entities = safe_getter(worker.source, 'message.entities', mode='dict', default=[])
    worker.entities = entities
    entities_check_response = check_entities(worker)
    worker.entities_check_response = entities_check_response
    logging.info("Found Entity: " + str(entities_check_response))
    if not entities_check_response["status"]:
        if not entities_check_response["unknown"]:
            # Sending answer message to the message with restricted entities
            worker['bot'].send_message(
                worker['participant_group'],
                message_removal_message_with_highest_role_template.format(
                    name=worker['participant'].name,
                    cause=entities_check_response["cause"],
                    highest_role=worker['groupspecificparticipantdata'].highest_role.name
                ),
                reply_to_message_id=worker['message']["message_id"],
            )
            # Removing message with restricted entities
            worker['bot'].delete_message(worker['participant_group'],
                                         worker['message']["message_id"])
            # Creating violation
            worker['groupspecificparticipantdata'].create_violation(
                get_from_Model(
                    ViolationType,
                    value='message_entity_low_permissions'),
                datetime.fromtimestamp(
                    worker['message']["date"],
                    tz=timezone.get_current_timezone()), worker=worker)
            return False
    return True
def get_groupspecificparticipantdata_of_active_participant_from_administrator_page(
        worker):
    """
    Will get groupspecificparticipantdata from administrator page and participant
    """
    worker.groupspecificparticipantdata = get_from_Model(
        worker.participant.groupspecificparticipantdata_set,
        _mode='direct',
        participant_group__administratorpage=worker.administrator_page)
def reject_command_in_pg(worker):
    worker['bot'].send_message(
        worker['participant_group'],
        command_rejection_message_template.format(
            name=worker['participant'].name,
            command=worker['command'],
            highest_role=worker['groupspecificparticipantdata'].highest_role.name
        ),
        reply_to_message_id=worker['message']["message_id"],
    )
    worker['groupspecificparticipantdata'].create_violation(
        get_from_Model(ViolationType, value='command_low_permissions'), worker=worker)
def remove_admin_binding(worker):
    """
    Will remove admin binding - has to be replied to that user's message.
    """
    if 'reply_to_message' not in worker.source.message:
        worker.answer_to_the_message(
            "You have to reply to the user's message to promote him/her to admin."
        )
        return False
    user_data = worker.source.message['reply_to_message']['from']
    participant = get_from_Model(Participant, id=user_data['id'])
    if not participant:
        worker.answer_to_the_message(
            f"The user {user_data['first_name'] or user_data['username']} is not a participant."
        )
        return False
    gspd = get_from_Model(
        participant.groupspecificparticipantdata_set,
        _mode='direct',
        participant_group=worker.source.administrator_page.participant_group)
    if not gspd:
        worker.answer_to_the_message(
            f"The user {participant.name} isn't registered in {worker.source.administrator_page.participant_group.title}."
        )
        return
    if not gspd.is_admin:
        worker.answer_to_the_message(
            f"The user {participant.name} is not an admin in the {worker.source.administrator_page.participant_group.title}."
        )
        return
    binding = get_from_Model(gspd.participantgroupbinding_set,
                             _mode='direct',
                             role__value='admin')
    if binding:
        binding.delete()
    worker.answer_to_the_message(f"{participant.name} is no longer an admin.")
Example #9
0
def check_message_length(worker):
    """
    Will check message length
    """
    if worker.source.raw_text and len(worker.source.raw_text) > TEXT_MAX_LENGTH and \
            worker.source.groupspecificparticipantdata.highest_role.priority_level <= 0 and \
            not worker.source.is_from_superadmin:  # Recruit
        worker.answer_to_the_message(
            f"Your message will be removed, because you don't have "
            f"permissions to send messages with length more than {TEXT_MAX_LENGTH}.")
        worker.bot.delete_message(worker.source.participant_group, worker.source.message['message_id'])
        worker.source.groupspecificparticipantdata.create_violation(
            get_from_Model(ViolationType, value='long_message_restriction'), worker=worker)
        return False
    return True
def handle_answer(worker):
    """
    Will handle participant answers
    """
    if not worker['participant_group'].activeProblem:
        print(f"There is no active problem in {worker['participant_group']}")
        return False
    old_answer = get_from_Model(
        worker['participant_group'].activeProblem.answer_set,
        group_specific_participant_data=worker['groupspecificparticipantdata'],
        processed=False,
        _mode='direct')
    worker.source.old_answer = old_answer
    if old_answer:
        handle_answer_change(worker)
    elif worker['bot'].for_testing:
        handle_answers_from_testing_bots(worker)
    else:
        accept_answer(worker)
Example #11
0
def check_message_language(worker):
    """
    Checking message language
    Default - only English
    """
    current_language = 'English'
    current_language_regex_negative = re.compile(r'[^a-zA-Z0-9?<>&#^_\'",.;:|+`/\\\s{}\[\]=~!@#$%^&*()£€•₽'
                            # Allowing all emojis
                            r'\u263a-\U0001f645'
                            # Allowing Greek characters
                            r'\u03B1-\u03C9\u0391-\u03A9\u03F4×µ'
                            r'-]+')
    non_english_parts = current_language_regex_negative.findall(worker.source.raw_text) if worker.source.raw_text else None
    if non_english_parts:# and not worker.is_from_superadmin:
        worker.answer_to_the_message(
            "Your message will be removed, because it contains these restricted parts: [ {} ].\n"
            "Currently allowed language is {}.".format(', '.join(non_english_parts), current_language))
        worker.bot.delete_message(worker.source.participant_group, worker.source.message['message_id'])
        worker.source.groupspecificparticipantdata.create_violation(
            get_from_Model(ViolationType, value='language_restriction'), worker=worker)
        return False
    return True
Example #12
0
def handle_message_bindings(worker) -> bool:
    message_bindings_check_response = check_message_bindings(worker)
    if not message_bindings_check_response["status"]:
        logging.info(message_bindings_check_response["cause"])
        if not message_bindings_check_response["unknown"]:
            worker['bot'].send_message(
                worker['participant_group'],
                message_removal_message_with_highest_role_template.format(
                    name=worker['participant'].name,
                    cause=', '.join(message_bindings_check_response["cause"]),
                    highest_role=worker['groupspecificparticipantdata'].
                    highest_role.name),
                reply_to_message_id=worker['message']["message_id"],
            )
            worker['bot'].delete_message(worker['participant_group'],
                                         worker['message']["message_id"])
            worker['groupspecificparticipantdata'].create_violation(
                get_from_Model(ViolationType,
                               value='message_binding_low_permissions'),
                worker=worker)
            return False
    return True
def get_message_sender_participant_from_administrator_page(worker):
    """
    Will get participant from administrator page message
    """
    if worker.source.get('message'):
        participant = get_from_Model(Participant,
                                     id=worker['message']['from']['id'])
        if not participant:
            worker.source.participant = None
            worker.source.is_from_superadmin = False
            print("Can't find participant {}".format(
                worker.message['from']['first_name']
                or worker.message['from']['username']
                or worker.message['from']['last_name']))
            return
        worker.source.participant = participant
        worker.source.is_from_superadmin = not not safe_getter(
            worker.participant, 'superadmin')
        return participant
    else:
        worker.source.participant = None
        worker.source.is_from_superadmin = False
        raise ValueError("INVALID MESSAGE DATA")