Ejemplo n.º 1
0
def get_user_chats(user_id):
    """
    Returns tuple: chat, if user contains in this chat, if user is admin of the chat
    """
    res = []
    if user_id > 0:
        user_chats = pony.orm.select(
            (c,
             pony.orm.exists(a for a in data_models.chat_admin
                             if c.chat_id == a.chat.chat_id
                             and u.user_id == a.user.user_id))
            for c in data_models.chat for u in data_models.user
            if u.user_id == user_id and (c.opened or not pony.orm.exists(
                b for b in data_models.ban_list if c.chat_id == b.chat.chat_id
                and u.user_id == b.user.user_id)))[:]

        for (c, admin) in user_chats:
            chat = models.Chat()
            chat.fill_from_data(c)
            res.append((chat, admin))

    else:
        user_chats = pony.orm.select(c for c in data_models.chat
                                     if c.opened)[:]
        for c in user_chats:
            chat = models.Chat()
            chat.fill_from_data(c)
            res.append((chat, False))

    return res
Ejemplo n.º 2
0
def add_message_to_db(data):
    message_type = get_message_type(data["message"])
    user = models.Users.query.get(user_emails[request.sid])
    db.session.add(models.Chat(user.email, data["message"], message_type))
    db.session.commit()

    bot_answer = bot.command(data["message"])
    if bot_answer:
        db.session.add(models.Chat(BOT_NAME, bot_answer, "text"))
        db.session.commit()
Ejemplo n.º 3
0
    def cmd_stop(self, update, context):
        """/stop command"""
        if update.effective_user.is_bot is True:
            return

        self.logger.info(update.message.text + ' from user ' +
                         str(update.effective_user.id))

        if update.effective_chat.id not in self.chats \
           or self.chats[update.effective_chat.id].is_on is False:
            return

        chat = self.chats[update.effective_chat.id]
        chat.is_on = False
        self.session.merge(
            models.Chat(id=chat.id,
                        u_id=chat.u_id,
                        q_id=chat.q_id,
                        is_on=chat.is_on,
                        lang=Config.DEFAULT_LANGUAGE,
                        game=chat.game.name))
        self.session.commit()

        stop_message = self.texter.get_text(text_id='game_stopped',
                                            lang=chat.lang)
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=stop_message,
                                 parse_mode="HTML",
                                 disable_web_page_preview=True)
Ejemplo n.º 4
0
def create_chat(user_key_1, user_key_2, title_1=None, title_2=None):
    from datetime import datetime
    chat_id = common.get_chat_key_name(user_key_1, user_key_2)

    userchat_key_1 = db.Key.from_path('User', user_key_1.id_or_name(),
                                      'UserChat', chat_id)
    userchat_key_2 = db.Key.from_path('User', user_key_2.id_or_name(),
                                      'UserChat', chat_id)

    userchat_1, userchat_2 = db.get([userchat_key_1, userchat_key_2])
    if userchat_1 is not None and userchat_2 is not None:
        return userchat_1, userchat_2

    chat_key = db.Key.from_path('Chat', chat_id)
    chat = models.Chat(key=chat_key)

    userchat_name_1 = models.User.get_username(user_key_2)
    userchat_name_2 = models.User.get_username(user_key_1)

    userchat_1 = models.UserChat(key=userchat_key_1,
                                 chat=chat_key,
                                 peer_userchat=userchat_key_2,
                                 name=userchat_name_1,
                                 title=title_1,
                                 last_updated=datetime.now())
    userchat_2 = models.UserChat(key=userchat_key_2,
                                 chat=chat_key,
                                 peer_userchat=userchat_key_1,
                                 name=userchat_name_2,
                                 title=title_2)

    db.put([chat, userchat_1, userchat_2])

    return userchat_1, userchat_2
Ejemplo n.º 5
0
def add_message_with_room_id(roomName, message):
    db.session.add(models.Chat(message, roomName))
    db.session.commit()
    if roomName in FAKEDB:
        FAKEDB[roomName].append(message)
    else:
        FAKEDB[roomName] = [message]
