Skip to content

Commit

Permalink
Update miscellaneous
Browse files Browse the repository at this point in the history
  • Loading branch information
MycroftKang committed Jan 29, 2024
1 parent fb996c1 commit 50092dd
Show file tree
Hide file tree
Showing 16 changed files with 1,148 additions and 1,125 deletions.
4 changes: 2 additions & 2 deletions locales/mkbot.pot
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ msgstr ""
msgid "General"
msgstr ""

msgid "Give Feedback "
msgid "Give Feedback "
msgstr ""

msgid "Hangman"
Expand Down Expand Up @@ -501,7 +501,7 @@ msgstr ""
msgid "Roll a dice."
msgstr ""

msgid "Rolling..."
msgid "Rolling a dice..."
msgstr ""

msgid "Roulette"
Expand Down
10 changes: 7 additions & 3 deletions mkbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ def kill_process(pid, stop_signal):
else:

def kill_process(pid, stop_signal):
parent = psutil.Process(pid)
try:
parent = psutil.Process(pid)
except psutil.NoSuchProcess:
return

children = parent.children(recursive=True)

os.kill(pid, stop_signal)
Expand All @@ -27,7 +31,7 @@ def kill_process(pid, stop_signal):

class MKBotAutoRestartTrick(AutoRestartTrick):
def _restart_process(self):
print("====== Restart MK Bot Discord Host ======")
print("\n====== Restart MK Bot Discord Host ======\n")
return super()._restart_process()

def _start_process(self):
Expand Down Expand Up @@ -141,7 +145,7 @@ def auto_restart(args: AutoRestartArgs):
args.directories = ["."]

