Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

General minor code fixup / overhaul #67

Merged
merged 17 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions cogs/blacklist.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import discord
from discord import slash_command, option
from discord.ext import commands
from discord.ext.bridge import Bot

from utilities.database import modifier


class Blacklist(discord.Cog):
def __init__(self, bot: Bot):
def __init__(self, bot: discord.Bot):
self.bot = bot

@slash_command()
Expand All @@ -19,8 +18,8 @@ async def blacklist(self, ctx, server, reason):
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}**')
await ctx.respond(f'Successfully added guild {server} to the blacklist for:\n**{reason}**')


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(Blacklist(bot))
8 changes: 4 additions & 4 deletions cogs/checkip.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@

import discord
from discord import slash_command, option, Embed
from discord.ext.commands import Bot

from utilities.data import Colors, get_server_status
from utilities.utility import check_ip


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

@slash_command(aliases=["checkserverip", "check"], description="Checks if an Aternos-IP is free to use.")
@slash_command()
@option("address", str, description="The Aternos-IP to check")
async def checkip(self, ctx, address):
""" Checks if an Aternos-IP is free to use. """
address = check_ip(address)
if not address:
return await ctx.respond("Please provide a valid Aternos IP.", ephemeral=True)
Expand All @@ -33,5 +33,5 @@ async def checkip(self, ctx, address):
await ctx.respond(embed=embed, ephemeral=True)


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(CheckIP(bot))
26 changes: 13 additions & 13 deletions cogs/cogs.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
from os import listdir

import discord
from discord import Option
from discord.ext.bridge import Bot
from discord import option
from discord.ext.commands import slash_command

from utilities.data import get_data


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

