added /ipcalc command, close #14

This commit is contained in:
kiriharu 2021-01-11 12:00:26 +03:00
parent d778e3b485
commit 335074d693
3 changed files with 63 additions and 1 deletions

View File

@ -6,6 +6,7 @@ from .whois import whois_cmd
from .icmp import ICMPCheckerHandler
from .tcp import TCPCheckerHandler
from .minecraft import MinecraftCheckerHandler
from .ipcalc import IPCalcCommandHandler
def setup(dp: Dispatcher):
@ -15,3 +16,4 @@ def setup(dp: Dispatcher):
dp.register_message_handler(ICMPCheckerHandler().handler, is_forwarded=False, commands=['icmp', 'ping'])
dp.register_message_handler(TCPCheckerHandler().handler, is_forwarded=False, commands=['tcp'])
dp.register_message_handler(MinecraftCheckerHandler().handler, is_forwarded=False, commands=['minecraft'])
dp.register_message_handler(IPCalcCommandHandler().handler, is_forwarded=False, commands=['ipcalc'])

View File

@ -0,0 +1,59 @@
from aiogram.types import Message
from typing import Union
import ipaddress
from tgbot.handlers.base import SimpleCommandHandler, NotEnoughArgs
ipcalc_help_message = """
Калькулятор IP подсетей.
Использование:
`/ipcalc <ip_with_mask>`
`/ipcalc <ip>` - автоматически выставит маску 32
"""
class IPCalcCommandHandler(SimpleCommandHandler):
help_message = ipcalc_help_message
def __init__(self):
super().__init__()
async def handler(self, message: Message):
try:
args = await self.process_args(message.text)
network = ipaddress.ip_network(args[1], False)
except NotEnoughArgs:
await message.answer(self.help_message)
except ValueError:
await message.answer(self.help_message)
else:
msg = await self.prepare_message(network)
await message.answer(msg)
async def process_args(self, text: str) -> list:
args = text.split(" ")
if len(args) == 1:
raise NotEnoughArgs
return args
async def prepare_message(self, ip_net: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]) -> str:
work_adresses = ip_net.num_addresses - 2
first_ip = "Нет доступных адресов."
last_ip = first_ip
if ip_net.num_addresses <= 2:
work_adresses = 0
else:
first_ip = list(ip_net.hosts())[0]
last_ip = list(ip_net.hosts())[-1]
return f"📱 IP подсети: {ip_net.with_prefixlen}\n" \
f"📌 Маска подсети: {ip_net.netmask}\n" \
f"📌 Обратная маска: {ip_net.hostmask}\n" \
f"📌 Широковещательный адрес: {ip_net.broadcast_address}\n" \
f"📌 Доступные адреса: {ip_net.num_addresses}\n" \
f"📌 Рабочие адреса: {work_adresses}\n\n" \
f"🔼 IP первого хоста: {first_ip}\n" \
f"🔽 IP последнего хоста: {last_ip}"

View File

@ -13,6 +13,7 @@ start_message = f"""
📌 /web `<host>` - Произведёт проверку по протоколу HTTP и вернёт код ответа
📌 /whois `<host>` - Вернёт информацию whois по домену
📌 /minecraft `<host> <port>` - Вернёт информацию связанную с Minecraft-сервером
📌 /ipcalc `<ip>` - Калькулятор подсетей
🚩[Репозиторий бота здесь](https://github.com/catspace-dev/unicheckbot).
🚩[Предложения или замечания можно оставлять здесь](https://github.com/catspace-dev/unicheckbot/issues).