def definition(message): '''Sends Definitions and Pronunciations.''' endpoint = "entries" language_code = "en-us" word_id = message.text word_id = util.extract_arguments(word_id) url = "https://od-api.oxforddictionaries.com/api/v2/" + endpoint + "/" + language_code + "/" + word_id.lower( ) r = requests.get(url, headers={"app_id": app_id, "app_key": app_key}) bot.send_message(message.chat.id, word_id) try: try: definitions = r.json()['results'][0]['lexicalEntries'][0][ 'entries'][0]['senses'][0]['definitions'][0] sentence = r.json()['results'][0]['lexicalEntries'][0]['entries'][ 0]['senses'][0]['examples'][0]['text'] bot.send_message( message.chat.id, f'Word - {word_id}\nDefinition - {definitions}\nExample Sentence - {sentence.capitalize()}.' ) except: bot.send_message(message.chat.id, 'Meaning not found!') try: audio_file = r.json()['results'][0]['lexicalEntries'][0][ 'entries'][0]['pronunciations'][1]['audioFile'] bot.send_audio(message.chat.id, audio=audio_file) except: bot.send_message(message.chat.id, 'Pronunciation not found!') except: bot.send_message(message.chat.id, 'Something went wrong...')
def change(message): """ Ejemplo de API abierta Usa la API definida en https://bitcoincharts.com/about/markets-api/ para saber el tipo de cambio de una moneda :param message: :return: """ exchange = util.extract_arguments(message.text).upper() if not exchange: bot.reply_to(message, "Debe indicar un tipo de cambio. Ej.: EUR, USD, ...") return # request.get(url).json() Devuelve los datos de una API pública response = requests.get( 'http://api.bitcoincharts.com/v1/weighted_prices.json').json() if exchange not in response: bot.reply_to(message, "No se ha encontrado el tipo de cambio") return bot.reply_to( message, "Un bitcoin equivale a %s %s" % (response[exchange]['24h'], exchange))
def weather(message): """ Ejemplo de API con Token en la URL Usa la API definida en https://openweathermap.org/current para conocer el tiempo en una ciudad """ weather_token = os.environ.get('OPENWEATHER_TOKEN', False) if not weather_token: bot.reply_to(message, "Debe configurarse el token de openweather") return city = util.extract_arguments(message.text).upper() if not city: bot.reply_to(message, "Debe indicar una ciudad") return url = 'https://api.openweathermap.org/data/2.5/weather?q=%s,es&lang=sp&units=metric&APPID=%s' % ( city, weather_token) response = requests.get(url=url) if response.status_code is not requests.codes.ok: bot.reply_to(message, "Error al consultar el tiempo") return data = response.json() bot.reply_to(message, "La temperatura es de %sºC" % data['main']['temp'])
def handle_message(self, json_string): self.message = types.Message.de_json(json_string) _content_type = self.message.content_type _result_text = None if _content_type == 'text': _text = self.message.text if util.is_command(_text): _cmd = util.extract_command(_text) _agrs = util.extract_arguments(_text) _result_text = self.command_callback(_cmd, _agrs) else: _result_text = self.text_callback(_text) elif _content_type == 'voice': _result_text = self.voice_callback(self.message.voice) elif os.environ.get('DEBUG'): _result_text = 'DEBUG content_type = {0}'.format(_content_type) # Bot always replies with text message return bothelper.new_message(self.message.chat.id, _result_text) if _result_text else None
def retweet_tweets(message): chat_id = message.chat.id api = getAPIObject(chat_id) #tl = api.home_timeline() #imprimir(tl, bot, chat_id) tweetsTBRT = util.extract_arguments(message.text) for n_tweets in tweetsTBRT: api.retweet(tl[n_tweets].id)
def fav_tweets(message): chat_id = message.chat.id api = getAPIObject(chat_id) tl = api.home_timeline() #imprimir(tl, bot, chat_id) tweetsTBFAV = util.extract_arguments(message.text) for n_tweets in tweetsTBFAV: api.favorite(tl[n_tweets].id)
def add_bot(message: types.Message): token = util.extract_arguments(message.text) tokens[token] = True new_bot = TeleBot(token) new_bot.delete_webhook() new_bot.set_webhook(f"{config.WEBHOOK_HOST}/{config.WEBHOOK_PATH}/{token}") new_bot.send_message(message.chat.id, "Webhook was set.")
def send_lyrics(message): '''Finds Lyrics of the given Song.''' song_name = message.text song_name = util.extract_arguments(song_name) lyric = genius.search_song(song_name, get_full_info=True) lyric = lyric.lyrics bot.send_message(message.chat.id, lyric)
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 send(message): if message.chat.id == ADMIN_CHAT: ID = util.extract_arguments(message.text) if message.reply_to_message: try: bot.send_message(ID, message.reply_to_message.text) except Exception: bot.send_message(ADMIN_CHAT, 'Somethign went wrong...Try Again.') elif not message.reply_to_message: bot.send_message(ADMIN_CHAT, 'Please reply to a text message to send.')
def save(message): """ Guarda un dato en el chat que se puede recuperar después """ data = util.extract_arguments(message.text) if not data: bot.reply_to(message, "Debe indicar el dato que quiere que guarde") return chat_id = message.chat.id chat.Chat.set_config(chat_id, 'memory', data) bot.reply_to(message, "Dato guardado. Usa /load para recuperar")
def send_songname(message): '''Finds Song Name of given Lyrics.''' lyric = message.text lyric = util.extract_arguments(lyric) song_names = genius.search_lyrics(lyric) song_names_lis = [] for hits in song_names['sections'][0]['hits']: song_names_lis.append(hits['result']['title']) titles = "\n".join(song_names_lis) print(lyric) bot.send_message(message.chat.id, f"All possible matches for {lyric}:-\n\n{titles}")
def size(message): if message.content_type == 'text': url = util.extract_arguments(message.text) if url != None or url == '': if validators.url(url): image = get_img(url) bot.send_message(message.chat.id, """<b><i>Fetching image details...</i></b>""", parse_mode='HTML', reply_to_message_id=message.message_id) if image['status']: bot.send_message(message.chat.id, f""" <u><b>IMAGE DETAILS</b></u> <b>WIDTH: {image['width']}</b> <b>HEIGHT: {image['height']}</b> <u><b>RECOMMENDED VALUES</b></u> <b>WIDTH: 512</b> <b>HEIGHT: 288</b> <i>Image size values have to be greater or equal to recommended values. </i> """, parse_mode='HTML') else: m = bot.reply_to(message, "Please enter a valid URL") bot.register_next_step_handler(m, size) else: msg = bot.reply_to(message, "Please enter a valid URL!") m = bot.send_message( msg.chat.id, """<b><u>Example: </u></b> <b>/size https://unsullied.xyz/img/logo/meta.png</b>""", parse_mode='HTML', reply_to_message_id=message.message_id) bot.register_next_step_handler(m, size) else: msg = bot.reply_to(message, "URL missing!") m = bot.send_message( msg.chat.id, """Example : <b>/size https://unsullied.xyz/img/logo/meta.png</b>""", parse_mode='HTML', reply_to_message_id=message.message_id) bot.register_next_step_handler(m, size) else: m = bot.reply_to(message, "Enter a valid URL!") bot.register_next_step_handler(m, size)
def history(message): try: base_currency, target_currency = extract_arguments( message.text).split("/") render_history( bot, message, currency_service.history(HISTORY_N_DAYS, base_currency, target_currency)) except NoDataAvailable as e: render_error(bot, message, "Could not load data!") logging.exception(e) except CurrencyNotFound as e: logging.exception(e) render_error(bot, message, "No currency {0}!".format(e.currency)) except Exception as e: handle_common_error(e, message, bot)
def exchange(message): try: args = extract_arguments(message.text) if re.compile("\d+\$\sto\s[A-Z]{3}").match(args): base_currency = 'USD' args = args.replace("$", "") amount, __, target_currency = args.split() else: amount, base_currency, __, target_currency = args.split() amount = Decimal(amount) result = currency_service.exchange(base_currency, target_currency, amount) render_exchange_rate(bot, message, target_currency, result) except CurrencyNotFound as e: logging.exception(e) render_error(bot, message, "No currency {0}!".format(e.currency)) except Exception as e: handle_common_error(e, message, bot)
def info(message): referencia = util.extract_arguments(message.text) if not referencia: referencia = chat.Chat.get_config(message.chat.id, 'referencia') if not referencia: bot.send_message(message.chat.id, "Debe indicar la referencia del pedido") return else: referencia = referencia.value url = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=order&ref=" + referencia url2 = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=allProductInOrder&ref=" + referencia url3 = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=shipping&ref=" + referencia response = urllib.urlopen(url) response2 = urllib.urlopen(url2) response3 = urllib.urlopen(url3) datos = json.loads(response.read()) datos2 = json.loads(response2.read()) datos3 = json.loads(response3.read()) if (datos == 1 or datos2 == 1 or datos3 == 1): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos == 2 or datos2 == 2 or datos3 == 2): bot.send_message(message.chat.id, "No se ha podido localizar su pedido") elif (datos == 3 or datos2 == 3 or datos3 == 3): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos == 4 or datos2 == 4 or datos3 == 4): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") else: chat.Chat.set_config(message.chat.id, 'referencia', referencia) for dato in datos: respuesta = ("📝 *Codigo de referencia del pedido:* " + str(dato["ref"]) + "\n📆 *Fecha del pedido:* " + str(dato["date_commande"])) total = 0 respuesta = respuesta + "\n\n\n📋 *Listado de productos:*\n\n" for dato in datos2: total_ttc = float(dato["total_ttc"]) respuesta = respuesta + "- " + "_" + dato[ "label"] + "_" + "\t\t" + "_" + str( total_ttc) + "_" + "\u20ac\n" total = total + float(dato["total_ttc"]) respuesta = (respuesta + "\n\n💶 *Precio total:* " + str(total) + "\u20ac") estados = {0: "_Borrador_", 1: "_En curso_", 2: "_Entregado_"} for dato in datos3: respuesta = respuesta + "\n\n🚚 *Estado del pedido:* " + estados[ int(dato["fk_statut"])] bot.send_message(message.chat.id, respuesta, parse_mode="Markdown") var = "El usuario con id " + str( message.chat.id ) + " ha hecho una peticion de informacion del pedido con referencia " + referencia send_log(var) return
def poster(message): if message.chat.id in users: if util.is_command(message.text) and util.extract_arguments( message.text) == 'help': bot.send_message(message.chat.id, """ <u><b> PARAMETERS</b></u> <b>Color : -c</b> <b>Image URL : -u</b> <b>Image Width : -iw</b> <b>Image Height : -ih</b> <b>Image x-coordinate : -ix</b> <b>Image y-coordinate : -iy</b> <b>Author Name : -a</b> <b>Author Size : -as</b> <b>Author x-coordinate : -ax</b> <b>Author y-coordinate : -ay</b> <b>Title Name : -t</b> <b>Title Size : -ts</b> <b>Title x-coordinate : -tx</b> <b>Title y-coordinate : -ty</b> """, reply_to_message_id=message.message_id, parse_mode='HTML') bot.send_message(message.chat.id, """ <u><b>EXAMPLE</b></u> /post -c orange -u https://unsullied.xyz/img/logo/meta.png -iw 390 -ih 200 -ix 185 -iy 225 -t "Testing is fun." -ts 25 -tx 180 -ty 455 -a "- Sarahfin" -as 19 -ax 488 -ay 526 """, reply_to_message_id=message.message_id, parse_mode='HTML') return try: param = message.text.split(' ') if validators.url(param[param.index('-u') + 1]): image = get_img(param[param.index('-u') + 1]) if (image['status']): data['image'] = image['image'] bot.send_message(message.chat.id, f""" <b>IMAGE FETCHED!</b> <b>WIDTH:</b> {image['width']} <b>HEIGHT:</b> {image['height']} <u><b>RECOMMENDED VALUES</b></u> <b>WIDTH: 512</b> <b>HEIGHT: 288</b> <i>Image size values have to be greater or equal to recommended values. </i> """, reply_to_message_id=message.message_id, parse_mode='HTML') title = message.text[message.text. find('-t'):len(message.text) - 1].replace('-t ', '') data['title'] = '' for i in range(1, len(title) - 1): if title[i] == '"': break data['title'] = data['title'] + title[i] data['title_size'] = int(param[param.index('-ts') + 1]) author = message.text[message.text. find('-a'):len(message.text) - 1].replace('-a ', '') data['author'] = '' for i in range(1, len(author) - 1): if author[i] == '"': break data['author'] = data['author'] + author[i] data['author_size'] = int(param[param.index('-as') + 1]) data['img_x'] = int(param[param.index('-ix') + 1]) data['img_y'] = int(param[param.index('-iy') + 1]) data['img_width'] = int(param[param.index('-iw') + 1]) data['img_height'] = int(param[param.index('-ih') + 1]) data['author_x'] = int(param[param.index('-ax') + 1]) data['author_y'] = int(param[param.index('-ay') + 1]) data['title_x'] = int(param[param.index('-tx') + 1]) data['title_y'] = int(param[param.index('-ty') + 1]) data['color'] = param[param.index('-c') + 1].lower() data['image'] = resize_img(data['image'], data['img_width'], data['img_height']) data['image'] = make_img(data['image'], data['color'], data['img_x'], data['img_y']) data['image'] = write_title(data['image'], data['title'], data['title_size'], data['title_x'], data['title_y']) data['image'] = write_author(data['image'], data['color'], data['author'], data['author_size'], data['author_x'], data['author_y']) saved_img = save_img(data['image']) img = upload_img(saved_img['directory']) if (img['success'] == True): bot.send_message(message.chat.id, """ <b>IMAGE GENERATED!</b> <i>Uploading...</i> """, parse_mode='HTML') bot.send_message(message.chat.id, img['data']['url']) os.remove(saved_img['directory']) else: bot.send_message( message.chat.id, "<b><u>IMAGE WAS NOT UPLOADED!</u></b>", parse_mode="HTML") else: bot.send_message(message.chat.id, "Please enter a valid URL!") msg = bot.send_message(message.chat.id, "Enter the image URL: ") bot.register_next_step_handler(msg, choose_img_width) else: bot.send_message(message.chat.id, "Please enter a valid URL!") msg = bot.send_message(message.chat.id, "Enter the image URL: ") bot.register_next_step_handler(msg, choose_img_width) except Exception as e: bot.send_message(message.chat.id, f""" <b>INVALID COMMAND!</b> Run <code>/post help</code> to get the list of accepted arguments <b>Error : {e}</b> """, parse_mode='HTML') else: bot.reply_to(message, """<b>You're not part of unsullied!</b>""", parse_mode='HTML')
def list(message): referencia = util.extract_arguments(message.text) if not referencia: referencia = chat.Chat.get_config(message.chat.id, 'referencia') if not referencia: bot.send_message(message.chat.id, "Debe indicar la referencia del pedido") return else: referencia = referencia.value url = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=allProductInOrder&ref=" + referencia response = urllib.urlopen(url) datos = json.loads(response.read()) if (datos == 1): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos == 2): bot.send_message(message.chat.id, "No se ha podido localizar su pedido") elif (datos == 3): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos == 4): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") else: chat.Chat.set_config(message.chat.id, 'referencia', referencia) for dato in datos: url2 = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=getImage&ref=" + dato[ 'ref'] url3 = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?ref=" + dato[ 'ref'] + "&case=urlshop" response2 = urllib.urlopen(url2) response3 = urllib.urlopen(url3) datos2 = json.loads(response2.read()) datos3 = json.loads(response3.read()) if (datos2 == 1 or datos3 == 1): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos2 == 2 or datos3 == 2): bot.send_message(message.chat.id, "No se ha podido localizar su pedido") elif (datos2 == 3 or datos3 == 3): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") elif (datos2 == 4 or datos3 == 4): bot.send_message( message.chat.id, "Ha habido un error al realizar su consulta de pedido") else: nombre = dato["label"] precio = float(dato["total_ttc"]) link = datos3 bot.send_photo(message.chat.id, datos2, caption="🛒 _" + nombre + "_" + "\n💶 *Precio:* " + str(precio) + "\u20ac", parse_mode="Markdown") bot.send_message(message.chat.id, link) var = "El usuario con id " + str( message.chat.id ) + " ha hecho una peticion de listado de productos del pedido con referencia " + referencia send_log(var) return