This commit is contained in:
yasir 2022-12-02 21:31:25 +07:00
parent 6580c27a61
commit 82728f2cea
26 changed files with 806 additions and 245 deletions

View file

@ -9,7 +9,7 @@ This repo has many bugs and i dont have time to fix it. If you can help me, plea
You can check demo this repo in this bot [MissKatyPyro](https://t.me/MissKatyRoBot) You can check demo this repo in this bot [MissKatyPyro](https://t.me/MissKatyRoBot)
## Features ## Features
I'm forget about it, try asking doraemon maybe know.. :) Check by yourself.. :)
## Variables ## Variables

View file

@ -1,32 +0,0 @@
[loggers]
keys=root
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=consoleFormatter,fileFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=ERROR
formatter=fileFormatter
args=('MissKatyLogs.txt','w',)
[formatter_consoleFormatter]
format=%(asctime)s - %(lineno)d - %(name)s - %(module)s - %(levelname)s - %(message)s
datefmt=%I:%M:%S %p
[formatter_fileFormatter]
format=[%(asctime)s:%(name)s:%(lineno)d:%(levelname)s] %(message)s
datefmt=%m/%d/%Y %I:%M:%S %p

View file

@ -1,18 +1,18 @@
import logging from logging import basicConfig, FileHandler, StreamHandler, getLogger
import time import time
import logging.config
# Get logging
logging.config.fileConfig("logging.conf")
logging.getLogger().setLevel(logging.INFO)
logging.getLogger("pyrogram").setLevel(logging.ERROR)
from pyrogram import Client from pyrogram import Client
from misskaty.vars import API_ID, API_HASH, BOT_TOKEN, USER_SESSION from misskaty.vars import API_ID, API_HASH, BOT_TOKEN, USER_SESSION
basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[FileHandler("MissKatyLogs.txt"), StreamHandler()],
level=INFO,
)
MOD_LOAD = [] MOD_LOAD = []
MOD_NOLOAD = [] MOD_NOLOAD = []
HELPABLE = {} HELPABLE = {}
LOGGER = getLogger(__name__)
botStartTime = time.time() botStartTime = time.time()
# Pyrogram Bot Client # Pyrogram Bot Client

View file

@ -5,15 +5,14 @@
* @projectName MissKatyPyro * @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved * Copyright @YasirPedia All rights reserved
""" """
import asyncio, importlib, re, logging import asyncio, importlib, re
from misskaty import app, user, HELPABLE from misskaty import app, user, HELPABLE, LOGGER
from misskaty.plugins import ALL_MODULES from misskaty.plugins import ALL_MODULES
from misskaty.helper import paginate_modules from misskaty.helper import paginate_modules
from misskaty.helper.tools import bot_sys_stats from misskaty.helper.tools import bot_sys_stats
from database.users_chats_db import db from database.users_chats_db import db
from misskaty.vars import LOG_CHANNEL from misskaty.vars import LOG_CHANNEL
from utils import temp from utils import temp
from logging import info as log_info
from pyrogram.raw.all import layer from pyrogram.raw.all import layer
from pyrogram import idle, __version__, filters from pyrogram import idle, __version__, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@ -44,15 +43,15 @@ async def start_bot():
await user.start() await user.start()
me = await app.get_me() me = await app.get_me()
ubot = await user.get_me() ubot = await user.get_me()
log_info("+===============================================================+") LOGGER.info("+===============================================================+")
log_info("| MissKatyPyro |") LOGGER.info("| MissKatyPyro |")
log_info("+===============+===============+===============+===============+") LOGGER.info("+===============+===============+===============+===============+")
log_info(bot_modules) LOGGER.info(bot_modules)
log_info("+===============+===============+===============+===============+") LOGGER.info("+===============+===============+===============+===============+")
log_info(f"[INFO]: BOT STARTED AS @{me.username}!") LOGGER.info(f"[INFO]: BOT STARTED AS @{me.username}!")
try: try:
log_info("[INFO]: SENDING ONLINE STATUS") LOGGER.info("[INFO]: SENDING ONLINE STATUS")
await app.send_message( await app.send_message(
617426792, 617426792,
f"USERBOT AND BOT STARTED with Pyrogram v{__version__}..\nUserBot: {ubot.first_name}\nBot: {me.first_name}\n\nwith Pyrogram v{__version__} (Layer {layer}) started on @{me.username}.", f"USERBOT AND BOT STARTED with Pyrogram v{__version__}..\nUserBot: {ubot.first_name}\nBot: {me.first_name}\n\nwith Pyrogram v{__version__} (Layer {layer}) started on @{me.username}.",
@ -63,7 +62,7 @@ async def start_bot():
await idle() await idle()
await app.stop() await app.stop()
await user.stop() await user.stop()
print("[INFO]: Bye!") LOGGER.info("[INFO]: Bye!")
home_keyboard_pm = InlineKeyboardMarkup( home_keyboard_pm = InlineKeyboardMarkup(
@ -339,4 +338,4 @@ if __name__ == "__main__":
try: try:
loop.run_until_complete(start_bot()) loop.run_until_complete(start_bot())
except KeyboardInterrupt: except KeyboardInterrupt:
logging.info("----------------------- Service Stopped -----------------------") LOGGER.info("----------------------- Service Stopped -----------------------")

View file

@ -8,9 +8,8 @@
import glob import glob
import importlib import importlib
import sys import sys
from logging import info as log_info
from os.path import basename, dirname, isfile from os.path import basename, dirname, isfile
from misskaty import MOD_LOAD, MOD_NOLOAD from misskaty import MOD_LOAD, MOD_NOLOAD, LOGGER
def __list_all_modules(): def __list_all_modules():
@ -18,8 +17,12 @@ def __list_all_modules():
# folder for the * in __main__ to work. # folder for the * in __main__ to work.
mod_paths = glob.glob(f"{dirname(__file__)}/*.py") mod_paths = glob.glob(f"{dirname(__file__)}/*.py")
all_modules = [ all_modules = [
basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") basename(f)[:-3]
and not f.endswith("__init__.py") and not f.endswith("__main__.py") for f in mod_paths
if isfile(f)
and f.endswith(".py")
and not f.endswith("__init__.py")
and not f.endswith("__main__.py")
] ]
if MOD_LOAD or MOD_NOLOAD: if MOD_LOAD or MOD_NOLOAD:
@ -27,19 +30,23 @@ def __list_all_modules():
if to_load: if to_load:
if not all( if not all(
any(mod == module_name for module_name in all_modules) any(mod == module_name for module_name in all_modules)
for mod in to_load): for mod in to_load
):
sys.exit() sys.exit()
else: else:
to_load = all_modules to_load = all_modules
return [item for item in to_load return (
if item not in MOD_NOLOAD] if MOD_NOLOAD else to_load [item for item in to_load if item not in MOD_NOLOAD]
if MOD_NOLOAD
else to_load
)
return all_modules return all_modules
log_info("[INFO]: IMPORTING PLUGINS") LOGGER.info("[INFO]: IMPORTING PLUGINS")
importlib.import_module("misskaty.plugins.__main__") importlib.import_module("misskaty.plugins.__main__")
ALL_MODULES = sorted(__list_all_modules()) ALL_MODULES = sorted(__list_all_modules())
__all__ = ALL_MODULES + ["ALL_MODULES"] __all__ = ALL_MODULES + ["ALL_MODULES"]

View file

@ -1,4 +1,3 @@
import logging
import asyncio, re import asyncio, re
from misskaty import app from misskaty import app
from misskaty.helper.functions import ( from misskaty.helper.functions import (
@ -64,7 +63,7 @@ async def admin_cache_func(_, cmu):
) )
], ],
} }
logging.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]") LOGGER.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]")
# Purge CMD # Purge CMD

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from misskaty import app from misskaty import app
from pyrogram import filters from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@ -9,7 +16,18 @@ from misskaty.core.decorator.errors import capture_err
@app.on_chat_join_request(filters.chat(-1001686184174)) @app.on_chat_join_request(filters.chat(-1001686184174))
async def approve_join_chat(c, m): async def approve_join_chat(c, m):
try: try:
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="Sudah", callback_data=f"approve_{m.chat.id}"), InlineKeyboardButton(text="Belum", callback_data=f"declined_{m.chat.id}")]]) markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="Sudah", callback_data=f"approve_{m.chat.id}"
),
InlineKeyboardButton(
text="Belum", callback_data=f"declined_{m.chat.id}"
),
]
]
)
await c.send_message( await c.send_message(
m.from_user.id, m.from_user.id,
"<b>PERMINTAAN JOIN CHANNEL YMOVIEZ REBORN</b>\n\nSebelum masuk ke channel ada tes kejujuran, apakah anda sudah membaca catatan di @YMovieZ_New? Jika sudah silahkan klik <b>Sudah</b>, jika kamu berbohong resiko kamu tanggung sendiri 😶‍🌫️.\n\nBot by @YasirPediaChannel", "<b>PERMINTAAN JOIN CHANNEL YMOVIEZ REBORN</b>\n\nSebelum masuk ke channel ada tes kejujuran, apakah anda sudah membaca catatan di @YMovieZ_New? Jika sudah silahkan klik <b>Sudah</b>, jika kamu berbohong resiko kamu tanggung sendiri 😶‍🌫️.\n\nBot by @YasirPediaChannel",
@ -24,10 +42,14 @@ async def approve_join_chat(c, m):
async def approve_chat(c, q): async def approve_chat(c, q):
i, chat = q.data.split("_") i, chat = q.data.split("_")
try: try:
await q.message.edit("Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn...") await q.message.edit(
"Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn..."
)
await c.approve_chat_join_request(chat, q.from_user.id) await c.approve_chat_join_request(chat, q.from_user.id)
except UserAlreadyParticipant: except UserAlreadyParticipant:
await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.") await q.message.edit(
"Kamu sudah di acc join grup, jadi ga perlu menekan button."
)
except Exception as err: except Exception as err:
await q.message.edit(err) await q.message.edit(err)
@ -36,9 +58,13 @@ async def approve_chat(c, q):
async def decline_chat(c, q): async def decline_chat(c, q):
i, chat = q.data.split("_") i, chat = q.data.split("_")
try: try:
await q.message.edit("Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh..") await q.message.edit(
"Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh.."
)
await c.decline_chat_join_request(chat, q.from_user.id) await c.decline_chat_join_request(chat, q.from_user.id)
except UserAlreadyParticipant: except UserAlreadyParticipant:
await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.") await q.message.edit(
"Kamu sudah di acc join grup, jadi ga perlu menekan button."
)
except Exception as err: except Exception as err:
await q.message.edit(err) await q.message.edit(err)

