class Handler: def __init__(self): self.API = None self.response = None self.target_station = None self.API = RadioBrowser() def station_validator(self): if len(self.response) == 0: log.error("No stations found by the name") sys.exit(0) if len(self.response) > 1: log.info("Multiple stations found by the name") stations_name = "" for station in self.response: # stations_name = stations_name + "," + station["name"] log.info("name: {} | id: {} | country: {}".format( station["name"], station["stationuuid"], station["country"])) log.info(stations_name) sys.exit(0) if len(self.response) == 1: log.info("Station found: {}".format(self.response[0]["name"])) log.debug(self.response[0]) self.target_station = self.response[0] self.API.click_counter(self.target_station["stationuuid"]) def play_by_station_name(self, _name=None): print(_name) self.response = self.API.search(name=_name, name_exact=False) self.station_validator() def play_by_station_uuid(self, _uuid): print(_uuid) # Pyradios by default don't let you search by uuid # a trick is to call click_counter(uuid) directly to get the statioon info is_ok = "false" try: self.target_station = self.API.click_counter(_uuid) log.debug(self.target_station) is_ok = self.target_station["ok"] except Exception as e: log.error("Could not find a station by the UUID") sys.exit(0) self.API.search(name=self.target_station["name"], name_exact=True) # againg register a valid click if is_ok == "false": res = self.API.click_counter(self.target_station["stationuuid"]) log.debug(res)
def CPS_match_query_phrase(self, phrase): # Look for regex matches # Play (radio|station|stream) <data> match = re.search(self.translate_regex('radio'), phrase) try: data = re.sub(self.translate_regex('radio'), '', phrase) rb = RadioBrowser() stations = rb.search(name=data, bitrateMin='128') stations != [] self.log.info('CPS Match (radio): ' + stations[0]['name'] + ' | ' + stations[0]['url']) if match: return (stations[0]['name'], CPSMatchLevel.EXACT, { "station": stations[0]["name"], "url": stations[0]["url"], "image": stations[0]['favicon'] }) else: return (stations[0]['name'], CPSMatchLevel.TITLE, { "station": stations[0]["name"], "url": stations[0]["url"], "image": stations[0]['favicon'] }) except Exception: return None
def match_genre(phrase): """Takes the user utterance and attempts to match a genre of station, returning the most popular of that genre. :param phrase: User utterance :type phrase: str :return: A tuple containing the original phrase, the CPS.MatchLevel, and a dictionary containing the resolved stream URL. :rtype: tuple """ # Strip 'a' and 'station' from phrases like 'Play a jazz station.'. stripped_phrase = phrase.lower().replace("a ", "").replace(" station", "") try: rb = RadioBrowser() except Exception as e: LOG.exception("Failed to load pyradios" + repr(e)) LOG.info(f"Searching for a {stripped_phrase} station") results = rb.search(tag=stripped_phrase, order="votes") parsed = json.loads(json.dumps(results)) if len(parsed) > 0: LOG.info(f"Found {parsed[0]['name']} ({parsed[0]['url_resolved']})") return phrase, CPSMatchLevel.EXACT, {"url": parsed[0]["url_resolved"]} else: match_station_name(phrase)
def cmd_rb_query(bot, user, text, command, parameter): global log log.info('cmd: Querying radio stations') if not parameter: log.debug('rbquery without parameter') msg = tr('rb_query_empty') bot.send_msg(msg, text) else: log.debug('cmd: Found query parameter: ' + parameter) rb = RadioBrowser() rb_stations = rb.search(name=parameter, name_exact=False) msg = tr('rb_query_result') msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>' if not rb_stations: log.debug(f"cmd: No matches found for rbquery {parameter}") bot.send_msg(f"Radio-Browser found no matches for {parameter}", text) else: for s in rb_stations: station_id = s['stationuuid'] station_name = s['name'] country = s['countrycode'] codec = s['codec'] bitrate = s['bitrate'] genre = s['tags'] msg += f"<tr><td>{station_id}</td><td>{station_name}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>" msg += '</table>' # Full message as html table if len(msg) <= 5000: bot.send_msg(msg, text) # Shorten message if message too long (stage I) else: log.debug('Result too long stage I') msg = tr('rb_query_result') + ' (shortened L1)' msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>' for s in rb_stations: station_id = s['stationuuid'] station_name = s['name'] msg += f'<tr><td>{station_id}</td><td>{station_name}</td>' msg += '</table>' if len(msg) <= 5000: bot.send_msg(msg, text) # Shorten message if message too long (stage II) else: log.debug('Result too long stage II') msg = tr('rb_query_result') + ' (shortened L2)' msg += '!rbplay ID - Station Name' for s in rb_stations: station_id = s['stationuuid'] station_name = s['name'][:12] msg += f'{station_id} - {station_name}' if len(msg) <= 5000: bot.send_msg(msg, text) # Message still too long else: bot.send_msg( 'Query result too long to post (> 5000 characters), please try another query.', text)
def match_station_name(phrase): """Takes the user utterance and attempts to match a specific station :param phrase: User utterance :type phrase: str :return: A tuple containing the original phrase, the CPS.MatchLevel, and a dictionary containing the resolved stream URL. :rtype: tuple """ numbers_regex = r"\b(one|two|three|four|five|six|seven|eight|nine)\b" try: rb = RadioBrowser() except Exception as e: LOG.exception("Failed to load pyradios" + repr(e)) LOG.info(f"Searching for {phrase}") results = rb.search(name=phrase) parsed = json.loads(json.dumps(results)) if len(parsed) > 0: # If an exatch match has been found return. LOG.info(f"Found {parsed[0]['name']} ({parsed[0]['url_resolved']})") return phrase, CPSMatchLevel.EXACT, {"url": parsed[0]["url_resolved"]} elif re.search(" [0-9]+ ", phrase): # If no match has been found, replace any digits (1,2,3) with text # (one, two, three) and repeat search. num = re.findall("[0-9]+", phrase) inf_eng = inflect.engine() for number in num: phrase = phrase.replace(num, inf_eng.number_to_words(number)) match_station_name(phrase) elif re.search(numbers_regex, phrase): # As above but reversed: change strings to ints and repeat search. num = re.findall(numbers_regex, phrase) for number in num: phrase = phrase.replace(number, str(w2n.word_to_num(number))) match_station_name(phrase) else: return None
class Raspado_Radios(): def __init__(self): self.nombre_radios_pais = [] self.url_radios_pais = [] self.resultado_pais_busqueda_nombre = [] self.resultado_pais_busqueda_numero = [] self.resultado_pais_busqueda_abreviado = [] self.nombre_busqueda_general_radio = [] self.url_busqueda_general_radio = [] self.nombre_idioma = [] self.cantidad_idioma = [] self.busqueda_nombre_idioma = [] self.busqueda_cantidad_idioma = [] self.nombre_tag = [] self.cantidad_tag = [] self.busqueda_nombre_tag = [] self.busqueda_cantidad_tag = [] self.paises_radio_español = [] self.paises_radio_abreviado = [] self.paises_numero_emisoras = [] self.paises_numero_total_emisoras = "" self.rb = RadioBrowser() self.datos_pais = self.rb.countries() def Paises_Español(self): claves = Raspado_Radios.keys_only(diccionario) valores = Raspado_Radios.values_only(diccionario) for i in range(len(self.datos_pais)): self.paises_radio_abreviado.append(self.datos_pais[i]["name"]) for i in self.paises_radio_abreviado: try: indice = valores.index(i.upper()) self.paises_radio_español.append(claves[indice]) except: pass def Paises_Bandera(self): for i in range(len(self.datos_pais)): self.paises_radio_abreviado.append(self.datos_pais[i]["name"]) def Paises_Cantidad_Emisoras(self): for i in range(len(self.datos_pais)): self.paises_numero_emisoras.append( self.datos_pais[i]["stationcount"]) def Suma_Total_Emisoras_Paises(self): self.temporal = [] for i in range(len(self.datos_pais)): self.temporal.append(self.datos_pais[i]["stationcount"]) self.paises_numero_total_emisoras = 0 for i in self.temporal: self.paises_numero_total_emisoras = self.paises_numero_total_emisoras + i def Actualizar_Pais(self): self.paises_radio_español = [] self.paises_radio_abreviado = [] self.paises_numero_emisoras = [] self.paises_numero_total_emisoras = "" Raspado_Radios.Paises_Español(self) Raspado_Radios.Paises_Bandera(self) Raspado_Radios.Paises_Cantidad_Emisoras(self) Raspado_Radios.Suma_Total_Emisoras_Paises(self) def Buscar_Pais(self, valor): self.resultado_pais_busqueda_nombre = [] self.resultado_pais_busqueda_numero = [] self.resultado_pais_busqueda_abreviado = [] for item in self.paises_radio_español: if valor.lower() in item.lower(): self.resultado_pais_busqueda_nombre.append(item) for i in self.resultado_pais_busqueda_nombre: posicion = self.paises_radio_español.index(i) self.resultado_pais_busqueda_numero.append( self.paises_numero_emisoras[posicion]) self.resultado_pais_busqueda_abreviado.append( self.paises_radio_abreviado[posicion]) def Resultado_Paises(self, valor): datos_frame = self.rb.stations_by_countrycode(valor) self.nombre_radios_pais = [] self.url_radios_pais = [] for i in range(0, len(datos_frame)): self.nombre_radios_pais.append(datos_frame[i]["name"]) self.url_radios_pais.append(datos_frame[i]["url"]) def Buscar_Radio_General(self, valor, valor1=True): datos_frame = self.rb.search(name=valor, name_exact=valor1) self.nombre_busqueda_general_radio = [] self.url_busqueda_general_radio = [] for i in range(0, len(datos_frame)): self.nombre_busqueda_general_radio.append(datos_frame[i]["name"]) self.url_busqueda_general_radio.append(datos_frame[i]["url"]) def Resultado_Idioma(self): datos_lenguaje = self.rb.languages() self.nombre_idioma = [] self.cantidad_idioma = [] for i in range(len(datos_lenguaje)): self.nombre_idioma.append(datos_lenguaje[i]["name"]) self.cantidad_idioma.append(datos_lenguaje[i]["stationcount"]) def Buscar_Idioma(self, valor): datos_lenguaje = self.rb.languages() temp_name = [] temp_count = [] for i in range(len(datos_lenguaje)): temp_name.append(datos_lenguaje[i]["name"]) temp_count.append(datos_lenguaje[i]["stationcount"]) self.busqueda_nombre_idioma = [] self.busqueda_cantidad_idioma = [] for item in temp_name: if valor.lower() in item.lower(): self.busqueda_nombre_idioma.append(item) for i in self.busqueda_nombre_idioma: posicion = temp_name.index(i) self.busqueda_cantidad_idioma.append(temp_count[posicion]) def Resultado_Idioma_Global(self, valor): pandas_radio_lenguaje = self.rb.stations_by_language(valor) self.nombre_radios_pais = [] self.url_radios_pais = [] for i in range(0, len(pandas_radio_lenguaje)): self.nombre_radios_pais.append(pandas_radio_lenguaje[i]["name"]) self.url_radios_pais.append(pandas_radio_lenguaje[i]["url"]) def Resultado_Tag(self): datos_genero = self.rb.tags() self.nombre_tag = [] self.cantidad_tag = [] for i in range(len(datos_genero)): self.nombre_tag.append(datos_genero[i]["name"]) self.cantidad_tag.append(datos_genero[i]["stationcount"]) def Buscar_Tag(self, valor): datos_genero = self.rb.tags() temp_name = [] temp_count = [] for i in range(len(datos_genero)): temp_name.append(datos_genero[i]["name"]) temp_count.append(datos_genero[i]["stationcount"]) self.busqueda_nombre_tag = [] self.busqueda_cantidad_tag = [] for item in temp_name: if valor.lower() in item.lower(): self.busqueda_nombre_tag.append(item) for i in self.busqueda_nombre_tag: posicion = temp_name.index(i) self.busqueda_cantidad_tag.append(temp_count[posicion]) def Resultado_Tag_Global(self, valor): pandas_tag = self.rb.stations_by_tag(valor) self.nombre_radios_pais = [] self.url_radios_pais = [] for i in range(0, len(pandas_tag)): self.nombre_radios_pais.append(pandas_tag[i]["name"]) self.url_radios_pais.append(pandas_tag[i]["url"]) def saber_pais_conexion(self): url = 'http://ipinfo.io/json' response = urlopen(url) data = json.load(response) IP = data['ip'] org = data['org'] city = data['city'] country = data['country'] region = data['region'] return country def load_obj(name): with open(name, 'rb') as f: return pickle.load(f) def save_obj(obj, name): with open(name, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def keys_only(flat_dict): return [k for k, v in flat_dict.items()] def values_only(flat_dict): return [v for k, v in flat_dict.items()]