예제 #1
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
 def fetch_search():
     if user_timeline & db.MODE_TRACK and user['track_words']:
         q = user['track_words'].replace(',', ' ')
         data = api.get_search(q, since_id=user['last_search_id'])
         if data:
             db.update_user(jid=user_jid, last_search_id=data[0]['id_str'])
             return data
예제 #2
0
파일: app1.py 프로젝트: cyntzhou/final
def viewMessage():    
    user= db.find_user({'username':session['username']})
    Message=user["Message"]
    if request.method=='GET':
        return render_template('view_message.html',Message=Message)
    else:        
        button = request.form['button']
        if button == 'Search':        
            return redirect('/search/'+request.form['query'])
        if button== "Submit Changes":
            counter=0
            toBeRemoved=[]
            for message in Message:
                try:
                    request.form[str(counter)+"message"]
                    removal=True
                except:
                    removal= False
                if removal==True:
                    toBeRemoved.append(counter)
                counter= counter+1
            for number in toBeRemoved:
                Message.pop(number)
            criteria= {"username":session['username']}
            db.update_user(criteria,{"Message":Message})
            Message= user["Message"]
        return render_template('view_message.html',Message=Message)
예제 #3
0
    def running(self):
        try:
            user_stream_handler = self.api.user_stream(timeout=MAX_CONNECT_TIMEOUT, track=self.user['track_words'])
            logger.debug('%s: connected.' % self.user['jid'])

            self.friend_ids = self.read_data(user_stream_handler)['friends']

            if self.wait_time_now_index:
                self.wait_time_now_index = 0

            while True:
                data = self.read_data(user_stream_handler)
                self.check_user_changed()
                if data:
                    self.process(data)
        except twitter.UnauthorizedError:
            logger.error('User %s OAuth unauthorized, exiting.' % self.user['jid'])
            db.update_user(self.user['id'], access_key=None, access_secret=None)
            self._queue.put(mythread.ThreadStop())
            raise mythread.ThreadStop
        except twitter.EnhanceYourCalmError:
            logger.warn('User %s Streaming connect too often!' % self.user['jid'])
            if not self.wait_time_now_index:
                self.wait_time_now_index = 1
        except (Error, twitter.Error), e:
            logger.warn('connection failed: %s' % str(e))
예제 #4
0
def vote():
    global voter_id
    cand_id = request.form['cand_id']
    print(voter_id,cand_id)
    update_vote(conn, int(cand_id))
    update_user(conn, voter_id, int(cand_id))
    return redirect("/confirmation", code=302)
예제 #5
0
파일: app1.py 프로젝트: cyntzhou/final
def viewProfile(username='******'):
    if username == 'None':
        return redirect('/')
    viewer=session['username']
    criteria= {"username":username}
    user=db.find_user(criteria)
    clubs=[] 
    clubList= db.list_clubs(username)
    for club in clubList:
        clubs.append(club[0])
        
    info=[username,user['first'],user['last'],user['schedule'],user['essays'],clubs]
    essays = db.find_essays({'user':username})
    if request.method== 'GET':
        return render_template('profile.html',viewer=viewer,info=info,counter=False,user=user, essays=essays)   
    else:
        button = request.form['button']
        if button == 'Search':        
            return redirect('/search/'+request.form['query'])
        localtime = time.strftime("%B %d, %Y, %I:%M %p")
        userMessage= user['Message']        
        message = request.form['User_Message']
        message = {"Message":message,"Sender":session['username'],"Time":localtime}        
        if userMessage== None:
            userMessage=[]
        userMessage.append(message)
        user=db.find_user(criteria)
        db.update_user(criteria,{"Message":userMessage})
        essays = db.find_essays({'user':username})
        
        return render_template('profile.html',info=info,viewer=viewer,counter=True,user=user, essays=essays)
예제 #6
0
 def func_on(self, *args):
     if args:
         for a in args:
             a = a.lower()
             if a == 'home':
                 self._user['timeline'] |= db.MODE_HOME
             elif a == 'mention':
                 self._user['timeline'] |= db.MODE_MENTION
             elif a == 'dm':
                 self._user['timeline'] |= db.MODE_DM
             elif a == 'list':
                 self._user['timeline'] |= db.MODE_LIST
             elif a == 'event':
                 self._user['timeline'] |= db.MODE_EVENT
             elif a == 'track':
                 self._user['timeline'] |= db.MODE_TRACK
         db.update_user(id=self._user['id'], timeline=self._user['timeline'])
         if self._user['timeline']:
             self._xmpp.start_worker(self._bare_jid)
             self._xmpp.start_stream(self._bare_jid)
     modes = []
     if self._user['timeline'] & db.MODE_LIST:
         modes.append('list')
     if self._user['timeline'] & db.MODE_HOME:
         modes.append('home')
     if self._user['timeline'] & db.MODE_MENTION:
         modes.append('mention')
     if self._user['timeline'] & db.MODE_DM:
         modes.append('dm')
     if self._user['timeline'] & db.MODE_EVENT:
         modes.append('event')
     if self._user['timeline'] & db.MODE_TRACK:
         modes.append('track')
     modes_str = ', '.join(modes) if modes else 'nothing'
     return u'You have enabled update for %s.' % modes_str
예제 #7
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
 def fetch_mention():
     # TODO: use activity api instead of this one. add event support
     if user_timeline & db.MODE_MENTION:
         data = api.get_mentions(since_id=user['last_mention_id'])
         if data:
             db.update_user(jid=user_jid, last_mention_id=data[0]['id_str'])
             return data
예제 #8
0
 def func_off(self, *args):
     if args:
         for a in args:
             a = a.lower()
             if a == 'home':
                 self._user['timeline'] &= ~db.MODE_HOME
             elif a == 'mention':
                 self._user['timeline'] &= ~db.MODE_MENTION
             elif a == 'dm':
                 self._user['timeline'] &= ~db.MODE_DM
             elif a == 'list':
                 self._user['timeline'] &= ~db.MODE_LIST
             elif a == 'event':
                 self._user['timeline'] &= ~db.MODE_EVENT
             elif a == 'track':
                 self._user['timeline'] &= ~db.MODE_TRACK
     else:
         self._user['timeline'] = db.MODE_NONE
     db.update_user(self._user['id'], timeline=self._user['timeline'])
     if self._user['timeline']:
         self._xmpp.stream_threads[self._bare_jid].user_changed()
     else:
         self._xmpp.stop_stream(self._bare_jid)
         self._xmpp.stop_worker(self._bare_jid)
     return self.func_on()
