Beispiel #1
0
def searchCities(city):
    city = ' '.join(city.replace('ё', 'е').replace('-', ' ').lower().split())
    data = db.getFromDB('citylist', '*', f"lower(name) LIKE '{city}%'", orderBy='ORDER BY maincity DESC')

    if data.__len__() == 0:
        data = db.getFromDB('citylist', '*', f"lower(name) LIKE '{city.replace('и', 'ы')}%'",
                            orderBy='ORDER BY maincity DESC')

    returnList = []

    for elem in data:
        returnList.append(convertToAdd(elem))

    return returnList
Beispiel #2
0
def drawDiagram(howMany, currency, userID):
    today = date.today() - timedelta(days=howMany)
    data = db.getFromDB(
        tableName=currency,
        what="to_char(date,'DD.MM') as dt,cast(rate as float)",
        where=f"date >= '{today}'",
        orderBy='order by date asc'
    )

    osX = []
    osY = []

    for item in data:
        osX.append(item[0])
        osY.append(item[1])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(osX, osY)
    xax = ax.xaxis
    xlabels = xax.get_ticklabels()

    for label in xlabels:
        label.set_rotation(75)
    fig.set_figwidth(15)
    fig.set_figheight(6)
    plt.title(f'Курс {currency} за {howMany} (дней)')
    plt.grid(True)
    plt.savefig(f'{IMAGE_PATH}{userID}.png')
    return f'{IMAGE_PATH}{userID}.png'
Beispiel #3
0
def getLocation(location):
    url = f"https://nominatim.openstreetmap.org/reverse?format=json&uselang=ru_RU&" \
          f"lat={location.latitude}&lon={location.longitude}"
    res = requests.get(url)
    respJson = json.loads(res.text)

    distinct = ''
    if 'address' in respJson:
        if 'city' in respJson['address']:
            cityName = translate(respJson['address']['city']).lower().replace('-', ' ')
        elif 'town' in respJson['address']:
            cityName = translate(respJson['address']['town']).lower().replace('-', ' ')
        elif 'village' in respJson['address']:
            cityName = translate(respJson['address']['village']).lower().replace('-', ' ')
        else:
            cityName = ''
            distinct = translate(respJson['address']['county']).lower().replace('-', ' ')
        region = translate(respJson['address']['state']).lower().replace('-', ' ')

    else:
        cityName = translate(respJson['city']).lower().replace('-', ' ')
        region = ''

    if cityName == '':
        cityList = [db.getFromDB('citylist', '*', f"dist like'%{distinct}%'")[0]]
        if cityList[0][5]:
            cityList = [cityList[0]]
    else:
        cityName = convertCityName(cityName)
        cityList = db.getFromDB('citylist', '*', f"name='{cityName}'")

    if cityList.__len__() > 1:
        cityList = db.getFromDB('citylist', '*', f"name='{cityName}' AND REGION like '%{region}%'")
        if cityList.__len__() > 1:
            distinct = translate(respJson['address']['county']).lower().replace('-', ' ')
            cityList = db.getFromDB('citylist', '*', f"name = '{cityName}' AND REGION = '{region}' "
                                                     f"AND DIST = '{distinct}'")
    elif cityList.__len__() == 0:
        cityList = db.getFromDB('citylist', '*', f"name LIKE'%{cityName}%' AND REGION = '{region}'")

    returnList = []
    for elem in cityList:
        returnList.append(convertToAdd(elem))

    return returnList
async def sendMainInfo():
    now = datetime.now()
    checkTime = f"{now.hour}:{now.minute}"
    users = db.getFromDB('users', 'id, location, maincurrency',
                         f"notify = '{checkTime}'")
    if users.__len__() != 0:
        for user in users:
            if not user[1] is None:
                city = db.getFromDB('citylist', 'name, link', f"id={user[1]}")
                whether = await getWeather(city[0])
            else:
                whether = ''
            rate: str = 'Курс валют:\n'
            if not user[2] is None:
                data = db.getCurrencyList()
                for currency in user[2][0]:
                    if db.getFromDB(currency, 'rate',
                                    f"date='{date.today()}'").__len__() == 0:
                        await addCurrencyInfo(100)
                    rate += f"{data[currency]['FullName']} {data[currency]['Emoji']}: {getTodayRate(currency)}\n"
            else:
                rate = ''
            if rate == '' and whether == '':
                pass
            else:
                if whether == '':
                    txt = rate
                else:
                    if 'дождь' in whether.lower():
                        whether += '\nНе забудьте взять зонтик☂️'
                    txt = f"{whether}\n\n{rate}"
                if now.hour < 6:
                    hiMessage = 'Доброй ночи🌃\n\n'
                elif 6 <= now.hour < 9:
                    hiMessage = 'Доброе утро🌅\n\n'
                elif 9 <= now.hour <= 19:
                    hiMessage = 'Добрый день☀️\n\n'
                else:
                    hiMessage = 'Добрый вечер🌆️\n\n'

                await dp.bot.send_message(user[0], hiMessage + txt)
