From dc13870315ee361c20f53f3939f557d913cabd9c Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 10:39:00 +0700 Subject: [PATCH 01/24] Add fastapi depedencies --- requirements.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/requirements.txt b/requirements.txt index e30cf1953f..517d7cf5a2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -34,3 +34,6 @@ GitPython aiofiles uvloop==0.19.0 lxml_html_clean +fastapi +uvicorn +python-multipart From 7b4fbf00834925c79d9ed1d6fbe94016977ee53b Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 10:51:14 +0700 Subject: [PATCH 02/24] cek --- Dockerfile | 6 +-- misskaty/__init__.py | 5 +++ misskaty/__main__.py | 3 +- misskaty/vars.py | 3 ++ web/webserver.py | 89 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 web/webserver.py diff --git a/Dockerfile b/Dockerfile index d7a95b4727..f2a0542fc4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,15 +5,15 @@ # Base Docker Using Ubuntu 24.04, Python 3.12 and Built In Pip ## With Built in Pip Package -FROM yasirarism/misskaty-docker:py3.12 +# FROM yasirarism/misskaty-docker:py3.12 ## Without Built in Pip Package -# FROM yasirarism/misskaty-docker:free +FROM yasirarism/misskaty-docker:free # Set Hostname ENV HOSTNAME=yasir-server # Copy Files COPY . . # Instal pip package -# RUN pip3 install --no-cache-dir -r requirements.txt +RUN pip3 install --no-cache-dir -r requirements.txt # Set CMD Bot CMD ["bash", "start.sh"] diff --git a/misskaty/__init__.py b/misskaty/__init__.py index 8dc0c40bcd..9f064f99bf 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -83,6 +83,11 @@ } scheduler = AsyncIOScheduler(jobstores=jobstores, timezone=TZ) +async def run_wsgi(): + config = uvicorn.Config(app, host="0.0.0.0", port=int(BASE_URL_PORT)) + server = uvicorn.Server(config) + await server.serve() + app.start() BOT_ID = app.me.id BOT_NAME = app.me.first_name diff --git a/misskaty/__main__.py b/misskaty/__main__.py index 9ab25ecf3e..e055682afd 100644 --- a/misskaty/__main__.py +++ b/misskaty/__main__.py @@ -24,6 +24,7 @@ app, get_event_loop, scheduler, + run_wsgi ) from misskaty.plugins import ALL_MODULES from misskaty.plugins.web_scraper import web @@ -56,7 +57,7 @@ async def start_bot(): LOGGER.info(bot_modules) LOGGER.info("+===============+===============+===============+===============+") LOGGER.info("[INFO]: BOT STARTED AS @%s!", BOT_USERNAME) - + asyncio.create_task(run_wsgi()) try: LOGGER.info("[INFO]: SENDING ONLINE STATUS") for i in SUDO: diff --git a/misskaty/vars.py b/misskaty/vars.py index 21103c1ab2..8b60656b6c 100644 --- a/misskaty/vars.py +++ b/misskaty/vars.py @@ -50,6 +50,7 @@ USER_SESSION = environ.get("USER_SESSION") DATABASE_NAME = environ.get("DATABASE_NAME", "MissKatyDB") TZ = environ.get("TZ", "Asia/Jakarta") +PORT = environ.get("PORT", 80) COMMAND_HANDLER = environ.get("COMMAND_HANDLER", "! /").split() SUDO = list( { @@ -64,6 +65,8 @@ AUTO_RESTART = environ.get("AUTO_RESTART", False) OPENAI_KEY = environ.get("OPENAI_KEY") GOOGLEAI_KEY = environ.get("GOOGLEAI_KEY") +PAYDISINI_KEY = environ.get("PAYDISINI_KEY") +PAYDISINI_CHANNEL_ID = environ.get("PAYDISINI_CHANNEL_ID", "17") ## Config For AUtoForwarder # Forward From Chat ID diff --git a/web/webserver.py b/web/webserver.py new file mode 100644 index 0000000000..478d5e6842 --- /dev/null +++ b/web/webserver.py @@ -0,0 +1,89 @@ +from logging import INFO, FileHandler, StreamHandler, basicConfig, getLogger, ERROR +from os import path +from time import time +from datetime import datetime, timedelta + +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, JSONResponse +from starlette.exceptions import HTTPException +from psutil import boot_time, disk_usage, net_io_counters +from contextlib import suppress +from asyncio import to_thread, subprocess, create_subprocess_shell +from apscheduler.triggers.date import DateTrigger +import hashlib + +app = FastAPI() + +basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[FileHandler("log.txt"), StreamHandler()], level=INFO) + +botStartTime = time() + +LOGGER = getLogger(__name__) +getLogger("fastapi").setLevel(ERROR) + +@app.post("/callback") +async def autopay(request: Request): + from bot import bot, config_dict, jkt + from bot.helper.ext_utils.db_handler import DbManger + from bot.helper.ext_utils.bot_utils import update_user_ldata + data = await request.form() + client_ip = request.client.host + if config_dict["PAYDISINI_KEY"] != data["key"] and client_ip != "84.247.150.90": + raise HTTPException(status_code=403, detail="Access forbidden") + signature_data = f"{config_dict['PAYDISINI_KEY']}{data['unique_code']}CallbackStatus" + gen_signature = hashlib.md5(signature_data.encode()).hexdigest() + if gen_signature != data["signature"]: + raise HTTPException(status_code=403, detail="Invalid Signature") + return data + unique_code = data['unique_code'] + status = data['status'] + exp_date = (datetime.now(jkt) + timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S") + r = await DbManger().get_autopay(unique_code) + msg = f"╭────〔 TRANSAKSI SUKSES🎉 〕──\n│・ Transaksi ID : {unique_code}\n│・ Product : VIP Bot Subscription by {config_dict['BY']}\n│・ Durasi : 30 hari\n│・ Total Dibayar : {r.get('amount')}\n│・ Langganan Berakhir: {exp_date}\n╰─────────" + if not r: + return JSONResponse({"status": false, "data": "Data not found on DB"}, 404) + if status == "Success": + with suppress(Exception): + await bot.send_message(r.get("user_id"), f"{msg}\n\nJika ada pertanyaan silahkan hubungi pemilik bot ini.") + await bot.delete_messages(r.get("user_id"), r.get("msg_id")) + await DbManger().update_user_data(r.get("user_id")) + await bot.send_message(config_dict["OWNER_ID"], msg) + return JSONResponse({"status": status, "msg": "Pesanan berhasil dibayar oleh customer."}, 200) + else: + with suppress(Exception): + await bot.send_message(r.get("user_id"), "QRIS Telah Expired, Silahkan Buat Transaksi Baru.") + await bot.delete_messages(r.get("user_id"), r.get("msg_id")) + return JSONResponse({"status": status, "msg": "Pesanan telah dibatalkan/gagal dibayar."}, 403) + +@app.get("/status") +async def status(): + from misskaty.helper.human_read import get_readable_file_size, get_readable_time + bot_uptime = get_readable_time(time() - botStartTime) + uptime = get_readable_time(time() - boot_time()) + sent = get_readable_file_size(net_io_counters().bytes_sent) + recv = get_readable_file_size(net_io_counters().bytes_recv) + if path.exists(".git"): + commit_date = (await (await create_subprocess_shell("git log -1 --date=format:'%y/%m/%d %H:%M' --pretty=format:'%cd'", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)).communicate())[0].decode() + else: + commit_date = "No UPSTREAM_REPO" + return { + "commit_date": commit_date, + "uptime": uptime, + "on_time": bot_uptime, + "free_disk": get_readable_file_size(disk_usage(".").free), + "total_disk": get_readable_file_size(disk_usage(".").total), + "network": { + "sent": sent, + "recv": recv, + }, + } + + +@app.api_route("/") +async def homepage(): + return "Hello World" + + +@app.exception_handler(HTTPException) +async def page_not_found(request: Request, exc: HTTPException): + return f"Error: {exc}" \ No newline at end of file From 25fb44dee434e4d01308366713e781808c6c0b04 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:01:05 +0700 Subject: [PATCH 03/24] s --- web/webserver.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/web/webserver.py b/web/webserver.py index 478d5e6842..620cce8753 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -23,14 +23,13 @@ @app.post("/callback") async def autopay(request: Request): - from bot import bot, config_dict, jkt - from bot.helper.ext_utils.db_handler import DbManger - from bot.helper.ext_utils.bot_utils import update_user_ldata + from misskaty import app + from misskaty.vars import PAYDISINI_KEY, OWNER_ID data = await request.form() client_ip = request.client.host - if config_dict["PAYDISINI_KEY"] != data["key"] and client_ip != "84.247.150.90": + if PAYDISINI_KEY != data["key"] and client_ip != "84.247.150.90": raise HTTPException(status_code=403, detail="Access forbidden") - signature_data = f"{config_dict['PAYDISINI_KEY']}{data['unique_code']}CallbackStatus" + signature_data = f"{PAYDISINI_KEY}{data['unique_code']}CallbackStatus" gen_signature = hashlib.md5(signature_data.encode()).hexdigest() if gen_signature != data["signature"]: raise HTTPException(status_code=403, detail="Invalid Signature") @@ -47,7 +46,7 @@ async def autopay(request: Request): await bot.send_message(r.get("user_id"), f"{msg}\n\nJika ada pertanyaan silahkan hubungi pemilik bot ini.") await bot.delete_messages(r.get("user_id"), r.get("msg_id")) await DbManger().update_user_data(r.get("user_id")) - await bot.send_message(config_dict["OWNER_ID"], msg) + await bot.send_message(OWNER_ID, msg) return JSONResponse({"status": status, "msg": "Pesanan berhasil dibayar oleh customer."}, 200) else: with suppress(Exception): From d7d7271010576565312815c0606f0ad4bb025a31 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:02:25 +0700 Subject: [PATCH 04/24] fix --- misskaty/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/misskaty/__init__.py b/misskaty/__init__.py index 9f064f99bf..c2d6610dd7 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -8,7 +8,7 @@ from faulthandler import enable as faulthandler_enable from logging import ERROR, INFO, StreamHandler, basicConfig, getLogger, handlers -import uvloop +import uvloop, uvicorn from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.schedulers.asyncio import AsyncIOScheduler from async_pymongo import AsyncClient From 4f0138b8cae0593818d8a05fe5a1dee9b938cca6 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:05:51 +0700 Subject: [PATCH 05/24] ok --- misskaty/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/misskaty/__init__.py b/misskaty/__init__.py index c2d6610dd7..0fb9bcc429 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -21,6 +21,7 @@ BOT_TOKEN, DATABASE_NAME, DATABASE_URI, + PORT, TZ, USER_SESSION, ) @@ -84,7 +85,7 @@ scheduler = AsyncIOScheduler(jobstores=jobstores, timezone=TZ) async def run_wsgi(): - config = uvicorn.Config(app, host="0.0.0.0", port=int(BASE_URL_PORT)) + config = uvicorn.Config(app, host="0.0.0.0", port=int(PORT)) server = uvicorn.Server(config) await server.serve() From 53a1e1d5c4bda6b5d025f4330fffaaa752c66cc9 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:09:32 +0700 Subject: [PATCH 06/24] oke --- misskaty/__init__.py | 3 ++- web/webserver.py | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/misskaty/__init__.py b/misskaty/__init__.py index 0fb9bcc429..892f86532c 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -14,6 +14,7 @@ from async_pymongo import AsyncClient from pymongo import MongoClient from pyrogram import Client +from web.webserver import api from misskaty.vars import ( API_HASH, @@ -85,7 +86,7 @@ scheduler = AsyncIOScheduler(jobstores=jobstores, timezone=TZ) async def run_wsgi(): - config = uvicorn.Config(app, host="0.0.0.0", port=int(PORT)) + config = uvicorn.Config(api, host="0.0.0.0", port=int(PORT)) server = uvicorn.Server(config) await server.serve() diff --git a/web/webserver.py b/web/webserver.py index 620cce8753..d08b1645fe 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -12,7 +12,7 @@ from apscheduler.triggers.date import DateTrigger import hashlib -app = FastAPI() +api = FastAPI() basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[FileHandler("log.txt"), StreamHandler()], level=INFO) @@ -21,7 +21,7 @@ LOGGER = getLogger(__name__) getLogger("fastapi").setLevel(ERROR) -@app.post("/callback") +@api.post("/callback") async def autopay(request: Request): from misskaty import app from misskaty.vars import PAYDISINI_KEY, OWNER_ID @@ -54,7 +54,7 @@ async def autopay(request: Request): await bot.delete_messages(r.get("user_id"), r.get("msg_id")) return JSONResponse({"status": status, "msg": "Pesanan telah dibatalkan/gagal dibayar."}, 403) -@app.get("/status") +@api.get("/status") async def status(): from misskaty.helper.human_read import get_readable_file_size, get_readable_time bot_uptime = get_readable_time(time() - botStartTime) @@ -78,11 +78,11 @@ async def status(): } -@app.api_route("/") +@api.api_route("/") async def homepage(): return "Hello World" -@app.exception_handler(HTTPException) +@api.exception_handler(HTTPException) async def page_not_found(request: Request, exc: HTTPException): return f"Error: {exc}" \ No newline at end of file From 92e2ed612abf1be6459528f6b9b4fb0d1911f16d Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:19:31 +0700 Subject: [PATCH 07/24] f --- web/webserver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/webserver.py b/web/webserver.py index d08b1645fe..6ccf0a6205 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -85,4 +85,4 @@ async def homepage(): @api.exception_handler(HTTPException) async def page_not_found(request: Request, exc: HTTPException): - return f"Error: {exc}" \ No newline at end of file + return HTMLResponse(content=f"