예제 #9
0
def drop(item_to_drop, inventory, user_id, response=None, quantity=None):
    # If the user attempts to drop something they don't have...
    if item_to_drop not in inventory:
        print('Player does not have {item}.'.format(item=item_to_drop))
        return 'You don\'t have anything like that.'

    # If they are removing an item from their inventory entirely...
    if inventory[item_to_drop]['quantity'] <= 1 or quantity == 'all':
        print('Deleting all {item}s from inventory.'.format(item=item_to_drop))
        del inventory[item_to_drop]
    # Otherwise, decrease its quantity by 1.
    else:
        print('Removing one {item} from inventory.'.format(item=item_to_drop))
        inventory[item_to_drop]['quantity'] -= 1

    if DEBUG.ITEM:
        print(COLOR.WARNING + 'Not updating inventory while debugging.' +
              COLOR.END)
    else:
        print(COLOR.GREEN + 'Updating inventory.' + COLOR.END)
        # Update the database with the modified inventory.
        db.update_user(inventory, user_id)

    if response != None:
        # If there is a pass-through response, return it.
        return response
    elif quantity == 'all':
        # TODO: Poorly pluralized.
        return 'You rid yourself of {item}s.'.format(item=item_to_drop)
    else:
        # Otherwise, just one is getting deleted.
        return 'You drop one {item}.'.format(item=item_to_drop)
예제 #10
0
def select_type(update, context):
    user = update.effective_user
    logger.info("Exchange type of %s: %s", user.first_name,
                update.callback_query.data)
    db.update_user(user.username, { 'exchange_type': ExchangeType[update.callback_query.data].name })
    update.callback_query.edit_message_text(text="Please provide your Api Key:")
    return ENTER_APIKEY
예제 #11
0
def edit_configration(user):
	print(Fore.MAGENTA + "\n======= Edit Configration =======")
	id = user.id
	user = read_configration()
	user.id = id
	db.update_user(user)
	return user
예제 #12
0
def viewMessage():
    user = db.find_user({'username': session['username']})
    Message = user["Message"]
    if request.method == 'GET':
        return render_template('view_message.html', Message=Message)
    else:
        button = request.form['button']
        if button == 'Search':
            return redirect('/search/' + request.form['query'])
        if button == "Submit Changes":
            counter = 0
            toBeRemoved = []
            for message in Message:
                try:
                    request.form[str(counter) + "message"]
                    removal = True
                except:
                    removal = False
                if removal == True:
                    toBeRemoved.append(counter)
                counter = counter + 1
            for number in toBeRemoved:
                Message.pop(number)
            criteria = {"username": session['username']}
            db.update_user(criteria, {"Message": Message})
            Message = user["Message"]
        return render_template('view_message.html', Message=Message)
예제 #13
0
 def func_track(self, *values):
     if values:
         self._user['track_words'] = ','.join(values)
         db.update_user(id=self._user['id'], track_words=self._user['track_words'])
         self._xmpp.stream_threads[self._bare_jid].stop()
         self._xmpp.stream_threads[self._bare_jid].join()
         self._xmpp.start_stream(self._bare_jid)
     return u'You are tracking words: %s. (comma seprated)' % self._user['track_words']
예제 #14
0
def enter_secretkey(update, context):
    user = update.message.from_user
    logger.info("Secret Key of %s: %s",
                user.first_name, update.message.text)
    db.update_user(user.username, { 'secret_key': update.message.text })
    update.message.reply_text('Bingo! Your account is now ready.')

    return ConversationHandler.END
예제 #15
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
 def fetch_home():
     data = api.get_home_timeline(since_id=user['last_home_id'])
     if data:
         db.update_user(jid=user_jid, last_home_id=data[0]['id_str'])
         if not user_timeline & db.MODE_HOME:
             if user_timeline & db.MODE_MENTION:
                 return [x for x in data if user_at_screen_name in x['text']]
         else:
             return data
예제 #16
0
def update_resume():
    huid = request.form.get('uid')
    uid = hash.database_safe_hash(huid)
    data = json.loads(request.form.get('data'))
    if get_user(uid):
        update_user(uid, data)
        return jsonify({
            'success': True,
            'message': 'User data has been updated.'
        })
    return jsonify({'success': False, 'message': 'Invalid user ID.'})
예제 #17
0
def replace(prev_item, next_item, inventory, user_id, response):
    print('Replacing an item.')
    # This function is used for converting one item into another, for example
    # "coin" => "bent coin".
    if next_item not in inventory:
        print('The player does not yet have ' + next_item + '.')
        # Add the item to the player's inventory and set its quantity to 1.
        inventory[next_item] = {}
        inventory[next_item]['quantity'] = 1
    else:
        print('Player has ' + next_item + '. Adding another.')
        # If the new item was in the inventory already, we should check that
        # they haven't reached the maximum amount they can hold of that item.
        item_max = db.select('max', 'items', 'name', next_item)
        print('Player can hold ' + str(item_max) + ' of these.')

        if inventory[next_item]['quantity'] < item_max:
            print('Player can hold one more.')
            # The player can hold another one, add 1.
            inventory[next_item]['quantity'] += 1
        else:
            print('Player can\'t hold anymore.')
            return 'You can\'t hold more {item}!'.format(item=next_item)

    # If they only had one of the item being replaced, remove it.
    # TODO: get() is the same as this function except for this if/else. Can we
    # share some logic here?
    if inventory[prev_item]['quantity'] <= 1:
        print('Deleting {item} from inventory.'.format(item=prev_item))
        del inventory[prev_item]
    # Otherwise, decrease its quantity by 1.
    else:
        print('Removing a {item} from inventory.'.format(item=prev_item))
        inventory[prev_item]['quantity'] -= 1

    print('Let\'s see how full the player\'s inventory is.')

    # Check if the player's inventory is too full after adding the item. If
    # so, return the warning without updating the database.
    # `'x' * 15` is a placeholder for a long `screen_name`.
    if len(build_tweet('x' * 15, build_inventory_tweet(inventory))) >= 140:
        return 'Your inventory is full.'

    if DEBUG.ITEM:
        print(COLOR.WARNING + 'Not updating inventory while debugging.' +
              COLOR.END)
    else:
        print(COLOR.GREEN + 'Updating inventory.' + COLOR.END)
        # Update the database with the modified inventory.
        db.update_user(inventory, user_id)

    # Return the pass-through response.
    return response