Beispiel #5
0
    def __init__(self, userID):
        if db.isExist('id', 'users', userID):
            data = convertToUser(db.getFromDB('users', '*', f"id={userID}"))
        else:
            data = db.addUser(userID)

        self.id = userID
        self.location = data['location']
        self.currency = data['currency']
        self.currencyPriority = data['currencyPriority']
        self.userCurrency = data['mainCurrency']
        self.dayForShow = data['dayForShow']
        self.notify = data['notify']
Beispiel #6
0
def drawHistogramm(howMany, currency, userID):
    locale.setlocale(locale.LC_ALL, "ru_RU")
    osX = []
    osY = []
    today = date.today() - timedelta(days=howMany)
    data = db.getFromDB(
        tableName=currency,
        what="to_char(date,'TMMon.YY') as dt, "
             'cast(round(avg(rate),3) as float)',
        where=f"date >= '{today}'",
        groupBy='group by dt, extract(MONTH from date), extract(year from date)',
        orderBy='order by extract(year from date) asc,extract(MONTH from date) asc'
    )

    fig, ax = plt.subplots()
    for item in data:
        osX.append(item[0])
        osY.append(item[1])
        if item[1] > 10:
            offset = 0.1
        elif item[1] > 2:
            offset = 0.01
        elif item[1] > 1:
            offset = 0.005
        else:
            offset = 0.001
        ax.text(item[0], item[1] + offset, item[1], ha='center')

    minValue = min(osY) - min(osY) * 0.2
    maxValue = max(osY) + max(osY) * 0.015
    ax.bar(osX, osY)
    ax.set_ylim(minValue, maxValue)

    fig.set_figwidth(data.__len__() + 2)
    fig.set_figheight(7)
    xax = ax.xaxis
    xlabels = xax.get_ticklabels()

    for label in xlabels:
        label.set_rotation(75)
    if data.__len__() < 5:
        monthName = 'месяца'
    else:
        monthName = 'месяцев'

    plt.title(f'Средний курс {currency} за {data.__len__()} {monthName} ({howMany} дней)')
    plt.savefig(f'{IMAGE_PATH}{userID}.png')
    return f'{IMAGE_PATH}{userID}.png'
async def searchBook(message: types.Message, state: FSMContext):
    if '|' in message.text:
        show = message.text.lower().split(' |')[0]
        data = await state.get_data()
        ret = isNameInSearch(show, data)
        if ret == -1:
            await message.answer('Выберите книгу из списка результатов')
        else:
            txt = f"Книга: <b>{data[ret][1].title()}</b>\n" \
                  f"Автор: <b>{data[ret][2].title()}</b>\n\n" \
                  f"Аннотация: {data[ret][3]}"
            await message.answer(text=txt, reply_markup=bookItemMarkup(data[ret][6][0]))
    else:
        whatSearch = ' '.join(message.text.lower().split())
        data = db.getFromDB('books', '*', where=f"name like '%{whatSearch}%'",
                            orderBy='order by array_length(links,2) desc')
        if data.__len__() == 0:
            await message.answer('Ничего не нашел😥')
        else:
            await message.answer('Вот, что я нашел 📚', reply_markup=bookMarkup(data))
            await state.set_data(data)
Beispiel #8
0
 def setMainCity(self, cityLink):
     idCity = db.getFromDB('citylist', 'id', f"link='{cityLink}'")[0][0]
     self.location = idCity
     db.update('users', 'location', idCity, f'id={self.id}')
Beispiel #9
0
 def getSearchQuery(self):
     data = db.getFromDB('citylist', '*', f"id={self.location}")[0]
     return convertToAdd(data)
Beispiel #10
0
 def getMainCity(self):
     result = db.getFromDB('users', 'citylist.*', f'users.id={self.id}',
                           'JOIN citylist ON citylist.id = users.location')
     return result[0][1].title()