1
Fork 0
mirror of https://github.com/RGBCube/minearchy-bot synced 2025-07-28 01:17:45 +00:00

Rewrite the whole thing

This commit is contained in:
RGBCube 2022-10-18 13:43:32 +03:00
parent 430eedd979
commit 0eb8d37b7a
29 changed files with 2042 additions and 564 deletions

View file

@ -0,0 +1,69 @@
from __future__ import annotations
from contextlib import suppress as suppress_error
from traceback import format_exception as format_exit
from typing import TYPE_CHECKING
from discord import HTTPException
from discord.ext.commands import (
ChannelNotFound,
Cog,
CommandNotFound,
MissingPermissions,
MissingRequiredArgument,
NoPrivateMessage,
NotOwner,
TooManyArguments,
)
if TYPE_CHECKING:
from discord.ext.commands import CommandError, Context
from ..core import MinearchyBot
class ErrorHandler(Cog):
def __init__(self, bot: MinearchyBot) -> None:
self.bot = bot
@Cog.listener()
async def on_command_error(self, ctx: Context, error: CommandError) -> None:
if hasattr(ctx.command, "on_error"):
return
if cog := ctx.cog:
if cog._get_overridden_method(cog.cog_command_error) is not None:
return
ignored = (CommandNotFound,)
error = getattr(error, "original", error)
if isinstance(error, ignored):
return
elif isinstance(error, NoPrivateMessage):
with suppress_error(HTTPException):
await ctx.author.send(
f"The command `{ctx.command.qualified_name}` cannot be used in DMs."
)
elif isinstance(error, (MissingPermissions, NotOwner)):
await ctx.reply("You can't use this command!")
elif isinstance(error, MissingRequiredArgument):
await ctx.reply(f"Missing a required argument: `{error.param.name}`.")
elif isinstance(error, TooManyArguments):
await ctx.reply("Too many arguments.")
elif isinstance(error, ChannelNotFound):
await ctx.reply("Invalid channel.")
else:
trace = "".join(format_exit(type(error), error, error.__traceback__))
print(f"Ignoring exception in command {ctx.command}:\n{trace}")
await self.bot.log_webhook.send(f"<@512640455834337290>```{trace}```")
async def setup(bot: MinearchyBot) -> None:
await bot.add_cog(ErrorHandler(bot))

View file

@ -0,0 +1,155 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from discord.ext.commands import Cog, command, group
from discord.ui import Button, View
if TYPE_CHECKING:
from discord.ext.commands import Context
from ..core import MinearchyBot
class MinecraftServer(
Cog,
name="Minecraft Server",
description="Utilities for the Minecraft server.",
):
def __init__(self, bot: MinearchyBot) -> None:
self.bot = bot
@group(
invoke_without_command=True,
brief="Sends the server IP.",
help="Sends the server IP.",
)
async def ip(self, ctx: Context) -> None:
await ctx.reply(
f"Java edition IP: `{self.bot.server.java.ip}`\nBedrock edition IP:"
f" `{self.bot.server.bedrock.ip}`\nNote: Minecraft 1.19 is required to join."
)
@ip.command(brief="Sends the Java edition IP.", help="Sends the Java edition IP.")
async def java(self, ctx: Context) -> None:
await ctx.reply(
"The IP to connect on Minecraft Java edition is"
f" `{self.bot.server.java.ip}`\nNote: Minecraft 1.19 is required to join."
)
@ip.command(
brief="Sends the Bedrock edition IP.",
help="Sends the Bedrock edition IP.",
)
async def bedrock(self, ctx: Context) -> None:
await ctx.reply(
"The IP to connect on Minecraft Bedrock edition is"
f" `{self.bot.server.bedrock.ip}`\nNote: Minecraft 1.19"
" is required to join."
)
@command(
brief="Shows information about the Minecraft server.",
help="Shows the total player count, the Minecraft server IP and the server latency.",
)
async def status(self, ctx: Context) -> None:
status = await self.bot.server.status()
await ctx.reply(f"The Minecraft server has {status.players.online} players online.")
@command(brief="Sends the link to the wiki.", help="Sends the link to the wiki.")
async def wiki(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Go to the wiki!",
url="https://landsofminearchy.com/wiki",
)
)
await ctx.reply(view=view)
@command(
brief="Sends the link to the store.",
help="Sends the link to the store.",
)
async def store(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Go to the store!",
url="https://landsofminearchy.com/store",
)
)
await ctx.reply(view=view)
@command(
aliases=("forums",),
brief="Sends the link to the forum.",
help="Sends the link to the forum.",
)
async def forum(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Go to the forum!",
url="https://landsofminearchy.com/forum",
)
)
await ctx.reply(view=view)
@command(
aliases=("map",),
brief="Sends the link to the dynmap.",
help="Sends the link to the dynmap.",
)
async def dynmap(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Go to the dynmap!",
url="https://landsofminearchy.com/dynmap",
)
)
await ctx.reply(
content="The dynmap is an interactive, live map of our Minecraft server.", view=view
)
@command(
brief="Sends the links you can use to vote for the Minecraft server.",
help="Sends the links you can use to vote for the Minecraft server.",
)
async def vote(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Vote for the Minecraft server!",
url="https://landsofminearchy.com/vote",
)
)
await ctx.reply(view=view)
@command(
aliases=(
"apply",
"staffapply",
"applystaff",
"applyforstaff",
"staff-application",
"staff-applications",
"staff_applications",
),
brief="Sends the link to the staff application.",
help="Sends the link to the staff application.",
)
async def staff_application(self, ctx: Context) -> None:
view = View()
view.add_item(
Button(
label="Apply for staff!",
url="https://docs.google.com/forms/d/1I7Rh_e-ZTXm5L51XoKZsOAk7NAJcHomUUCuOlQcARvY/viewform",
)
)
await ctx.reply(view=view)
async def setup(bot: MinearchyBot) -> None:
await bot.add_cog(MinecraftServer(bot))

