Example #1
0
File: main.py Project: BojPav/chat-
    def get(self):
        user = users.get_current_user()

        if user:
            logiran = True
            logout_url = users.create_logout_url('/')

            seznam = Chat.query().fetch()
            #params = {"seznam": seznam}

            params = {
                "seznam": seznam,
                "logiran": logiran,
                "logout_url": logout_url,
                "user": user
            }
            return self.render_template("hello.html", params=params)
        else:
            logiran = False
            login_url = users.create_login_url('/')

            seznam = Chat.query().fetch()
            #params = {"seznam": seznam}

            params = {
                "seznam": seznam,
                "logiran": logiran,
                "login_url": login_url,
                "user": user
            }
            return self.render_template("hello.html", params=params)
Example #2
0
    def create(self, request):
        activity_id = request.POST.get("activity_id", 0)
        text = request.POST.get("text", "")
        service = request.POST.get("service", "dev")
        try:
            #TODO 检查用户是否有权限发布消息
            activity = Activity.objects.get(pk=activity_id)
        except Activity.DoesNotExist:
            activity = None
        if not activity:
            return rc.NOT_FOUND
        
        if "" == text:
            empty = rc.BAD_REQUEST
            empty.write("Text can not empty.")
            return empty
        ip_address = utils.get_client_ip(request)
        chat = Chat(user=request.user, activity=activity, text=text, \
                    ip=ip_address)
        chat.save()

        notification = push_models.Notification(message=text)
        notification.extra = {\
            'activity_id': activity_id,
            'chat_id': chat.id,
            'user_id': request.user.id,
            'chat_text': text,
            'type': 'chat',
        }
        devices = activity.devices(service, exclude=[request.user])
        send_notification(devices, service, notification)
        return chat
Example #3
0
 def form_valid(self, form):
     if self.can_not_send_mess:
         self.set_message(
             u'Вы не можете добавлять коментарии не ко своим вопросам',
             True)
         return self.form_invalid(form)
     body = form.cleaned_data['body']
     file = form.cleaned_data['file']
     new_msg = Chat(question=self.question,
                    admin_name=self.user,
                    body=body,
                    date=now())
     new_msg.save()
     if file:
         new_file = Files(content_object=new_msg,
                          file=file,
                          name=file.name,
                          size=file.size,
                          date=now())
         new_file.save()
     answers_count = Chat.objects.filter(question=self.question).count()
     self.question.answers = answers_count
     self.question.save()
     self.set_message(u'Ответ успешно добавлен.')
     return super(QuesChatForm, self).form_valid(form)
Example #4
0
 def post(self):
     name = self.request.get("name")
     message = self.request.get("message")
     time = datetime.now().strftime("%d.%m.%Y ob %H:%M")
     save_message = Chat(name=name, message=message, time=time)
     save_message.put()
     return self.redirect_to("main-page")
Example #5
0
def chat_new(request):
    chat_users = User.objects.filter(id__in= request.POST.getlist("users[]"))
    chat = Chat(title=request.POST["title"])
    chat.save()
    for user in chat_users:
        chat_user = ChatUserList(chat= chat, user= user)
        chat_user.save()

    data = simplejson.dumps({'chat_id': chat.id, 'title': chat.title})
    return HttpResponse(data, content_type='application/json')
Example #6
0
def set_or_create_chat(id=-1, inited=True):
    try:
        chat = Chat.create(id=id, inited=inited)
    except:
        chat = Chat.get(id=id)
        chat.inited = inited

    chat.save()

    return chat
Example #7
0
def group_chat_logging(bot, update):
    """handle text msgs in group chat. MessageHandler((Filters.text & Filters.group)"""
    log.info(log_msg(update))
    
    user_id = update.effective_user.id
    full_name = update.effective_user.full_name
    msg_len = len(update.message.text)
    msg = update.message.text
    
    Chat.create(user_id=user_id, full_name=full_name, msg_len=msg_len, msg=msg)
Example #8
0
File: main.py Project: BojPav/chat-
 def post(self):
     user = users.get_current_user()
     name = user.nickname()
     message = self.request.get("message")
     #   datum = self.request.get("nastanek")   # datume generira avtomaticno
     new_message = Chat(name=name, message=message)
     new_message.put()
     seznam = Chat.query().fetch()
     #seznam = sorted(seznam)
     params = {"seznam": seznam, "user_nick": name}
     return self.redirect_to("main", params=params)
Example #9
0
def create_chat(request):
	if request.user.is_authenticated():
		chat_name = request.POST['chat_name']
		chat = Chat(
			chat_name = chat_name,
			start_time = timezone.now(),
			owner = str(request.user),
			)
		chat.save()
		return redirect('chat', id=chat.id)
	else:
		return redirect('/', status = 403)
Example #10
0
    def put(self, chat_id):
        """ activate/deactivate chat """
        _reqparse = reqparse.RequestParser()
        _reqparse.add_argument('active',
                               type=bool,
                               required=True,
                               location='json')
        args = _reqparse.parse_args()

        self.chat_id_validator(chat_id)
        Chat.update(chat_id, 'active', args['active'])
        return {}, 204
Example #11
0
def save_chat(chat_name: str):
    """
    Salva o nome de todos os chats
    :param str_chat: Lista contendo o nome de todos os chats.
    :type str_chat: list
    """
    db_url = config('DATABASE_URL')
    port = config('DATABASE_PORT', cast=int)
    c = Chat(db_url, port, chat_name)
    chat_obj = c.find_chat()
    if chat_obj is False:
        c.update_chat()
Example #12
0
def say(request):
    req =simplejson.loads(request.body)
    content = req['content']
    cmd = req['cmd']
    target = req['target']
    uid = request.user.id
    
    
    if not cmd:
        return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')

    chat = Chat()
    pattern1 = re.compile(r'<')
    content_t = re.sub(pattern1, '&lt;', content)

    pattern2 = re.compile(r'>')
    content_t = re.sub(pattern2, '&gt;', content_t)

    chat.username_id = request.user.id

    #................................................................
    if cmd == "chat":
        insertMsg(content_t,uid,datetime.datetime.now(),cmd,-1,'pub',ifPCInGame(uid))
	return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #..............................OK..................................
    if cmd == "GPCL":   #get pc list
	bValue = updateOnlineList(request)
	target_t = uid 
	content_t = getPcList(request)
	insertMsg( content_t, request.user.id, datetime.datetime.now(),"OLPC",uid,"pri",ifPCInGame(uid))
	return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #..............................OK..................................
    if cmd == "CRTG":   # create game
        bValue = updateOnlineList(request)
        
        g = createGame(uid, get_client_ip(request))

        debugLog("CRTG: createGame() return value="+str(g))
        
        if g["gid"]>0: 
            try:
                grinfo = getGIRNDByUid(uid, request.user.username)
                rCRTG = insertMsg( simplejson.dumps(grinfo),uid, datetime.datetime.now(), "CRTG", uid, "pri", g["gid"])
            except Exception,data:
                debugLog("CRTG error:"+str(Exception)+":"+str(data))
                
        else:
            rCRTG = insertMsg( g["errmsg"],uid, datetime.datetime.now(), "CRTG", uid, "pri", -1)
        
        return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
Example #13
0
def say(request):
    req = simplejson.loads(request.raw_post_data)
    username = req['username']
    content = req['content']
    
    if not content:
        return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')
        
    chat = Chat()
    chat.content = content
    chat.username = username
    chat.save()         
    return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
Example #14
0
def save_message(request):
    context = RequestContext(request)
    chat = ChatClass(request.session)
    if request.method == 'POST':
        send = Chat(
                    name = chat.get_login(),
                    message = unicode(request.POST['message']),
                    time = datetime.datetime.now(),
                    session = chat.get_session()
                )
        send.save()
    return get_message(request)
    
