Beispiel #1
0
def money_status():
    current_data = str(
        str(time.localtime()[0]) + "-0" + str(time.localtime()[1]) + "-" +
        str(time.localtime()[2]))
    yesterday = str(
        str(time.localtime()[0]) + "-0" + str(time.localtime()[1] - 1) + "-" +
        str(time.localtime()[2]))
    rates = ExchangeRates(current_data, locale_en=False)
    rates_yesterday = ExchangeRates(yesterday, locale_en=False)
    flag_list = ("🇦🇺", "🇦🇿", "🇬🇧", "🇬🇪", "🇧🇾", "🇧🇬", "🇧🇷", "🇭🇺", "🇭🇰", "🇩🇰",
                 "🇺🇸", "💶", "🇮🇳", "🇰🇿", "🇨🇦", "🇰🇬", "🇨🇳", "🇲🇩", "🇳🇴", "🇵🇱",
                 "🇷🇴", "", "🇸🇬", "🇹🇯", "🇹🇷", "🇹🇲", "🇺🇿", "🇺🇦", "🇨🇿", "🇸🇪",
                 "🇸🇪", "🇿🇦", "🇰🇷", "🇯🇵")
    flag = 0

    msg_text_money = ""
    for rate in rates.rates:
        value_money = float(
            (rates[rate.code].value - rates_yesterday[rate.code].value))
        if value_money < 0:
            msg_text_money = msg_text_money + (
                flag_list[flag] + (str(rates[rate.code].name) + " " +
                                   ("%.2f" % rates[rate.code].value) +
                                   " руб." + " 🔻" + str(value_money)) + "\n")
        elif value_money >= 0:
            msg_text_money = msg_text_money + (
                flag_list[flag] + str(rates[rate.code].name) + " " +
                ("%.2f" % rates[rate.code].value) + " руб." + " 🔺+" +
                str(value_money) + "\n")
        flag += 1
    return msg_text_money
Beispiel #2
0
def find_value(currency):
    """Возвращает текущий курс"""
    rates = ExchangeRates(now)
    name = rates[currency].name
    value = rates[currency].value
    answer = str(name) + " " + str(value)
    return answer
Beispiel #3
0
def exchange_rate(message):
    text = message.text.strip().lower()
    if text.startswith('/'):
        bot.send_message(message.chat.id,
                         "Невозможно вызвать команду в данный момент",
                         reply_markup=main_markup)
        return
    if text in ['stop', 'back', 'back⬅']:
        bot.send_message(message.chat.id,
                         "Возвращаемся назад",
                         reply_markup=main_markup)
        return
    if text in ['usd💵', 'eur💶', 'cny💴', 'gbp💷']:
        text = text[:-1]
    if text in ['usd', 'eur', 'cny', 'gbp']:
        rates = ExchangeRates(datetime.now())
        bot.send_message(
            chat_id=message.chat.id,
            text=
            f"<b>Сейчас курс: {text.upper()} = {float(rates[text.upper()].rate)}</b>",
            parse_mode="html",
            reply_markup=main_markup)
    else:
        bot.send_message(message.chat.id,
                         f'Не надйен курс валюты: {text.upper()}',
                         reply_markup=main_markup)
Beispiel #4
0
def message(message):

    message_norm = message.text.strip().lower()

    if message_norm in ['usd', 'eur']:
        rates = ExchangeRates(datetime.now())

        bot.send_message(chat_id = message.chat.id, text = f"{message_norm.upper()} курс - {float(rates[message_norm.upper()].rate)}", parse_mode = "html")
