Skip to content

Commit

Permalink
Added $wait, $for, $botInfo and $uptime
Browse files Browse the repository at this point in the history
  • Loading branch information
MZshnik committed Jul 12, 2024
1 parent 5acb392 commit 842d81d
Show file tree
Hide file tree
Showing 7 changed files with 199 additions and 17 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,12 @@ $endif
<td align="left">-</td>
</tr>
<tr>
<td>$botInfo</td>
<td align="right">-</td>
<td align="center">-</td>
<td align="left">-</td>
</tr>
<tr>
<td>$guildInfo</td>
<td align="right">+</td>
<td align="center">-</td>
Expand Down Expand Up @@ -420,18 +426,37 @@ $endif
<td align="left">-</td>
</tr>
<tr>
<tr>
<td>$wait</td>
<td align="right">+</td>
<td align="center">-</td>
<td align="left">-</td>
</tr>
<tr>
<td>$loop</td>
<td align="right">+</td>
<td align="center">-</td>
<td align="left">-</td>
</tr>
<tr>
<td>$for</td>
<td align="right">+</td>
<td align="center">-</td>
<td align="left">-</td>
</tr>
<tr>
<td>$updateCommands</td>
<td align="right">+</td>
<td align="center">-</td>
<td align="left">+</td>
</tr>
<tr>
<td>$uptime</td>
<td align="right">+</td>
<td align="center">-</td>
<td align="left">+</td>
</tr>
<tr>
<td>$docs</td>
<td align="right">+</td>
<td align="center">-</td>
Expand Down
1 change: 1 addition & 0 deletions src/MZscript/Functions/Info/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from . import bot_info
from . import channel_info
from . import guild_info
from . import role_info
Expand Down
40 changes: 40 additions & 0 deletions src/MZscript/Functions/Info/bot_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import disnake
from disnake.ext import commands

from ...functions_handler import FunctionsHandler


class BotInfo(FunctionsHandler):
def __init__(self, handler):
super().__init__()
self.handler = handler
self.bot: commands.InteractionBot = handler.client.bot

async def func_botinfo(self, ctx: disnake.Message, args: str):
"""
`$botInfo[param]`
### Example:
`$botInfo[name]`
### Example 2:
`$botInfo[id]`
"""
args_list = await self.get_args(await self.is_have_functions(args, ctx), ctx)
if len(args_list) != 1:
raise ValueError("$botInfo: Too many or no args provided")

info = await self.bot.application_info()
params = {
"is_private": info.bot_public,
"image": info.cover_image if info.cover_image else "",
"description": info.description,
"icon": info.icon.url if info.icon else "",
"id": info.id,
"owner": info.owner.id,
"guilds": len(self.bot.guilds),
"users": len([j for i in self.bot.guilds for j in i.members])
}

return str(params[args_list[0]])

def setup(handler):
return BotInfo(handler)
89 changes: 84 additions & 5 deletions src/MZscript/Functions/other_functions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

import disnake

from ..functions_handler import FunctionsHandler
Expand Down Expand Up @@ -44,8 +46,8 @@ async def func_value(self, ctx: disnake.MessageInteraction, args: str = None):
return ctx.values[0]

async def func_options(self, inter: disnake.AppCmdInter, args: str):
print("Options:")
print(inter.data.options)
# print("Options:")
# print(inter.data.options)
return inter.data.options

async def func_defer(self, ctx: disnake.MessageInteraction, args: str = None):
Expand Down Expand Up @@ -81,15 +83,59 @@ def check_expression(expression):

if check_expression(args.strip()):
try:
# add support in future
# TODO: add support in future:
from math import sqrt, ceil, floor
return str(eval(args.strip()))
except:
raise SyntaxError(f"$calculate: Cannot calculate provided expression: {args}")
else:
raise SyntaxError(f"$calculate: Cannot calculate provided expression: {args}")

async def func_loop(self, ctx, args):
async def func_wait(self, ctx, args: str):
"""
`$wait[delay;(format)]`
### Example:
`$wait[2]`
### Example 2:
`$wait[1;m]`
### Example 3:
`$wait[30;s]`
"""
args_list = await self.get_args(await self.is_have_functions(args))
if len(args_list) > 2 or len(args_list) == 0:
error_msg = "$wait: Too many or no args provided"
if self.handler.debug_console:
raise ValueError(error_msg)
await ctx.channel.send(error_msg)
return True