Error: {exc}

", status_code=exc.status_code) \ No newline at end of file From a20c3b32ee67bad5cdc1cbde1405e9fcbc3ea085 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:24:42 +0700 Subject: [PATCH 08/24] oke --- misskaty/plugins/dev.py | 41 ++++++++++++++++++++++++++++++++++++++++- web/webserver.py | 2 +- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 93c356f7a9..de8a2bcc3d 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -55,7 +55,7 @@ from misskaty.helper.http import fetch from misskaty.helper.human_read import get_readable_file_size, get_readable_time from misskaty.helper.localization import use_chat_lang -from misskaty.vars import AUTO_RESTART, COMMAND_HANDLER, LOG_CHANNEL, SUDO +from misskaty.vars import AUTO_RESTART, COMMAND_HANDLER, LOG_CHANNEL, SUDO, PAYDISINI_CHANNEL_ID, PAYDISINI_KEY __MODULE__ = "DevCommand" __HELP__ = """ @@ -179,6 +179,45 @@ async def log_file(_, ctx: Message, strings): else: await msg.edit_msg("Unsupported parameter") +@app.on_message(filters.command(["payment"], COMMAND_HANDLER)) +async def payment(self: Client, message: Message): + api_url = 'https://api.paydisini.co.id/v1/' + api_key = PAYDISINI_KEY + unique_id = f"VIP-{secrets.token_hex(5)}" + amount = "10000" + id_ = message.from_user.id + valid_time = str(5*60) + service_id = PAYDISINI_CHANNEL_ID + + params = { + 'key': api_key, + 'request': 'new', + 'unique_code': unique_id, + 'service': service_id, + 'amount': amount, + 'note': f'VIP Bot Subscription by {config_dict["BY"]}', + 'valid_time': valid_time, + 'type_fee': '1', + 'payment_guide': True, + 'signature': hashlib.md5((api_key + unique_id + service_id + amount + valid_time + 'NewTransaction').encode()).hexdigest(), + 'return_url': f'https://t.me/{client.me.username}' + } + if message.chat.type.value != "private": + return await message.reply("Please use this command on DM.") + if id_ in user_data and user_data[id_].get("is_auth"): + return await message.reply("Already Authorized!") + rget = await fetch.post(api_url, data=params) + if rget.status_code != 200: + return await message.reply("ERROR: Maybe your IP is not whitelisted or have another error from api.") + res = rget.json() + if not res.get("success"): + return await message.reply(res["msg"]) + qr_photo = f"https://api.qrserver.com/v1/create-qr-code/?size=300x300&data={quote(res['data']['qr_content'])}" + capt = f"𝗠𝗲𝗻𝘂𝗻𝗴𝗴𝘂 𝗽𝗲𝗺𝗯𝗮𝘆𝗮𝗿𝗮𝗻\nKode: {res['data']['unique_code']}\nNote: {res['data']['note']}\nHarga: {res['data']['amount']}\nFee: {res['data']['fee']}\nExpired: {res['data']['expired']}\n\n" + payment_guide = f"{res['payment_guide'][0]['title']}:\n" + "\n".join(f"{i+1}. {step}" for i, step in enumerate(res["payment_guide"][0]['content'])) + msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", web_app=WebAppInfo(url=res["data"]["checkout_url_v2"]))]]), quote=True) + # if DATABASE_URL: + # await DbManger().autopay_update(msg.id, res["data"]["note"], id_, res['data']['amount'], res['data']['status'], res['data']['unique_code'], res['data']['created_at']) @app.on_message(filters.command(["donate"], COMMAND_HANDLER)) async def donate(self: Client, ctx: Message): diff --git a/web/webserver.py b/web/webserver.py index 6ccf0a6205..af711a75cb 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -23,6 +23,7 @@ @api.post("/callback") async def autopay(request: Request): + # ToDO Add Database Integration from misskaty import app from misskaty.vars import PAYDISINI_KEY, OWNER_ID data = await request.form() @@ -45,7 +46,6 @@ async def autopay(request: Request): with suppress(Exception): await bot.send_message(r.get("user_id"), f"{msg}\n\nJika ada pertanyaan silahkan hubungi pemilik bot ini.") await bot.delete_messages(r.get("user_id"), r.get("msg_id")) - await DbManger().update_user_data(r.get("user_id")) await bot.send_message(OWNER_ID, msg) return JSONResponse({"status": status, "msg": "Pesanan berhasil dibayar oleh customer."}, 200) else: From 15aa45ab04010dfd1b847939a481558df5115b69 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:30:51 +0700 Subject: [PATCH 09/24] cek --- misskaty/__main__.py | 2 +- misskaty/plugins/dev.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/misskaty/__main__.py b/misskaty/__main__.py index e055682afd..3b8fffa395 100644 --- a/misskaty/__main__.py +++ b/misskaty/__main__.py @@ -57,7 +57,6 @@ async def start_bot(): LOGGER.info(bot_modules) LOGGER.info("+===============+===============+===============+===============+") LOGGER.info("[INFO]: BOT STARTED AS @%s!", BOT_USERNAME) - asyncio.create_task(run_wsgi()) try: LOGGER.info("[INFO]: SENDING ONLINE STATUS") for i in SUDO: @@ -74,6 +73,7 @@ async def start_bot(): except Exception as e: LOGGER.error(str(e)) scheduler.start() + # asyncio.create_task(run_wsgi()) if "web" not in await dbname.list_collection_names(): webdb = dbname["web"] for key, value in web.items(): diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index de8a2bcc3d..13764d28b9 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -8,6 +8,7 @@ import platform import privatebinapi import re +import secrets import sys import traceback from datetime import datetime From d4fd8a0b48701dee2cee1d9a4fe135c36ddcaeaa Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:34:16 +0700 Subject: [PATCH 10/24] oke --- web/webserver.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/web/webserver.py b/web/webserver.py index af711a75cb..2365575765 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -1,4 +1,4 @@ -from logging import INFO, FileHandler, StreamHandler, basicConfig, getLogger, ERROR +from logging import INFO, StreamHandler, basicConfig, getLogger, ERROR, StreamHandler from os import path from time import time from datetime import datetime, timedelta @@ -14,8 +14,17 @@ api = FastAPI() -basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[FileHandler("log.txt"), StreamHandler()], level=INFO) - +basicConfig( + level=INFO, + format="[%(levelname)s] - [%(asctime)s - %(name)s - %(message)s] -> [%(module)s:%(lineno)d]", + datefmt="%d-%b-%y %H:%M:%S", + handlers=[ + handlers.RotatingFileHandler( + "MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1 + ), + StreamHandler(), + ], +) botStartTime = time() LOGGER = getLogger(__name__) From 9eac66be351f60c469e1ae35f9e91a89aa78b7ec Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:35:40 +0700 Subject: [PATCH 11/24] hee --- misskaty/plugins/dev.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 13764d28b9..49490c5428 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -182,6 +182,7 @@ async def log_file(_, ctx: Message, strings): @app.on_message(filters.command(["payment"], COMMAND_HANDLER)) async def payment(self: Client, message: Message): + # ToDO Add DB Intgration api_url = 'https://api.paydisini.co.id/v1/' api_key = PAYDISINI_KEY unique_id = f"VIP-{secrets.token_hex(5)}" @@ -196,7 +197,7 @@ async def payment(self: Client, message: Message): 'unique_code': unique_id, 'service': service_id, 'amount': amount, - 'note': f'VIP Bot Subscription by {config_dict["BY"]}', + 'note': f'VIP Bot Subscription by YS Dev', 'valid_time': valid_time, 'type_fee': '1', 'payment_guide': True, @@ -205,8 +206,8 @@ async def payment(self: Client, message: Message): } if message.chat.type.value != "private": return await message.reply("Please use this command on DM.") - if id_ in user_data and user_data[id_].get("is_auth"): - return await message.reply("Already Authorized!") + # if id_ in user_data and user_data[id_].get("is_auth"): + # return await message.reply("Already Authorized!") rget = await fetch.post(api_url, data=params) if rget.status_code != 200: return await message.reply("ERROR: Maybe your IP is not whitelisted or have another error from api.") From 97eabb550451d6d526ee8d10836e6c6aa2e060da Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:36:37 +0700 Subject: [PATCH 12/24] hmm --- web/webserver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/webserver.py b/web/webserver.py index 2365575765..2c80e36f8a 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -1,4 +1,4 @@ -from logging import INFO, StreamHandler, basicConfig, getLogger, ERROR, StreamHandler +from logging import INFO, StreamHandler, basicConfig, getLogger, ERROR, handlers from os import path from time import time from datetime import datetime, timedelta From 26e074c99a14695838050a6f2cceabd38fb390b9 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:37:57 +0700 Subject: [PATCH 13/24] hadeh --- misskaty/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/misskaty/__main__.py b/misskaty/__main__.py index 3b8fffa395..95f76f5f4f 100644 --- a/misskaty/__main__.py +++ b/misskaty/__main__.py @@ -73,7 +73,7 @@ async def start_bot(): except Exception as e: LOGGER.error(str(e)) scheduler.start() - # asyncio.create_task(run_wsgi()) + asyncio.create_task(run_wsgi()) if "web" not in await dbname.list_collection_names(): webdb = dbname["web"] for key, value in web.items(): From b48847aff4c35f84bbd806399edfb665a2894070 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:38:58 +0700 Subject: [PATCH 14/24] hadhe --- misskaty/plugins/dev.py | 1 + 1 file changed, 1 insertion(+) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 49490c5428..f95449a95f 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -4,6 +4,7 @@ import io import json import os +import hashlib import pickle import platform import privatebinapi From cded4f3a81ca7cdd034b533d9ac7eddef97e8df1 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:41:32 +0700 Subject: [PATCH 15/24] hmm --- misskaty/plugins/dev.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index f95449a95f..1b2fdc4cce 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -182,7 +182,7 @@ async def log_file(_, ctx: Message, strings): await msg.edit_msg("Unsupported parameter") @app.on_message(filters.command(["payment"], COMMAND_HANDLER)) -async def payment(self: Client, message: Message): +async def payment(client: Client, message: Message): # ToDO Add DB Intgration api_url = 'https://api.paydisini.co.id/v1/' api_key = PAYDISINI_KEY From 31bbbcf62b5d47dcd1851a055619fb2f797477e5 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:45:28 +0700 Subject: [PATCH 16/24] oke --- misskaty/plugins/dev.py | 1 + 1 file changed, 1 insertion(+) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 1b2fdc4cce..c9e610c3fb 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -24,6 +24,7 @@ import requests from apscheduler.schedulers.asyncio import AsyncIOScheduler from bs4 import BeautifulSoup +from urllib.parse import quote from PIL import Image, ImageDraw, ImageFont from psutil import Process, boot_time, cpu_count, cpu_percent from psutil import disk_usage as disk_usage_percent From 4f07175f9cd505f2b4e428a09d442411bdad3792 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 11:46:44 +0700 Subject: [PATCH 17/24] e --- misskaty/plugins/dev.py | 1 + 1 file changed, 1 insertion(+) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index c9e610c3fb..43726c9499 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -47,6 +47,7 @@ LabeledPrice, Message, PreCheckoutQuery, + WebAppInfo, ) from database.gban_db import add_gban_user, is_gbanned_user, remove_gban_user From 99559bd23e5943de134bd8be3d84ea1d996e3daa Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:31:04 +0700 Subject: [PATCH 18/24] cek --- misskaty/plugins/dev.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 43726c9499..d371d3acb3 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -220,7 +220,10 @@ async def payment(client: Client, message: Message): qr_photo = f"https://api.qrserver.com/v1/create-qr-code/?size=300x300&data={quote(res['data']['qr_content'])}" capt = f"𝗠𝗲𝗻𝘂𝗻𝗴𝗴𝘂 𝗽𝗲𝗺𝗯𝗮𝘆𝗮𝗿𝗮𝗻\nKode: {res['data']['unique_code']}\nNote: {res['data']['note']}\nHarga: {res['data']['amount']}\nFee: {res['data']['fee']}\nExpired: {res['data']['expired']}\n\n" payment_guide = f"{res['payment_guide'][0]['title']}:\n" + "\n".join(f"{i+1}. {step}" for i, step in enumerate(res["payment_guide"][0]['content'])) - msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", web_app=WebAppInfo(url=res["data"]["checkout_url_v2"]))]]), quote=True) + if message.chat.type.value != "private": + msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", url=res["data"]["checkout_url_v2"])]]), quote=True) + else: + msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", web_app=WebAppInfo(url=res["data"]["checkout_url_v2"]))]]), quote=True) # if DATABASE_URL: # await DbManger().autopay_update(msg.id, res["data"]["note"], id_, res['data']['amount'], res['data']['status'], res['data']['unique_code'], res['data']['created_at']) From abe904a8814850d7a7ecf468d6f63ad084747a44 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:33:08 +0700 Subject: [PATCH 19/24] oke --- misskaty/plugins/dev.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index d371d3acb3..2904cf0c3d 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -190,7 +190,7 @@ async def payment(client: Client, message: Message): api_key = PAYDISINI_KEY unique_id = f"VIP-{secrets.token_hex(5)}" amount = "10000" - id_ = message.from_user.id + id_ = message.from_user.id if message.chat.id != message.from_user.id else message.chat.id valid_time = str(5*60) service_id = PAYDISINI_CHANNEL_ID @@ -207,8 +207,6 @@ async def payment(client: Client, message: Message): 'signature': hashlib.md5((api_key + unique_id + service_id + amount + valid_time + 'NewTransaction').encode()).hexdigest(), 'return_url': f'https://t.me/{client.me.username}' } - if message.chat.type.value != "private": - return await message.reply("Please use this command on DM.") # if id_ in user_data and user_data[id_].get("is_auth"): # return await message.reply("Already Authorized!") rget = await fetch.post(api_url, data=params) From 63fa8e00e1dde5e1f1a55b5bdbf2dd091ea6c6ad Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:36:41 +0700 Subject: [PATCH 20/24] oke --- misskaty/plugins/dev.py | 2 +- web/webserver.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 2904cf0c3d..32684221de 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -205,7 +205,7 @@ async def payment(client: Client, message: Message): 'type_fee': '1', 'payment_guide': True, 'signature': hashlib.md5((api_key + unique_id + service_id + amount + valid_time + 'NewTransaction').encode()).hexdigest(), - 'return_url': f'https://t.me/{client.me.username}' + 'return_url': f'https://t.me/{client.me.username}?start' } # if id_ in user_data and user_data[id_].get("is_auth"): # return await message.reply("Already Authorized!") diff --git a/web/webserver.py b/web/webserver.py index 2c80e36f8a..3e96dc5d90 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -48,7 +48,7 @@ async def autopay(request: Request): status = data['status'] exp_date = (datetime.now(jkt) + timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S") r = await DbManger().get_autopay(unique_code) - msg = f"╭────〔 TRANSAKSI SUKSES🎉 〕──\n│・ Transaksi ID : {unique_code}\n│・ Product : VIP Bot Subscription by {config_dict['BY']}\n│・ Durasi : 30 hari\n│・ Total Dibayar : {r.get('amount')}\n│・ Langganan Berakhir: {exp_date}\n╰─────────" + msg = f"╭────〔 TRANSAKSI SUKSES🎉 〕──\n│・ Transaksi ID : {unique_code}\n│・ Product : MissKaty Support by YS Dev\n│・ Durasi : 30 hari\n│・ Total Dibayar : {r.get('amount')}\n│・ Langganan Berakhir: {exp_date}\n╰─────────" if not r: return JSONResponse({"status": false, "data": "Data not found on DB"}, 404) if status == "Success": From 6434ae19e1bcc2f2efcdc0dda9556e45ed8dc888 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:48:18 +0700 Subject: [PATCH 21/24] oke --- database/payment_db.py | 15 +++++++++++++++ misskaty/plugins/dev.py | 7 +++---- web/webserver.py | 7 ++++--- 3 files changed, 22 insertions(+), 7 deletions(-) create mode 100644 database/payment_db.py diff --git a/database/payment_db.py b/database/payment_db.py new file mode 100644 index 0000000000..0e9ddba0b0 --- /dev/null +++ b/database/payment_db.py @@ -0,0 +1,15 @@ +from database import dbname + +autopay = dbname["autpay"] + + +async def delete_autopay(uniqueCode: str): + await autopay.delete_one({"_id": uniqueCode}) + +async def get_autopay(self, uniqueCode: str): + exists = await autopay.find_one({"_id": uniqueCode}) + return exists + +async def autopay_update(self, msg_id: Optional[int] = "", note: Optional[str] = "", user_id: Optional[int] = "", amount: Optional[int] = "", status: Optional[str] = "", uniqueCode: Optional[str] = "", createdAt: Optional[str] = ""): + data = {"msg_id": msg_id, "note": note, "user_id": user_id, "amount": amount, "status": status, "createdAt": createdAt} + await autopay.update_one({"_id": uniqueCode}, {"$set": data}, upsert=True) \ No newline at end of file diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 32684221de..057af71fed 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -59,6 +59,7 @@ from misskaty.helper.http import fetch from misskaty.helper.human_read import get_readable_file_size, get_readable_time from misskaty.helper.localization import use_chat_lang +from database.payment_db import autopay_update from misskaty.vars import AUTO_RESTART, COMMAND_HANDLER, LOG_CHANNEL, SUDO, PAYDISINI_CHANNEL_ID, PAYDISINI_KEY __MODULE__ = "DevCommand" @@ -185,11 +186,10 @@ async def log_file(_, ctx: Message, strings): @app.on_message(filters.command(["payment"], COMMAND_HANDLER)) async def payment(client: Client, message: Message): - # ToDO Add DB Intgration api_url = 'https://api.paydisini.co.id/v1/' api_key = PAYDISINI_KEY unique_id = f"VIP-{secrets.token_hex(5)}" - amount = "10000" + amount = "10000" if len(message.command) == 1 else str(message.command[1]) id_ = message.from_user.id if message.chat.id != message.from_user.id else message.chat.id valid_time = str(5*60) service_id = PAYDISINI_CHANNEL_ID @@ -222,8 +222,7 @@ async def payment(client: Client, message: Message): msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", url=res["data"]["checkout_url_v2"])]]), quote=True) else: msg = await message.reply_photo(qr_photo, caption=capt+payment_guide, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Payment Web", web_app=WebAppInfo(url=res["data"]["checkout_url_v2"]))]]), quote=True) - # if DATABASE_URL: - # await DbManger().autopay_update(msg.id, res["data"]["note"], id_, res['data']['amount'], res['data']['status'], res['data']['unique_code'], res['data']['created_at']) + await autopay_update(msg.id, res["data"]["note"], id_, res['data']['amount'], res['data']['status'], res['data']['unique_code'], res['data']['created_at']) @app.on_message(filters.command(["donate"], COMMAND_HANDLER)) async def donate(self: Client, ctx: Message): diff --git a/web/webserver.py b/web/webserver.py index 3e96dc5d90..84871642ce 100644 --- a/web/webserver.py +++ b/web/webserver.py @@ -32,8 +32,8 @@ @api.post("/callback") async def autopay(request: Request): - # ToDO Add Database Integration from misskaty import app + from database.payment_db import delete_autopay, get_autopay from misskaty.vars import PAYDISINI_KEY, OWNER_ID data = await request.form() client_ip = request.client.host @@ -43,11 +43,10 @@ async def autopay(request: Request): gen_signature = hashlib.md5(signature_data.encode()).hexdigest() if gen_signature != data["signature"]: raise HTTPException(status_code=403, detail="Invalid Signature") - return data unique_code = data['unique_code'] status = data['status'] exp_date = (datetime.now(jkt) + timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S") - r = await DbManger().get_autopay(unique_code) + r = await get_autopay(unique_code) msg = f"╭────〔 TRANSAKSI SUKSES🎉 〕──\n│・ Transaksi ID : {unique_code}\n│・ Product : MissKaty Support by YS Dev\n│・ Durasi : 30 hari\n│・ Total Dibayar : {r.get('amount')}\n│・ Langganan Berakhir: {exp_date}\n╰─────────" if not r: return JSONResponse({"status": false, "data": "Data not found on DB"}, 404) @@ -56,11 +55,13 @@ async def autopay(request: Request): await bot.send_message(r.get("user_id"), f"{msg}\n\nJika ada pertanyaan silahkan hubungi pemilik bot ini.") await bot.delete_messages(r.get("user_id"), r.get("msg_id")) await bot.send_message(OWNER_ID, msg) + await delete_autopay(unique_code) return JSONResponse({"status": status, "msg": "Pesanan berhasil dibayar oleh customer."}, 200) else: with suppress(Exception): await bot.send_message(r.get("user_id"), "QRIS Telah Expired, Silahkan Buat Transaksi Baru.") await bot.delete_messages(r.get("user_id"), r.get("msg_id")) + await delete_autopay(unique_code) return JSONResponse({"status": status, "msg": "Pesanan telah dibatalkan/gagal dibayar."}, 403) @api.get("/status") From 544333415ac383c327a23bde27ce0c3bafc01857 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:50:27 +0700 Subject: [PATCH 22/24] oke --- database/payment_db.py | 1 + 1 file changed, 1 insertion(+) diff --git a/database/payment_db.py b/database/payment_db.py index 0e9ddba0b0..915df43b9f 100644 --- a/database/payment_db.py +++ b/database/payment_db.py @@ -1,4 +1,5 @@ from database import dbname +from typing import Optional autopay = dbname["autpay"] From e9b0117b8a4e1e1359c1000b5b67c94cc489a75b Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:55:57 +0700 Subject: [PATCH 23/24] Update Dockerfile --- Dockerfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index f2a0542fc4..5ad9bfa71d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,15 +5,15 @@ # Base Docker Using Ubuntu 24.04, Python 3.12 and Built In Pip ## With Built in Pip Package -# FROM yasirarism/misskaty-docker:py3.12 +FROM yasirarism/misskaty-docker:py3.12 ## Without Built in Pip Package -FROM yasirarism/misskaty-docker:free +# FROM yasirarism/misskaty-docker:free # Set Hostname ENV HOSTNAME=yasir-server # Copy Files COPY . . -# Instal pip package -RUN pip3 install --no-cache-dir -r requirements.txt +# Instal pip package if you use free depedencies +# RUN pip3 install --no-cache-dir -r requirements.txt # Set CMD Bot CMD ["bash", "start.sh"] From 18ab296eea2a92f9ea417d752a714eb567f57149 Mon Sep 17 00:00:00 2001 From: Yasir Aris M Date: Sat, 14 Sep 2024 12:57:05 +0700 Subject: [PATCH 24/24] Update dev.py --- misskaty/plugins/dev.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index 057af71fed..85ae71be2f 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -200,7 +200,7 @@ async def payment(client: Client, message: Message): 'unique_code': unique_id, 'service': service_id, 'amount': amount, - 'note': f'VIP Bot Subscription by YS Dev', + 'note': f'MissKaty Support by YS Dev', 'valid_time': valid_time, 'type_fee': '1', 'payment_guide': True,