Beispiel #5
0
def test_rates():

    rates = ExchangeRates('2016-06-26', locale_en=True)

    assert str(rates.date_requested) == '2016-06-26 00:00:00'
    assert str(rates.date_received) == '2016-06-25 00:00:00'
    assert not rates.dates_match

    assert rates['USD'].name == 'US Dollar'
    assert rates['R01235'].name == 'US Dollar'
    assert rates['840'].name == 'US Dollar'

    rates = ExchangeRates('2016-06-25')

    assert str(rates.date_requested) == '2016-06-25 00:00:00'
    assert str(rates.date_received) == '2016-06-25 00:00:00'
    assert rates.dates_match

    assert rates['USD'].name == u'Доллар США'
    assert rates['R01235'].name == u'Доллар США'
    assert rates['840'].name == u'Доллар США'
Beispiel #6
0
def rates2(call):
    dt = datetime.datetime.now().strftime("%Y-%m-%d")
    r = ExchangeRates(dt, locale_en=True)
    cm = bot.send_message(call.message.chat.id, "Введите код валюты в формате: ХХХ . Например USD или JPY.")
    bot.register_next_step_handler(cm, call)

    try:
        # print(r)
        answer = "По состоянию на " + dt + ": \n " \
                                           "1 USD (Доллар) = " + str(r[cm].value) + " руб. \n "
        bot.send_message(call.message.chat.id, answer)
    except Exception as a:
        bot.send_message(call.message.chat.id, a)
Beispiel #7
0
def rates(call):
    dt = datetime.datetime.now().strftime("%Y-%m-%d")
    r = ExchangeRates(dt, locale_en=True)
    try:
        # print(r)
        answer = "По состоянию на " + dt + ": \n " \
                                           "1 USD (Доллар) = " + str(r['USD'].value) + " руб. \n " \
                 + "1 EUR (Евро) = " + str(r['EUR'].value) + " руб. \n " \
                 + "1 GBP (Фунт стерлингов Соединенного Королевства) = " + str(r['GBP'].value) + " руб. \n " \
                 + "1 CHF (Швейцарский франк) = " + str(r['CHF'].value) + " руб. \n " \
                 + "1 JPY (Японская иена) = " + str(r['JPY'].value) + " руб. \n " \
                 + "1 DKK (Датская крона) = " + str(r['DKK'].value) + " руб. \n "
        bot.send_message(call.message.chat.id, answer)
    except Exception as a:
        bot.send_message(call.message.chat.id, a)
Beispiel #8
0
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint
                            | Qt.WindowStaysOnTopHint)
        self.show()

        if obj:
            self.obj = obj
            self.load()
        else:
            self.obj = Note()
            self.save()

        self.closeButton.pressed.connect(self.delete_window)
        self.moreButton.pressed.connect(create_new_note)
        self.textEdit.textChanged.connect(self.save)

        self._drag_active = False
        today = datetime.datetime.now()
        str22 = str(today.year) + '-' + str(today.month) + '-' + str(today.day)
        rates = ExchangeRates(str22, locale_en=True)
        rates.dates_match

        self.label.setText(
            str(rates['USD'].value)[:4] + "$" + " " +
            str(rates['EUR'].value)[:4] + "€")
        if len(str(today.minute)) == 2:
            self.label_2.setText("Time: " + str(today.hour) + ":" +
                                 str(today.minute))
        else:
            self.label_2.setText("Time: 0" + str(today.hour) + ":0" +
                                 str(today.minute))
        self.label_3.setText("Date: " + str(today.month) + "-" +
                             str(today.day))

        for n in range(0, 10):
            getattr(self, 'pushButton_n%s' %
                    n).pressed.connect(lambda v=n: self.input_number(v))

        self.pushButton_add.pressed.connect(lambda: self.equals("+"))
        self.pushButton_sub.pressed.connect(lambda: self.equals("-"))
        self.pushButton_mul.pressed.connect(lambda: self.equals("*"))
        self.pushButton_div.pressed.connect(lambda: self.equals("/"))
        self.pushButton_cvad.pressed.connect(lambda: self.equals("2"))
        self.pushButton_cor.pressed.connect(lambda: self.equals("/2"))
        self.pushButton_eq.pressed.connect(lambda: self.equals("="))
        self.pushButton_ac.pressed.connect(lambda: self.input_number("del"))
