Exemple #1
0
def start_vk():
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
            user_res=vk_session.method("users.get",{'user_ids':[event.user_id],'fields':['id','first_name','last_name']})
            insert_user(user_res[0]['id'],user_res[0]['first_name'],user_res[0]['last_name'],'vk')
            result = vk_session.method("messages.getById", {"message_ids": [event.message_id],"group_id": 192738048})
            if result['items'][0]['geo']:
                geo = result['items'][0]['geo']['coordinates']
                latitude, longitude = geo['latitude'], geo['longitude']
                print(latitude, longitude)
                my_location={'latitude':latitude,'longitude':longitude}
                places = select_places()
                dist={p['id']:distance(my_location['longitude'],my_location['latitude'],p['loc_lon'],p['loc_lat']) for p in places}
                min_dist=min(dist.keys(), key=(lambda k: dist[k]))
                db_place = select_place_param(min_dist)
                image_url = 'https://ecoukhta.herokuapp.com/images/?img='+str(db_place['id'])
                image = session.get(image_url, stream=True)
                photo = upload.photo_messages(photos=image.raw)[0]
                attachments='photo{}_{}'.format(photo['owner_id'], photo['id'])
                vk.messages.send(
                    user_id=event.user_id,
                    attachment=attachments,
                    random_id=get_random_id(),
                    lat=db_place['loc_lat'],
                    long=db_place['loc_lon'],
                    message=db_place['info']
                )
                insert_log(select_userid_by_name(str(user_res[0]['id'])),db_place['id'])
            return 'ok'
        else: return 'ok'
Exemple #2
0
def analyze_input_currency(ID,text_input):
    to_currency=None
    eur_currency_match = re.search(eur,text_input)
    usd_currency_match = re.search(usd,text_input)
    cny_currency_match = re.search(cny,text_input)
    conv_answer = None
    if eur_currency_match:
        to_currency = 'EUR'
    elif cny_currency_match:
        to_currency = 'CNY'
    elif usd_currency_match:
        to_currency = 'USD'
    else:
        to_currency = None
        conv_answer = None

    if to_currency is not None:
        if not check_if_user_exists(ID):
            insert_user(ID)
        update_currency(ID,to_currency)
        update_conversion_rate(ID)
        calculate_converted_amount(ID)
        conv_answer = return_converted_amount(ID)
        return conv_answer
    else:
        return None
Exemple #3
0
def main(*args, **kwargs):
    """
    Main function for orchestration of the application
  
    Parameters: 
    Currently not using any parameters, but left the *args, **kwargs because in
    a production application, the config values would come from using ChainMap
    with configargparse by chaining config file, os.environ, and command line args
  
    Returns:
    Exit code on success or failure
    """
    for url in get_user_lists():
        if url:
            user_detail = get_request_json(url)
        if user_detail:
            user = get_and_validate_user(user_detail)
            if user:
                insert_user(user)
                logger.info(f"Inserted valid user {user}.")
            else:
                logger.info(f"Unable to insert user: {user_detail}")
    result = get_youngest_five()
    logger.info(
        f"Retrieved youngest five:{result}... Getting ready to launch application"
    )
    build_and_run_app(result)
Exemple #4
0
def start_message(message):
    user=str(message.from_user.id)
    insert_user(user,message.from_user.first_name, message.from_user.last_name,'telegram')
    greeting='''
    Привет, вышли геолокацию и бот покажет ближайшую точку сдачи батареек.
    Хочешь увидеть все точки введи /list 
    '''
    bot.send_message(message.chat.id,greeting)
Exemple #5
0
def insert_user(user_id: int, first_name: str, last_name: str):
    if not check_user_existing(user_id):
        db.insert_user(user_id, first_name, last_name)
        user_dict[user_id] = {
            'first_name': first_name,
            'last_name': last_name,
            'current_group': ''
        }
Exemple #6
0
    def on_sign_up(self, request):
        if request.method == 'POST':
            username = request.form['username']
            email = request.form['email']
            password = request.form['password']
            insert_user(self.redis, username, email, generate_password_hash(password))
            return redirect('/sign_in')

        return self.render_template("sign_up.html")