예제 #18
0
 def func_oauth(self):
     consumer = oauth.Consumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET)
     client = oauth.Client(consumer)
     resp = client.request(twitter.REQUEST_TOKEN_URL)
     if resp:
         request_token = dict(urlparse.parse_qsl(resp))
         oauth_token = request_token['oauth_token']
         redirect_url = "%s?oauth_token=%s" % (twitter.AUTHORIZATION_URL, oauth_token)
         db.update_user(self._user['id'], access_key=oauth_token, access_secret=None)
         return u'Please visit below url to get PIN code:\n%s\nthen you should use "-bind PIN" command to actually bind your Twitter.' % redirect_url
     else:
         return u'Network error.'
예제 #19
0
def callback_inline(call):
    if call.message:
        user = db.get_user(call.message.chat.id)
        if call.data == "YES":
            user.status = Status.GET_PERIOD.value
            db.update_user(user)
            bot.edit_message_reply_markup(message_id=call.message.message_id,
                                          chat_id=call.message.chat.id)
            bot.send_message(text=texts['GET_PERIOD'],
                             parse_mode='Markdown',
                             chat_id=call.message.chat.id,
                             reply_markup=keyboards.HIDE)
def handler(user_id: str) -> Response:
    """ Handler of TEAM_06_OPEN_TIME_TRACKING intent,
        TEAM_06_OPEN_TIME_TRACKING intent is activated when user says 'zeiterfassung stoppen'
        welcomes user

    :return:        Response
    """

    user_info = get_user(user_id)

    if user_info:
        update_user(user_info)
    else:
        create_user(user_id)

    clockify_api_key = get_clockify_api_key(user_id)

    if clockify_api_key is None or clockify_api_key == '':
        user_token = get_user_token(user_id)

        if user_token is None or user_token == '':
            user_token = get_random_string(4)
            set_user_token(user_id, user_token)

        msg = _('WELCOME_NEW_USER')

        response = tell(msg)

        response.card = Card(
            type_="GENERIC_DEFAULT",
            title="Time Tracker: Hinterlege deinen Clockify Account",
            text="User Token: {token}".format(token=user_token),
            action=get_auth_url(token=user_token),
            action_text="Klick hier, um einen Account zu hinterlegen.")
    else:
        clockify = get_clockify(clockify_api_key)
        clockify_id = clockify['user_id']
        workspace_id = clockify['active_workspace_id']
        time_entries = get_time_entries(clockify_api_key=clockify_api_key,
                                        workspace_id=workspace_id,
                                        user_id=clockify_id)
        running_timer = check_running_timer(time_entries)
        # Get time tracking status
        if running_timer:
            msg = _('WELCOME_RETURNING_USER')
            msg = msg + " " + _('WELCOME_STOP_SELECTION')
        else:
            msg = _('WELCOME_SELECTION')

        response = ask(msg)

    return response
예제 #21
0
def get_acc_id(user, region):
    engine = db.get_engine()
    acc_df = pd.read_sql(sql="SELECT t.*, CTID FROM public.lol_summoners t",
                         con=engine)
    if user.lower() not in [name.lower() for name in list(acc_df["name"])]:
        db.update_user(user=user, region=region)

    acc_df = pd.read_sql(
        sql="SELECT t.*, CTID FROM public.lol_summoners t WHERE name='%s'" %
        user,
        con=engine,
    )
    return acc_df["accountId"][0]
예제 #22
0
    def run_loop(self, game):
        """Main Reddit input loop.

        Gets comments, ensures comment is new and not made
        by "karma-tycoon", parses the command and replies
        with an appropriate response.

        Sleeps 2 seconds after each comment. If this is too
        slow, nesting this loop in a while loop may be the
        way to go.
        """

        #for comment in self.subr.get_comments():
        for comment in praw.helpers.comment_stream(
                reddit_session=self.reddit, subreddit=self.subr, limit=100
            ):

            if not db.has_comment_id(comment.id):
                if "karma-tycoon" == comment.link_author \
                        and "karma-tycoon" != comment.author.name:

                    comment_user = user.get_user(comment.author.name)
                    command_count = db.get_command_count(comment_user)

                    print ":: new comment %s by %s (%d)" % (
                        comment.id, comment.author.name, command_count
                    )

                    success, info, gold = game.parse_command(
                        comment_user, comment.body
                    )

                    if not info == "not command":
                        if success:
                            # maybe someone will get gold on their first try?
                            if gold:
                                self.reply_gilded(comment, info)
                                print ":: %s was gilded!" % comment.author.name
                            else:
                                self.reply_success(comment, info)
                        else:
                            self.reply_fail(comment, info)

                    self.update_op(game)
                    self.update_user_flair(comment_user)
                    db.update_user(comment_user)
                    db.update_game(game)

                print ":: adding %s to db" % comment.id
                db.add_comment_id(comment.id)
                time.sleep(2)
예제 #23
0
def refresh_token(user_id):
    tk = db.get(user_id)
    print(tk[0])
    b = requests.post("https://accounts.spotify.com/api/token",
                      headers=dict(
                          Authorization=f"Basic {keys['basic']}"
                      ),
                      data=dict(
                          grant_type="refresh_token",
                          refresh_token=tk[0]
                      )).json()
    print(b)
    db.update_user(user_id,b['access_token'])
    return b['access_token']
예제 #24
0
def manage_index_POST(request):
    data = request.POST_query
    nickname, email, photodata = data["name"][0], data['email'][0], data[
        'photo'][0]
    user = request.auth_get_user()

    e = {'name': nickname.strip(), 'email': email.strip()}
    if photodata:
        photopath = save_photo(photodata)
        e.update(photopath=photopath)
    update_chat_user(user.id, e)
    db.update_user(user.id, **e)

    return redirect_to(request, '/auth/manage/index/')