Beispiel #9
0
def exchange_rate(message):
    message_norm = message.text.strip().lower()
    if message_norm in ['usd', 'eur', 'cny', 'gbp']:
        rates = ExchangeRates(datetime.now())
        bot.send_message(
            chat_id=message.chat.id,
            text=
            f"<b>Сейчас курс: {message_norm.upper()} = {float(rates[message_norm.upper()].rate)}</b>",
            parse_mode="html")
        bot.register_next_step_handler(message, exchange_rate)
    elif message_norm == "exit":
        bot.register_next_step_handler(message)
    else:
        bot.send_message(
            message.chat.id,
            f'Такой курс валюты: {message_norm.upper()} не найден')
Beispiel #10
0
def rates(currency, date):
    """Prints out exchange rates."""
    def print_rate(rate):
        click.secho('[%s] %s - %s' % (rate.code, rate.name, rate.rate))

    rates = ExchangeRates(on_date=date, locale_en=True)

    click.secho(rates.date_received.strftime('%Y-%m-%d'))
    click.secho('=' * 10)

    if currency:
        rate = rates[currency]
        if rate:
            print_rate(rate)
        else:
            click.secho('No data for %s' % currency)
    else:
        for rate in sorted(rates.rates, key=attrgetter('code')):
            print_rate(rate)
Beispiel #11
0
            print(srz_start_point)
            size_mm = ws1['f' + str(row_i + 2)].value[srz_start_point -
                                                      4:srz_start_point]
            _ = ws1.cell(column=19, row=row_i + 2, value="{0}".format(size_mm))
            size_mm.strip(' ')
            size_mm = int(size_mm.split(',')[0])

            if srz_start_point > 0:
                _ = ws1.cell(column=18,
                             row=row_i + 2,
                             value="{0}".format(size_mm))

        except:
            continue


# Разделение статуса и срока.

file = 'db_1.xlsx'
wb1 = load_workbook(filename=file)
ws1 = wb1['price']
rates = ExchangeRates('2019-07-03', locale_en=True)
curse_test_eur = rates['EUR'].value

new_data(curse_test_eur)

try:
    wb1.save(file)
except:
    print('!!!Открыт файл!!!')
Beispiel #12
0
def get_currency_cost(currency_code):
    rates = ExchangeRates(datetime.today())
    for rate in rates.rates:
        if rate.code == currency_code:
            return rates[currency_code].value
    return None
Beispiel #13
0
def get_rate():
    rates = ExchangeRates()
    usd_value = rates['USD'].value
    eur_value = rates['EUR'].value
    return usd_value, eur_value
Beispiel #14
0
def curs():
    rates = ExchangeRates()
    funt = rates['GBP']
    euro = rates['EUR']
    cur = euro[4] / funt[4]
    return cur
Beispiel #15
0
def rub():
    return float(ExchangeRates('2021-05-03')['USD'][4])
