示例#1
0
def get_forecast(message, place, n, lang_num=None):
    if not lang_num: lang_num = language_define(message)
    name = name_define(n, lang_num)
    try:
        coords = get_coords(message, place)
        
        town = coords[0]
        if len(coords) == 3: latitude, longitude = coords[1:]

        if lang_num == 0: town = translate(town, lang_num)

        weather_inf = get_inf(lang_num, latitude, longitude)
        precipType, summary, search_term, inf = get_main_parts(n, lang_num, town, weather_inf, name)
        bot.send_message(message.chat.id, inf)

        thumbnail_url = get_photo(message, search_term)
        poem = get_poem(message, precipType, summary, search_term)
    except Exception as e:
        town = place
        poem = ''
        thumbnail_url = ''
        inf = '' 
        bot.send_message(message.chat.id, take_phrase_2('errors', 'top_error', lang_num))
         
    try:      
        check_user(message)
        check_user_all(message)
        query_add(message, name, town, inf, thumbnail_url, poem)    
    except Exception as e:
        report_error(e)

    weather_menu(message)
示例#2
0
def get_users_all(message):
    lang_num = language_define(message)
    num_of_users = make_query(
        'select count(*) from (select Tel_ID from Users_new)')[0][0]

    answer = f"{take_phrase_2('stat_answers', 'users_all', lang_num)}{num_of_users}"
    bot.send_message(message.chat.id, answer)

    try:
        query_add_stat(message, phrases['stat_db']['users_all'], answer)
        check_user(message)
        check_user_all(message)
    except Exception as e:
        report_error(e)
示例#3
0
def get_query_all(message):
    lang_num = language_define(message)
    queries = (make_query('''select count(*) from (select * from Queries); '''))[0][0]
    queries_s = (make_query('''select count(*) from (select * from Queries_stat);'''))[0][0]

    answer = f"{take_phrase_2('stat_answers', 'requests_all', lang_num)}{queries+queries_s}"
    bot.send_message(message.chat.id, answer)

    try:
        query_add_stat(message, phrases['stat_db']['requests_all'], answer)
        check_user(message)
        check_user_all(message)
    except Exception as e:
        report_error(e)
示例#4
0
def get_query_today(message):
    lang_num = language_define(message)
    Time_d = date_time('date')
    queries = (make_query('''select count(*) from (select * from Queries where Time_d=?); ''', (Time_d, )))[0][0]
    queries_s = (make_query('''select count(*) from (select * from Queries_stat where Time_d=?); ''', (Time_d, )))[0][0]
    answer = take_phrase_2('stat_answers', 'requests_today', lang_num)+str(queries+queries_s)
    bot.send_message(message.chat.id, answer)

    try:
        query_add_stat(message, phrases['stat_db']['requests_today'], answer)
        check_user(message)
        check_user_all(message)
    except Exception as e:
        report_error(e)
示例#5
0
def get_users_today(message):
    lang_num = language_define(message)
    Time = date_time('date')

    query = make_query(
        '''select distinct Tel_ID from Users_All_new where Time=?; ''',
        (Time, ))

    people = set()
    for user in query:
        people.add(user[0])

    answer = f"{take_phrase_2('stat_answers', 'users_today', lang_num)}{len(people)}"
    bot.send_message(message.chat.id, answer)

    try:
        query_add_stat(message, phrases['stat_db']['users_today'], answer)
        check_user(message)
        check_user_all(message)
    except Exception as e:
        report_error(e)