View file

@ -1,6 +1,5 @@
# Code copy from https://github.com/AbirHasan2005/Forward-Client # Code copy from https://github.com/AbirHasan2005/Forward-Client
import logging from misskaty import user, LOGGER
from misskaty import user
from pyrogram import filters from pyrogram import filters
from asyncio import sleep from asyncio import sleep
from pyrogram.types import Message from pyrogram.types import Message
@ -76,14 +75,14 @@ async def ForwardMessage(client: user, msg: Message):
await msg.copy(FORWARD_TO_CHAT_ID[i]) await msg.copy(FORWARD_TO_CHAT_ID[i])
except FloodWait as e: except FloodWait as e:
await sleep(e.value) await sleep(e.value)
logging.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!") LOGGER.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!")
await ForwardMessage(client, msg) await ForwardMessage(client, msg)
except Exception as err: except Exception as err:
logging.warning( LOGGER.warning(
f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: <code>{err}</code>" f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: <code>{err}</code>"
) )
except Exception as err: except Exception as err:
logging.warning(f"#ERROR: {err}") LOGGER.warning(f"#ERROR: {err}")
@user.on_message((filters.text | filters.media) & filters.chat(FORWARD_FROM_CHAT_ID)) @user.on_message((filters.text | filters.media) & filters.chat(FORWARD_FROM_CHAT_ID))

View file

@ -8,7 +8,9 @@ from misskaty import app
async def banned_users(_, client, message: Message): async def banned_users(_, client, message: Message):
return (message.from_user is not None or not message.sender_chat) and message.from_user.id in temp.BANNED_USERS return (
message.from_user is not None or not message.sender_chat
) and message.from_user.id in temp.BANNED_USERS
banned_user = filters.create(banned_users) banned_user = filters.create(banned_users)
@ -24,7 +26,9 @@ disabled_group = filters.create(disabled_chat)
@app.on_message(filters.private & banned_user & filters.incoming) @app.on_message(filters.private & banned_user & filters.incoming)
async def ban_reply(bot, message): async def ban_reply(bot, message):
ban = await db.get_ban_status(message.from_user.id) ban = await db.get_ban_status(message.from_user.id)
await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}') await message.reply(
f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}'
)
@app.on_message(filters.group & disabled_group & filters.incoming) @app.on_message(filters.group & disabled_group & filters.incoming)
@ -32,7 +36,10 @@ async def grp_bd(bot, message):
buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]] buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
vazha = await db.get_chat(message.chat.id) vazha = await db.get_chat(message.chat.id)
k = await message.reply(text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : <code>{vazha['reason']}</code>.", reply_markup=reply_markup) k = await message.reply(
text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : <code>{vazha['reason']}</code>.",
reply_markup=reply_markup,
)
try: try:
await k.pin() await k.pin()
except: except:

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import re import re
from misskaty.helper.http import http from misskaty.helper.http import http
from misskaty import app from misskaty import app

View file

@ -12,10 +12,25 @@ async def copy(client, message):
if not message.reply_to_message: if not message.reply_to_message:
return await message.reply("Silahkan balas pesan yang mau dicopy.") return await message.reply("Silahkan balas pesan yang mau dicopy.")
try: try:
await message.reply_to_message.copy(message.from_user.id, caption_entities=message.reply_to_message.entities, reply_markup=message.reply_to_message.reply_markup) await message.reply_to_message.copy(
message.from_user.id,
caption_entities=message.reply_to_message.entities,
reply_markup=message.reply_to_message.reply_markup,
)
return await message.reply_text("Pesan berhasil dikirim..") return await message.reply_text("Pesan berhasil dikirim..")
except UserIsBlocked: except UserIsBlocked:
return await message.reply("Silahkan PM Saya untuk mengcopy pesan ke chat pribadi..", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="💬 Chat Aku Yahh", url="https://t.me/MissKatyRoBot")]])) return await message.reply(
"Silahkan PM Saya untuk mengcopy pesan ke chat pribadi..",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="💬 Chat Aku Yahh", url="https://t.me/MissKatyRoBot"
)
]
]
),
)
except Exception as e: except Exception as e:
return await message.reply(f"ERROR: {str(e)}") return await message.reply(f"ERROR: {str(e)}")
elif message.reply_to_message: elif message.reply_to_message:
@ -31,7 +46,11 @@ async def copy(client, message):
and message.from_user.id != 2024984460 and message.from_user.id != 2024984460
): ):
return await message.reply_text("🦉🦉🦉") return await message.reply_text("🦉🦉🦉")
await message.reply_to_message.copy(idtujuan, caption_entities=message.reply_to_message.entities, reply_markup=message.reply_to_message.reply_markup) await message.reply_to_message.copy(
idtujuan,
caption_entities=message.reply_to_message.entities,
reply_markup=message.reply_to_message.reply_markup,
)
return await message.reply_text("Pesan berhasil dikirim..") return await message.reply_text("Pesan berhasil dikirim..")
except UserNotParticipant: except UserNotParticipant:
return await message.reply("Command ini hanya untuk admin YMoviezNew") return await message.reply("Command ini hanya untuk admin YMoviezNew")
@ -51,7 +70,18 @@ async def forward(client, message):
await message.reply_to_message.forward(message.from_user.id) await message.reply_to_message.forward(message.from_user.id)
return await message.reply_text("Pesan berhasil dikirim..") return await message.reply_text("Pesan berhasil dikirim..")
except UserIsBlocked: except UserIsBlocked:
return await message.reply("Silahkan PM Saya untuk memforward pesan ke chat pribadi..", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="💬 Chat Aku Yahh", url="https://t.me/MissKatyRoBot")]])) return await message.reply(
"Silahkan PM Saya untuk memforward pesan ke chat pribadi..",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="💬 Chat Aku Yahh", url="https://t.me/MissKatyRoBot"
)
]
]
),
)
except Exception as e: except Exception as e:
return await message.reply(f"ERROR: {str(e)}") return await message.reply(f"ERROR: {str(e)}")
elif message.reply_to_message: elif message.reply_to_message:

View file

@ -2,12 +2,11 @@ import time
import asyncio import asyncio
import math import math
import os import os
import logging
import aiohttp import aiohttp
import json import json
from misskaty.helper.http import http from misskaty.helper.http import http
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from misskaty import app from misskaty import app, LOGGER
from pySmartDL import SmartDL from pySmartDL import SmartDL
from datetime import datetime from datetime import datetime
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
@ -130,7 +129,7 @@ async def download(client, message):
display_message = current_message display_message = current_message
await asyncio.sleep(10) await asyncio.sleep(10)
except Exception as e: except Exception as e:
logging.info(str(e)) LOGGER.info(str(e))
if os.path.exists(download_file_path): if os.path.exists(download_file_path):
end_t = datetime.now() end_t = datetime.now()
ms = (end_t - start_t).seconds ms = (end_t - start_t).seconds

View file

