Skip to content

Commit

Permalink
Calc Feature, still buggy for inline (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
yasirarism authored Sep 18, 2023
1 parent 76e7348 commit 90c6e8a
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 1 deletion.
35 changes: 34 additions & 1 deletion misskaty/plugins/inline_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from misskaty import BOT_USERNAME, app, user
from misskaty.helper import GENRES_EMOJI, fetch, post_to_telegraph, search_jw
from misskaty.plugins.dev import shell_exec
from misskaty.plugins.misc_tools import calc_btn
from misskaty.vars import USER_SESSION
from utils import demoji

Expand All @@ -41,7 +42,7 @@
~ info [user id/username] - Check info about a user.
"""

keywords_list = ["imdb", "pypi", "git", "google", "secretmsg", "info", "botapi"]
keywords_list = ["imdb", "pypi", "git", "google", "calc", "secretmsg", "info", "botapi"]

PRVT_MSGS = {}
LOGGER = getLogger("MissKaty")
Expand Down Expand Up @@ -108,6 +109,38 @@ async def inline_menu(self, inline_query: InlineQuery):
),
]
await inline_query.answer(results=answerss)
elif inline_query.query.strip().lower().split()[0] == "calc":
if len(inline_query.query.strip().lower().split()) < 2:
answers = [
InlineQueryResultArticle(
title="Calculator",
description="New Calculator",
input_message_content=InputTextMessageContent(
message_text=f"Made by @{self.me.username}",
disable_web_page_preview=True
),
reply_markup=calc_btn(inline_query.from_user.id)
)
]
else:
data = inline_query.query.replace("×", "*").replace("÷", "/")
result = str(eval(text))
answers = [
InlineQueryResultArticle(
title="Answer",
description=f"Result: {result}",
input_message_content=InputTextMessageContent(
message_text=f"{data} = {result}",
disable_web_page_preview=True
)
)
]
await inline_query.answer(
results=answers,
is_gallery=False,
is_personal=False,
switch_pm_parameter="help",
)
elif inline_query.query.strip().lower().split()[0] == "botapi":
if len(inline_query.query.strip().lower().split()) < 2:
return await inline_query.answer(
Expand Down
104 changes: 104 additions & 0 deletions misskaty/plugins/misc_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import html
import json
import os
import re
import traceback
from logging import getLogger
from urllib.parse import quote
Expand Down Expand Up @@ -45,6 +46,7 @@
__MODULE__ = "Misc"
__HELP__ = """
/carbon [text or reply to text or caption] - Make beautiful snippet code on carbon from text.
/calc - Simple math calculator using inline buttons.
/kbbi [keyword] - Search definition on KBBI (For Indonesian People)
/sof [query] - Search your problem in StackOverflow.
/google [query] - Search using Google Search.
Expand All @@ -67,6 +69,108 @@ def remove_html_tags(text):
return re.sub(clean, "", text)


def calcExpression(text):
try:
return float(eval(text))
except (SyntaxError, ZeroDivisionError):
return ""
except TypeError:
return float(eval(text.replace('(', '*(')))
except Exception as e:
logger.error(e, exc_info=True)
return ""


def calc_btn(uid):
CALCULATE_BUTTONS = InlineKeyboardMarkup(
[
[
InlineKeyboardButton("DEL", callback_data=f"calc|{uid}|DEL"),
InlineKeyboardButton("AC", callback_data=f"calc|{uid}|AC"),
InlineKeyboardButton("(", callback_data=f"calc|{uid}|("),
InlineKeyboardButton(")", callback_data=f"calc|{uid}|)")
],
[
InlineKeyboardButton("7", callback_data=f"calc|{uid}|7"),
InlineKeyboardButton("8", callback_data=f"calc|{uid}|8"),
InlineKeyboardButton("9", callback_data=f"calc|{uid}|9"),
InlineKeyboardButton("÷", callback_data=f"calc|{uid}|/")
],
[
InlineKeyboardButton("4", callback_data=f"calc|{uid}|4"),
InlineKeyboardButton("5", callback_data=f"calc|{uid}|5"),
InlineKeyboardButton("6", callback_data=f"calc|{uid}|6"),
InlineKeyboardButton("×", callback_data=f"calc|{uid}|*")
],
[
InlineKeyboardButton("1", callback_data=f"calc|{uid}|1"),
InlineKeyboardButton("2", callback_data=f"calc|{uid}|2"),
InlineKeyboardButton("3", callback_data=f"calc|{uid}|3"),
InlineKeyboardButton("-", callback_data=f"calc|{uid}|-"),
],
[
InlineKeyboardButton(".", callback_data=f"calc|{uid}|."),
InlineKeyboardButton("0", callback_data=f"calc|{uid}|0"),
InlineKeyboardButton("=", callback_data=f"calc|{uid}|="),
InlineKeyboardButton("+", callback_data=f"calc|{uid}|+"),
]
]
)
return CALCULATE_BUTTONS


@app.on_message(filters.command(["calc", "calculate", "calculator"]))
async def calculate_handler(self, ctx):
if not ctx.from_user:
return
await ctx.reply_text(
text=f"Made by @{self.me.username}",
reply_markup=calc_btn(ctx.from_user.id),
disable_web_page_preview=True,
quote=True
)

@app.on_callback_query(filters.regex("^calc"))
async def calc_cb(self, query):
_, uid, data = query.data.split("|")
if query.from_user.id != int(uid):
return await query.answer("Who are you??", show_alert=True, cache_time=5)
try:
text = query.message.text.split("\n")[0].strip().split("=")[0].strip()
text = '' if f"Made by @{self.me.username}" in text else text
inpt = text + query.data
result = ""
if data == "=":
result = calcExpression(text)
text = ""
elif data == "DEL":
text = text[:-1]
elif data == "AC":
text = ""
else:
dot_dot_check = re.findall(r"(\d*\.\.|\d*\.\d+\.)", inpt)
opcheck = re.findall(r"([*/\+-]{2,})", inpt)
if not dot_dot_check and not opcheck:
strOperands = re.findall(r"(\.\d+|\d+\.\d+|\d+)", inpt)
if strOperands:
text += data
result = calcExpression(text)

text = f"{text:<50}"
if result:
if text:
text += f"\n{result:>50}"
else:
text = result
text += f"\n\nMade by @{self.me.username}"
await query.message.edit_msg(
text=text,
disable_web_page_preview=True,
reply_markup=calc_btn(query.from_user.id)
)
except Exception as error:
LOGGER.error(error)

@app.on_cmd("kbbi")
async def kbbi_search(_, ctx: Client):
if len(ctx.command) == 1:
Expand Down

0 comments on commit 90c6e8a

Please sign in to comment.