예제 #25
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
 def fetch_list():
     if user_timeline & db.MODE_LIST and user['list_user'] and user['list_name']:
         try:
             data = api.get_list_statuses(screen_name=user['list_user'], slug=user['list_name'],
                 since_id=user['last_list_id'])
         except twitter.NotFoundError:
             user['timeline'] &= ~db.MODE_LIST
             db.update_user(id=user['id'], timeline=user['timeline'])
             queue.put({"jid": user['jid'], "title": 'List %s/%s not exists, disable List update.' % (
                 user['list_user'], user['list_name'])})
         else:
             if data:
                 db.update_user(jid=user_jid, last_list_id=data[0]['id_str'])
                 return data
예제 #26
0
 def func_always(self, value=None):
     if value is not None:
         value = value.lower()
         if value in ('true', '1', 'on'):
             value = 1
         elif value in ('false', '0', 'off'):
             value = 0
         else:
             raise TypeError('Only accept true/false, 1/0, on/off.')
         self._user['always'] = value
         db.update_user(id=self._user['id'], always=value)
     if self._user['always']:
         return u'You will always receive updates no matter you are online or not.'
     else:
         return u'You will only receive updates when your status is available.'
예제 #27
0
def manage_edit_password_POST(request, **kwargs):
    data = request.POST_query
    old_password, new_password, confirm_password = data["old_password"][0].strip(), data["new_password"][0].strip(), \
                                                   data["confirm_password"][0].strip()
    user = request.auth_get_user()
    print(old_password, new_password, confirm_password)
    if not old_password or not new_password or not confirm_password or \
            new_password != confirm_password or not equal_passhash(user.password, old_password):
        kwargs.setdefault('message', 'bad password')
        return render_template(request,
                               'templates/auth/manage/edit_password.html',
                               kwargs=kwargss)
    pass_hex = convert_pass_to_passhash(new_password)
    db.update_user(user.id, password=pass_hex)
    return redirect_to(request, '/auth/manage/index/')
예제 #28
0
def viewProfile(username='******'):
    if username == 'None':
        return redirect('/')
    viewer = session['username']
    criteria = {"username": username}
    user = db.find_user(criteria)
    clubs = []
    clubList = db.list_clubs(username)
    for club in clubList:
        clubs.append(club[0])

    info = [
        username, user['first'], user['last'], user['schedule'],
        user['essays'], clubs
    ]
    essays = db.find_essays({'user': username})
    if request.method == 'GET':
        return render_template('profile.html',
                               viewer=viewer,
                               info=info,
                               counter=False,
                               user=user,
                               essays=essays)
    else:
        button = request.form['button']
        if button == 'Search':
            return redirect('/search/' + request.form['query'])
        localtime = time.strftime("%B %d, %Y, %I:%M %p")
        userMessage = user['Message']
        message = request.form['User_Message']
        message = {
            "Message": message,
            "Sender": session['username'],
            "Time": localtime
        }
        if userMessage == None:
            userMessage = []
        userMessage.append(message)
        user = db.find_user(criteria)
        db.update_user(criteria, {"Message": userMessage})
        essays = db.find_essays({'user': username})

        return render_template('profile.html',
                               info=info,
                               viewer=viewer,
                               counter=True,
                               user=user,
                               essays=essays)
예제 #29
0
파일: app.py 프로젝트: svv232/DB_Project
def edit_profile():
    user = get_user(session['email'])
    db_email = user['email']
    db_first = user['fname']
    db_last = user['lname']

    new_email = request.form.get(
        'email') if request.form.get('email') != db_email else None
    new_first = request.form.get(
        'fname') if request.form.get('fname') != db_first else None
    new_last = request.form.get(
        'lname') if request.form.get('lname') != db_last else None

    status = update_user(db_email,
                         new_email=new_email,
                         new_first=new_first,
                         new_last=new_last)

    if status[0]:
        if new_email:
            user = get_user(new_email)
        else:
            user = get_user(session['email'])

        session['email'] = user['email']
        session['fname'] = user['fname']
        session['lname'] = user['lname']

    return redirect('/')
예제 #30
0
파일: web.py 프로젝트: nickrobson/bloggo
def settings():
    username = session.get('username')
    if not username:
        abort(401)
    user_info = get_user_info(username)
    if request.method == 'GET':
        return render_template('settings.html', user_info = user_info)
    form = request.form
    files = request.files
    to_update = {}
    new_display = form.get('display')
    new_description = form.get('description')
    new_password = form.get('npassword')
    if new_password and len(new_password):
        curr_password = form.get('password')
        if not curr_password or not len(curr_password):
            flash('You need to enter your current password!')
        elif new_password == form.get('cnpassword'):
            to_update['password'] = new_password
            to_update['old_password'] = curr_password
        else:
            flash('The "new" passwords that you entered do not match!')
    if new_display and len(new_display) and new_display != user_info['display']:
        to_update['display'] = new_display
    if new_description and len(new_description) and new_description != user_info['info']:
        to_update['info'] = new_description
    if db.update_user(username, to_update, flash):
        flash('Successfully updated!')
        if 'display' in to_update:
            session['display'] = to_update['display']
    return redirect(url_for('.settings'))
예제 #31
0
def send_membro(message):
    """Permite ao usuario se cadastrar e informar seu estado e cidade"""
    params = shlex.split(message.text)
    if len(params) < 2:
        bot_responda(message, MEMBRO_AJUDA)
        return
    estado = params[1].strip()
    print(params)
    if len(params) > 2:
        cidade = params[2].strip()
    else:
        cidade = None

    membro, db_estado, db_cidade = db.update_user(message.from_user, estado,
                                                  cidade)

    if membro:
        bot_responda(
            message,
            MEMBRO_RESULTADO.format(message.from_user, db_estado, db_cidade
                                    or "Não informada/encontrada"))
    else:
        bot_responda(message, MEMBRO_ESTADO.format(message.chat, estado))

    if not message.from_user.last_name:
        bot_responda(message, TELEGRAM_ULTIMO_NOME_AJUDA)

    if not message.from_user.username:
        bot_responda(message, TELEGRAM_NOME_USUARIO_AJUDA)