@ -17,20 +17,50 @@ async def start(_, message):
await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇") await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇")
@app.on_message(filters.regex(r"#request|#req", re.I) & (filters.text | filters.photo) & filters.chat(-1001255283935) & ~filters.channel) @app.on_message(
filters.regex(r"#request|#req", re.I)
& (filters.text | filters.photo)
& filters.chat(-1001255283935)
& ~filters.channel
)
@capture_err @capture_err
async def request_user(client, message): async def request_user(client, message):
if message.sender_chat: if message.sender_chat:
return await message.reply(f"{message.from_user.mention} mohon gunakan akun asli saat request.") return await message.reply(
f"{message.from_user.mention} mohon gunakan akun asli saat request."
)
is_in_gap, sleep_time = await check_time_gap(message.from_user.id) is_in_gap, sleep_time = await check_time_gap(message.from_user.id)
if is_in_gap: if is_in_gap:
return await message.reply("Sabar dikit napa.. 🙄") return await message.reply("Sabar dikit napa.. 🙄")
markup = InlineKeyboardMarkup( markup = InlineKeyboardMarkup(
[ [
[InlineKeyboardButton(text="💬 Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}")], [
[InlineKeyboardButton(text="🚫 Tolak", callback_data=f"rejectreq_{message.id}_{message.chat.id}"), InlineKeyboardButton(text="✅ Done", callback_data=f"donereq_{message.id}_{message.chat.id}")], InlineKeyboardButton(
[InlineKeyboardButton(text="⚠️ Tidak Tersedia", callback_data=f"unavailablereq_{message.id}_{message.chat.id}")], text="💬 Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}"
[InlineKeyboardButton(text="🔍 Sudah Ada", callback_data=f"dahada_{message.id}_{message.chat.id}")], )
],
[
InlineKeyboardButton(
text="🚫 Tolak",
callback_data=f"rejectreq_{message.id}_{message.chat.id}",
),
InlineKeyboardButton(
text="✅ Done",
callback_data=f"donereq_{message.id}_{message.chat.id}",
),
],
[
InlineKeyboardButton(
text="⚠️ Tidak Tersedia",
callback_data=f"unavailablereq_{message.id}_{message.chat.id}",
)
],
[
InlineKeyboardButton(
text="🔍 Sudah Ada",
callback_data=f"dahada_{message.id}_{message.chat.id}",
)
],
] ]
) )
try: try:
@ -40,16 +70,47 @@ async def request_user(client, message):
else: else:
REQUEST_DB[user_id] = 1 REQUEST_DB[user_id] = 1
if REQUEST_DB[user_id] > 3: if REQUEST_DB[user_id] > 3:
return await message.reply(f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝.") return await message.reply(
f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝."
)
if message.text: if message.text:
forward = await client.send_message(-1001575525902, f"Request by <a href='tg://user?id={message.from_user.id}'>{message.from_user.first_name}</a> (#id{message.from_user.id})\n\n{message.text}", reply_markup=markup) forward = await client.send_message(
markup2 = InlineKeyboardMarkup([[InlineKeyboardButton(text="⏳ Cek Status Request", url=f"https://t.me/c/1575525902/{forward.id}")]]) -1001575525902,
f"Request by <a href='tg://user?id={message.from_user.id}'>{message.from_user.first_name}</a> (#id{message.from_user.id})\n\n{message.text}",
reply_markup=markup,
)
markup2 = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="⏳ Cek Status Request",
url=f"https://t.me/c/1575525902/{forward.id}",
)
]
]
)
if message.photo: if message.photo:
forward = await client.send_photo( forward = await client.send_photo(
-1001575525902, message.photo.file_id, caption=f"Request by <a href='tg://user?id={message.from_user.id}'>{message.from_user.first_name}</a> (#id{message.from_user.id})\n\n{message.caption}", reply_markup=markup -1001575525902,
message.photo.file_id,
caption=f"Request by <a href='tg://user?id={message.from_user.id}'>{message.from_user.first_name}</a> (#id{message.from_user.id})\n\n{message.caption}",
reply_markup=markup,
)
markup2 = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="⏳ Cek Status Request",
url=f"https://t.me/c/1575525902/{forward.id}",
)
]
]
)
await message.reply_text(
text=f"Hai {message.from_user.mention}, request kamu sudah dikirim yaa. Harap bersabar mungkin admin juga punya kesibukan lain.\n\n<b>Sisa Request:</b> {3 - REQUEST_DB[user_id]}x",
quote=True,
reply_markup=markup2,
) )
markup2 = InlineKeyboardMarkup([[InlineKeyboardButton(text="⏳ Cek Status Request", url=f"https://t.me/c/1575525902/{forward.id}")]])
await message.reply_text(text=f"Hai {message.from_user.mention}, request kamu sudah dikirim yaa. Harap bersabar mungkin admin juga punya kesibukan lain.\n\n<b>Sisa Request:</b> {3 - REQUEST_DB[user_id]}x", quote=True, reply_markup=markup2)
except: except:
pass pass
@ -78,7 +139,10 @@ async def start(_, message):
async def _callbackreq(c, q): async def _callbackreq(c, q):
try: try:
user = await c.get_chat_member(-1001201566570, q.from_user.id) user = await c.get_chat_member(-1001201566570, q.from_user.id)
if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: if user.status in [
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
]:
i, msg_id, chat_id = q.data.split("_") i, msg_id, chat_id = q.data.split("_")
await c.send_message( await c.send_message(
chat_id=chat_id, chat_id=chat_id,
@ -87,23 +151,54 @@ async def _callbackreq(c, q):
) )
if q.message.caption: if q.message.caption:
await q.message.edit_text(f"<b>COMPLETED</b>\n\n<s>{q.message.caption}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]])) await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
)
else: else:
await q.message.edit_text(f"<b>COMPLETED</b>\n\n<s>{q.message.text}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]])) await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
)
await q.answer("Request berhasil diselesaikan ✅") await q.answer("Request berhasil diselesaikan ✅")
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) return await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
show_alert=True,
cache_time=10,
)
@app.on_callback_query(filters.regex(r"^dahada")) @app.on_callback_query(filters.regex(r"^dahada"))
async def _callbackreqada(c, q): async def _callbackreqada(c, q):
try: try:
user = await c.get_chat_member(-1001201566570, q.from_user.id) user = await c.get_chat_member(-1001201566570, q.from_user.id)
if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: if user.status in [
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
]:
i, msg_id, chat_id = q.data.split("_") i, msg_id, chat_id = q.data.split("_")
await c.send_message( await c.send_message(
chat_id=chat_id, chat_id=chat_id,
@ -112,23 +207,56 @@ async def _callbackreqada(c, q):
) )
if q.message.caption: if q.message.caption:
await q.message.edit_text(f"<b>#AlreadyAvailable</b>\n\n<s>{q.message.caption}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🔍 Request Sudah Ada", callback_data="reqavailable")]])) await q.message.edit_text(
f"<b>#AlreadyAvailable</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🔍 Request Sudah Ada",
callback_data="reqavailable",
)
]
]
),
)
else: else:
await q.message.edit_text(f"<b>Already Available</b>\n\n<s>{q.message.text}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🔍 Request Sudah Ada", callback_data="reqavailable")]])) await q.message.edit_text(
f"<b>Already Available</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🔍 Request Sudah Ada",
callback_data="reqavailable",
)
]
]
),
)
await q.answer("Done ✔️") await q.answer("Done ✔️")
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) return await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
show_alert=True,
cache_time=10,
)
@app.on_callback_query(filters.regex(r"^rejectreq")) @app.on_callback_query(filters.regex(r"^rejectreq"))
async def _callbackreject(c, q): async def _callbackreject(c, q):
try: try:
user = await c.get_chat_member(-1001201566570, q.from_user.id) user = await c.get_chat_member(-1001201566570, q.from_user.id)
if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: if user.status in [
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
]:
i, msg_id, chat_id = q.data.split("_") i, msg_id, chat_id = q.data.split("_")
await c.send_message( await c.send_message(
chat_id=chat_id, chat_id=chat_id,
@ -137,23 +265,54 @@ async def _callbackreject(c, q):
) )
if q.message.caption: if q.message.caption:
await q.message.edit_text(f"<b>REJECTED</b>\n\n<s>{q.message.caption}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]])) await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
)
else: else:
await q.message.edit_text(f"<b>REJECTED</b>\n\n<s>{q.message.text}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]])) await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
)
await q.answer("Request berhasil ditolak 🚫") await q.answer("Request berhasil ditolak 🚫")
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
show_alert=True,
cache_time=10,
)
@app.on_callback_query(filters.regex(r"^unavailablereq")) @app.on_callback_query(filters.regex(r"^unavailablereq"))
async def _callbackunav(c, q): async def _callbackunav(c, q):
try: try:
user = await c.get_chat_member(-1001201566570, q.from_user.id) user = await c.get_chat_member(-1001201566570, q.from_user.id)
if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: if user.status in [
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
]:
i, msg_id, chat_id = q.data.split("_") i, msg_id, chat_id = q.data.split("_")
await c.send_message( await c.send_message(
chat_id=chat_id, chat_id=chat_id,
@ -162,36 +321,86 @@ async def _callbackunav(c, q):
) )
if q.message.caption: if q.message.caption:
await q.message.edit_text(f"<b>UNAVAILABLE</b>\n\n<s>{q.message.caption}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="⚠️ Request Unavailable", callback_data="requnav")]])) await q.message.edit_text(
f"<b>UNAVAILABLE</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="⚠️ Request Unavailable",
callback_data="requnav",
)
]
]
),
)
else: else:
await q.message.edit_text(f"<b>UNAVAILABLE</b>\n\n<s>{q.message.text}</s>", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="⚠️ Request Unavailable", callback_data="requnav")]])) await q.message.edit_text(
await q.answer("Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital.") f"<b>UNAVAILABLE</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="⚠️ Request Unavailable",
callback_data="requnav",
)
]
]
),
)
await q.answer(
"Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital."
)
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=1000) await q.answer(
"Apa motivasi kamu menekan tombol ini?",
show_alert=True,
cache_time=1000,
)
except UserNotParticipant: except UserNotParticipant:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
show_alert=True,
cache_time=10,
)
@app.on_callback_query(filters.regex(r"^reqcompl$")) @app.on_callback_query(filters.regex(r"^reqcompl$"))
async def _callbackaft_done(c, q): async def _callbackaft_done(c, q):
await q.answer("Request ini sudah terselesaikan 🥳, silahkan cek di channel atau grup yaa..", show_alert=True, cache_time=1000) await q.answer(
"Request ini sudah terselesaikan 🥳, silahkan cek di channel atau grup yaa..",
show_alert=True,
cache_time=1000,
)
@app.on_callback_query(filters.regex(r"^reqreject$")) @app.on_callback_query(filters.regex(r"^reqreject$"))
async def _callbackaft_rej(c, q): async def _callbackaft_rej(c, q):
await q.answer("Request ini ditolak 💔, silahkan cek rules grup yaa.", show_alert=True, cache_time=1000) await q.answer(
"Request ini ditolak 💔, silahkan cek rules grup yaa.",
show_alert=True,
cache_time=1000,
)
@app.on_callback_query(filters.regex(r"^requnav$")) @app.on_callback_query(filters.regex(r"^requnav$"))
async def _callbackaft_unav(c, q): async def _callbackaft_unav(c, q):
await q.answer("Request ini tidak tersedia ☹️, mungkin filmnya belum rilis atau memang tidak tersedia versi digital.", show_alert=True, cache_time=1000) await q.answer(
"Request ini tidak tersedia ☹️, mungkin filmnya belum rilis atau memang tidak tersedia versi digital.",
show_alert=True,
cache_time=1000,
)
@app.on_callback_query(filters.regex(r"^reqavailable$")) @app.on_callback_query(filters.regex(r"^reqavailable$"))
async def _callbackaft_dahada(c, q): async def _callbackaft_dahada(c, q):
await q.answer("Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True) await q.answer(
"Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True
)
scheduler = AsyncIOScheduler(timezone="Asia/Jakarta") scheduler = AsyncIOScheduler(timezone="Asia/Jakarta")

