Пример #1
0
async def showRate(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    await message.delete()
    currency = message.text[:3].upper()
    user.addCurrencyUse(currency)
    currState = await getCurrentState(state)
    if currState == 'otherCurrency':
        markup = currencyMarkup(user)
    else:
        markup = mainCurrencyMarkup(user)
    if currency == 'UAH':
        await message.answer("Это легко, 1 гривна как стоила 1 гривну, так и стоит 1 гривну 🙃",
                             disable_notification=True)
    elif 20 < user.dayForShow < 63:
        file = drawDiagram(user.dayForShow, currency, user.id)
        await dp.bot.send_photo(message.chat.id, photo=open(file, 'rb'),
                                caption=f'Курс {currency} за {user.dayForShow} дней',
                                reply_markup=markup)
        os.remove(file)
    elif user.dayForShow > 62:
        file = drawHistogramm(user.dayForShow, currency, user.id)
        await dp.bot.send_photo(message.chat.id, open(file, 'rb'),
                                f'Курс {currency} за {user.dayForShow} дней',
                                reply_markup=markup)
        os.remove(file)
    else:
        await message.answer(getReturnRate(currency, user.dayForShow), reply_markup=markup,
                             disable_notification=True)
Пример #2
0
async def selectCity(message: types.Message, state: FSMContext):
    await message.delete()
    if message.text.split('.')[0].isdigit():
        currentState = await getCurrentState(state)
        elemNumber = int(message.text.split('.')[0]) - 1
        weatherSearch = await state.get_data('search')
        await message.answer(await
                             getWeather(weatherSearch['search'][elemNumber],
                                        state),
                             reply_markup=futureWeatherInlineMarkup(),
                             disable_notification=True)
        if currentState in ['setMainCity', 'selectMainCity']:
            user = User(message.from_user.id)
            user.setMainCity(weatherSearch['search'][elemNumber][1])
            if currentState == 'selectMainCity':
                await deleteMessages(message.message_id, message.chat.id,
                                     state)
                await message.answer(
                    f"{weatherSearch['search'][elemNumber][0]} установлен как город по умолчанию\n"
                    f"Настройка закончена, спасибо 🤗",
                    reply_markup=mainMarkup())
                await sendKeanu(message.chat.id)
                await state.reset_state()
                return
            else:
                await message.answer(
                    f"{weatherSearch['search'][elemNumber][0]} установлен как город по умолчанию",
                    reply_markup=settingsMarkup(user))
                await SettingsState.settingsMenu.set()
    elif message.text == 'Искать еще 🔍':

        await message.answer('Укажите населенный пункт 🏙️',
                             reply_markup=locationMarkup(),
                             disable_notification=True)
        await WeatherState.weatherMenu.set()
Пример #3
0
def change_pwd(mob_no, from_choice='login'):
    try:
        a = User()
        if from_choice == 'login':
            old_pwd = input("Old Password : "******"New Password : "******"Confirm New password : "******"Password changed Successfully")
    except CustomExceptions.InvalidConfirmPasswordException as e:
        print(e)
    except CustomExceptions.InvalidPassword as e:
        print(e)
    except CustomExceptions.InvalidPasswordException as e:
        print(e)
Пример #4
0
 def __init__(self):
     self.apps_path = ""
     self.working_dir = ""
     self.hack_dir = ""
     self.decrypt_dir = ""
     self.backup_dir = ""
     self.user = User()
     self.game = Game()
Пример #5
0
async def changeCurrencyList(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    await message.delete()
    await message.answer('Пожалуйста, выберите интересующие Вас валюты',
                         reply_markup=currencyMarkup(user, True, True),
                         disable_notification=True)
    await message.answer('Выберите до 5 валют')
    await SettingsState.setCurrencyList.set()
    await state.set_data(user.dictUserCurrency())
Пример #6
0
def function_RegisterUser(email, first_name, last_name, password):
    if DoExist('account', email):
        return 'Account is already registered.'

    user = User(email, first_name, last_name)
    user.password = password

    userId = InsertDB('account', user)
    return userId
Пример #7
0
def user_import():
    try:
        name = request.args.get('name')
        password = request.args.get('password')
        user = User(name, password)
        user.input_user()
        return user.name
    except Exception as e:
        logging.exception(f"Exception [{e}]: while adding user")
        return make_response("Unprocessable entity", 430)
Пример #8
0
async def start(event):
    try:
        user_info = await bot.get_entity(event.original_update.message.peer_id)
        user = User(user_info.id, user_info.username, '', '')
        users.add_user(user)
        msg = await event.respond(welcome_text,
                                  buttons=welcome_keyboard,
                                  parse_mode=html)
        user.add_message(msg.id)
    except Exception:
        print('Ошибка:\n', traceback.format_exc())
Пример #9
0
def addDevice():
    global dbConnection
    form = AddDeviceForm()
    if form.validate_on_submit():
        salt, hash = User.generateUserPassword(form.password.data)
        newDevice = User(form.devicename.data, hash, salt)
        dbConnection.insertUser(newDevice)
        flash(f'Device added with name {form.devicename.data}!', 'success')
        psLogger.debug("Added device")
        return redirect(url_for('admin'))
    return render_template("add_device.html", title="Add Device", form=form)
Пример #10
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed = bcrypt.generate_password_hash(
            request.form['password']).decode('utf-8')
        user1 = User(request.form['username'], hashed, request.form['email'],
                     'default.jpg')
        user1.upload()
        flash(f'Account created for {form.username.data}! Now log in',
              'success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Registration', form=form)
Пример #11
0
async def weatherMenu(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    await message.delete()
    if user.location is None:
        pass
    else:
        await message.answer(await getWeather(user.getSearchQuery(), state),
                             reply_markup=futureWeatherInlineMarkup(),
                             disable_notification=True)
    await message.answer('Отправте сообщение с названием населенного пункта',
                         reply_markup=locationMarkup(),
                         disable_notification=True)
    await WeatherState.weatherMenu.set()
Пример #12
0
async def goBack(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    currentState = await state.get_state()
    if currentState is None:
        await message.answer('Перехожу в главное меню', reply_markup=mainMarkup(), disable_notification=True)
        return
    currentState = currentState.split(':')[1]
    await message.delete()
    if currentState in [
        'otherCurrency',
        'changeCurrencyFrom',
        'changeCurrencyFrom',
        'selectCurrencyFrom'
    ]:
        await message.answer('Выберите валюту', reply_markup=mainCurrencyMarkup(user), disable_notification=True)
        await CurrencyState.mainMenu.set()
    elif currentState in [
        'mainMenu',
        'settingsMenu',
        'searchState',
        'weatherMenu',
        'yapMainMenu',
        'bookMenu'
    ]:
        await message.answer('Окей. Перехожу в главное меню', reply_markup=mainMarkup(), disable_notification=True)
        await state.finish()

    elif currentState in ['subMenu', 'showPhotos', 'card']:
        await deleteMessages(message.message_id, message.chat.id, state)
        await message.answer('Выберите категорию', reply_markup=mainYapMarkup(), disable_notification=True)
        await Yap.yapMainMenu.set()
Пример #13
0
async def changeMainCurrency(message: types.Message):
    await message.delete()
    await message.answer(
        'Выберите валюту, которая будет установлена по умолчанию в конвертере',
        reply_markup=currencyMarkup(user=User(message.from_user.id),
                                    addUAH=True))
    await SettingsState.setMainCurrency.set()
Пример #14
0
async def start(event):
    try:
        user_info = await bot.get_entity(event.original_update.message.peer_id)
        user = users.get_user(user_info.id)
        msg = await event.respond('Возвращаемся в начало',
                                  buttons=Button.clear())
        user.add_message(msg)
        user.add_user_message(event.message.id)
        await user.delete_all_messages()
        user_info = await bot.get_entity(event.original_update.message.peer_id)
        user = User(user_info.id, user_info.username, '', '')
        users.add_user(user)
        msg = await event.respond(welcome_text, buttons=welcome_keyboard)
        user.add_message(msg)
    except Exception:
        print('Ошибка:\n', traceback.format_exc())
Пример #15
0
    def fetch_widget_data(self):
        """
        Get widget data via query manager

        returns: {Dict} A dictionary of the pandas dataframe data from the query manager
        """
        # Create the widget name for the QueryManager
        cur_user = User.get_instance()
        user_id = cur_user.get_user_id()
        time_stamp_from = cur_user.get_time_stamp_from()
        time_stamp_to = cur_user.get_time_stamp_to()
        database_id = cur_user.get_user_database_id()
        widget_name = '%s-widget-%s-%s-%s-%s-user-%s' % (
            self.widget_type, self.config['title']['text'], time_stamp_from,
            time_stamp_to, database_id, user_id)
        # Define the MySQL query to run
        sql_query = "SELECT t_stamp, value, name FROM data WHERE name=\'" + self.config[
            'metric'] + "\' AND t_stamp BETWEEN \'%s 00:00:00\' AND \'%s 00:00:00\' order by t_stamp" % (
                time_stamp_from, time_stamp_to)

        # Fetch the data from the query manager
        self.widget_data = self.queryManager.getWidgetDataFromQueryManager(
            widget_name, time_stamp_from, time_stamp_to, database_id,
            sql_query, user_id, True)

        # return the fetched data
        return self.widget_data
Пример #16
0
async def start_showMainCurrency(message: types.Message):
    user = User(message.from_user.id)
    await message.delete()
    await message.answer(
        text=
        'Для начала, укажите валюту, которая будет использована как основная в конверторе валют?',
        reply_markup=currencyMarkup(user, addUAH=True))
    await FirstSettings.showCurrency.set()
Пример #17
0
def mock_createUsers():
    with open('./mockData/users.json') as json_data:
        data = json.load(json_data)
        return [
            User(name=u['name'],
                 firstName=u['firstName'],
                 lastName=u['lastName']) for u in data
        ]
Пример #18
0
    def userData(self):
        users = []
        userDB = db.users.find()

        for user in userDB:
            users.append(User(user["name"], user["surname"], user["_id"]))

        return users
Пример #19
0
async def backFromSetNotify(call: CallbackQuery):
    await call.message.delete()
    await SettingsState.settingsMenu.set()
    user = User(call.from_user.id)
    msg = await call.message.answer('Закрываю настройку времени уведомлений', reply_markup=types.ReplyKeyboardRemove())
    await msg.delete()

    await call.message.answer('Перехожу в настройки', reply_markup=settingsMarkup(user))
Пример #20
0
 def backupUsers(self, name, users):
     log("Backing up", name)
     # print("Friends:", , "(",", ".join([f"{a.name}#{a.discriminator}" for a in self.user.friends]),")")
     _users = list()
     for friend in users:
         user = User(friend)
         _users.append(user)
     savePath = os.path.join(self.backupPath, f"{name}.json")
     saveJSON(savePath, _users, encoder=MyEncoder)
     log("Backed up", len(_users), name, "to", savePath)
Пример #21
0
async def exitFromInline(call: CallbackQuery):
    user = User(call.from_user.id)
    currentResult = call.message.reply_markup.inline_keyboard[2][0].text
    await call.message.delete()
    if currentResult == 'Результат':
        txt = 'Открываю меню курса валют'
    else:
        txt = f"{currentResult} {call.message.reply_markup.inline_keyboard[1][1].text.split(' - ')[1]}"
    await call.message.answer(txt, reply_markup=mainCurrencyMarkup(user))
    await CurrencyState.mainMenu.set()
Пример #22
0
    def test_Response_User(self):

        res = mocked_get_ok(url=ENDPOINT_USER)

        self.assertEqual(200, res.status_code, 'Wrong status code: 200 !='+str(res.status_code))

        usr: User = User(res.data)
        self.assertEqual(user1_json['id'], usr.id)
        self.assertEqual(user1_json['email'], usr.email)
        self.assertEqual(user1_json['firstname'], usr.firstname)
        self.assertEqual(user1_json['lastname'], usr.lastname)
Пример #23
0
async def selectNotificationTime(message: types.Message):
    txt = replaceListOne(message.text.strip(), ['.', ',', '/', '-', ';'], ':')
    await message.delete()
    sp = txt.split(':')
    if sp.__len__() == 2:
        if -1 < int(sp[0]) < 25 and -1 < int(sp[1]) < 61:
            if -1 < int(sp[1]) < 61:
                user = User(message.from_user.id)
                txt = datetime.strptime(txt, '%H:%M').strftime('%H:%M')
                user.setNotificetionTime(txt)
                await message.answer(f'Буду высылать уведомления в {txt} ⏰',
                                     reply_markup=settingsMarkup(user))
                await SettingsState.settingsMenu.set()
            else:
                await message.answer('Я не знаю столько минут 🙃')
        else:
            await message.answer('Я не знаю столько часов 🙃')
    elif sp.__len__() <= 1:
        await message.answer('Слишком маленькое значение 😟')
    else:
        await message.answer('Слишком большое значение 😟')
Пример #24
0
def UnconnectedRoutes(request: pituophis.Request, userCache):
	if request.path=="/":
		return pituophis.Item('i',"BIENVENUE SUR AO3")
		
	if request.path=="/connect":
		x = User()
		userCache[x.id] = x
		return [
			pituophis.Item("i","You are now connected as {}.".format(x.id)),
			pituophis.Item("i",""),
			pituophis.Item("1","Continue","/connected/{}".format(x.id),dotenv.get_key("../","HOST"),70)
		]
Пример #25
0
def signup():
    if request.method == 'GET':
        return render_template('sign_up.html')

    username = request.form.get('user')
    password1 = request.form.get('password1')
    password2 = request.form.get('password2')
    user = User(username, password1)

    if password1 != password2:
        flash('Password must match', category='error')
        return render_template("sign_up.html")

    success = user.input_user()

    if not success:
        flash("User must have atleast 3 chars, password 4.", category='error')
        return render_template("sign_up.html")

    token = user.get_encoded_token()
    return render_template('user.html', user=user.name, token=token)
Пример #26
0
async def setUserCurrencyList(call: CallbackQuery, state: FSMContext):
    user = User(call.from_user.id)
    data = await state.get_data()
    if data.__len__() == 0:
        await call.message.answer('Выберите хотя бы одну валюту 🥺')
    else:
        await call.message.delete()
        data = list(data.keys())
        user.setUserCurrency(data)
        currentState = await getCurrentState(state)
        if currentState == 'setCurrencyList':
            await call.message.answer(
                f"{', '.join(data)} теперь будут отображатся в меню курса валют",
                reply_markup=settingsMarkup(user))
            await SettingsState.settingsMenu.set()
        else:
            await call.message.answer(
                f"{', '.join(data)} теперь будут отображатся в меню курса валют\n"
                f"За сколько дней отображать курс валют (напишите число от 1 до 400)?",
                reply_markup=types.ReplyKeyboardRemove())
            await FirstSettings.indicateDaysForShow.set()
Пример #27
0
async def changeCurrencyTo(call: CallbackQuery, state: FSMContext):
    user = User(call.from_user.id)
    await call.message.delete()
    await call.message.answer('В какую валюту конвертировать?',
                              reply_markup=currencyMarkup(user))
    await state.set_data({
        'from':
        call.message.reply_markup.inline_keyboard[1][0].text.split(' - ')[1],
        'to':
        call.message.reply_markup.inline_keyboard[1][1].text.split(' - ')[1]
    })
    await CurrencyState.changeCurrencyTo.set()
Пример #28
0
async def setDayForShow(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    await message.delete()
    if message.text.isdigit():
        if 0 < int(message.text) < 401:
            user.setDayForShow(message.text)
            currentState = await getCurrentState(state)
            if currentState == 'setDayForShow':
                await message.answer(
                    f"Окей. Буду выводить курс за {message.text} дней",
                    reply_markup=settingsMarkup(user))
                await SettingsState.settingsMenu.set()
            else:
                await message.answer(
                    f"Окей. Буду выводить курс за {message.text} дней\n"
                    f"Установим населенный пункт для погоды по умолчанию?",
                    reply_markup=locationMarkup(True))
                await FirstSettings.indicateMainCity.set()
        else:
            await message.answer("Пожалуйста, укажите целое число от 1 до 400")
    else:
        await message.answer("Пожалуйста, укажите целое число")
Пример #29
0
async def setMainCurrencySettings(message: types.Message, state: FSMContext):
    user = User(message.from_user.id)
    currency = message.text[:3]
    await message.delete()
    user.setCurrency(currency)
    currentState = await getCurrentState(state)
    if currentState == 'showCurrency':
        await message.answer(text='Выберите до 5 валют (включительно)',
                             reply_markup=currencyMarkup(user, True, True),
                             disable_notification=True)
        await message.answer(
            text=
            f"{currency} {getFlag(currency)} установлена как основная валюта\n"
            f"Теперь укажите интересующие Вас валюты (из списка выше)",
            reply_markup=types.ReplyKeyboardRemove())
        await FirstSettings.indicateCurrencyList.set()
        await state.set_data(user.dictUserCurrency())
    else:
        await message.answer(
            f"{currency} {getFlag(currency)} установлена как валюта по умолчанию в конвертере",
            reply_markup=settingsMarkup(user))
        await SettingsState.settingsMenu.set()
Пример #30
0
    def __init__(self, master):
        """ Class constructor
        Parameters:
        master -- object tkinter
        """
        super().__init__(master)

        # Add title -> windows
        self.master.title(self.title)

        # Set background color
        self.master['bg'] = 'white'

        # init Food object
        self.food = Food()

        # init User object
        self.user = User()

        # init Category object
        self.category = Category()

        # var categories
        self.category_ids = []

        # var foods
        self.food_data = []

        # var current category index
        self.current_category_idx = None

        # var current food index
        self.current_food_idx = None

        # var current food index
        self.aliment = None

        # Add element in windows
        self.category_list = None
        self.status_bar = None
        self.input_category = None
        self.product_list = None
        self.button_next_page = None
        self.button_before_page = None
        self.description_box = None
        self.button_save_food = None

        # construct window
        self.build_window()
        self.button_before_page.pack(side=tk.LEFT)
        self.button_next_page.pack(side=tk.LEFT)
Пример #31
0
from classes.User import User;

test = User();
test.firstFunction('test');