Ejemplo n.º 6
0
    def cmd_next(self, update, context):
        """/next command"""

        if update.effective_user.is_bot is True:
            return

        if update.effective_chat.id not in self.chats:
            return

        self.logger.info(update.message.text + ' from user ' +
                         str(update.effective_user.id))

        chat = self.chats[update.effective_chat.id]
        if chat.is_on is False:
            return

        if chat.next_question():
            self.session.merge(
                models.Chat(id=chat.id,
                            u_id=chat.u_id,
                            q_id=chat.q_id,
                            is_on=chat.is_on,
                            lang=chat.lang,
                            game=chat.game.name))
            self.session.commit()
            self.cmd_ask(update, context)
        else:
            out_text = self.texter.get_text('lets_think_more', lang=chat.lang) \
                .format(question=chat.get_question())
            context.bot.send_message(chat_id=chat.id,
                                     text=out_text,
                                     parse_mode='HTML')
Ejemplo n.º 7
0
def get_chat_by_name(name):
    chats = data_models.chat.select(lambda c: c.name == name)[:1]
    if chats:
        res = models.Chat()
        res.fill_from_data(chats[0])
        return res
    return None
Ejemplo n.º 8
0
    def cmd_lang(self, update, context):
        """/lang command"""
        if update.effective_user.is_bot is True:
            return

        self.logger.info(update.message.text + ' from user ' +
                         str(update.effective_user.id))

        if update.effective_chat.id not in self.chats \
           or self.chats[update.effective_chat.id].is_on is False:
            return

        chat = self.chats[update.effective_chat.id]
        if chat.lang == 'en':
            chat.lang = 'ru'
        else:
            chat.lang = 'en'
        self.session.merge(
            models.Chat(id=chat.id,
                        u_id=chat.u_id,
                        q_id=chat.q_id,
                        is_on=chat.is_on,
                        lang=chat.lang,
                        game=chat.game.name))
        self.session.commit()

        lang_message = self.texter.get_text(
            text_id='lang_set', lang=chat.lang).format(lang=chat.lang)
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=lang_message,
                                 parse_mode="HTML",
                                 disable_web_page_preview=True)
Ejemplo n.º 9
0
def get_chat(chat_id):
    try:
        chat = data_models.chat[chat_id]
        res = models.Chat()
        res.fill_from_data(chat)
        return res
    except pony.orm.ObjectNotFound:
        return None
Ejemplo n.º 10
0
 async def get(self):
     if self.request.get("user"):
         c = models.Chat()
         chats = c.FindAllForUser(
             user_id=self.request["user_session"].user_id)
         response = []
         for chat in chats:
             response.append(await chat.to_json())
         return web.json_response(response)
     return web.HTTPUnauthorized()
Ejemplo n.º 11
0
 async def get(self):
     if 'user_session' in self.request:
         c = models.Chat(id=self.request.match_info['id'])
         chat = c.FindOneForUser(
             user_id=self.request["user_session"].user_id, )
         if chat:
             response = await chat.to_json()
             return web.json_response(response)
         else:
             return web.HTTPNotFound()
     return web.HTTPUnauthorized()
Ejemplo n.º 12
0
async def get_dialogs():
    if not user.is_connected():
        await user.connect()
    if not await user.is_user_authorized():
        return templates.get_template("auth/not_authorized.html").render()
    dialogs = await user.get_dialogs()
    chats = [
        models.Chat(id=chat.id, title=chat.title, unread=chat.unread_count)
        for chat in dialogs
    ]
    return templates.get_template("chats.jinja2").render(chats=chats)
Ejemplo n.º 13
0
def _on_new_address(data):
    print("Got an event for new message input with data:", data)
    db.session.add(models.Chat(data["message"]))
    db.session.commit()
    string = []
    if "!! " in data["message"]:
        if "!! about" in data["message"]:
            db.session.add(models.Chat(bot.about(data["message"])))
            db.session.commit()
        if "!! help" in data["message"]:
            db.session.add(models.Chat(bot.helps(data["message"])))
            db.session.commit()
        if "!! date" in data["message"]:
            db.session.add(models.Chat(bot.dates(data["message"])))
            db.session.commit()
        if "!! funtranslate" in data["message"]:
            string = data["message"]
            word = string.split("!!funtranslate")
            db.session.add(
                models.Chat(bot.fun_translate(data["message"], word[1])))
            db.session.commit()
    _emit_all_chats(CHAT_RECEIVED_CHANNEL)