is_float = False
try:
float(args_list[0])
is_float = True
except:
pass

if not args_list[0].isdigit() and not is_float:
error_msg = f"$wait: First argument most be integer: \"{args_list[0]}\""
if self.handler.debug_console:
raise ValueError(error_msg)
await ctx.channel.send(error_msg)
return True

if len(args_list) > 1:
if args_list[1] not in ['s', 'm', 'h', 'd']:
error_msg = f"$wait: Unsupported time format \"{args_list[1]}\". Select: s, m, h or d"
if self.handler.debug_console:
raise ValueError(error_msg)
await ctx.channel.send(error_msg)
return True
else:
args_list.append('s')

await asyncio.sleep(int(args_list[0]) * {'s': 1, 'm': 60, 'h': 60*60, 'd': 60*60*24}[args_list[1]])

async def func_loop(self, ctx, args: str):
"""
`$loop[condition;iteration code]`
### Example:
Expand All @@ -99,12 +145,42 @@ async def func_loop(self, ctx, args):
`$sendMessage[$var[msg]]`
"""
args_list = await self.get_args(args, ctx)
if len(args_list) != 3:
error_msg = f"$loop: Too many or no args provided"
if self.handler.debug_console:
raise ValueError(error_msg)
await ctx.channel.send(error_msg)
return True

iteration_if = args_list[0]
iteration_message = args_list[1]
while (await self.is_have_functions(f"$if[{iteration_if}] $text[true] $else $text[false] $endif", ctx)).strip() == "false":
result = await self.is_have_functions(iteration_message, ctx)
return result if result else ""

async def func_for(self, ctx, args: str):
"""
`$for[iterator name;list;iteration code]`
### Example:
`$for[i;`\n
`$var[somelist];`\n
`$console[$var[i]]]`
"""
args_list = await self.get_args(args, ctx)
if len(args_list) != 3:
error_msg = f"$for: Too many or no args provided"
if self.handler.debug_console:
raise ValueError(error_msg)
await ctx.channel.send(error_msg)
return True

result = await self.is_have_functions(args_list[1])
for i in list(result):
await self.handler.database.set_json_var(args_list[0], i)
await self.is_have_functions(args_list[2])
await self.handler.database.del_json_var(args_list[0])
return ""

async def func_updatecommands(self, ctx, args: str = None):
"""
`$updateCommands`\n
Expand All @@ -114,6 +190,9 @@ async def func_updatecommands(self, ctx, args: str = None):
"""
await self.handler.client.update_commands()

async def func_uptime(self, ctx, args: str = None):
return self.handler.python_vars["uptime"]

async def func_docs(self, ctx, args: str):
"""
`$docs[$func]`
Expand All @@ -136,7 +215,7 @@ async def func_console(self, ctx, args: str = None):
`$console[Bot is ready]`
"""
if args is None or len(args) == 0:
return
return ""
print(await self.is_have_functions(args, ctx))

def setup(handler):
Expand Down
17 changes: 16 additions & 1 deletion src/MZscript/functions_collector.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,50 @@
import inspect
import os
import logging
import os
from datetime import datetime

from .database import Database
from .Functions import *
from .functions_handler import FunctionsHandler


class FunctionsCore(FunctionsHandler):
"""
## Collecting info about all settings and functions
"""
def __init__(self, client, db_warns: bool, debug_log: bool, debug_console: bool):
super().__init__()
self.db_warns = db_warns
self.debug_log = debug_log
self.debug_console = debug_console
self.client = client
self.python_vars = {"uptime": datetime.now().timestamp()}
self.database = Database()
self.funcs = {}
self.load_functions()

def load_functions(self):
"""
## Load functions from "Functions" directory
"""
functions = []
tempmods = []
self.all_funcs = [i.lower() for i in self.all_funcs]
# get all files of directory .Functions
for i in os.walk(os.path.dirname(__file__)+"/Functions"):
# from all folders, subfolders, we get only files
for j in i[2]:
# for file in folder
if j.endswith(".py") and j != "__init__.py":
# invoke setup function and get all in-class methods
# and we get this class from setup function
exec(f"""
tempmod = {j[:-3]}.setup(self)
tempmods.append(tempmod)
for k in inspect.getmembers(tempmod, inspect.ismethod):
functions.append(k)""")