Exemple #7
0
def add_message(message):
    ''' Set of functions to ADD PLACE in BASE '''
    user=str(message.from_user.id)
    insert_user(user,message.from_user.first_name, message.from_user.last_name,'telegram')
    if isAdmin(str(message.from_user.id)):
        keyboard1=telebot.types.ReplyKeyboardMarkup(True,True)
        keyboard1.row('battery')
        bot.send_message(message.chat.id,'Привет, что сдаем?',reply_markup=keyboard1)
        bot.register_next_step_handler(message, get_type)
Exemple #8
0
def list_message(message):
    user=str(message.from_user.id)
    insert_user(user,message.from_user.first_name, message.from_user.last_name,'telegram')
    places= select_places() #red_get(str(message.from_user.id)+'_type'))
    for p in places:
        db_place = select_place_param(p['id'])
        bot.send_location(message.chat.id, db_place['loc_lat'], db_place['loc_lon'])
        bot.send_photo(message.chat.id, db_place['photo'],caption=db_place['info'])
    insert_log(select_userid_by_name(str(message.from_user.id)),1)
Exemple #9
0
def form_data_handler(page_route, data):
    global userID
    global fullname

    if page_route == "/":
        user_fullname = data['user_fullname'][0]
        username = data['username'][0]
        password = data['password'][0]

        new_user = {
            "user_fullname": user_fullname,
            "username": username,
            "password": password
        }
        db.insert_user(new_user)

        user = db.get_user(username, password)

        userID = user['_id']
        fullname = user['user_fullname']

    elif page_route == "/todo":
        todo_subject = data['todo_subject'][0]
        todo_desc = data['todo_desc'][0]
        due_date = data['due_date'][0]
        due_date = datetime.strptime(due_date, "%Y-%m-%d")

        try:
            priority = bool(data['priority'][0])

        except KeyError:
            priority = False

        new_todo = {
            "todo_subject": todo_subject,
            "todo_desc": todo_desc,
            "due_date": due_date,
            "priority": priority,
            "completed": False,
            "userID": userID
        }

        db.insert_todo(new_todo)

    elif page_route == "/login":
        username = data['username'][0]
        password = data['password'][0]

        user = db.get_user(username, password)

        try:
            userID = user['_id']
            fullname = user['user_fullname']
        except TypeError:
            userID = ""
            fullname = ""
Exemple #10
0
def loc_message(message):
    user=str(message.from_user.id)
    insert_user(user,message.from_user.first_name, message.from_user.last_name,'telegram')
    my_location={'latitude':message.location.latitude,'longitude':message.location.longitude}
    places = select_places() #red_get(str(message.from_user.id)+'_type'))
    dist={p['id']:distance(my_location['longitude'],my_location['latitude'],p['loc_lon'],p['loc_lat']) for p in places}
    min_dist=min(dist.keys(), key=(lambda k: dist[k]))
    db_place = select_place_param(min_dist)
    bot.send_location(message.chat.id, db_place['loc_lat'], db_place['loc_lon'])
    bot.send_photo(message.chat.id, db_place['photo'],caption=db_place['info'])
    insert_log(select_userid_by_name(str(message.from_user.id)),db_place['id'])
def transform_user():
    users = json.load(open(BASE_PATH + 'tripadvisor_user' + SUFFIX, 'r'))

    for user in users:
        data = {
            'user': user['user'],
            'source': TRIPADVISOR_SOURCE,
            'likes': -1 if user['likes'] == '' else float(user['likes']),
            'reviews': user['reviews']
        }

        insert_user(data)
Exemple #12
0
def register():
    # 如果是表单提交
    if request.method == 'POST':
        # print('正在注册')
        # 提交,即开始验证
        username = request.form['username']
        password = request.form['password']
        # 注册
        db.insert_user(username, password)
        # 如果注册成功,返回登录界面,重新登录,即可进入主界面
        return redirect(url_for('login'))
    return render_template('register.html')
Exemple #13
0
def pre_operations(message):
    global db_initialized
    if not db_initialized:
        db.bootstrap()
        db_initialized = True
    user = db.get_user(message.from_user.id)
    if not user:
        logger.info("Inserting user")
        db.insert_user(message.from_user.id, message.from_user.username)
    else:
        logger.info("Updating user")
        db.update_username(message.from_user.id, message.from_user.username)