Ejemplo n.º 14
0
 async def delete(self):
     if 'user_session' in self.request:
         c = models.Chat(id=self.request.match_info['id'])
         chat = c.FindOneForUser(
             user_id=self.request["user_session"].user_id, )
         if chat:
             err = chat.Delete()
             if err == None:
                 return web.HTTPNoContent()
             else:
                 return web.Response(text="422: %s" % str(err), status=422)
         else:
             return web.HTTPNotFound()
     return web.HTTPUnauthorized()
Ejemplo n.º 15
0
    def cmd_hint(self, update, context):
        """/hint command"""

        if update.effective_user.is_bot is True:
            return

        if update.effective_chat.id not in self.chats:
            return

        self.logger.info(update.message.text + ' from user ' +
                         str(update.effective_user.id))

        chat = self.chats[update.effective_chat.id]
        if chat.is_on is False:
            return

        hint_result = chat.do_hint()

        if hint_result == 'hint_ok':
            sym = self.texter.get_text('hint_symbol', lang=chat.lang)
            sep = self.texter.get_text('hint_separator', lang=chat.lang)
            out_text = self.texter.get_text('hint_text', lang=chat.lang) \
                .format(hint_text=chat.get_hint_text(sym, sep))
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text=out_text,
                                     parse_mode='HTML')
        elif hint_result in ['whole_word_open', 'max_time_exceed']:
            chat.next_question()
            self.session.merge(
                models.Chat(id=chat.id,
                            u_id=chat.u_id,
                            q_id=chat.q_id,
                            is_on=chat.is_on,
                            lang=chat.lang,
                            game=chat.game.name)
            )  # TODO improvement: add different game types later
            self.session.commit()
            out_text = self.texter.get_text('nobody_could', lang=chat.lang)
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text=out_text,
                                     parse_mode='HTML')
            out_text = self.texter.get_text('ask_question', lang=chat.lang) \
                .format(question=chat.get_question())
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text=out_text,
                                     parse_mode='HTML')
        elif hint_result == 'hint_pause_not_spent':
            pass
        else:
            self.logger.error('Hint error: ' + hint_result)
Ejemplo n.º 16
0
def on_new_message(data):
    new_str = data["entry"]

    date = datetime.datetime.now()
    time = str(
        datetime.datetime.now(
            pytz.timezone("US/Eastern")).strftime("%H:%M"))  # NYC time
    time_str = months[date.month - 1] + " " + str(date.day) + " \n@" + time

    user_id = data["email"]
    db.session.add(models.Chat(data["entry"], time_str, user_id))
    db.session.commit()
    emit_all_messages(MESSAGE_RECEIVED_CHANNEL)
    displaying_quotes()
Ejemplo n.º 17
0
    async def get(self):
        if 'user_session' in self.request:
            c = models.Chat(id=self.request.match_info['id'])
            chat = c.FindOneForUser(
                user_id=self.request["user_session"].user_id, )
            if chat:
                query_params = {}
                if len(self.request.query_string) > 0:
                    query_params = parse_qs(self.request.query_string)

                response = []
                messages = chat.GetMessages(params=query_params)
                for message in messages:
                    response.append(await message.to_json())
                return web.json_response(response)
            else:
                return web.HTTPNotFound()
        return web.HTTPUnauthorized()
Ejemplo n.º 18
0
    async def post(self):
        user = self.request.get("user")
        if user:
            data = await self.request.post()

            c = models.Chat()
            chat, err = c.Create(creator=user,
                                 name=data.get('name', ''),
                                 raw_members=data.getall('members', []))
            if err == None:
                response = await chat.to_json()
                return web.json_response(response, status=201)
            else:
                if err == exceptions.ChatWithMembersAlreadyExists:
                    return web.HTTPConflict()
                else:
                    return web.Response(text="422: %s" % str(err), status=422)
        return web.HTTPUnauthorized()
