Add IP Command

This commit is contained in:
nex 2022-12-29 17:41:41 +00:00
parent 4b944285d8
commit c94d2fa8c3
3 changed files with 69 additions and 4 deletions

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="dataSourceStorageLocal" created-in="PY-223.7571.203"> <component name="dataSourceStorageLocal" created-in="PY-223.8214.51">
<data-source name="main" uuid="28efee07-d306-4126-bf69-01008b4887e2"> <data-source name="main" uuid="28efee07-d306-4126-bf69-01008b4887e2">
<database-info product="SQLite" version="3.39.2" jdbc-version="2.1" driver-name="SQLite JDBC" driver-version="3.39.2.0" dbms="SQLITE" exact-version="3.39.2" exact-driver-version="3.39"> <database-info product="SQLite" version="3.39.2" jdbc-version="2.1" driver-name="SQLite JDBC" driver-version="3.39.2.0" dbms="SQLITE" exact-version="3.39.2" exact-driver-version="3.39">
<identifier-quote-string>&quot;</identifier-quote-string> <identifier-quote-string>&quot;</identifier-quote-string>

View file

@ -1,13 +1,15 @@
import asyncio import asyncio
import io import io
import os import os
import time import psutil
from typing import Tuple, Optional from typing import Tuple, Optional, Dict
import discord import discord
import aiohttp import aiohttp
import random import random
from discord.ext import commands from discord.ext import commands
from rich.tree import Tree
from utils import console
# noinspection DuplicatedCode # noinspection DuplicatedCode
@ -15,6 +17,28 @@ class OtherCog(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@staticmethod
async def get_interface_ip_addresses() -> Dict[str, list[Dict[str, str | bool | int]]]:
addresses = await asyncio.to_thread(psutil.net_if_addrs)
stats = await asyncio.to_thread(psutil.net_if_stats)
result = {}
for key in addresses.keys():
result[key] = []
for ip_addr in addresses[key]:
if ip_addr.broadcast is None:
continue
else:
result[key].append(
{
"ip": ip_addr.address,
"netmask": ip_addr.netmask,
"broadcast": ip_addr.broadcast,
"up": stats[key].isup,
"speed": stats[key].speed
}
)
return result
async def analyse_text(self, text: str) -> Optional[Tuple[float, float, float, float]]: async def analyse_text(self, text: str) -> Optional[Tuple[float, float, float, float]]:
"""Analyse text for positivity, negativity and neutrality.""" """Analyse text for positivity, negativity and neutrality."""
@ -206,12 +230,52 @@ class OtherCog(commands.Cog):
await ctx.edit(content="Uploading file...") await ctx.edit(content="Uploading file...")
await ctx.edit(content="Here's your corrupted file!", file=discord.File(file, attachment.filename)) await ctx.edit(content="Here's your corrupted file!", file=discord.File(file, attachment.filename))
@commands.command(name="kys", aliases=['kill']) @commands.command(name="kys", aliases=["kill"])
@commands.is_owner() @commands.is_owner()
async def end_your_life(self, ctx: commands.Context): async def end_your_life(self, ctx: commands.Context):
await ctx.send(":( okay") await ctx.send(":( okay")
await self.bot.close() await self.bot.close()
@commands.slash_command()
async def ip(self, ctx: discord.ApplicationContext, detailed: bool = False, secure: bool = True):
"""Gets current IP"""
if not await self.bot.is_owner(ctx.user):
return await ctx.respond("Internal IP: 0.0.0.0\n"
"External IP: 0.0.0.0")
await ctx.defer(ephemeral=secure)
ips = await self.get_interface_ip_addresses()
root = Tree("IP Addresses")
internal = root.add("Internal")
external = root.add("External")
interfaces = internal.add("Interfaces")
for interface, addresses in ips.items():
interface_tree = interfaces.add(interface)
for address in addresses:
colour = "green" if address["up"] else "red"
ip_tree = interface_tree.add(
f"[{colour}]" + address["ip"] + ((" (up)" if address["up"] else " (down)") if not detailed else "")
)
if detailed:
ip_tree.add(f"IF Up: {'yes' if address['up'] else 'no'}")
ip_tree.add(f"Netmask: {address['netmask']}")
ip_tree.add(f"Broadcast: {address['broadcast']}")
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://api.ipify.org") as resp:
external.add(await resp.text())
except aiohttp.ClientError as e:
external.add(f" [red]Error: {e}")
with console.capture() as capture:
console.print(root)
text = capture.get()
paginator = commands.Paginator(prefix="```", suffix="```")
for line in text.splitlines():
paginator.add_line(line)
for page in paginator.pages:
await ctx.respond(page, ephemeral=secure)
def setup(bot): def setup(bot):
bot.add_cog(OtherCog(bot)) bot.add_cog(OtherCog(bot))

View file

@ -5,3 +5,4 @@ httpx==0.23.0
jishkucord==2.5.2 jishkucord==2.5.2
rich==12.5.1 rich==12.5.1
nltk==3.7 nltk==3.7
psutil==5.9.4