예제 #32
0
파일: util.py 프로젝트: ayanamist/TwiOtaku
 def generate_short_id(self, long_id, single_type):
     short_id = db.get_short_id_from_long_id(self._user['id'], long_id, single_type)
     if short_id is not None:
         if self.no_duplicate:
             raise DuplicateError
     else:
         self._user['id_list_ptr'] += 1
         short_id = self._user['id_list_ptr']
         if short_id >= config.MAX_ID_LIST_NUM:
             short_id = self._user['id_list_ptr'] = 0
         old_long_id, _ = db.get_long_id_from_short_id(self._user['id'], short_id)
         if db.get_long_id_count(old_long_id) <= 1:
             db.delete_cache(old_long_id)
         db.update_user(id=self._user['id'], id_list_ptr=short_id)
         db.update_long_id_from_short_id(self._user['id'], short_id, long_id, single_type)
     return short_id, number.digit_to_alpha(short_id)
예제 #33
0
def updateuser():
    if not session.get('name'):
        return redirect('/login')
#通过id查询到要更新的数据,并渲染到更新页面
    if request.method == "GET":
        uid = request.args.get("uid")
        print uid
        userinfo = getuser(uid)
        print userinfo
        return json.dumps(userinfo)
#获取到更新页面表单的值,然后提交更新
    if request.method == "POST":
        userinfo = dict((k, v[0]) for k, v in dict(request.form).items())
        print userinfo
        update_user(userinfo)
        return json.dumps({"code": 0})
예제 #34
0
def update_user(email):
    # Retrieve user data.
    row = db.find_user(email)

    if row is None:
        flash("User {} doesn't exist".format(email))
        return redirect(url_for('all_users'))

    # Initialize object with form data if available (this is the default behavior for a FlaskForm;
    # you need not even provide the argument. Otherwise initialize with specific values fetched
    # previously from the database.
    user_form = UserForm(email=row['email'],
                         first_name=row['first_name'],
                         last_name=row['last_name'])

    if user_form.validate_on_submit():
        # If we get here, we're handling a POST request and the form validated successfully.
        rowcount = db.update_user(email, user_form.first_name.data,
                                  user_form.last_name.data,
                                  user_form.password.data)

        # We're updating a single row, so we're successful if the row count is one.
        if rowcount == 1:
            # Everything worked. Flash a success message and redirect to the home page.
            flash("User '{}' updated".format(email))
            return redirect(url_for('index'))

        else:  # The update operation failed for some reason. Flash a message.
            flash('User not updated')

    return render_template(
        'user-form.html',
        form=user_form,
        mode='update',
    )
예제 #35
0
 def func_datefmt(self, *content):
     content = ' '.join(content)
     if content:
         if content.lower() == 'reset':
             content = None
             result = u'You have reset date format to default.'
         else:
             now = datetime.datetime.now()
             now_str = now.strftime(content.encode('UTF8')).decode('UTF8')
             result = u'You have updated date format as following: %s\nPreview: %s' % (content, now_str)
         db.update_user(id=self._user['id'], date_fmt=content)
     else:
         if self._user['date_fmt']:
             result = u'Your current date format is: %s.' % self._user['date_fmt']
         else:
             result = u'Your current date format is default.'
     return result
예제 #36
0
 def func_live(self, list_user_name=None):
     if list_user_name:
         path = list_user_name.split('/', 1)
         if len(path) == 1:
             list_user = self._user['screen_name']
             list_name = path[0]
         else:
             list_user, list_name = path
         response = self._api.get_list(list_user.encode('UTF8'), list_name.encode('UTF8'))
         self._user['list_user'] = response['user']['screen_name']
         self._user['list_name'] = response['slug']
         db.update_user(id=self._user['id'], list_user=self._user['list_user'], list_name=self._user['list_name'],
             list_ids=None, list_ids_last_update=0)
         self._xmpp.stream_threads[self._bare_jid].user_changed()
     if self._user['list_user'] and self._user['list_name']:
         return u'List update is assigned for %s/%s.' % (self._user['list_user'], self._user['list_name'])
     return u'Please specify a list as screen_name/list_name format first.'
예제 #37
0
 def update(self, dict_patch):
     dict_patch.pop('hashed_password', None)
     dict_patch.pop('salt', None)
     dict_patch.pop('ctime', None)
     self._user_dict.update(dict_patch)
     for key, val in self._user_dict.items():
         if val is None:
             del self._user_dict[key]
     return db.update_user(self._user_dict)
예제 #38
0
def updateuser():
#通过id查询到要更新的数据,并渲染到更新页面
	if request.method =="GET":
		uid=request.args.get("uid")
		print uid
		userinfo=getuser(uid)
		return render_template("update.html",user=userinfo)
#获取到更新页面表单的值,然后提交更新
	if request.method =="POST":
		userinfo={}
        	userinfo["name"] = request.form['name']
		userinfo["name_cn"] = request.form['name_cn']
        	userinfo["email"] = request.form['email']
       	 	userinfo["mobile"] = request.form['mobile']
        	userinfo["role"] = request.form['role']
        	userinfo["status"] = request.form['status']
        	update_user(userinfo)
        	return redirect("/userlist")
예제 #39
0
 def func_bind(self, pin_code):
     if self._user['access_key']:
         token = oauth.Token(self._user['access_key'])
         if type(pin_code) is unicode:
             pin_code = pin_code.encode('UTF8')
         token.set_verifier(pin_code)
         consumer = oauth.Consumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET)
         client = oauth.Client(consumer, token)
         resp = client.request(twitter.ACCESS_TOKEN_URL, "POST")
         if not resp:
             return u'Network error.'
         access_token = dict(urlparse.parse_qsl(resp))
         if 'oauth_token' in access_token:
             db.update_user(self._user['id'], access_key=access_token['oauth_token'],
                 access_secret=access_token['oauth_token_secret'],
                 screen_name=access_token['screen_name'])
             self._xmpp.add_online_user(self._bare_jid)
             return u'Associated you with @%s.' % access_token['screen_name']
     return u'Invalid PIN code.'
