mirror of
https://github.com/Marsh232/Telegram-IP-CALC.git
synced 2026-10-12 03:34:12 +00:00
Add /start /calc /help
Refactor calc_subnet()
This commit is contained in:
+63
-20
@@ -6,33 +6,45 @@
|
|||||||
|
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
from aiogram import Bot
|
from aiogram import Bot, Dispatcher, types
|
||||||
|
from aiogram.types import ChatType, ParseMode
|
||||||
|
from aiogram.utils import executor
|
||||||
|
|
||||||
from src.config import Config
|
from src.config import Config
|
||||||
|
|
||||||
config = Config("config.json")
|
config = Config("config.json")
|
||||||
log = logging.getLogger("Bot")
|
log = logging.getLogger("Bot")
|
||||||
|
|
||||||
bot = Bot(token=config.token)
|
bot = Bot(token=config.token)
|
||||||
|
dp = Dispatcher(bot)
|
||||||
|
|
||||||
|
|
||||||
def main(ip):
|
def calc_subnet(_ip):
|
||||||
list_ip = ip.split('/') # Разделяет вводимый ip на часть с маской, и без
|
splt = _ip.split('/') # Разделяет вводимый ip на часть с маской, и без
|
||||||
print('Ваш ip адрес:', ip) # Выводит например "Ваш ip адрес: 192.168.10.128/24"
|
if len(splt) == 1:
|
||||||
|
splt.append("24")
|
||||||
|
|
||||||
|
ip, mask = splt
|
||||||
|
addr = ip + "/" + mask
|
||||||
|
|
||||||
|
net = ipaddress.ip_network(addr, strict=False) # В функцию кладётся сетевая часть ip, без хостовой части
|
||||||
|
dict_out = {
|
||||||
|
"addr": addr,
|
||||||
|
"mask": f"{net.netmask} - {mask}", # Выводит маску
|
||||||
|
"net": f"{net}", # Выводит сеть
|
||||||
|
"broadcast": f'{net.broadcast_address}', # Выводит broadcast
|
||||||
|
"max": f"{net[1]}",
|
||||||
|
"min": f"{net[-2]}",
|
||||||
|
"hosts": f"{len(list(net.hosts()))}",
|
||||||
|
"num": None
|
||||||
|
}
|
||||||
|
|
||||||
net = ipaddress.ip_network(ip, strict=False) # В функцию кладётся сетевая часть ip, без хостовой части
|
|
||||||
print('Маска:', net.netmask, '=', list_ip[1], '\n') # Выводит маску
|
|
||||||
print('Network:', net) # Выводит сеть
|
|
||||||
print('Broadcast:', net.broadcast_address) # Выводит broad
|
|
||||||
print('HostMin:', net[1])
|
|
||||||
print('HostMax:', net[-2])
|
|
||||||
print('Hosts:', len(list(net.hosts()))) # Выводит кол-во хостовых ip
|
|
||||||
count = 0
|
count = 0
|
||||||
for n_ip in net.hosts():
|
for n_ip in net.hosts():
|
||||||
count += 1
|
count += 1
|
||||||
if str(n_ip) == list_ip[0]:
|
if str(n_ip) == ip:
|
||||||
print('№ в сети:', count) # Выводит какой ip по счёту в сети
|
dict_out["num"] = count # Выводит какой ip по счёту в сети
|
||||||
break
|
|
||||||
|
return dict_out
|
||||||
|
|
||||||
|
|
||||||
def subnets(ip, prefix):
|
def subnets(ip, prefix):
|
||||||
@@ -50,13 +62,44 @@ def subnets(ip, prefix):
|
|||||||
print('HostMin:', subnet2[1])
|
print('HostMin:', subnet2[1])
|
||||||
print('HostMax:', subnet2[-2])
|
print('HostMax:', subnet2[-2])
|
||||||
print('Hosts:', len(list((subnet2.hosts()))))
|
print('Hosts:', len(list((subnet2.hosts()))))
|
||||||
print()
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["start"], chat_type=ChatType.PRIVATE)
|
||||||
|
async def start(msg: types.Message):
|
||||||
|
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||||
|
await msg.reply(f"Привет, дорогой мой {msg.from_user.username}")
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["help"], chat_type=ChatType.PRIVATE)
|
||||||
|
async def start(msg: types.Message):
|
||||||
|
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||||
|
await msg.reply("Ты беспомощный")
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=["calc"], chat_type=ChatType.PRIVATE)
|
||||||
|
async def calc(msg: types.Message):
|
||||||
|
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||||
|
text = msg.text
|
||||||
|
splt = text.split(" ")
|
||||||
|
if len(splt) > 1:
|
||||||
|
ip = splt[1]
|
||||||
|
c = calc_subnet(ip)
|
||||||
|
await msg.reply(f"Данные ввода: `{c['addr']}`\n"
|
||||||
|
f"Маска: `{c['mask']}`\n"
|
||||||
|
f"Сеть: `{c['net']}`\n"
|
||||||
|
f"Broadcast: `{c['broadcast']}`\n"
|
||||||
|
f"Макс адресов: `{c['max']}`\n"
|
||||||
|
f"Мин адресов: `{c['min']}`\n"
|
||||||
|
f"Всего адресов: `{c['hosts']}`\n"
|
||||||
|
f"Номер в сети: `{c['num']}`",
|
||||||
|
parse_mode=ParseMode.MARKDOWN)
|
||||||
|
else:
|
||||||
|
await msg.reply("Пример выполнения команды: `/calc 192.168.0.1/24`", parse_mode=ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
addr = input('Введите ip: ') # Пользователь вводит ip
|
executor.start_polling(dp)
|
||||||
main(addr)
|
|
||||||
exit(0)
|
exit(0)
|
||||||
# Тут должна быть кнопка типа "Подсети"
|
# Тут должна быть кнопка типа "Подсети"
|
||||||
new_prefix = input('\nВведите префикс: ')
|
# new_prefix = input('\nВведите префикс: ')
|
||||||
subnets(addr, new_prefix)
|
# subnets(addr, new_prefix)
|
||||||
|
|||||||
Reference in New Issue
Block a user