Example #15
0
    def run(self):
        log.info('Started tracking {}'.format(self.channel_name))

        chat = TwitchChat()
        chat.join_channel(self.channel_name)

        while not self.shutdown_flag.is_set():
            messages = chat.get_messages()
            if messages:
                Chat.save_messages(messages)

            time.sleep(TRACK_SLEEP_PERIOD)

        chat.close_connection()
        log.info('Stopped tracking {}'.format(self.channel_name))
Example #16
0
 def form_valid(self, form):
     if self.can_not_send_mess:
         self.set_message(u'Вы не можете добавлять коментарии не ко своим вопросам', True)
         return self.form_invalid(form)
     body = form.cleaned_data['body']
     file = form.cleaned_data['file']
     new_msg = Chat(question=self.question, admin_name=self.user,body=body, date=now())
     new_msg.save()
     if file:
         new_file = Files(content_object=new_msg, file=file, name=file.name, size=file.size, date=now())
         new_file.save()
     answers_count = Chat.objects.filter(question=self.question).count()
     self.question.answers = answers_count
     self.question.save()
     self.set_message(u'Ответ успешно добавлен.')
     return super(QuesChatForm, self).form_valid(form)
Example #17
0
def ch_stats_mood(channel, window=10):
    """
    Computes mood of the channel
    :param channel: channel name
    :param window: period of time in minutes in which we select messages
    :return: mood
    """
    # !!! limit is for test purposes. Sentiment analysis API is not fast
    msgs = Chat.get_messages(channel, window=window, limit=10)

    mood = {'neg': 0, 'neutral': 0, 'pos': 0}
    for msg in msgs:
        r = requests.post('http://text-processing.com/api/sentiment/',
                          {'text': msg})
        # TODO: Implement local sentiment analysis
        # !!! this API is open, thus there are limits
        # !!! moreover relying on outer service is not always good. In production I would implement
        # !!! local sentiment analysis
        # !!! hopefully, for the test case should be OK
        if r.status_code == 200:
            resp = r.json()
            for key, val in mood.items():
                mood[key] = (val + resp['probability'][key]) / 2

    return jsonify({'mood': max(mood, key=mood.get), 'moods': mood})
Example #18
0
 def _handle_start_command(self, bot, update):
     chat_id = update.message.chat_id
     chat, created = Chat.get_or_create(chat_id=chat_id)
     if created:
         bot.send_message(chat_id=chat_id, text=REGISTRATION_SUCCESS_MSG)
     else:
         bot.send_message(chat_id=chat_id, text=ALREADY_REGISTERED_MSG)
Example #19
0
def add_task(message):
    with db_session:
        try:
            if Chat.exists(id=str(message.chat.id)):
                if message.reply_to_message is not None:
                    if message.reply_to_message.from_user.id == ME:
                        bot.reply_to(message, "Cannot save my own messages")
                        return
                    add_new_task(task=message.reply_to_message.text,
                                 chat=str(message.chat.id),
                                 complete=False)
                    bot.reply_to(message, "Task was added.")
                else:
                    task = message.text.split("/add ", 1)[1]
                    add_new_task(task=task,
                                 chat=str(message.chat.id),
                                 complete=False)
                    bot.reply_to(message, "Task was added.")
            else:
                add_new_chat(message)
        except TransactionIntegrityError as e:
            print(str(e))
        except IndexError as error:
            # is a group
            if not message.text.startswith("/add@Todo_taskBot"):
                return
            task = message.text.split("/add@Todo_taskBot ", 1)[1]
            add_new_task(task=task, chat=str(message.chat.id), complete=False)
            bot.reply_to(message, "Task was added.")
        else:
            pass
