Skip to content
Permalink
Browse files

final fixes

  • Loading branch information...
progsly committed Nov 21, 2017
1 parent d2534cb commit 50d646648051d0050eaa5b7eb7575a94b4937be3
@@ -1 +1,56 @@
# converter-bot
# Бот для чата [Радио-Т](https://github.com/umputun/rt-bot)

## Описание
Бот конвертер. Если сообщение начинается с цифры и в тексте есть упоминания едениц измерения, бот конвертирует значение.


### Пример 1
Сообщение:
```json
{
text: "1 миля это сколько?",
username: "test",
display_name: "test"
}
```

Ответ:
**_test_** упомянул 1 миля

Метр 1609.344

Километр 1.609

Миллиметр 1609344.0

Дециметр 16093.44

Дюйм 63359.873

Сантиметр 160934.4

Фут 5280.0

### Пример 2
Сообщение:
```json
{
text: "1 литр это сколько пинт",
username: "test",
display_name: "test"
}
```

Ответ:
**_test_** упомянул 1 литр

Пинта 2.113

### Пример ответа в json
Сообщение:
```json
{
"text": "**_test_** упомянул 1 литр \\nПинта 2.113 ",
"bot": "converter-bot"
}
```
@@ -6,8 +6,8 @@ ignored_commands:
- "Как дела?"

test_cases:
- command: "что лучше, этот или тот?"
- command: "1 метр в сантиметрах"
result: ".+"

- command: "кто лучше, я или он"
- command: "10 мегабайт"
result: ".+"
@@ -13,35 +13,35 @@ class Converter(object):
categories = []
value = None
DB = {}
LANGUAGE = 'ru'
LANGUAGE = "ru"

def __init__(self):
self.units['length'] = length
self.units['mass'] = mass
self.units['temperature'] = temperature
self.units['time'] = time
self.units['volume'] = volume
self.units['data'] = data_db
self.units["length"] = length
self.units["mass"] = mass
self.units["temperature"] = temperature
self.units["time"] = time
self.units["volume"] = volume
self.units["data"] = data_db
self.map_aliases()

def map_aliases(self):
for category, data in self.units.items():
for unit, items in data['units'].items():
for alias in items['languages']['ru']['aliases']:
for unit, items in data["units"].items():
for alias in items["languages"]["ru"]["aliases"]:
self.aliases[alias] = {
'unit': unit,
'category': category,
'from': items['from'],
'to': items['to'],
'name': items['languages']['ru']['name']
"unit": unit,
"category": category,
"from": items["from"],
"to": items["to"],
"name": items["languages"]["ru"]["name"]
}
for alias in items['languages']['en']['aliases']:
for alias in items["languages"]["en"]["aliases"]:
self.aliases[alias] = {
'unit': unit,
'category': category,
'from': items['from'],
'to': items['to'],
'name': items['languages']['en']['name']
"unit": unit,
"category": category,
"from": items["from"],
"to": items["to"],
"name": items["languages"]["en"]["name"]
}

def analyse(self, message):
@@ -54,41 +54,41 @@ def analyse(self, message):
if len(units) == 0:
return False, {}
data = self.process_unit(units)
return True, {'value': self.value, 'unit': units[0], 'data': data}
return True, {"value": self.value, "unit": units[0], "data": data}

def process_unit(self, units):
current = self.aliases[units[0]]
original = eval(current['from'].format(n=self.value))
original = eval(current["from"].format(n=self.value))
data = []
if len(units) == 2:
current_2 = self.aliases[units[1]]
if current['category'] == current_2['category'] and current['unit'] != current_2['unit']:
to = eval(current_2['to'].format(n=original))
if current["category"] == current_2["category"] and current["unit"] != current_2["unit"]:
to = eval(current_2["to"].format(n=original))
to = round(to, 3)
data.append({'value': to, 'name': self.units[self.aliases[units[0]]['category']]['units']
[current_2['unit']]['languages'][self.LANGUAGE]['name']})
data.append({"value": to, "name": self.units[self.aliases[units[0]]["category"]]["units"]
[current_2["unit"]]["languages"][self.LANGUAGE]["name"]})
return data

for unit, item in self.units[self.aliases[units[0]]['category']]['units'].items():
if unit == current['unit']:
for unit, item in self.units[self.aliases[units[0]]["category"]]["units"].items():
if unit == current["unit"]:
continue
to = eval(item['to'].format(n=original))
to = eval(item["to"].format(n=original))
to = round(to, 3)
data.append({'value': to, 'name': item['languages'][self.LANGUAGE]['name']})
data.append({"value": to, "name": item["languages"][self.LANGUAGE]["name"]})

return data

def get_value(self, message):
result = re.match(r'^\s*([+-]?((?=\.)\.\d+|\d+(?:[\.,]?\d+)?))', message)
result = re.match(r"^\s*([+-]?((?=\.)\.\d+|\d+(?:[\.,]?\d+)?))", message)
if result is not None:
value = result.group(0)
return value.replace(',', '.')
return value.replace(",", ".")
else:
return None

