def logic(interaction, message): # We can also use the command number detected before user_id = message['user_id'] user_data = user.get(user_id) agent_name = user_data.get('name') user_context = conversation.context(user_id) current_p_conversation_id = user_context.get( 'current_pending_conversation') if current_p_conversation_id is None: list_pending_conversations.logic(interaction, message) return None p_convo_data = pending_conversations.get(current_p_conversation_id) client_id = p_convo_data.get('user_id') client_data = user.get(client_id) client_name = client_data.get('name') conversation.update_context(client_id, 'is_closing', True) s_msg = f"Se ha invitado confirmar al usuari@ {client_name}({current_p_conversation_id}) a confirmar el cierre de su caso." chat_api.reply(s_msg, message) message_client = {'user_id': client_id} c_msg = f"{agent_name} ha informado que ya tu caso ya no requiere seguimiento ¿Puedes confirmar? Responde si o no." chat_api.reply(c_msg, message_client) return True
def logic(interaction, message): user_id = message['user_id'] user_context = context(message['user_id']) # TODO(ricalanis): Change to broadcast agent_phones = [key for key in user.agents().keys()] last_message = get_last_message(user_id) user_new_message = user.get(user_context['id']) if user_new_message.get('owner') is not None: message_redirect = f"Mensaje de {user_context['name']}({user_context['phone']}):{last_message}" message = {'user_id': user.get('owner')} chat_api.reply(message_redirect, message) return True for phone in agent_phones: agent_user_id = user.phone_to_id(phone) if user.get(agent_user_id) is None: continue message = {'user_id': user.phone_to_id(phone)} agent_name = user.agents()[phone]['name'] text_alert = f"Acaba de llegar un mensaje de: {user_context['name']}({user_context['phone']})" chat_api.reply(text_alert, message) text_alert = f"*Ultimo mensaje: {last_message}*" chat_api.reply(text_alert, message) update_context(agent_user_id, 'last_message_user', user_context['id']) update_context(agent_user_id, 'last_message_name', user_context['name']) update_context(agent_user_id, 'last_message_phone', user_context['phone']) text_alert = f"Escribe 'p' para poner un timer de 5 min a esta conversación y entrar en la conversación con {user_context['name']}({user_context['phone']}). Por lo contrario sigue escribiendo." chat_api.reply(text_alert, message) return True
def context(user_id): try: context_data = [conversation['context'] for conversation in list(conversations.find({'user_id': user_id}))][0] context_data.update(user.get(user_id)) except: context_data=user.get(user_id) return context_data
def logic(interaction, message): # We can also use the command number detected before user_id = message['user_id'] current_p = message['text'].split(' ')[0].lower() current_p_object = pending_conversations.get(current_p) if current_p_object is None: list_pending_conversations.logic(interaction, message) return True redirect_user_number = current_p_object['user_id'] user_found = user.get(redirect_user_number) if user_found is not None: conversation.update_context(user_id, 'redirect_user', user_found['id']) conversation.update_context(user_id, 'redirect_name', user_found['name']) conversation.update_context(user_id, 'redirect_phone', user_found['phone']) conversation.update_context(user_id, 'conversational_level', 'user') if user_found.get('owner') is None: user.update(user_found['id'], {'owner': user_id}) conversation.update_context(user_id, 'current_pending_conversation', current_p) pending_conversations.add_owner(current_p, user_id) pending_conversations.remove_new_messages(current_p) s_msg = "Haz selecionado al " + user_found['uuid'] + " " + user_found[ 'name'] chat_api.reply(s_msg, message) s_msg = "Con la conversacion pendiente " + current_p chat_api.reply(s_msg, message) else: already_selected_p = conversation.context( 'current_pending_conversation') if already_selected_p is None: list_pending_conversations.logic(interaction, message) else: already_p_object = pending_conversations.get(already_selected_p) already_user = user.get(already_p_object['user_id']) already_user_name = already_user.get('name') s_msg = "Sigues hablando con " + already_user_name chat_api.reply(s_msg, message) return True
def init_1st_step(self): auth = OAuthHandler(APP_KEY, APP_SECRET, '') auth_url = auth.get_authorization_url() user.update_app('sina', self.email, request_token=auth.request_token.key, request_secret=auth.request_token.secret) log.debug(repr(user.get(self.email))) return auth_url
def lock_one_username(): q = memcache.get('q') or [] for username in q: logging.debug('Retrieving %s from db' % username) u = user.get(username) if not u._need_update: remove(u) continue logging.debug('Checking lock') locked_time = memcache.get('qlock_' + username) logging.debug('locked_time: %s' % locked_time) if locked_time: logging.debug('Locked, timeout?') # I don't think this would be used... if util.td_seconds(locked_time) >= FETCH_TIMEOUT: logging.debug('Yes, timed out') # Force to acquire, if locked more than FETCH_TIMEOUT ago memcache.set('qlock_' + username, util.now()) return username else: continue else: logging.debug( 'locked_time does not have a value, force to acquire') memcache.set('qlock_' + username, util.now()) return username return False
def update_context(user_id, field, text): user_data = user.get(user_id) if field in user_data: user.update(user_id, {field: text} ) else: conversations.update({'user_id': user_id}, {'$set': {'context.'+field: text}}) return True
def new_user(username): """ Creates a new user. """ user.new(username) app.logger.info("[USER] User '{}' was created.".format(username)) return jsonify(user.get(username)), 201
def accum_timestats(self, message): uid = message['user_id'] timestamp = int(float(message['timestamp'])) # First, get stats unadjusted and by UTC localtime = time.gmtime(timestamp) hour = localtime.tm_hour wday = localtime.tm_wday self.increment(["weekday", wday], message) self.increment(["hour", hour], message) # Now, adjust stats to the authors' timezone user = self.user.get(uid) if not user: # Weird. We couldn't find this user. Oh well. print("Couldn't find user {}".format(message['user_id'])) return if 'tz_offset' not in user or 'tz' not in user: return tz_offset = user['tz_offset'] tz = user.get("tz", "Unknown") self.increment(["timezone", tz], message) timestamp += tz_offset localtime = time.gmtime(timestamp) hour = localtime.tm_hour wday = localtime.tm_wday self.increment(["user_weekday", wday], message) if wday < 5: # We only look at weekday activity self.increment(["user_weekday_hour", hour], message) self.increment(["user_weekday_hour_per_user", uid, hour], message)
def create(user_id, first_message_id=None, label=None, last_message_id=None, label_set_by='arbi'): if first_message_id == None: first_message_id = conversation.get_canonical_user_message(user_id, position=0) current_threads = user.get(user_id).get('threads') current_thread_pos = len(current_threads) - 1 new_thread = { 'label': label, 'label_set_by': label_set_by, 'label_set_at': datetime.now(), 'first_canonical_message_id': first_message_id, 'last_canonical_message_id': last_message_id, 'solved': False, 'closed_at': None, 'created_at': datetime.now(), 'updated_at': datetime.now(), 'current_thread': current_thread_pos, } push_obj = {'$push': {'threads': new_thread}} user.users.update({'id': user_id}, push_obj) return True
def lock_one_username(): q = memcache.get('q') or [] for username in q: logging.debug('Retrieving %s from db' % username) u = user.get(username) if not u._need_update: remove(u) continue logging.debug('Checking lock') locked_time = memcache.get('qlock_' + username) logging.debug('locked_time: %s' % locked_time) if locked_time: logging.debug('Locked, timeout?') # I don't think this would be used... if util.td_seconds(locked_time) >= FETCH_TIMEOUT: logging.debug('Yes, timed out') # Force to acquire, if locked more than FETCH_TIMEOUT ago memcache.set('qlock_' + username, util.now()) return username else: continue else: logging.debug('locked_time does not have a value, force to acquire') memcache.set('qlock_' + username, util.now()) return username return False
def user_list(): #B1 GET ALL FOOD 1.Funton ? 2.Write funtion ? all_user = user.get({}) #lấy hết. #B2: render: ALL FOOD + html #B3: Return return render_template("user_list.html", u_list=all_user)
def get(url_id, usr): user_info = user.get(usr) task = ndb.Key(urlsafe=url_id).get() if task.cls != user_info.cls: raise Exception('Unauthorized to view task') else: return task
def logic(interaction, message): user_id = message['user_id'] user_context = conversation.context(user_id) last_reply_time = user_context.get('last_reply_time') is_closing = user_context.get('is_closing') pending_convos = pending_conversations.find(user_id=user_id, closed=False) current_p_convo_id = pending_convos[0].get( 'id') if len(pending_convos) > 0 else None if current_p_convo_id is not None and is_closing == True: text = message.get('text').lower().split(' ')[0] current_p_data = pending_conversations.get(current_p_convo_id) current_user = user.get(user_id) user_name = current_user.get('name') if 'no' in text: for owner in current_p_data['owners']: agent_context = conversation.context(owner) message = {'user_id': owner} c_msg = f'El usuario {user_name} no ha confirmado el cierre de su conversación' chat_api.reply(c_msg, message) elif 'si' in text: pending_conversations.close(current_p_convo_id) for owner in current_p_data['owners']: agent_context = conversation.context(owner) redirect_user = agent_context.get('redirect_user') agent_p_convo = agent_context.get( 'current_pending_conversation') message = {'user_id': owner} c_msg = f'La conversación pendiente con {user_name}({current_p_convo_id}) se ha cerrado' chat_api.reply(c_msg, message) if redirect_user == user_id and current_p_convo_id == agent_p_convo: conversation.update_context(owner, 'redirect_user', None) conversation.update_context(owner, 'redirect_name', None) conversation.update_context(owner, 'redirect_phone', None) conversation.update_context(owner, 'conversational_level', 'user') conversation.update_context( owner, 'current_pending_conversation', None) conversation.update_context(user_id, 'is_closing', False) return True if last_reply_time is None: conversation.update_context(user_id, 'last_reply_time', datetime.now()) chat_api.reply(interaction['text'], message) else: if datetime.now() > last_reply_time + timedelta(hours=24): conversation.update_context(user_id, 'last_reply_time', datetime.now()) chat_api.reply(interaction['text'], message) else: None # Do nothing if 24 before last reply did not happen return True
def test_save(self): newuser = {"firstName": "Stefan", "lastName": "Agner", "eMail": self.testmail, "password": "******"} newuser2 = newuser.copy() useridsave = user.save(newuser) with self.assertRaises(DuplicateKeyError): user.save(newuser2) userdata = user.get(self.testmail) user.remove(self.testmail) self.assertTrue(self.testmail == userdata["eMail"])
def add_event(uuid, type, usr): uuids = [b.uuid for b in beacon.get_list()] assert uuid in uuids assert user.get(usr) AttendanceActivity(uuid=uuid, type=type, usr=usr, time=sgtime.get_datetime_now()).put()
def get(usr, cls=None): user_info = user.get(usr) if cls is None: cls = user_info.cls timetable = Timetable.query( Timetable.school == user_info.school, Timetable.cls == cls.cls, ).fetch()[0] return timetable.events
def users(): if request.method == "GET": return user.get() elif request.method == "POST": return user.post() elif request.method == "PATCH": return user.patch() elif request.method == "DELETE": return user.delete() else: Response("Not Supported", mimetype="text/html", status=500)
def accum_timestats(self, message): uid = message['user_id'] cid = message['slack_cid'] ts = int(float(message['ts'])) # First, get stats unadjusted and by UTC localtime = time.gmtime(ts) hour = localtime.tm_hour wday = localtime.tm_wday self.increment(["weekday", wday], message) self.increment(["hour", hour], message) # Now, adjust stats to the authors' timezone user = self.user.get(uid) if not user: # Weird. We couldn't find this user. Oh well. print("Couldn't find user {}".format(message['user_id'])) return if 'tz_offset' not in user or 'tz' not in user: return tz_offset = user.get("tz_offset") if tz_offset is None: tz_offset = config.default_tz_offset tz = user.get("tz", "Unknown") self.increment(["timezone", tz], message) ts += tz_offset localtime = time.gmtime(ts) hour = localtime.tm_hour wday = localtime.tm_wday self.increment(["user_weekday", wday], message) if uid in self.track: self.increment(["user_stats", uid, "posting_days", wday], message) if cid in self._data['enriched_channel']: self.increment(["enriched_channel", cid, "posting_days", wday], message) if wday < 5: # We only look at weekday activity self.increment(["user_weekday_hour", hour], message) self.increment(["user_weekday_hour_per_user", uid, hour], message) if uid in self.track: self.increment(["user_stats", uid, "posting_hours", hour], message) if cid in self._data['enriched_channel']: self.increment( ["enriched_channel", cid, "posting_hours", hour], message)
def get_list(usr): user_info = user.get(usr) tasks = Task.query( Task.school == user_info.school, Task.due_date >= sgtime.get_datetime_now(), Task.cls == user_info.cls, Task.subject.IN(user_info.subjects) ).fetch() tasks.sort(key=lambda x: x.time_added, reverse=True) for t in tasks: t.done = usr in t.done_users return tasks
def update_user(username): """ Update the user. """ if not request.json: raise ValueError("No values were passed in the request body.") for field in request.json: value = request.json[field] user.set_value(username, field, value) app.logger.info("[USER] '{}': {} -> {}".format(username, field, value)) return jsonify(user.get(username)), 200
def gal_userinfo(username): if username == '': u = current_user if not u.is_authenticated: return flask.json.jsonify({'userinfo': {}}) else: u = user.get(username) if u is None: return flask.json.jsonify({'userinfo': {}}) else: u.unseen = design.NewerDesigns(u.lastdesign) return flask.json.jsonify({'userinfo': dict(u)})
def checkFind(): global _array, _deleted size = len(_array) num = randint(0, size - 1) key = list(_array)[num] val = _array[key] t = time.time() user_val = user.get(key) dt = (time.time() - t) * TIME_MULTIPLIER return user_val == val and dt < TIME_TEST_LIMIT
def test_save(self): newuser = { "firstName": "Stefan", \ "lastName": "Agner", \ "eMail": self.testmail, \ "password": "******" \ } newuser2 = newuser.copy() useridsave = user.save(newuser) with self.assertRaises(DuplicateKeyError): user.save(newuser2) userdata = user.get(self.testmail) user.remove(self.testmail) self.assertTrue(self.testmail == userdata["eMail"])
def get_user_info(self, _): usr = user.get(endpoints.get_current_user()) fixedSubjects = [] for s in usr.subjects: if s == 'MA': fixedSubjects.append('MATH') else: fixedSubjects.append(s) return msg.UserMessage(name=usr.name, subjects=fixedSubjects, points=usr.points, rank=usr.rank, cls=usr.cls)
def login(): if current_user.is_authenticated() and current_user.is_active(): return redirect(url_for('index')) if request.method == "POST": username = request.form['username'] password = request.form['password'] if(username and password): # do login because username and password have been specified uid = user.authenticate(username, password) if uid != None: login_user(user.get(uid)) return redirect(url_for('index')) return render_template('login.html')
def logic(interaction, message): user_id = message['user_id'] text = message['text'] users_list = list(user.users.find({'type': 'agent'})) #message['user_id'] if len(users_list) == 0: chat_api.reply("No hay agentes dados de alta", message) return True agent_uuid = text.split(' ')[0].lower() agent_data_uuid = user.find(uuid = agent_uuid) if len(agent_data_uuid) == 0: r_text = 'No se encontro ningún agente con dicho identificador' chat_api.reply(r_text, message) return True agent_data = agent_data_uuid[0] user_context = conversation.context(user_id) redirect_user_id = user_context.get('redirect_user') if redirect_user_id is None: r_text = 'No tienes ninguna conversación seleccionada' chat_api.reply(r_text, message) return True user_data = user.get(redirect_user_id) current_p_results = pending_conversations.find(user_id = redirect_user_id, closed = False) current_p = current_p_results[0].get('id') if len(current_p_results)>0 else None if current_p is None: pending_conversations.create(redirect_user_id, [agent_uuid]) current_p_results = pending_conversations.find(user_id = redirect_user_id, closed = False) current_p = current_p_results[0].get('id') if len(current_p_results)>0 else None else: pending_conversations.switch_owner(current_p, user_id, agent_uuid) conversation.update_context(user_id, 'redirect_user', None) conversation.update_context(user_id, 'redirect_name', None) conversation.update_context(user_id, 'redirect_phone', None) conversation.update_context(user_id, 'conversational_level', 'user') conversation.update_context(user_id, 'current_pending_conversation', None) r_text = f"{agent_uuid} ha recibido al usuario {user_data['uuid']}" chat_api.reply(r_text, message) a_text = f"Has recibido al usuario {user_data['uuid']} de {user_id}" chat_api.reply(a_text, {'user_id': agent_uuid, 'text': a_text}) return True
def add(subject, cls, title, due_date, usr): user_info = user.get(usr) if cls == user_info.cls and (subject in user_info.subjects): Task( school=user_info.school, subject=subject, cls=cls, title=title, due_date=due_date, usr=usr, time_added=sgtime.get_datetime_now() ).put() user.increment_points(usr) else: raise Exception('Unauthorized to add task')
def checkFindDeleted(): global _array, _deleted size = len(_deleted) if size == 0: return True num = randint(0, size - 1) key = list(_deleted)[num] t = time.time() user_find = user.get(key) dt = (time.time() - t) * TIME_MULTIPLIER return user_find is None and dt < TIME_TEST_LIMIT
def submit(call): user_info = user.get(call.message.chat.id) user.set(call.message.chat.id, reg_form=questions.start(user_info['service'])) text = "".join([ f"Тип продукта: {user_info['service']}!\n", f"Имя продукта: {user_info['proposal']}.\n\n", "Желаете продолжить?", ]) markup = types.ReplyKeyboardMarkup(resize_keyboard=True) markup.add(types.KeyboardButton("Продолжить")) markup.add(types.KeyboardButton("Отмена")) bot.send_message(call.message.chat.id, text, reply_markup=markup) bot.register_next_step_handler(call.message, is_accept)
def login(): form = LoginForm() if request.method == 'POST' and form.validate_on_submit(): #user = app.config['USERS_COLLECTION'].find_one({"_id": form.username.data}) user = User() curr_user = user.get(form.username.data) if curr_user and User.validate_login(curr_user.password, form.password.data): # ensure that user exists # user_obj = User(user['_id']) login_user(curr_user) flash("Logged in successfully!", category='success') return redirect(url_for("search")) else: flash("Wrong username or password!", category='error') # could not find in database return render_template('login.html', title='login', form=form)
def checkRestoreDeleted(): global _array, _deleted size = len(_deleted) if size == 0: return True num = randint(0, size - 1) key = list(_deleted)[num] res_add = add(key, "new" + str(key)) val = _array[key] t = time.time() user_val = user.get(key) dt = (time.time() - t) * TIME_MULTIPLIER return res_add and user_val == val and dt < TIME_TEST_LIMIT
def get_task_list(self, _): usr = endpoints.get_current_user() tasks = task.get_list(usr=usr) message = [] for t in tasks: message.append( msg.TaskMessage(title=t.title, time_added=t.time_added, usr=user.get(t.usr).name, subject=t.subject, due_date=datetime.datetime.combine( t.due_date, datetime.datetime.min.time()), url_id=t.key.urlsafe(), cls=t.cls, description=t.description, school=t.school, done=t.done, is_owner=t.usr == usr)) return msg.TasksMessage(tasks=message)
def logic(interaction, message): chat_api.reply("Estas son las conversaciones pendientes:", message) user_id = message['user_id'] pending_conversations.clean_pending_index() p_list = list(pending_conversations.find( owner=user_id, closed=False)) #message['user_id'] if len(p_list) == 0: chat_api.reply("No hay casos pendientes a resolver", message) return True for p in p_list: star_messages = '' if p['new_messages'] == True: star_messages = '* ' user_p = user.get(p['user_id']) #user_name = user_info['name'] #user_phone = user_info['phone'] text_message = f"👤{p['id']} {star_messages}= {user_p['name']}" chat_api.reply(text_message, message) return True
def respond(data): print(data) text = data.get('body') user_id = data.get('author') body = data.get('body') print(data) if os.getenv('ARBITRUR_PHONE') in user_id: return True message = build_message(user_id, text, body) log_handler.insert_message(message) print(message) if message['text'] == 'KABOOM!': hard_reset(message) return True RECIEVER_ID = user.phone_to_id(os.getenv('ARBITRUR_PHONE')) new_user_phone = data.get('chatId').replace('@c.us', '') user_data = { 'name': data.get('senderName'), 'phone': new_user_phone, 'country': geo.get_country_name_and_flag(new_user_phone) } if user.get(user_id) is None: user.create(user_id, user_data) # Demote or promote user if there is a change in the agent list user.demote_to_user_if_needed(user_id, user_data) user.promote_to_agent_if_needed(user_id, user_data) # If we are already handling a message and we are not done, ignore. conversation.update_canonical_conversation(user_id, RECIEVER_ID, text, 'user') if user.is_bot_answering(user_id) == True: return True user.set_user_answering(user_id) print('Moving Convo') core.recieve_message(message) user.remove_user_answering(user_id) return True
def process_queue(): """Process a bit""" # Check if it's time to process last_process = memcache.get('last_process_queue') if last_process and util.td_seconds(last_process) < PROCESS_QUEUE_INTERVAL: return memcache.set('last_process_queue', util.now()) username = lock_one_username() if not username: logging.debug('No item in queue, skipped') return curr = memcache.get('q_' + username) if curr is None: u = user.get(username) if not u: logging.debug('No such user %s in db' % username) remove(username) return # Retrieve the friends list friends = u._friends # TODO Should drop protected friends? curr = (u.username, friends, []) memcache.set('q_' + username, curr) # Start to process a bit # In case this user do have friends if curr[1]: curr_f = curr[1].popitem() client = twitter_client.service.TwitterService(application_name='LasTweet/0') gdata.alt.appengine.run_on_appengine(client) search = client.NewSearch() search.keywords = ['from:' + curr[0], 'to:' + curr_f[0]] search.rpp = 1 new_tweet = { 'username': curr_f[0], 'msg': '', 'msg_id': 0, 'published': None, 'profile_image': curr_f[1], 'maggie': None, } result = search.Search() if len(result.entry) == 1: entry = result.entry[0] # Process the message # Get the unicode string msg = entry.title.text.decode('utf-8') # Remove the @reply msg = message_body_pattern.match(msg).group(1) # Truncate if len(msg) > 50: msg = msg[:47] + '...' else: msg = msg[:50] new_tweet['msg'] = msg new_tweet['msg_id'] = int(entry.GetMessageID()) new_tweet['published'] = entry.published.Get() # Search for maggie ads search.keywords = ['from:' + curr_f[0], '#magpie'] search.rpp = 10 result = search.Search() for entry in result.entry: # If #magpie at beginning, then this is a possiblity; and a link as well if entry.title.text.find('#magpie') == 0 and entry.title.text.find('http://') >= 0: msg = entry.title.text.decode('utf-8') if len(msg) > 50: msg = msg[:47] + '...' else: msg = msg[:50] new_tweet['magpie'] = { 'msg': msg, 'msg_id': int(entry.GetMessageID()), 'published': entry.published.Get(), } # Only store the last break curr[2].append(new_tweet) # If there is no more in curr[1] if not curr[1]: u = db.run_in_transaction(user.transaction_update_tweets, curr[0], sort_messages(curr[2])) user.try_mail(u) # End of updating for this user remove(u) else: memcache.set('q_' + username, curr) unlock('qlock_' + username)
def get_user(username): """ Return the profile of the user. """ return jsonify(user.get(username)), 200
def load_user(userid): return user.get(userid)
def load_user(username): user = User() return user.get(username)