Exemplo n.º 1
0
 def parse(self, request):
     """
     Me quedo con el metodo y la URL que le paso como parametro
     """
     request = request.decode('utf-8')
     method = request.split()[0]
     url = request.split()[1]
     return method, url
Exemplo n.º 2
0
 def parse(self, request):
     print("RECIBIDO_________ " + request)
     try:
         metodo = request.split()[0]
         recurso = request.split()[1]
         cuerpo = recurso.split('/')[1]
         self.cabecera1 = metodo + recurso
     except IndexError:
         return None
     return (cuerpo)
Exemplo n.º 3
0
    def react_to(self, request):
        """
        -----------------------------------------------------------------------------------
        Bi.react_to(self,request):

        # Params: request là đoạn text 
        # Chức năng: phân tích đoạn text để gọi chức năng thực hiện phù hợp
        # Trả về:
            + thành công: dữ liệu trả về của chức năng đã thực hiên
            + exception: dữ liệu trả về khi xảy ra exception trong chức năng đã thực hiện
        -----------------------------------------------------------------------------------
        """
        request=request.lower()
        if request=='':
            return
        if 'bi ơi' in request:
            return self.multiprocess_speak('Mình đây, bạn cần gì')
        elif 'làm được gì' in request or 'có thể làm gì' in request:
            return self.multiprocess_speak('Tôi có thể trò chuyện, làm toán tiểu học, tìm kiếm, mở video, thay đổi hình nền và trả lời những câu hỏi của bạn')
        elif "tạm biệt bạn" == request or "tạm biệt" == request:
            return self.multiprocess_speak('Bái bai')
        elif "hiện tại" in request or "mấy giờ" in request or 'bây giờ là' in request:
            response='Bây giờ là '+self.get_time()
            self.multiprocess_speak(response)
            return response
        elif 'hôm nay là' in request or 'ngày mấy' in request:
            response='Hôm nay là '+self.get_date()
            self.multiprocess_speak(response)
            return response
        elif 'tìm' in request:
            if request.split(' ').index('tìm')==0:
                return self.search_google(request.replace('tìm',''))
            return self.search_google(request.split(" tìm ",1)[1])
        elif 'mở' in request or 'phát' in request:
            return self.play_youtube(request)
        elif 'gửi mail' in request or 'gởi mail' in request:
            self.speak('Bạn muốn gửi mail cho ai')
            destination=self.listen()
            self.speak('Bạn muốn đặt tiêu đề là gì')
            subject=self.listen()
            self.speak('Nội dung của mail là gì')
            content=self.listen()
            return self.send_email(destination,subject,content)
        elif 'đổi ảnh' in request or 'thay ảnh' in request or 'đổi hình' in request or 'thay hình' in request or 'đổi nền' in request or 'thay nền' in request:
            return self.change_random_walpaper()
        elif 'thời tiết' in request:
            return self.wheather_forecast()
        elif ('là gì' in request or 'là ai' in request) and 'bạn là ai' not in request:
            return self.define(request.replace('là gì','').replace('là ai',''))
        else:
            return self.multiprocess_speak(str(self.brain.get_response(request)))
def serve_resource(client_connection,
                   url='https://uclm-arco.github.io/ietf-clone/rfc'):

    request = client_connection.recv(1024).decode()
    method, resource = request.split(' ')[0], request.split(' ')[1]
    resource_url = url + resource
    if method == 'POST':
        identifier7 = request.partition('code:')[2].partition('\n')[0]
        print(request.partition('code:')[2])
        solve_challenge7(identifier7)
        return
    reply_header = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "\r\n"
    url_content = urllib.request.urlopen(resource_url).read()
    HTTP_reply = reply_header.encode("utf-8") + url_content
    client_connection.sendall(HTTP_reply)
    client_connection.close()
Exemplo n.º 5
0
def doFile(request, default_sleep, debug):
    print("         > File:", request)
    time.sleep(default_sleep)

    req = request.split(" ")

    if "--create" in req:
        path = req[req.index("--path") + 1].strip('\"')
        size = req[req.index("--size") + 1]
        count = int(req[req.index("--count") + 1])

        # Only specify for Windows
        if "USERPROFILE" in os.environ:
            path = path.replace("%USERPROFILE%", os.environ["USERPROFILE"])

        ### Debug
        if debug == True:
            path = "/tmp/scythe/important_files.wasted"

        # Convert size to bytes
        if size.endswith("MB"):
            size = int(size[:-2]) * 1024 * 1024

        # Creating file(s)
        for i in range(count):
            f = open(path + str(i + 1), "wb")
            f.seek(size - 1)
            f.write(b"\0")
            f.close()
            # Insert a short delay between each file creation
            time.sleep(0.01)