예제 #40
0
 def func_msgtpl(self, *content):
     content = ' '.join(content)
     if content:
         if content.lower() == 'reset':
             content = None
             result = u'You have reset message template to default. Preview:\n%s'
         else:
             result = u'You have updated message template. Preview:\n%s'
         self._user['msg_tpl'] = content
         db.update_user(id=self._user['id'], msg_tpl=content)
         self._util = util.Util(self._user)
         preview = self._util.parse_status(template_test.status)
         result %= preview
     else:
         if self._user['msg_tpl']:
             result = u'Your current message template is:\n%s' % self._user['msg_tpl']
         else:
             result = u'Your current message template is default'
     return result
예제 #41
0
async def give(message):
    '''
    Give money to a user from your own stash. Syntax is as follows: $give {user_name} {amount}
    '''
    values = _parse_options(message)

    try:
        source_id = message.author.id
        target_name = values[0]
        amount = _dollars_to_cents(float(values[1]))

        if len(values) != 2:
            raise IndexError

        if amount <= 0:
            return await message.channel.send(
                'Cannot give an amount less than or equal to zero.')

        source_user = await db.get_user_by_id(source_id)
        target_user = await db.get_user_by_name(target_name)

        if not target_user:
            return await message.channel.send(
                f'Cannot find user with name {target_name} - be sure to use the full syntax, eg: user#1234.)'
            )

        if source_user['money'] - amount < 0:
            return await message.channel.send(
                'You do not have enough money to complete this transaction.')

        source_user['money'] -= amount
        target_user['money'] += amount

        # This is not atomic, but it's fine for the prototype.
        await (db.update_user(source_user))
        await (db.update_user(target_user))

        await message.channel.send(
            f"You've given {_cents_to_dollars(amount)} to {target_name}.")
    except IndexError:
        await message.channel.send(f'Unable to parse give - check your syntax!'
                                   )
예제 #42
0
def deposit():
    try:
        amount = int(input("How much will you like to deposit? "))
        current_user['balance'] += amount
        updated = db.update_user(current_user['email'], current_user)
        if updated:
            update_user(current_user['email'])
            print("current balance is %d" % current_user['balance'])
        operations()
    except:
        print("something went wrong")
예제 #43
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
def cron_list(user, xmpp):
    if user['list_user'] and user['list_name']:
        api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
            consumer_secret=config.OAUTH_CONSUMER_SECRET,
            access_token_key=user['access_key'],
            access_token_secret=user['access_secret'])
        thread = xmpp.stream_threads.get(user['jid'])
        cursor = -1
        list_ids = set()
        while cursor:
            try:
                result = api.get_list_members(user['list_user'], user['list_name'], cursor=cursor)
            except twitter.NotFoundError:
                break
            for x in result['users']:
                list_ids.add(x['id_str'])
            cursor = result['next_cursor']
        user = db.get_user_from_jid(user['jid'])
        if (list_ids and user['list_ids'] is None) or (list_ids ^ set((user['list_ids'] or '').split(','))):
            db.update_user(id=user['id'], list_ids=','.join(list_ids))
            thread.user_changed()
예제 #44
0
def get(item, inventory, user_id, response):
    print('Getting an item.')
    # This function is used for adding an item to the player's inventory.
    if item not in inventory:
        print('The player does not yet have ' + item + '.')
        # Add the item to the player's inventory and set its quantity to 1.
        inventory[item] = {}
        inventory[item]['quantity'] = 1
    else:
        print('Player has ' + item + '. Adding another.')
        # If the new item was in the inventory already, we should check that
        # they haven't reached the maximum amount they can hold of that item.
        item_max = db.select('max', 'items', 'name', item)
        print('Player can hold ' + str(item_max) + ' of these.')

        if inventory[item]['quantity'] < item_max:
            print('Player can hold one more.')
            # The player can hold another one, add 1.
            inventory[item]['quantity'] += 1
        else:
            print('Player can\'t hold anymore.')
            return 'You can\'t hold more {item}!'.format(item=item)

    print('Let\'s see how full the player\'s inventory is.')
    # Check if the player's inventory is too full after adding the item. If
    # so, return the warning without updating the database.
    # `'x' * 15` is a placeholder for a long `screen_name`.
    if len(build_tweet('x' * 15, build_inventory_tweet(inventory))) >= 140:
        return 'Your inventory is full.'

    if DEBUG.ITEM:
        print(COLOR.WARNING + 'Not updating inventory while debugging.' +
              COLOR.END)
    else:
        print(COLOR.GREEN + 'Updating inventory.' + COLOR.END)
        # Update the database with the modified inventory.
        db.update_user(inventory, user_id)

    # Return the pass-through response.
    return response
예제 #45
0
def edit_profile():
    id = current_user.get_id()
    user = db.find_user_by_id(id)

    if hasattr(current_user, 'role'):
        role = current_user.get_role()
    else:
        role = ""

    if user is None:
        flash("User doesn't exist", category='danger')
        return redirect(url_for('all_users'))

    user_form = UserForm(name=user['name'],
                         email=user['email'],
                         zip=user['zip'],
                         password=user['password'],
                         bio=user['bio'])

    if user_form.validate_on_submit():
        user_dict = db.update_user(user_form.name.data, user_form.email.data,
                                   user_form.zip.data, user_form.password.data,
                                   user_form.bio.data, id)

        # uploaded_photo = user_form.image.data
        #
        # photo_row = db.init_user_photo(user_dict['id'])
        #
        # file_name = "file{:04d}".format(photo_row['id'])
        #
        # extension = PurePath(uploaded_photo.filename).suffix
        # file_name += extension
        #
        # file_path = os.path.join('static/user-photos', file_name)
        #
        # file_path2 = os.path.join('user-photos', file_name)
        #
        # save_path = os.path.join(app.static_folder, file_path2)
        # uploaded_photo.save(save_path)
        #
        # db.set_user_photo(photo_row['id'], file_path)

        if user_dict['rowcount'] == 1:
            flash("Profile updated!", category='success')
            return redirect(url_for('profile'))
        else:
            flash('User not updated', category='danger')

    return render_template('user-form.html',
                           form=user_form,
                           mode='edit-profile',
                           role=role)