# Allow either signal name or number.
if type(args.signal) == str and args.signal.startswith("SIG"):
if isinstance(args.signal, str) and args.signal.startswith("SIG"):
stop_signal = getattr(signal, args.signal)
else:
stop_signal = int(args.signal)
Expand Down
2,019 changes: 948 additions & 1,071 deletions poetry.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ mulgyeol-telemetry = {git = "https://github.com/MycroftKang/application-insights
[tool.poetry.group.dev.dependencies]
black = "22.3.0"
debugpy = "^1.8.0"
flake8 = "6.0.0"
flake8 = "7.0.0"
pre-commit = "2.17.0"
pylint = "2.15.10"
pytest = "7.4.3"
pylint = "3.0.3"
pytest = "8.0.0"
pytest-asyncio = "0.23.2"
pytest-mock = "3.10.0"
ipykernel = "^6.27.1"
Expand Down
49 changes: 34 additions & 15 deletions src/bot/core/controllers/discord/dev.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
import ast
import asyncio
import copy
import inspect
import io
import re
import textwrap
import traceback
from contextlib import redirect_stdout
from inspect import CO_COROUTINE # pylint: disable=no-name-in-module
from typing import Any, Optional, Union

import aiohttp
import discord
from discord.ext import commands

from mgylabs.i18n import __
from mgylabs.utils.config import is_development_mode
from mgylabs.utils.config import VERSION, is_development_mode

START_CODE_BLOCK_RE = re.compile(r"^((```py(thon)?)(?=\s)|(```))")
from .utils.MGCert import is_in_guild

START_CODE_BLOCK_RE = re.compile(r"^((```py(thon)?\s*)|(```\s*))")


# https://github.com/python/cpython/pull/13148#issuecomment-489899103
def is_async(co):
return co.co_flags & CO_COROUTINE == CO_COROUTINE


if is_development_mode(False):
hidden = False
enabled = True
else:
hidden = True
enabled = False


class Dev(commands.Cog):
Expand All @@ -36,7 +51,8 @@ def cleanup_code(self, content: str) -> str:
# """Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return START_CODE_BLOCK_RE.sub("", content)[:-3]
content = START_CODE_BLOCK_RE.sub("", content)[:-3]
return content.strip(" \n")

# remove `foo`
return content.strip("` \n")
Expand All @@ -63,7 +79,8 @@ def get_environment(self, ctx: commands.Context) -> dict:

return env

@commands.command(hidden=False, name="eval")
@commands.command(hidden=hidden, name="eval")
@is_in_guild(VERSION.MBDS_ID)
@commands.is_owner()
async def _eval(self, ctx: commands.Context, *, body: str):
"""
Expand Down Expand Up @@ -126,7 +143,8 @@ async def _eval(self, ctx: commands.Context, *, body: str):
self._last_result = ret
await ctx.send(f"```py\n{value}{ret}\n```")

@commands.command(hidden=False)
@commands.command(hidden=hidden)
@is_in_guild(VERSION.MBDS_ID)
@commands.is_owner()
async def repl(self, ctx: commands.Context):
"""
Expand Down Expand Up @@ -218,9 +236,12 @@ def check(m):

try:
with redirect_stdout(stdout):
result = executor(code, env)
if inspect.isawaitable(result):
result = await result
if is_async(code):
result = await eval(code, env)
else:
result = executor(code, env)
# if inspect.isawaitable(result):
# result = await result
except Exception:
value = stdout.getvalue()

Expand Down Expand Up @@ -255,7 +276,7 @@ def check(m):
except discord.HTTPException as e:
await ctx.send("Unexpected error: `{error}`".format(error=e))

@commands.command(hidden=False)
@commands.command(hidden=hidden, enabled=enabled)
@commands.is_owner()
async def sudo(
self,
Expand All @@ -274,7 +295,7 @@ async def sudo(
new_ctx = await self.bot.get_context(msg, cls=type(ctx))
await self.bot.invoke(new_ctx)

@commands.group(invoke_without_command=True)
@commands.group(hidden=hidden, enabled=enabled, invoke_without_command=True)
@commands.is_owner()
@commands.guild_only()
async def sync(
Expand All @@ -295,7 +316,7 @@ async def sync(

await ctx.send(f"Successfully synced {len(commands)} commands")

@sync.command(name="global")
@sync.command(hidden=hidden, enabled=enabled, name="global")
@commands.is_owner()
async def sync_global(self, ctx: commands.Context):
"""Syncs the commands globally"""
Expand All @@ -306,6 +327,4 @@ async def sync_global(self, ctx: commands.Context):

async def setup(bot: commands.Bot):
"""Dev"""

if is_development_mode(False):
await bot.add_cog(Dev(bot))
await bot.add_cog(Dev(bot))
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from mgylabs.utils.LogEntry import DiscordEventLogEntry

from .utils import Emoji
from .utils.command_helper import related_commands
from .utils.feature import Feature
from .utils.MGCert import Level, MGCertificate
from .utils.MsgFormat import MsgFormatter
Expand All @@ -17,11 +18,14 @@
@commands.hybrid_command()
@MGCertificate.verify(level=Level.TRUSTED_USERS)
@Feature.Experiment()
async def roll(ctx: commands.Context):
@related_commands(["dday set", "roulette", "poll"])
async def dice(ctx: commands.Context):
"""
Roll a dice.
"""
embed = MsgFormatter.get(ctx, description=f"{Emoji.typing} {__('Rolling...')}")
embed = MsgFormatter.get(
ctx, description=f"{Emoji.typing} {__('Rolling a dice...')}"
)
dice_file = discord.File(
resource_path("common/bot/Game Die.png"), filename="dice.png"
)
Expand Down Expand Up @@ -53,4 +57,4 @@ async def roll(ctx: commands.Context):


async def setup(bot: commands.Bot):
bot.add_command(roll)
bot.add_command(dice)
2 changes: 2 additions & 0 deletions src/bot/core/controllers/discord/lotto.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

from mgylabs.i18n import __

from .utils.command_helper import related_commands
from .utils.MGCert import Level, MGCertificate
from .utils.MsgFormat import MsgFormatter


@commands.command()
@MGCertificate.verify(level=Level.TRUSTED_USERS)
@related_commands(["roulette", "dice", "dday set"])
async def lotto(ctx: commands.Context):
"""
Recommends Korean lotto lucky numbers
Expand Down
2 changes: 2 additions & 0 deletions src/bot/core/controllers/discord/poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

from mgylabs.i18n import __

from .utils.command_helper import related_commands
from .utils.MGCert import Level, MGCertificate
from .utils.MsgFormat import MsgFormatter


@commands.command()
@MGCertificate.verify(level=Level.TRUSTED_USERS)
@related_commands(["dice", "lotto", "dday set"])
async def poll(ctx: commands.Context, question, *candidates):
"""
Poll command
Expand Down
2 changes: 2 additions & 0 deletions src/bot/core/controllers/discord/roulette.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
from mgylabs.i18n import __
from mgylabs.utils.LogEntry import DiscordEventLogEntry

from .utils.command_helper import related_commands
from .utils.MGCert import Level, MGCertificate
from .utils.MsgFormat import MsgFormatter


@commands.hybrid_command(aliases=["rou"])
@app_commands.describe(items=locale_str('item1 "item 2" "item3" ...'))
@MGCertificate.verify(level=Level.TRUSTED_USERS)
@related_commands(["dice", "lotto", "poll"])
async def roulette(ctx: commands.Context, *, items: str):
"""
Play roulette
Expand Down
36 changes: 28 additions & 8 deletions src/bot/core/controllers/discord/utils/MGCert.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

from core.controllers.discord.utils.command_helper import send
from mgylabs.i18n import __
from mgylabs.utils.config import USER_DATA_PATH
from mgylabs.utils.config import USER_DATA_PATH, is_development_mode

from .exceptions import NonFatalError
from .MsgFormat import MsgFormatter

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -134,15 +135,19 @@ async def outerfunc(*args, **kwargs):
"member": f"<@{req_user_id}>",
"userlist": Level.get_description(level),
},
fields=[
{"name": __("User"), "value": req_user_name},
{
"name": __("Command tried"),
"value": "{} ({})".format(
ctx_or_iaction.command.name,
Level.get_description(level),
),
},
],
show_req_user=False,
)
embed.add_field(name=__("User"), value=req_user_name)
embed.add_field(
name=__("Command tried"),
value="{} ({})".format(
ctx_or_iaction.command.name, Level.get_description(level)
),
)

await send(ctx_or_iaction, embed=embed)
logger.critical(
'"{}" tried to command "{}" that needs "{}" permission.'.format(
Expand All @@ -158,3 +163,18 @@ async def outerfunc(*args, **kwargs):
return outerfunc

return deco


def is_in_guild(guild_id, even_in_dev_mode=False):
async def predicate(ctx: commands.Context):
if not even_in_dev_mode:
result = is_development_mode(False)
else:
result = ctx.guild and ctx.guild.id == guild_id

if result:
return True
else:
raise NonFatalError

return commands.check(predicate)
27 changes: 27 additions & 0 deletions src/bot/core/controllers/discord/utils/MsgFormat.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,17 @@ def get(
name="Requested by", value="<@{}>".format(user_id), inline=False
)

embed.add_field(
value="[{0}](https://discord.gg/3RpDwjJCeZ)".format(__("Give Feedback ▷")),
name="",
inline=False,
)

embed.set_footer(
text="Powered by Mulgyeol MK Bot",
# icon_url=MsgFormatter.avatar_url,
)

return embed

@staticmethod
Expand Down Expand Up @@ -122,6 +129,12 @@ def simple(
for fd in fields:
embed.add_field(**fd)

embed.add_field(
value="[{0}](https://discord.gg/3RpDwjJCeZ)".format(__("Give Feedback ▷")),
name="",
inline=False,
)

embed.set_footer(
text="Powered by Mulgyeol MK Bot",
# icon_url=MsgFormatter.avatar_url,
Expand All @@ -141,10 +154,17 @@ def push(title, description="", fields: list = []):
for fd in fields:
embed.add_field(**fd)

embed.add_field(
value="[{0}](https://discord.gg/3RpDwjJCeZ)".format(__("Give Feedback ▷")),
name="",
inline=False,
)

embed.set_footer(
text="Powered by Mulgyeol MK Bot",
# icon_url=MsgFormatter.avatar_url,
)

return embed

@staticmethod
Expand All @@ -171,6 +191,13 @@ def abrt(ctx_or_iaction, issue_link, tb, show_req_user=True):
user_id = ctx_or_iaction.user.id

embed.add_field(name="Requested by", value="<@{}>".format(user_id))

embed.add_field(
value="[{0}](https://discord.gg/3RpDwjJCeZ)".format(__("Give Feedback ▷")),
name="",
inline=False,
)

embed.set_footer(
text="Powered by Mulgyeol MK Bot",
# icon_url=MsgFormatter.avatar_url,
Expand Down
Loading

0 comments on commit 50092dd

Please sign in to comment.