示例#6
0
def inline(c):
    if c.data == 'Подробнее':
        bot.edit_message_text(chat_id=c.message.chat.id, message_id=c.message.message_id, text=phrases['game']['advanced_rules'], parse_mode='Markdown')
    elif c.data == 'Информация':
        c_req = (c.message.text).strip().split()
        town = c_req[-1]

        if len(c_req) == 5: town = f'{c_req[3]}_{c_req[4]}'
        elif len(c_req) == 2: town =  f'{c_req[0]}_{c_req[1]}'

        db_inf = make_query('select inf from Inf_towns where town=?', (town, ))
        
        if len(db_inf) != 0:
            text = db_inf[0][0]
        else:
            req = requests.get(f'https://ru.wikipedia.org/wiki/{town}').text
            soup = BeautifulSoup(req, 'html.parser')
            all_p = soup.find_all('p')
            try:
                inf_extra = (all_p[0]).text
                if 'отпатрулирована' in inf_extra: inf_extra = (all_p[1]).text
                inf_extra = inf_extra.strip().split()
                inf = ''
                
                for j in range(2):
                    for part in inf_extra:
                        l, r = part.find('['), part.find(']')
                        if l != -1: part = part.replace(part[l:r+1], '')
                        inf += f'{part} '

                if 'фамилия' in inf or 'населённых пунктов' in inf: raise Exception
                else: text = phrases['game']['all_inf'].format(inf, town)

                make_query(f'insert into Inf_towns (town, inf) values ("{town}", "{text}")')
            
            except Exception:
                text = phrases['game']['no_inf'].format(' '.join(town.split('_')), town)
                
        bot.edit_message_text(chat_id=c.message.chat.id, message_id=c.message.message_id, text=text, parse_mode='Markdown')
        
    elif 'Больше' in c.data or 'More' in c.data:
        _, lang_num, town, date = (c.data).split('&')
        lang_num, date = int(lang_num), list(map(int, date.split('-')))
        date = datetime.date(day=date[2], month=date[1], year=date[0])
        n = (date - datetime.date.today()).days
        
        try:
            coords = get_coords(c.message, town)
            town = coords[0]
            if len(coords) == 3: latitude, longitude = coords[1:]
            name = name_define(n, lang_num)
            weather_inf = get_inf(lang_num, latitude, longitude)   
            precipType_ru, summary, search_term, inf = get_main_parts(n, lang_num, town, weather_inf, name)

            bot.edit_message_text(chat_id=c.message.chat.id, message_id=c.message.message_id, text=inf, parse_mode='Markdown')
            
        except Exception as e:
            bot.edit_message_text(chat_id=c.message.chat.id, message_id=c.message.message_id, text=take_phrase_2('errors', 'top_error', lang_num))
            inf = ''
        try:
            check_user(c.message)
            check_user_all(c.message)
            query_add(c.message, name, town, inf, '', '')
        except Exception as e:
            report_error(e) 

    elif 'Get weather' in c.data or 'Получить погоду' in c.data:
        address = c.data.strip().split('|')[-1]
        if address != 'None': weather_0(c.message, address, lang_num=0 if 'Get' in c.data else 1)
        else: preparing_0(c.message, c.data)

    elif 'Get statistics'  in c.data or 'Получить статистику' in c.data:
        lang_num = 0 if 'Get' in c.data else 1
        text = take_phrase_1('stats_text_pq_2', lang_num)
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        markup.row(take_phrase_2('statistic', 'today_users', lang_num), take_phrase_2('statistic', 'today_requests', lang_num))
        markup.row(take_phrase_1('back_menu', lang_num), take_phrase_1('back_start', lang_num))
        bot.send_message(c.message.chat.id, text, reply_markup=markup)         
    else:
        bot.send_message(c.message.chat.id, 'C Error')
示例#7
0
def weather_week(message, adress=None):

    place = adress if adress else message.text
    lang_num = language_define(message)

    try:
        coords = get_coords(message, place)
        town = coords[0]
        if len(coords) == 3: latitude, longitude = coords[1:]

        if lang_num == 0: town = translate(town, lang_num)

        weather_inf = get_inf(lang_num, latitude, longitude)

        full_inf = ''
        date = datetime.date.today() - datetime.timedelta(days=1)

        type_str = take_character_1('type', lang_num)
        temperature_max_str = take_character_2('temperature', 'max', lang_num)
        temperature_min_str = take_character_2('temperature', 'min', lang_num)

        for n in range(8):
            date += datetime.timedelta(days=1)
            try:
                subjects = weather_inf['daily']['data'][n]

                summary = subjects['summary']

                keys_ = subjects.keys()
                precipType = subjects[
                    'precipType'] if 'precipType' in keys_ else ''
                if (lang_num == 1 and precipType):
                    precipType = translate(precipType)
                temperatureHigh = round(
                    5 / 9 * (subjects['temperatureHigh'] -
                             32)) if 'temperatureHigh' in keys_ else ''
                temperatureLow = round(
                    5 / 9 * (subjects['temperatureLow'] -
                             32)) if 'temperatureLow' in keys_ else ''
                inf = f'{date}, {town}:\n{summary}{type_str}{precipType}\
                        {"%s%s°C" % (temperature_max_str, temperatureHigh) if temperatureHigh else ""}\
                        {"%s%s°C" % (temperature_min_str, temperatureLow) if temperatureLow else ""}'

                keyboard = types.InlineKeyboardMarkup()
                keyboard.add(*[
                    types.InlineKeyboardButton(
                        text=word,
                        callback_data=f'{word}&{lang_num}&{town}&{date}')
                    for word in [take_phrase_1('more', lang_num)]
                ])
                bot.send_message(message.chat.id, inf, reply_markup=keyboard)
            except KeyError:
                inf = f'{date} {town}:\n{language_1("errors", "top_0_error", lang_num)}'
                bot.send_message(message.chat.id, inf)
            full_inf += inf

    except Exception as e:
        town = place
        full_inf = ''
        bot.send_message(message.chat.id,
                         take_phrase_2('errors', 'top_error', lang_num))

    try:
        check_user(message)
        check_user_all(message)
        query_add(message, 'Неделя', town, full_inf, '', '')
    except Exception as e:
        report_error(e)
    weather_menu(message)