Example #20
0
def add(message, creditor, debtor, amount, currency=None):
    chat, _ = Chat.get_or_create(id=message.chat.id)
    creditor, _ = User.get_or_create(username=creditor.upper())
    debtor, _ = User.get_or_create(username=debtor.upper())
    amount = Decimal(amount)
    original_amount = amount

    currency = check_currency(currency, chat.currency)

    if currency != chat.currency:
        amount = cr.convert(currency, chat.currency, amount)
    transaction = Transaction(
        chat=chat,
        transaction_id=uuid4(),
        transaction_type=TransactionType.DEBT.value,
        date=datetime.now(),
        debtor=debtor,
        creditor=creditor,
        amount=amount,
        currency=chat.currency,
        original_amount=original_amount,
        original_currency=currency
    )
    transaction.save()

    debt_graph = DebtGraph.load_graph(chat)
    debt_graph.add_debt(transaction)
    DebtGraph.save_graph(chat, debt_graph)

    return str(transaction)
Example #21
0
def newroom():
    if not g.user:
        abort(404)
    elif request.method == "POST":
        POST_ROOM = remove_tags(str(request.form['room']))
        POST_CHAT = remove_tags(str(request.form['msg']))
        if POST_CHAT != None:
            newRoom = Room(POST_ROOM, g.user.id, None, None)
            eprint("newRoom: " + str(newRoom))
            db.session.add(newRoom)
            try:
                db.session.commit()
                newChat = Chat(newRoom.id, g.user.id, None, POST_CHAT)
                eprint("newChat: " + str(newChat))
                db.session.add(newChat)
                try:
                    db.session.commit()
                    flash ("Created room: " + str(newRoom.roomname))
                    return redirect(url_for("joinroom", rid=newRoom.id))
                except Exception as e:
                    db.session.rollback()
                    eprint(str(e))
                    flash("Error adding message to new room")
                    return redirect(url_for("newroom"))
            except Exception as e:
                flash("Room creation failed")
        else:
            flash("Must enter initial message")
    return Response(render_template('/rooms/newRoom.html'), mimetype='text/html')
Example #22
0
def get_updates(count=None):
    if g.user:
        updates = Chat.as_jsonUpdates(g.user.currentroom, count)
        eprint("updates" + str(updates))
        return json.dumps(updates, default=json_serial)
    else:
        abort(404)
Example #23
0
def test_default_language_code(execute, raw_message):
    del raw_message["message"]["from"]["language_code"]

    execute(raw_message)

    chat = Chat.select().first()
    assert chat.language_code == "en"
Example #24
0
def process_message(update):
    chat_id = update['message']['chat']['id']

    data = {}
    data['chat_id'] = chat_id
    print(update['message']['text'])
    if (update['message']['text'].startswith('/token')):
        with app.app_context():
            chat = Chat.query.filter_by(chat_id=chat_id, revoked=False).first()
            if (chat == None):
                new_uuid = str(uuid.uuid1()).replace('-', '')
                # TO-DO: ADD CHECK TO SEE IF UUID ALREADY EXISTS
                new_chat = Chat(chat_id=str(chat_id), token=new_uuid)
                db.session.add(new_chat)
                db.session.commit()

                data['text'] = 'Here is your token: {}'.format(new_uuid)
            else:
                data['text'] = 'Looks like you already have a token for this chat.\n' \
                               'Here it is: {}'.format(chat.token)
    elif (update['message']['text'].startswith('/revoke')):
        with app.app_context():
            chat = Chat.query.filter_by(chat_id=chat_id, revoked=False).first()
            if (chat == None):
                data['text'] = 'You have no active token.'
            else:
                chat.revoked = True
                db.session.commit()
                data[
                    'text'] = 'Token revoked. Please use /token to generate a new one.'
    else:
        data[
            'text'] = 'Hi, please use the available commands:\n/token to generate a new token or\n/revoke to revoke a token.'
    r = requests.post(get_url('sendMessage'), data=data)
Example #25
0
def rawstats():
    msg = ""
    msg += User.Everything()
    msg += "\n\n"
    msg += Room.Everything()
    msg += "\n\n"
    msg += Chat.Everything()
    return Response(render_template('test.html', testMessage=msg), status=203, mimetype='text/html')
Example #26
0
def before_request():
    g.user = None
    g.rooms = None
    g.chats = None
    g.jchats = None
    g.others = None
    if 'uid' in session:
        g.user = User.query.filter_by(id=session['uid']).first()
        if g.user != None:
            g.rooms = Room.query.order_by(Room.lastmessage.asc()).all()
            if g.user.currentroom > 0:
                g.chats = Chat.query.filter(Chat.room == g.user.currentroom).order_by(Chat.created.asc()).all()
                g.jchats = Chat.as_json(g.user.currentroom)
                g.others = [u.username for u in User.query.filter(User.currentroom == g.user.currentroom).all()]
            else:
                g.chats = Chat.query.limit(10).all()
                g.jchats = Chat.as_json()
Example #27
0
def add_chat(user_id, msg_recieved, msg_replied, recieved_time, replied_time):
    chat = Chat(user_id=user_id,
                message_recieved=msg_recieved,
                message_reply=msg_replied,
                recieved_time=recieved_time,
                reply_time=replied_time)
    db.session.add(chat)
    db.session.commit()
Example #28
0
def test_previous_chat_messages_stood_intact(chat, execute, raw_message):
    raw_message["message"]["chat"]["id"] = 300500

    execute(raw_message)

    new_chat = Chat.select()[1]
    assert chat.messages.count() == 0
    assert new_chat.messages.count() == 1
Example #29
0
def get_chat(update):
    chat_id = update.message.chat.id
    chat = session.query(Chat).get(chat_id)
    if chat is None:
        chat = Chat(id=chat_id)
        session.add(chat)
        session.commit()
    return chat
Example #30
0
def set_default_currency(message, currency='RUB'):
    chat, _ = Chat.get_or_create(id=message.chat.id)
    old_currency = chat.currency
    chat.currency = check_currency(currency, chat.currency)
    chat.inited = True
    chat.save()

    return "Changed the default currency from %s to %s" % (old_currency, chat.currency)
Example #31
0
    def register_chat(self, msg):
        chat_id = msg['chat'].get('id')
        chat_type = msg['chat'].get('type')
        title = msg['chat'].get('title')
        chat = Chat(chat_id=chat_id, chat_type=chat_type, title=title)
        self.session.add(chat)
        self.session.commit()

        return chat
Example #32
0
def test_message_added_to_new_chat(execute, raw_message):
    execute(raw_message)

    chat = Chat.select().first()
    message = Message.select().first()
    assert message.message_id == 48
    assert message.text == "/start"
    assert message.chat == chat
    assert message.date == "2017-07-14 02:40:00+00:00"
Example #33
0
def start(bot, update):
    chat_id = update.message.chat.id
    chat = session.query(Chat).get(chat_id)
    if chat is not None:
        return help_me(bot, update)
    chat = Chat(id=chat_id)
    session.add(chat)
    session.commit()
    update.message.reply_text("Hola!, ¿necesitas /ayuda?\n")
Example #34
0
 def _add_chat(self, chat_id):
     try:
         chat = Chat(chat_id=chat_id, state='ready')
         db.session.add(chat)
         db.session.commit()
         result = 'Добро пожаловать!'
     except:
         result = 'Ошибка регистрации'
     return result