Beispiel #16
0
def test_exchange_rates_extra():
    # test without date, for today
    rates = ExchangeRates()

    assert len(rates) > 0
    a = rates['USD']
    a = 1

    assert rates['eur'].id == 'R01239'
    assert rates['EUR'].currency.name_ru == 'Евро'
    assert rates['R01239'].name == 'Евро'
    assert rates['r01239'].num == '978'
    assert rates['978'].code == 'EUR'
    assert rates[978].par == Decimal(1)

    assert rates['usd'].currency.id == 'R01235'
    assert rates['USD'].currency.name_ru == 'Доллар США'
    assert rates['R01235'].currency.name_eng == 'US Dollar'
    assert rates['r01235'].currency.num == '840'
    assert rates['840'].currency.code == 'USD'
    assert rates[840].currency.par == Decimal(1)

    # test with a request date different from the response date
    rates = ExchangeRates('2021-08-22')
    assert len(rates) == 34

    assert str(rates.date_requested) == '2021-08-22 00:00:00'
    assert str(rates.date_received) == '2021-08-21 00:00:00'
    assert not rates.dates_match

    assert rates['cad'].currency.id == 'R01350'
    assert rates['CAD'].currency.name_ru == 'Канадский доллар'
    assert rates['R01350'].currency.name_eng == 'Canadian Dollar'
    assert rates['r01350'].currency.num == '124'
    assert rates['124'].currency.code == 'CAD'
    assert rates[124].currency.par == Decimal(1)
    assert rates['CAD'].value == Decimal('57.5885')
    assert rates['CAD'].rate == Decimal('57.5885')

    assert rates['usd'].id == 'R01235'
    assert rates['USD'].name == 'Доллар США'
    assert rates['R01235'].currency.name_eng == 'US Dollar'
    assert rates['r01235'].num == '840'
    assert rates['840'].code == 'USD'
    assert rates[840].par == Decimal(1)
    assert rates['USD'].value == Decimal('74.3640')
    assert rates['USD'].rate == Decimal('74.3640')

    # test with the request date matching the response date
    rates = ExchangeRates('2021-08-24')
    assert len(rates) == 34

    assert str(rates.date_requested) == '2021-08-24 00:00:00'
    assert str(rates.date_received) == '2021-08-24 00:00:00'
    assert rates.dates_match

    assert rates['kzt'].currency.id == 'R01335'
    assert rates['KZT'].currency.name_ru == 'Казахстанский тенге'
    assert rates['R01335'].currency.name_eng == 'Kazakhstan Tenge'
    assert rates['r01335'].currency.num == '398'
    assert rates['398'].currency.code == 'KZT'
    assert rates[398].currency.par == Decimal(100)
    assert rates['KZT'].value == Decimal('17.3926')
    assert rates['KZT'].rate == Decimal('0.173926')

    assert rates['mdl'].id == 'R01500'
    assert rates['MDL'].name == 'Молдавский лей'
    assert rates['R01500'].currency.name_eng == 'Moldova Lei'
    assert rates['r01500'].num == '498'
    assert rates['498'].code == 'MDL'
    assert rates[498].par == Decimal(10)
    assert rates['MDL'].value == Decimal('41.9277')
    assert rates['MDL'].rate == Decimal('4.19277')
Beispiel #17
0
}  # обход запрета в РФ

# используемые команды
commands = {
    'start ': 'Приветственная информация',
    'help  ': 'Показать информацию по вариантам команд',
    'config': 'Конфигурацию бота под пользователя'
}

TOKEN = '638610225:AAEoPelXhzUC11J11x8L9bBHbjoGPKj9zXk'  # Price3Mbot
# TOKEN = "842039603:AAFy4Cd_mWZSyjFEQGcUgI0uYP87ZrQy1pQ"  # pogodaDBbot
bot = telebot.TeleBot(TOKEN)

# параметры курса ЦБ
date_of_curse = str(datetime.date.today() - timedelta(1))
rates = ExchangeRates(date_of_curse, locale_en=True)
curse_eur_glob = float(rates['EUR'].value)


# Поиск по прайсу
def indexing(search):
    """Поиск нужных позиций."""

    file = 'db_1.xlsx'
    wb1 = load_workbook(filename=file)
    ws1 = wb1['price']

    # Поиск по ключам
    search = search.lower()
    search = search.split(' ')
Beispiel #18
0
def get_usd_course() -> Decimal:
    """ Возвращает текущий курс доллара от ЦБ РФ."""
    rates = ExchangeRates(get_formatted_now())
    return Decimal(rates['USD'].value)
Beispiel #19
0
def __get_usd_rub_rate(date=None):
    try:
        return float(ExchangeRates(on_date=date)['USD'].rate)
    except Exception as e:
        print('ExchangeRates exc')
        return None
Beispiel #20
0
def get_usd_course() -> Decimal:
    rates = ExchangeRates(get_now())
    return rates['USD'].value