Exemplo n.º 6
0
def doDownloader(request, default_sleep, debug):
    print("         > Download :", request)
    time.sleep(default_sleep)

    req = request.split(" ")
    src = req[req.index("--src") + 1].strip('\"')
    dest = req[req.index("--dest") + 1].strip('\"')

    # Only specify for Windows
    if "USERPROFILE" in os.environ:
        dest = dest.replace("%USERPROFILE%", os.environ["USERPROFILE"])

    # If URL is from pastebin, make sure we pull the "raw" file
    if "pastebin.com/raw/" not in src:
        src = src.replace("pastebin.com/", "pastebin.com/raw/")

    ### Debug
    if debug == True:
        dest = "/tmp/scythe/wasted_info.txt"

    print("            Source :", src)
    print("              Dest :", dest)

    r = urllib.request.Request(src)
    rs = urllib.request.urlopen(r)
    data = rs.read()

    out = open(dest, 'wb')
    out.write(data)
    out.close()
Exemplo n.º 7
0
def _transform_request(request):
    request = request.decode('utf-8')
    request = unquote(request)

    # Direct http example
    if request.startswith('http'):
        request = download_image(request)
    else:
        # Slack Label Example
        request_array = request.split('&')
        print(request_array)

        result = [
            value for value in request_array if value.startswith('text=')
        ]
        if len(result) > 0:
            request = download_image(result[0][5:])
            print(request)

    predict_img = image.load_img(request, target_size=(224, 224))
    predict_img_array = image.img_to_array(predict_img)
    predict_img_array = np.expand_dims(predict_img_array, axis=0)
    predict_preprocess_img = preprocess_input(predict_img_array)

    return predict_preprocess_img
Exemplo n.º 8
0
    def payload(self):
        for picked_ptr in self.item:

            try:
                request = urllib.request.urlopen(picked_ptr).read()
                # Getting the path to the image file
                image_location = request.split(b'<img src=')[-1]
                only_image = eval(image_location.split(b" ")[0])

                # Download path && Download to temp_file and path to download
                temp_name = urllib.request.urlretrieve(self.url + '/' + only_image)[0]

                # Renaming the file from image_only to filename
                filename = only_image.split('/')[-1]

                try:
                    if sys.platform.startswith('win'):
                        shutil.move(temp_name, os.path.abspath(self.full_path + filename))
                        print(os.path.abspath(self.full_path + filename))

                    elif sys.platform.startswith('linux'):
                        shutil.move(temp_name, os.path.join(self.full_path, filename))
                        print(os.path.join(self.full_path, filename))

                except FileExistsError:
                    os.remove(os.path.join(self.full_path, filename))
                    os.remove(temp_name)

            except EnvironmentError:
                pass
Exemplo n.º 9
0
    def parse(self, request):
        """Return the method and the resource name (with /)"""

        lista = request.split()
        method = lista[0]
        resourceName = lista[1]

        return (method, resourceName)
Exemplo n.º 10
0
def getPaintingURLs():
    progress = 0
    # Main url
    listURL = "https://www.wikiart.org/en/api/2/PaintingsByArtist?id="
    paginatedURL = ""
    # Set hasMore default to true
    hasMore = True
    # Set default token to empty string
    paginationToken = ""
    for id in artistIDs:
        while hasMore:
            print(progress)
            progress += 1

            try:
                # get page of list of artists
                request = requests.get(listURL + id + paginatedURL).text
            except:
                continue

            # update hasMore
            request = request.split("\"hasMore\":")

            # break if end of list
            if len(request) < 2:
                break

            if request[1] == "true}":
                hasMore = True

                # update pagination token
                request = request[0].split("\"paginationToken\":")
                paginationToken = request[1].strip("\",")

                # update URL component
                paginatedURL = "&paginationToken=" + paginationToken
            else:
                hasMore = False

                # reset paginatedURL if next request is new artist (aka no pagination token on first page)
                paginatedURL = ""


            # add to set of URLs
            request = request[0].split("\"height\":")
            for url in request:

                url = url.split("\"image\":")

                if len(url) > 1:
                    image = url[1].strip("\",")
                    print(image)
                    imageURLs.add(image)

        # reset hasMore
        hasMore = True
Exemplo n.º 11
0
def filter_requests(request_raw: List, domain: str, before_datetime: datetime) -> List:
    requests_filtered = []

    for request in request_raw:
        if 'UPN: e2e-technical-user' in request and datetime.strptime('/'.join(request.split(' ')[0:2]), '%Y-%m-%d/%H:%M:%S') > \
                before_datetime:
            request_resource = re.search(f'{domain}(.*?)\s+', request)  # noqa
            requests_filtered.append(request_resource.group(1).strip().split('?')[0])

    return requests_filtered
