Skip to content

Commit 5ff1a38

Browse files
committed
Add base64 conversion, keyboard layout correcting; remove the shrugging
¯\_(ツ)_/¯ was removed in favor of recently discovered specialized @shrugbot. Implement #4.
1 parent ae17823 commit 5ff1a38

3 files changed

Lines changed: 84 additions & 18 deletions

File tree

app/bot.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python3
22

3+
import string
34
import logging
45
from aiohttp import web
56
from aiotg import Bot, Chat, InlineQuery
@@ -51,26 +52,27 @@ def empty_suggest(chat: Chat, _) -> None:
5152

5253

5354
@bot.inline
54-
def shrug_shoulders(request: InlineQuery) -> None:
55-
str_from_bin = bin_to_str(request.query)
56-
str_from_hex = hex_to_str(request.query)
57-
55+
def inline_request_handler(request: InlineQuery) -> None:
5856
results = InlineQueryResultsBuilder()
5957
add_article = get_articles_generator_for(results)
6058

61-
if str_from_bin:
62-
add_article("Притвориться человеком", str_from_bin)
63-
elif str_from_hex:
64-
add_article("Просто текст", str_from_hex)
65-
else:
66-
lentach_logo = "{} ¯\_(ツ)_/¯".format(request.query).lstrip()
67-
add_article("Пожать плечами", lentach_logo)
68-
69-
if request.query:
70-
binary = str_to_bin(request.query)
71-
hex_str = str_to_hex(request.query)
72-
add_article("Говорить, как робот", binary)
73-
add_article("Типа программист", hex_str)
59+
if all(map(lambda char: char in (0, 1), request.query)):
60+
str_from_bin = bin_to_str(request.query)
61+
if str_from_bin:
62+
add_article("Притвориться человеком", str_from_bin)
63+
elif all(map(lambda char: char in string.hexdigits, request.query)):
64+
str_from_hex = hex_to_str(request.query)
65+
if str_from_hex:
66+
add_article("Просто текст", str_from_hex)
67+
elif all(map(lambda char: char in string.ascii_letters + string.digits + '+/=', request.query)):
68+
str_from_base64 = base64_to_str(request.query)
69+
if str_from_base64:
70+
add_article("Дешифровка", str_from_base64)
71+
elif request.query:
72+
add_article("Проблемы с раскладкой?", switch_keyboard_layout(request.query))
73+
add_article("Говорить, как робот", str_to_bin(request.query))
74+
add_article("Типа программист", str_to_hex(request.query))
75+
add_article("Шифровка", str_to_base64(request.query))
7476

7577
request.answer(results.build_list())
7678

app/strconv.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
"""Utility functions for string conversions."""
22

33
import re
4+
import string
5+
import base64
6+
import binascii
47
from typing import Optional
58

69

7-
__all__ = ['escape_html', 'str_to_bin', 'str_to_hex', 'bin_to_str', 'hex_to_str']
10+
__all__ = ['escape_html', 'str_to_bin', 'str_to_hex', 'str_to_base64', 'bin_to_str', 'hex_to_str', 'base64_to_str',
11+
'switch_keyboard_layout']
812

913

1014
def escape_html(text: str) -> str:
@@ -40,6 +44,10 @@ def str_to_hex(s: str) -> str:
4044
return " ".join(bl)
4145

4246

47+
def str_to_base64(s: str) -> str:
48+
return base64.encodebytes(bytes(s, 'UTF-8')).decode('UTF-8').rstrip()
49+
50+
4351
def bin_to_str(b: str) -> Optional[str]:
4452
"""
4553
'01001000 01100101 01101100 01101100 01101111' => 'Hello'
@@ -66,3 +74,27 @@ def hex_to_str(s: str) -> Optional[str]:
6674
return bytearray.fromhex(s).decode()
6775
except ValueError:
6876
return None
77+
78+
79+
def base64_to_str(b: str) -> Optional[str]:
80+
try:
81+
return base64.decodebytes(bytes(b, 'UTF-8')).decode('UTF-8')
82+
except binascii.Error or UnicodeDecodeError:
83+
return None
84+
85+
86+
def switch_keyboard_layout(s: str) -> str:
87+
en_weight = sum(c in string.ascii_letters for c in s)
88+
ru_weight = sum(c in _russian_letters for c in s)
89+
if ru_weight > en_weight:
90+
return s.translate(_layouts_correspondings_table_ru_en)
91+
else:
92+
return s.translate(_layouts_correspondings_table_en_ru)
93+
94+
95+
_russian_letters = "абвгдеёжзийклмонпрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
96+
_latin_layout = "qwertyuiop[]asdfghjkl;'\zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>?@#$^&"
97+
_cyrillic_layout = "йцукенгшщзхъфывапролджэ\ячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,\"№;:?"
98+
99+
_layouts_correspondings_table_en_ru = str.maketrans(_latin_layout, _cyrillic_layout)
100+
_layouts_correspondings_table_ru_en = str.maketrans(_cyrillic_layout, _latin_layout)

tests/test_strconv.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,35 @@ def test_to_str(self):
5555
def test_fails(self):
5656
assert hex_to_str(self.f1) is None
5757
assert hex_to_str(self.f2) is None
58+
59+
60+
class TestBase64:
61+
s = "Hello World"
62+
b = "SGVsbG8gV29ybGQ="
63+
sr = "Привет, мир!"
64+
br = "0J/RgNC40LLQtdGCLCDQvNC40YAh"
65+
f = "Не base64-строка"
66+
67+
def test_from_str(self):
68+
assert str_to_base64(self.s) == self.b
69+
70+
def test_to_str(self):
71+
assert base64_to_str(self.b) == self.s
72+
73+
def test_russian(self):
74+
assert str_to_base64(self.sr) == self.br
75+
assert base64_to_str(self.br) == self.sr
76+
77+
def test_fails(self):
78+
assert base64_to_str(self.f) is None
79+
80+
81+
class TestLayoutSwitcher:
82+
en = "J,kf;fkcz c hfcrkflrjq"
83+
ru = "Облажался с раскладкой"
84+
85+
def test_en_ru(self):
86+
assert switch_keyboard_layout(self.en) == self.ru
87+
88+
def test_ru_en(self):
89+
assert switch_keyboard_layout(self.ru) == self.en

0 commit comments

Comments
 (0)