コード例 #1
0
    def post(self, host_id):
        try:
            body = request.get_json()
            user_id = get_jwt_identity()
            user = User.objects.get(id=user_id)
            host = User.objects.get(id=host_id)
            product = Product.objects.get(id=body['product_id'])

            host_chat_info = None
            chat = Chat.objects.filter(Q(host=host) & Q(users__contains=user.id) & Q(type='prviate')).first()

            if chat:
                return '', 400
            else:
                chat = Chat(host=host, product=product, type='private')
                chat.users.append(user)
                host_chat_info = ChatInfo(chat=chat, user=host)
                user_chat_info = ChatInfo(chat=chat, user=user)

                chat.save()
                host_chat_info.save()
                user_chat_info.save()

                return { 'id': str(chat.id) }, 200
        except ValidationError:
            raise SchemaValidationError
        except DoesNotExist:
            raise DocumentMissing
        except Exception as e:
            raise InternalServerError
コード例 #2
0
ファイル: chats.py プロジェクト: toddbirchard/broiestbot
def persist_chat_logs(user_name: str, room_name: str, chat_message: str,
                      bot_username: str) -> None:
    """
    Save chat log record.

    :param str user_name: Chatango username of chatter.
    :param str room_name: Chatango room where chat occurred.
    :param str chat_message: Content of the chat.
    :param str bot_username: Name of the currently run bot.

    :returns: None
    """
    try:
        if PERSIST_CHAT_DATA == "true" and bot_username in ("broiestbro",
                                                            "broiestbot"):
            session.add(
                Chat(username=user_name, room=room_name, message=chat_message))
    except IntegrityError as e:
        LOGGER.warning(f"Failed to save duplicate chat entry: {e}")
    except SQLAlchemyError as e:
        LOGGER.warning(
            f"SQLAlchemyError occurred while persisting chat data from  {user_name}, `{chat_message}`: {e}"
        )
    except Exception as e:
        LOGGER.warning(
            f"Unexpected error occurred while persisting chat data from {user_name}, `{chat_message}`: {e}"
        )