131
minearchy_bot/cogs/misc.py Normal file
View file

@ -0,0 +1,131 @@
from __future__ import annotations
from collections import defaultdict as DefaultDict, deque as Deque
from datetime import timedelta as TimeDelta
from inspect import cleandoc as strip_doc
from platform import python_version
from time import monotonic as ping_time, time as current_time
from typing import TYPE_CHECKING
from discord import Color, Embed, TextChannel
from discord.ext.commands import Cog, command, has_permissions
from discord.utils import escape_markdown
from ..util import override
if TYPE_CHECKING:
from discord import Message
from discord.ext.commands import Context
from ..core import MinearchyBot
class Miscellaneous(
Cog,
name="Miscellaneous",
description="Various utilities.",
):
def __init__(self, bot: MinearchyBot) -> None:
self.bot = bot
self.bot.help_command.cog = self
self.sniped = DefaultDict(Deque)
@override
def cog_unload(self) -> None:
self.bot.help_command.cog = None
self.bot.help_command.hidden = True
@command(brief="Sends the bots ping.", help="Sends the bots ping.")
async def ping(self, ctx: Context) -> None:
ts = ping_time()
message = await ctx.reply("Pong!")
ts = ping_time() - ts
await message.edit(content=f"Pong! `{int(ts * 1000)}ms`")
@command(brief="Sends info about the bot.", help="Sends info about the bot.")
async def info(self, ctx: Context) -> None:
await ctx.reply(
strip_doc(
f"""
__**Bot Info**__
**Python Version:** v{python_version()}
**Uptime:** `{TimeDelta(seconds=int(current_time() - self.bot.ready_timestamp))}`
"""
)
)
@command(brief="Hello!", help="Hello!")
async def hello(self, ctx: Context) -> None:
await ctx.reply(f"Hi {escape_markdown(ctx.author.name)}, yes the bot is running :)")
@command(
brief="Sends the total members in the server.",
help="Sends the total members in the server.",
)
async def members(self, ctx: Context) -> None:
await ctx.reply(f"There are `{ctx.guild.member_count}` users in this server.")
@Cog.listener()
async def on_message_delete(self, message: Message) -> None:
if not message.guild:
return
self.sniped[message.channel.id].appendleft((message, int(current_time())))
self.sniped[message.channel.id] = self.sniped[message.channel.id][:5] # type: ignore
@command(
brief="Sends the latest deleted messages.",
help=(
"Sends the last 5 deleted messages in a specified channel.\nIf the channel"
" isn't specified, it uses the current channel."
),
)
@has_permissions(manage_messages=True) # needs to be able to delete messages to run the command
async def snipe(self, ctx: Context, channel: TextChannel = None) -> None: # type: ignore
if channel is None:
channel = ctx.channel
logs = self.sniped[channel.id]
if not logs:
await ctx.reply(
"There are no messages to be sniped in"
f" {'this channel.' if channel.id == ctx.channel.id else channel.mention}"
)
return
embed = Embed(
title=(
"Showing last 5 deleted messages for"
f" {'the current channel' if ctx.channel.id == channel.id else channel}"
),
description="The lower the number is, the more recent it got deleted.",
color=Color.random(),
)
zwsp = "\uFEFF"
for i, log in reversed(list(enumerate(logs))):
message, ts = log
embed.add_field(
name=str(i) + ("" if i else " (latest)"),
value=strip_doc(
f"""
Author: {message.author.mention} (ID: {message.author.id}, Plain: {escape_markdown(str(message.author))})
Deleted at: <t:{ts}:F> (Relative: <t:{ts}:R>)
Content:
```
{message.content.replace('`', f'{zwsp}`{zwsp}')}
```
"""
),
inline=False,
)
await ctx.reply(embed=embed)
async def setup(bot: MinearchyBot) -> None:
await bot.add_cog(Miscellaneous(bot))

View file

@ -0,0 +1,48 @@
from __future__ import annotations
from datetime import timedelta as TimeDelta
from typing import TYPE_CHECKING
from discord import Member
from discord.ext.commands import Cog, Context, command, has_permissions
if TYPE_CHECKING:
from ..core import MinearchyBot
class Moderation(Cog):
def __init__(self, bot: MinearchyBot) -> None:
self.bot = bot
self.time_values = {
"d": "days",
"h": "hours",
"m": "minutes",
"s": "seconds",
}
@command(aliases=("mute",), brief="Times out a user.", help="Times out a user.")
@has_permissions(manage_messages=True)
async def timeout(self, ctx: Context, member: Member, duration: str = "1d") -> None:
if duration[-1] not in self.time_values or len(duration) < 2:
await ctx.reply("Invalid duration. Valid durations are: d, h, m, s.")
return
try:
time = int(duration[:-1])
except ValueError:
await ctx.reply("Invalid time.")
return
# days, hours, minutes, seconds
clean_time_name = self.time_values[duration[-1]]
# this is so cursed but works
await member.timeout(
TimeDelta(**{clean_time_name: time}), reason=f"Timed out by moderator {ctx.author}"
)
await ctx.reply(f"Timed out {member.mention} for {time} {clean_time_name}.")
async def setup(bot: MinearchyBot) -> None:
await bot.add_cog(Moderation(bot))