### # Copyright (c) 2019, Pedro de Oliveira # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### from supybot import utils, plugins, ircutils, callbacks from supybot.commands import * try: from supybot.i18n import PluginInternationalization _ = PluginInternationalization('Inquisicao') except ImportError: # Placeholder that allows to run the plugin on a bot # without the i18n module _ = lambda x: x from urllib.parse import urlencode import json import re import requests class Inquisicao(callbacks.Plugin): """Client for Inquisicao""" threaded = True def __init__(self, irc): self.__parent = super(Inquisicao, self) self.__parent.__init__(irc) self.__truncate = 380 # max chars self.__apiKey = self.registryValue('apiKey') def __truncate_unicode_to_byte_limit(self, src, byte_limit, encoding='utf-8'): """Ripado daqui: https://stackoverflow.com/a/24839091""" return src.encode(encoding)[:byte_limit].decode(encoding, 'ignore') def __format_message(self, data, search): """Devolve uma string bonita sobre o processo""" result = "" extra = "crime" shown = 0 # Se for pesquisa, mostra o registo actual / total if search: result = "[%d/%d] " % ( data['next'] - 1 if data['next'] else data['total'], data['total']) data = data['message'] # Titulo result = "%s%s" % (result, data['titulo']) # Printa o Crime se existir, e incrementa o shown if data['crime']: result = "%s | Crime: %s" % (result, data['crime']) shown = shown + 1 # Printa a Sentença se existir, e incrementa o shown if data['sentenca']: result = u"%s | Sentença: %s" % (result, data['sentenca']) shown = shown + 1 # Se printou menos de 2 registos if shown < 2: # Se tiver "Notas" e "Outros dados" if data['notas'] and data['outros']: # Ver qual deles é maior e printa. # Define a variavel "extra" com o valor da chave que foi # extra-printada, para ser utilizada em caso de pesquisa if len(data['notas']) > len(data['outros']): result = "%s | Notas: %s" % (result, data['notas']) extra = "notas" else: result = "%s | Outros dados: %s" % (result, data['outros']) extra = "outros" # Senão printa as Notas elif data['notas']: result = "%s | Notas: %s" % (result, data['notas']) extra = "notas" # Ou os Outros dados elif data['outros']: result = "%s | Outros dados: %s" % (result, data['outros']) extra = "outros" # Se for pesquisa if search: # Verifica se o match é o mesmo que algum dos items já printados # Estou a comparar duas vezes com o Crime quando o "extra" não é definido if (data['crime'] != data['match']['value'] and data['sentenca'] != data['match']['value'] and data[extra] != data['match']['value']): # Printa o match result = "%s | %s: %s" % ( result, data['match']['key'], data['match']['value']) # Remover newlines e espaços duplicados result = result.replace("\r\n", " ") result = result.replace("\n", " ") result = re.sub(' +', ' ', result) original = result result = self.__truncate_unicode_to_byte_limit(original, self.__truncate) # Se a foi cortada, adiciona os ... if original != result: result = result + u"…" # Adiciona o short url result = "%s | %s" % (result, data['url']) return result def __do_request(self, action, arguments): baseurl = "https://inquisicao.info/api/v1/" response = requests.get( baseurl + action + "?" + urlencode(arguments), headers={ "Accept": "application/json", "Authorization": "Bearer " + self.__apiKey } ) return json.loads(response.content.decode('utf-8')) def find(self, irc, msg, args, text, position): """[text] [position] Returns the matched proccess with , at [position]. Or a random one if no arguments are given. """ if not text: data = self.__do_request('degredo', {}) irc.reply(self.__format_message(data, False), prefixNick=False) return data = self.__do_request('adcautelam', { 'key': text, 'page': position }) if not data: irc.reply("Not found", prefixNick=False) return irc.reply(self.__format_message(data, True), prefixNick=False) find = wrap(find, [optional('anything'), optional('int', default=0)]) Class = Inquisicao # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: