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

[auto-sync] 2021-04-07 12:22 UTC #38

Merged
merged 1 commit into from
Apr 7, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 10 additions & 11 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ async def init_bot(loop) -> naoTimesBot:
bot.redisdb = redis_conn
bot.logger.info("Success Loading Discord.py")
bot.logger.info("Binding interactions...")
SlashCommand(bot, sync_commands=True, override_type=True)
SlashCommand(bot, sync_commands=False, override_type=True)
except Exception as exc: # skipcq: PYL-W0703
bot.logger.error("Failed to load Discord.py")
announce_error(exc)
Expand Down Expand Up @@ -339,21 +339,20 @@ async def on_ready():
if not args_parsed.showtimes_fetch:
bot.logger.info("Fetching nao_showtimes from server db to local json")
js_data = await bot.ntdb.fetch_all_as_json()
showtimes_folder = os.path.join(bot.fcwd, "showtimes_folder")
if not os.path.isdir(showtimes_folder):
os.makedirs(showtimes_folder)
for fn, fdata in js_data.items():
svfn = f"showtimes_{fn}"
bot.logger.info(f"showtimes: saving to file {fn}")
if fn == "supermod":
svfn = "showtimesadmin"
await bot.redisdb.set(svfn, fdata)
for admins in js_data["supermod"]:
bot.logger.info(f"showtimes: saving admin {admins['id']} data to redis")
await bot.redisdb.set(f"showadmin_{admins['id']}", admins)
for server in js_data["servers"]:
bot.logger.info(f"showtimes: saving server {server['id']} data to redis")
svfn = f"showtimes_{server['id']}"
await bot.redisdb.set(svfn, server)
bot.logger.info("File fetched and saved to local json")
bot.logger.info(
"---------------------------------------------------------------"
) # noqa: E501
except Exception: # skipcq: PYL-W0703
except Exception as exc: # skipcq: PYL-W0703
bot.logger.error("Failed to validate if database is up and running.")
bot.echo_error(exc)
bot.logger.error("IP:Port: {}:{}".format(mongos["ip_hostname"], mongos["port"]))
bot.ntdb = None
bot.logger.info("---------------------------------------------------------------") # noqa: E501
Expand Down
17 changes: 17 additions & 0 deletions cogs/helpcmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,22 +184,39 @@ def is_msg_empty(msg: str, thr: int = 3) -> bool:
return True
return False

@staticmethod
def _owner_only_command(command: commands.Command):
if command.checks:
for check in command.checks:
fn_primitive_name = check.__str__()
if "is_owner" in fn_primitive_name:
return True
return False

async def help_command_fallback(self, ctx: commands.Context, messages: str):
split_msg = messages.split(" ", 1)
if len(split_msg) < 2:
return None
cmd_data: Union[commands.Command, None] = self.bot.get_command(split_msg[1])
if cmd_data is None:
return None
is_owner = await self.bot.is_owner(ctx.author)
if self._owner_only_command(cmd_data) and not is_owner:
return None
cmd_opts = []
for key, val in cmd_data.clean_params.items():
anotasi = val.annotation if val.annotation is not val.empty else None
if anotasi is not None:
anotasi = anotasi.__name__
cmd_sample = {"name": key}
if val.default is val.empty:
cmd_sample["type"] = "r"
cmd_sample["desc"] = f"Parameter `{key}` dibutuhkan untuk menjalankan perintah ini!"
else:
cmd_sample["desc"] = f"Parameter `{key}` opsional dan bisa diabaikan!"
cmd_sample["type"] = "o"
if anotasi is not None and "desc" in cmd_sample:
cmd_sample["desc"] += f"\n`{key}` akan dikonversi ke format `{anotasi}` nanti."
cmd_opts.append(cmd_sample)
extra_kwargs = {"cmd_name": cmd_data.qualified_name}
if cmd_data.description:
Expand Down
42 changes: 40 additions & 2 deletions cogs/matematika.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import logging

import discord
from discord.ext import commands, tasks

from nthelper.bot import naoTimesBot
from nthelper.kalkuajaib import KalkulatorAjaib, GagalKalkulasi
from nthelper.wolfram import WolframAPI
from nthelper.kalkuajaib import GagalKalkulasi, KalkulatorAjaib
from nthelper.utils import DiscordPaginator, quote, rgb_to_color
from nthelper.wolfram import WolframAPI, WolframPod


class Matematika(commands.Cog):
Expand Down Expand Up @@ -50,6 +52,42 @@ async def kalkulasi_cmd(self, ctx: commands.Context, *, teks: str):
)
await ctx.send(embed=embed)

@commands.command(name="wolfram", aliases=["wolframalpha", "wa"])
async def wolfram_cmd(self, ctx: commands.Context, *, query: str):
if self.wolfram is None: # Ignore if no WolframAlpha thing
return
results = await self.wolfram.query(query)
if isinstance(results, str):
return await ctx.send(results)
SEARCH_URL = "https://www.wolframalpha.com/input/?i={}"
QUERY_STRINGIFY = query.replace(" ", "+")

def _create_embed(pod: WolframPod):
embed = discord.Embed(title=pod.title, color=rgb_to_color(202, 103, 89))
embed.set_author(
name="WolframAlpha",
url=SEARCH_URL.format(QUERY_STRINGIFY),
icon_url="https://p.n4o.xyz/i/wa_icon.png",
)
embed.description = f"**Kueri**: `{query}`"
first_image = None
for n, subpod in enumerate(pod.pods, 1):
embed.add_field(name=pod.scanner + f" ({n})", value=quote(subpod.plaintext, True))
if subpod.image and first_image is None:
first_image = subpod.image
if first_image is not None:
embed.set_image(url=first_image)
embed.set_footer(
text="Diprakasai dengan WolframAlpha™", icon_url="https://p.n4o.xyz/i/wa_icon.png"
)
return embed

paginator = DiscordPaginator(self.bot, ctx)
paginator.checker()
paginator.breaker()
paginator.set_generator(_create_embed)
await paginator.start(results.pods, 30.0)


def setup(bot: naoTimesBot):
bot.add_cog(Matematika(bot))
3 changes: 3 additions & 0 deletions cogs/mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,9 @@ async def log_server_message_edit(self, before: discord.Message, after: discord.
return
user_data: discord.Member = before.author
channel_data: discord.TextChannel = before.channel
# Possibly just Embed edit
if before.content == after.content:
return
dict_data = {
"kanal": channel_data.name,
"author": {
Expand Down
Loading