def subscribe(): if data.get_field(connection=connection, table_name="Status", select_field="subscribe", field="id_vk", value=id)[0][0] == False: data.set_field(connection=connection, table_name="Status", ID_VK=id, field="subscribe", value="1") vk.method("messages.send", { "user_id": id, "message": "Теперь ты подписан на уведомления" }) else: data.set_field(connection=connection, table_name="Status", ID_VK=id, field="subscribe", value="0") vk.method("messages.send", { "user_id": id, "message": "Теперь ты отписан от уведомлений" }) use_menu(status=data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id)[0][0])
def get_target_playlist(date: dt, client: spotipy.Spotify, user: str) -> str: """ ASSUMPTIONS: a user has no duplicate playlist names In the case that a user has a duplicate playlist name, the script will modify the one 'lower' in the user's playlist library Solution: no intuitive workaround """ # december of 2019 looks for playlist "winter 2020" target_playlist_name = get_current_season(date) + " " + str( date.year if date.month != 12 else date.year + 1) chunk, offset = 50, 0 all_playlists = {} # Case 1: Playlist is cached and playlist is current season # Good, use it # Case 2: Playlist is cached but playlist is out of season # Make a new playlist and cache it # Case 3: Playlist isnt cached # Look for it playlist_id = "" try: playlist_id = database.get_field(user, "last_playlist") # case 1 if playlist_id != '' and client.playlist( playlist_id)["name"] == target_playlist_name: return playlist_id # case 2 else: resp = client.user_playlist_create( client.me()['id'], target_playlist_name, public=False, description= 'AUTOMATED PLAYLIST - https://github.com/turrence/spotify-new-music-sorter' ) return resp['id'] except KeyError as e: # case 3: do nothing, it's not cached, hopefully this is rare pass while True: playlist_info = client.current_user_playlists(chunk, offset) for item in playlist_info['items']: all_playlists[item['name']] = item['id'] if len(all_playlists) >= playlist_info['total']: break else: offset += chunk if target_playlist_name not in all_playlists: resp = client.user_playlist_create( client.me()['id'], target_playlist_name, public=False, description= 'AUTOMATED PLAYLIST - https://github.com/turrence/spotify-new-music-sorter' ) return resp['id'] else: return all_playlists[target_playlist_name]
def create_msgs(news, vk, id): msg = "" msgs = [] date = data.get_field(connection=connection, table_name="USERS", select_field="LAST_NEWS", field="ID", value=id)[0][0] date_last_news = news[0]["NEWS_DATE"][0:10] + " " + news[0]["NEWS_DATE"][ 11:len(news[0]["NEWS_DATE"])] for one_news in news: date_news = one_news["NEWS_DATE"][0:10] + " " + one_news["NEWS_DATE"][ 11:len(one_news["NEWS_DATE"])] print(date) print(date_news) if str(date) < date_news: if len(msg) < 3500: msg = msg + "Статья: " + one_news[ 'TITLE'] + "\nПосмотреть можно здесь: " + one_news[ 'URL'] + "\n \n" else: msgs.append(msg) msg = "" msgs.append(msg) if str(date) < date_last_news: data.set_complex_str_in_field(connection=connection, table_name="USERS", ID_VK=id, field="LAST_NEWS", value=date_last_news) return msgs
def send_shedule(body): user_id = body["object"]["message"]["from_id"] today = str(datetime.datetime.today().date()) fields = database.get_field(today) message = "Рассписание на " + today + ":\n\n" print(fields) for field in fields: message += "Тренировка: " + field[4] + ";\n" message += "Тренер: " + field[1] + ";\n" message += "Время: " + field[2] + " " + field[3] + ";\n\n" send_keyboard(body, message)
def update_clients(): """ Refreshes the access tokens and updates the playlists for all clients in the cache """ for user in db.get_users(): if db.get_field(user, "active") != "false": print("updating", user) oauth = spotipy.oauth2.SpotifyOAuth( scope=constant.SCOPE, cache_handler=DatabaseCacheHandler(user), client_id=config.client_id, client_secret=config.client_secret, redirect_uri=config.redirect_uri) try: client = spotipy.Spotify(auth_manager=oauth) playlist.update_playlist(client, user) # reset the users error count if an update was successful db.update_user(user, "error_count", 0) except SpotifyException as e: # we hit a rate limit wait 60 seconds and retry if e.code == 429: time.sleep(60) try: playlist.update_playlist(client) except Exception as e: log_error_to_database(user, e) else: log_error_to_database(user, e) except Exception as e: log_error_to_database(user, e) # if a user passes a certain error threshold, mark them as # inactive, they probably revoked our access if db.get_field(user, "error_count") > constant.ERROR_THRESHOLD: try: db.update_user(user, "active", "false") except Exception: print("Could not set user to inactive")
def search_subject(id, connection, table_name, flag): mas = [ "russian", "math", "biology", "geography", "foreign_language", "informatics", "history", "literature", "social_science", "physics", "chemistry" ] for i in mas: if data.get_field(connection=connection, table_name=table_name, select_field=i, field="id_vk", value=id)[0][0] == int(flag): return i return 0
def add_subject(id, connection, field, know_points): if data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id)[0][0] == True: if know_points == "yes": vk.method( "messages.send", { "user_id": id, "message": "Введи баллы:" } ) #убрал клавиатуру, тк можно нажать Главное меню и в базе останется -2 data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field=field, value=WAIT_FILLING) else: vk.method( "messages.send", { "user_id": id, "message": "Выбор сделан", "keyboard": keyboard_exams } ) #убрал клавиатуру, тк можно нажать Главное меню и в базе останется -2 data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field=field, value=TEMP_FILLING) else: vk.method( "messages.send", { "user_id": id, "message": 'Предмет добавлен в список', "keyboard": keyboard_exams }) data.set_field(connection=connection, table_name="Schoolchildren", ID_VK=id, field=field, value=True)
def data_processing(id, pay, msg): if data.search_field(table_name="USERS",connection=connection,value=id, field="ID")==False: data.set_user(table_name="USERS", connection=connection,ID_VK=id) if pay=={"command":"start"} or pay == "admin": vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("START"))[0]}) vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("HELP_MSG"))[0], "keyboard": get_main_keyboard(id =id, connection = connection)}) elif msg=="admin": vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ADMIN"))[0], "keyboard":key['start']}) elif pay == "main_menu": vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("MAIN_MENU"))[0], "keyboard":get_main_keyboard(id =id, connection = connection)}) elif pay=="subscribe": if data.get_field(connection=connection, table_name="USERS",select_field = "SUBSCRIBE", field="ID", value=id)[0][0]==False: print("tut") data.set_field(connection = connection, table_name = "USERS", ID_VK = id, field = "SUBSCRIBE", value = 1) vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("SUBSCRIBE"))[0], 'keyboard': get_main_keyboard(id =id, connection = connection)}) else: data.set_field(connection = connection, table_name = "USERS", ID_VK = id, field = "SUBSCRIBE", value = 0) vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("UNSUBSCRIBE"))[0], 'keyboard': get_main_keyboard(id =id, connection = connection)}) elif pay=="direction_selection": vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("DIRECTION_SELECTION"))[0], "keyboard":key['direction_selection']}) elif pay=="sphere": sql = "DELETE FROM USERS_SPHERES WHERE ID_USER = "******"messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("SPHERE"))[0], "keyboard":key['sphere']}) elif pay=="Машиностроение" or pay=="Безопасность" or pay=="Энергетика" or pay=="IT-технологии" or pay=="Электроника" or pay=="Авиация" or pay=="Общество" or pay=="Экономика" or pay=="Химия" or pay=="Языки" or pay=="Физика": sql = "SELECT ID_SPHERE FROM USERS_SPHERES WHERE ID_USER = "******"messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ADD_MSG"))[0], "keyboard":key['sphere']}) if len(size)+1>=3: search_direction(id = id, type = "SPHERE") else: add_sphere(id=id,connection=connection, pay = pay) vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ADD_MSG"))[0], "keyboard":key['sphere']}) elif pay=="name_dir": sql = "DELETE FROM USERS_SUBJECTS WHERE ID_USER = "******"messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("NAME_DIR"))[0], "keyboard":key['subjects']}) elif pay == "math" or pay == "biology" or pay == "geography" or pay == "foreign_language" or pay == "informatics" or pay == "history" or pay == "literature" or pay == "social_science" or pay == "physics" or pay == "chemistry": sql = "SELECT ID_SUB FROM USERS_SUBJECTS WHERE ID_USER = "******"messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ADD_MSG"))[0], "keyboard":key['subjects']}) if(len(idSub)+1>=2): search_direction(id = id, type = "SUBJECTS") else: add_sub(id = id, connection = connection, sub = pay) vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ADD_MSG"))[0], "keyboard":key['subjects']}) elif pay == "search_by_sphere": search_direction(id = id, type = "SPHERE") elif pay == "search_by_subjects": search_direction(id = id, type = "SUBJECTS") elif pay == "lists": vk.method("messages.send", {"user_id": id, "message": "Выберите функцию:", "keyboard": key['list']}) elif pay == "lk_code": vk.method("messages.send", {"user_id": id, "message": "Меня пока что этому не научили😞\nНо совсем скоро научат, обещаю!", "keyboard": get_main_keyboard(id =id, connection = connection)}) elif pay == "frequency": vk.method("messages.send", {"user_id": id, "message": "Меня пока что этому не научили😞\nНо совсем скоро научат, обещаю!", "keyboard": get_main_keyboard(id =id, connection = connection)}) elif msg == "Бу!": vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("FEAR_MSG"))[0], "keyboard": get_main_keyboard(id =id, connection = connection)}) else: vk.method("messages.send", {"user_id": id, "message": random.choice(from_pay_to_msg("ERROR"))[0], "keyboard": get_main_keyboard(id =id, connection = connection)})
def search_direction(id): res = [] sphere = data.get_field(select_field="SPHERE", table_name="Status", connection=connection, value=id, field="id_vk")[0][0] if sphere == 0: vk.method( "messages.send", { "user_id": id, "message": "Нет добавленных сфер:", "keyboard": keyboard_sphere }) if sphere < 100: res = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=sphere, field="SPHERE") elif sphere < 10000: if int(sphere / 100) > sphere % 100: sphere = (sphere % 100) * 100 + int(sphere / 100) res = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=sphere % 100, field="SPHERE") temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=int(sphere / 100), field="SPHERE") if temp != 0: for item in temp: res.append(item) temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=sphere, field="SPHERE") if temp != 0: for item in temp: res.append(item) else: a1 = int(sphere / 10000) a2 = int(sphere / 100) % 100 a3 = (sphere % 10000) % 100 print("a1 = ", a1, " a2 = ", a2, " a3 = ", a3) print("id: ", sphere) if a1 < a2 and a1 < a3: sphere = a1 * 100 if a2 < a3: sphere = (sphere + a2) * 100 + a3 else: sphere = (sphere + a3) * 100 + a2 elif a2 < a1 and a2 < a3: sphere = a2 * 100 if a1 < a3: sphere = (sphere + a1) * 100 + a3 else: sphere = (sphere + a3) * 100 + a1 elif a3 < a1 and a3 < a2: sphere = a3 * 100 if a2 < a1: sphere = (sphere + a2) * 100 + a1 else: sphere = (sphere + a1) * 100 + a2 print("new id: ", sphere) res = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=int(sphere / 10000), field="SPHERE") temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=sphere % 100, field="SPHERE") if temp != 0: for item in temp: res.append(item) temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=int(sphere / 100), field="SPHERE") if temp != 0: for item in temp: res.append(item) temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=sphere % 10000, field="SPHERE") if temp != 0: for item in temp: res.append(item) temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=int(str(sphere % 100) + str(int(sphere / 10000))), field="SPHERE") if temp != 0: for item in temp: res.append(item) temp = data.get_field( select_field="DIRECTION, PROFILE_NAME, FACULT, DESCR, URL", table_name="Directions", connection=connection, value=int((sphere % 100) / 100), field="SPHERE") if temp != 0: for item in temp: res.append(item) response = "" vk.method( "messages.send", { "user_id": id, "message": "По данным сферам найдены следуюшие направления:" }) res = list(set(res)) for item in res: if item[1] == 'null': if item[3] == 'null': response = response + "Направление: " + '"' + item[ 0] + '"' + " на факультете " + item[ 2] + "\n" + "Ссылка на направление: " + item[4] + "\n\n" else: response = response + "Направление: " + '"' + item[ 0] + '"' + " на факультете " + item[2] + "\n" + item[ 3] + "\n" + "Ссылка на направление: " + item[4] + "\n\n" else: if item[3] == 'null': response = response + "Направление: " + '"' + item[ 0] + ' (' + item[1] + ')' + '"' + " на факультете " + item[ 2] + "\n" + "Ссылка на направление: " + item[4] + "\n\n" else: response = response + "Направление: " + '"' + item[ 0] + ' (' + item[1] + ')' + '"' + " на факультете " + item[ 2] + "\n" + item[ 3] + "\n" + "Ссылка на направление: " + item[ 4] + "\n\n" vk.method("messages.send", {"user_id": id, "message": response}) vk.method( "messages.send", { "user_id": id, "message": "Искал как в последний раз:)", "keyboard": keyboard_default })
def other_event(msg): if data.get_field(connection=connection, table_name="Graduates", select_field="name", field="id_vk", value=id)[0][0] == "-2": #обрабатываем ФИО msg = "'" + msg + "'" data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field="name", value=msg) vk.method("messages.send", {"user_id": id, "message": "ФИО сохранены"}) use_cabinet(status=True) elif data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id)[0][0] == 1 and search_subject( id=id, connection=connection, table_name="Graduates", flag=WAIT_FILLING) != 0: #обрабатываем баллы try: points = int(msg) except: vk.method("messages.send", { "user_id": id, "message": "Баллы введены не верно" }) data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field=search_subject(id=id, connection=connection, table_name="Graduates", flag=WAIT_FILLING), value=0) use_exams() finally: if points >= 0 and points <= 100: data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field=search_subject(id=id, connection=connection, table_name="Graduates", flag=WAIT_FILLING), value=msg) vk.method("messages.send", { "user_id": id, "message": "Баллы учтены" }) else: vk.method("messages.send", { "user_id": id, "message": "Баллы введены не верно" }) data.set_field(connection=connection, table_name="Graduates", ID_VK=id, field=search_subject(id=id, connection=connection, table_name="Graduates", flag=WAIT_FILLING), value=0) use_exams() else: vk.method("messages.send", { "user_id": id, "message": "Используй клавиатуру. Я тебя не понимаю" }) use_menu(status=data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id)[0][0])
value="False") data.set_user(table_name="Schoolchildren", connection=connection, ID_VK=id) use_menu(status=False) elif pay == "information": vk.method( "messages.send", { "user_id": id, "message": "Что ты хочешь узнать?", "keyboard": keyboard_info }) elif pay == "cabinet": use_cabinet(status=data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id)[0][0]) elif pay == "personal_info": use_data() elif pay == "exam_points": use_exams() elif pay == "main_menu": use_menu(status=(data.get_field(connection=connection, table_name="Status", select_field="status", field="id_vk", value=id))[0][0]) elif pay == "biology" or pay == "geography" or pay == "foreign_language" or pay == "informatics" or pay == "history" or pay == "literature" or pay == "social_science" or pay == "physics" or pay == "chemistry" or pay == "russian" or pay == "math": vk.method( "messages.send", {