Ejemplo n.º 19
0
    def _put_message_to_database(self, update):
        session = self.bot_db.get_session()
        try:
            chat = session.query(models.Chat).filter_by(id=update.message.chat_id).first()
            if chat is None:
                chat = models.Chat(update.message.chat.id, update.message.chat.type, update.message.chat.title,
                                   update.message.chat.first_name, update.message.chat.last_name,
                                   update.message.chat.username)
                session.add(chat)
            else:
                chat.id = update.message.chat.id
                chat.type = update.message.chat.type
                chat.title = update.message.chat.title
                chat.first_name = update.message.chat.first_name
                chat.last_name = update.message.chat.last_name
                chat.username = update.message.chat.username
                session.merge(chat)

            user = session.query(models.User).filter_by(id=update.message.from_user.id).first()
            if user is None:
                user = models.User(update.message.from_user.id, update.message.from_user.username,
                                   update.message.from_user.first_name, update.message.from_user.last_name,
                                   update.message.from_user.type)
                session.add(user)
            else:
                user.id = update.message.from_user.id
                user.username = update.message.from_user.username
                user.first_name = update.message.from_user.first_name
                user.last_name = update.message.from_user.last_name
                user.type = update.message.from_user.type
                session.merge(user)

            if chat not in user.participate_in_chats:
                user.participate_in_chats.append(chat)
            if user not in chat.users_in_chat:
                chat.users_in_chat.append(user)

            session.commit()
            return chat, user
        except Exception as e:
            print(str(e))
            session.rollback()
        finally:
            session.close()
Ejemplo n.º 20
0
    def cmd_play(self, update, context):
        """/play command"""
        if update.effective_user.is_bot is True:
            return

        self.logger.info(update.message.text + ' from user ' +
                         str(update.effective_user.id))

        if update.effective_chat.get_member_count(
        ) < self.parameters['min_members']:
            out_text = self.texter.get_text('min_members_group_play',
                                            lang=Config.DEFAULT_LANGUAGE)
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text=out_text.format(
                    min_members=self.parameters['min_members']),
                parse_mode='HTML')
            return
        if update.effective_chat.id not in self.chats:
            # TODO improvement: add different game types later
            game = self.games['textquiz']
            chat = Chat(c_id=update.effective_chat.id,
                        u_id=update.effective_user.id,
                        game=game,
                        parameters=self.parameters,
                        is_on=True,
                        lang=Config.DEFAULT_LANGUAGE)
            chat.next_question()
            self.chats[update.effective_chat.id] = chat
        else:
            chat = self.chats[update.effective_chat.id]
            chat.is_on = True
        self.session.merge(
            models.Chat(id=chat.id,
                        u_id=chat.u_id,
                        q_id=chat.q_id,
                        is_on=chat.is_on,
                        lang=chat.lang,
                        game=chat.game.name))
        self.session.commit()
        if update.effective_user.id not in chat.users:
            self.new_player(update)
        self.cmd_ask(update, context)
Ejemplo n.º 21
0
def update_chat(user1, user2):
    net_chats = models.Chat.query.all()
    chat_a = list(
        filter(lambda chat: chat.user1 == user1 and chat.user2 == user2,
               net_chats))
    chat_b = list(
        filter(lambda chat: chat.user1 == user2 and chat.user2 == user1,
               net_chats))
    data = request.get_json()

    if len(chat_a) > 0:
        chat = chat_a[0]
        chat_list = json.loads(chat.chat)
        chat_list.append(data)
        out = json.dumps(chat_list)
        chat.chat = out
        db.session.commit()
        print(chat_a[0].chat)

    elif len(chat_b) > 0:
        chat = chat_b[0]
        chat_list = json.loads(chat.chat)
        chat_list.append(data)
        out = json.dumps(chat_list)
        chat.chat = out
        db.session.commit()
        print(chat_b[0].chat)

    else:
        chat_list = []
        chat_list.append(data)
        out = json.dumps(chat_list)
        chat = models.Chat(user1=user1, user2=user2, chat=out)
        db.session.add(chat)
        print(chat_list)
        db.session.commit()

    response = jsonify({'success': True})
    return response
Ejemplo n.º 22
0
    async def post(self):
        if 'user_session' in self.request:
            c = models.Chat(id=self.request.match_info['id'])
            chat = c.FindOneForUser(
                user_id=self.request["user_session"].user_id, )
            if chat:
                data = await self.request.post()

                query_params = {}
                if len(self.request.query_string) > 0:
                    query_params = parse_qs(self.request.query_string)
                    err = chat.AddMembers(members=query_params.all('members'))
                else:
                    err = chat.SendMessage(
                        sender=self.request["user"],
                        message_text=data.get('message', ''),
                    )
                if err == None:
                    return web.HTTPCreated()
                else:
                    return web.Response(text="422: %s" % str(err), status=422)
            else:
                return web.HTTPNotFound()
        return web.HTTPUnauthorized()
