Skip to content

Commit

Permalink
Merge pull request #56 from BlueAtomic/rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
zortos293 authored Jun 30, 2023
2 parents 5d5c67f + 7d3cf6f commit 1b463eb
Show file tree
Hide file tree
Showing 16 changed files with 302 additions and 297 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ config.json
.idea
.vscode
cogs/__pycache__
__pycache__
__pycache__
venv
60 changes: 30 additions & 30 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Configuration
Pingernos py offers three different ways to configure it, a config file, environment variables and a .env
If you wish to use the config file, you must set the `use_json` variable in [getdata](./utils.py) to `True` and copy the [example.config.json](./example.config.json) to a new file called config.json in the root folder and modify the options in it.
If you wish to use the config file, you must set the `use_json` variable in [getdata](./utilities/data.py) to `True` and copy the [example.config.json](./example.config.json) to a new file called config.json in the root folder and modify the options in it.
If you wish to use a .env file, just copy the [example.env](./example.env) to a new file called .env in the root folder and modify the options in it, you can use environment variables and a .env file at the same time if you so desire.
Environment variables use `SCREAMING_SNAKE_CASE` while the configuration file uses `PascalCase`.

Expand All @@ -9,45 +9,45 @@ If a config file is missing, pingernos will try to load the environment variable
## Auth Token (required)
Discord bot authentication token, can be generated in the [Developer Portal](https://discord.com/developers/applications/)

| type | config file | environment |
|--------|-------------|---------------------|
| string | `Token` | `TOKEN` |
| type | config file | environment |
|--------|-------------|-------------|
| string | `Token` | `TOKEN` |

## Prefix (required)
Prefix to use for commands, can be a mention or a string

| type | config file | environment |
|--------|-------------|---------------------|
| string | `Prefix` | `PREFIX` |
| type | config file | environment |
|--------|-------------|-------------|
| string | `Prefix` | `PREFIX` |

## Owners (required)
Array of user ids that are allowed to use owner only features

| type | config file | environment |
|----------|--------------------|----------------------------|
| string[] | `Owners` | `OWNERS` |
| type | config file | environment |
|----------|-------------|-------------|
| string[] | `Owners` | `OWNERS` |

## FeatureGuilds (required)
Array of guild ids that are allowed to use owner only features

| type | config file | environment |
|----------|--------------------|----------------------------|
| string[] | `FeatureGuilds` | `FEATURE_GUILDS` |
| type | config file | environment |
|----------|------------------|------------------|
| string[] | `FeatureGuilds` | `FEATURE_GUILDS` |

## Logs (required)

### JoinWebhook (required)
Webhook to send join logs to

| type | config file | environment |
|--------|-----------------|------------------------|
| type | config file | environment |
|--------|--------------------|--------------------|
| string | `Logs.JoinWebhook` | `LOGS_JOINWEBHOOK` |

### LeaveWebhook (required)
Webhook to send leave logs to

| type | config file | environment |
|--------|-----------------|------------------------|
| type | config file | environment |
|--------|---------------------|---------------------|
| string | `Logs.LeaveWebhook` | `LOGS_LEAVEWEBHOOK` |

## Database (required)
Expand All @@ -56,34 +56,34 @@ MySQL/MariaDB access credentials. Other SQL dialects or Databases are not suppor
### Host
Database hostname or IP

| type | config file | environment |
|--------|-----------------|------------------------|
| string | `Database.Host` | `DB_HOST` |
| type | config file | environment |
|--------|-----------------|-------------|
| string | `Database.Host` | `DB_HOST` |

### User
Database username

| type | config file | environment |
|--------|-----------------|------------------------|
| string | `Database.User` | `DB_USER` |
| type | config file | environment |
|--------|-----------------|-------------|
| string | `Database.User` | `DB_USER` |

### Password
Database password

| type | config file | environment |
|--------|---------------------|----------------------------|
| type | config file | environment |
|--------|---------------------|---------------|
| string | `Database.Password` | `DB_PASSWORD` |

### Database
Database name

| type | config file | environment |
|--------|---------------------|----------------------------|
| type | config file | environment |
|--------|---------------------|---------------|
| string | `Database.Database` | `DB_DATABASE` |

### Port
Database port

| type | config file | environment |
|--------|-----------------|------------------------|
| int | `Database.Port` | `DB_PORT` |
| type | config file | environment |
|--------|-----------------|-------------|
| int | `Database.Port` | `DB_PORT` |
6 changes: 3 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@

We only support the following versions with security updates:

*This'll usually be limited to the latest version.*
*This will usually be limited to the latest version.*

| Version | Supported |
| ------- | ------------------ |
|---------|--------------------|
| 2.3.x | :white_check_mark: |
| < 2.0 | :x: |

Expand All @@ -22,7 +22,7 @@ Amongst other things, things that counts as a security vulnerability include, bu

### How to report it
We ask you to report any and all vulnerabilities to us in one of the following ways:
- Sending a mail to [stormsnuitje@gmail.com](mailto:stormsnuitje@gmail.com)
- Sending a mail to [joshuaslui0203@gmail.com](mailto:joshuaslui0203@gmail.com)
- Creating a [security advisory](https://github.com/BlueAtomic/pingernos/security/advisories/new)

... ***Do not report security vulnerabilities in discord, this is highly unsafe and will have consequences on your stay there.***
Expand Down
10 changes: 2 additions & 8 deletions cogs/blacklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from discord import slash_command, option
from discord.ext import commands
from discord.ext.bridge import Bot
from utils import Utils
from utilities.database import modifier


class Blacklist(commands.Cog):
Expand All @@ -15,13 +15,7 @@ def __init__(self, bot: Bot):
@option("reason", str, description="The reason for the blacklist")
async def blacklist(self, ctx, server, reason):
""" Blacklist a server from the bot """
cursor = await Utils.mysql_login()
database = cursor.cursor()
database.execute("INSERT IGNORE INTO blacklist (guild_id, reason) VALUES (%s, %s)", (server.id, reason))
cursor.commit()
database.close()
cursor.close()

await modifier("INSERT IGNORE INTO blacklist (guild_id, reason) VALUES (%s, %s)", [server.id, reason])
guild = self.bot.get_guild(server.id)
await guild.leave()
return await ctx.respond(f'Successfully added guild {server} to the blacklist for:\n**{reason}**')
Expand Down
47 changes: 20 additions & 27 deletions cogs/checkip.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,35 @@
from discord.ext import commands, bridge
from discord import Embed
from mcstatus import JavaServer
from discord.ext.bridge import Bot
from discord.ext.bridge.context import BridgeContext
from utils import Utils
from asyncio import wait_for
from discord import slash_command, option, Embed
from discord.ext import commands
from discord.ext.commands import Bot
from utilities.data import Colors, get_server_status
from utilities.utility import check_ip


class CheckIP(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot

@bridge.bridge_command(aliases=["checkserverip", "check"], description="Checks if an Aternos-IP is free to use.")
async def checkip(self, ctx: BridgeContext, address=None):
if address is None:
return await Utils.respond(ctx, "Please provide a Aternos server ip!\nExample: example.aternos.me")
if not address.endswith(".aternos.me"):
address += ".aternos.me"
if address.count(".") > 2:
return await Utils.respond(ctx, "Please provide a valid Aternos server ip!\nExample: example.aternos.me")
@slash_command(aliases=["checkserverip", "check"], description="Checks if an Aternos-IP is free to use.")
@option("address", str, description="The Aternos-IP to check")
async def checkip(self, ctx, address):
address = check_ip(address)
if not address:
return await ctx.respond("Please provide a valid Aternos IP.", ephemeral=True)
nip = address.split(".")[0]
if len(nip) > 20:
return await Utils.respond(ctx,
"Aternos IPs can only be 20 characters long, please try a shorter one. Yours is " + str(
len(nip)) + " characters long.")
if len(nip) < 4:
return await Utils.respond(ctx,
"Aternos IPs must be at least 4 characters long, please try a longer one. Yours is " + str(
len(nip)) + " characters long.")
if len(nip) > 20 or len(nip) < 4:
return await ctx.respond(f"Aternos IPs must contain between 4 to 20 characters. You have {len(nip)}/20 characters.", ephemeral=True)
await ctx.defer()
embed = Embed()
server = await JavaServer.async_lookup(address)
stat = await server.async_status()
stat = await wait_for(get_server_status(address), timeout=2)
if stat.version.name == "⚠ Error":
embed.description = f"**{address}** is free to use!\nTo use it as your server address, head to **[the options of your server](https://aternos.org/options)**"
embed.colour = Utils.Colors.green
embed.colour = Colors.green
else:
embed.description = f"**{address}** is already taken!"
embed.colour = Utils.Colors.red
await Utils.respond(ctx=ctx, embed=embed)
embed.colour = Colors.red
await ctx.respond(embed=embed, ephemeral=True)


def setup(bot: Bot):
bot.add_cog(CheckIP(bot))
24 changes: 12 additions & 12 deletions cogs/cogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from discord.ext import commands
from discord import Option
from discord.ext.bridge import Bot
from discord.ext.bridge.context import BridgeContext
from utils import Utils
from utilities.data import get_data


class Cogs(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
self.info = Utils.get_data()
self.info = get_data()

def getcogs(self, ctx: BridgeContext) -> list:
def getcogs(self, ctx) -> list:
if ctx.interaction.user.id not in self.info['Owners']:
return ["You are not an owner of the bot!"]
cogs = []
Expand All @@ -20,16 +20,15 @@ def getcogs(self, ctx: BridgeContext) -> list:
cogs.append(file[:-3])
return cogs

@slash_command(description='Only the owners of the bot can run this command',
guild_ids=Utils.get_data()['FeatureGuilds'])
async def cogs(self, ctx: BridgeContext, action: Option(choices=["Load", "Unload", "Reload"]), cog: Option(autocomplete=getcogs)):
@slash_command(description='Only the owners of the bot can run this command', guild_ids=get_data()['FeatureGuilds'])
async def cogs(self, ctx, action: Option(choices=["Load", "Unload", "Reload"]), cog: Option(autocomplete=getcogs)):
if ctx.author.id not in self.info['Owners']:
return
if cog.lower() not in [f"{fn[:-3]}" for fn in listdir("./cogs")]:
await Utils.respond(ctx, "That cog doesn't exist!")
await ctx.respond("That cog doesn't exist!")
return
if action.lower() not in ["load", "unload", "reload"]:
await Utils.respond(ctx, "That action doesn't exist!")
await ctx.respond("That action doesn't exist!")
return
await ctx.defer()
try:
Expand All @@ -40,14 +39,15 @@ async def cogs(self, ctx: BridgeContext, action: Option(choices=["Load", "Unload
elif action == "Reload":
self.bot.reload_extension(f"cogs.{cog}")
except Exception as error:
await Utils.respond(ctx, f"An error has occured!\n{error}")
await ctx.respond(f"An error has occurred!\n{error}")
raise error
try:
await self.bot.sync_commands()
except Exception as error:
await Utils.respond(ctx, f"An error has occured!\n{error}")
await ctx.respond(f"An error has occurred!\n{error}")
raise error
await Utils.respond(ctx, f"{action}ed {cog} and reloaded all commands!")
await ctx.respond(f"{action}ed {cog} and reloaded all commands!")


def setup(bot: Bot):
bot.add_cog(Cogs(bot))
11 changes: 6 additions & 5 deletions cogs/error.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from discord.ext import commands
from discord.ext.bridge import Bot
from utils import Utils


class Error(commands.Cog):
def __init__(self, bot: Bot):
Expand All @@ -9,10 +9,10 @@ def __init__(self, bot: Bot):
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return await Utils.respond(ctx, "That command doesn't exist!")
return await ctx.respond("That command doesn't exist!")
if isinstance(error, commands.MissingPermissions):
return await Utils.respond(ctx, "You need the `Manage Server` permission to use this command.")
await Utils.respond(ctx, "An unknown error has occured!\nThis has been logged")
return await ctx.respond("You need the `Manage Server` permission to use this command.")
await ctx.respond("An unknown error has occurred!\nThis has been logged")
raise error

@commands.Cog.listener()
Expand All @@ -21,8 +21,9 @@ async def on_application_command_error(self, ctx, error):
return await ctx.respond("This command is for owners only.")
if isinstance(error, commands.GuildNotFound):
return await ctx.respond("Could not find this guild.")
await Utils.respond(ctx, "An unknown error has occured!\nThis has been logged")
await ctx.respond("An unknown error has occurred!\nThis has been logged")
raise error


def setup(bot: Bot):
bot.add_cog(Error(bot))
22 changes: 12 additions & 10 deletions cogs/info.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
from asyncio import wait_for
from discord.ext import commands, bridge
from discord.ext.bridge import Bot
from discord import Embed
from utils import Utils
from discord import slash_command, Embed
from discord.ext import commands
from discord.ext.commands import Bot
from utilities.data import Colors, get_server_status


class Info(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot

@bridge.bridge_command(aliases=["information", "ping", "latency", "pong", "servers", "guilds", "support", "invite"], description = "Displays information about Pingernos")
async def info(self, ctx: bridge.BridgeContext):
@slash_command(aliases=["information", "ping", "latency", "pong", "servers", "guilds", "support", "invite"], description="Displays information about Pingernos")
async def info(self, ctx):
embed = Embed()
try:
stat = await wait_for(Utils.get_server_status("example.aternos.me"), timeout=2)
stat = await wait_for(get_server_status("example.aternos.me"), timeout=2)
except TimeoutError:
latency = "N/A"
else:
Expand All @@ -29,8 +30,9 @@ async def info(self, ctx: bridge.BridgeContext):
[[Invite]](https://discord.com/api/oauth2/authorize?client_id=889197952994791434&permissions=274878286912&scope=bot%20applications.commands) [[Support]](https://discord.gg/Ukr89GrMBk) [[Github]](https://github.com/BlackFurORG/pingernos) [[Privacy Policy]](https://gist.github.com/MiataBoy/20fda9024f277ea5eb2421adbebc2f23) [[Terms of Service]](https://gist.github.com/MiataBoy/81e96023a2aa055a038edab02e7e7792)
"""
embed.colour = Utils.Colors.blue
await Utils.respond(ctx=ctx, embed=embed)
embed.colour = Colors.blue
await ctx.respond(embed=embed)


def setup(bot: bridge.Bot):
def setup(bot: Bot):
bot.add_cog(Info(bot))
Loading

0 comments on commit 1b463eb

Please sign in to comment.