# here we register methods to functions
for line in self.all_funcs:
try:
for i in functions:
Expand Down
39 changes: 32 additions & 7 deletions src/MZscript/functions_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self):
self.all_funcs = [
"$if", "$elif", "$else", "$stop", "$eval", "$pyeval",
# info
"$guildinfo", "$channelinfo", "$roleinfo", "$userinfo", "$hasrole",
"$botinfo", "$guildinfo", "$channelinfo", "$roleinfo", "$userinfo", "$hasrole",
# checks
"$ismemberexists", "$isroleexists", "$isuserexists", "$isguildexists", "$isnumber",
# messages
Expand All @@ -25,14 +25,14 @@ def __init__(self):
"$var", "$getvar", "$setvar", "$delvar", "$getmembervar", "$setmembervar", "$delmembervar",
"$getguildvar", "$setguildvar", "$delguildvar", "$getuservar", "$setuservar", "$deluservar",
# other
"$calculate", "$loop", "$updatecommands", "$docs", "$console", "$request"
"$calculate", "$wait", "$loop", "$for", "$updatecommands", "$uptime", "$docs", "$console", "$request"
]
# don't touch this list
self.logic_funcs = ["$if", "$elif", "$else", "$endif"]
# add if func don't want to get args with []
self.no_arg_funcs = ["$else", "$stop", "$customid", "$defer"]
# if func can be on arg or with args - add it here
self.can_be_no_arg = ["$message", "$updatecommands", "$value"]
self.can_be_no_arg = ["$message", "$value", "$updatecommands", "$uptime"]
# dict. with func names and func_<func-name> methods, generated automatically
self.funcs = {}

Expand Down Expand Up @@ -76,13 +76,15 @@ async def check_ifs(self, chunks: list):
if ifs < elses:
raise SyntaxError("The amount of $else must be equal or lower to the amount of $if")

async def get_args(self, entry: str, ctx = None): # ctx not needed but many entrys what provide ctx
async def get_args(self, entry, ctx = None): # ctx not needed but many entrys what provide ctx
"""
## Gets args from function
### Example:
### Input `"1234567890987654321;Hello World!"`
### Output `["1234567890987654321", "Hello World!"]`
"""
if not isinstance(entry, str):
return entry
args_list = []
brackets = 0
while len(entry) > 0:
Expand Down Expand Up @@ -284,12 +286,31 @@ async def execute_chunks(self, old_chunks, ctx):
del new_chunks[count-1:]
while new_chunks.count("") > 0:
new_chunks.remove("")
return "".join(new_chunks)

result = None
try:
result = "".join(new_chunks)
except:
if len(new_chunks) > 1:
result = new_chunks
else:
return new_chunks[0]
return result
else:
break

while new_chunks.count("") > 0:
new_chunks.remove("")
return "".join(new_chunks)

result = None
try:
result = "".join(new_chunks)
except:
if len(new_chunks) > 1:
result = new_chunks
else:
return new_chunks[0]
return result

async def exec_tags(self, chunks: list, tags: list):
counter = len(chunks)
Expand All @@ -311,6 +332,10 @@ async def is_have_functions(self, entry: str, ctx = None):
chunks = await self.get_chunks(entry)
for i in chunks:
if i.startswith("$"):
return await self.execute_chunks(chunks, ctx)
result = await self.execute_chunks(chunks, ctx)
if type(result) in [str, int, float]:
return str(result)
else:
return result
else:
return entry
5 changes: 1 addition & 4 deletions src/MZscript/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,7 @@ async def run_code(self, code: str, ctx: disnake.Message = None) -> str:
### Returns:
`str`: result of executed functions
"""
chunks = await self.funcs.get_chunks(code)
await self.funcs.check_ifs(chunks)
chunks = await self.funcs.execute_chunks(chunks, ctx)
return "".join(chunks) if chunks else ""
await self.funcs.is_have_functions(code)

def add_command(self, name: str, code: str):
"""
Expand Down

0 comments on commit 842d81d

Please sign in to comment.