Exemple #14
0
def join_action():
    if request.method == 'GET':
        return '나는 액션 GET 페이지야~'
    else:
        userid = request.form['userid']
        pwd = request.form['pwd']
        name = request.form['name']
        phone = request.form['phone']
        print(userid, pwd, name, phone)
        # 디비에 데이터 넣기
        db.insert_user(userid, pwd, name, phone)
        return '회원가입 성공!!@'
Exemple #15
0
async def process_group(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        direction = data["direction"]
        if msg.text not in get_group_names_by_short_direction_name(direction):
            return await msg.answer("Выберите группу с клавиатуры!")
        data["group"] = msg.text
        user_data = msg.from_user
        user = User(user_data.id, user_data.first_name, user_data.last_name,
                    user_data.username, user_data.language_code,
                    user_data.is_bot, get_group_id_by_name(msg.text))
        insert_user(user)
        await state.finish()
        await msg.answer("Ура! Теперь вам доступно расписание!",
                         reply_markup=menu_kb)
Exemple #16
0
def toroku():
    pw = request.form.get("pw")
    salt = request.form.get("salt")
    data = session["data"]
    id = data[0]
    name = data[1]
    age = data[2]
    birthday = data[3]
    gender = data[4]
    mail = data[5]
    zip = data[6]
    zyusyo = data[7]

    b_pw = bytes(pw, "utf-8")
    b_salt = bytes(salt, "utf-8")
    hashed_pw = hashlib.pbkdf2_hmac("sha256", b_pw, b_salt, 10).hex()

    result = db.insert_user(id, name, age, birthday, gender, mail, zip, zyusyo,
                            hashed_pw, salt)
    if result == "ok":
        mail_pdf.toroku_mail(mail, name)
        session.pop("data", None)
        return render_template("toroku.html", name=name)
    else:
        return render_template("toroku_no.html")
Exemple #17
0
def create_user():
    if request.method == 'POST':
        key = app.config['SECRET_KEY']
        dataDict = json.loads(request.data)
        username = dataDict['username']
        password = dataDict['password']
        return json.dumps(insert_user(username, password, key))
    def __call__(self, data):

        if not 'callback_query' in data.keys():

            if 'photo' in data['message'].keys():

                chat_id = data['message']['chat']['id']
                msg = data['message']['photo'][0]['file_id']
                user_name = data['message']['chat']['first_name'] + data[
                    'message']['chat']['last_name']
                self.chat_id = str(chat_id)
                self.text = msg
                self.name = user_name
            else:
                chat_id = data['message']['chat']['id']
                msg = data['message']['text']
                user_name = data['message']['chat']['first_name'] + data[
                    'message']['chat']['last_name']
                message_id = data['message']['message_id']
                self.chat_id = str(chat_id)
                self.text = msg
                self.name = user_name
                self.message_id = message_id

        else:
            chat_id = data['callback_query']['from']['id']
            #msg = data['callback_query']['data']
            user_name = data['callback_query']['from']['first_name'] + data[
                'callback_query']['from']['last_name']
            self.chat_id = str(chat_id)
            self.text = data
            self.name = user_name

        # 신규 고객이면 db insert
        isExist = db.get_user(self.chat_id)

        #신규고객
        if not isExist:
            db.insert_user(self.chat_id, self.name)
        #기존고객이라면 isnew변수 update
        else:
            if db.get_single_value(self.chat_id, 'user_state'):
                self.is_member = True

        # 사용자의 현재 상태 저장
        self.state = db.get_single_value(self.chat_id, 'dialog_state')
Exemple #19
0
def insert_user():
    '''Insert user'''
    email = request.form['email']
    password = request.form['password']
    if db.insert_user(CONN, email, password):
        return jsonify('success')
    else:
        return jsonify('failed')
Exemple #20
0
def register_new_user(user_phone_id, password):
    users = [u for u in db.select_all_users() if u.id == user_phone_id]
    # if users:
    #     raise UserExists('user {} exists'.format(user_phone_id))
    # else:

    # for now this is the behavior
    if users:
        print 'found users'
        return users[0].token
    else:
        print 'creating'
        token = _get_hash(password)
        user = User(user_phone_id, '123123123', user_phone_id, user_phone_id,
                    None, token)
        db.insert_user(user)
    return token
 def regisiter(self):
     username = self.argv[1]
     email = self.argv[2]
     password = self.argv[3]
     if db.insert_user(username, email, password) == 0:
         return "Register successfully."
     else:
         return "Username is already used."
Exemple #22
0
def register():
	if g.user:
		return redirect(url_for('notes'))
	error = None
	if request.method == 'POST':
		if not request.form['username']:
			error = 'You have to enter a username'
		elif not request.form['password']:
			error = 'You have to enter a password'
		elif request.form['password'] != request.form['password2']:
			error = 'The two passwords do not match'
		elif db.get_user(request.form['username']) is not None:
			error = 'The username is already taken'
		else:
			db.insert_user(request.form['username'],generate_password_hash(request.form['password']))
			#flash('You were successfully registered and can login now')
			return redirect(url_for('login'))
	return render_template('register.html', error=error)
Exemple #23
0
def register_users():
    ## SQLite3 user database initialization
    create_user_table()

    # Open users worksheet
    sheet = access_spreadsheet()
    users_sheet = sheet.get_worksheet(0)

    # Get number of rows (new user registrations)
    number_of_users = (users_sheet.row_count - 1)
    print('Number of new registrations: ' + str(number_of_users))

    # Loop through new user registrations
    for x in range(number_of_users):
        new_user = users_sheet.row_values(2 + x)

        # Formatting user data
        reg_date = time_now('date.month.year')
        email = new_user[1]
        firstname = new_user[2]
        lastname = new_user[3]
        age = new_user[4]
        postal_number = new_user[5]
        street_name = new_user[6]
        street_number = new_user[7]
        phone = new_user[8]
        bsu = new_user[9]
        bsu_bank = new_user[10]
        savings = new_user[11]
        savings_bank = new_user[12]
        savings_limit = new_user[13]
        savings_limit_bank = new_user[14]
        retirement = new_user[15]
        retirement_bank = new_user[16]
        usagesalary = new_user[17]
        usagesalary_bank = new_user[18]

        # Formatting current user to class
        current_user = User(reg_date, email, firstname, lastname, age,
                            postal_number, street_name, street_number, phone,
                            bsu, bsu_bank, savings, savings_bank,
                            savings_limit, savings_limit_bank, retirement,
                            retirement_bank, usagesalary, usagesalary_bank)

        # Insert new user into the user database
        response = insert_user(current_user)

        # Send confirmation email for new registrations and updates
        if response == 'new_user':
            registration_email(current_user)
        elif response == 'update_user':
            update_email(current_user)

    # Loop through and delete user entries in sheet
    print('Deleting new user entries from sheet...')
    for x in range(number_of_users):
        users_sheet.delete_row((number_of_users + 1) - x)
Exemple #24
0
def register():
    if request.method == 'POST':
        print('正在注册')
        # 提交,即开始验证
        username = request.form['username']
        password = request.form['password']
        result = db.insert_user(username, password)
        return redirect(url_for('login'))
    return render_template('register.html')
Exemple #25
0
 def regisiter(self):
     username = self.argv[1]
     email = self.argv[2]
     password = self.argv[3]
     bucket = 'nphw0616026user' + str(int(time.time()*100000)) + ''.join(random.choice(string.ascii_lowercase) for i in range(8))
     if db.insert_user(username, email, password, bucket) == 0:
         return '&<!register::>' + bucket + "&<!meta|msg>Register successfully."
     else:
         return "Username is already used."
Exemple #26
0
def register():
	if g.user:
		return redirect(url_for('notes'))
	error = None
	if request.method == 'POST':
		if not request.form['username']:
			error = 'You have to enter a username'
		elif not request.form['password']:
			error = 'You have to enter a password'
		elif request.form['password'] != request.form['password2']:
			error = 'The two passwords do not match'
		elif db.get_user(request.form['username']) is not None:
			error = 'The username is already taken'
		else:
			db.insert_user(request.form['username'],generate_password_hash(request.form['password']))
			#flash('You were successfully registered and can login now')
			return redirect(url_for('login'))
	return render_template('register.html', error=error)
Exemple #27
0
def create_account():
    username = request.form["username"]
    password = request.form["password"]
    password2 = request.form["password2"]
    moderator = check_moderator()

    user_id = db.find_user_id(username)
    if user_id != None:
        return render_template("create.html",
                               error="Username taken",
                               moderator=moderator)
    if password != password2:
        return render_template("create.html",
                               error="Passwords not identical",
                               moderator=moderator)

    password = generate_password_hash(password2)
    db.insert_user(username, password)
    return redirect("/login")
def register_user():
	if request.method == 'GET':
		return render_template("auth/register_form.html")
	elif request.method == 'POST':
		if request.form["submit_btn"] == "cancel":
			return redirect(url_for("index"))
		elif request.form["submit_btn"] == "create new user":
			# result is a a list of tuples
			result = check_if_already_registered(db_name, request.form["username"].lower())
			print(result)
			if result[0] != (0,):
				flash('Username already taken.')
				return redirect(url_for("register_user"))
			else:
				insert_user(db_name, request.form["username"].lower(), request.form["email"], request.form["password"])
				flash('New account created successfully.')
				return redirect(url_for("login_check"))
	else:
		return redirect(url_for("logout"))
Exemple #29
0
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="From now on you'll recieve notifications about new"
                                                                    " programs and also fresh assets for existing "
                                                                    "ones. Type '/stop' to stop, '/noempty' to not "
                                                                    "recieve notifications about programs with no "
                                                                    "found assets")
    if insert_user(update.effective_chat.id):
        user_list.append([update.effective_chat.id, 0])
    else:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="You are already signed up for notifications")
