Exemple #1
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")
Exemple #2
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)
Exemple #3
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')
Exemple #4
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)
Exemple #5
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()
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
Exemple #7
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
Exemple #8
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
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")
Exemple #10
0
def add_chat(request):
    text = str(request.GET.get("text", ""))
    name = str(request.GET.get("name", ""))
    if text == "" or name == "":
        return JsonResponse({'status': 'ERROR'})
    chat = Chat()
    chat.name = name
    chat.chat = text
    chat.save()
    return JsonResponse({'status': 'OK'})
Exemple #11
0
def post_chat(request):
    if request.method == 'POST':
        response = request.META.get('HTTP_REFERER', '/')
        chat = Chat()
        chat.content = request.POST.get('chat_content')
        chat.sender = request.user
        chat.save()
        return HttpResponseRedirect(response)
    else:
        raise Http404
Exemple #12
0
 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)
Exemple #13
0
def add_new_chat(message):
    Chat(id=str(message.chat.id),
         type=message.chat.type,
         title=message.chat.title,
         username=message.chat.username,
         first_name=message.chat.first_name,
         last_name=message.chat.last_name,
         photo=message.chat.photo,
         description=message.chat.description,
         invite_link=message.chat.invite_link,
         pinned_message=message.chat.pinned_message)
Exemple #14
0
def new_message(message):
    # Emitimos el mensaje con el alias y el mensaje del usuario
    emit('new_message', {
        'username': message['username'],
        'text': message['text']
    },
         broadcast=True)
    # Salvamos el mensaje en la base de datos
    my_new_chat = Chat(username=message['username'], text=message['text'])
    db.session.add(my_new_chat)
    db.session.commit()
Exemple #15
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()
Exemple #16
0
def db_update_chat(chat_id, step, place_id=None):
    chat = db_get_chat(chat_id)
    if chat:
        chat.step = step
        if place_id:
            chat.place_id = place_id
    else:
        chat = Chat(id=chat_id, step=step)
        session.add(chat)

    session.commit()
    return chat
Exemple #17
0
def insert_chat_id(chat_id):
    """ Add chat_id to the database of chats. """
    if not is_returning_chat(chat_id):
        chat = Chat(chat_id=chat_id)
        db_session.add(chat)
        db_session.commit()
        logger.info(
            f'Inserted new chat_id: {chat_id}. Total Chats: {get_chats()}')

        return True

    return False
Exemple #18
0
def create():
    """
    Create a new chat"""
    form = NewChatForm()
    if request.method == "POST":
        if form.validate_on_submit():
            new_chat = Chat(name=form.name.data)
            db.session.add(new_chat)
            current_user.chats.append(new_chat)
            db.session.commit()
        return redirect(url_for('main'))
    return render_template('create.html', form=form)
def add_message():
    body = request.get_json()

    db.session.add(
        Chat(fromId=body["fromId"],
             fromName=body["fromName"],
             fromEmail=body["fromEmail"],
             toId=body["toId"],
             toName=body["toName"],
             toEmail=body["toEmail"],
             message=body["message"],
             dateSent=body["dateSent"]))
Exemple #20
0
def query_all_chats(db_path: str, contacts: Dict[str,
                                                 Optional[str]]) -> List[Chat]:
    chats = []
    con = sqlite3.connect(db_path)
    cur = con.cursor()
    query = "SELECT raw_string_jid as key_remote_jid, subject, sort_timestamp FROM chat_view WHERE sort_timestamp IS NOT NULL ORDER BY sort_timestamp DESC"
    for key_remote_jid, subject, sort_timestamp in cur.execute(query):
        chats.append(
            Chat(key_remote_jid, subject, sort_timestamp,
                 contacts.get(key_remote_jid, None),
                 query_messages(con, key_remote_jid, contacts)))
    con.close()
    return chats
Exemple #21
0
def add():
    eprint(str(request.json))
    message = request.json["msg"]
    message = remove_tags(message)
    newChat = Chat(g.user.currentroom, g.user.id, None, message)
    db.session.add(newChat)
    try:
        db.session.commit()
        flash ("Message received")
        return ('', 204)
    except Exception as e:
        db.session.rollback()
        flash("Error receiving message")
        return ('', 510)
Exemple #22
0
def select_chat(connection: DictConnection, chat_id: int) -> Optional[Chat]:
    logging.info(f"DB: selecting chat: chat_id=[{chat_id}]")
    with get_cursor(connection) as cursor:
        cursor.execute(
            "select chat_id, chat_title, chat_username, is_anarchy_enabled"
            " from chat"
            " where chat_id = %(chat_id)s", {"chat_id": chat_id})
        row = cursor.fetchone()
        if not row:
            return None
        return Chat(chat_id=row["chat_id"],
                    chat_title=row["chat_title"],
                    chat_username=row["chat_username"],
                    is_anarchy_enabled=row["is_anarchy_enabled"])