Exemplo n.º 12
0
    def parse(self, request, dic):
        """Parse the received request, extracting the relevant information.
        request: HTTP request received from the client
        """

        parsedRequest = request.split(' ', 2)[1]
        if parsedRequest == "/":
            print("Running app for / \n")
            mode = "root"
            return (request.split(' ', 2)[0], parsedRequest, mode)
        for prefix in dic.keys():
            if parsedRequest[1:].startswith(prefix):
                print("Running app for prefix: " + prefix + "\n")
                mode = prefix
                parsedRequest = parsedRequest[1:]
                parsedRequest = parsedRequest[parsedRequest.find("/"):]
                return (request.split(' ', 2)[0], parsedRequest, mode)
        print("Runing app cache\n")
        mode = "cache"

        return (request.split(' ', 2)[0], parsedRequest, mode)
Exemplo n.º 13
0
    async def parse(self, reader: StreamReader, writer: StreamWriter):
        data = b""

        while not b"\r\n" in data:
            # read data wile does not get first line
            tmp = await reader.read(1024)
            # if empty data
            if not tmp:
                break
            else:
                data += tmp

        # if data is empty
        if not data:
            return

        request = data.decode("utf-8")
        request = request.split("\r\n", 1)[0]
        logging.debug(request.split(" ", 2))
        if len(request.split(" ", 2)) < 3:
            answer = send_error(status_code=404)
            writer.write(answer)
            await writer.drain()

        else:
            method, address, protocol = request.split(" ", 2)
            if method in ("GET", "HEAD"):
                answer = await send_file(address, method,
                                         self._config.root_dir)
                writer.write(answer)
                await writer.drain()

            else:
                answer = send_error(status_code=405)
                writer.write(answer)
                await writer.drain()
            writer.close()
Exemplo n.º 14
0
def doUploader(request, default_sleep, debug):
    print("         > Upload :", request)
    time.sleep(default_sleep)

    req = request.split(" ")
    rpath = req[req.index("--remotepath") + 1].strip('\"')

    # Only specify for Windows
    if "USERPROFILE" in os.environ:
        dest = dest.replace("%USERPROFILE%", os.environ["USERPROFILE"])

    ### Debug
    if debug == True:
        dest = "/tmp/"

    print("         Upload to :", rpath)
Exemplo n.º 15
0
 def parse_raw_request(self, raw_request):
     request = str(raw_request, 'utf-8')
     request = request.rstrip('\r\n')
     elements = request.split()
     if len(elements) == 0:
         raise ValueError("Invalid HTTP entry, please  try again")
     http_method = elements[0]  #Get http_method
     path = elements[1]  #Get path
     for i in elements:
         if i.startswith('HTTP/'):
             http_version = i
     #Get host
     for i in range(0, len(elements) - 1):
         if elements[i] == "Host:":
             host = "http://" + elements[
                 i + 1]  #host has to have "http://" in the beginning
     return http_method, http_version, host, path
Exemplo n.º 16
0
def respond(sock):
    """
    This server responds only to GET requests (not PUT, POST, or UPDATE).
    Any valid GET request is answered with an ascii graphic of a cat.
    """
    sent = 0
    request = sock.recv(1024)  # We accept only short requests
    request = str(request, encoding='utf-8', errors='strict')
    log.info("--- Received request ----")
    log.info("Request was {}\n***\n".format(request))
    cur_path = os
    parts = request.split()
    if len(parts) > 1:
        if (".." in parts[1]) or ("~" in parts[1]) or ("//" in parts[1]):
            log.info("Unhandled request: {}".format(request))
            transmit(STATUS_FORBIDDEN, sock)
            transmit("\nI don't handle this request: {}\n".format(request),
                     sock)
        elif (parts[1][-5:] == ".html") or (parts[1][-4:] == ".css"):
            for m in get_options().DOCROOT.split():
                if parts[1][1:] == m:
                    transmit(STATUS_OK, sock)
                    cur_path = os.path.dirname(
                        os.path.dirname(os.path.abspath(__file__)))
                    f = open(cur_path + "/pages" + parts[1], 'r')
                    w = f.read()
                    f.close()
                    transmit(w, sock)
                    sock.shutdown(socket.SHUT_RDWR)
                    sock.close()
                    return
                else:
                    log.info("Unhandled request: {}".format(request))
                    transmit(STATUS_NOT_FOUND, sock)
                    transmit(
                        "\nThe request is not found: {}\n".format(request),
                        sock)
        else:
            log.info("Unhandled request: {}".format(request))
            transmit(STATUS_FORBIDDEN, sock)
            transmit("\nI don't handle this request: {}\n".format(request),
                     sock)

    sock.shutdown(socket.SHUT_RDWR)
    sock.close()
    return