Example #35
0
def create_fake_message(user, bot, chat, text):
    """
    {
        u'message': {
            u'from': {
                u'username': u'xorduna',
                u'first_name': u'xavi',
                u'id': 15610499
            },
            u'text': u'/start',
            u'entities': [
                {u'length': 6, u'type': u'bot_command', u'offset': 0}
            ],
            u'chat': {
                u'username': u'xorduna',
                u'first_name': u'xavi',
                u'type': u'private',
                u'id': 15610499
            },
            u'date': 1488558871,
            u'message_id': 177
        },
        u'update_id': 399565371
    }

    {u'message': {u'date': 1488559366, u'text': u'wola', u'from': {u'username': u'xorduna', u'first_name': u'xavi', u'id': 15610499}, u'message_id': 178, u'chat': {u'username': u'xorduna', u'first_name': u'xavi', u'type': u'private', u'id': 15610499}}, u'update_id': 399565372}

    :param user:
    :param bot:
    :param text:
    :return:
    """

    update_id = Chat.incr_update_id(chat['id'])
    return {
        'message': {
            'from': {
                'username': user['username'],
                'first_name': user['first_name'],
                'id': user['id']
            },
            'text': text,
            #'entities': [
            #    {'length': 6, u'type': u'bot_command', u'offset': 0}
            #],
            'chat': {
                'username': user['username'],
                'first_name': user['first_name'],
                'type': u'private',
                'id': chat['id']
            },
            u'date': get_utc_timestamp(),
            u'message_id': 177
        },
        u'update_id': update_id
    }
Example #36
0
def test_chat_created(execute, raw_message):
    execute(raw_message)

    chat = Chat.select().first()
    assert chat.chat_id == 200500
    assert chat.username == "boi"
    assert chat.first_name == "John"
    assert chat.last_name == "Doe"
    assert chat.chat_type == "private"
    assert chat.language_code == "ru"
Example #37
0
        def wrapped(*args, **kwargs):
            chat, _ = Chat.get_or_create(id=args[0].chat.id)

            if need_to_be_inited == chat.inited:
                return foo(*args, **kwargs)

            if need_to_be_inited:
                return "Please, /init first"
            else:
                return "Already inited"
Example #38
0
def create(request):
    """Creates a new chat object.

    FIXME: If the given name is taken, this will just silently
    redirect the user to the already-created chat with that name
    without telling them that they did not create a new chat."""
    name = request.POST.get('name')
    if not name:
        return HttpResponseRedirect(reverse('index'))
    slug = slugify(name)
    chat = Chat(name=name, slug=slug, is_public=True, created_by=request.user)
    try:
        chat.save()
    except:
        # For now, if a chat with the same slug has already been created
        # just silently redirect to that chat.
        pass

    # Redirect the user to the URL for their new chat.
    return HttpResponseRedirect(chat.get_absolute_url())
Example #39
0
    def put(self, group_key):
        chat_key = self.get_argument("key", u"")
        update_type = self.get_argument("type", u"")
        chat = Chat.get(chat_key)

        if chat:
            if update_type == "like":
                chat.like += 1

            chat.store()
            ChatSocketHandler.broadcast(group_key, chat)

        return self.write({})
Example #40
0
    def post(self, group_key):
        participant_key = ChatTrait.get_participant_key(self)

        msg_type = self.get_argument("type", "")
        message = self.get_argument("message", "")
        reference = self.get_argument("reference", "")

        chat = Chat(
            type=msg_type,
            message=message
        )

        #set reference if exist
        if reference:
            reference = Chat.get(reference)
            if reference is not None:
                chat.reference = reference.key

        chat.store(group_key, participant_key)

        # send same group members (include myself)
        ChatSocketHandler.broadcast(group_key, chat)

        return self.write({})
Example #41
0
 def chat(self, *args, **kwargs):
     errors = {}
     if 'message' not in kwargs or len(kwargs['message']) is 0:
         errors['message'] = 'Enter a chat message'
     if errors:
         self.send_error(errors)
     else:
         self.send({'status': 'ok'})
         chat = Chat()
         chat.text = kwargs['message']
         chat.user_receive_id = kwargs['user']
         chat.user_sent = User.objects.get(id=kwargs['user_sent'])
         chat.save()
         self.publish(self.get_subscription_channels(), kwargs)