mirror of
https://github.com/Marsh232/Telegram-IP-CALC.git
synced 2026-02-16 02:20:53 +00:00
Add function subnets
This commit is contained in:
125
src/main.py
125
src/main.py
@@ -9,21 +9,29 @@ import logging
|
||||
from aiogram import Bot, Dispatcher, types
|
||||
from aiogram.types import ChatType, ParseMode, KeyboardButton, ReplyKeyboardMarkup
|
||||
from aiogram.utils import executor
|
||||
from aiogram.contrib.fsm_storage.memory import MemoryStorage
|
||||
|
||||
from utils import Config
|
||||
|
||||
from utils import Config, FSMachine, FSMContext
|
||||
|
||||
storage = MemoryStorage()
|
||||
|
||||
config = Config("config.json")
|
||||
log = logging.getLogger("Bot")
|
||||
bot = Bot(token=config.token)
|
||||
dp = Dispatcher(bot)
|
||||
dp = Dispatcher(bot, storage=storage)
|
||||
|
||||
network_button = KeyboardButton('🧮Сеть🧮')
|
||||
subnet_button = KeyboardButton('🕸Подсети🕸')
|
||||
cancel_button = KeyboardButton('❌Отмена❌')
|
||||
more_button = KeyboardButton('📝Прочее📝')
|
||||
|
||||
network_button = KeyboardButton('Сеть')
|
||||
subnet_button = KeyboardButton('Подсети')
|
||||
start_buttons = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False)
|
||||
start_buttons.row(network_button, subnet_button)
|
||||
start_buttons.add(more_button).add(cancel_button)
|
||||
|
||||
|
||||
def calc_subnet(_ip):
|
||||
def calc_net(_ip):
|
||||
splt = _ip.split('/') # Разделяет вводимый ip на часть с маской, и без
|
||||
if len(splt) == 1:
|
||||
splt.append("24")
|
||||
@@ -52,40 +60,59 @@ def calc_subnet(_ip):
|
||||
return dict_out
|
||||
|
||||
|
||||
def subnets(ip, prefix):
|
||||
subnet = ipaddress.ip_network(ip, strict=False)
|
||||
list_subnet = list(subnet.subnets(new_prefix=int(prefix)))
|
||||
subnet1 = ipaddress.ip_network(str(list_subnet[1]), strict=False)
|
||||
|
||||
print('\nМаска:', subnet1.netmask, '=', prefix)
|
||||
print()
|
||||
|
||||
for i in list_subnet:
|
||||
subnet2 = ipaddress.ip_network(i, strict=False)
|
||||
print('Network:', subnet2)
|
||||
print('Broadcast:', subnet2.broadcast_address)
|
||||
print('HostMin:', subnet2[1])
|
||||
print('HostMax:', subnet2[-2])
|
||||
print('Hosts:', len(list((subnet2.hosts()))))
|
||||
#def calc_subnets(ip, prefix):
|
||||
# subnet = ipaddress.ip_network(ip, strict=False)
|
||||
# list_subnet = list(subnet.subnets(new_prefix=int(prefix)))
|
||||
# subnet1 = ipaddress.ip_network(str(list_subnet[1]), strict=False)
|
||||
#
|
||||
# print('\nМаска:', subnet1.netmask, '=', prefix)
|
||||
# print()
|
||||
#
|
||||
# for i in list_subnet:
|
||||
# subnet2 = ipaddress.ip_network(i, strict=False)
|
||||
# print('Network:', subnet2)
|
||||
# print('Broadcast:', subnet2.broadcast_address)
|
||||
# print('HostMin:', subnet2[1])
|
||||
# print('HostMax:', subnet2[-2])
|
||||
# print('Hosts:', len(list((subnet2.hosts()))))
|
||||
|
||||
|
||||
@dp.message_handler(commands=["start"], chat_type=ChatType.PRIVATE)
|
||||
@dp.message_handler(commands=["start"], state=None, 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}", reply_markup=start_buttons)
|
||||
await msg.reply(f"Привет {msg.from_user.username}😀, я IP Bot🤖, я могу посчитать🧮 ip и не только.", reply_markup=start_buttons)
|
||||
|
||||
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('сеть'))
|
||||
async def calcnet(msg: types.Message):
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('❌отмена❌'), state="*")
|
||||
#@dp.message_handler(Text(equals='отмена', ignore_case=True), state="*")
|
||||
async def cancel_handler(msg: types.Message, state: FSMContext):
|
||||
current_state = await state.get_state()
|
||||
if current_state is None:
|
||||
return
|
||||
await state.finish()
|
||||
await msg.reply('Ок🥸')
|
||||
|
||||
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('📝прочее📝'))
|
||||
async def more_handler(msg: types.Message, state: FSMContext):
|
||||
await msg.reply(f"📄Все идеи и предложения писать -> @ilassik📄\n"
|
||||
f"💸Донаты -> www.donationalerts.com/r/ilassik💸",
|
||||
parse_mode=ParseMode.MARKDOWN,
|
||||
reply_markup=start_buttons)
|
||||
|
||||
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('🧮сеть🧮'))
|
||||
async def calcnet(msg: types.Message, state: FSMContext):
|
||||
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||
await msg.reply("Введи ip")
|
||||
await FSMachine.network.set()
|
||||
await msg.reply("Введите ip")
|
||||
|
||||
|
||||
@dp.message_handler(regexp=r"^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}(|\/\d{0,2})$", chat_type=ChatType.PRIVATE)
|
||||
async def calcnet1(msg):
|
||||
@dp.message_handler(state=FSMachine.network, chat_type=ChatType.PRIVATE)
|
||||
async def calcnet1(msg: types.Message, state: FSMContext):
|
||||
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||
text = msg.text
|
||||
c = calc_subnet(text)
|
||||
c = calc_net(text)
|
||||
await msg.reply(f"Вводимые данные: `{c['addr']}`\n"
|
||||
f"Маска: `{c['mask']}`\n"
|
||||
f"Сеть: `{c['net']}`\n"
|
||||
@@ -96,19 +123,49 @@ async def calcnet1(msg):
|
||||
f"Номер в сети: `{c['num']}`",
|
||||
parse_mode=ParseMode.MARKDOWN,
|
||||
reply_markup=start_buttons)
|
||||
await state.finish()
|
||||
|
||||
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('подсети'))
|
||||
async def calcsub(msg: types.Message):
|
||||
@dp.message_handler(lambda msg: msg.text.lower().startswith('🕸подсети🕸'))
|
||||
async def calcsub(msg: types.Message, state: FSMContext):
|
||||
log.info(f"New message from {msg.from_user.id}(@{msg.from_user.username}) in {msg.chat.id}: '{msg.text}'")
|
||||
await FSMachine.subnetwork.set()
|
||||
await msg.reply("**Введите ip с увеличенной маской**"
|
||||
"**Пример -> 10.10.10.10/24 26**")
|
||||
|
||||
|
||||
@dp.message_handler(state=FSMachine.subnetwork, chat_type=ChatType.PRIVATE)
|
||||
async def calcsub1(msg: types.Message, state: FSMContext):
|
||||
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]
|
||||
await msg.reply("Не готова")
|
||||
try:
|
||||
ip = splt[0]
|
||||
prefix = splt[1]
|
||||
subnet = ipaddress.ip_network(ip, strict=False)
|
||||
list_subnet = list(subnet.subnets(new_prefix=int(prefix)))
|
||||
subnet1 = ipaddress.ip_network(str(list_subnet[1]), strict=False)
|
||||
|
||||
await msg.reply(f"Маска: {subnet1.netmask} = {prefix}")
|
||||
|
||||
for i in list_subnet:
|
||||
subnet2 = ipaddress.ip_network(i, strict=False)
|
||||
await msg.reply(f"Network: `{subnet2}`\n"
|
||||
f"Broadcast: `{subnet2.broadcast_address}`\n"
|
||||
f"HostMin: `{subnet2[1]}`\n"
|
||||
f"HostMax: `{subnet2[-2]}`\n"
|
||||
f"Hosts: `{len(list((subnet2.hosts())))}`",
|
||||
parse_mode=ParseMode.MARKDOWN,
|
||||
reply_markup=start_buttons)
|
||||
await state.finish()
|
||||
except IndexError:
|
||||
await msg.reply("**😡Вы ввели неправильно**😡\n"
|
||||
"**🤓Попробуйте ещё раз🤓**",
|
||||
parse_mode=ParseMode.MARKDOWN)
|
||||
else:
|
||||
await msg.reply("**Командна введена не правильно**\n"
|
||||
"Пример выполнения команды: `/calcsub 192.168.0.1/24 26`",
|
||||
await msg.reply("**😡ВЫ ввели неправильно**😡\n"
|
||||
"🤓Пример ввода: ` 192.168.0.1/24 26`🤓",
|
||||
parse_mode=ParseMode.MARKDOWN)
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ import logging
|
||||
import json
|
||||
import os
|
||||
|
||||
from aiogram.dispatcher import FSMContext
|
||||
from aiogram.dispatcher.filters.state import State, StatesGroup
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)-29s - %(levelname)-5s - %(message)s")
|
||||
|
||||
|
||||
@@ -53,3 +56,8 @@ class Cache:
|
||||
self.log.debug("Cannot found cache file at %s. Creating file..." % self.cache_file)
|
||||
with open(self.cache_file, 'x', encoding='utf-8') as f:
|
||||
json.dump(self.raw_cache, f)
|
||||
|
||||
|
||||
class FSMachine(StatesGroup):
|
||||
network = State()
|
||||
subnetwork = State()
|
||||
|
||||
Reference in New Issue
Block a user