def handler(user_id: str) -> Response:
    """ Handler of TEAM_06_START_TIME_TRACKING intent,
        TEAM_06_START_TIME_TRACKING intent is activated when user says 'zeiterfassung starten'
        returns question for project

    :return:        Response
    """

    user_info = get_user(user_id)

    if user_info:
        update_user(user_info)
    else:
        create_user(user_id)

    clockify_api_key = get_clockify_api_key(user_id)

    if clockify_api_key is None or clockify_api_key == '':
        user_token = get_user_token(user_id)

        if user_token is None or user_token == '':
            user_token = get_random_string(4)
            set_user_token(user_id, user_token)

        msg = _('WELCOME_NEW_USER')

        response = tell(msg)

        response.card = Card(
            type_="GENERIC_DEFAULT",
            title="Time Tracker: Hinterlege deinen Clockify Account",
            text="User Token: {token}".format(token=user_token),
            action=get_auth_url(token=user_token),
            action_text="Klick hier, um einen Account zu hinterlegen.")
    else:
        msg = _('ASK_PROJECT')
        response = ask(msg)

    return response
예제 #47
0
def run_get_status(user, message):
    try:
        if user.status == Status.GET_PERIOD.value:
            period_length = int(message.text)
            user.period_end = datetime.datetime.now() + datetime.timedelta(
                days=period_length)

        elif user.status == Status.GET_BALANCE_FOOD.value:
            user.food = int(message.text)

        elif user.status == Status.GET_BALANCE_ALCO.value:
            user.alco = int(message.text)

        elif user.status == Status.GET_BALANCE_TRANSPORT.value:
            user.transport = int(message.text)

        elif user.status == Status.GET_BALANCE_GENERAL.value:
            user.general = int(message.text)

        elif user.status == Status.GET_BALANCE_FINPILLOW.value:
            user.pillow = int(message.text)

        user.status = Status.get_next_balance(user.status)
        db.update_user(user)
        if user.status == Status.MAIN_MENU.value:
            bot.send_message(text=texts['SUCCESSFUL_REG'],
                             parse_mode='Markdown',
                             chat_id=message.chat.id,
                             reply_markup=keyboards.MAIN_MENU)
        else:
            bot.send_message(text=texts[user.status],
                             parse_mode='Markdown',
                             chat_id=message.chat.id,
                             reply_markup=keyboards.HIDE)
    except ValueError:
        bot.send_message(text=texts.NOT_A_NUMBER,
                         parse_mode='Markdown',
                         chat_id=message.chat.id)
def update_user(user_id):
    member = db.find_user_info(user_id)
    email = member['email']
    user_form = UpdateUserForm(email=member['email'])
    if user_form.validate_on_submit():
        old_password = user_form.old_password.data
        new_password = user_form.new_password.data
        confirm_password = user_form.confirm_password.data
        if bcrypt.check_password_hash(member['password'], old_password):
            if new_password == confirm_password:
                password = new_password
                pw_hash = bcrypt.generate_password_hash(password)
                print(member['role_id'])
                db.update_user(email, pw_hash, member['role_id'])
                flash('Password updated')
                return redirect(url_for('index'))
            else:
                flash('New Password and Confirmation Password Do Not Match')
                return redirect(url_for('update_user', user_id))
        else:
            flash('Entered in wrong current password')
            return redirect(url_for('update_user', user_id))
    return render_template('update_user.html', form=user_form, email=email)
예제 #49
0
def edit_user(user_id):
    auth_user_id = get_jwt_identity()
    auth_user = get_user(auth_user_id)
    target_user = get_user(user_id)

    json_input = request.get_json()
    changed_user = json_input['user'].items()

    if target_user.ID != auth_user.ID:
        return jsonify({'Error': 'Not authorized'}), 403

    if target_user.create_json() == changed_user:
        return jsonify({'Error': 'No changes submitted.'}), 400

    changeable_values = ['email', 'real_name', 'username']
    for kvp in changed_user:
        if kvp[0] not in changeable_values:
            return jsonify(
                {'Error':
                 'You can only edit email, real_name, or username.'}), 400

    update_user(user_id, changed_user)
    return jsonify({'Success': 'User modified.'})
def change_account():
    if request.method == 'GET':
        return render_template('change_account.html')

    if request.form['button'] == 'cancel':
        return redirect('/')

    criteria = {'username': session['username']}

    username = request.form['username']
    password = request.form['password']
    changeset = {}
    if username:
        changeset['username'] = username
    if password:
        changeset['password'] = password

    if valid_change(username, password)==True:
        db.update_user(criteria, changeset)
        if username:
            session['username'] = username
        return redirect('/display')
    else:
        return render_template('change_account.html', error=valid_change(username, password))
예제 #51
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
def cron_block(user, xmpp):
    api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
        consumer_secret=config.OAUTH_CONSUMER_SECRET,
        access_token_key=user['access_key'],
        access_token_secret=user['access_secret'])
    thread = xmpp.stream_threads.get(user['jid'])
    try:
        blocked_ids = api.get_blocking_ids(stringify_ids=True)
    except twitter.UnauthorizedError:
        db.update_user(user['id'], access_key=None, access_secret=None)
        if thread:
            thread.stop()
    else:
        if (blocked_ids and user['blocked_ids'] is None) or\
           (set(blocked_ids) - set(user['blocked_ids'].split(',') if user['blocked_ids'] else tuple())):
            db.update_user(id=user['id'], blocked_ids=','.join(blocked_ids))
            thread.user_changed()
        else:
            db.update_user(id=user['id'])
예제 #52
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
 def fetch_dm():
     if user_timeline & db.MODE_DM:
         data = api.get_direct_messages(since_id=user['last_dm_id'])
         if data and isinstance(data, list) and isinstance(data[0], twitter.DirectMessage):
             db.update_user(jid=user_jid, last_dm_id=data[0]['id_str'])
             return data
예제 #53
0
    def save_data(self):
        """Save data to db"""

        db.update_user(self)
예제 #54
0
파일: app1.py 프로젝트: cyntzhou/final
def change_user_info(key, value):
    criteria = {'username': session['username']}
    changeset = {}
    changeset[key] = value #a dictionary with the item you want to change
    db.update_user(criteria, changeset)