Exemplo n.º 17
0
def getArtists():
    progress = 0
    # get list of artists by genre / medium and store in set
    artistsURL = "https://www.wikiart.org/en/api/2/UpdatedArtists"
    paginatedURL = ""
    hasMore = True
    paginationToken = ""
    while hasMore:
        print(progress)
        progress += 1

        # get page of list of artists
        request = requests.get(artistsURL + paginatedURL).text

        # update hasMore
        request = request.split("\"hasMore\":")

        # break if end of list
        if len(request) < 2:
            break

        # Checking hasMore in split string for true or false
        if request[1] == "true}":
            hasMore = True
        else:
            hasMore = False

        # update pagination token
        request = request[0].split("\"paginationToken\":")
        paginationToken = request[1].strip("\",")

        #print(request)
        #print(paginationToken)


        # update URL
        paginatedURL = "?paginationToken=" + paginationToken

        # add to set of artists
        request = request[0].split("\"artistName\":")
        for artist in request:
            if artist[-2] == "]":
                continue
            id = artist[-26:-2]
            artistIDs.add(id)
Exemplo n.º 18
0
def crawlStock(stock):
    print("Currently pulling " + stock)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

    f = open(stock + '.txt', 'w')

    url = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stock + "/chartdata;type=quote;range=1y/csv"
    request = urllib.request.urlopen(url).read().decode("utf-8")

    splitSource = request.split('\n')
    for eachLine in splitSource:
        splitData = eachLine.split(',')
        if len(splitData) == 6:
            if 'values' not in eachLine:
                f.write(eachLine + '\n')

    f.close()
    time.sleep(1)
Exemplo n.º 19
0
def submitScore(score, univ_id, password):
    print(univ_id, password)
    request = submitToServer(score, univ_id, password)
    message = request.split(b',')
    if int(message[0]) == 100:
        print('Try to submit in 10 min!')
    elif int(message[0]) == 101:
        print('You already submitted a better result.')
        print('Current Ranking: ', message[1], '/', message[2])
        print('Your Best Score: ', message[3])
    elif int(message[0]) == 102:
        print('Submitted successfully!')
        print('Current Ranking: ', message[1], '/', message[2])
        print('Your Best Score: ', message[3])
    elif int(message[0]) == 501:
        print('Wrong user name or password!')
    else:
        print('Something wrong... Try again later.')
Exemplo n.º 20
0
def doCrypt(request, default_sleep, debug):
    print("         > Crypt:", request)
    time.sleep(default_sleep)

    req = request.split(" ")

    target = req[req.index("--target") + 1].strip('\"')
    password = req[req.index("--password") + 1].strip('\"')

    # Only specify for Windows
    if "USERPROFILE" in os.environ:
        target = target.replace("%USERPROFILE%", os.environ["USERPROFILE"])

    if debug == True:
        target = "/tmp/scythe"

    doErase = False
    doRecurse = False

    if "--erase" in req:
        doErase = True

    # Ignore recurse for now
    if "--recurse" in req:
        doRecurse = True

    allfiles = os.listdir(target)

    for filename in allfiles:
        outfile = filename + ".xor"
        outfile = os.path.join(target, outfile)
        filename = os.path.join(target, filename)

        with open(filename, mode='rb') as file:
            data = file.read()
            enc = doXOR(data, password.encode())
            out = open(outfile, 'wb+')
            out.write(enc)
            out.close()

        if doErase == True:
            os.remove(filename)
Exemplo n.º 21
0
def crawl(stock):
    wb = Workbook()
    ws = wb.active

    url = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stock + "/chartdata;type=quote;range=1y/csv"
    request = urllib.request.urlopen(url).read().decode('utf-8')

    aryName = []
    stockData = []
    splitSource = request.split('\n')
    for line in splitSource:
        splitData = line.split(',')
        if len(splitData) == 6:
            if 'values' in line:
                aryName.append(splitData)
            else:
                stockData.append(splitData)

    aryName[0].append('ma5')
    aryName[0].append('ma10')
    ws.append(aryName[0])

    close = []
    for row in range(len(stockData)):
        close.append(stockData[row][1])

    closep = np.loadtxt(close, float)

    ma5 = moving_average(closep, 5)
    ma10 = moving_average(closep, 10)

    for i in range(9, len(closep)):
        stockData[i].append(ma5[i - 9])
        stockData[i].append(ma10[i - 9])
        ws.append(stockData[i])

    wb.save(stock + '.xlsx')
