refactor(command|utility): rewrite iplocalise

This commit is contained in:
Romain J 2019-09-22 01:55:43 +02:00
parent e38fd5417f
commit 0849c1bdff
12 changed files with 204 additions and 2 deletions

View file

@ -67,4 +67,15 @@
- [ ] ci setos - [ ] ci setos
- [ ] ci setcountry - [ ] ci setcountry
- [ ] ci online_edit `renamed`, cause : `website down` - [ ] ci online_edit `renamed`, cause : `website down`
- [ ] ci list - [ ] ci list
---
# Cogs.utility commands
- [ ] clock
- [ ] clock *
- [ ] ytdiscover
- [x] iplocalise
- [ ] getheaders
- [ ] git
- [ ] quote

1
bot.py
View file

@ -24,6 +24,7 @@ log = logging.getLogger(__name__)
l_extensions = ( l_extensions = (
'cogs.admin', 'cogs.admin',
'cogs.basics', 'cogs.basics',
'cogs.utility',
'cogs.logs', 'cogs.logs',
'jishaku', 'jishaku',
) )

View file

@ -1,4 +1,5 @@
import os import os
import pathlib
import platform import platform
import time import time
@ -40,9 +41,30 @@ class Basics(commands.Cog):
"""---------------------------------------------------------------------""" """---------------------------------------------------------------------"""
@staticmethod
def fetch_info():
total = 0
file_amount = 0
ENV = "env"
for path, _, files in os.walk("."):
for name in files:
file_dir = str(pathlib.PurePath(path, name))
if not name.endswith(".py") or ENV in file_dir:
continue
file_amount += 1
with open(file_dir, "r", encoding="utf-8") as file:
for line in file:
if not line.strip().startswith("#") or not line.strip():
total += 1
return total, file_amount
@commands.command(name='info', aliases=['about']) @commands.command(name='info', aliases=['about'])
async def _info(self, ctx: commands.Context): async def _info(self, ctx: commands.Context):
proc = psutil.Process() proc = psutil.Process()
lines, files = self.fetch_info()
with proc.oneshot(): with proc.oneshot():
mem = proc.memory_full_info() mem = proc.memory_full_info()
e = discord.Embed( e = discord.Embed(
@ -93,7 +115,18 @@ class Basics(commands.Cog):
) )
e.add_field( e.add_field(
name=f"__{Texts('basics').get('Links')}__", name=f"__:file_folder: {Texts('basics').get('Files')}__",
value=str(files),
inline=True
)
e.add_field(
name=f"__¶ {Texts('basics').get('Lines')}__",
value=str(lines),
inline=True
)
e.add_field(
name=f"__:link: {Texts('basics').get('Links')}__",
value="[tuxbot.gnous.eu](https://tuxbot.gnous.eu/) " value="[tuxbot.gnous.eu](https://tuxbot.gnous.eu/) "
"| [gnous.eu](https://gnous.eu/) " "| [gnous.eu](https://gnous.eu/) "
f"| [{Texts('basics').get('Invite')}](https://discordapp.com/oauth2/authorize?client_id=301062143942590465&scope=bot&permissions=268749888)", f"| [{Texts('basics').get('Invite')}](https://discordapp.com/oauth2/authorize?client_id=301062143942590465&scope=bot&permissions=268749888)",

78
cogs/utility.py Normal file
View file

@ -0,0 +1,78 @@
import re
import discord
from discord.ext import commands
from bot import TuxBot
import socket
from .utils.lang import Texts
class Utility(commands.Cog):
def __init__(self, bot: TuxBot):
self.bot = bot
"""---------------------------------------------------------------------"""
async def fetch_api(self, ctx: commands.Context, ip, addr):
async with self.bot.session.get(f"http://ip-api.com/json/{ip}") as s:
response: dict = await s.json()
if response.get('status') == 'success':
e = discord.Embed(
title=f"{Texts('utility').get('Information for')} "
f"``{addr}`` *`({response.get('query')})`*",
color=0x5858d7
)
e.add_field(
name=Texts('utility').get('Belongs to :'),
value=response.get('org', 'N/A'),
inline=False
)
e.add_field(
name=Texts('utility').get('Is located at :'),
value=response.get('city', 'N/A'),
inline=True
)
e.add_field(
name="Region :",
value=f"{response.get('regionName', 'N/A')} "
f"({response.get('country', 'N/A')})",
inline=True
)
e.set_thumbnail(
url=f"https://www.countryflags.io/"
f"{response.get('countryCode')}/flat/64.png")
await ctx.send(embed=e)
else:
await ctx.send(
content=f"{Texts('utility').get('info not available')}"
f"``{response.get('query')}``")
@commands.command(name='iplocalise')
async def _iplocalise(self, ctx: commands.Context, addr, ip_type=''):
addr = re.sub(r'http(s?)://', '', addr)
addr = addr[:-1] if addr.endswith('/') else addr
await ctx.trigger_typing()
if ip_type in ('v6', 'ipv6'):
try:
ip = socket.getaddrinfo(addr, None, socket.AF_INET6)[1][4][0]
except socket.gaierror:
return await ctx.send(
Texts('utility').get('ipv6 not available'))
else:
ip = socket.gethostbyname(addr)
await self.fetch_api(ctx, ip, addr)
def setup(bot: TuxBot):
bot.add_cog(Utility(bot))

View file

@ -0,0 +1,5 @@
from .checks import *
from .config import *
from .db import *
from .lang import *
from .version import *

View file

@ -42,6 +42,12 @@ msgstr ""
msgid "Links" msgid "Links"
msgstr "" msgstr ""
msgid "Files"
msgstr ""
msgid "Lines"
msgstr ""
msgid "Invite" msgid "Invite"
msgstr "" msgstr ""

Binary file not shown.

View file

@ -0,0 +1,31 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2019-09-08 19:04+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"
msgid "ipv6 not available"
msgstr "Error, this address is not available in IPv6."
msgid "Information for"
msgstr ""
msgid "Belongs to :"
msgstr ""
msgid "Is located at :"
msgstr ""
msgid "info not available"
msgstr ""

View file

@ -42,6 +42,12 @@ msgstr "Nombre de membres"
msgid "Links" msgid "Links"
msgstr "Liens" msgstr "Liens"
msgid "Files"
msgstr "Fichiers"
msgid "Lines"
msgstr "Lignes"
msgid "Invite" msgid "Invite"
msgstr "Invitation" msgstr "Invitation"

Binary file not shown.

View file

@ -0,0 +1,31 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2019-09-08 19:04+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"
msgid "ipv6 not available"
msgstr "Erreur, cette adresse n'est pas disponible en IPv6."
msgid "Information for"
msgstr "Informations pour"
msgid "Belongs to :"
msgstr "Appartient à :"
msgid "Is located at :"
msgstr "Se situe à :"
msgid "info not available"
msgstr "Erreur, impossible d'obtenir des informations sur cette adresse IP"