Ejemplo n.º 23
0
    def message(self, update, context):
        """message in chat"""

        # new message in bot channel
        if update.effective_chat.id == self.channel and update.channel_post.message_id:
            self.logger.info(update.channel_post.text + ' from channel ' +
                             str(update.effective_chat.id))
            for user in self.admins:
                context.bot.forward_message(user, self.channel,
                                            update.channel_post.message_id)
                out_text = self.texter.get_text('broadcast_newpost', lang=Config.DEFAULT_LANGUAGE) \
                    .format(message_id=str(update.channel_post.message_id))
                context.bot.send_message(chat_id=user,
                                         text=out_text,
                                         parse_mode='HTML')
            return

        # message in game chat
        if update.effective_user.is_bot is True:
            return

        if update.effective_chat.id not in self.chats:
            return

        chat = self.chats[update.effective_chat.id]
        if chat.is_on is False:
            return

        if update.effective_user.id not in chat.users:
            self.new_player(update)
        user = chat.users[update.effective_user.id]

        if chat.max_time_exceed():
            context.bot.send_message(chat_id=chat.id,
                                     text=self.texter.get_text('nobody_could',
                                                               lang=chat.lang),
                                     parse_mode='HTML')
            chat.next_question()
            self.session.merge(
                models.Chat(id=chat.id,
                            u_id=chat.u_id,
                            q_id=chat.q_id,
                            is_on=chat.is_on,
                            lang=chat.lang,
                            game=chat.game.name)
            )  # TODO improvement: add different game types later
            self.session.commit()
            out_text = self.texter.get_text('ask_question', lang=chat.lang) \
                .format(question=chat.get_question())
            context.bot.send_message(chat_id=chat.id,
                                     text=out_text,
                                     parse_mode='HTML')
            return

        if chat.game.answer_is_correct(chat.q_id, update.message.text) \
           and chat.is_on and chat.got_correct_answer is False:
            # turn off game, we don't want to get more than one winner
            chat.got_correct_answer = True

            # calculate points for correction answer
            points = chat.parameters['base_points'] \
                - chat.hint.count(True) / len(chat.hint) \
                * chat.parameters['base_points']
            multiplied_points = points = int(round(points, 0))
            if points < 1:
                points = 1
            combo_str_list = []

            # double points if it was quick answer
            if chat.check_speed():
                multiplier = 2
                points = points * multiplier
                combo_str_list.append(
                    self.texter.get_text('quick_answer', lang=chat.lang) \
                        .format(multiplier=multiplier))

            # count correct answer in chat and user
            chat.count_correct_answer(user)

            # if user exceeded limit count of answers in series
            if chat.answer_count > chat.parameters['series_max']:
                points = chat.parameters['google_points']
                combo_str_list.append(
                    self.texter.get_text('was_googled', lang=chat.lang))
            else:
                # series is going, multiply points
                multiplier = chat.answer_count
                multiplied_points = points * multiplier
                combo_str_list.append(
                    self.texter.get_text('series_answer', lang=chat.lang) \
                        .format(multiplier=multiplier))

            user.add_points(multiplied_points)
            self.session.merge(
                models.User(chat_id=chat.id,
                            id=user.id,
                            correct_answers=user.correct_answers,
                            points=user.points,
                            user_name=user.name))
            self.session.commit()
            out_text = self.texter.get_text('get_points', lang=chat.lang) \
                .format(username=user.get_name(),
                        points=str(points))
            out_text += '\n' + '\n'.join(combo_str_list)
            out_text += '\n' + self.texter.get_text('result_points', lang=chat.lang) \
                .format(points=str(multiplied_points))

            # congratulate user
            context.bot.send_message(chat_id=chat.id,
                                     text=out_text,
                                     parse_mode='HTML')

            # go to the next question
            chat.next_question()
            self.session.merge(
                models.Chat(id=chat.id,
                            u_id=chat.u_id,
                            q_id=chat.q_id,
                            is_on=chat.is_on,
                            lang=chat.lang))
            self.session.commit()

            out_text = self.texter.get_text('ask_question', lang=chat.lang) \
                .format(question=chat.get_question())
            context.bot.send_message(chat_id=chat.id,
                                     text=out_text,
                                     parse_mode='HTML')

        # wrong answer and bad words in it
        elif self.texter.check_bad(update.message.text):
            update.message.reply_text(self.texter.get_joke())