def action_add(): parser = argparse.ArgumentParser(description='Create user and print it\'s uid to stdout.') parser.add_argument('uid', type=int, default=-1, help='ID of user to be added. (pass -1 to get first free one)') args = parser.parse_args() print users.add(args.uid)
def send_welcome(message): # TODO: security try: bot.reply_to(message, MESSAGES["welcome"]) if users.exists(message.from_user.username): bot.send_message(message.chat.id, MESSAGES["you_are_my_user_already"]) else: users.add(message.from_user.username, message.chat.id) # send message for function _check_if_reply_to_server_request(msg) markup = telebot.types.ForceReply(selective=False) bot.send_message(message.chat.id, MESSAGES["request_for_server"], reply_markup=markup) except Exception as err: print(err) traceback.print_exc()
def attachUser(id, userId, accessToken=None): ''' This adds a user ID to the users array. It doesn't create a new user. :param id: :param userId: :param accessToken: :return: ''' mylist = _get(id) if not list: logging.error("List with id %s doesn't exist!", id) return False users = mylist['users'] or [] users = set(users) users.add(userId) mylist['users'] = list(users) return _update(id, mylist)
def main(): load() current_id = None while True: try: updates = bot.get_updates(offset=current_id).wait() or [] for update in updates: current_id = update.update_id + 1 msg = update.message _user = User( msg.sender.id, '%s %s' % (msg.sender.first_name, msg.sender.last_name)) add(_user) print('"%s" from %s' % (msg.text, _user.name)) handle(find_user(_user.id), msg) if not len(updates): time.sleep(0.1) except Exception as e: print(e)
def POST(self): post = web.input(_method='POST') # Validate user = users.get_user_by_name(post['username']) if user is not None: response = {'message': 'false'} else: auth = 1 if post['authority'] == 'guest' else 0 user = users.add(username=post['username'], password=users.pswd(post['password']), authority=auth) response = {'message': 'true'} logs.add_user(post['username']) return json.dumps(response)
def authorized(path, params, env): logger.info("authorized") cookie = Cookie.SimpleCookie(env["HTTP_COOKIE"]) name = cookie["twitter_name"].value succ, user = users.add(params["code"], name) logger.info("add user " + (succ and "ok" or "failed")) logger.debug(str(user)) cs1 = "sina_name=%s" % urllib.quote_plus(user["sina_name"].encode("unicode_escape")) cs2 = "session=%s" % user["session"] cs3 = "userid=%s" % user["sina_id"] headers = [ ("Content-Type", "text/plain"), ("Location", "/settings"), ("Set-Cookie", cs1), ("Set-Cookie", cs2), ("Set-Cookie", cs3), ] return ("302 Found", headers, "")
""" Fetches idea gists and stores them to the database. """ import db import users import ideas # Initialize the database db.init() # Add all registered users to db for user in users.fetch_registered(): users.add(user) # Fetch gists of every user for user in users.get_all(): for gist in ideas.fetch_gists(user): if not gist['description']: continue # Extract gists that are ideas if "#ideabin" in gist['description']: ideas.add(user, gist)
def process_line(line, currentChat, playerLookup): if line == "": return #print(line) line = line.rstrip().split() if len(line) == 0: print("this condition is necessary") return ismod = False userId = -1 if line[0][0] == "@": tags = line.pop(0) tmp8 = tags.split("mod=") if len(tmp8) > 1: if tmp8[1][0] == "1": ismod = True tmp9 = tags.split("user-id=") if len(tmp9) > 1: userId = tmp9[1].split(";")[0] user = "" command = [] channel = "" for index, word in enumerate(line): if index == 0: user = word.split('!')[0] #user = user[0:24] # what's this for? if user == "PING": currentChat.pong() return if len(line) < 4: return if index == 2: channel = word if index == 3: if len(word) <= 1: return command.append(word.lower()[1:]) if index >= 4: command.append(word) if len(channel) <= 1: channel = "00-main" if channel[0] != "#": channel = "00-main" path = f"irc/{channel[1:]}.log" with open(os.path.join(settings.baseDir,path), 'a') as f: f.write(datetime.datetime.now().isoformat().split(".")[0] + " " + " ".join(line) + "\n") #print("[user]", user, "[command]", command, "[userid]", userid, "[ismod]", ismod) if command[0] not in ['!ping','!roles','!racecommands','!whitelist','!unwhitelist','!add','!set','!rejoin','!quit','!start','!forcequit','!dq','!noshow', '!revive', '!settime', '!blacklist', '!unblacklist', '!admin', '!debugquit', '!togglestream']: return user = user.lower()[1:] print("[In chat "+channel+"] "+user+":"+str(command)) # global commands if command[0] == "!ping": currentChat.message(channel, "Hi. Bot is alive.") if command[0] == "!racecommands": currentChat.message(channel, "Command list: https://pastebin.com/d7mPZd13") if command[0] == "!roles": if len(command) == 1: statusMsg = users.status(user, playerLookup) else: statusMsg = users.status(command[1], playerLookup) if statusMsg is not None: currentChat.message(channel, statusMsg) # shared commands if (user in users.admins) or (user in users.racersL): if command[0] == "!whitelist" and len(command) == 2: subject = command[1].lower() if subject in users.blacklist: currentChat.message(channel, "Sorry, " + command[1] + " is on the blacklist.") elif subject not in users.updaters: users.add(subject,users.Role.UPDATER) currentChat.message(channel, command[1] + " is now an updater.") else: currentChat.message(channel, command[1] + " is already an updater.") elif command[0] == "!unwhitelist" and len(command) == 2: subject = command[1].lower() if subject in users.updaters: users.remove(subject,users.Role.UPDATER) currentChat.message(channel, command[1] + " is no longer an updater.") else: currentChat.message(channel, command[1] + " is already not an updater.") # racer commands if user in users.racersL: if (command[0] == "!add" or command[0] == "!set") and len(command) == 2: try: number = int(command[1]) if user in playerLookup.keys(): response = "" if command[0] == "!add": response = playerLookup[user].update(playerLookup[user].collects + number) elif command[0] == "!set": response = playerLookup[user].update(number) if response != "": currentChat.message(channel, response) settings.redraw = True except ValueError: pass if (command[0] == "!rejoin"): if playerLookup[user].status == "quit": playerLookup[user].status = "live" currentChat.message(channel, playerLookup[user].nameCaseSensitive +" has rejoined the race.") elif playerLookup[user].status == "done": playerLookup[user].collects -= 1 playerLookup[user].status = "live" currentChat.message(channel, playerLookup[user].nameCaseSensitive +" has rejoined the race.") settings.redraw = True if command[0] == "!quit" and playerLookup[user].status == "live": playerLookup[user].fail("quit") settings.redraw = True currentChat.message(channel, playerLookup[user].nameCaseSensitive + " has quit.") # updater commands if ((user in users.updaters) or (ismod==True) or (user in users.racersL)) and (user not in users.blacklist): if (command[0] == "!add" or command[0] == "!set") and len(command) == 3: player = command[1].lower() try: number = int(command[2]) if player in playerLookup.keys(): response = "" if command[0] == "!add": response = playerLookup[player].update(playerLookup[player].collects + number) elif command[0] == "!set": response = playerLookup[player].update(number) if response != "": currentChat.message(channel, response) settings.redraw = True except ValueError: pass # admin commands if user in users.admins: if command[0] == "!start": newTime = -1 if len(command)==1: newTime = datetime.datetime.now() elif len(command)==2: newTime = command[1] try: newTime = datetime.datetime.fromisoformat(newTime) except ValueError: currentChat.message(channel, "Invalid date format. Must be of this format: 2018-12-29@09:00") else: currentChat.message(channel, "Invalid date format. Must be of this format: 2018-12-29@09:00") if type(newTime) == datetime.datetime: settings.startTime = newTime with open(os.path.join(settings.baseDir,'settings.json'), 'r+') as f: j = json.load(f) j['start-time'] = settings.startTime.isoformat().split(".")[0] f.seek(0) json.dump(j, f, indent=4) f.truncate() currentChat.message(channel, "The race start time has been set to " + settings.startTime.isoformat().split(".")[0]) for player in playerLookup.keys(): playerLookup[player].calculateCompletionTime(settings.startTime) settings.redraw = True elif command[0] == "!forcequit" and len(command) == 2: player = command[1].lower() if player in playerLookup.keys(): if playerLookup[player].status == "live" or playerLookup[player].status == "done": playerLookup[player].fail("quit") settings.redraw = True currentChat.message(channel, command[1] + " has been forcequit.") elif command[0] == "!noshow" and len(command) == 2: player = command[1].lower() if player in playerLookup.keys(): playerLookup[player].fail("noshow") settings.redraw = True currentChat.message(channel, command[1] + " set to No-show.") elif command[0] == "!dq" and len(command) == 2: player = command[1].lower() if player in playerLookup.keys(): if playerLookup[player].status == "live" or playerLookup[player].status == "done": playerLookup[player].fail("disqualified") settings.redraw = True currentChat.message(channel, command[1] + " has been disqualified.") elif command[0] == "!revive" and len(command) == 2: player = command[1].lower() if player in playerLookup.keys(): if playerLookup[player].status == "done": playerLookup[player].collects -= 1 playerLookup[player].status = "live" settings.redraw = True currentChat.message(channel, command[1] + " has been revived.") elif command[0] == "!settime" and len(command) == 3: subject = command[1].lower() if subject in playerLookup.keys(): player = playerLookup[subject] stringTime = command[2] newTime = command[2].split(":") if len(newTime) != 3: currentChat.message(channel, "Invalid time string.") return try: duration = int(newTime[2]) + 60*int(newTime[1]) + 3600*int(newTime[0]) except ValueError: currentChat.message(channel, "Invalid time string.") return if int(newTime[1]) >= 60 or int(newTime[2]) >= 60: currentChat.message(channel, "Invalid time string.") return player.duration = duration player.completionTime = stringTime player.manualDuration(settings.startTime) settings.redraw = True currentChat.message(channel, player.nameCaseSensitive+"'s time has been updated.") elif command[0] == "!blacklist" and len(command) == 2: subject = command[1].lower() if subject not in users.blacklist: users.add(subject,users.Role.BLACKLIST) if subject in users.updaters: users.remove(subject,users.Role.UPDATER) currentChat.message(channel, command[1] + " has been blacklisted.") else: currentChat.message(channel, command[1] + " is already blacklisted.") elif command[0] == "!unblacklist" and len(command) == 2: subject = command[1].lower() if subject in users.blacklist: users.remove(subject,users.Role.BLACKLIST) currentChat.message(channel, command[1] + " is no longer blacklisted.") else: currentChat.message(channel, command[1] + " is already not blacklisted.") elif command[0] == "!admin" and len(command) == 2: subject = command[1].lower() if subject not in users.admins: users.add(subject,users.Role.ADMIN) currentChat.message(channel, command[1] + " is now an admin.") else: currentChat.message(channel, command[1] + " is already an admin.") elif command[0] == "!debugquit": currentChat.message(channel, "Quitting program.") settings.doQuit = True elif command[0] == "!togglestream": #pyautogui.hotkey("ctrl","5") kb = Controller() with kb.pressed(Key.ctrl): kb.tap("5") currentChat.message(channel, "Toggled stream.")
def input_request(mode): """" Запрашивает и результирует данные """ session = connect_db() if mode == 1: """ Пункт меню: добавление пользователя в базу """ # DONE users.add(session, bcolors()) if mode == 2: """ Вывод по заданию """ print(bcolors.OKGREEN + "\n Ищем атлетов - ближайших ровесников пользователя," + "\n а также атлетов одинакового с пользователем роста.\n" + bcolors.ENDC) id = id_ask() res = users.find_id(id, session) if res: print(bcolors.OKGREEN + f"\n Найден пользователь: {res}" + bcolors.ENDC) # Ищем ближайших ровесников ath_str = find_athlete.bday_compare(id, session) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) print(bcolors.OKGREEN + f"\n Самые близкие ровесники - атлеты: \n{ath_str}" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) ath_str = find_athlete.height_compare(id, session, bcolors()) if ath_str != "": print(bcolors.OKGREEN + f" Атлеты с одинаковым ростом:\n" + bcolors.ENDC) # input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) print(bcolors.OKGREEN + f"{ath_str}" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: print(bcolors.FAIL + f"ERROR: Пользователь с ID:{id} не найден" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) if mode == 3: """ Пункт меню: поиск пользователя по ID """ # DONE print(bcolors.OKGREEN + "\n Ищем пользователя по ID:\n" + bcolors.ENDC) id = id_ask() res = users.find_id(id, session) if res: print(bcolors.OKGREEN + f"\n Найден пользователь: {res}" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: print(bcolors.FAIL + f"\nERROR: Пользователь с ID:{id} не найден" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) if mode == 4: """ Поиск атлета по параметрам даты рождения пользователя """ print(bcolors.OKGREEN + "\n Ищем атлета по параметрам даты рождения пользователя:\n" + bcolors.ENDC) id = id_ask() res = users.find_id(id, session) if res: print(bcolors.OKGREEN + f"\n Найден пользователь: {res}" + bcolors.ENDC) # Ищем подходящих атлетов: ath = find_athlete.bday_compare(id, session) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) print(bcolors.OKGREEN + f"\n Самые близкие ровесники: \n{ath}" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: print(bcolors.FAIL + f"\nERROR: Пользователь с ID:{id} не найден" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) if mode == 5: """ Поиск атлета по параметрам роста пользователя """ print(bcolors.OKGREEN + "\n Ищем атлета по параметрам пользователя:\n" + bcolors.ENDC) id = id_ask() res = users.find_id(id, session) if res: print(bcolors.OKGREEN + f"\n Найден пользователь: {res}" + bcolors.ENDC) # Ищем подходящего атлета: ath = find_athlete.height_compare(id, session, bcolors()) if ath != "": input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) print(bcolors.OKGREEN + f"{ath}" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) else: print(bcolors.FAIL + f"\nERROR: Пользователь с ID:{id} не найден" + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) if mode == 6: print(bcolors.OKBLUE + "\n" + task + bcolors.ENDC) input(bcolors.WARNING + "\n [Enter]\n" + bcolors.ENDC) if mode == 7: print(bcolors.WARNING + bcolors.BOLD + "\nХорошего дня!\n" + bcolors.ENDC) sys.exit(0) return 0
while True: rfid_tag_id = wait_for_valid_rfid() user = users.fetch(rfid_tag_id) print("-----------------------------------------------") if not user: print('There is no rfidtag named {rfid}, creating user!'.format(rfid=rfid_tag_id)) print("To verify correct reading please blipp tag again.") if rfid_tag_id == wait_for_valid_rfid(): new_user_nick = input("input your nick: ") if new_user_nick: users.add(new_user_nick, rfid_tag_id) log_action(new_user_nick, 'login') print('You now exist and are logged in! Dont forget to logout!') else: print('Provied nick empty blipp again.') else: print("Tagg not the same as earlier please try again") else: if user['isHere']: users.logout(rfid_tag_id) log_action(user['Nick'], 'logout') user = users.fetch(rfid_tag_id) print('Goodbye {Nick}, your highscore is: {totalTime}'.format( Nick = user['Nick'], totalTime = util.formatTime(user['totalTime'])))