Exemplo n.º 22
0
def send_lyrics_welcome(message):
    a = telebot.util.extract_arguments(
        message.text
    )  #checa se a pessoa já digitou algo junto ao comando ou não
    if not a:
        if message.chat.type == "private":  #se não, verifica se o comando foi feito em um chat privado ou não
            msg = bot.reply_to(
                message,
                "Digite o nome do artista e a música, separados por uma vírgula (Ex: The Weeknd, Blinding Lights): "
            )  #caso foi no PV, ele pede então o artista para o próximo input
            bot.register_next_step_handler(
                msg, process_lyrics_step
            )  #vai pegar a próxima mensagem como o próximo passo do comando
        else:
            bot.send_message(
                message.chat.id,
                "Esse comando não é apropriado para ser usado em grupos. Se ainda quiser usá-lo, peça diretamente junto ao comando, como por exemplo escrevendo: /lyrics U2, One."
            )  #caso o comando for feito em um grupo, ele deixa apenas caso envie junto do comando, para evitar conflitos com outras mensagens/outros usuários
            return

    else:
        request = a  #O que veio junto ao comando se torna o pedido - request
        get_user = message.from_user.username
        try:
            aux = request.split(
                ",", 1
            )  #Aqui, ele vai separar Artista e Música, que no comando foram escritos com uma vírgula
            separate = aux[1].lstrip(
                " "
            )  #Aqui, ele tira o expaço extra que fica digitado depois da vírgula, evitando erros
        except Exception as e:
            bot.reply_to(
                message,
                "Eita... parece que você não fez corretamente seu pedido. Tente digitar igual ao exemplo, por favor."
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou errado por " + request)
            return  #Se ele não achar, retorna o erro para o usuário e me informa o que tentaram fazer que deu errado, através do terminal

        #condicionais especiais para ajustar específicos artistas que não são bem colocados no Vagalume
        if aux[0] in ['loona', 'Loona', 'LOONA']:
            aux[0] = 'loo'
        if aux[0] in ['april', 'April', 'APRIL']:
            aux[0] = 'april-k-pop'
        if aux[0] in [
                'florence + the machine', 'Florence + The Machine',
                'Florence + the machine'
        ]:
            aux[0] = 'florence-and-the-machine'

        try:
            #processo para retirar acentuações e símbolos, tanto no artista quanto na música
            normalize_artist = normalize('NFKD', aux[0]).encode(
                'ASCII', 'ignore').decode('ASCII')
            normalize_song = normalize('NFKD', separate).encode(
                'ASCII', 'ignore').decode('ASCII')
            #aqui, vai substituir os espaços (e vírgulas) com hífen, para formar o link igual o da API que dá as letras
            artist = normalize_artist.replace(" ", "-")
            song_step1 = normalize_song.replace(",", "-")
            song_step2 = song_step1.replace(" ", "-")
            song = song_step2.replace("--", "-")
        except Exception as e:
            bot.reply_to(
                message,
                "Eita... parece que você não fez corretamente seu pedido. Tente digitar no modelo dos exemplos (/lyrics Slipknot, Duality), por favor."
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou errado por " + request)
            return  #se o processo de ajuste do pedido falhar, significa que o usuário o digitou errado.

        print(get_user + " pediu por " + artist + " - " + song)

        try:
            url = "https://api.vagalume.com.br/search.php" + "?art=" + artist + "&mus=" + song + "&apikey={API_VAGALUME}"
            response = urllib.request.urlopen(
                url)  #abrir a URL que informa as letras
            data = json.loads(
                response.read())  #carregar o json e ler os valores
        except Exception as e:
            bot.reply_to(
                message,
                "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou por " + artist + " e " + song)
            return
        try:
            #pega artista, música e letra
            f_artist = data['art']['name']
            f_song = data['mus'][0]['name']
            f_letra = data['mus'][0]['text']
        except Exception as e:
            bot.reply_to(
                message,
                "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou por " + artist + " e " + song)
            return

        #condicional para caso a letra for grande demais, excedendo os limites do Telegram (dessa forma, enviando em mensagens divididas)
        if len(f_letra) > 3000:
            letra_split = util.split_string(f_letra, 3000)
            bot.send_message(message.chat.id,
                             "`" + f_artist + " - " + f_song + "`" + "\n\n" +
                             letra_split[0],
                             parse_mode='Markdown')
            for text in letra_split:
                bot.send_message(message.chat.id, text)
        else:
            bot.send_message(message.chat.id,
                             "`" + f_artist + " - " + f_song + "`" + "\n\n" +
                             f_letra,
                             parse_mode='Markdown')
Exemplo n.º 23
0
def send_lyricsmin_welcome(message):
    a = telebot.util.extract_arguments(message.text)
    if not a:
        if message.chat.type == "private":
            msg = bot.reply_to(
                message,
                "Digite o nome do artista e a música, separados por uma vírgula (Ex: The Weeknd, Blinding Lights): "
            )
            bot.register_next_step_handler(msg, process_lyricsmin_step)
        else:
            bot.send_message(
                message.chat.id,
                "Esse comando não é apropriado para ser usado em grupos. Se ainda quiser usá-lo, peça diretamente junto ao comando, como por exemplo escrevendo: /lyrics_random U2, One."
            )

    else:

        request = a
        get_user = message.from_user.username
        try:
            aux = request.split(",", 1)
            separate = aux[1].lstrip(" ")
        except Exception as e:
            bot.reply_to(
                message,
                "Eita... parece que você não fez corretamente seu pedido. Tente digitar igual ao exemplo, por favor."
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou errado por " + request)
            return

        if aux[0] in ['loona', 'Loona', 'LOONA']:
            aux[0] = 'loo'
        if aux[0] in ['april', 'April', 'APRIL']:
            aux[0] = 'april-k-pop'
        if a in [
                'florence + the machine', 'Florence + The Machine',
                'Florence + the machine'
        ]:
            a = 'florence-and-the-machine'

        try:
            normalize_artist = normalize('NFKD', aux[0]).encode(
                'ASCII', 'ignore').decode('ASCII')
            normalize_song = normalize('NFKD', separate).encode(
                'ASCII', 'ignore').decode('ASCII')
            artist = normalize_artist.replace(" ", "-")
            song_step1 = normalize_song.replace(",", "-")
            song_step2 = song_step1.replace(" ", "-")
            song = song_step2.replace("--", "-")
        except Exception as e:
            bot.reply_to(
                message,
                "Eita... parece que você não fez corretamente seu pedido. Tente digitar igual ao exemplo, por favor."
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou errado por " + request)
            return

        print(get_user + " pediu por " + artist + " " + song +
              " versão minimalista")

        try:
            url = "https://api.vagalume.com.br/search.php" + "?art=" + artist + "&mus=" + song + "&apikey={API_VAGALUME}"
            response = urllib.request.urlopen(
                url)  #abrir a URL que informa as letras
            data = json.loads(
                response.read())  #carregar o json e ler os valores
        except Exception as e:
            bot.reply_to(
                message,
                "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
            )
            print("Bot encontrou um erro em Lyrics Minimalistas, quando " +
                  get_user + " pesquisou por " + artist + " e " + song)
            return

        try:
            f_artist = data['art']['name']
            f_song = data['mus'][0]['name']
            f_letra = data['mus'][0]['text']
        except Exception as e:
            bot.reply_to(
                message,
                "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
            )
            print("Bot encontrou um erro em Lyrics, quando " + get_user +
                  " pesquisou por " + artist + " e " + song)
            return

        #essa etapa é para juntar estrofes, já que são divididas por duas quebras de linha
        letra_random = f_letra.replace("\n\n", "\n")
        #agora, salva numa array cada verso da música, dividindo a cada quebra de linha
        x = letra_random.split("\n")
        y = len(x)
        #tira 2 para que ele não pegue o último verso da música e não retorne só um
        cont = random.randint(0, y - 2)
        cont2 = cont + 1
        bot.send_message(message.chat.id,
                         "`" + f_artist + " - " + f_song +
                         " (Minimalist Version, by TheLearningBot)" + "`" +
                         "\n\n" + x[cont] + "\n" + x[cont2],
                         parse_mode='Markdown')
Exemplo n.º 24
0
def process_lyricsmin_step(message):
    request = message.text
    get_user = message.from_user.username

    try:
        aux = request.split(",", 1)
        separate = aux[1].lstrip(" ")
    except Exception as e:
        bot.reply_to(
            message,
            "Eita... parece que você não fez corretamente seu pedido. Tente digitar igual ao exemplo, por favor."
        )
        print("Bot encontrou um erro em Lyrics, quando " + get_user +
              " pesquisou errado por " + request)
        return

    if aux[0] in ['loona', 'Loona', 'LOONA']:
        aux[0] = 'loo'
    if aux[0] in ['april', 'April', 'APRIL']:
        aux[0] = 'april-k-pop'
    if a in [
            'florence + the machine', 'Florence + The Machine',
            'Florence + the machine'
    ]:
        a = 'florence-and-the-machine'

    try:
        normalize_artist = normalize('NFKD',
                                     aux[0]).encode('ASCII',
                                                    'ignore').decode('ASCII')
        normalize_song = normalize('NFKD',
                                   separate).encode('ASCII',
                                                    'ignore').decode('ASCII')
        artist = normalize_artist.replace(" ", "-")
        song_step1 = normalize_song.replace(",", "-")
        song_step2 = song_step1.replace(" ", "-")
        song = song_step2.replace("--", "-")

    except Exception as e:
        bot.reply_to(
            message,
            "Eita... parece que você não fez corretamente seu pedido. Tente digitar igual ao exemplo, por favor."
        )
        print("Bot encontrou um erro em Lyrics, quando " + get_user +
              " pesquisou errado por " + request)
        return

    print(get_user + " pediu por " + artist + " " + song +
          " versão minimalista")

    try:
        url = "https://api.vagalume.com.br/search.php" + "?art=" + artist + "&mus=" + song + "&apikey={API_VAGALUME}"
        response = urllib.request.urlopen(
            url)  #abrir a URL que informa as letras
        data = json.loads(response.read())  #carregar o json e ler os valores
    except Exception as e:
        bot.reply_to(
            message,
            "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
        )
        print("Bot encontrou um erro em Lyrics Minimalistas, quando " +
              get_user + " pesquisou por " + artist + " e " + song)
        return

    try:
        f_artist = data['art']['name']
        f_song = data['mus'][0]['name']
        f_letra = data['mus'][0]['text']
    except Exception as e:
        bot.reply_to(
            message,
            "Uepa! Parece que eu não consegui encontrar o artista ou a música que você quer. Confira se você não digitou errado, ou se o artista/música consta no site do Vagalume, e tente novamente. É preciso digitar o nome exatamente como ele consta lá!"
        )
        print("Bot encontrou um erro em Lyrics, quando " + get_user +
              " pesquisou por " + artist + " e " + song)
        return

    letra_random = f_letra.replace("\n\n", "\n")
    x = letra_random.split("\n")
    y = len(x)
    cont = random.randint(0, y - 2)
    cont2 = cont + 1
    bot.send_message(message.chat.id,
                     "`" + f_artist + " - " + f_song +
                     " (Minimalist Version, by TheLearningBot)" + "`" +
                     "\n\n" + x[cont] + "\n" + x[cont2],
                     parse_mode='Markdown')
Exemplo n.º 25
0
 def parse(self, request):
     lista = request.split()
     metodo = lista[0]
     recurso = lista[1][1:]
     return (metodo, recurso)
Exemplo n.º 26
0
    def _process_request(self, request):
        response = ""
        logger.info(request.encode('utf-8'))
        args = request.split('\n')
        for i in range(len(args)):
            args[i] = unescape(args[i])
        logger.info(args)
        cmd = args[0]

        # Lookup
        if (cmd == "L"):
            if len(args) == 2:
                result_list = self.kv_helper.lookup(args[1])
                result = ""
                for key in result_list:
                    if result == "":
                        result = key
                    else:
                        result = result + "," + key
                # Lookup result found
                if result != "":
                    response = "l\n" + escape(result)
                # No result found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Lookup")
                response = "e\nInvalid args for cmd Lookup"

        # Get
        elif (cmd == "G"):
            if len(args) == 3:
                result = self.kv_helper.get(args[1], args[2])
                # Value found
                if result is not None:
                    response = "v\n" + escape(result)
                # Value not found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Get")
                response = "e\nInvalid args for cmd Get"

        # Set
        elif (cmd == "S"):
            if len(args) == 4:
                result = self.kv_helper.set(args[1], args[2], args[3])
                # Set successful (returned True)
                if result:
                    response = "t"
                # Set unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Set")
                response = "e\nInvalid args for cmd Set"

        # Remove
        elif (cmd == "R"):
            if len(args) == 3 or len(args) == 4:
                if len(args) == 3:
                    result = self.kv_helper.remove(args[1], args[2])
                else:
                    result = self.kv_helper.remove(args[1],
                                                   args[2],
                                                   value=args[3])
                # Remove successful (returned True)
                if result:
                    response = "t"
                # Remove unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Remove")
                response = "e\nInvalid args for cmd Remove"
        # Error
        else:
            logger.error("Unknown cmd")
            response = "e\nUnknown cmd"
        return response
Exemplo n.º 27
0
def proxy(conn):
    """Serves a client request to a remote server, and returns the response of the remote server to the client.

    Args:
        conn: a socket object of the client being served

    Returns:
        response: result of the client's request to the remote server
    """
    # Receive data as raw bytes and decode it into a string
    request = conn.recv(MAX_BUFFER_SIZE).decode("UTF-8")
    print("SERVER: Client request received")

    if DEBUG:
        print(request)

    # Get the HTTP request line, then the method and url from the headers (could use urllib.parse next time)
    url = ""
    request_lines = request.split("\n")
    try:
        method = request_lines[0].split(" ")[0].upper()
        url = request_lines[0].split(" ")[1]

        if DEBUG:
            print("Method: " + method + ", URL: " + url)

        if url.find("/proxy/") != -1:
            url = url[url.find("/proxy/") + len("/proxy/"):]
        else:
            print(
                "SERVER: Please specify a URL after {0}:{1}/proxy/ (received {2} instead)"
                .format(hostname, port, url))
            conn.close()
            return None
    except (IndexError, StopIteration):
        pass

    # Search for the user-agent header in the HTTP request and remove trailing whitespace
    ua_header = ""
    try:
        ua_header = next(line for line in request_lines
                         if "User-Agent" in line)[len("User-Agent") +
                                                  2:].rstrip()
    except StopIteration:
        pass

    if DEBUG:
        print("User-Agent: " + ua_header)

    headers = {"User-Agent": ua_header}

    # Serve the client's request
    try:
        if method == "GET":
            # Serves a GET request
            req = urllib.request.Request(url, data=None, headers=headers)
            response = urllib.request.urlopen(req).read()
            conn.sendall(response)
            print("SERVER: Client GET request served")
        elif method == "POST":
            # Serves a POST request

            # Locate the request body
            try:
                body_index = -1
                for line in request_lines:
                    if line in os.linesep:
                        body_index = request_lines.index(line)
                        break
                req_body = "".join(request_lines[body_index:]).strip()

                if DEBUG:
                    print("Request body: " + req_body)

                post_data = dict(
                    item.split('=') for item in req_body.split('&'))

                if DEBUG:
                    for keys, values in post_data.items():
                        print("post_data: " + keys + ": " + values)

                # Encode the key-value pairs; first URL encode, then byte encode using UTF-8
                post_data = urllib.parse.urlencode(post_data)
                post_data = post_data.encode("UTF-8")

            except IndexError as e:
                print(e)
                print("SERVER: Client request not served")
                conn.close()
                return None

            req = urllib.request.Request(url, data=post_data, headers=headers)
            response = urllib.request.urlopen(req).read()
            conn.sendall(response)
            print("SERVER: Client POST request served.")
        else:
            print("SERVER: Request type unimplemented. Please try GET or POST")
        conn.close()
    except (ValueError, urllib.error.HTTPError) as e:
        print(e)
        print("SERVER: Client request not served")
        conn.close()
        return None
Exemplo n.º 28
0
def process(update):
    request = str(update['message']['text']) if 'text' in update['message'] else "$$"
    global chat_id
    chat_id = update['message']['chat']['id']
    global message_id
    message_id = update['message']['message_id']
    user_id = update['message']['from']['id']
    username = update['message']['from']['username'] if 'username' in update['message']['from'] else False
    first_name = update['message']['from']['first_name'] if 'first_name' in update['message']['from'] else False
    last_name = update['message']['from']['last_name'] if 'last_name' in update['message']['from'] else False
    name = (first_name + " ") if first_name else ""
    name += last_name if last_name else ""
    global requester
    requester = username if username else name

    message_timestamp = update['message']['date']

    # update stats
    for chat_var in [Chats, SessionChats]:
        if chat_id in chat_var:
            if user_id in chat_var[chat_id]:
                chat_var[chat_id][user_id].new_message(message_timestamp)
            else:
                chat_var[chat_id][user_id] = UserStat([username, first_name, last_name], timestamp=message_timestamp)
        else:
            chat_var[chat_id] = {user_id: UserStat([username, first_name, last_name], timestamp=message_timestamp)}

    # process received commands
    if request.startswith(botprefix):

        request = request.split(botprefix, 1)[1]
        if request:
            if "@" in request:
                target = request.split("@", 1)[1].split(" ")
                if target[0] != bot_username:
                    return
                else:
                    request = request.replace("@" + bot_username, "")
        else:
            return

        try:
            request = shlex.split(request)
        except ValueError:
            return

        switcher = {
            "": dummy,
            "help": build_help,
            "quote": build_quote,
            "stats_alltime": build_alltime_stats,
            "stats_daily": build_daily_stats,
            "about": build_about,
            "uptime": build_uptime,
            "list_users": list_users,
            "save_stats": save_stats,
            "reset_daily": reset_daily_stats,
            "remember": build_remember_link,
            "forget": build_forget_link,
            "recall": build_recall_link,
            "search": build_search_link,
            "getpic": build_imgur_pic,
            "memegen": build_meme_gen,
            "search_meme": build_search_memes,
            "login_imgur": login_imgur,
            "logout_imgur": logout_imgur,
            "imgur_status": login_status_imgur
        }
        log("Request - " + str(request))
        response = switcher[request[0]](request) if request[0] in switcher else False
        log("Response - " + str(response))
        if response:
            send_message(response)
Exemplo n.º 29
0
    def parse(self, request):
        metodo = request.split(' ', 1)[0]
        recurso = request.split(' ', 2)[1]
        body = request.split('\r\n\r\n')[1]

        return (metodo, recurso, body)
Exemplo n.º 30
0
                        anss = []
                        while ans:
                            num = 4096
                            if len(ans) < num:
                                num = len(ans)
                                anss.append(ans[:num])
                                if len(ans) > num:
                                    ans = ans[num:]
                                else:
                                    ans = ''
                                    for i in anss:
                                        write_msg(current_user, i)

            #игра
            elif act == 'play' and request != 'назад в меню':
                x = request.split()[0]
                req = 'https://api.wordassociations.net/associations/v1.0/json/search?apikey=45197842-3902-45e1-bc7b-bb5fd308657a&text='
                req += x
                req += '&pos=noun&type=response&lang=ru&limit=2'
                response = requests.get(req)
                json_response = response.json()
                print(json_response['response'])
                my_ans = json_response['response'][0]['items'][random.randint(
                    0, 1)]['item']
                ans = nomn_case(my_ans).lower()
                words_menu()
                write_msg2(current_user, ans, keyboard)

            #досье
            elif act == 'user_info':
                msg = info_about_vk(request)
Exemplo n.º 31
0
def get_entry(index):
	url = urlunparse(('http','oeis.org','search','',urlencode({'q':'id:'+index,'fmt':'text'}),''))
	request = urllib.request.urlopen(url).read().decode(encoding='utf-8')
	a_file = request.split('\n\n')[2]
	return Entry(a_file)