def search_cheaper(message): if len(message.text.split('/search_cheaper')[1]) > 1: object_search = message.text.split('/search_cheaper')[1] url = 'https://www.amazon.es/s/ref=sr_st_price-asc-rank?keywords=' + object_search.encode( encoding='utf-8', errors='strict' ) + '&rh=i%3Aaps%2Ck%3Afundas&__mk_es_ES=%C3%85M%C3%85Z%C3%95%C3%91&qid=1540914465&sort=price-asc-rank' response = requests.get(url) list_response_products = [] soup = BeautifulSoup(response.content) products = soup.find("ul", {"id": "s-results-list-atf"}) list_products = products.find_all("li") for product in list_products: price = product.find( "span", {"class": "a-size-base a-color-price s-price a-text-bold"}) if hasattr(price, 'text'): price = price.text url = product.find("a", {"a-link-normal a-text-normal"}) url = url['href'] list_response_products.append({'url': url, 'price': price}) html = '' for product_response in list_response_products: html += ' Precio: %s \n Url: %s ' % ( product_response['price'], product_response['url'], ) bot.send_message(message.chat.id, html, parse_mode="HTML") else: bot.send_message(message.chat.id, 'Por favor, escribe /search_cheaper Producto', parse_mode="HTML")
def nextLaunch(message): r = requests.get('https://api.spacexdata.com/v3/rockets/falcon9') pipo = json.loads(r.content) a = RocketInfo(pipo) bot.send_message(message.chat.id, a.imprimir())
def search(message): #import ipdb; ipdb.set_trace() if len(message.text.split('/search')[1]) > 1: object_search = message.text.split('/search')[1] url = 'https://www.amazon.es/s/ref=nb_sb_noss_1?__mk_es_ES=ÅMÅŽÕÑ&url=search-alias%3Daps&field-keywords=' + object_search.encode( 'utf-8') response = requests.get(url) list_response_products = [] soup = BeautifulSoup(response.content) products = soup.find("ul", {"id": "s-results-list-atf"}) list_products = products.findAll("li") for product in list_products: price = product.find( "span", {"class": "a-size-base a-color-price s-price a-text-bold"}) if hasattr(price, 'text'): price = price.text url = product.find("a", {"a-link-normal a-text-normal"}) url = url['href'] list_response_products.append({'url': url, 'price': price}) html = '' for product_response in list_response_products: html += ' Precio: %s \n Url: %s ' % ( product_response['price'], product_response['url'], ) bot.send_message(message.chat.id, html, parse_mode="HTML") else: bot.send_message(message.chat.id, 'Por favor, escribe /search Producto', parse_mode="HTML")
def departments(message): response = requests.get( "https://www.amazon.es/gp/site-directory?ref=nav_shopall_btn", allow_redirects=True) soup = BeautifulSoup(response.content) categories = soup.findAll("h2", {"class": "popover-category-name"}) click_kb = InlineKeyboardMarkup() list_categories = [] i = 0 for category in categories: i += 1 name_category = category.get_text() click_button = InlineKeyboardButton(name_category, callback_data='parent_' + name_category) list_categories.append(click_button) if i % 2 == 0: click_kb.row(*list_categories) list_categories = [] bot.send_message( message.chat.id, "<b>Aquí se muestran todos los departamentos de Amazon...</b>", parse_mode="HTML", reply_markup=click_kb, disable_web_page_preview=True)
def search_author(message): if len(message.text.split('/search_author')[1]) > 1: object_search = message.text.split('/search_author')[1] url = 'http://openlibrary.org/search.json?author=' + object_search resp = requests.get(url).json() docsDictionary = resp['docs'] click_kb = InlineKeyboardMarkup() list_titles = [] i = 0 for doc in docsDictionary: title = doc['title'] i += 1 """ bot.send_message(message.chat.id, doc['title'], parse_mode="HTML") """ click_button = InlineKeyboardButton(title, callback_data='parent_' + title) list_titles.append(click_button) if i % 2 == 0: click_kb.row(*list_titles) list_titles = [] bot.send_message(message.chat.id, "Aquí se muestran todos los titulos de " + object_search.encode('utf-8'), reply_markup=click_kb, disable_web_page_preview=True) else: bot.send_message(message.chat.id, 'Por favor, escribe /search_author "autor"', parse_mode="HTML")
def roadster(message): r = requests.get('https://api.spacexdata.com/v3/roadster') print(r.status_code) pipo = json.loads(r.content) a = Roadster(pipo) bot.send_message(message.chat.id, a.imprimir())
def getanswer(cid, rcid): keyboard = types.InlineKeyboardMarkup(row_width=2) keyboard.add(types.InlineKeyboardButton("Si", callback_data=rcid), types.InlineKeyboardButton("No", callback_data="no") ) bot.send_message(cid, "Alguien necesita un sitio ¿se lo guardas?", reply_markup=keyboard)
def getlocation(message): keyboard = types.InlineKeyboardMarkup(row_width=2) keyboard.add(types.InlineKeyboardButton("Rabanales", callback_data="BRabanales"), types.InlineKeyboardButton("Medicina y Enfermeria", callback_data="BMedicinaEnfermeria"), types.InlineKeyboardButton("Ciencias de la Educacion", callback_data="BCienciasEducacion"), types.InlineKeyboardButton("Derecho", callback_data="BDerecho"), types.InlineKeyboardButton("Filosofia y Letras", callback_data="BFilosofiaLetras"), types.InlineKeyboardButton("General", callback_data="BGeneral") ) bot.send_message(message.chat.id, "¿En que biblioteca?", reply_markup=keyboard)
def load(message): """ Recupera un dato guardado con save """ users = User.get_all() if len(users) > 0: for user in users: bot.send_message( message.chat.id, "user: %s\n place: %s\n status: %s" % ( user.cid, user.place, user.status, )) else: bot.reply_to(message, "not users")
def summoner(message): name = util.extract_arguments(message.text) if not name: bot.send_message(message.chat.id, "Especifique un nombre de invocador") else: cid = chat_id = message.chat.id region = Chat.get_config(cid, "region") if region is None: bot.send_message( message.chat.id, "Utiliza /region para seleccionar una region primero") else: url = 'https://' + region.value + '.api.riotgames.com/lol/summoner/v4/summoners/by-name/' + name params = {'api_key': RIOT_KEY} r = requests.get(url, params) if (r.status_code in range(200, 299)): #Request accepted content = r.json() summonerId = content["id"] url = 'https://' + region.value + '.api.riotgames.com/lol/league/v4/positions/by-summoner/' + summonerId r = requests.get(url, params) contentLeague = r.json() text = "*Nombre:* " + str( content["name"]) + "\n*Nivel:* " + str( content["summonerLevel"]) + "\n" text += "*SoloQ:* " + contentLeague[0][ "tier"] + " " + contentLeague[0]["rank"] + " -> " + str( contentLeague[0]["leaguePoints"]) + " LP\n" text += " *Victorias:* " + str( contentLeague[0]["wins"]) + "\n" text += " *Derrotas:* " + str( contentLeague[0]["losses"]) + "\n\n" url = 'https://' + region.value + '.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/' + summonerId r = requests.get(url, params) contentChamp = r.json() champ = "" with open('champion.json') as json_file: file = json.load(json_file) champion_list = file['data'] for champion_name in champion_list.keys(): if champion_list[champion_name]['key'] == str( contentChamp[0]["championId"]): champ += champion_list[champion_name]['name'] text += "*Mejor campeón:* " + champ bot.send_message(message.chat.id, text, parse_mode="Markdown") else: #Request error bot.send_message(message.chat.id, "Invocador desconocido")
def load(message): chat_id = message.chat.id data = Song.get_config(chat_id, 'memory') if not data: bot.reply_to(message, "Aún no has guardado nada") return songsMessage = "" for song in data: songTitle = song.title songArtist = song.artist songAlbum = song.album songInfo = "- " + songTitle + " | " + songArtist + " | " + songAlbum + "\n" songsMessage = songsMessage + songInfo.encode('utf-8') + "\n" messageToSend = "*Canciones que has buscado:*\n\n" + songsMessage bot.send_message(message.chat.id, messageToSend, parse_mode="markdown")
def game_process_response(message): chat_id = message.chat.id number = int(Chat.get(chat_id, 'game_number')) steps = int(Chat.get(chat_id, 'game_steps')) guess_number = int(message.text) if (number == guess_number): bot.send_message(chat_id, f"Enhorabuena has acertado en {steps} pasos") return if (guess_number > number): reply = bot.send_message(chat_id, "El número es más pequeño") else: reply = bot.send_message(chat_id, "El número es más grande") Chat.set(chat_id, "game_steps", 1 + steps) bot.register_next_step_handler(reply, game_process_response)
def game_play(message): chat_id = message.chat.id reply = bot.send_message(chat_id, "Adivina el número que he pensado del 1 al 100") number = randint(1, 10) Chat.set(chat_id, "game_number", number) Chat.set(chat_id, "game_steps", 1) bot.register_next_step_handler(reply, game_process_response)
def searchCategory(message): if len(message.text.split('/search_category')[1]) > 1: object_search = message.text.split('/search_category')[1] subject= object_search #selecionar por menus la que sea url = "https://openlibrary.org/subjects/"+subject+".json?limit=50" response = requests.get(url).json() works_diccionary=response['works'] for i in range(0,10): x= random.randrange(50) if 'authors' in works_diccionary[x]: bot.send_message ("Titulo:" + works_diccionary[x]['title'] ) bot.send_message ("Autor:" + works_diccionary[x]['authors'][0]['name']+'\n') else: bot.send_message ("Titulo:" + works_diccionary[x]['title'] + " Autor: Desconocido") bot.send_message ("Autor: Desconocido"+'\n') else: bot.send_message(message.chat.id, "Por favor, escribe /search_category categoría")
def region_board(message): keyboard = types.InlineKeyboardMarkup(row_width=2) keyboard.add( types.InlineKeyboardButton("br", callback_data="b1"), types.InlineKeyboardButton("eune", callback_data="eun1"), types.InlineKeyboardButton("euw", callback_data="euw1"), types.InlineKeyboardButton("pj", callback_data="jp1"), types.InlineKeyboardButton("kr", callback_data="kr"), types.InlineKeyboardButton("lan", callback_data="la1"), types.InlineKeyboardButton("las", callback_data="la2"), types.InlineKeyboardButton("na", callback_data="na1"), types.InlineKeyboardButton("oce", callback_data="oc1"), types.InlineKeyboardButton("tr", callback_data="tr1"), types.InlineKeyboardButton("ru", callback_data="ru"), types.InlineKeyboardButton("pbe", callback_data="pbe1"), ) bot.send_message(message.chat.id, "¿en que región estás?", reply_markup=keyboard)
def searchTitle(message): if len(message.text.split('/search_title')[1]) > 1: object_search = message.text.split('/search_title')[1] bookname_list = list(object_search) for index, letra in enumerate(bookname_list): if re.match(" ", letra): bookname_list[index] = "+" bookname = ''.join(bookname_list) books_dic = requests.get('http://openlibrary.org/search.json?q=' + bookname).json() docs_dic = books_dic['docs'] for doc in docs_dic: url = 'URL: https://openlibrary.org'+doc['key'] if 'author_name'in doc: if 'publish_date' in doc: author = "".join(doc['author_name']) author = re.sub(r"(?<=\w)([A-Z])", r"|\1", author) bot.send_message (doc['title'] + " - " + author ) bot.send_message ('Publish date: ' + doc['publish_date'][0]) bot.send_message (url) bot.send_message('\n') elif 'publish_date' in doc: if 'author_name' not in doc: bot.send_message (doc['title'] + " - " + "Unknown Author") bot.send_message ('Publish date: ' + doc['publish_date'][0]) bot.send_message (url) bot.send_message('\n') else: bot.send_message (doc['title'] + " - " + "Unknown Author") bot.send_message ('Publish date: Unknown') bot.send_message (url) bot.send_message('\n') else: bot.send_message(message.chat.id, "Por favor, escribe /search_title titulo")
def userDec(ans): if ans.data != "no": bot.send_message(ans.data, "Aceptado!")
def recognize_song(message): bot.reply_to(message, "⚙️ Procesando tu audio...", parse_mode="Markdown") fileId = message.voice.file_id getPathRequest = requests.get('https://api.telegram.org/bot' + TOKEN + '/getFile?file_id=' + fileId) if getPathRequest.status_code == 200: path = getPathRequest.json()['result']['file_path'] rawFileRequest = requests.get('https://api.telegram.org/file/bot' + TOKEN + '/' + path) if rawFileRequest.status_code == 200: fileKey = str(uuid.uuid4()) upload = s3.Bucket('musictelegram').put_object( Key=fileKey, Body=rawFileRequest.content, ACL='public-read') bucket_location = s3Client.get_bucket_location( Bucket='musictelegram') object_url = "http://s3-{0}.amazonaws.com/{1}/{2}".format( bucket_location['LocationConstraint'], 'musictelegram', fileKey) method = "recognizeWithOffset/" if humming_mode else "" getSongInfo = requests.get('https://api.audd.io/' + method + '?api_token=' + AUDD_API_TOKEN + '&url=' + object_url) if getSongInfo.status_code == 200: songInfo = getSongInfo.json()['result'] if songInfo: if humming_mode: if songInfo['count']: predictionList = songInfo['list'] bot.send_message( message.chat.id, "Tu canción puede ser una de estas:") for prediction in predictionList: title = None artist = None album = None score = None if prediction.has_key('title'): title = prediction['title'] if prediction.has_key('artist'): artist = prediction['artist'] if prediction.has_key('album'): album = prediction['album'] if prediction.has_key('score'): score = prediction['score'] bot.send_message(message.chat.id, get_song_info( title, artist, album, score).encode('utf-8'), parse_mode="Markdown") else: bot.reply_to( message, "Lo has hecho fatal, intenta tararear de nuevo." ) else: songTitle = songInfo['title'] songArtist = songInfo['artist'] songAlbum = songInfo['album'] messageToSend = "Tu cancion es:\n" + get_song_info( songTitle, songArtist, songAlbum) bot.send_message(message.chat.id, messageToSend, parse_mode="Markdown") spotifySearch = spotify.search( q='track:' + songTitle.encode('utf-8'), type='track') if (len(spotifySearch)): spotifyURL = spotifySearch['tracks']['items'][0][ 'external_urls']['spotify'] bot.send_message(message.chat.id, "*URL Spotify:* " + spotifyURL, parse_mode="Markdown") Song.set_config(message.chat.id, 'memory', songTitle, songAlbum, songArtist) else: bot.reply_to( message, "No se ha podido reconocer ninguna canción. Inténtalo de nuevo." ) else: bot.reply_to(message, "Error de reconocimiento de audio.") else: bot.reply_to(message, "Error procesando tu audio. Intentalo de nuevo.") else: bot.reply_to(message, "Error procesando tu audio. Intentalo de nuevo.")
else: bot.send_message(message.chat.id, "Por favor, escribe /search_title titulo") @bot.message_handler(commands = ['search_category']) def searchCategory(message): if len(message.text.split('/search_category')[1]) > 1: object_search = message.text.split('/search_category')[1] subject= object_search #selecionar por menus la que sea url = "https://openlibrary.org/subjects/"+subject+".json?limit=50" response = requests.get(url).json() works_diccionary=response['works'] for i in range(0,10): x= random.randrange(50) if 'authors' in works_diccionary[x]: bot.send_message ("Titulo:" + works_diccionary[x]['title'] ) bot.send_message ("Autor:" + works_diccionary[x]['authors'][0]['name']+'\n') else: bot.send_message ("Titulo:" + works_diccionary[x]['title'] + " Autor: Desconocido") bot.send_message ("Autor: Desconocido"+'\n') else: bot.send_message(message.chat.id, "Por favor, escribe /search_category categoría") @bot.message_handler(commands = ['help']) lista_cat = ["love","science","art","biographies","fantasy","romance","religion","recipes", "mystery","music", "medicine","history", "chilcren","sci-fi"] bot.send_message(lista_cat)
def start(message): bot.reply_to(message, 'Hello, ' + message.from_user.first_name) lista_cat = ["love","science","art","biographies","fantasy","romance","religion","recipes", "mystery","music", "medicine","history", "chilcren","sci-fi"] bot.send_message("Categorías disponibles: " + lista_cat)