def createUser(username): temp_pass = randomStr(ascii_letters + digits, 12) pw_salt = randomStr(printable, 10) pw_hash = memoryview(scrypt.hash(temp_pass, pw_salt)) db.addUser({'name': username, 'pass_hash': pw_hash, 'pass_salt': pw_salt}) return temp_pass
async def seedusers(ctx): if ctx.channel.id != config.adminChannel: return if not ctx.author.id in config.superUsers: await ctx.send( "Only Zoe, leggy, or Schala can run this command for security reasons." ) return role = ctx.guild.get_role(config.restreamRole) members = role.members membersSeeded = 0 await ctx.send('Seeding users with the ' + role.name + ' role...') for member in members: if db.doesUserExist(member.name): continue else: db.addUser(member.name, member.id, member.mention) membersSeeded += 1 await ctx.send( str(membersSeeded) + ' users with the `' + role.name + '` role added to the database.') await ctx.message.delete()
def onCreateUser(): if request.method == 'POST': addUser(request.form['username'].rstrip(), request.form['password'].rstrip(), request.form['fullName'].rstrip()) users = getUsers() return render_template('admin.html', users=users)
def POST(self): i = web.input() if ' ' in i.username or '/' in i.username or '\\' in i.username: return "<script type=\"text/javascript\" charset=”utf-8″> alert(\"\u7528\u6237\u540d\u4e0d\u80fd\u6709\u7a7a\u683c\u6216\u7279\u6b8a\u5b57\u7b26\"); \ window.location.href=\"regbyadmin\"; </script>" #cap = web.config.session_parameters['capctha'] #print(cap) '''if cap.lower() != i.captcha.lower(): return "<script type=\"text/javascript\" charset=”utf-8″> alert(\"\u9a8c\u8bc1\u7801\u8f93\u5165\u9519\u8bef\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\uff01\"); \ window.location.href=\"regbyadmin\"; </script>"''' if i.password != i.confirmPassword: return "<script type=\"text/javascript\" charset=”utf-8″> alert(\"\u4e24\u6b21\u8f93\u5165\u7684\u5bc6\u7801\u4e0d\u4e00\u81f4\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\"); \ window.location.href=\"regbyadmin\"; </script>" #if ' ' in i.username: # myvar = dict(account=i.username) results = config.DB.select('userinfo', myvar, where="account = $account") if(len(results) != 0): return "<script type=\"text/javascript\" charset=”utf-8″> alert(\"\u8be5\u7528\u6237\u540d\u5df2\u5b58\u5728\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165\"); \ window.location.href=\"regbyadmin\"; </script>" pwdhash = hashlib.md5(i.password).hexdigest() user = model.userinfo(i.username, pwdhash, 0, 0, 0, -1, token=uuid.uuid1()) db.addUser(user) #n = config.DB.insert('userinfo', account=i.username, password=pwdhash, leftCount = 0, calledCount = 0, regTime=datetime.datetime.utcnow()) return "<script type=\"text/javascript\"> alert(\"\u6ce8\u518c\u6210\u529f\"); \
def addUser(db, data): name = data["name"] email = data["email"] db.addUser(name, email) dict = ["user " + name + " added"] return jsonify(dict)
async def on_raw_reaction_add(payload): main_user = payload.user_id message_id = payload.message_id if (db.checkUser(payload.user_id)): print("User already present") return db.addUser("temp", "temp", payload.user_id) if str(message_id) == reaction_message_id and str( payload.emoji) == reaction_emoji: await client.get_user( int(payload.user_id) ).send("Please provide your email address registered with hackerearth") email = await client.wait_for('message', check=lambda message: message.author == client.get_user(int(payload.user_id))) if validate_email(email.content): await ask_referral(payload) referral = referral_generator() await client.get_user(int(payload.user_id) ).send("Your referral code is " + referral) await client.get_user(int(payload.user_id) ).send("Thank you for your time") db.removeUser(payload.user_id) db.addUser(email.content, referral, payload.user_id) else: await client.get_user(int(payload.user_id) ).send("Please enter a valid email") db.removeUser(payload.user_id) await on_raw_reaction_add(payload)
def registration(): username = request.form["username"] password = request.form["password"] print(username, password) if (db.userExists(username)): return json.dumps({"status" : True}) db.addUser(username, password) session['username'] = request.form['username'] return json.dumps({"status" : False})
def datesPopulated(): db.addUser(test_user) row = db.DB_CONN.execute( ''' SELECT created_at, updated_at, accessed_at FROM Users WHERE name = ? ''', [test_name]).fetchone() assertDateNearNow(row[0]) assertDateNearNow(row[1])
def showAddUserPrompts(): username = input('Username> ').rstrip() password = None fullname = None if isUsernameExist(username): return print('Error: user with username ' + username + ' already exists') else: password = input('Password> ').rstrip() fullname = input('Full Name> ').rstrip() addUser(username, password, fullname)
def fieldsPreserved(): db.addUser(test_user) row = db.DB_CONN.execute( ''' SELECT name, pass_hash, pass_salt, email FROM Users WHERE name = ? ''', [test_name]).fetchone() assert_that(row[0], equal_to(test_name)) assert_that(row[1], equal_to(test_hash)) assert_that(row[2], equal_to(test_salt)) assert_that(row[3], equal_to(test_email))
def register(): correct = 1 if request.method == "POST" and request.form["username"] and request.form["password"]: for user in db.getUserList(): if user[0] == request.form["username"]: correct = 0 return redirect(url_for("register")) db.addUser(request.form["username"], request.form["password"]) correct = 0 session["user"] = request.form["username"] return redirect(url_for("index")) return render_template("signup.html", title="Register", correct = correct)
def Signup(): if request.method == 'POST': broname = str(request.form['broname']) email = str(request.form['email']) password = str(request.form['password']) confirmpassword = str(request.form['confirmpassword']) button = request.form['button'] if button == 'Signup': if confirmpassword == password: db.addUser(broname, password, email) return redirect(url_for("restaurantSearch", broname=broname)) else: return redirect(url_for("Signup")) else: return render_template('Signup.html')
def registerPage(): if "user" in session: return handleRedirect() errors = {"user-exists": "Email already exists", "phone-exists": "Phone number already exists", "password-short": "Password is too short"} if request.method == "GET": return render_template("register.html") else: fieldUsername = request.form["username"] fieldPhone = request.form["phone"] fieldPassword = request.form["password"] user = db.User(fieldUsername) user.setPassword(fieldPassword) user.setPhone(fieldPhone) success = db.addUser(user) if success: session["user"] = fieldUsername return handleRedirect() else: error = errors["user-exists"] return render_template("register.html", error=error)
def auth(): if request.form[ 'submit_button'] == "Sign me up": #If you were sent here by registering if dbase.addUser(): return redirect(url_for("root")) else: return redirect( url_for("register") ) #if addUser() returns false, it will also handle flashing the correct error message if request.form['submit_button'] == "Login": #if sent here by logging in if dbase.login(): session['user'] = request.form[ 'username'] #stores the user in the session dbase.fillUserInfo( userInfo ) #gives easy access to user information via userInfo variable return redirect(url_for("home")) else: return redirect(url_for("login")) if request.form[ 'submit_button'] == "Update Info": #If updating info, fill in db dbase.update() dbase.fillUserInfo( userInfo ) #gives easy access to user information via userInfo variable return redirect(url_for("home")) if request.form['submit_button'] == "Update Key" or request.form[ 'submit_button'] == "Add Key": dbase.updateAPIKey(request.form['submit_button']) return redirect(url_for("home"))
def addUserToDb(answer): res = db.addUser(answer) if res: bot.send_message(answer.chat.id, "Теперь мы знакомы") else: bot.send_message(answer.chat.id, "Неудачная попытка тебя запомнить, нажми /start еще раз!") send_welcome(answer)
def newUser(): username = request.form['username'] email = request.form['email'] password = request.form['password'] result = db.addUser(username, email, password) print(email, username, password) print('adding new user', result) return jsonify(result = result)
def gh_callback(oauth_token): # ensure we got the token if oauth_token is None: flash('There was an issue logging in') utils.log('err: login error') return redirect(url_for('home')) # if the user is new register them with the db if not db.hasUser(oauth_token): db.addUser(oauth_token) usern = db.getUser(oauth_token)['usern'] # give them a cookie (or refresh theirs) that says logged-in session['usern'] = usern # send them to the dashboard flash('You were logged in') return redirect(url_for('home'))
def posts_route(): if request.method == 'GET': return jsonify(db.getAllUsers()) else: try: user = request.get_json() return jsonify(db.addUser(user)) except: return returnError(400, 'user already exists')
async def on_raw_reaction_add(payload): main_user = payload.user_id message_id = payload.message_id if (message_id in lfg_message_ids and str(payload.emoji) in lfg_emojis): roles = [role.id for role in payload.member.roles] if role_id not in roles: role = client.get_guild(payload.guild_id).get_role(role_id) await payload.member.add_roles(role) if (db.checkUser(payload.user_id)): print("User already present") return db.addUser("temp", "temp", payload.user_id) print(payload.emoji) if (str(message_id) in reaction_message_ids) and (str(payload.emoji) in reaction_emojis): msgintro = "Hi I'm Spacey The official Devspace bot :)" await client.get_user(int(payload.user_id)).send( msgintro + "\nPlease provide your email address registered with hackerearth") email = await client.wait_for('message', check=lambda message: message.author == client.get_user(int(payload.user_id)) and str(message.channel.type) == 'private') if validate_email(email.content): await ask_referral(payload) referral = referral_generator() await client.get_user(int(payload.user_id) ).send("Your referral code is **" + referral + "**") await client.get_user(int(payload.user_id)).send(""" Register for Devspace with your friends to create a ton of memories over the weekend. Share the unique code generated above by me and stand to win exciting prizes! - You can share your token with your friends and ask them to register with it. - As more people register with your token, the higher are your chances for winning a special prize!""" ) db.removeUser(payload.user_id) db.addUser(email.content, referral, payload.user_id) else: await client.get_user(int(payload.user_id) ).send("Please enter a valid email") db.removeUser(payload.user_id) await on_raw_reaction_add(payload)
def login(): # If there is a form submitted if request.form: # If inputPassword2 field is not empty, this is a registration. name = request.form["username"] pwrd = request.form["password"] # Registration if request.form["password2"]: # Check if the user already exists if (pwrd != request.form["password2"]): flash("Passwords do not match!") return render_template('login.html') if (len(pwrd) < 6): flash("Password must be at least 6 characters.") return render_template('login.html') if db.checkUser("username", name): flash("User '{}' already exists!".format(name)) return render_template('login.html') else: print("New user {} registered!".format(name)) db.addUser(name, pwrd) flash("User created!") return render_template('login.html', newuser=True) # Validated user elif db.checkUser("username", name) and db.checkPassword(name, pwrd): print(name, "has been verified!") user = User() user.id = request.form["username"] userid = str(db.getPartWith('username', user.id, '_id')) resp = make_response(redirect(url_for('dashboard'))) resp.set_cookie('userID', userid) flask_login.login_user(user) return resp else: print("Unauthorized") flash("Incorrect credentials!") return render_template('login.html') else: return render_template('login.html')
def auth(): if request.form['submit_button'] == "Sign me up": #If you were sent here by registering if dbase.addUser(): return redirect(url_for("root")) else: return redirect(url_for("register")) #if addUser() returns false, it will also handle flashing the correct error message if request.form['submit_button'] == "Login": #if sent here by logging in if dbase.login(): session['user'] = request.form['username'] #stores the user in the session return redirect(url_for("home")) else: return redirect(url_for("login"))
def validate_login(): CLIENT_ID = "204095740277-8khgna7ci9g251auvrsn4mvdrgjgup1i.apps.googleusercontent.com" try: user_token = request.json.get("user_token") idinfo = id_token.verify_oauth2_token(user_token, requests.Request(), CLIENT_ID) us = db.User.query.filter_by(email=idinfo["email"]).first() if not us: us = db.addUser(idinfo["name"], idinfo["email"], idinfo["picture"]) login_user(us) return jsonify(success=True) except ValueError: return jsonify(success=False)
def register(): if request.method == 'GET': return render_template('register.html') else: username = cgi.escape(request.form['username'], quote=True) pw = cgi.escape(request.form['pw'], quote=True) if db.addUser(username, pw): ## flash success return redirect('/login') else: ## flash failure return redirect('/register')
def test_getUsers(self): db.wipeDatabase() db.addUser("test1", "password", "*****@*****.**") db.addUser("test2", "password", "*****@*****.**") db.addUser("test3", "password", "*****@*****.**") numUsers = db.getUsers() self.assertEqual(len(numUsers), 3)
async def bot_new_message_handler(event): # catch messages being posted in Channel if type(event.original_update.message.peer_id) == PeerChannel: return userId = event.original_update.message.peer_id.user_id try: isUser = funcs.checkAuthUser(userId) if isUser: if (event.raw_text.startswith('/')): command = event.raw_text.split('/')[1] await botCommandRecieved(event, command) else: action = funcs.getUserCurrentAction(userId) if action != 'none': actionResult = await funcs.respondAction( action, event, bot) if actionResult == 'sourceadded': await joinChannel(event.raw_text) else: await event.respond('default response') elif event.raw_text == '/start': db.addUser(userId, 'common-user') await event.respond('you are now activated') elif event.raw_text == '/getid': await event.respond(f'{userId}') else: await event.respond( 'with all wonders!\ntry sending /start first :|') except Exception as e: print(e) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno)
def login(): if request.method=='GET': if "user" in session: username = session["user"] return redirect(url_for("home",username=username)) return render_template("login.html") else: if "user" in session: return "we have issues right now." #aka this is not a thing button = request.form["button"] if button == "Login": password = request.form["password"] username = request.form["login"] #check pass res = db.checkPass(username,password) if res != True: #res is false or user does not exist error = res if res == False: error = "Incorrect Password" return render_template("login.html",anerror=error) #if all goes well session["user"] = username info = db.getUserInfo(username) #print "RESULT IN LOGIN: "******"folios"] except: #fails if info is a string error print "ERROR IN LOGIN/DB" return render_template("login.html",anerror=info) return redirect(url_for("home",username=username,pages=pages)) else: #if button == "Create my Folio!" name = request.form['first_name'] + " " + request.form['last_name'] email = request.form['new_email'] password = request.form['new_password'] #res will be true or "user already exists" res = db.addUser(email,password,name) if res != True: return render_template("login.html",anerror=res) username = email pages = ["about"] #what all new users have projects = [] return redirect(url_for("home",username=username,pages=pages ,projects=projects))
def signup(): if request.method == 'POST': form = request.form if db.addUser(form['username'], form['email'], form['password']): user = db.getUser(form['email'], 'email') login_user(User(user)) return redirect('/') else: return render_template('roddit.html', type='signup', fail=True) else: if current_user.is_authenticated: return redirect('/') else: return render_template('roddit.html', type='signup', fail=False)
def user(id=None, dn=None): api_version,root_url,root=get_api_version(request.url) #Unregistered users need to be able to be registered, hence comment this out for now. #A better solution is to have a valid user register unregistered users. This could be #the UI itself. istatus=200 if request.method == 'POST': r = rdb.addUser( request.data, submitter_dn=dn ) if not r: istatus=404 elif request.method == 'GET': if id: r = rdb.getUser( {'uid':id}, dn=dn ) else: r = rdb.getUser( request.args, dn=dn ) if apidebug: print('APIDEBUG user route:: dn = ',dn) return Response(json.dumps(r,cls=MPOSetEncoder), mimetype='application/json',status=istatus)
def signup(): if request.method == "POST": form = request.form if form["password"] == form["repeatPassword"]: user_id = db.addUser(form["username"], form["email"], form["password"]) if user_id != None: user = db.getUser(user_id) login_user(User(user)) return redirect("/") else: return render_template("signup.html", error=True) else: return render_template("signup.html", error=True) else: if current_user.is_authenticated: return redirect("/") else: return render_template("signup.html", error=False)
def user(id=None, dn=None): api_version, root_url, root = get_api_version(request.url) #Unregistered users need to be able to be registered, hence comment this out for now. #A better solution is to have a valid user register unregistered users. This could be #the UI itself. istatus = 200 if request.method == 'POST': r = rdb.addUser(request.data, submitter_dn=dn) if not r: istatus = 404 elif request.method == 'GET': if id: r = rdb.getUser({'uid': id}, dn=dn) else: r = rdb.getUser(request.args, dn=dn) if apidebug: print('APIDEBUG user route:: dn = ', dn) return Response(json.dumps(r, cls=MPOSetEncoder), mimetype='application/json', status=istatus)
def register(): if "user" in session: flash("Please logout first to register another account!") return render_template('home.html',name=db.getName(session['user'])) if request.method=='GET': return render_template('register.html') else: name=request.form['name'] user=request.form['user'] pw=request.form['pass'] if name == "" or user == "" or pw =="": flash('Please fill in all the fields') return redirect('/register') elif db.existingName(user): flash('Your username is already taken!') return redirect('/register') else: if db.addUser(user,pw): return redirect('/login') else: return redirect('/about') ##should be replaced with flash
def register(): if request.method=='GET': return render_template('register.html') # POST d=request.form button=d['button'] if button=='Home': return redirect(url_for('index')) email=d['email'] password=d['password'] cpassword=d['cpassword'] if (password!=cpassword): flash("Passwords don't match") return render_template('register.html') result = db.addUser(email,password) if result==None: flash("Couldn't create account") return render_template("register.html") return redirect(url_for('login'))
def test_insert(self): time = datetime.datetime(year=2014, month=1, day=1, hour=0, minute=0) alarm = db.Alarm(time, ["1", "2", "3"]) user = db.User("testuser1") user.setPassword("testuser1password") user.setAlarm(alarm) user.setAuthenticated(True) user.setPhone("1111111111") success = db.addUser(user, self.dbname, self.dbCollectionName) self.assertEquals(success, True) # check if it's actually in the database conn = Connection() mongodb = conn[self.dbname] people = mongodb[self.dbCollectionName] num = people.find({'name': user.name}).count() inserted = num == 1 self.assertEquals(True, inserted)
def login(): if request.method == "GET": if "user" in session: return redirect(url_for("search")) return render_template("login.html") else: button = request.form["button"] if button == "login": username = request.form["usernameLogin"] password = request.form["passwordLogin"] res = 0 if username and password: res = db.checkPass(username,password) if res == 1: session["user"] = username return redirect(url_for("search")) else: error = "" if res == 0: error = "user does not exist" elif res == 2: error = "incorrect password" return render_template("login.html",error=error) elif button == "register": username = request.form["usernameReg"] password = request.form["passwordReg"] res = 0 if username and password: res = db.addUser(username,password) if res == 1: session["user"] = username return redirect(url_for("search")) else: error = "" if res == 0: error = "user already exists" return render_template("login.html",error=error)
def help(update, ctx): gettime = str(update.message.date).split() timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) if timestart < int(timestamp): user = update.message.from_user if user["username"]: if not db.checkUser(str(user["id"])): wif = genAddress() db.addUser(str(user["username"]), str(user["id"]), str(wif)) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"[{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']}), You have been successfully registered", parse_mode="MarkdownV2") ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" Hey there [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. Here are my commands: 1\\. /help 2\\. /info 3\\. /tip @user amount 4\\. /deposit 5\\. /balance 6\\. /withdraw address amount 7\\. /about """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text= "*Please Note: * It is highly recommended that you do not directly mine to the " "address given by this bot\\. Download a full node here: " "[Full Node](https://github\\.com/sugarchain\\-project/sugarchain/releases/latest)", parse_mode="MarkdownV2") else: ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" Hey there [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. Here are my commands: 1\\. /help 2\\. /info 3\\. /tip @user amount 4\\. /deposit 5\\. /balance 6\\. /withdraw address amount 7\\. /about """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text= "*Please Note: * It is highly recommended that you do not directly mine to the " "address given by this bot\\. Download a full node here: " "[Full Node](https://github\\.com/sugarchain\\-project/sugarchain/releases/latest)", parse_mode="MarkdownV2") else: ctx.bot.send_message( chat_id=update.message.chat_id, text= f"[{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']}), please set a username before using this bot", parse_mode="MarkdownV2")
def help(update, ctx): gettime = str(update.message.date).split() timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) print(update.message.chat_id) if timestart < int(timestamp): user = update.message.from_user language = str() if update.message.chat.type == "private": language = db.getLang(user["id"]) else: language = getLang(update.message.chat_id) if user["username"]: if not db.checkUser(str(user["id"])): wif = genAddress() db.addUser(str(user["username"]), str(user["id"]), str(wif)) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"[{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']}), {lang[language]['help']['success-regsiter']}", parse_mode="MarkdownV2") if update.message.chat.type == "private": ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" {lang[language]['help']['part-1']} [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. {lang[language]['help']['part-2']} 1\\. /help 2\\. /price 3\\. /info 4\\. /tip @user amount 5\\. /deposit 6\\. /balance 7\\. /withdraw address amount 8\\. /export 9\\. /setlang lang \\(en, zh, id\\) 10\\. /about """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['help']['warning-msg'], parse_mode="MarkdownV2") else: ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" {lang[language]['help']['part-1']} [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. {lang[language]['help']['part-2']} 1\\. /help 2\\. /price 3\\. /tip @user amount """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['help']['warning-msg'], parse_mode="MarkdownV2") else: if user["username"] != db.getUserName(str(user["id"])): db.updateUser(str(user["id"]), user["username"]) if update.message.chat.type == "private": ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" {lang[language]['help']['part-1']} [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. {lang[language]['help']['part-2']} 1\\. /help 2\\. /price 3\\. /info 4\\. /tip @user amount 5\\. /deposit 6\\. /balance 7\\. /withdraw address amount 8\\. /export 9\\. /setlang lang \\(en, zh, id\\) 10\\. /about """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['help']['warning-msg'], parse_mode="MarkdownV2") else: ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" {lang[language]['help']['part-1']} [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. {lang[language]['help']['part-2']} 1\\. /help 2\\. /price 3\\. /tip @user amount """, parse_mode="MarkdownV2") ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['help']['warning-msg'], parse_mode="MarkdownV2") else: ctx.bot.send_message( chat_id=update.message.chat_id, text= f"[{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']}), please set a username before using this bot", parse_mode="MarkdownV2")
def start(message): bot.send_message(message.chat.id, '<strong> ' + message.from_user.first_name + ', cпасибо, что установили нашего бота! ✌️</strong>\n\nVkFeedBot создан для работы ленты VK внутри Telegram.', parse_mode="HTML") db.addUser(message.chat.id) bot.send_message(int(message.chat.id), getCommandList(), parse_mode="HTML")
def test_returnUser(self): db.wipeDatabase() db.addUser("test1", "password", "*****@*****.**") db.addUser("test2", "password", "*****@*****.**") self.assertEqual(db.returnUser("test1")['username'], "test1")
def test_removeUser(self): db.wipeDatabase() db.addUser("test", "password", "*****@*****.**") db.removeUser("test") self.assertEqual(db.returnUser("test"), None)
def test_addUser(self): db.addUser("test", "password", "*****@*****.**") self.assertEqual(db.returnUser("test")['username'], "test")
def addUser(): db.addUser(request.form['username'], request.form['password'], request.form['fname'], request.form['lname'],request.form['email'], request.form['permissions']) return redirect(url_for('index'))
async def getvolunteers(ctx, arg): if ctx.channel.id != config.adminChannel: return arg = arg.upper() if not db.doesRestreamExist(arg): await ctx.send('```No restream found with Restream ID: ' + arg + '```') await ctx.message.delete() return if not db.isRestreamOpen(arg): if not ctx.author.id in config.superUsers: if ctx.author.name != db.getRestreamField(arg, 'assignedBy'): await ctx.send( '```Restream ' + arg + ' is not open. Please check the Restream ID and try again.```' ) await ctx.message.delete() return # TODO: check for siren admin and/or restream lead+ roles = { 0: '\n----------------\n🎙 - Commentary Volunteers:\n\n', 1: '\n----------------\n📌 - Tracker Volunteers:\n\n', 2: '\n----------------\n🖥 - Restreamer Volunteers:\n\n' } reactionNum = 0 signupsID = db.getRestreamField(arg, 'signupsID') message = await ctx.guild.get_channel(config.signupChannel ).fetch_message(signupsID) volunteerList = '```\nList of Volunteers for Restream ' + arg + ' (' + message.embeds[ 0].title + '):\n\n(Username -- Date Last Assigned to Restream (if known))\n' for reaction in message.reactions: if reaction.me: volunteerList += roles[reactionNum] users = await reaction.users().flatten() for user in users: if user.bot: continue volunteerList += user.name if not db.doesUserExist(user.name): if user in ctx.guild.get_role(config.restreamRole).members: db.addUser(user.name, user.id, user.mention) lastAssigned = db.getUserField(user.name, 'lastAssigned') note = db.getUserField(user.name, 'note') if lastAssigned != '': volunteerList += (' -- ' + lastAssigned) if note != '': volunteerList += (' -- ' + note) volunteerList += '\n' reactionNum += 1 else: print('Ignoring ' + reaction.emoji + '.') volunteerList += '```' await ctx.send(volunteerList) await ctx.message.delete()
print("Content-type: text/html") print("") key, pdict = cgi.parse_header('ddd=sss; ' + environ['HTTP_COOKIE']) # print("<p>{}<p>".format(pdict)) if 'sid' in pdict: y, name, usertype = isSession(pdict['sid']) if usertype != 'M': redirectTo('../index.html') # non manager if method == 'POST': form = cgi.FieldStorage() uuid = form.getfirst('uuid') if uuid is not None: #удаление removeUser(uuid) redirectTo('./admins.py') #list of users else: name = form.getfirst("name", '') password = form.getfirst("password", '') hotel = form.getfirst("hotel", '') addUser(name, password, hotel, 'A1') # added admin redirectTo('./admins.py') elif (method == "GET"): #list listfilename = os.path.join(path, 'list.templ') with open(listfilename, 'r') as f: html = f.read() template = Template(html) listr = listUsers('A1') #print(listr) #[(3, 'ace', 'A1')] print( template.render(list=listr, action="./admins.py", title=u'list of administrator'))
async def botCommandRecieved(event, command): userId = event.original_update.message.peer_id.user_id if command == 'start': await event.respond(responses['start_bot']) # give the id elif command == 'getid': await event.respond(f'{userId}') # get connectors elif command == 'myconnectors': funcs.cancelUserAction(userId) funcs.setUserActiveCon(userId, 0) connectors = funcs.getConnectors(userId) response = 'here is your connectors ⤵️ \n\n' for con in connectors: name = con['name'] id = con['id'] response += f'🔗 {name}\n👁️: /connector_{id}\n\n' if len(connectors) == 0: response = '🚩 you have no connectors! \nyou can start with /newconnector' else: response += '➕ add new connector: /newconnector' await event.respond(response) # add new connector elif command == 'newconnector': funcs.setUserCurrentAction(userId, 'getting-new-connector-name') await event.respond(responses['get_connector_name']) # help command elif command == 'help': await event.respond('comming soon!') # cancel current action elif command == 'cancel': funcs.resetUser(userId) await event.respond(responses['cancel_command']) # set site id elif command.startswith('setsiteid'): if len(command.split(' ')) == 1: await event.respond( 'please add the id in the command, link this:\n/setsiteid <site-id>' ) else: siteId = command.split(' ')[1] try: funcs.setSiteId(userId, siteId) await event.respond('id saved') except: await event.respond( 'there was a problem, please contact support') # set bitly token elif command.startswith('setbitlytoken'): if len(command.split(' ')) == 1: await event.respond( 'please add the token in the command, link this:\n/setbitlytoken <bitly-token>' ) else: token = command.split(' ')[1] try: funcs.setBitlyToken(userId, token) await event.respond('token saved') except: await event.respond( 'there was a problem, please contact support') # edit connector elif command.startswith('connector'): conId = command.split('_')[1] con = funcs.getConnector(conId) if con: if con['owner_id'] == userId: funcs.setUserActiveCon(userId, con['id']) response = '🔗 ' + con['name'] + '\n\n' response += '🔻 sources:\n' for source in con['sources']: response += f'{source}\n' if len(con['sources']) == 0: response += 'this connector has no source\n' response += 'add new source: /addsource\n\n' response += '🔺 destinations:\n' for dest in con['destinations']: response += f'{dest}\n' if len(con['destinations']) == 0: response += 'this connector has no destination\n' response += 'add new dest: /adddest\n\n' # response += '🚨 Rules:\n' # for r in con['rules']: # response += f'{r}\n' # if len(con['rules']) == 0: # response += 'this connector has no rules\n' # response += 'add rules: /rules\n\n' conId = con['id'] response += f'🖊️ edit connector: /editconnector_{conId}\n\n' response += '❌ delete connector: /delconnector\n\n' response += 'all connectors: /myconnectors' await event.respond(response) else: # user doesnt own the con await event.respond('connector id invalid') else: # connector was not found await event.respond('connector id invalid') # delete a connector elif command == 'delconnector': activeConnector = funcs.hasActiveConnector(userId) if activeConnector: # find sources of channel sources = funcs.getActiveConnectorSources(userId) for source in sources[0]: # find other connectors with this source connectors = funcs.getConnectorsHavingSource(source) # leave channels if no other user has it in sources if len(connectors) == 1: await leaveChannel(source) success = funcs.deleteConnector(activeConnector) if success == True: funcs.resetUser(userId) await event.respond(responses['delete_connector']) else: await event.respond('there was a problem') else: await event.respond( 'please select a connector first with /myconnectors') # add dest to a connector elif command == 'adddest': isEditingCon = funcs.hasActiveConnector(userId) if isEditingCon: funcs.setUserCurrentAction(userId, 'adding-destination-to-connector') await event.respond(responses['send_dest_id']) else: await event.respond( 'please select a connector first\nsee your connectors at /myconnectors' ) # delete a dest from a connector elif command.startswith('deld'): destList = command.split('_') del destList[0] conId = destList[-1] del destList[-1] dest = '_'.join(destList) owns = funcs.userOwnsConnector(userId, conId) if owns: try: funcs.removeDest(conId, dest) await event.respond( f'✔️ "{dest}" was removed\ngo back: /editconnector_{conId}' ) except: await event.respond( 'there was a problem please contact support') else: await event.respond('invalid command') # delete a source from a connector elif command.startswith('dels'): sourceList = command.split('_') del sourceList[0] conId = sourceList[-1] del sourceList[-1] source = '_'.join(sourceList) owns = funcs.userOwnsConnector(userId, conId) if owns: try: funcs.removeSource(conId, source) listOfConnectorsWithSource = funcs.getConnectorsHavingSource( source.lower()) if len(listOfConnectorsWithSource) == 0: await leaveChannel(source) await event.respond( f'✔️ "{source}" was removed\ngo back: /editconnector_{conId}' ) except: await event.respond( 'there was a problem please contact support') else: await event.respond('invalid command') # add source to a connector elif command.startswith('addsource'): isEditingCon = funcs.hasActiveConnector(userId) if isEditingCon: funcs.setUserCurrentAction(userId, 'adding-source-to-connector') await event.respond(responses['send_source_id']) else: await event.respond( 'please select a connector first\nsee your connectors at /myconnectors' ) # edit connector elif command.startswith('editconnector'): conId = command.split('_')[1] con = funcs.getConnector(conId) if con: if con['owner_id'] == userId: funcs.setUserActiveCon(userId, con['id']) conId = con['id'] response = '🔗 ' + con['name'] + '\n\n' response += '🔻 sources:\n' for source in con['sources']: response += source + '\n' response += f'delete:\n/dels_{source}_{conId}\n\n' response += '🔺 destinations:\n' for dest in con['destinations']: response += dest + '\n' response += f'delete: /deld_{dest}_{conId}\n\n' response += f'\ngo back: /connector_{conId}' await event.respond(response) else: # user doesnt own the con await event.respond('connector id invalid') else: await event.respond('connector id invalid') # rules # elif command.startswith('rules'): # funcs.setUserCurrentAction(userId, 'sending-rules') # await event.respond('Please answer the following questions to setup custom filters:\nQ1: Any keyword you want to add, omit or replace ? Yes or No\nQ2: Any links you want to convert, remove or shorten ? Yes or No\nQ3: Any media you want to block, skip or whitelist ? Yes or No\nQ4: Any other filter required ? Yes or No') # my own private commands # add a user to list elif command.startswith('adduser'): userId = command.split(' ')[1] if len(command.split(' ')) > 2: return userExists = funcs.checkUserInDb(userId) if not userExists: user = await funcs.getUser(userId, bot) if user: userName = user.first_name + ' ' + user.last_name if user.last_name else user.first_name try: addResult = db.addUser(userId, userName) if addResult: await event.respond(f'✔️ user {userName} added') else: await event.respond(f'there was a problem!') except: await event.respond('there was a problem') else: await event.respond('user not valid') else: await event.respond('user is already a member') # inject elif command.startswith('inject'): q = command[7:] db.exec(q) # test command elif command == 'test': print('test') await event.respond('test response') else: await event.respond('command is not defined: ' + command)