Exemple #1
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from common import generate_request
from commands.command__weather_in_city.server import WeatherServer
from db import get_execute_command_url_server

url = get_execute_command_url_server(WeatherServer.guid)
command_name = 'погода'

import requests
rs = requests.post(url,
                   json=generate_request(command_name, command='Магнитогорск'))
print(rs.json())

rs = requests.post(url,
                   json=generate_request(command_name, command='Челябинск'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='Москва'))
print(rs.json())

rs = requests.post(url,
                   json=generate_request(command_name, command='3421выаы:)'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command=''))
print(rs.json())
Exemple #2
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from common import generate_request
from commands.command__exchange_rate.server import ExchangeRateServer
from db import get_execute_command_url_server

url = get_execute_command_url_server(ExchangeRateServer.guid)
command_name = 'курс валют'

import requests
rs = requests.post(url, json=generate_request(command_name))
print(rs.json())

rs = requests.post(url,
                   json=generate_request(command_name=command_name,
                                         command='ok'))
print(rs.json())
Exemple #3
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'


from common import generate_request
from commands.command__calc.server import CalcServer
from db import get_execute_command_url_server

url = get_execute_command_url_server(CalcServer.guid)
command_name = 'калькулятор'


import requests
rs = requests.post(url, json=generate_request(command_name))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='2 + 2'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='2 + 2 * 2'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='10 ** 3'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='sin(2 ** 10)'))
print(rs.json())

rs = requests.post(url, json=generate_request(command_name, command='(0xFF + 255) / 0b1010'))
Exemple #4
0
    def _execute_body(self, rq: dict,
                      **params: dict) -> typing.Union[dict, str]:
        command = rq['command']
        command_name = rq['command_name']
        attachment = rq['attachment']

        # Если команды нет, показываем список команд
        if not command.strip():
            return self.get_top10_commands(as_result=True)

        # Приведение в нижний регистр чтобы проверка команды была регистронезависимой
        execute_command = command.lower()
        print('execute_command: "{}"'.format(execute_command))

        all_command_by_url = db.get_all_command_name_by_url()
        command_name_list = [x.lower() for x in all_command_by_url.keys()]

        # Если текущая команда не была найдена среди списка команд хотя бы по совпадению начальной строки,
        # пытаемся найти, учитывая, что в ней могут быть опечатки, иначе ругаемся на неизвестную команду
        if not any(execute_command.startswith(x) for x in command_name_list):
            fix_execute_command = None

            for command_name in command_name_list:
                word_list = execute_command.split()
                for i in range(1, len(word_list) + 1):
                    part_command_name = ' '.join(word_list[:i])

                    # Если нашли команду
                    if command_name == fix_command(part_command_name,
                                                   command_name_list):
                        # Составляем команду с текстом
                        fix_execute_command = ' '.join([command_name] +
                                                       word_list[i:])

            # Если это была опечатка, обновляем запрос команды, исправив опечатку
            if fix_execute_command is not None and execute_command != fix_execute_command:
                print('fix execute command: "{}" -> "{}"'.format(
                    execute_command, fix_execute_command))
                execute_command = fix_execute_command

            # Если не удалось разобрать команду как опечатку
            if fix_execute_command is None:
                result = 'Получена неизвестная команда "{}".\n' \
                         'Чтобы узнать доступные команды введи: Бот, команды'.format(command)

                return result

        # Обработка собственных команд
        if execute_command == 'команды':
            return self.get_top10_commands(as_result=True)

        elif execute_command == 'все команды':
            return self.get_commands(as_result=True)

        for command_name, url in all_command_by_url.items():
            if execute_command.startswith(command_name.lower()):
                command_text = command[len(command_name):].strip()
                print(
                    'Found server: {}, command name: "{}", command text: "{}"'.
                    format(url, command_name, command_text))

                rq = generate_request(command_name, command_text, attachment)
                print('Generate request:', rq)

                import requests
                try:
                    rs = requests.post(url, json=rq)
                    print('Response:', rs.text)
                    return rs.json()

                except requests.exceptions.ConnectionError:
                    error = 'Сервер команды "{}" ({}) недоступен'.format(
                        command_name, url)
                    return self.generate_response(error=error)

        error = 'Что-то пошло не так: команда "{}" не была распознана'.format(
            command)
        return self.generate_response(error=error)
Exemple #5
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from common import generate_request
from commands.command__text_converter.server import TextConverter
from db import get_url_server

url = get_url_server(TextConverter.guid)

import requests

rs = requests.post(url + '/execute?str2hex',
                   json=generate_request(command_name='str2hex',
                                         command='Привет мир!'))
print(rs.json())
assert rs.json()['result'] == 'D09FD180D0B8D0B2D0B5D18220D0BCD0B8D18021'

rs = requests.post(url + '/execute?hex2str',
                   json=generate_request(
                       command_name='hex2str',
                       command='D09FD180D0B8D0B2D0B5D18220D0BCD0B8D18021'))
print(rs.json())
assert rs.json()['result'] == 'Привет мир!'

rs = requests.post(url + '/execute?str2bin',
                   json=generate_request(command_name='str2bin',
                                         command='Привет мир!'))
print(rs.json())
assert rs.json()['result'] == '11001111 11110000 11101000 11100010 11100101 11110010 ' \
Exemple #6
0
import requests
import pathlib
from common import generate_request, create_attachment, FileAttachment, AttachmentType
from commands.command__get_image_info.server import GetImageInfoServer
from db import get_execute_command_url_server

url = get_execute_command_url_server(GetImageInfoServer.guid)
command_name = 'получить информацию о картинке'

FILE_NAME = 'example.jpg'

with open(FILE_NAME, 'rb') as f:
    content = f.read()
    extension = pathlib.Path(FILE_NAME).suffix[1:]

attachment = FileAttachment(content=content, extension=extension)
attachment_type = AttachmentType.IMAGE

rs = requests.post(url, json=generate_request())
print(rs.json())

rs = requests.post(url, json=generate_request(command_name))
print(rs.json())

rs = requests.post(url,
                   json=generate_request(command_name,
                                         attachment=create_attachment(
                                             attachment, attachment_type)))
print(rs.json())
print(rs.json()['result'])