コード例 #3
0
async def confirm_call(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        admin_id = db.students.get_system_id_of_student(
            ans.object.object.message.peer_id, )
        msg = call.generate_message(admin_id)
        store = db.admin.get_admin_storage(admin_id)
        chat_id = Chat.get_by_id(store.current_chat_id).chat_id
        try:
            query = await api.messages.get_conversations_by_id(chat_id)
            chat_name = query.response.items[0].chat_settings.title
        except IndexError:
            chat_name = "???"
        if not msg and not store.attaches:
            raise EmptyCallMessage("Сообщение призыва не может быть пустым")
        db.shortcuts.update_admin_storage(
            db.students.get_system_id_of_student(
                ans.object.object.message.peer_id),
            state_id=db.bot.get_id_of_state("confirm_call"),
        )
        await ans.answer(
            f'Сообщение будет отправлено в чат "{chat_name}":\n{msg}',
            keyboard=kbs.call.call_prompt(
                db.students.get_system_id_of_student(
                    ans.object.object.message.peer_id), ),
            attachment=store.attaches or "",
        )
コード例 #4
0
    def test_get_active_chat(self):

        test_admin_id = 1
        test_chat = Chat.get(id=2)

        res = shortcuts.get_active_chat(test_admin_id)

        it(res).should.be_equal(test_chat)
コード例 #5
0
def song(text,chat):
    s = Song.is_song(text)

    if s not None:
        c = Chat.get_chat(chat)
        t = Tracker.find_tracker(c,s)

        return t.next_line(text)
コード例 #6
0
def delete_chat(chat_id: int) -> int:
    """
    Удаляет чат из зарегистрированных.

    Args:
        chat_id: идентфикатор чата

    Returns:
        int: количество удаленных записей
    """
    return Chat.delete().where(Chat.id == chat_id).execute()
コード例 #7
0
def get_active_chat(admin_id: int) -> Chat:
    """
    Получает объект активного чата конкретного администратора.

    Args:
        admin_id: идентификатор администратора

    Returns:
        Chat: объект активного чата
    """
    store = db.admin.get_admin_storage(admin_id)
    return Chat.get_by_id(store.current_chat_id)
コード例 #8
0
def get_list_of_chats_by_group(group_id: int) -> t.List[Chat]:
    """
    Возвращает список чатов активной группы.

    Args:
        group_id: Идентификатор группы

    Returns:
        list[Chat]: Список объектов чатов
    """
    query = Chat.select().where(Chat.group_id == group_id)
    return shortcuts.generate_list(query)
コード例 #9
0
def register_chat(chat_id: int, group_id: int) -> Chat:
    """
    Зарегистрировать чат.

    Args:
        chat_id: идентификатор чата
        group_id: идентификатор группы

    Returns:
        Chat: объект чата
    """
    return Chat.create(chat_id=chat_id, group_id=group_id)
コード例 #10
0
    def post(self, host_id):
        try:
            user_id = get_jwt_identity()
            user = User.objects.get(id=user_id)
            host = User.objects.get(id=host_id)

            host_chat_info = None
            chat = Chat.objects(host=host, type='public').first()
            if chat:
                if user not in chat.users and user not in chat.admins and user != chat.host:
                    chat.users.append(user)
            else:
                chat = Chat(host=host)
                chat.users.append(user)
                host_chat_info = ChatInfo(chat=chat, user=host)


            message = Message(type='userJoined', text='', author=user)
            chat.messages.append(message)

            chat_info = ChatInfo.objects(chat=chat, user=user).first()
            if not chat_info:
                chat_info = ChatInfo(chat=chat, user=user)

            chat_info.message = get_last_message(chat)

            message.save()
            chat.save()
            chat_info.save()

            if host_chat_info:
                host_chat_info.save()

            return { 'id': str(chat.id) }, 200
        except DoesNotExist:
            raise DocumentMissing
        except Exception as e:
            raise InternalServerError
コード例 #11
0
def is_chat_registered(chat_id: int, group_id: int) -> bool:
    """
    Проверяет, был ли зарегистрирован чат для группы.

    Args:
        chat_id: Идентификатор чата
        group_id: Идентификатор группы

    Returns:
        bool: Флаг регистрации чата
    """
    chat = Chat.get_or_none(chat_id=chat_id, group_id=group_id)
    if chat is not None:
        return True
    return False
コード例 #12
0
async def configure_chat(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        payload = hyperjson.loads(ans.object.object.message.payload)
        chat = Chat.get_by_id(payload["chat_id"])
        chat_object = await api.messages.get_conversations_by_id(
            peer_ids=chat.chat_id,
            group_id=os.getenv("GROUP_ID"),
        )
        try:
            chat_title = chat_object.response.items[0].chat_settings.title
        except IndexError:
            chat_title = "???"
        await ans.answer(
            f"Настройки чата {chat_title}",
            keyboard=kbs.preferences.configure_chat(chat.id),
        )
コード例 #13
0
    def get(self):
        try:
            user_id = get_jwt_identity()
            user = User.objects.get(id=user_id)
            chats = Chat.objects(type='private', users__contains=user)

            all_sessions = [convert_session(session) for session in Session.objects(host=user)]
            for chat in chats:
                sessions = Session.objects(chats__contains=chat)
                for session in sessions:
                    all_sessions.append(convert_session_chat(session, chat))

            return Response(JSONEncoder().encode(all_sessions), mimetype="application/json", status=200)
        except DoesNotExist:
            raise DocumentMissing
        except Exception as e:
            raise InternalServerError
コード例 #14
0
async def send_call(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        admin_id = db.students.get_system_id_of_student(
            ans.object.object.message.peer_id, )
        store = db.admin.get_admin_storage(admin_id)
        msg = call.generate_message(admin_id)
        await api.messages.send(
            peer_id=Chat.get_by_id(store.current_chat_id).chat_id,
            message=msg,
            random_id=random.getrandbits(64),
            attachment=store.attaches or "",
        )
        db.shortcuts.clear_admin_storage(admin_id)
        await ans.answer(
            "Сообщение отправлено",
            keyboard=kbs.main.main_menu(admin_id),
        )
コード例 #15
0
ファイル: bot.py プロジェクト: acleee/acleebot
    def on_message(self, room: Room, user: User, message: Message) -> None:
        """
        Triggers upon every chat message to parse commands, validate users, and save chat logs.

        :param Room room: Chatango room.
        :param User user: User responsible for triggering command.
        :param Message message: Raw chat message submitted by a user.

        :returns: None
        """
        chat_message = message.body.lower()
        user_name = user.name.title().lower()
        room_name = room.room_name.lower()
        self._check_blacklisted_users(room, user_name, message)
        self._get_user_data(room_name, user, message)
        self._process_command(chat_message, room, user_name, message)
        session.add(
            Chat(username=user_name, room=room_name, message=chat_message))
コード例 #16
0
async def index_chat(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        payload = hyperjson.loads(ans.object.object.message.payload)
        chat = Chat.get_by_id(payload["chat"])

        chat_members = await api.messages.get_conversation_members(chat.chat_id)
        group_members = db.students.get_active_students(chat.group_id)

        vk_set = prepare_set_from_vk(chat_members.response.items)
        db_set = prepare_set_from_db(group_members)

        diff_vk_db = vk_set.difference(db_set)  # есть в вк, нет в бд
        diff_db_vk = db_set.difference(vk_set)  # есть в бд, нет в вк

        query = await api.users.get(
            user_ids=list(diff_vk_db),
        )
        students = [Student.get(vk_id=st) for st in diff_db_vk]

        vk_list = [
            f"- @id{st.id} ({st.first_name} {st.last_name})" for st in query.response
        ]
        db_list = [
            f"- @id{st.vk_id} ({st.first_name} {st.second_name})" for st in students
        ]

        sep = "\n"

        await ans.answer(
            f"""
        Добавлены в чат, но не зарегистрированы в системе:\n{sep.join(vk_list) or "⸻"}
    Зарегистрированы в системе, но не добавлены в чат:\n{sep.join(db_list) or "⸻"}
    Вы можете зарегистрировать студентов в системе в автоматическом режиме,
     нажав соответствующую кнопку на клавиатуре. Студенты появятся в базе данных,
     вам останется лишь изменить тип их обучения (бюджет/контракт и пр.)
        """,
            keyboard=kbs.preferences.index_chat(
                chat.id,
                list(diff_vk_db),
                list(diff_db_vk),
            ),
        )
コード例 #17
0
async def call_debtors(ans: SimpleBotEvent):
    with logger.contextualize(user_id=ans.object.object.message.from_id):
        if db.chats.get_list_of_chats_by_group(
                db.admin.get_active_group(
                    db.students.get_system_id_of_student(
                        ans.object.object.message.from_id), ), ):
            msgs = generate_debtors_call(
                db.students.get_system_id_of_student(
                    ans.object.object.message.from_id), )
            db.shortcuts.update_admin_storage(
                db.students.get_system_id_of_student(
                    ans.object.object.message.from_id),
                state_id=db.bot.get_id_of_state("confirm_debtors_call"),
            )
            store = db.admin.get_admin_storage(
                db.students.get_system_id_of_student(
                    ans.object.object.message.from_id), )
            chat_id = Chat.get_by_id(store.current_chat_id).chat_id
            chat_object = await api.messages.get_conversations_by_id(chat_id)
            try:
                chat_title = chat_object.response.items[0].chat_settings.title
            except IndexError:
                chat_title = "???"
            for msg in msgs:
                await ans.answer(msg)
            if len(msgs) > 1:
                text = f"Сообщения будут отправлены в {chat_title}"
            else:
                text = f"Сообщение будет отправлено в {chat_title}"
            await ans.answer(
                text,
                keyboard=kbs.finances.confirm_debtors_call(),
            )
        else:
            await ans.answer(
                "У вашей группы нет зарегистрированных чатов. Возврат в главное меню",
                keyboard=kbs.finances.fin_category(),
            )