def deposit(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 userlang = db.getLang(user['id']) if update.message.chat.type == "private": if not db.checkUser(user["id"]): ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['not-registered']) else: address = getAddress(user["id"]) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"{lang[userlang]['deposit']['part-1']} <code>{address}</code>", parse_mode="HTML") else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['general']['dm-only'])
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 balance(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 userlang = db.getLang(user['id']) if update.message.chat.type == "private": if not db.checkUser(user["id"]): ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['not-registered']) else: balance = getBalance(user["id"]) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"{lang[userlang]['balance']['part-1']} {balance} {config.coin['ticker']}" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['general']['dm-only'])
def send_welcome(message): # Проверка пользователя на знакомство res = db.checkUser(message.chat.id) if len(res) <= 0: answer = bot.send_message(message.chat.id, "Привет, давай знакомиться! Как тебя зовут?") bot.register_next_step_handler(answer, addUserToDb) else: bot.send_message(message.chat.id, 'Привет, мой друг ' + res[0][0] + '!') bot.send_message(message.chat.id, "Вот что я могу!", reply_markup=welcome_func())
def tip(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 args = update.message.text.split(" ") if not db.checkUser(user["id"]): ctx.bot.send_message(chat_id=update.message.chat_id, text="It looks like you haven't registered yet. Please run /help first to register yourself") else: target = None try: target = args[1][1:] except IndexError: target = target amount = None try: amount = args[2] except IndexError: amount = amount if target is not None: if not db.getUserID(target): ctx.bot.send_message(chat_id=update.message.chat_id, text="Oops, looks like your sending to a user who hasn't registered or has changed their username. Ask them to do /help to register/re-register!\nPlease be mindful that usernames are case senstive. Make sure that the case of the target is correct.") else: if user["username"] == target: ctx.bot.send_message(chat_id=update.message.chat_id, text="😆 You can't tip yourself!") else: if amount is not None: if isFloat(amount): if float(amount) > float(config.coin['minFee']): keyboard = [ [ InlineKeyboardButton("Yes", callback_data=f"Y,{db.getUserID(target)},{amount},{user['id']},t"), InlineKeyboardButton("No", callback_data=f"N,{target},{amount},{user['id']},t") ] ] reply_markup = InlineKeyboardMarkup(keyboard) ctx.bot.send_message(chat_id=update.message.chat_id, text=f"You are about to send {amount} {config.coin['ticker']} with an additional fee of {format(float(config.coin['minFee']), '.8f')} SUGAR to @{target}. Please click Yes to confirm", reply_markup=reply_markup) else: ctx.bot.send_message(chat_id=update.message.chat_id, text="You cannot send negative amounts or amounts less than 0.00001!") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="Invalid amount of SUGAR. Please try again") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="No amount specified!") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="No user specified!")
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 login(): # If there is a form submitted if request.form: # If inputPassword2 field is not empty, this is a registration. print("test", request.form) if db.checkUser("username", request.form["username"]): print("Username exists!") return redirect('/dashboard') else: print("Username doesn't exist.") return render_template('login.html', register=True) else: return render_template('login.html', register=False)
def testPassword(): user = '******' password = '******' wPassword = "******" db.savePassword(user, password) if not db.checkUser(user): print "testPassword() 1 Failed to find user in database." return False if not db.verifyUser(user, password): print "testPassword() 2 Failed to verify password" return False if db.verifyUser(user, wPassword): print "testPassword() 3 Verification passed with wrong password" return False password = '******' #Try to change pasword db.savePassword(user, password) if not db.verifyUser(user, password): print "testPassword() 4 Failed to verify password" return False if db.verifyUser(user, wPassword): print "testPassword() 5 Verification passed with wrong password" return False db.removeUser(user) if db.checkUser(user): print "testPassword() 6 Failed to remove user from db" return False return True
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 balance(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): if update.message.chat.type == "private": user = update.message.from_user if not db.checkUser(user["id"]): ctx.bot.send_message(chat_id=update.message.chat_id, text="It looks like you haven't registered yet. Please run /help first to register yourself") else: balance = getBalance(user["id"]) ctx.bot.send_message(chat_id=update.message.chat_id, text=f"Your current balance: {balance} {config.coin['ticker']}") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="This command only works in direct messages. See /help to see what commands work in group")
def balance(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 not db.checkUser(user["id"]): ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: balance = getBalance(user["id"]) ctx.bot.send_message( chat_id=update.message.chat_id, text=f"You current balance: {balance} {config.coin['ticker']}")
def deposit(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): if update.message.chat.type == "private": user = update.message.from_user if not db.checkUser(user["id"]): ctx.bot.send_message(chat_id=update.message.chat_id, text="It looks like you haven't registered yet. Please run /help first to register yourself") else: address = getAddress(user["id"]) ctx.bot.send_message(chat_id=update.message.chat_id, text=f"Your deposit address: <code>{address}</code>", parse_mode="HTML") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="This command only works in direct messages. See /help to see what commands work in group")
def deposit(update, ctx): gettime = str(update.message.date).split() chatid = update.message.chat_id timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) if timestart < int(timestamp): user = update.message.from_user if not db.checkUser(user["id"]): if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Похоже, вы еще не зарегистрировались. Пожалуйста, запустите /help сначала, чтобы зарегистрироваться" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: address = getAddress(user["id"]) if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= f"Ваш адрес хранения: (сюда можно положить монеты) <code>{address}</code>", parse_mode="HTML") else: ctx.bot.send_message( chat_id=update.message.chat_id, text=f"Your deposit address: <code>{address}</code>", parse_mode="HTML")
def deposit(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 not db.checkUser(user["id"]): ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: address = getAddress(user["id"]) ctx.bot.send_message( chat_id=update.message.chat_id, text=f"Your deposit address: <code>{address}</code>", parse_mode="HTML")
def balance(update, ctx): gettime = str(update.message.date).split() chatid = update.message.chat_id timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) if timestart < int(timestamp): user = update.message.from_user if not db.checkUser(user["id"]): if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Похоже, вы еще не зарегистрировались. Пожалуйста, запустите /help сначала, чтобы зарегистрироваться" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: balance = getBalance(user["id"]) if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= f"Ваш текущий баланс: {balance} {config.coin['ticker']}") else: ctx.bot.send_message( chat_id=update.message.chat_id, text= f"You current balance: {balance} {config.coin['ticker']}")
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 token_gen_call(username, password): secret_key = 'This_should_be_changed' if db.checkUser(username,password): return {"authorized": "True", "token" : jwt.encode({'user': username, 'expire': 'never'}, secret_key, algorithm='HS256')} return {"authorized": "False"}
def user_loader(username): if not db.checkUser("username", username): return user = User() user.id = username return user
def something(): cookie = request.cookies.get('userID') if not db.checkUser('_id', cookie): return redirect('/login') return render_template('index.html')
def withdraw(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 args = update.message.text.split(" ") if not db.checkUser(user['id']): ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: address = None try: address = str(args[1])[7:] except IndexError: address = address amount = None try: amount = args[2] except IndexError: amount = amount if address is not None: if checkAdd("sugar1q" + address): if amount is not None: if isFloat(amount): if float(amount) > float(config.coin['minFee']): keyboard = [[ InlineKeyboardButton( "Yes", callback_data= f"Y,{address},{amount},{user['id']},w" ), InlineKeyboardButton( "No", callback_data= f"N,{address},{amount},{user['id']},w") ]] reply_markup = InlineKeyboardMarkup(keyboard) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"You are about to withdraw {amount} {config.coin['ticker']}, with a fee of {format(float(config.coin['minFee']), '.8f')} SUGAR to {'sugar1q' + address}. Please click Yes to confirm", reply_markup=reply_markup) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You cannot withdraw negative amounts or amounts less than 0.00001" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "The amount you have specified is not valid. Please try again." ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You did not specify the amount you wish to withdraw. Please try again" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You have specified an invalid withdraw address. Try again with a valid address." ) else: ctx.bot.send_message(chat_id=update.message.chat_id, text="No withdraw address specified")
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 tip(update, ctx): gettime = str(update.message.date).split() chatid = update.message.chat_id timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) if timestart < int(timestamp): user = update.message.from_user args = update.message.text.split(" ") if not db.checkUser(user["id"]): if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Похоже, вы еще не зарегистрировались. Пожалуйста запустите команду /help для регистрации" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: target = None try: target = args[1][1:] except IndexError: target = target amount = None try: amount = args[2] except IndexError: amount = amount if target is not None: if not db.getUserID(target): if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Упс, похоже, вы отправляете пользователю, который не зарегистрировался. Попросите его сделать /help для регистрации!\nПомните, что имена пользователей чувствительны к регистру. Убедитесь, что большие и маленькие буквы введены правильно." ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "Oops, looks like your sending to a user who hasn't registered. Ask them to do /help to register!\nPlease be mindful that usernames are case senstive. Make sure that the case of the target is correct." ) else: if user["username"] == target: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text="рџ† Вы не можете дать себе чаевые!") else: ctx.bot.send_message( chat_id=update.message.chat_id, text="рџ† You can't tip yourself!") else: if amount is not None: if isFloat(amount): if float(amount) > float( config.coin['minFee']): keyboard = [[ InlineKeyboardButton( "Yes", callback_data= f"Y,{db.getUserID(target)},{amount},{user['id']},t" ), InlineKeyboardButton( "No", callback_data= f"N,{target},{amount},{user['id']},t" ) ]] reply_markup = InlineKeyboardMarkup( keyboard) if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= f"Вы собираетесь отправить {amount} {config.coin['ticker']} с дополнительной комиссией в размере {format(float(config.coin['minFee']), '.8f')} YENTEN to @{target}. Пожалуйста, нажмите Yes, чтобы подтвердить", reply_markup=reply_markup) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= f"You are about to send {amount} {config.coin['ticker']} with an additional fee of {format(float(config.coin['minFee']), '.8f')} YENTEN to @{target}. Please click Yes to confirm", reply_markup=reply_markup) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Вы не можете отправлять отрицательные суммы или суммы меньше, чем 0.00001!" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You cannot send negative amounts or amounts less than 0.00001!" ) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Неверное количество YENTEN. Пожалуйста, попробуйте еще раз" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "Invalid amount of YENTEN. Please try again" ) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text="Сумма не указана!") else: ctx.bot.send_message( chat_id=update.message.chat_id, text="Сумма не указана!") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="No amount specified!")
def withdraw(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 userlang = db.getLang(user["id"]) if update.message.chat.type == "private": args = update.message.text.split(" ") sender_address = getAddress(user['id']) if not db.checkUser(user['id']): ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['not-registered']) else: address = None try: address = str(args[1])[7:] except IndexError: address = address amount = None try: amount = args[2] except IndexError: amount = amount if address is not None: if checkAdd("sugar1q" + address): if ("sugar1q" + address) != str(sender_address): if amount is not None: if isFloat(amount): if float(amount) > float( config.coin['minFee']): keyboard = [[ InlineKeyboardButton( "Yes", callback_data= f"Y,{address},{amount},{user['id']},w" ), InlineKeyboardButton( "No", callback_data= f"N,{address},{amount},{user['id']},w" ) ]] reply_markup = InlineKeyboardMarkup( keyboard) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"{lang[userlang]['withdraw']['part-1']} {amount} {config.coin['ticker']}, {lang[userlang]['withdraw']['part-2']} {format(float(config.coin['minFee']), '.8f')} {lang[userlang]['withdraw']['part-3']} {'sugar1q' + address}. {lang[userlang]['withdraw']['part-4']}", reply_markup=reply_markup) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error'] ['withdraw']['negative-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error'] ['withdraw']['invalid-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['withdraw'] ['no-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['withdraw'] ['same-address']) else: ctx.bot.send_message(chat_id=update.message.chat_id, text=lang[userlang]['error'] ['withdraw']['invalid-address']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[userlang]['error']['withdraw']['no-address']) else: ctx.bot.send_message(chat_id=update.message.chat_id, text=lang[userlang]['error']['dm-only'])
def withdraw(update, ctx): gettime = str(update.message.date).split() chatid = update.message.chat_id timetoconvert = gettime[0] + "T" + gettime[1] timestamp = strict_rfc3339.rfc3339_to_timestamp(timetoconvert) if timestart < int(timestamp): user = update.message.from_user args = update.message.text.split(" ") if not db.checkUser(user['id']): if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Похоже, вы еще не зарегистрировались. Пожалуйста, запустите /help сначала, чтобы зарегистрироваться" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "It looks like you haven't registered yet. Please run /help first to register yourself" ) else: address = None try: address = str(args[1])[1:] except IndexError: address = address amount = None try: amount = args[2] except IndexError: amount = amount if address is not None: if checkAdd("Y" + address): if amount is not None: if isFloat(amount): if float(amount) > float(config.coin['minFee']): keyboard = [[ InlineKeyboardButton( "Yes", callback_data= f"Y,{address},{amount},{user['id']},w" ), InlineKeyboardButton( "No", callback_data= f"N,{address},{amount},{user['id']},w") ]] reply_markup = InlineKeyboardMarkup(keyboard) if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= f"Вы собираетесь вывести {amount} {config.coin['ticker']}, с комиссией {format(float(config.coin['minFee']), '.8f')} YENTEN to {'Y' + address}. Пожалуйста, нажмите Yes, чтобы подтвердить", reply_markup=reply_markup) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= f"You are about to withdraw {amount} {config.coin['ticker']}, with a fee of {format(float(config.coin['minFee']), '.8f')} YENTEN to {'Y' + address}. Please click Yes to confirm", reply_markup=reply_markup) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Вы не можете снимать отрицательные суммы или суммы меньше чем 0.00001" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You cannot withdraw negative amounts or amounts less than 0.00001" ) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Указанная вами сумма недействительна. Пожалуйста, попробуйте еще раз." ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "The amount you have specified is not valid. Please try again." ) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Вы не указали сумму, которую хотите снять. Пожалуйста, попробуйте еще раз" ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You did not specify the amount you wish to withdraw. Please try again" ) else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= "Вы указали неверный адрес для вывода средств. Повторите попытку с действительным адресом." ) else: ctx.bot.send_message( chat_id=update.message.chat_id, text= "You have specified an invalid withdraw address. Try again with a valid address." ) else: if checkRus(chatid): ctx.bot.send_message(chat_id=update.message.chat_id, text="Адрес для вывода не указан") else: ctx.bot.send_message(chat_id=update.message.chat_id, text="No withdraw address specified")
def help(update, ctx): gettime = str(update.message.date).split() chatid = update.message.chat_id 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']}), Поздравляю! Вы успешно зарегестрировались. Попросите у людей монетку, они обязательно дадут.", parse_mode="MarkdownV2") if checkRus(chatid): ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" Приветище [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. У нас есть следующие команды: 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= "*Полезное: * Мы не рекомендуем майнить на данный адрес, т\\.к\\. монеты могут зависнуть из\\-за частых мелких переводов\\. " "Скачайте полноценный yenten core кошелёк на свой компьютер: " "[Yenten Core](https://github\\.com/yentencoin/yenten/releases)", 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: " "[Yenten Core](https://github\\.com/yentencoin/yenten/releases)", parse_mode="MarkdownV2") else: if checkRus(chatid): ctx.bot.send_message(chat_id=update.message.chat_id, text=f""" Приветище [{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']})\\. У нас есть следующие команды: 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= "*Полезное: * Мы не рекомендуем майнить на данный адрес, т\\.к\\. монеты могут зависнуть из\\-за частых мелких переводов\\. " "Скачайте полноценный yenten core кошелёк на свой компьютер: " "[Yenten Core](https://github\\.com/yentencoin/yenten/releases)", 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: " "[Yenten Core](https://github\\.com/yentencoin/yenten/releases)", parse_mode="MarkdownV2") else: if checkRus(chatid): ctx.bot.send_message( chat_id=update.message.chat_id, text= f"[{escape_markdown(user['first_name'], 2)}](tg://user?id={user['id']}), пожалуйста зайдите в настройки telegram и настройте username перед началом использования бота", parse_mode="MarkdownV2") else: tx.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 tip(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 args = update.message.text.split(" ") language = str() if update.message.chat.type == "private": language = db.getLang(user["id"]) else: language = getLang(update.message.chat_id) if not db.checkUser(user["id"]): ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['general']['dm-only']) else: target = None try: target = args[1][1:] except IndexError: target = target amount = None try: amount = args[2] except IndexError: amount = amount if target is not None: if not db.getUserID(target): ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['tip']['re-register']) else: if user["username"] == target: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['tip']['tip-yourself']) else: if amount is not None: if isFloat(amount): if float(amount) > float( config.coin['minFee']): print(db.getUserID(target)) keyboard = [[ InlineKeyboardButton( "Yes", callback_data= f"Y,{db.getUserID(target)},{amount},{user['id']},t" ), InlineKeyboardButton( "No", callback_data= f"N,{db.getUserID(target)},{amount},{user['id']},t" ) ]] reply_markup = InlineKeyboardMarkup( keyboard) ctx.bot.send_message( chat_id=update.message.chat_id, text= f"{lang[language]['tip']['part-1']} {amount} {config.coin['ticker']} {lang[language]['tip']['part-2']} {format(float(config.coin['minFee']), '.8f')} {lang[language]['tip']['part-2']} @{target}. {lang[language]['tip']['part-4']}", reply_markup=reply_markup) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['tip'] ['negative-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['tip'] ['invalid-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['tip'] ['no-amount']) else: ctx.bot.send_message( chat_id=update.message.chat_id, text=lang[language]['error']['tip']['no-user'])
def POST(self): rel1 = False rel3 = False web.header('Content-Type','application/json') dat = web.data() input = json.loads(dat) act = input['action'] print "data: "+act if act == 'Relay 1 on' : ser.write('1') rel1 = True rv = {'status' : 'True', 'message' : 'Relay 1 is ON!'} return json.dumps(rv) elif act == 'Relay 1 off' : ser.write('!') rel1 = False rv = {'status':'True', 'message': 'Relay 1 is OFF!'} return json.dumps(rv) elif act == 'Relay 2 on' : ser.write('2') #rel2 = True rv = {'status':'True', 'message':'Relay 2 is ON!'} return json.dumps(rv) elif act == 'Relay 3 on' : ser.write('3') rel3 = True rv = {'status': 'True', 'message' : 'Relay 3 is ON!' } return json.dumps(rv) elif act == 'Relay 3 off' : ser.write('#') rel3 = False rv = {'status' : 'True', 'message' : 'Relay 3 is OFF!'} return json.dumps(rv) elif act == 'CHECK' : ser.write('5') sta = ser.readline() stat = int(sta,2) if stat == 0 : rel1=False; #rel2=False; rel3=False; elif stat == 1 : rel1=False; #rel2=False; rel3=True; elif stat == 2 : rel1=True; #rel2=True; rel3=False; elif stat == 3 : rel1=True; #rel2=True; rel3=True; '''elif stat == 4 : rel1=True; rel2=False; rel3=False; elif stat == 5 : rel1=True; rel2=False; rel3=True; elif stat == 6 : rel1=True; rel2=True; rel3=False; elif stat == 7 : rel1=True; rel2=True; rel3=True;''' rv = {'status':'True', 'message' : stat} return json.dumps(rv) elif act == 'loginF': idata = input['data'] image = open('imageFromPhone.jpg','wb') image.write(idata.decode('base64')) image.close() image = cv2.imread('imageFromPhone.jpg') recog = fileH.trainRecog() [label , dist] = fileH.recognize(image,recog) rv = {} if label == -1: rv = {'status': 'False'} else: conn = db.Connect() [status,uname,pswd] = db.checkFace(conn,label) conn.close() rv = {'status':str(status),'uname':uname,'pswd':pswd} #rv = {'status':'True', 'message' : 'label : '+str(label)+'\ndist : '+str(dist)} return json.dumps(rv) elif act == 'login': uname = input['username'] pswd = input['password'] conn = db.Connect() if db.checkUser(conn,uname,pswd): print "User Exists!" flag = True for names in self.users: if names == uname : flag = False break else: flag = True if flag : self.users.append(uname) rv={'stat':'True'} conn.close() return json.dumps(rv) else: rv={'stat':'False'} conn.close() return json.dumps(rv) elif act == 'logout': uname = input['username'] flag = False for name in self.users: if name == uname: self.users.remove(name) flag = True break else: flag = False rv={'stat':'abc'} ser.write('4') if flag: rv={'stat':'True'} else: rv={'stat':'False'} return json.dumps(rv) elif act == 'getUsers': conn = db.Connect() usernames = db.getUsers(conn) conn.close() rv={'users':usernames} return json.dumps(rv) elif act == 'register': flag = input['pic'] uname = input['uname'] pswd = input['pswd'] name = input['name'] #logging.warning(str(flag)+' '+uname+' '+pswd+' '+name) if flag == 'False': #logging.warning('Entered False') try: #logging.warning('Entered Try') conn = db.Connect() db.insertUser(conn,uname,pswd,name,'') conn.commit() conn.close() rv={'stat':'True'} return json.dumps(rv) except: #logging.warning('Entered Except') rv={'stat':'False'} return json.dumps(rv) elif flag == 'True': im1 = input['img1'] im2 = input['img2'] im3 = input['img3'] im4 = input['img4'] path = fileH.getPath() im = open('image.jpg','wb') im.write(im1.decode('base64')) im.close() img = cv2.imread('image.jpg') fileH.saveFace(img,path) im = open('image.jpg','wb') im.write(im2.decode('base64')) im.close() img = cv2.imread('image.jpg') fileH.saveFace(img,path) im = open('image.jpg','wb') im.write(im3.decode('base64')) im.close() img = cv2.imread('image.jpg') fileH.saveFace(img,path) im = open('image.jpg','wb') im.write(im4.decode('base64')) im.close() img = cv2.imread('image.jpg') fileH.saveFace(img,path) fileH.createCSV() face = fileH.getLabel() logging.warning('label '+str(face)) con = db.Connect() db.insertUser(con,uname,pswd,name,face) con.commit() con.close() #fileH.trainRecog() rv={'stat':'True'} return json.dumps(rv) else : rv={'message':'Invalid Request'} return json.dumps(rv)