def fetch_aliases(self, message):
reg = re.compile('[^a-zA-Zа-яёА-ЯЁ ]')
message = reg.sub('', message)
reg = re.compile("[^a-zA-Zа-яёА-ЯЁ ]")
message = reg.sub("", message)
words = message.split()
units = []
while len(words) and len(units) <= 2:
@@ -127,7 +127,7 @@
},
'ru': {
'name': 'Пинта',
'aliases': ['пт', 'пинт', 'пинта', 'питнах', 'пинты']
'aliases': ['пт', 'пинт', 'пинта', 'пинтах', 'пинты']
}
}
},
@@ -7,33 +7,38 @@

def event():
try:
data = json.loads(request.data.decode('utf-8'))
data = json.loads(request.data.decode("utf-8"))
except ValueError:
return silence()

message = data.get('text')
display_name = data.get('display_name')
message = message.strip()
status, data = app.converter.analyse(message)
if status:
resp = display_name + ' упомянул ' + str(data['value']) + ' ' + str(data['unit'])
for item in data['data']:
resp += '\n\n' + ' ' + str(item['value']) + ' - ' + item['name']

return Response(
response=json.dumps({'text': resp, 'bot': 'converter-bot'}),
status=201,
mimetype="application/json"
)
else:
try:
message = data.get("text")
display_name = data.get("display_name")
username = data.get("username")
message = message.strip()
status, data = app.converter.analyse(message)
if status:
resp = "**_" + username + "_** " + "упомянул " + str(data["value"]) + " " + str(data["unit"]) + " "
for item in data["data"]:
resp += "\\n" + item["name"] + " " + str(item["value"]) + " "

return Response(
response=json.dumps({"text": resp, "bot": "converter-bot"}),
status=201,
mimetype="application/json"
)
else:
return silence()
except ValueError:
return silence()


def info():
return Response(
response=json.dumps({
'author': "Sergey Kovalchuk",
"info": "Бот конвертер "
"author": "progsly",
"info": "Бот конвертер. Если сообщение начинается с цифры и в тексте есть упоминания едениц измерения, "
"бот конвертирует значение."
}),
status=200,
mimetype="application/json",
@@ -42,18 +47,17 @@ def info():

def silence():
return Response(
response=json.dumps({'error': True, 'status': 417}),
response=json.dumps({"error": True, "status": 417}),
status=417,
mimetype="application/json"
)


app = Flask('converter-bot')
app = Flask("converter-bot")
app.converter = Converter()

app.add_url_rule('/event', 'event', event, methods=['POST'])
app.add_url_rule('/info', 'info', info, methods=['GET'])
app.add_url_rule("/event", "event", event, methods=["POST"])
app.add_url_rule("/info", "info", info, methods=["GET"])

if __name__ == "__main__":
# app.run(host='0.0.0.0', port=8080)
app.run(host='0.0.0.0', debug=True)
app.run(host="0.0.0.0", port=8080)
@@ -58,6 +58,7 @@ services:
- lucky
- weather-bot
- or-bot
- converter-bot

hello:
build: hello
@@ -314,3 +315,11 @@ services:
hostname: or-bot
restart: always
logging: *default_logging

converter-bot:
build: converter-bot
image: rtbot/converter-bot
container_name: converter-bot
hostname: converter-bot
restart: always
logging: *default_logging
@@ -18,7 +18,7 @@ server {

location /list {
default_type application/json;
return 200 '["hello", "memberberries", "wiki-bot", "search-bot", "noter-bot", "repl-bot", "stat-bot", "5minphp-bot", "loro-bot", "brackets-bot", "guido-bot", "karma-bot", "anek-bot", "ksenks-bot", "rtnumber-bot", "excerpt-bot", "tweet-bot", "rest-voter", "hcalendar-bot", "doit-bot", "money-bot", "docker-bot", "random-bot", "bot-4-bots", "lucky", "weather-bot", "or-bot"]';
return 200 '["hello", "memberberries", "wiki-bot", "search-bot", "noter-bot", "repl-bot", "stat-bot", "5minphp-bot", "loro-bot", "brackets-bot", "guido-bot", "karma-bot", "anek-bot", "ksenks-bot", "rtnumber-bot", "excerpt-bot", "tweet-bot", "rest-voter", "hcalendar-bot", "doit-bot", "money-bot", "docker-bot", "random-bot", "bot-4-bots", "lucky", "weather-bot", "or-bot", "converter-bot"]';
}

location /api/hello/ {
@@ -253,6 +253,13 @@ server {
proxy_pass http://or-bot:8080/;
}

location /api/converter-bot/ {
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://converter-bot:8080/;
}

location / {
return 302 'https://github.com/umputun/rt-bot';

0 comments on commit 50d6466

Please sign in to comment.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.