예제 #55
0
 def func_list(self, *args):
     length = len(args)
     if not length:
         lists = self._api.get_all_lists()
         texts = list()
         for l in lists:
             texts.append(u'%s %s: %s' %
                          (l['slug'] if l['user']['screen_name'] == self._user['screen_name'] else u'%s/%s' % (
                              l['user']['screen_name'],
                              l['slug']), l['mode'], l['description']))
         return u'Subscribing Lists:\n' + '\n'.join(texts)
     elif length == 1 or (length == 2 and args[1].isdigit()):
         try:
             page = int(args[1]) if length == 2 else 1
         except ValueError:
             return u'Unknown page number: %s.' % args[1]
         list_user_name = args[0]
         path = list_user_name.split('/', 1)
         if len(path) == 1:
             list_user = self._user['screen_name']
             list_name = path[0]
         else:
             list_user, list_name = path
         self._job["data"] = self._api.get_list_statuses(list_user, list_name, page=page)
         self._job["title"] = 'List %s Statuses: Page %d' % (list_user_name, page)
     else:
         list_command = args[0].lower()
         if list_command == 'info' and length == 2:
             list_user_name = args[1]
             path = list_user_name.split('/', 1)
             if len(path) == 1:
                 list_user = self._user['screen_name']
                 list_name = path[0]
             else:
                 list_user, list_name = path
             l = self._api.get_list(screen_name=list_user, slug=list_name)
             texts = (u'List %s/%s %s: %s' %
                      (l['user']['screen_name'], l['slug'], l['mode'],
                       u'You are following.' if l['following'] else u''),
                      u'Member Count: %d' % l['member_count'], u'Subscriber Count: %d' % l['subscriber_count'],
                      u'Description: %s' % l['description'])
             return '\n'.join(texts)
         elif list_command in ('add', 'del') and 2 <= length <= 3:
             if length == 2:
                 if list_command == 'add':
                     self._api.create_list(args[1], public=False)
                     return u'Created private list %s.' % args[1]
                 else:
                     self._api.destroy_list(self._user['screen_name'], args[1])
                     return u'Deleted list %s.' % args[1]
             else:
                 if list_command == 'add':
                     self._api.create_list_member(self._user['screen_name'], args[1], args[2])
                     title = u'Added %s to list %s.' % (args[2], args[1])
                 else:
                     self._api.destroy_list_member(self._user['screen_name'], args[1], args[2])
                     title = u'Removed %s from list %s.' % (args[2], args[1])
                 if self._user['screen_name'] == self._user['list_user'] and args[1] == self._user['list_name']:
                     db.update_user(id=self._user['id'], list_ids_last_update=0)
                     self._xmpp.stream_threads[self._bare_jid].user_changed()
                 return title
         else:
             raise TypeError('Not supported list command.')
예제 #56
0
파일: cron.py 프로젝트: ayanamist/TwiOtaku
def cron_timeline(user, queue):
    @logdecorator.silent
    def fetch_home():
        data = api.get_home_timeline(since_id=user['last_home_id'])
        if data:
            db.update_user(jid=user_jid, last_home_id=data[0]['id_str'])
            if not user_timeline & db.MODE_HOME:
                if user_timeline & db.MODE_MENTION:
                    return [x for x in data if user_at_screen_name in x['text']]
            else:
                return data

    @logdecorator.silent
    def fetch_mention():
        # TODO: use activity api instead of this one. add event support
        if user_timeline & db.MODE_MENTION:
            data = api.get_mentions(since_id=user['last_mention_id'])
            if data:
                db.update_user(jid=user_jid, last_mention_id=data[0]['id_str'])
                return data

    @logdecorator.silent
    def fetch_dm():
        if user_timeline & db.MODE_DM:
            data = api.get_direct_messages(since_id=user['last_dm_id'])
            if data and isinstance(data, list) and isinstance(data[0], twitter.DirectMessage):
                db.update_user(jid=user_jid, last_dm_id=data[0]['id_str'])
                return data

    @logdecorator.silent
    def fetch_list():
        if user_timeline & db.MODE_LIST and user['list_user'] and user['list_name']:
            try:
                data = api.get_list_statuses(screen_name=user['list_user'], slug=user['list_name'],
                    since_id=user['last_list_id'])
            except twitter.NotFoundError:
                user['timeline'] &= ~db.MODE_LIST
                db.update_user(id=user['id'], timeline=user['timeline'])
                queue.put({"jid": user['jid'], "title": 'List %s/%s not exists, disable List update.' % (
                    user['list_user'], user['list_name'])})
            else:
                if data:
                    db.update_user(jid=user_jid, last_list_id=data[0]['id_str'])
                    return data

    @logdecorator.silent
    def fetch_search():
        if user_timeline & db.MODE_TRACK and user['track_words']:
            q = user['track_words'].replace(',', ' ')
            data = api.get_search(q, since_id=user['last_search_id'])
            if data:
                db.update_user(jid=user_jid, last_search_id=data[0]['id_str'])
                return data

    def all_statuses_add(iterable):
        if not iterable:
            return
        for x in iterable:
            if x['id'] not in all_data_ids and x['user']['screen_name'] != user['screen_name']:
                all_data_ids.append(x['id'])
                all_data.append(x)


    user_jid = user['jid']
    user_timeline = user['timeline']
    db.update_user(id=user['id'], last_update=int(time.time()))

    api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
        consumer_secret=config.OAUTH_CONSUMER_SECRET,
        access_token_key=user['access_key'],
        access_token_secret=user['access_secret'])
    user_at_screen_name = '@%s' % user['screen_name']

    data = fetch_dm()
    if data:
        queue.put({"jid": user_jid, "data": data, "title": 'Direct Message:', "no_duplicate": True,
                   "not_always": True, "not_command": True})

    all_data = list()
    all_data_ids = list()
    all_statuses_add(fetch_list())
    all_statuses_add(fetch_mention())
    all_statuses_add(fetch_home())
    all_statuses_add(fetch_search())

    for status in all_data:
        if "in_reply_to_status_id_str" in status:
            status["in_reply_to_status"] = None

    if all_data:
        queue.put({"jid": user_jid, "data": all_data.sort(key=operator.itemgetter('id')), "no_duplicate": True,
                   "not_always": True, "not_command": True})