示例#8
0
def weather(message, adress=None):

    place = adress if adress else message.text
    lang_num = language_define(message)

    try:
        coords = get_coords(message, place)
        town = coords[0]
        if len(coords) == 3: latitude, longitude = coords[1:]

        weather_inf = get_inf(lang_num, latitude, longitude)

        subjects = weather_inf['currently']

        summary = subjects['summary']
        humidity = round(subjects['humidity'] * 100)
        windSpeed = round(subjects['windSpeed'] * 0.447)
        windGust = round(subjects['windGust'] * 0.447)
        pressure = round(subjects['pressure'] * 0.75006)
        time = datetime.datetime.now(tz=None)
        time = str((time + datetime.timedelta(hours=3)
                    ) if lang_num == 1 else time).split('.')[0]
        current_time = take_phrase_2('weather', 'now', lang_num)
        time_name = take_character_2('time_all', 'time', lang_num)
        temperature_name = take_character_2('temperature', 'usual', lang_num)
        temperature_feeling_name = take_character_2('temperature', 'feeling',
                                                    lang_num)

        timezone, precipType_name, humidity_name, wind_name, wind_max_name, wind_unit, pressure_name, pressure_unit, visibility_name, visibility_unit = words(
            lang_num)

        if lang_num == 0: town = translate(town, lang_num)

        keys_ = subjects.keys()

        precipType = subjects['precipType'] if 'precipType' in keys_ else ''
        if lang_num == 1 and precipType: precipType = translate(precipType)

        temperature = round(
            5 / 9 *
            (subjects['temperature'] - 32)) if 'temperature' in keys_ else ''
        apparentTemperature = round(
            5 / 9 * (subjects['apparentTemperature'] -
                     32)) if 'apparentTemperature' in keys_ else ''

        visibility = round(subjects['visibility'] *
                           1.61, 1) if 'visibility' in keys_ else ''

        search_term = f'{town} {precipType}'

        inf = f'{current_time}, {town}:{time_name}{time}{timezone}\n{summary}{precipType_name}{precipType}\
                {humidity_name}{humidity}%{"%s%s°C" % (temperature_name, temperature) if temperature else ""}\
                {"%s%s°C" % (temperature_feeling_name, apparentTemperature) if apparentTemperature else ""}\
                {wind_name}{windSpeed}{wind_unit}{wind_max_name}{windGust}{wind_unit}\
                {pressure_name}{pressure}{pressure_unit}{visibility_name}{visibility}{visibility_unit}'

        bot.send_message(message.chat.id, inf)

        thumbnail_url = get_photo(message, search_term)
        poem = get_poem(message, precipType, summary, search_term)

    except Exception as e:
        town = place
        inf = ''
        thumbnail_url = ''
        poem = ''
        bot.send_message(message.chat.id,
                         take_phrase_2('errors', 'top_error', lang_num))

    try:
        check_user(message)
        check_user_all(message)
        query_add(message, 'Сейчас', town, inf, thumbnail_url, poem)
    except Exception as e:
        report_error(e)

    weather_menu(message)