Exemple #23
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)
Exemple #24
0
def persist_chat(chat: Dict):
    migrate_from = 'migrate_from_chat_id'
    migrate_to = 'migrate_to_chat_id'
    chat_has_migrated = (migrate_to in chat and migrate_from in chat)
    original_id = chat[migrate_from] if chat_has_migrated else chat['id']
    original_registry = Chat.query.filter(Chat.chat_id == original_id).first()
    title = None if 'title' not in chat else chat['title']

    if original_registry is None:
        Chat(title=title, chat_id=chat['id']).save()
    else:
        if chat_has_migrated:
            original_registry.update(chat_id=chat[migrate_to])
        if original_registry.title != title:
            original_registry.update(title=title)
Exemple #25
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')
Exemple #26
0
def new_message(message):
    # Send message to alls users
    emit('channel-' + str(message['channel']), {
        'username': message['username'],
        'text': message['text']
    },
         broadcast=True)
    # Save message
    my_new_chat = Chat(username=message['username'],
                       text=message['text'],
                       channel=message['channel'])
    db.session.add(my_new_chat)
    try:
        db.session.commit()
    except:
        db.session.rollback()
Exemple #27
0
    async def constructMetadata(self, message):
        try:
            session = Session()
            session.expire_on_commit = False

            if (message.guild):
                current_server = Server(id=message.guild.id,
                                        service_id=self.service.id,
                                        server_name=message.guild.name)
            else:
                current_server = None

            current_user = User(id=message.author.id,
                                service_id=self.service.id,
                                username=message.author.display_name)

            if (message.channel.name):
                current_channel = Chat(id=message.channel.id,
                                       server_id=current_server.id,
                                       chat_name=message.channel.name,
                                       nsfw=message.channel.is_nsfw())
            else:
                current_channel = get_or_create(session,
                                                Chat,
                                                id=message.channel.id,
                                                server_id=current_server.id,
                                                chat_name=message.channel.id)

        except Exception as e:
            logger.error("Couldn't get data from message! " + str(e))
            return None

        # Metadata for use by commands and reactions
        metadata = {
            "service": self.service,
            "user": current_user,
            "server": current_server,
            "chat": current_channel,
            "message": message,
            "client": self
        }
        return metadata
def add_list_chats(chats):
    for chat in tqdm(chats):
        account = random.choice(Account.query.filter_by(valid=True).all())
        chat_parser = ChatParserMethods(
            StringSession(account.session),
            api_hash='5c10a75e8f9a21326fa191dc8dd4d916',
            api_id=933676)
        chat_parser.connect()
        usernames_obj = [
            chat.username
            for chat in db.session.query(UserNames.chat).filter_by(
                username=chat).all()
        ]
        if chat in usernames_obj:
            continue
        try:
            chat_entity = chat_parser.get_entity(chat)
            if type(chat_entity) == User:
                continue
            chat_obj = Chat.query.get(chat_entity.id)
            if not chat_obj:
                chat_username_obj = UserNames.query.filter_by(
                    username=chat_entity.username).first()
                if not chat_username_obj:
                    chat_username_obj = UserNames(
                        username=chat_entity.username)
                chat_obj = Chat(id=chat_entity.id,
                                user_names=[chat_username_obj],
                                title=chat_entity.title)
                db.session.add(chat_obj)
                db.session.commit()
        except UsernameInvalidError:
            print(f"UsernameInvalidError: {chat}")
            continue
        except FloodWaitError:
            print(f"FloodWaitError:")
            chat_parser.valid = False
            db.session.commit()
        except Exception as e:
            print(f"Exception: {e}")
            continue
Exemple #29
0
def profile(username):
    all_chats = Chat.query.order_by(Chat.chat_id).all()
    if request.method == "GET":
        return render_template("profile.html",
                               username=g.user.username,
                               chats=all_chats)
    elif request.method == "POST":
        if not request.form['chatName']:
            flash("You must enter a chat name to create a new chat!")
        elif get_chat_id(request.form['chatName']) is not None:
            flash("This chat name has already been used, please try another!")
        else:
            db.session.add(Chat(g.user.id, request.form['chatName']))
            db.session.commit()
            flash(
                "You have created a new chatroom, you can find this in the list of chatrooms to join"
            )
            all_chats = Chat.query.order_by(Chat.chat_id).all()
    return render_template("profile.html",
                           username=g.user.username,
                           chats=all_chats)
Exemple #30
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({})