View file

@ -1,17 +1,16 @@
# the logging things """
import logging * @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
logging.basicConfig( * @lastModified 2022-12-01 09:32:31
level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" * @projectName MissKatyPyro
) * Copyright @YasirPedia All rights reserved
logger = logging.getLogger(__name__) """
import os, time, traceback import os, time, traceback
from asyncio import sleep, gather from asyncio import sleep, gather
from shutil import rmtree from shutil import rmtree
from pyrogram import filters, enums from pyrogram import filters, enums
from pyrogram.errors import FloodWait from pyrogram.errors import FloodWait
from misskaty import app from misskaty import app, LOGGER
from misskaty.helper.ffmpeg_helper import take_ss, genss_link from misskaty.helper.ffmpeg_helper import take_ss, genss_link
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from misskaty.helper.pyro_progress import progress_for_pyrogram from misskaty.helper.pyro_progress import progress_for_pyrogram

View file

@ -1,12 +1,11 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
import time import time
import os import os
import logging
from misskaty.helper.http import http from misskaty.helper.http import http
from pyrogram import enums, filters from pyrogram import enums, filters
from pyrogram.types import ChatMemberUpdated, InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import ChatMemberUpdated, InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.errors import ChatSendMediaForbidden, MessageTooLong, RPCError, SlowmodeWait from pyrogram.errors import ChatSendMediaForbidden, MessageTooLong, RPCError, SlowmodeWait
from misskaty import app from misskaty import app, LOGGER
from misskaty.core.decorator.errors import capture_err, asyncify from misskaty.core.decorator.errors import capture_err, asyncify
from PIL import Image, ImageChops, ImageDraw, ImageFont from PIL import Image, ImageChops, ImageDraw, ImageFont
import textwrap import textwrap
@ -15,9 +14,6 @@ from utils import temp
from pyrogram.errors import ChatAdminRequired from pyrogram.errors import ChatAdminRequired
from misskaty.vars import SUDO, LOG_CHANNEL, SUPPORT_CHAT, COMMAND_HANDLER from misskaty.vars import SUDO, LOG_CHANNEL, SUPPORT_CHAT, COMMAND_HANDLER
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
LOGGER = logging.getLogger(__name__)
def circle(pfp, size=(215, 215)): def circle(pfp, size=(215, 215)):
pfp = pfp.resize(size, Image.ANTIALIAS).convert("RGBA") pfp = pfp.resize(size, Image.ANTIALIAS).convert("RGBA")

View file

@ -1,3 +1,11 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import os import os
from pyrogram import filters from pyrogram import filters
from misskaty import app from misskaty import app

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import io import io
from os import remove as osremove from os import remove as osremove
import time import time
@ -14,11 +21,15 @@ from misskaty.helper.pyro_progress import (
) )
@app.on_message(filters.command(["mediainfo", "mediainfo@MissKatyRoBot"], COMMAND_HANDLER)) @app.on_message(
filters.command(["mediainfo", "mediainfo@MissKatyRoBot"], COMMAND_HANDLER)
)
@capture_err @capture_err
async def mediainfo(client, message): async def mediainfo(client, message):
if message.reply_to_message and message.reply_to_message.media: if message.reply_to_message and message.reply_to_message.media:
process = await message.reply_text("`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True) process = await message.reply_text(
"`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True
)
file_info = get_file_id(message.reply_to_message) file_info = get_file_id(message.reply_to_message)
if file_info is None: if file_info is None:
await process.edit_text("Balas ke format media yang valid") await process.edit_text("Balas ke format media yang valid")
@ -54,14 +65,22 @@ async def mediainfo(client, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
if link.startswith("https://file.yasirweb.my.id"): if link.startswith("https://file.yasirweb.my.id"):
link = link.replace("https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev") link = link.replace(
"https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev"
)
if link.startswith("https://link.yasirweb.my.id"): if link.startswith("https://link.yasirweb.my.id"):
link = link.replace("https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com") link = link.replace(
"https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com"
)
process = await message.reply_text("`Mohon tunggu sejenak...`") process = await message.reply_text("`Mohon tunggu sejenak...`")
try: try:
output = subprocess.check_output(["mediainfo", f"{link}"]).decode("utf-8") output = subprocess.check_output(["mediainfo", f"{link}"]).decode(
"utf-8"
)
except Exception: except Exception:
return await process.edit("Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download.") return await process.edit(
"Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download."
)
title = "MissKaty Bot Mediainfo" title = "MissKaty Bot Mediainfo"
body_text = f""" body_text = f"""
<img src='https://telegra.ph/file/72c99bbc89bbe4e178cc9.jpg' /> <img src='https://telegra.ph/file/72c99bbc89bbe4e178cc9.jpg' />
@ -72,10 +91,18 @@ async def mediainfo(client, message):
# response = await http.post(siteurl, data={"content": output, "extension": 'txt'} ) # response = await http.post(siteurl, data={"content": output, "extension": 'txt'} )
# response = response.json() # response = response.json()
# spacebin = "https://spaceb.in/"+response['payload']['id'] # spacebin = "https://spaceb.in/"+response['payload']['id']
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="💬 Telegraph", url=tgraph)]]) markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="💬 Telegraph", url=tgraph)]]
)
with io.BytesIO(str.encode(output)) as out_file: with io.BytesIO(str.encode(output)) as out_file:
out_file.name = "MissKaty_Mediainfo.txt" out_file.name = "MissKaty_Mediainfo.txt"
await message.reply_document(out_file, caption=f"Hasil mediainfo anda..\n\n<b>Request by:</b> {message.from_user.mention}", reply_markup=markup) await message.reply_document(
out_file,
caption=f"Hasil mediainfo anda..\n\n<b>Request by:</b> {message.from_user.mention}",
reply_markup=markup,
)
await process.delete() await process.delete()
except IndexError: except IndexError:
return await message.reply_text("Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo.") return await message.reply_text(
"Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo."
)

View file

@ -6,7 +6,14 @@ import traceback
from pyrogram import Client, filters from pyrogram import Client, filters
from deep_translator import GoogleTranslator from deep_translator import GoogleTranslator
from gtts import gTTS from gtts import gTTS
from pyrogram.errors import MediaEmpty, MessageNotModified, PhotoInvalidDimensions, UserNotParticipant, WebpageMediaEmpty, MessageTooLong from pyrogram.errors import (
MediaEmpty,
MessageNotModified,
PhotoInvalidDimensions,
UserNotParticipant,
WebpageMediaEmpty,
MessageTooLong,
)
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from utils import extract_user, get_file_id, demoji from utils import extract_user, get_file_id, demoji
import time import time
@ -16,11 +23,7 @@ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQ
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
from misskaty.helper.tools import rentry, GENRES_EMOJI from misskaty.helper.tools import rentry, GENRES_EMOJI
from misskaty.helper.http import http from misskaty.helper.http import http
from misskaty import app from misskaty import app, LOGGER
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
__MODULE__ = "Misc" __MODULE__ = "Misc"
__HELP__ = """ __HELP__ = """
@ -46,12 +49,20 @@ def remove_html_tags(text):
async def stackoverflow(client, message): async def stackoverflow(client, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply("Give a query to search in StackOverflow!") return await message.reply("Give a query to search in StackOverflow!")
r = (await http.get(f"https://api.stackexchange.com/2.3/search/excerpts?order=asc&sort=relevance&q={message.command[1]}&accepted=True&migrated=False¬ice=False&wiki=False&site=stackoverflow")).json() r = (
await http.get(
f"https://api.stackexchange.com/2.3/search/excerpts?order=asc&sort=relevance&q={message.command[1]}&accepted=True&migrated=False¬ice=False&wiki=False&site=stackoverflow"
)
).json()
hasil = "" hasil = ""
for count, data in enumerate(r["items"], start=1): for count, data in enumerate(r["items"], start=1):
question = data["question_id"] question = data["question_id"]
title = data["title"] title = data["title"]
snippet = remove_html_tags(data["excerpt"])[:80].replace("\n", "").replace(" ", "") if len(remove_html_tags(data["excerpt"])) > 80 else remove_html_tags(data["excerpt"]).replace("\n", "").replace(" ", "") snippet = (
remove_html_tags(data["excerpt"])[:80].replace("\n", "").replace(" ", "")
if len(remove_html_tags(data["excerpt"])) > 80
else remove_html_tags(data["excerpt"]).replace("\n", "").replace(" ", "")
)
hasil += f"{count}. <a href='https://stackoverflow.com/questions/{question}'>{title}</a>\n<code>{snippet}</code>\n" hasil += f"{count}. <a href='https://stackoverflow.com/questions/{question}'>{title}</a>\n<code>{snippet}</code>\n"
try: try:
await message.reply(hasil) await message.reply(hasil)
@ -70,8 +81,14 @@ async def gsearch(client, message):
query = message.text.split(" ", maxsplit=1)[1] query = message.text.split(" ", maxsplit=1)[1]
msg = await message.reply_text(f"**Googling** for `{query}` ...") msg = await message.reply_text(f"**Googling** for `{query}` ...")
try: try:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/61.0.3163.100 Safari/537.36"} headers = {
html = await http.get(f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17", headers=headers) "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.100 Safari/537.36"
}
html = await http.get(
f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17",
headers=headers,
)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
# collect data # collect data
@ -96,17 +113,24 @@ async def gsearch(client, message):
arr = json.dumps(data, indent=2, ensure_ascii=False) arr = json.dumps(data, indent=2, ensure_ascii=False)
parse = json.loads(arr) parse = json.loads(arr)
total = len(parse) total = len(parse)
res = "".join(f"<a href='{i['link']}'>{i['title']}</a>\n{i['snippet']}\n\n" for i in parse) res = "".join(
f"<a href='{i['link']}'>{i['title']}</a>\n{i['snippet']}\n\n" for i in parse
)
except Exception: except Exception:
exc = traceback.format_exc() exc = traceback.format_exc()
return await msg.edit(exc) return await msg.edit(exc)
await msg.edit(text=f"<b>Ada {total} Hasil Pencarian dari {query}:</b>\n{res}<b>Scraped by @MissKatyRoBot</b>", disable_web_page_preview=True) await msg.edit(
text=f"<b>Ada {total} Hasil Pencarian dari {query}:</b>\n{res}<b>Scraped by @MissKatyRoBot</b>",
disable_web_page_preview=True,
)
@app.on_message(filters.command(["tr", "trans", "translate"], COMMAND_HANDLER)) @app.on_message(filters.command(["tr", "trans", "translate"], COMMAND_HANDLER))
@capture_err @capture_err
async def translate(client, message): async def translate(client, message):
if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption): if message.reply_to_message and (
message.reply_to_message.text or message.reply_to_message.caption
):
target_lang = "id" if len(message.command) == 1 else message.text.split()[1] target_lang = "id" if len(message.command) == 1 else message.text.split()[1]
text = message.reply_to_message.text or message.reply_to_message.caption text = message.reply_to_message.text or message.reply_to_message.caption
else: else:
@ -118,20 +142,28 @@ async def translate(client, message):
text = message.text.split(None, 2)[2] text = message.text.split(None, 2)[2]
msg = await message.reply("Menerjemahkan...") msg = await message.reply("Menerjemahkan...")
try: try:
tekstr = (await http.get(f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}")).json()["text"] tekstr = (
await http.get(
f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}"
)
).json()["text"]
except Exception as err: except Exception as err:
return await msg.edit(f"Error: <code>{str(err)}</code>") return await msg.edit(f"Error: <code>{str(err)}</code>")
try: try:
await msg.edit(f"<code>{tekstr}</code>") await msg.edit(f"<code>{tekstr}</code>")
except MessageTooLong: except MessageTooLong:
url = await rentry(tekstr.text) url = await rentry(tekstr.text)
await msg.edit(f"Your translated text pasted to rentry because has long text:\n{url}") await msg.edit(
f"Your translated text pasted to rentry because has long text:\n{url}"
)
@app.on_message(filters.command(["tts"], COMMAND_HANDLER)) @app.on_message(filters.command(["tts"], COMMAND_HANDLER))
@capture_err @capture_err
async def tts(_, message): async def tts(_, message):
if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption): if message.reply_to_message and (
message.reply_to_message.text or message.reply_to_message.caption
):
if len(message.text.split()) == 1: if len(message.text.split()) == 1:
target_lang = "id" target_lang = "id"
else: else:
@ -160,13 +192,18 @@ async def tts(_, message):
pass pass
@app.on_message(filters.command(["tosticker", "tosticker@MissKatyRoBot"], COMMAND_HANDLER)) @app.on_message(
filters.command(["tosticker", "tosticker@MissKatyRoBot"], COMMAND_HANDLER)
)
@capture_err @capture_err
async def tostick(client, message): async def tostick(client, message):
try: try:
if not message.reply_to_message or not message.reply_to_message.photo: if not message.reply_to_message or not message.reply_to_message.photo:
return await message.reply_text("Reply ke foto untuk mengubah ke sticker") return await message.reply_text("Reply ke foto untuk mengubah ke sticker")
sticker = await client.download_media(message.reply_to_message.photo.file_id, f"tostick_{message.from_user.id}.webp") sticker = await client.download_media(
message.reply_to_message.photo.file_id,
f"tostick_{message.from_user.id}.webp",
)
await message.reply_sticker(sticker) await message.reply_sticker(sticker)
os.remove(sticker) os.remove(sticker)
except Exception as e: except Exception as e:
@ -180,9 +217,16 @@ async def topho(client, message):
if not message.reply_to_message or not message.reply_to_message.sticker: if not message.reply_to_message or not message.reply_to_message.sticker:
return await message.reply_text("Reply ke sticker untuk mengubah ke foto") return await message.reply_text("Reply ke sticker untuk mengubah ke foto")
if message.reply_to_message.sticker.is_animated: if message.reply_to_message.sticker.is_animated:
return await message.reply_text("Ini sticker animasi, command ini hanya untuk sticker biasa.") return await message.reply_text(
photo = await client.download_media(message.reply_to_message.sticker.file_id, f"tostick_{message.from_user.id}.jpg") "Ini sticker animasi, command ini hanya untuk sticker biasa."
await message.reply_photo(photo=photo, caption="Sticker -> Image\n@MissKatyRoBot") )
photo = await client.download_media(
message.reply_to_message.sticker.file_id,
f"tostick_{message.from_user.id}.jpg",
)
await message.reply_photo(
photo=photo, caption="Sticker -> Image\n@MissKatyRoBot"
)
os.remove(photo) os.remove(photo)
except Exception as e: except Exception as e:
@ -198,7 +242,10 @@ async def showid(client, message):
last = message.from_user.last_name or "" last = message.from_user.last_name or ""
username = message.from_user.username username = message.from_user.username
dc_id = message.from_user.dc_id or "" dc_id = message.from_user.dc_id or ""
await message.reply_text(f"<b>➲ First Name:</b> {first}\n<b>➲ Last Name:</b> {last}\n<b>➲ Username:</b> {username}\n<b>➲ Telegram ID:</b> <code>{user_id}</code>\n<b>➲ Data Centre:</b> <code>{dc_id}</code>", quote=True) await message.reply_text(
f"<b>➲ First Name:</b> {first}\n<b>➲ Last Name:</b> {last}\n<b>➲ Username:</b> {username}\n<b>➲ Telegram ID:</b> <code>{user_id}</code>\n<b>➲ Data Centre:</b> <code>{dc_id}</code>",
quote=True,
)
elif chat_type in ["group", "supergroup"]: elif chat_type in ["group", "supergroup"]:
_id = "" _id = ""
@ -212,10 +259,16 @@ async def showid(client, message):
) )
file_info = get_file_id(message.reply_to_message) file_info = get_file_id(message.reply_to_message)
else: else:
_id += "<b>➲ User ID</b>: " f"<code>{message.from_user.id if message.from_user else 'Anonymous'}</code>\n" _id += (
"<b>➲ User ID</b>: "
f"<code>{message.from_user.id if message.from_user else 'Anonymous'}</code>\n"
)
file_info = get_file_id(message) file_info = get_file_id(message)
if file_info: if file_info:
_id += f"<b>{file_info.message_type}</b>: " f"<code>{file_info.file_id}</code>\n" _id += (
f"<b>{file_info.message_type}</b>: "
f"<code>{file_info.file_id}</code>\n"
)
await message.reply_text(_id, quote=True) await message.reply_text(_id, quote=True)
@ -246,24 +299,41 @@ async def who_is(client, message):
if message.chat.type in (("supergroup", "channel")): if message.chat.type in (("supergroup", "channel")):
try: try:
chat_member_p = await message.chat.get_member(from_user.id) chat_member_p = await message.chat.get_member(from_user.id)
joined_date = datetime.fromtimestamp(chat_member_p.joined_date or time.time()).strftime("%Y.%m.%d %H:%M:%S") joined_date = datetime.fromtimestamp(
message_out_str += "<b>➲Joined this Chat on:</b> <code>" f"{joined_date}" "</code>\n" chat_member_p.joined_date or time.time()
).strftime("%Y.%m.%d %H:%M:%S")
message_out_str += (
"<b>➲Joined this Chat on:</b> <code>" f"{joined_date}" "</code>\n"
)
except UserNotParticipant: except UserNotParticipant:
pass pass
if chat_photo := from_user.photo: if chat_photo := from_user.photo:
local_user_photo = await client.download_media(message=chat_photo.big_file_id) local_user_photo = await client.download_media(message=chat_photo.big_file_id)
buttons = [[InlineKeyboardButton("🔐 Close", callback_data="close_data")]] buttons = [[InlineKeyboardButton("🔐 Close", callback_data="close_data")]]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_photo(photo=local_user_photo, quote=True, reply_markup=reply_markup, caption=message_out_str, disable_notification=True) await message.reply_photo(
photo=local_user_photo,
quote=True,
reply_markup=reply_markup,
caption=message_out_str,
disable_notification=True,
)
os.remove(local_user_photo) os.remove(local_user_photo)
else: else:
buttons = [[InlineKeyboardButton("🔐 Close", callback_data="close_data")]] buttons = [[InlineKeyboardButton("🔐 Close", callback_data="close_data")]]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_text(text=message_out_str, reply_markup=reply_markup, quote=True, disable_notification=True) await message.reply_text(
text=message_out_str,
reply_markup=reply_markup,
quote=True,
disable_notification=True,
)
await status_message.delete() await status_message.delete()
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10"} headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10"
}
async def get_content(url): async def get_content(url):
@ -298,7 +368,10 @@ async def mdlsearch(client, message):
] ]
for movie in res for movie in res
] ]
await k.edit(f"Ditemukan {len(movies)} query dari <code>{title}</code>", reply_markup=InlineKeyboardMarkup(btn)) await k.edit(
f"Ditemukan {len(movies)} query dari <code>{title}</code>",
reply_markup=InlineKeyboardMarkup(btn),
)
else: else:
await message.reply("Berikan aku nama drama yang ingin dicari. 🤷🏻‍♂️") await message.reply("Berikan aku nama drama yang ingin dicari. 🤷🏻‍♂️")
@ -313,16 +386,22 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
try: try:
res = (await http.get(f"https://kuryana.vercel.app/id/{slug}")).json() res = (await http.get(f"https://kuryana.vercel.app/id/{slug}")).json()
result += f"<b>Title:</b> <a href='{res['data']['link']}'>{res['data']['title']}</a>\n" result += f"<b>Title:</b> <a href='{res['data']['link']}'>{res['data']['title']}</a>\n"
result += f"<b>AKA:</b> <code>{res['data']['others']['also_known_as']}</code>\n\n" result += (
f"<b>AKA:</b> <code>{res['data']['others']['also_known_as']}</code>\n\n"
)
result += f"<b>Rating:</b> <code>{res['data']['details']['score']}</code>\n" result += f"<b>Rating:</b> <code>{res['data']['details']['score']}</code>\n"
result += f"<b>Content Rating:</b> <code>{res['data']['details']['content_rating']}</code>\n" result += f"<b>Content Rating:</b> <code>{res['data']['details']['content_rating']}</code>\n"
result += f"<b>Type:</b> <code>{res['data']['details']['type']}</code>\n" result += f"<b>Type:</b> <code>{res['data']['details']['type']}</code>\n"
result += f"<b>Country:</b> <code>{res['data']['details']['country']}</code>\n" result += (
f"<b>Country:</b> <code>{res['data']['details']['country']}</code>\n"
)
if res["data"]["details"]["type"] == "Movie": if res["data"]["details"]["type"] == "Movie":
result += f"<b>Release Date:</b> <code>{res['data']['details']['release_date']}</code>\n" result += f"<b>Release Date:</b> <code>{res['data']['details']['release_date']}</code>\n"
elif res["data"]["details"]["type"] == "Drama": elif res["data"]["details"]["type"] == "Drama":
result += f"<b>Episode:</b> {res['data']['details']['episodes']}\n" result += f"<b>Episode:</b> {res['data']['details']['episodes']}\n"
result += f"<b>Aired:</b> <code>{res['data']['details']['aired']}</code>\n" result += (
f"<b>Aired:</b> <code>{res['data']['details']['aired']}</code>\n"
)
try: try:
result += f"<b>Aired on:</b> <code>{res['data']['details']['aired_on']}</code>\n" result += f"<b>Aired on:</b> <code>{res['data']['details']['aired_on']}</code>\n"
except: except:
@ -331,11 +410,17 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
result += f"<b>Original Network:</b> <code>{res['data']['details']['original_network']}</code>\n" result += f"<b>Original Network:</b> <code>{res['data']['details']['original_network']}</code>\n"
except: except:
pass pass
result += f"<b>Duration:</b> <code>{res['data']['details']['duration']}</code>\n" result += (
result += f"<b>Genre:</b> <code>{res['data']['others']['genres']}</code>\n\n" f"<b>Duration:</b> <code>{res['data']['details']['duration']}</code>\n"
)
result += (
f"<b>Genre:</b> <code>{res['data']['others']['genres']}</code>\n\n"
)
result += f"<b>Synopsis:</b> <code>{res['data']['synopsis']}</code>\n" result += f"<b>Synopsis:</b> <code>{res['data']['synopsis']}</code>\n"
result += f"<b>Tags:</b> <code>{res['data']['others']['tags']}</code>\n" result += f"<b>Tags:</b> <code>{res['data']['others']['tags']}</code>\n"
btn = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]]) btn = InlineKeyboardMarkup(
[[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]]
)
await query.message.edit_text(result, reply_markup=btn) await query.message.edit_text(result, reply_markup=btn)
except Exception as e: except Exception as e:
await query.message.edit_text(f"<b>ERROR:</b>\n<code>{e}</code>") await query.message.edit_text(f"<b>ERROR:</b>\n<code>{e}</code>")
@ -349,9 +434,13 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
async def imdb1_search(client, message): async def imdb1_search(client, message):
BTN = [] BTN = []
if message.sender_chat: if message.sender_chat:
return await message.reply("Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa..") return await message.reply(
"Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa.."
)
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply("Berikan aku nama series atau movie yang ingin dicari. 🤷🏻‍♂️", quote=True) return await message.reply(
"Berikan aku nama series atau movie yang ingin dicari. 🤷🏻‍♂️", quote=True
)
r, judul = message.text.split(None, 1) r, judul = message.text.split(None, 1)
k = await message.reply("🔎 Sedang mencari di Database IMDB..", quote=True) k = await message.reply("🔎 Sedang mencari di Database IMDB..", quote=True)
msg = "" msg = ""
@ -368,7 +457,11 @@ async def imdb1_search(client, message):
type = movie.get("q").replace("feature", "movie").capitalize() type = movie.get("q").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{count}. {title} {year} ~ {type}\n" msg += f"{count}. {title} {year} ~ {type}\n"
BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}")) BTN.append(
InlineKeyboardButton(
text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}"
)
)
buttons.add(*BTN) buttons.add(*BTN)
await k.edit(msg, reply_markup=buttons) await k.edit(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
@ -386,12 +479,18 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
url = f"https://www.imdb.com/title/tt{movie}/" url = f"https://www.imdb.com/title/tt{movie}/"
resp = await get_content(url) resp = await get_content(url)
sop = BeautifulSoup(resp, "lxml") sop = BeautifulSoup(resp, "lxml")
r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0]) r_json = json.loads(
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
res_str = "" res_str = ""
type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else "" type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else ""
if r_json.get("name"): if r_json.get("name"):
try: try:
tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text tahun = (
sop.select('ul[data-testid="hero-title-block__metadata"]')[0]
.find(class_="sc-8c396aa2-2 itZqyK")
.text
)
except: except:
tahun = "-" tahun = "-"
res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n" res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n"
@ -400,31 +499,63 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
else: else:
res_str += "\n" res_str += "\n"
if sop.select('li[data-testid="title-techspec_runtime"]'): if sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text durasi = (
sop.select('li[data-testid="title-techspec_runtime"]')[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n" res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n"
if r_json.get("contentRating"): if r_json.get("contentRating"):
res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n" res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n"
if r_json.get("aggregateRating"): if r_json.get("aggregateRating"):
res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n" res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n"
if sop.select('li[data-testid="title-details-releasedate"]'): if sop.select('li[data-testid="title-details-releasedate"]'):
rilis = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text rilis = (
rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link")["href"] sop.select('li[data-testid="title-details-releasedate"]')[0]
res_str += f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n" .find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
.text
)
rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[
0
].find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)[
"href"
]
res_str += (
f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
)
if r_json.get("genre"): if r_json.get("genre"):
genre = "".join(f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " if i in GENRES_EMOJI else f"#{i.replace('-', '_').replace(' ', '_')}, " for i in r_json["genre"]) genre = "".join(
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
if i in GENRES_EMOJI
else f"#{i.replace('-', '_').replace(' ', '_')}, "
for i in r_json["genre"]
)
genre = genre[:-2] genre = genre[:-2]
res_str += f"<b>Genre:</b> {genre}\n" res_str += f"<b>Genre:</b> {genre}\n"
if sop.select('li[data-testid="title-details-origin"]'): if sop.select('li[data-testid="title-details-origin"]'):
country = "".join( country = "".join(
f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, "
for country in sop.select('li[data-testid="title-details-origin"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") for country in sop.select('li[data-testid="title-details-origin"]')[
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
country = country[:-2] country = country[:-2]
res_str += f"<b>Negara:</b> {country}\n" res_str += f"<b>Negara:</b> {country}\n"
if sop.select('li[data-testid="title-details-languages"]'): if sop.select('li[data-testid="title-details-languages"]'):
language = "".join( language = "".join(
f"#{lang.text.replace(' ', '_').replace('-', '_')}, " for lang in sop.select('li[data-testid="title-details-languages"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") f"#{lang.text.replace(' ', '_').replace('-', '_')}, "
for lang in sop.select('li[data-testid="title-details-languages"]')[
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
language = language[:-2] language = language[:-2]
res_str += f"<b>Bahasa:</b> {language}\n" res_str += f"<b>Bahasa:</b> {language}\n"
@ -455,7 +586,9 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
actors = actors[:-2] actors = actors[:-2]
res_str += f"<b>Pemeran:</b> {actors}\n\n" res_str += f"<b>Pemeran:</b> {actors}\n\n"
if r_json.get("description"): if r_json.get("description"):
summary = GoogleTranslator("auto", "id").translate(r_json.get("description")) summary = GoogleTranslator("auto", "id").translate(
r_json.get("description")
)
res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n" res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n"
if r_json.get("keywords"): if r_json.get("keywords"):
keywords = r_json["keywords"].split(",") keywords = r_json["keywords"].split(",")
@ -466,27 +599,66 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
key_ = key_[:-2] key_ = key_[:-2]
res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n" res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n"
if sop.select('li[data-testid="award_information"]'): if sop.select('li[data-testid="award_information"]'):
awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text awards = (
sop.select('li[data-testid="award_information"]')[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n" res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n"
else: else:
res_str += "\n" res_str += "\n"
res_str += "<b>©️ IMDb by</b> @MissKatyRoBot" res_str += "<b>©️ IMDb by</b> @MissKatyRoBot"
if r_json.get("trailer"): if r_json.get("trailer"):
trailer_url = r_json["trailer"]["url"] trailer_url = r_json["trailer"]["url"]
markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"), InlineKeyboardButton("▶️ Trailer", url=trailer_url)]]) markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
),
InlineKeyboardButton("▶️ Trailer", url=trailer_url),
]
]
)
else: else:
markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}")]]) markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
)
]
]
)
if thumb := r_json.get("image"): if thumb := r_json.get("image"):
try: try:
await query.message.reply_photo(photo=thumb, quote=True, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) await query.message.reply_photo(
photo=thumb,
quote=True,
caption=res_str,
reply_to_message_id=usr.id,
reply_markup=markup,
)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg") poster = thumb.replace(".jpg", "._V1_UX360.jpg")
await query.message.reply_photo(photo=poster, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) await query.message.reply_photo(
photo=poster,
caption=res_str,
reply_to_message_id=usr.id,
reply_markup=markup,
)
except Exception: except Exception:
await query.message.reply(res_str, reply_markup=markup, disable_web_page_preview=False, reply_to_message_id=usr.id) await query.message.reply(
res_str,
reply_markup=markup,
disable_web_page_preview=False,
reply_to_message_id=usr.id,
)
await query.message.delete() await query.message.delete()
else: else:
await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False) await query.message.edit(
res_str, reply_markup=markup, disable_web_page_preview=False
)
await query.answer() await query.answer()
except MessageNotModified: except MessageNotModified:
pass pass
@ -503,7 +675,10 @@ async def imdb_en_search(client, message):
if message.sender_chat: if message.sender_chat:
return await message.reply("This feature not available for channel.") return await message.reply("This feature not available for channel.")
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply("Give movie name or series. Ex: <code>/imdb_en soul</code>. 🤷🏻‍♂️", quote=True) return await message.reply(
"Give movie name or series. Ex: <code>/imdb_en soul</code>. 🤷🏻‍♂️",
quote=True,
)
r, title = message.text.split(None, 1) r, title = message.text.split(None, 1)
k = await message.reply("Searching Movie/Series in IMDB Database.. 😴", quote=True) k = await message.reply("Searching Movie/Series in IMDB Database.. 😴", quote=True)
msg = "" msg = ""
@ -520,7 +695,11 @@ async def imdb_en_search(client, message):
type = movie.get("qid").replace("feature", "movie").capitalize() type = movie.get("qid").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{count}. {titles} {year} ~ {type}\n" msg += f"{count}. {titles} {year} ~ {type}\n"
BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}")) BTN.append(
InlineKeyboardButton(
text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}"
)
)
buttons.add(*BTN) buttons.add(*BTN)
await k.edit(msg, reply_markup=buttons) await k.edit(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
@ -539,12 +718,18 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
url = f"https://www.imdb.com/title/tt{movie}/" url = f"https://www.imdb.com/title/tt{movie}/"
resp = await get_content(url) resp = await get_content(url)
sop = BeautifulSoup(resp, "lxml") sop = BeautifulSoup(resp, "lxml")
r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0]) r_json = json.loads(
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
res_str = "" res_str = ""
type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else "" type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else ""
if r_json.get("name"): if r_json.get("name"):
try: try:
tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text tahun = (
sop.select('ul[data-testid="hero-title-block__metadata"]')[0]
.find(class_="sc-8c396aa2-2 itZqyK")
.text
)
except: except:
tahun = "-" tahun = "-"
res_str += f"<b>📹 Title:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n" res_str += f"<b>📹 Title:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n"
@ -553,31 +738,61 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
else: else:
res_str += "\n" res_str += "\n"
if sop.select('li[data-testid="title-techspec_runtime"]'): if sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text durasi = (
sop.select('li[data-testid="title-techspec_runtime"]')[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Duration:</b> <code>{durasi}</code>\n" res_str += f"<b>Duration:</b> <code>{durasi}</code>\n"
if r_json.get("contentRating"): if r_json.get("contentRating"):
res_str += f"<b>Category:</b> <code>{r_json['contentRating']}</code> \n" res_str += f"<b>Category:</b> <code>{r_json['contentRating']}</code> \n"
if r_json.get("aggregateRating"): if r_json.get("aggregateRating"):
res_str += f"<b>Rating:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ from {r_json['aggregateRating']['ratingCount']} user</code> \n" res_str += f"<b>Rating:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ from {r_json['aggregateRating']['ratingCount']} user</code> \n"
if sop.select('li[data-testid="title-details-releasedate"]'): if sop.select('li[data-testid="title-details-releasedate"]'):
rilis = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text rilis = (
rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link")["href"] sop.select('li[data-testid="title-details-releasedate"]')[0]
.find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
.text
)
rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[
0
].find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)[
"href"
]
res_str += f"<b>Release Data:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n" res_str += f"<b>Release Data:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
if r_json.get("genre"): if r_json.get("genre"):
genre = "".join(f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " if i in GENRES_EMOJI else f"#{i.replace('-', '_').replace(' ', '_')}, " for i in r_json["genre"]) genre = "".join(
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
if i in GENRES_EMOJI
else f"#{i.replace('-', '_').replace(' ', '_')}, "
for i in r_json["genre"]
)
genre = genre[:-2] genre = genre[:-2]
res_str += f"<b>Genre:</b> {genre}\n" res_str += f"<b>Genre:</b> {genre}\n"
if sop.select('li[data-testid="title-details-origin"]'): if sop.select('li[data-testid="title-details-origin"]'):
country = "".join( country = "".join(
f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, "
for country in sop.select('li[data-testid="title-details-origin"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") for country in sop.select('li[data-testid="title-details-origin"]')[
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
country = country[:-2] country = country[:-2]
res_str += f"<b>Country:</b> {country}\n" res_str += f"<b>Country:</b> {country}\n"
if sop.select('li[data-testid="title-details-languages"]'): if sop.select('li[data-testid="title-details-languages"]'):
language = "".join( language = "".join(
f"#{lang.text.replace(' ', '_').replace('-', '_')}, " for lang in sop.select('li[data-testid="title-details-languages"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") f"#{lang.text.replace(' ', '_').replace('-', '_')}, "
for lang in sop.select('li[data-testid="title-details-languages"]')[
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
language = language[:-2] language = language[:-2]
res_str += f"<b>Language:</b> {language}\n" res_str += f"<b>Language:</b> {language}\n"
@ -618,27 +833,66 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
key_ = key_[:-2] key_ = key_[:-2]
res_str += f"<b>🔥 Keywords:</b> {key_} \n" res_str += f"<b>🔥 Keywords:</b> {key_} \n"
if sop.select('li[data-testid="award_information"]'): if sop.select('li[data-testid="award_information"]'):
awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text awards = (
sop.select('li[data-testid="award_information"]')[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Awards:</b> <code>{awards}</code>\n\n" res_str += f"<b>🏆 Awards:</b> <code>{awards}</code>\n\n"
else: else:
res_str += "\n" res_str += "\n"
res_str += "<b>©️ IMDb by</b> @MissKatyRoBot" res_str += "<b>©️ IMDb by</b> @MissKatyRoBot"
if r_json.get("trailer"): if r_json.get("trailer"):
trailer_url = r_json["trailer"]["url"] trailer_url = r_json["trailer"]["url"]
markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"), InlineKeyboardButton("▶️ Trailer", url=trailer_url)]]) markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
),
InlineKeyboardButton("▶️ Trailer", url=trailer_url),
]
]
)
else: else:
markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}")]]) markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
)
]
]
)
if thumb := r_json.get("image"): if thumb := r_json.get("image"):
try: try:
await query.message.reply_photo(photo=thumb, quote=True, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) await query.message.reply_photo(
photo=thumb,
quote=True,
caption=res_str,
reply_to_message_id=usr.id,
reply_markup=markup,
)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg") poster = thumb.replace(".jpg", "._V1_UX360.jpg")
await query.message.reply_photo(photo=poster, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) await query.message.reply_photo(
photo=poster,
caption=res_str,
reply_to_message_id=usr.id,
reply_markup=markup,
)
except Exception: except Exception:
await query.message.reply(res_str, reply_markup=markup, disable_web_page_preview=False, reply_to_message_id=usr.id) await query.message.reply(
res_str,
reply_markup=markup,
disable_web_page_preview=False,
reply_to_message_id=usr.id,
)
await query.message.delete() await query.message.delete()
else: else:
await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False) await query.message.edit(
res_str, reply_markup=markup, disable_web_page_preview=False
)
await query.answer() await query.answer()
except Exception: except Exception:
exc = traceback.format_exc() exc = traceback.format_exc()

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import os import os
from pyrogram import filters from pyrogram import filters
from telegraph import upload_file from telegraph import upload_file
@ -28,7 +35,7 @@ async def ocr(_, message):
req = ( req = (
await http.get( await http.get(
f"https://script.google.com/macros/s/AKfycbwURISN0wjazeJTMHTPAtxkrZTWTpsWIef5kxqVGoXqnrzdLdIQIfLO7jsR5OQ5GO16/exec?url={url}", f"https://script.google.com/macros/s/AKfycbwURISN0wjazeJTMHTPAtxkrZTWTpsWIef5kxqVGoXqnrzdLdIQIfLO7jsR5OQ5GO16/exec?url={url}",
follow_redirects=True follow_redirects=True,
) )
).json() ).json()
await msg.edit(f"Hasil OCR:\n<code>{req['text']}</code>") await msg.edit(f"Hasil OCR:\n<code>{req['text']}</code>")

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from os import remove from os import remove
from re import compile as compiles from re import compile as compiles
from misskaty.helper.http import http from misskaty.helper.http import http

View file

@ -1,3 +1,11 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
# This plugin to scrape from melongmovie, and lk21 # This plugin to scrape from melongmovie, and lk21
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import aiohttp import aiohttp

View file

@ -1,3 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from misskaty import app from misskaty import app
from pyrogram import filters from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup

View file

@ -1,3 +1,4 @@
# Code in this plugin to learn basic userbot in pyrogram
import os import os
from pyrogram import enums, filters from pyrogram import enums, filters
from pyrogram.types import ( from pyrogram.types import (

View file

@ -1,12 +1,5 @@
""" import os, json, shutil, asyncio, time
* @author yasir <yasiramunandar@gmail.com> from misskaty import app, LOGGER
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import os, logging, json, shutil, asyncio, time
from misskaty import app
from PIL import Image from PIL import Image
from pyrogram import filters from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@ -20,11 +13,6 @@ from misskaty.plugins.dev import shell_exec
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
from misskaty.helper.pyro_progress import progress_for_pyrogram from misskaty.helper.pyro_progress import progress_for_pyrogram
logging.basicConfig(
level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
LOGGER = logging.getLogger(__name__)
user_time = {} user_time = {}

View file

@ -1,11 +1,9 @@
import logging from bot import LOGGER
from os import environ from os import environ
from dotenv import load_dotenv from dotenv import load_dotenv
load_dotenv("config.env", override=True) load_dotenv("config.env", override=True)
LOGGER = logging.getLogger(__name__)
def getConfig(name: str): def getConfig(name: str):
try: try:

View file

@ -1,15 +1,17 @@
import logging from pyrogram.errors import (
from pyrogram.errors import FloodWait, InputUserDeactivated, PeerIdInvalid, UserIsBlocked FloodWait,
InputUserDeactivated,
PeerIdInvalid,
UserIsBlocked,
)
import asyncio import asyncio
from misskaty import LOGGER
from pyrogram.types import Message from pyrogram.types import Message
from typing import Union from typing import Union
import os import os
import emoji import emoji
from database.users_chats_db import db from database.users_chats_db import db
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
BANNED = {} BANNED = {}
@ -38,14 +40,14 @@ async def broadcast_messages(user_id, message):
return await broadcast_messages(user_id, message) return await broadcast_messages(user_id, message)
except InputUserDeactivated: except InputUserDeactivated:
await db.delete_user(int(user_id)) await db.delete_user(int(user_id))
logging.info(f"{user_id}-Removed from Database, since deleted account.") LOGGER.info(f"{user_id}-Removed from Database, since deleted account.")
return False, "Deleted" return False, "Deleted"
except UserIsBlocked: except UserIsBlocked:
logging.info(f"{user_id} -Blocked the bot.") LOGGER.info(f"{user_id} -Blocked the bot.")
return False, "Blocked" return False, "Blocked"
except PeerIdInvalid: except PeerIdInvalid:
await db.delete_user(int(user_id)) await db.delete_user(int(user_id))
logging.info(f"{user_id} - PeerIdInvalid") LOGGER.info(f"{user_id} - PeerIdInvalid")
return False, "Error" return False, "Error"
except Exception: except Exception:
return False, "Error" return False, "Error"
@ -65,7 +67,16 @@ def get_size(size):
def get_file_id(msg: Message): def get_file_id(msg: Message):
if msg.media: if msg.media:
for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"): for message_type in (
"photo",
"animation",
"audio",
"document",
"video",
"video_note",
"voice",
"sticker",
):
if obj := getattr(msg, message_type): if obj := getattr(msg, message_type):
setattr(obj, "message_type", message_type) setattr(obj, "message_type", message_type)
return obj return obj