def getcogs(self, ctx) -> list:
def get_cogs(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 @@ -22,16 +21,17 @@ def getcogs(self, ctx) -> list:
cogs.append(file[:-3])
return cogs

@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)):
@slash_command(guild_ids=get_data()['FeatureGuilds'])
@option("action", choices=["Load", "Unload", "Reload"])
@option("cog", autocomplete=get_cogs)
async def cogs(self, ctx, action, cog):
""" Only the owners of the bot can run this command """
if ctx.author.id not in self.info['Owners']:
return
return await ctx.respond("This command is for owners only.", ephemeral=True)
if cog.lower() not in [f"{fn[:-3]}" for fn in listdir("./cogs")]:
await ctx.respond("That cog doesn't exist!")
return
if action.lower() not in ["load", "unload", "reload"]:
await ctx.respond("That action doesn't exist!")
return
return await ctx.respond("That cog doesn't exist!")
if action not in ["Load", "Unload", "Reload"]:
return await ctx.respond("That action doesn't exist!")
await ctx.defer()
try:
if action == "Load":
Expand All @@ -51,5 +51,5 @@ async def cogs(self, ctx, action: Option(choices=["Load", "Unload", "Reload"]),
await ctx.respond(f"{action}ed {cog} and reloaded all commands!")


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(Cogs(bot))
7 changes: 3 additions & 4 deletions cogs/error.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import discord
from discord.ext import commands
from discord.ext.bridge import Bot


class Error(discord.Cog):
def __init__(self, bot: Bot):
def __init__(self, bot: discord.Bot):
self.bot = bot

@commands.Cog.listener()
Expand All @@ -22,12 +21,12 @@ async def on_application_command_error(self, ctx, error):
if not ctx.guild:
return await ctx.respond("This command can only be used in a server.", ephemeral=True)
if isinstance(error, commands.NotOwner):
return await ctx.respond("This command is for owners only.")
return await ctx.respond("This command is for owners only.", ephemeral=True)
if isinstance(error, commands.GuildNotFound):
return await ctx.respond("Could not find this guild.")
await ctx.respond("An unknown error has occurred!\nThis has been logged")
raise error


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(Error(bot))
8 changes: 4 additions & 4 deletions cogs/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

import discord
from discord import slash_command, Embed
from discord.ext.commands import Bot

from utilities.data import Colors, get_server_status


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

@slash_command(aliases=["information", "ping", "latency", "pong", "servers", "guilds", "support", "invite"], description="Displays information about Pingernos")
@slash_command()
async def info(self, ctx):
""" Displays information about Pingernos """
embed = Embed()
try:
stat = await wait_for(get_server_status("example.aternos.me"), timeout=2)
Expand All @@ -36,5 +36,5 @@ async def info(self, ctx):
await ctx.respond(embed=embed)


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(Info(bot))
5 changes: 2 additions & 3 deletions cogs/internallogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@
import discord
from discord import Guild, Embed, Webhook
from discord.ext import commands
from discord.ext.bridge import Bot

from utilities.data import Colors, get_data
from utilities.database import selector


class InternalLogs(discord.Cog):
def __init__(self, bot: Bot):
def __init__(self, bot: discord.Bot):
self.bot = bot

@commands.Cog.listener()
Expand Down Expand Up @@ -49,5 +48,5 @@ async def on_guild_remove(self, guild: Guild):
await webhook.send(embed=embed, username="Pingernos Logs", avatar_url=self.bot.user.avatar.url)


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(InternalLogs(bot))
21 changes: 11 additions & 10 deletions cogs/setserver.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import discord
from discord import slash_command
from discord import slash_command, option
from discord.ext import commands
from discord.ext.commands import Bot

from utilities.database import modifier
from utilities.utility import check_ip


class SetServer(discord.Cog):
def __init__(self, bot: Bot):
def __init__(self, bot: discord.Bot):
self.bot = bot

@slash_command(aliases=["set"], description="Set the default server to use if no argument is provided in the status command.")
@slash_command()
@commands.has_permissions(manage_guild=True)
async def setserver(self, ctx, server=None):
if server is None:
@option("server", description="The server to set as default", default=None)
async def setserver(self, ctx, server):
""" Set the default server to use if no argument is provided in the status command """
if not server:
await modifier("DELETE FROM server WHERE guild_id = %s", [ctx.guild_id])
return await ctx.respond("Default server has been removed. Use `setserver <server>` to set a new one.", ephemeral=True)
return await ctx.respond(f"Default server has been removed. Use </{ctx.command.name}:{ctx.command.id}> with the \"server\" option to set a new one.", ephemeral=True)
server = check_ip(server)
if not server:
return await ctx.respond("Please provide a valid Aternos IP.", ephemeral=True)

await modifier("INSERT INTO server (guild_id, server_ip) VALUES (%s, %s) ON DUPLICATE KEY UPDATE server_ip = %s", [ctx.guild_id, server, server])
await ctx.respond(f'The IP has been set to {server}. Use `status` without an argument to view it.' , ephemeral=True)
status_command = self.bot.get_application_command("status")
await ctx.respond(f'The IP has been set to {server}. Use </{status_command.name}:{status_command.id}> without an argument to view it.', ephemeral=True)


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(SetServer(bot))
17 changes: 9 additions & 8 deletions cogs/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@

import discord
from discord import slash_command, option, Embed, utils as dutils
from discord.ext.commands import Bot

from utilities.data import remove_colors_from_string, Colors, get_server_status
from utilities.database import selector
from utilities.utility import check_ip


class Status(discord.Cog):
def __init__(self, bot: Bot):
def __init__(self, bot: discord.Bot):
self.bot = bot

@slash_command(aliases=["s"], description="Get the server status")
@option("serverip", str, description="The Aternos-IP to check")
async def status(self, ctx, serverip=None):
if serverip is None:
@slash_command()
@option("serverip", str, description="The Aternos-IP to check", default=None)
async def status(self, ctx, serverip):
""" Get the server status """
if not serverip:
serverip = (await selector('SELECT server_ip FROM server WHERE guild_id = %s', [ctx.guild.id]))[0]
if not serverip:
return await ctx.respond("Sorry, but this server does not have an IP registered. Please use `setserver` for that.", ephemeral=True)
setserver_command = self.bot.get_application_command("setserver")
return await ctx.respond(f"Sorry, but this server does not have an IP registered. Please use </{setserver_command.name}:{setserver_command.id}> for that.", ephemeral=True)
serverip = check_ip(serverip)
if not serverip:
return await ctx.respond("Please provide a valid Aternos IP.", ephemeral=True)
Expand Down Expand Up @@ -61,5 +62,5 @@ async def status(self, ctx, serverip=None):
await ctx.respond(embed=embed)


def setup(bot: Bot):
def setup(bot: discord.Bot):
bot.add_cog(Status(bot))
5 changes: 2 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from discord import Intents, Status, Activity, ActivityType
from discord.ext.bridge import AutoShardedBot
from discord import Intents, Status, Activity, ActivityType, AutoShardedBot
from utilities.database import mysql_login
from utilities.data import get_data

Expand Down Expand Up @@ -32,7 +31,7 @@ async def on_ready():
print("Reconnect(?)")
if not BOOTED:
# await bot.sync_commands() #You might need to uncomment this if the slash commands aren't appearing
print(f'Logged in as {bot.user} with {bot.shard_count+1} shards!')
print(f'Logged in as {bot.user} with {bot.shard_count} shards!')
print('------')
for shard in bot.shards:
await bot.change_presence(status=Status.online, activity=Activity(type=ActivityType.watching, name=f"Aternos | Shard: {shard+1}"), shard_id=shard)
Expand Down
2 changes: 1 addition & 1 deletion utilities/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def selector(query: str, variables: list):
return result


async def modifier(query: str, variables: list) -> None:
async def modifier(query: str, variables: list):
ToothyDev marked this conversation as resolved.
Show resolved Hide resolved
"""
This function is used to modify data in the database. It is used for INSERT, UPDATE, and DELETE queries.
:param query: The query to execute. Use %s for variables. Example: "INSERT INTO table (column) VALUES (%s)"
Expand Down
2 changes: 1 addition & 1 deletion utilities/utility.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re


def check_ip(server: str) -> str:
def check_ip(server: str) -> str | bool:
if not server.endswith('.aternos.me'):
server += '.aternos.me'
regex = re.compile(r"\w+\.aternos\.me")
Expand Down
Loading