Exemple #30
0
def analyze_input_amount(ID,text_input):
    amount=None
    ID = ID
    text_input = str(text_input)
    amount_match = [float(s) for s in text_input.split() if s.isdigit()]
    try:
        amount  = amount_match[0]
        amount = float(amount)
    except: amount = None

    if amount is not None:
        if not check_if_user_exists(ID):
            insert_user(ID)
        update_yen_amount(ID,amount)
        print('amount updated')
        return 'amount updated'

    else:
        print('no amount')
        return None
Exemple #31
0
def start(bot, update,user_data):
	print(bot)
	print(update)
	user_data['id']=update.message.from_user.id
	result=db.insert_user(update.message.from_user.id)
	if result=='Exist':
		bot.sendMessage(update.message.from_user.id,'Hey Welcome back. To see your booking type /details or make a new booking press /book')
	elif result==False:
		bot.sendMessage(update.message.from_user.id,'Something wrong happened! Try again later')
	else:

		bot.sendMessage( update.message.from_user.id,"Welcome to Rajat Waffle's Factory. Press or type '/help' for information")
Exemple #32
0
def register(first_name, last_name, email, password, age, state, native_lang):
    """Registers new user.
    This function takes data, which describes user object and inserts this data
    into database. After that it gets new user object with get_user_by_id
    function and returns it.
    :Parameters:
        - `first_name`: first name of the new user,
        - `last_name`: last name of the new user,
        - `email`: email of the new user,
        - `password`: password of the new user.
    :Returns:
        User object of the new user.
    """
    salted_pass = hash_pass(password)
    register_user_id = db.insert_user(first_name, last_name, age, state, email,
                                      salted_pass, native_lang)
    return get_user_by_id(register_user_id)
#-*- coding:utf-8 -*-

from zhihu_api import User
import Queue,db,sys


reload(sys)
sys.setdefaultencoding('utf8')

initial_page = u'http://www.zhihu.com/people/liu-yang-57-86'
url_queue = Queue.Queue()
seen = db.get_existing("users")
seen.add(initial_page)
url_queue.put(initial_page)
while(True): #一直进行直到海枯石烂
    if url_queue.qsize()>0:
        current_url = url_queue.get()    #拿出队例中第一个的url
        #store(current_url)               把这个url代表的网页存储好
        for next_url in User(current_url).get_followees(): #提取把这个url里链向的url
            if next_url not in seen:
                seen.add(next_url)
                try:
                    name,url,followees_num,followers_num,thanks_num,agree_num,asks_num,answers_num = User(next_url).get_info()
                    db.insert_user(name,url,followees_num,followers_num,thanks_num,agree_num,asks_num,answers_num)
                except:
                    print next_url+'用户不存在'
                url_queue.put(next_url)
    else:
        break