def on_pelota_command(self, update, *args, **kwargs): message = get_message(update) dashboard = kwargs.get('pizarra', False) msg = "❌ Season not found" try: year = "" cmd_args = re.sub('—\w*', '', message.text).split(" ") if len(cmd_args) > 1: year = cmd_args[1] data = self.stats_http(temporada=year) if data: msg = self.stats_msg(data, "Serie Regular") data = self.stats_http(temporada=year, etapa="RR") if data: msg += "\n" msg += self.stats_msg(data, "Serie Semifinal") data = self.stats_http(temporada=year, etapa="SF") if data: msg += "\n" msg += self.stats_msg(data, "Serie Final") except Exception as err: log.error("Pelota error: {}".format(err)) msg = "❌ Error" self.adapter.bot.sendMessage(chat_id=message.chat_id, text=msg, parse_mode='Markdown', disable_web_page_preview=True)
def on_anime(self, update, *args, **kwargs): message = get_message(update) fetched_response = self.fetch_anime() data = self.parse_anime_search(fetched_response) rss = data.get('rss', None) if rss is None: message.reply_text(text="❌ Invalid response.") log.error("No rss") return channel = rss.get('channel', None) if channel is None: message.reply_text(text="❌ Invalid response.") log.error("No channel") return item = channel.get('item', None) if item is None: message.reply_text(text="❌ Invalid response.") log.error("No item") return responses = [] title = item.get('title', '').strip() responses.append("<b>{}</b>".format(title)) size = item.get('nyaa:size', '').strip() responses.append("\n\n<b>Size:</b> {} | ".format(size)) link = item.get('link', '').strip() responses.append( "<b>Download:</b> <a href='{}'>Torrent</a>".format(link)) release_date = item.get('pubDate', '').strip() responses.append("\n<b>Date:</b> {}".format(release_date)) message.reply_text(text="".join(responses), parse_mode='HTML')
def on_rae_command(self, update, *args, **kwargs): message = get_message(update) msg = "" reply_markup = "" try: cmd_args = message.text.split(" ") if len(cmd_args) > 1: word = cmd_args[1] rae = self.http(word=word) if 'options' in rae: options = [] options_tmp = [] options_count = 1 for o in rae['options']: d = "rae:{}".format(o['href']) options_tmp.append( InlineKeyboardButton(text=o['word'].strip("."), callback_data=d)) if options_count % 3 == 0: options.append(options_tmp) options_tmp = [] options_count = options_count + 1 else: if len(options_tmp) > 0: options.append(options_tmp) if len(options) > 0: options.append([ InlineKeyboardButton( text="Cancelar", callback_data="rae:__cancel__") ]) reply_markup = InlineKeyboardMarkup(options) else: msg = "❌ No se encontro una relación" reply_markup = "" else: msg = self.make_msg(rae) else: msg = "‼️ Utiliza: /rae <palabra>" except Exception as err: log.error("Rae error: {}".format(err)) msg = "❌ Un error ha ocurrido" traceback.print_exc() if reply_markup: self.adapter.bot.sendMessage(chat_id=message.chat_id, text="📚 Quiso decir:", reply_markup=reply_markup) else: self.adapter.bot.sendMessage(chat_id=message.chat_id, text=msg, parse_mode='Markdown', disable_web_page_preview=True)
def on_ud_command(update, *args, **kwargs): log.info('Urban Dictionary command caught') message = get_message(update) terms = " ".join(kwargs.get('terms')) if len(terms) == 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Term or phrase is too short.") return verbose = kwargs.get('verbose') no_examples = kwargs.get('no_examples') n = int(kwargs.get('n')) n = n if n > 0 and n <= 5 else 1 data = fetch_definitions(terms) # adapter.bot.sendMessage(chat_id=message.chat_id, # text=json.dumps(data, indent=4, sort_keys=True)) def_list = data.get("list") tags_list = data.get("tags") if len(def_list) == 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ No definitions found.") return responses = [] for item in def_list[0:n]: item["definition"] = strip_markdown(item.get("definition")) d = dict(item) response = "📖 *{word}*: {definition}" if no_examples is False and item.get("example"): response += "\n\n_e.g. {example}_" if verbose is True: response += "\n\n👤 {author}\n👍{thumbs_up} / 👎 {thumbs_down}" if len(tags_list) > 0: tags = map(lambda tag: "#{}".format(tag), set(tags_list)) response += "\n{}".format(" ".join(tags)) response += "\n[Permalink ↗️]({permalink})" responses.append(response.format(**d)) if len(responses) == 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ No results") return if len(responses) <= 3: adapter.bot.sendMessage(chat_id=message.chat_id, text="\n\n".join(responses), parse_mode="Markdown", disable_web_page_preview=True) else: for response in responses: adapter.bot.sendMessage(chat_id=message.chat_id, text=response, parse_mode="Markdown", disable_web_page_preview=True)
def on_pizarra_command(self, update, *args, **kwargs): global last message = get_message(update) last = [ x for x in last if x['date'] + self.config.get("timer") > time.time() ] old_message = next( (x for x in last if x['chat_id'] == message.chat_id), None) try: data = self.dashboard_http() msg = self.dashboard_msg(data) except Exception as err: log.error("Pelota error: {}".format(err)) msg = "❌ Error occurred getting the dashboard" self.adapter.bot.sendMessage(chat_id=message.chat_id, text=msg, parse_mode='Markdown', disable_web_page_preview=True) return if old_message and old_message['date'] + self.config.get( "timer") > time.time(): msg_update = "{}\n__updated at {}__\n".format( msg, datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S")) self.adapter.bot.editMessageText( chat_id=message.chat_id, text=msg_update, message_id=old_message['message_id'], parse_mode='Markdown', disable_web_page_preview=True) msg_replay = "#pizarra #updated" self.adapter.bot.sendMessage( chat_id=message.chat_id, reply_to_message_id=old_message['message_id'], text=msg_replay, parse_mode='Markdown', disable_web_page_preview=True) else: last_message = self.adapter.bot.sendMessage( chat_id=message.chat_id, text=msg, parse_mode='Markdown', disable_web_page_preview=True) if old_message: last.remove(old_message) last.append({ 'date': time.time(), 'chat_id': message.chat_id, 'message_id': last_message.message_id })
def on_lidom_command(self, update, *args, **kwargs): message = get_message(update) try: data = self.lidom_http() msg = self.lidom_msg(data) except Exception as err: log.error("Pelota error: {}".format(err)) msg = "❌ Error." self.adapter.bot.sendMessage(chat_id=message.chat_id, text=msg, parse_mode='Markdown', disable_web_page_preview=True)
def on_url(self, update): message = get_message(update) urls = map( lambda url: message.text[url.offset:url.offset + url.length], filter(lambda entity: entity.type == MessageEntity.URL, message.entities)) for url in urls: m = self.url_pattern.match(url) if not m: continue if m.group("type") == "track": track_id = m.group("id") preview_url, filename, track_name, artists = self.get_track_preview( track_id) if preview_url is None or len(preview_url) == 0: log.info( "Not fetching %s - %s. Reason: preview_url is empty", artists, track_name) continue log.info("Fetching %s - %s", artists, track_name) self.fetch_and_send(message.chat_id, preview_url, filename, track_name, artists) if m.group("type") == "album": album_id = m.group("id") data = self.spotify.album(album_id) artists = ", ".join( map( lambda artist: "[{}]({})".format( trim_markdown(artist["name"]), artist[ "external_urls"]["spotify"]), data["artists"])) album = "[{}]({})".format(trim_markdown(data["name"]), data["external_urls"]["spotify"]) release_date = data.get("release_date") responses = [] responses.append( "💽 {album}\n🎙 {artists}\n📅 {release_date}\n". format(release_date=release_date, album=album, artists=artists)) for item in data["tracks"]["items"]: responses.append("🎼 [{name}]({url})".format( name=item["name"], url=item["external_urls"]["spotify"])) self.adapter.bot.sendMessage(chat_id=message.chat_id, text='\n'.join(responses), disable_web_page_preview=True, parse_mode="Markdown")
def on_downvote(self, update): message = get_message(update) if message.from_user.id == message.reply_to_message.from_user.id: self.adapter.bot.sendMessage( chat_id=message.chat_id, text="❌ You can't downvote yourself. #TeamAbo.") return if not message.from_user.username: self.adapter.bot.sendMessage( chat_id=message.chat_id, text="❌ You must set a username first to use this feature.") return if not message.reply_to_message.from_user.username: self.adapter.bot.sendMessage( chat_id=message.chat_id, text= "❌ That user must set their username first to use this feature." ) return data = { 'chat_id': message.chat_id, 'message_id': message.message_id, 'response_message_id': message.reply_to_message.message_id, 'message': message.text, 'giver_user_id': message.from_user.id, 'giver_username': message.from_user.username, 'receiver_user_id': message.reply_to_message.from_user.id, 'receiver_username': message.reply_to_message.from_user.username, 'vote': -1 } if KarmaPlugin.add_karma(**data): receiver_username = KarmaPlugin.username_as_link( message.reply_to_message.from_user.username) giver_username = KarmaPlugin.username_as_link( message.from_user.username) text = "⬇ Negative karma for {} given by {}.".format( receiver_username, giver_username) self.adapter.bot.sendMessage(chat_id=message.chat_id, text=text, parse_mode='Markdown', disable_web_page_preview=True) else: self.adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Unable to save karma.")
def on_cine_command(self, update, *args, **kwargs): log.info('Reply command caught') message = get_message(update) r = requests.get("http://www.cinema.com.do/") soup = BeautifulSoup(r.text, 'html.parser') movies = soup.select("li.text-center.img-container") movie_list = [] try: for num, movie in enumerate(movies, start=1): movie_list.append("{} - {}".format(num, movie.strong.string.encode('iso-8859-1').decode('utf8'))) except Exception as err: log.error("Parse error: {}".format(err)) message.reply_text(text="\n".join(movie_list), parse_mode='HTML')
def on_gas(self, update, *args, **kwargs): message = get_message(update) fetched_response = self.fetch_gas_prices() data = self.parse_gas_prices(fetched_response) rss = data.get('rss', None) if rss is None: message.reply_text(text="❌ Invalid response.") log.error("No rss") return channel = rss.get('channel', None) if channel is None: message.reply_text(text="❌ Invalid response.") log.error("No channel") return item = channel.get('item', None) if item is None: message.reply_text(text="❌ Invalid response.") log.error("No item") return responses = [] title = item.get('title', '').strip() responses.append("⛽ <b>{}</b>\n".format(title)) last_update = item.get('pubDate', '').strip() description = item.get('description', '').encode('iso-8859-1').decode('utf8') soup = BeautifulSoup(description, 'html.parser') try: for div in soup.select("div"): category, price = div.contents responses.append("💰 {}{}".format(category.string, price)) except Exception as err: log.error("Parse error: {}".format(err)) responses.append("\n📅 Actualizado el {}".format(last_update)) message.reply_text(text="\n".join(responses), parse_mode='HTML')
def on_match(self, update): message = get_message(update) text = message.text # Quit early if there's no text if len(text) == 0: return # Filter messages that are not replies if not message.reply_to_message: return # Filter replies to messages without text if len(message.reply_to_message.text) == 0: return # Check if we are getting s// match = self.pattern.match(text) if not match: return user_pattern = match.group('pattern') user_replacement = match.group('replacement') # Try compiling user pattern try: pattern = re.compile(user_pattern, flags=re.IGNORECASE) if not pattern: return response_text = pattern.sub("<b>{}</b>".format(user_replacement), message.reply_to_message.text) self.adapter.bot.sendMessage( chat_id=message.chat_id, text="<b>Did you mean</b>❔\n{}".format(response_text), parse_mode='HTML') except Exception as ex: log.info("Exception when compiling user pattern: {}".format(ex))
def on_probe_command(update, *args, **kwargs): message = get_message(update) probes = kwargs.get('probe_id') api_key = get_config().get("api_key") responses = [] for probe in probes: if probe.isdigit(): probe_id = probe.strip() else: probe_alias = ProbeAlias.by_alias(probe.strip()) if probe_alias is None or probe_alias.date_deleted is not None: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Not a valid probe alias.") return else: probe_id = probe_alias.probe_id data = query_probe_status(probe_id, api_key) if not data: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Probe does not exist.") continue if data.get("status") is None: continue status = data.get("status") values = { "since": arrow.get(status.get("since")).humanize(), "icon": "✅" if status.get("name") == "Connected" else "🅾", "desc": data.get("description"), "status_name": status.get("name") } response = "{icon} {desc}: {status_name} since {since}".format(**values) responses.append(response) if len(responses) > 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="\n".join(responses), parse_mode="Markdown")
def on_cine_command(self, update, *args, **kwargs): log.info('Reply command caught') message = get_message(update) url = self.config.get('base_url') r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') movies = soup.select("li.text-center.img-container") movie_list = [] try: for num, movie in enumerate(movies, start=1): movie_detail = ( '<a href="{}">↗�</a>').format(url + movie.a['href']) #for futures implementations #movie_list.append(("{} - {}: 🎞 {}").format(num, movie.strong.string.encode('iso-8859-1').decode('utf8'), movie_detail)) movie_list.append(("🎬 {} {}").format( movie.strong.string.encode('iso-8859-1').decode('utf8'), movie_detail)) except Exception as err: log.error("Parse error: {}".format(err)) message.reply_text(text="\n".join(movie_list), parse_mode='HTML', disable_web_page_preview=True)
def on_probe_alias_command(update, *args, **kwargs): log.info('on_probe_alias_command') message = get_message(update) probe_id = kwargs.get('probe_id') alias = kwargs.get('alias') remove = kwargs.get('remove') if alias is None: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ You must specify an alias.") return if len(alias) == 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Specified alias is too short") return if remove: if remove_probe_alias(alias): adapter.bot.sendMessage(chat_id=message.chat_id, text="🚮 1 probe alias removed.") else: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ No such probe alias.") return if probe_id is None: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ You must specify a probe.") return if len(probe_id) == 0: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Specified probe ID is too short.") return probe_alias = ProbeAlias.by_alias(alias) if probe_alias: if probe_alias.date_deleted is None: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Probe alias already exists.") return user_id = message.from_user.id username = message.from_user.username date_added = localized_date() date_modified = localized_date() if probe_alias is None: probe_alias = ProbeAlias() probe_alias.probe_id = probe_id probe_alias.alias = alias probe_alias.user_id = user_id probe_alias.username = username probe_alias.date_modified = date_modified probe_alias.date_deleted = None try: probe_alias.save() adapter.bot.sendMessage(chat_id=message.chat_id, text="✅ Probe alias added.") except: adapter.bot.sendMessage(chat_id=message.chat_id, text="❌ Unable to add probe alias.")
def on_text(self, update): text = trim_accents(get_message(update).text) if len(text) == 0: log.info('Ignoring text message. Message length is zero') return def handle_text_response(update, reply): self.bot.sendMessage(chat_id=update.message.chat_id, text=reply.response) def handle_photo_response(update, reply): self.bot.sendPhoto(chat_id=update.message.chat_id, photo=reply.response, caption=reply.caption) def handle_sticker_response(update, reply): self.bot.sendSticker(chat_id=update.message.chat_id, sticker=reply.response) def handle_document_response(update, reply): self.bot.sendDocument(chat_id=update.message.chat_id, document=reply.response) def handle_audio_response(update, reply): self.bot.sendAudio(chat_id=update.message.chat_id, audio=reply.response) def handle_video_response(update, reply): self.bot.sendVideo(chat_id=update.message.chat_id, video=reply.response) def handle_voice_response(update, reply): self.bot.sendVoice(chat_id=update.message.chat_id, voice=reply.response) def handle_json_response(update, reply): data = json.loads(reply.response) self.bot.sendContact(chat_id=update.message.chat_id, **data) def handle_unknown_response(update, reply): self.bot.sendMessage( chat_id=update.message.chat_id, text="❌ Invalid response type '{response_type}' for '{pattern}'" .format(pattern=reply.pattern, response_type=reply.response_type)) response_handlers = { "text": handle_text_response, "photo": handle_photo_response, "sticker": handle_sticker_response, "gif": handle_document_response, "audio": handle_audio_response, "video": handle_video_response, "voice": handle_voice_response, "file": handle_document_response, "contact": handle_json_response, "location": handle_json_response, } def on_match(text, reply): response_handler = response_handlers[ reply. response_type] if reply.response_type in response_handlers else handle_unknown_response response_handler(update, reply) self.find_match(text, on_match)
def on_reply_command(self, update, *args, **kwargs): log.info('Reply command caught') message = get_message(update) if not User.is_user_admin(message.from_user): self.bot.sendMessage(chat_id=message.chat_id, text="❌ You are not allowed to do that.") return remove = kwargs.get('remove') new_pattern = kwargs.get('new_pattern') pattern = " ".join(kwargs.get('pattern')) pattern = trim_accents(pattern).lower() pattern_type = kwargs.get('type') mime_type = None file_name = None caption = None parse_mode = None if remove: if SimpleRepliesPlugin.remove_reply(pattern): self.bot.sendMessage(chat_id=message.chat_id, text="🚮 1 reply removed.") self.fetch_replies() else: self.bot.sendMessage(chat_id=message.chat_id, text="❌ No such reply.") return if new_pattern: reply = SimpleRepliesPlugin.fetch_reply(pattern) if reply is None: self.bot.sendMessage(chat_id=message.chat_id, text="❌ No such reply..") else: new_pattern = trim_accents(str(new_pattern).strip()).lower() reply.pattern = new_pattern pattern_types = set([x[0] for x in PATTERN_TYPES]) if pattern_type in pattern_types: reply.pattern_type = pattern_type reply.save() self.fetch_replies() self.bot.sendMessage(chat_id=message.chat_id, text="✅ Reply updated.") return if not message.reply_to_message: self.bot.sendMessage( chat_id=message.chat_id, text= "❌ When adding new replies, use this command while replying.") return response_type = SimpleRepliesPlugin.get_message_type( message.reply_to_message) if response_type is None: self.bot.sendMessage(chat_id=message.chat_id, text="❌ Media type is not supported") return if response_type == 'sticker': response = message.reply_to_message.sticker.file_id elif response_type == 'voice': response = message.reply_to_message.voice.file_id elif response_type in ('gif', 'file'): mime_type = message.reply_to_message.document.mime_type response = message.reply_to_message.document.file_id file_name = message.reply_to_message.document.file_name elif response_type == 'photo': mime_type = 'image/jpeg' response = message.reply_to_message.photo[-1].file_id file_name = "{}.jpg".format( message.reply_to_message.photo[-1].file_id) caption = message.reply_to_message.caption elif response_type == 'location': response = message.reply_to_message.location.to_json() elif response_type == 'contact': response = message.reply_to_message.contact.to_json() else: parse_mode = kwargs.get('mode') if parse_mode not in ('HTML', 'Markdown'): parse_mode = None response = get_message(update).reply_to_message.text user_id = message.from_user.id username = message.from_user.username date_added = localized_date() date_modified = localized_date() if len(pattern) == 0: self.bot.sendMessage(chat_id=message.chat_id, text="❌ Reply pattern is too short.") return reply = SimpleRepliesPlugin.fetch_reply(pattern) if reply: if reply.date_deleted is None: self.bot.sendMessage( chat_id=message.chat_id, text="❌ A reply with this pattern already exists.") return else: result = SimpleRepliesPlugin.add_reply( id=reply.id, user_id=user_id, username=username, pattern=pattern, pattern_type=pattern_type, response=response, response_type=response_type, caption=caption, parse_mode=parse_mode, file_name=file_name, mime_type=mime_type, date_added=date_added, date_modified=date_modified) else: result = SimpleRepliesPlugin.add_reply(user_id=user_id, username=username, pattern=pattern, pattern_type=pattern_type, response=response, response_type=response_type, caption=caption, parse_mode=parse_mode, file_name=file_name, mime_type=mime_type, date_added=date_added, date_modified=date_modified) if result: self.bot.sendMessage(chat_id=message.chat_id, text="✅ Reply added.") self.fetch_replies() else: self.bot.sendMessage(chat_id=message.chat_id, text="❌ Unable to add reply.")
def on_spotify_command(self, update, **kwargs): message = get_message(update) query = (" ".join(kwargs.get('terms'))).strip() if query == '': return artists = kwargs.get('artists') albums = kwargs.get('albums') playlists = kwargs.get('playlists') n = int(kwargs.get('count', 1)) n = n if n >= 1 else 1 s = int(kwargs.get('skip', 0)) s = s if s >= 0 else 0 if artists: query_type = 'artist' elif albums: query_type = 'album' elif playlists: query_type = 'playlist' else: query_type = 'track' data = self.spotify.search(q=query, type=query_type) responses = [] if query_type == 'track': for item in data["tracks"]["items"][s:s + n]: artists = ", ".join( map( lambda a: "[{}]({})".format( trim_markdown(a["name"]), a["external_urls"][ "spotify"]), item["artists"])) track = "[{}]({})".format(trim_markdown(item["name"]), item["external_urls"]["spotify"]) album = "[{}]({})".format( trim_markdown(item["album"]["name"]), item["album"]["external_urls"]["spotify"]) response = "🎼 {track}\n🎙 {artists}\n💽 {album}".format( track=track, album=album, artists=artists) responses.append(response) else: self.adapter.bot.sendMessage(chat_id=message.chat_id, text="Not yet implemented") return if not responses: self.adapter.bot.sendMessage(chat_id=message.chat_id, text="No results") return track_id = data["tracks"]["items"][s]["id"] callback_data = "{name}:{action}:{track_id}".format( name=self.name, action="fetch-preview", track_id=track_id) url = "https://open.spotify.com/track/{}".format(track_id) listen_on_spotify = InlineKeyboardButton(text="Listen on Spotify", url=url) if data["tracks"]["items"][s]["preview_url"]: preview_button = InlineKeyboardButton(text="Preview", callback_data=callback_data) keyboard = [[preview_button, listen_on_spotify]] else: keyboard = [[listen_on_spotify]] reply_markup = InlineKeyboardMarkup(keyboard) self.adapter.bot.sendMessage(chat_id=message.chat_id, text="\n\n".join(responses), parse_mode="Markdown", disable_web_page_preview=True, reply_markup=reply_markup)