Ultroid v0.0.7 2021/05/22

Co-authored-by: New-dev0 <New-dev0@notavailable.live>
Co-authored-by: Danish <danish@ultroid.tech>
Co-authored-by: Amit Sharma <48654350+buddhhu@users.noreply.github.com>
Co-authored-by: Programming Error <error@notavailable.live>
Co-authored-by: Aakash <BLUE-DEVIL1134@users.noreply.github.com>
Co-authored-by: Aditya <me@xditya.me>
Co-authored-by: sppidy <sppidy@users.noreply.github.com>
Co-authored-by: Arnab Paryali <Arnabxd@users.noreply.github.com>
Co-authored-by: divkix <divkix@users.noreply.github.com>
Co-authored-by: hellboi_atul <hellboi-atul@users.noreply.github.com>
This commit is contained in:
Danish
2021-05-22 22:21:41 +05:30
committed by GitHub
parent 427b6f5dfa
commit 68839e9dd0
84 changed files with 3915 additions and 1501 deletions

View File

@@ -16,6 +16,7 @@ from pyUltroid.functions.goodbye_db import *
from pyUltroid.functions.google_image import googleimagesdownload
from pyUltroid.functions.sudos import *
from pyUltroid.functions.welcome_db import *
from pyUltroid.functions.ytdl import *
from pyUltroid.utils import *
from strings import get_string
@@ -29,7 +30,7 @@ except ModuleNotFoundError:
start_time = time.time()
ultroid_version = "v0.0.6"
ultroid_version = "v0.0.7"
OWNER_NAME = ultroid_bot.me.first_name
OWNER_ID = ultroid_bot.me.id

View File

@@ -5,11 +5,11 @@
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import random
import re
import time
from datetime import datetime
from math import ceil
from os import remove
from platform import python_version as PyVer
from git import Repo
@@ -22,7 +22,7 @@ from . import *
# ================================================#
notmine = f"This bot is for {OWNER_NAME}"
ULTROID_PIC = "https://telegra.ph/file/031957757a4f6a5191040.jpg"
ULTROID_PIC = "https://telegra.ph/file/115f149ed8e154641708b.jpg"
helps = get_string("inline_1")
add_ons = udB.get("ADDONS")
@@ -30,6 +30,10 @@ if add_ons == "True" or add_ons is None:
zhelps = get_string("inline_2")
else:
zhelps = get_string("inline_3")
if udB.get("INLINE_PIC"):
_file_to_replace = udB.get("INLINE_PIC")
else:
_file_to_replace = "resources/extras/inline.jpg"
# ============================================#
@@ -71,399 +75,486 @@ async def e(o):
await o.answer(res, switch_pm=f"👥 ULTROID PORTAL", switch_pm_param="start")
if asst.me is not None:
@inline
@in_owner
async def inline_handler(event):
builder = event.builder
result = None
query = event.text
if event.query.user_id in sed and query.startswith("ultd"):
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z) + 10
bnn = asst.me.username
result = builder.article(
title="Help Menu",
description="Help Menu - UserBot | Telethon ",
url="https://t.me/TheUltroid",
thumb=InputWebDocument(ULTROID_PIC, 0, "image/jpeg", []),
text=get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS) - 5,
len(ADDONS),
cmd,
),
buttons=[
[
Button.inline("• Pʟɢɪɴs", data="hrrrr"),
Button.inline("• Aᴅᴅɴs", data="frrr"),
],
[
Button.inline("Oɴᴇʀ•ᴛʟ", data="ownr"),
Button.inline("Iɴʟɪɴᴇ•Pʟɢɪɴs", data="inlone"),
],
[
Button.url(
"Sᴇᴛᴛɪɴɢs⚙",
url=f"https://t.me/{bnn}?start=set",
),
],
[Button.inline("••Cʟᴇ••", data="close")],
],
)
await event.answer([result] if result else None)
elif event.query.user_id in sed and query.startswith("paste"):
ok = query.split("-")[1]
link = f"https://nekobin.com/{ok}"
link_raw = f"https://nekobin.com/raw/{ok}"
result = builder.article(
title="Paste",
text="Pᴀsᴛᴇᴅ T Nᴇᴋʙɪɴ!",
buttons=[
[
Button.url("NekoBin", url=f"{link}"),
Button.url("Raw", url=f"{link_raw}"),
],
],
)
await event.answer([result] if result else None)
@callback("ownr")
@owner
async def setting(event):
await event.edit(
buttons=[
[
Button.inline("•Pɪɴɢ•", data="pkng"),
Button.inline("•Uᴘᴛɪᴍᴇ•", data="upp"),
],
[Button.inline("•Rᴇsᴛᴀʀᴛ•", data="rstrt")],
[Button.inline("<- Bᴀ", data="open")],
],
)
@callback("pkng")
async def _(event):
start = datetime.now()
end = datetime.now()
ms = (end - start).microseconds / 1000
pin = f"🌋Pɪɴɢ = {ms}ms"
await event.answer(pin, cache_time=0, alert=True)
@callback("upp")
async def _(event):
uptime = grt(time.time() - start_time)
pin = f"🙋Uᴘᴛɪᴍᴇ = {uptime}"
await event.answer(pin, cache_time=0, alert=True)
@callback("inlone")
@owner
async def _(e):
button = [
[
Button.switch_inline(
"Sᴇɴᴅ Oғғɪɪᴀʟ Pʟɢɪɴs",
query="send",
same_peer=True,
),
],
[
Button.switch_inline(
"Pʟᴀʏ Sᴛʀᴇ Aᴘᴘs",
query="app telegram",
same_peer=True,
),
Button.switch_inline(
"Mᴅᴅᴇᴅ Aᴘᴘs",
query="mods minecraft",
same_peer=True,
),
],
[
Button.switch_inline(
"Sᴇᴀʀʜ Oɴ Gɢʟᴇ",
query="go TeamUltroid",
same_peer=True,
),
Button.switch_inline(
"Sᴇᴀʀʜ Oɴ Yᴀʜ",
query="yahoo TeamUltroid",
same_peer=True,
),
],
[
Button.switch_inline(
"YTʙᴇ Dɴʟᴀᴅᴇʀ",
query="yt Ed Sheeran Perfect",
same_peer=True,
),
],
[
Button.switch_inline(
"ɪᴘAʀᴛ Sᴇᴀʀʜ",
query="clipart frog",
same_peer=True,
),
Button.switch_inline(
"OʀᴀɴɢᴇFx🦊",
query="ofox beryllium",
same_peer=True,
),
],
[
Button.inline(
"<- Bᴀ",
data="open",
),
],
]
await e.edit(buttons=button, link_preview=False)
@callback("hrrrr")
@owner
async def on_plug_in_callback_query_handler(event):
xhelps = helps.format(OWNER_NAME, len(PLUGINS) - 5)
buttons = paginate_help(0, PLUGINS, "helpme")
await event.edit(f"{xhelps}", buttons=buttons, link_preview=False)
@callback("frrr")
@owner
async def addon(event):
halp = zhelps.format(OWNER_NAME, len(ADDONS))
if len(ADDONS) > 0:
buttons = paginate_addon(0, ADDONS, "addon")
await event.edit(f"{halp}", buttons=buttons, link_preview=False)
else:
await event.answer(
f"• Tʏᴘᴇ `{HNDLR}setredis ADDONS True`\n T ɢᴇᴛ ᴀᴅᴅɴs ᴘʟɢɪɴs",
cache_time=0,
alert=True,
)
@callback("rstrt")
@owner
async def rrst(ult):
await restart(ult)
@callback(
re.compile(
rb"helpme_next\((.+?)\)",
@in_pattern("ultd")
@in_owner
async def inline_handler(event):
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z)
bnn = asst.me.username
result = event.builder.photo(
file=_file_to_replace,
link_preview=False,
text=get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS),
len(ADDONS),
cmd,
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = paginate_help(current_page_number + 1, PLUGINS, "helpme")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"helpme_prev\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = paginate_help(current_page_number - 1, PLUGINS, "helpme")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"addon_next\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = paginate_addon(current_page_number + 1, ADDONS, "addon")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"addon_prev\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = paginate_addon(current_page_number - 1, ADDONS, "addon")
await event.edit(buttons=buttons, link_preview=False)
@callback("back")
@owner
async def backr(event):
xhelps = helps.format(OWNER_NAME, len(PLUGINS) - 5)
current_page_number = int(upage)
buttons = paginate_help(current_page_number, PLUGINS, "helpme")
await event.edit(f"{xhelps}", buttons=buttons, link_preview=False)
@callback("buck")
@owner
async def backr(event):
xhelps = zhelps.format(OWNER_NAME, len(ADDONS))
current_page_number = int(addpage)
buttons = paginate_addon(current_page_number, ADDONS, "addon")
await event.edit(f"{xhelps}", buttons=buttons, link_preview=False)
@callback("open")
@owner
async def opner(event):
bnn = asst.me.username
buttons = [
buttons=[
[
Button.inline("• Pʟɢɪɴs ", data="hrrrr"),
Button.inline("• Pʟɢɪɴs", data="hrrrr"),
Button.inline("• Aᴅᴅɴs", data="frrr"),
],
[
Button.inline("Oɴᴇʀ•Tᴏᴏʟꜱ", data="ownr"),
Button.inline("Oɴᴇʀ•ᴏᴏʟꜱ", data="ownr"),
Button.inline("Iɴʟɪɴᴇ•Pʟɢɪɴs", data="inlone"),
],
[
Button.url(
"Sᴇᴛᴛɪɴɢs⚙",
url=f"https://t.me/{bnn}?start={ultroid_bot.me.id}",
),
Button.url("Sᴇᴛᴛɪɴɢs⚙", url=f"https://t.me/{bnn}?start=set"),
],
[Button.inline("••Cʟᴇ••", data="close")],
]
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z) + 10
],
)
await event.answer([result])
@in_pattern("paste")
@in_owner
async def _(event):
ok = event.text.split(" ")[1]
link = "https://nekobin.com/"
result = event.builder.article(
title="Paste",
text="Pᴀsᴛᴇᴅ T Nᴇᴋʙɪɴ!",
buttons=[
[
Button.url("NekoBin", url=f"{link}{ok}"),
Button.url("Raw", url=f"{link}raw/{ok}"),
],
],
)
await event.answer([result])
@callback("ownr")
@owner
async def setting(event):
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z)
await event.edit(
get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS),
len(ADDONS),
cmd,
),
file=_file_to_replace,
link_preview=False,
buttons=[
[
Button.inline("•Pɪɴɢ•", data="pkng"),
Button.inline("•Uᴘᴛɪᴍᴇ•", data="upp"),
],
[
Button.inline("•Rᴇsᴛᴀʀᴛ•", data="rstrt"),
Button.inline("•Uᴘᴅᴀᴛᴇ•", data="doupdate"),
],
[Button.inline("« Bᴀ", data="open")],
],
)
@callback("doupdate")
@owner
async def _(event):
check = await updater()
if not check:
return await event.answer(
"You Are Already On Latest Version", cache_time=0, alert=True
)
repo = Repo.init()
ac_br = repo.active_branch
changelog, tl_chnglog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")
changelog_str = changelog + f"\n\nClick the below button to update!"
if len(changelog_str) > 1024:
await event.edit(get_string("upd_4"))
file = open(f"ultroid_updates.txt", "w+")
file.write(tl_chnglog)
file.close()
await event.edit(
get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS) - 5,
len(ADDONS),
cmd,
get_string("upd_5"),
file="ultroid_updates.txt",
buttons=[
[Button.inline("• Uᴘᴅᴀᴛᴇ N", data="updatenow")],
[Button.inline("« Bᴀ", data="ownr")],
],
)
remove(f"ultroid_updates.txt")
return
else:
await event.edit(
changelog_str,
buttons=[
[Button.inline("Update Now", data="updatenow")],
[Button.inline("« Bᴀ", data="ownr")],
],
parse_mode="html",
)
@callback("pkng")
async def _(event):
start = datetime.now()
end = datetime.now()
ms = (end - start).microseconds / 1000
pin = f"🌋Pɪɴɢ = {ms}ms"
await event.answer(pin, cache_time=0, alert=True)
@callback("upp")
async def _(event):
uptime = grt(time.time() - start_time)
pin = f"🙋Uᴘᴛɪᴍᴇ = {uptime}"
await event.answer(pin, cache_time=0, alert=True)
@callback("inlone")
@owner
async def _(e):
button = [
[
Button.switch_inline(
"Pʟᴀʏ Sᴛʀᴇ Aᴘᴘs",
query="app telegram",
same_peer=True,
),
buttons=buttons,
link_preview=False,
Button.switch_inline(
"Mᴅᴅᴇᴅ Aᴘᴘs",
query="mods minecraft",
same_peer=True,
),
],
[
Button.switch_inline(
"Sᴇᴀʀʜ Oɴ Gɢʟᴇ",
query="go TeamUltroid",
same_peer=True,
),
Button.switch_inline(
"Sᴇᴀʀʜ Oɴ Yᴀʜ",
query="yahoo TeamUltroid",
same_peer=True,
),
],
[
Button.switch_inline(
"ɪSᴘᴇʀ",
query="msg username wspr Hello",
same_peer=True,
),
Button.switch_inline(
"YTʙᴇ Dɴʟᴀᴅᴇʀ",
query="yt Ed Sheeran Perfect",
same_peer=True,
),
],
[
Button.switch_inline(
"ɪᴘAʀᴛ Sᴇᴀʀʜ",
query="clipart frog",
same_peer=True,
),
Button.switch_inline(
"OʀᴀɴɢᴇFx🦊",
query="ofox beryllium",
same_peer=True,
),
],
[
Button.inline(
"« Bᴀ",
data="open",
),
],
]
await e.edit(buttons=button, link_preview=False)
@callback("hrrrr")
@owner
async def on_plug_in_callback_query_handler(event):
xhelps = helps.format(OWNER_NAME, len(PLUGINS))
buttons = page_num(0, PLUGINS, "helpme", "def")
await event.edit(f"{xhelps}", buttons=buttons, link_preview=False)
@callback("frrr")
@owner
async def addon(event):
halp = zhelps.format(OWNER_NAME, len(ADDONS))
if len(ADDONS) > 0:
buttons = page_num(0, ADDONS, "addon", "add")
await event.edit(f"{halp}", buttons=buttons, link_preview=False)
else:
await event.answer(
f"• Tʏᴘᴇ `{HNDLR}setredis ADDONS True`\n T ɢᴇᴛ ᴀᴅᴅɴs ᴘʟɢɪɴs",
cache_time=0,
alert=True,
)
@callback("close")
@owner
async def on_plug_in_callback_query_handler(event):
await event.edit(
get_string("inline_5"),
buttons=Button.inline("Oᴘᴇɴ Mᴀɪɴ Mᴇɴ Aɢᴀɪɴ", data="open"),
)
@callback(
re.compile(
b"us_plugin_(.*)",
),
@callback("rstrt")
@owner
async def rrst(ult):
await restart(ult)
@callback(
re.compile(
rb"helpme_next\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = page_num(current_page_number + 1, PLUGINS, "helpme", "def")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"helpme_prev\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = page_num(current_page_number - 1, PLUGINS, "helpme", "def")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"addon_next\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = page_num(current_page_number + 1, ADDONS, "addon", "add")
await event.edit(buttons=buttons, link_preview=False)
@callback(
re.compile(
rb"addon_prev\((.+?)\)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
current_page_number = int(event.data_match.group(1).decode("UTF-8"))
buttons = page_num(current_page_number - 1, ADDONS, "addon", "add")
await event.edit(buttons=buttons, link_preview=False)
@callback("back")
@owner
async def backr(event):
xhelps = helps.format(OWNER_NAME, len(PLUGINS))
current_page_number = int(upage)
buttons = page_num(current_page_number, PLUGINS, "helpme", "def")
await event.edit(
f"{xhelps}",
file=_file_to_replace,
buttons=buttons,
link_preview=False,
)
@owner
async def on_plug_in_callback_query_handler(event):
plugin_name = event.data_match.group(1).decode("UTF-8")
help_string = f"Plugin Name - `{plugin_name}`\n"
try:
for i in HELP[plugin_name]:
help_string += i
except BaseException:
pass
if help_string == "":
reply_pop_up_alert = f"{plugin_name} has no detailed help..."
@callback("buck")
@owner
async def backr(event):
xhelps = zhelps.format(OWNER_NAME, len(ADDONS))
current_page_number = int(upage)
buttons = page_num(current_page_number, ADDONS, "addon", "add")
await event.edit(
f"{xhelps}",
file=_file_to_replace,
buttons=buttons,
link_preview=False,
)
@callback("open")
@owner
async def opner(event):
bnn = asst.me.username
buttons = [
[
Button.inline("• Pʟɢɪɴs ", data="hrrrr"),
Button.inline("• Aᴅᴅɴs", data="frrr"),
],
[
Button.inline("Oɴᴇʀ•Tʟ", data="ownr"),
Button.inline("Iɴʟɪɴᴇ•Pʟɢɪɴs", data="inlone"),
],
[
Button.url(
"Sᴇᴛᴛɪɴɢs⚙",
url=f"https://t.me/{bnn}?start={ultroid_bot.me.id}",
),
],
[Button.inline("••Cʟᴇ••", data="close")],
]
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z) + 10
await event.edit(
get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS),
len(ADDONS),
cmd,
),
buttons=buttons,
link_preview=False,
)
@callback("close")
@owner
async def on_plug_in_callback_query_handler(event):
await event.edit(
get_string("inline_5"),
file=_file_to_replace,
buttons=Button.inline("Oᴘᴇɴ Mᴀɪɴ Mᴇɴ Aɢᴀɪɴ", data="open"),
)
@callback(
re.compile(
b"def_plugin_(.*)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
plugin_name = event.data_match.group(1).decode("UTF-8")
help_string = f"Plugin Name - `{plugin_name}`\n"
try:
for i in HELP[plugin_name]:
help_string += i
except BaseException:
pass
if help_string == "":
reply_pop_up_alert = f"{plugin_name} has no detailed help..."
else:
reply_pop_up_alert = help_string
reply_pop_up_alert += "\n© @TeamUltroid"
buttons = [
[
Button.inline(
"« Sᴇɴᴅ Pʟɢɪɴ »",
data=f"sndplug_{(event.data).decode('UTF-8')}",
)
],
[
Button.inline("« Bᴀ", data="back"),
Button.inline("••Cʟᴇ••", data="close"),
],
]
try:
if event.query.user_id in sed:
await event.edit(
reply_pop_up_alert,
buttons=buttons,
)
else:
reply_pop_up_alert = help_string
reply_pop_up_alert += "\n© @TeamUltroid"
try:
if event.query.user_id in sed:
await event.edit(
reply_pop_up_alert,
buttons=[
Button.inline("<- Bᴀ", data="back"),
Button.inline("••Cʟᴇ••", data="close"),
],
)
else:
reply_pop_up_alert = notmine
await event.answer(reply_pop_up_alert, cache_time=0)
except BaseException:
halps = f"Do .help {plugin_name} to get the list of commands."
await event.edit(halps)
reply_pop_up_alert = notmine
await event.answer(reply_pop_up_alert, cache_time=0)
except BaseException:
halps = f"Do .help {plugin_name} to get the list of commands."
await event.edit(halps, buttons=buttons)
@callback(
re.compile(
b"add_plugin_(.*)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
plugin_name = event.data_match.group(1).decode("UTF-8")
help_string = ""
@callback(
re.compile(
b"add_plugin_(.*)",
),
)
@owner
async def on_plug_in_callback_query_handler(event):
plugin_name = event.data_match.group(1).decode("UTF-8")
help_string = ""
try:
for i in HELP[plugin_name]:
help_string += i
except BaseException:
try:
for i in HELP[plugin_name]:
help_string += i
for u in CMD_HELP[plugin_name]:
help_string = f"Plugin Name-{plugin_name}\n\n✘ Commands Available-\n\n"
help_string += str(CMD_HELP[plugin_name])
except BaseException:
try:
for u in CMD_HELP[plugin_name]:
if plugin_name in LIST:
help_string = (
f"Plugin Name-{plugin_name}\n\n✘ Commands Available-\n\n"
)
help_string += str(CMD_HELP[plugin_name])
for d in LIST[plugin_name]:
help_string += HNDLR + d
help_string += "\n"
except BaseException:
try:
if plugin_name in LIST:
help_string = (
f"Plugin Name-{plugin_name}\n\n✘ Commands Available-\n\n"
)
for d in LIST[plugin_name]:
help_string += HNDLR + d
help_string += "\n"
except BaseException:
pass
if help_string == "":
reply_pop_up_alert = f"{plugin_name} has no detailed help..."
pass
if help_string == "":
reply_pop_up_alert = f"{plugin_name} has no detailed help..."
else:
reply_pop_up_alert = help_string
reply_pop_up_alert += "\n© @TeamUltroid"
buttons = [
[
Button.inline(
"« Sᴇɴᴅ Pʟɢɪɴ »",
data=f"sndplug_{(event.data).decode('UTF-8')}",
)
],
[
Button.inline("« Bᴀ", data="buck"),
Button.inline("••Cʟᴇ••", data="close"),
],
]
try:
if event.query.user_id in sed:
await event.edit(
reply_pop_up_alert,
buttons=buttons,
)
else:
reply_pop_up_alert = help_string
reply_pop_up_alert += "\n© @TeamUltroid"
try:
if event.query.user_id in sed:
await event.edit(
reply_pop_up_alert,
buttons=[
Button.inline("<- Bᴀ", data="buck"),
Button.inline("••Cʟᴇ••", data="close"),
],
)
else:
reply_pop_up_alert = notmine
await event.answer(reply_pop_up_alert, cache_time=0)
except BaseException:
halps = f"Do .help {plugin_name} to get the list of commands."
await event.edit(halps)
reply_pop_up_alert = notmine
await event.answer(reply_pop_up_alert, cache_time=0)
except BaseException:
halps = f"Do .help {plugin_name} to get the list of commands."
await event.edit(halps, buttons=buttons)
def paginate_help(page_number, loaded_plugins, prefix):
def page_num(page_number, loaded_plugins, prefix, type):
number_of_rows = 5
number_of_cols = 2
emoji = Redis("EMOJI_IN_HELP")
if emoji:
multi, mult2i = emoji, emoji
multi = emoji
else:
multi, mult2i = "", ""
multi = ""
helpable_plugins = []
global upage
upage = page_number
for p in loaded_plugins:
if not p.startswith("_"):
helpable_plugins.append(p)
helpable_plugins.append(p)
helpable_plugins = sorted(helpable_plugins)
modules = [
Button.inline(
"{} {} {}".format(
random.choice(list(multi)),
multi,
x,
random.choice(list(mult2i)),
multi,
),
data=f"us_plugin_{x}",
data=f"{type}_plugin_{x}",
)
for x in helpable_plugins
]
@@ -478,12 +569,12 @@ def paginate_help(page_number, loaded_plugins, prefix):
] + [
(
Button.inline(
"<- Pʀᴇɪs",
"« Pʀᴇɪs",
data=f"{prefix}_prev({modulo_page})",
),
Button.inline("-Bᴀ-", data="open"),
Button.inline("« Bᴀ »", data="open"),
Button.inline(
"Nᴇxᴛ ->",
"Nᴇxᴛ »",
data=f"{prefix}_next({modulo_page})",
),
),
@@ -491,59 +582,5 @@ def paginate_help(page_number, loaded_plugins, prefix):
else:
pairs = pairs[
modulo_page * number_of_rows : number_of_rows * (modulo_page + 1)
] + [(Button.inline("-Bᴀ-", data="open"),)]
return pairs
def paginate_addon(page_number, loaded_plugins, prefix):
number_of_rows = 5
number_of_cols = 2
emoji = Redis("EMOJI_IN_HELP")
if emoji:
multi, mult2i = emoji, emoji
else:
multi, mult2i = "", ""
helpable_plugins = []
global addpage
addpage = page_number
for p in loaded_plugins:
if not p.startswith("_"):
helpable_plugins.append(p)
helpable_plugins = sorted(helpable_plugins)
modules = [
Button.inline(
"{} {} {}".format(
random.choice(list(multi)),
x,
random.choice(list(mult2i)),
),
data=f"add_plugin_{x}",
)
for x in helpable_plugins
]
pairs = list(zip(modules[::number_of_cols], modules[1::number_of_cols]))
if len(modules) % number_of_cols == 1:
pairs.append((modules[-1],))
max_num_pages = ceil(len(pairs) / number_of_rows)
modulo_page = page_number % max_num_pages
if len(pairs) > number_of_rows:
pairs = pairs[
modulo_page * number_of_rows : number_of_rows * (modulo_page + 1)
] + [
(
Button.inline(
"<- Pʀᴇɪs",
data=f"{prefix}_prev({modulo_page})",
),
Button.inline("-Bᴀᴋ-", data="open"),
Button.inline(
"Nᴇxᴛ ->",
data=f"{prefix}_next({modulo_page})",
),
),
]
else:
pairs = pairs[
modulo_page * number_of_rows : number_of_rows * (modulo_page + 1)
] + [(Button.inline("-Bᴀᴋ-", data="open"),)]
] + [(Button.inline("« Bᴀ »", data="open"),)]
return pairs

View File

@@ -26,5 +26,5 @@ async def repify(e):
await q[0].click(e.chat_id)
if e.sender_id == ultroid_bot.uid:
await e.delete()
except ChatSendInlineForbiddenError or bmi:
except (ChatSendInlineForbiddenError, bmi):
await eor(e, REPOMSG)

View File

@@ -5,14 +5,20 @@
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from telethon.utils import get_display_name
from telethon.errors.rpcerrorlist import MediaEmptyError as mee
from . import *
import re
from telethon.errors.rpcerrorlist import (
ChatWriteForbiddenError,
MediaEmptyError,
PeerIdInvalidError,
)
from telethon.utils import get_display_name
from . import *
# taglogger
@ultroid_bot.on(
events.NewMessage(
incoming=True,
@@ -24,11 +30,11 @@ async def all_messages_catcher(e):
try:
NEEDTOLOG = int(udB.get("TAG_LOG"))
except Exception:
return LOGS.warning("you given Wrong Grp/Channel ID in TAG_LOG.")
x = await ultroid_bot.get_entity(e.sender_id)
return LOGS.info("you given Wrong Grp/Channel ID in TAG_LOG.")
x = e.sender
if x.bot or x.verified:
return
y = await ultroid_bot.get_entity(e.chat_id)
y = e.chat
where_n = get_display_name(y)
who_n = get_display_name(x)
where_l = f"https://t.me/c/{y.id}/{e.id}"
@@ -39,36 +45,54 @@ async def all_messages_catcher(e):
await asst.send_message(
NEEDTOLOG,
send,
buttons=[[Button.url(who_n, who_l)],[Button.url(where_n, where_l)]],
buttons=[
[Button.url(who_n, who_l)],
[Button.url(where_n, where_l)],
],
)
else:
await asst.send_message(
NEEDTOLOG,
send,
buttons=[[Button.inline(who_n, data=f"who{x.id}")],[Button.url(where_n, where_l)]],
buttons=[
[Button.inline(who_n, data=f"who{x.id}")],
[Button.url(where_n, where_l)],
],
)
except mee:
except MediaEmptyError:
if x.username:
who_l = f"https://t.me/{x.username}"
await asst.send_message(
NEEDTOLOG,
"`Unsupported Media`",
buttons=[[Button.url(who_n, who_l)],[Button.url(where_n, where_l)]],
buttons=[
[Button.url(who_n, who_l)],
[Button.url(where_n, where_l)],
],
)
else:
await asst.send_message(
NEEDTOLOG,
"`Unsupported Media`",
buttons=[[Button.inline(who_n, data=f"who{x.id}")],[Button.url(where_n, where_l)]],
buttons=[
[Button.inline(who_n, data=f"who{x.id}")],
[Button.url(where_n, where_l)],
],
)
except PeerIdInvalidError:
await ultroid_bot.send_message(
int(udB.get("LOG_CHANNEL")),
"The Chat Id You Set In Tag Logger Is Wrong , Please Correct It",
)
except ChatWriteForbiddenError:
await ultroid_bot.send_message(NEEDTOLOG, "Please Give Your Assistant Bot")
except Exception as er:
LOGS.info(str(er))
await ultroid_bot.send_message(NEEDTOLOG, f"Please Add Your Assistant Bot - @{asst.me.username} as admin here.")
else:
return
@callback(re.compile(b"who(.*)"))
@callback(re.compile("who(.*)"))
async def _(e):
wah = e.pattern_match.group(1).decode("UTF-8")
y = await ultroid_bot.get_entity(int(wah))
@@ -85,18 +109,13 @@ async def when_asst_added_to_chat(event):
user = await event.get_user()
chat = (await event.get_chat()).title
tmp = event.added_by
add = tmp.id
if user.id == (await asst.get_me()).id:
if add == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|bot"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\nYou had added me to {chat}."
)
else:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|bot"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\n`{add}` added me to {chat}."
)
if user.is_self:
buttons = Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|bot")
return await asst.send_message(
int(udB.get("LOG_CHANNEL")),
f"#ADD_LOG\n\n[{tmp.first_name}](tg://user?id={tmp.id}) added [{user.first_name}](tg://user?id={user.id}) to {chat}.",
buttons=buttons,
)
# log for user's new joins
@@ -108,35 +127,37 @@ async def when_ultd_added_to_chat(event):
user = await event.get_user()
chat = (await event.get_chat()).title
tmp = event.added_by
add = tmp.id
if user.id == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user"))
if user.is_self:
buttons = Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user")
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\n`{add}` just added you to {chat}."
int(udB.get("LOG_CHANNEL")),
f"#ADD_LOG\n\n[{tmp.first_name}](tg://user?id={tmp.id}) just added [{user.first_name}](tg://user?id={user.id}) to {chat}.",
buttons=buttons,
)
elif event.user_joined:
user = await event.get_user()
chat = (await event.get_chat()).title
if user.id == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user"))
if user.is_self:
buttons = Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user")
return await asst.send_message(
Var.LOG_CHANNEL, f"#JOIN_LOG\n\nYou just joined {chat}."
int(udB.get("LOG_CHANNEL")),
f"#JOIN_LOG\n\n[{user.first_name}](tg://user?id={user.id}) just joined {chat}.",
buttons=buttons,
)
"""
@callback(
re.compile(
b"leave_ch_(.*)",
"leave_ch_(.*)",
),
)
@owner
async def leave_ch_at(event):
cht = event.data_match.group(1).decode("UTF-8")
ch_id, client = cht.split("|")
name = (await event.get_chat()).title
if client == "bot":
await asst.delete_dialog(ch_id)
await asst.delete_dialog(int(ch_id))
elif client == "user":
await ultroid.delete_dialog(ch_id)
await event.edit(f"Left `{ch_id}`")
"""
await ultroid_bot.delete_dialog(int(ch_id))
await event.edit(f"Left `{name}`")

View File

@@ -100,7 +100,7 @@ async def _(e):
Button.url("Private", url=f"t.me/{username}"),
Button.switch_inline(
"Secret msg",
query=f"msg {query} wspr ",
query=f"msg {query} wspr Hello 👋",
same_peer=True,
),
]

View File

@@ -9,16 +9,12 @@
✘ Commands Available -
• `{i}promote <reply to user/userid/username>`
Promote the user in the chat.
• `{i}demote <reply to user/userid/username>`
Demote the user in the chat.
• `{i}demote`
Promote/Demote the user in the chat.
• `{i}ban <reply to user/userid/username> <reason>`
Ban the user from the chat.
• `{i}unban <reply to user/userid/username> <reason>`
Unban the user from the chat.
• `{i}unban`
Ban/Unban the user from the chat.
• `{i}kick <reply to user/userid/username> <reason>`
Kick the user from the chat.
@@ -28,11 +24,14 @@
for silent pin use ({i}pin silent).
• `{i}unpin (all) <reply to message>`
Unpin the message(s) in the chat.
Unpin the messages in the chat.
• `{i}pinned`
Get pinned message in the current chat.
• `{i}autodelete <24h/7d/off>`
Enable Auto Delete Messages in Chat.
• `{i}listpinned`
Get all pinned messages in current chat.
@@ -42,21 +41,16 @@
• `{i}purgeme <reply to message>`
Purge Only your messages from the replied message.
• `{i}purgeall <reply to message>`
• `{i}purgeall`
Delete all msgs of replied user.
• `{i}del <reply to message>`
Delete the replied message.
• `{i}edit <new message>`
Edit your last message.
"""
import asyncio
from telethon.errors import BadRequestError
from telethon.errors.rpcerrorlist import UserIdInvalidError
from telethon.tl.functions.channels import EditAdminRequest
from telethon.errors.rpcerrorlist import ChatNotModifiedError, UserIdInvalidError
from telethon.tl.functions.channels import DeleteUserHistoryRequest, EditAdminRequest
from telethon.tl.functions.messages import SetHistoryTTLRequest
from telethon.tl.types import ChatAdminRights, InputMessagesFilterPinned
from . import *
@@ -317,7 +311,13 @@ async def unp(ult):
async def fastpurger(purg):
chat = await purg.get_input_chat()
match = purg.pattern_match.group(1)
if match and purg.text[6] == " ":
try:
ABC = purg.text[6]
except IndexError:
ABC = None
if ABC and purg.text[6] in ["m", "a"]:
return
if match and not purg.is_reply:
p = 0
async for msg in ultroid_bot.iter_messages(purg.chat_id, limit=int(match)):
await msg.delete()
@@ -408,14 +408,9 @@ async def _(e):
input = (await e.get_reply_message()).sender_id
name = (await e.client.get_entity(input)).first_name
try:
nos = 0
async for x in e.client.iter_messages(e.chat_id, from_user=input):
await e.client.delete_messages(e.chat_id, x)
nos += 1
await xx.edit(
f"**Purged **`{nos}`** msgs of **[{name}](tg://user?id={input})",
)
except ValueError:
await ultroid_bot(DeleteUserHistoryRequest(e.chat_id, input))
await eod(e, f"Successfully Purged All Messages from {name}")
except Exception as er:
return await eod(xx, str(er), time=5)
else:
return await eod(
@@ -425,40 +420,6 @@ async def _(e):
)
@ultroid_cmd(
pattern="del$",
)
async def delete_it(delme):
msg_src = await delme.get_reply_message()
if delme.reply_to_msg_id:
try:
await msg_src.delete()
await delme.delete()
except BaseException:
await eod(
delme,
f"Couldn't delete the message.\n\n**ERROR:**\n`{str(e)}`",
time=5,
)
@ultroid_cmd(
pattern="edit",
)
async def editer(edit):
message = edit.text
chat = await edit.get_input_chat()
self_id = await ultroid_bot.get_peer_id("me")
string = str(message[6:])
i = 1
async for message in ultroid_bot.iter_messages(chat, self_id):
if i == 2:
await message.edit(string)
await edit.delete()
break
i = i + 1
@ultroid_cmd(pattern="pinned")
async def get_pinned(event):
x = await eor(event, get_string("com_1"))
@@ -503,4 +464,22 @@ async def get_all_pinned(event):
await x.edit(m + a, parse_mode="html")
@ultroid_cmd(pattern="autodelete ?(.*)", groups_only=True, admins_only=True)
async def autodelte(ult): # Tg Feature
match = ult.pattern_match.group(1)
if not match or match not in ["24h", "7d", "off"]:
return await eod(ult, "`Please Use Proper Format..`")
if match == "24h":
tt = 3600 * 24
elif match == "7d":
tt = 3600 * 24 * 7
else:
tt = 0
try:
await ultroid_bot(SetHistoryTTLRequest(ult.chat_id, period=tt))
except ChatNotModifiedError:
return await eod(ult, f"Auto Delete Setting is Already same to `{match}`")
await eor(ult, f"Auto Delete Status Changed to {match} !")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -37,7 +37,7 @@ last_afk_message = {}
last_afk_msg = {}
afk_start = {}
LOG = Var.LOG_CHANNEL
LOG = int(udB.get("LOG_CHANNEL"))
@ultroid_bot.on(events.NewMessage(outgoing=True))

View File

@@ -24,14 +24,14 @@ tr = Translator()
@ultroid_cmd(pattern="autocorrect")
async def acc(e):
if not is_fullsudo(ult.sender_id):
if not is_fullsudo(e.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
if Redis("AUTOCORRECT") != "True":
udB.set("AUTOCORRECT", "True")
await eod(e, "AUTOCORRECT Feature On")
else:
udB.delete("AUTOCORRECT")
await eof(e, "AUTOCORRECT Feature Off")
await eod(e, "AUTOCORRECT Feature Off")
@ultroid_bot.on(events.NewMessage(outgoing=True))

View File

@@ -8,10 +8,10 @@
"""
✘ Commands Available -
{i}autopic <search query>
`{i}autopic <search query>`
Will change your profile pic at defined intervals with pics related to the given topic.
{i}stoppic
`{i}stoppic`
Stop the AutoPic command.
"""

View File

@@ -122,17 +122,16 @@ async def cmds(event):
)
async def restartbt(ult):
if Var.HEROKU_API:
await eor(ult, "`Restarting..`")
try:
await restart(ult)
except BaseException:
await bash("pkill python3 && python3 -m pyUltroid")
await restart(ult)
else:
await bash("pkill python3 && python3 -m pyUltroid")
@ultroid_cmd(pattern="shutdown")
async def shutdownbot(ult):
if not ult.out:
if not is_fullsudo(ult.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
try:
dyno = ult.text.split(" ", maxsplit=1)[1]
except IndexError:
@@ -181,7 +180,7 @@ async def heroku_logs(event):
await ultroid.send_file(
event.chat_id,
file="ultroid-heroku.log",
thumb="resources/extras/logo_rdm.png",
thumb="resources/extras/ultroid.jpg",
caption=f"**Ultroid Heroku Logs.**\nPasted [here]({url}) too!",
)
os.remove("ultroid-heroku.log")
@@ -201,7 +200,7 @@ async def def_logs(ult):
await ultroid.send_file(
ult.chat_id,
file="ultroid.log",
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
caption=f"**Ultroid Logs.**\nPasted [here]({url}) too!",
)
await xx.edit("Done")

View File

@@ -8,10 +8,10 @@
"""
✘ Commands Available
• `{i}add <id/reply to list/none>`
• `{i}addch <id/reply to list/none>`
Add chat to database. Adds current chat if no id specified.
• `{i}rem <all/id/none>`
• `{i}remch <all/id/none>`
Removes the specified chat (current chat if none specified), or all chats.
• `{i}broadcast <reply to msg>`
@@ -30,11 +30,11 @@ import io
from . import *
@ultroid_cmd(pattern="add ?(.*)", allow_sudo=False)
@ultroid_cmd(
pattern="addch ?(.*)",
allow_sudo=False,
)
async def broadcast_adder(event):
if len(event.text) > 4:
if not event.text[4] == " ": # weird fix
return
msgg = event.pattern_match.group(1)
x = await eor(event, get_string("bd_1"))
aldone = new = crsh = 0
@@ -74,7 +74,7 @@ async def broadcast_adder(event):
return
chat_id = event.chat_id
try:
if int(chat_id) == Var.LOG_CHANNEL:
if int(chat_id) == int(udB.get("LOG_CHANNEL")):
return
except BaseException:
pass
@@ -92,11 +92,11 @@ async def broadcast_adder(event):
await event.delete()
@ultroid_cmd(pattern="rem ?(.*)", allow_sudo=False)
@ultroid_cmd(
pattern="remch ?(.*)",
allow_sudo=False,
)
async def broadcast_remover(event):
if len(event.text) > 4:
if not event.text[4] == " ": # weird fix
return
chat_id = event.pattern_match.group(1)
x = await eor(event, get_string("com_1"))
if chat_id == "all":
@@ -120,7 +120,9 @@ async def broadcast_remover(event):
await x.delete()
@ultroid_cmd(pattern="listchannels")
@ultroid_cmd(
pattern="listchannels$",
)
async def list_all(event):
x = await eor(event, "`Calculating...`")
channels = get_channels()
@@ -153,7 +155,10 @@ async def list_all(event):
await x.edit(msg)
@ultroid_cmd(pattern="forward ?(.*)", allow_sudo=False)
@ultroid_cmd(
pattern="forward$",
allow_sudo=False,
)
async def forw(event):
if not event.is_reply:
await eor(event, "Reply to a message to broadcast.")
@@ -177,7 +182,7 @@ async def forw(event):
except Exception:
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
int(udB.get("LOG_CHANNEL")),
f"Error in sending at {channel}.",
)
except BaseException:
@@ -189,12 +194,17 @@ async def forw(event):
await x.edit(f"{sent_count} messages sent with {error_count} errors.")
if error_count > 0:
try:
await ultroid_bot.send_message(Var.LOG_CHANNEL, f"{error_count} Errors")
await ultroid_bot.send_message(
int(udB.get("LOG_CHANNEL")), f"{error_count} Errors"
)
except BaseException:
await x.edit("Set up log channel for checking errors.")
@ultroid_cmd(pattern="broadcast ?(.*)", allow_sudo=False)
@ultroid_cmd(
pattern="broadcast ?(.*)",
allow_sudo=False,
)
async def sending(event):
x = await eor(event, "`Processing...`")
if not event.is_reply:
@@ -220,7 +230,7 @@ async def sending(event):
except Exception as error:
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
int(udB.get("LOG_CHANNEL")),
f"Error in sending at {channel}.\n\n{error}",
)
except BaseException:
@@ -233,7 +243,7 @@ async def sending(event):
if error_count > 0:
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
int(udB.get("LOG_CHANNEL")),
f"{error_count} Errors",
)
except BaseException:

146
plugins/calculator.py Normal file
View File

@@ -0,0 +1,146 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`{i}calc` - Inline Calculator
"""
import re
from . import *
@ultroid_cmd(pattern="calc")
async def icalc(e):
udB.delete("calc")
results = await ultroid_bot.inline_query(asst.me.username, "calc")
await results[0].click(e.chat_id, silent=True, hide_via=True)
await e.delete()
@in_pattern("calc")
@in_owner
async def _(e):
m = [
"AC",
"C",
"",
"%",
"7",
"8",
"9",
"+",
"4",
"5",
"6",
"-",
"1",
"2",
"3",
"x",
"00",
"0",
".",
"÷",
]
tultd = [Button.inline(f"{x}", data=f"calc{x}") for x in m]
lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4]))
lst.append([Button.inline("=", data="calc=")])
calc = e.builder.article("Calc", text="• Ultroid Inline Calculator •", buttons=lst)
await e.answer([calc])
@callback(re.compile("calc(.*)"))
@owner
async def _(e):
x = (e.data_match.group(1)).decode()
if x == "AC":
udB.delete("calc")
return await e.edit(
"• Ultroid Inline Calculator •",
buttons=[Button.inline("Open Calculator Again", data="recalc")],
)
elif x == "C":
udB.delete("calc")
return await e.answer("cleared")
elif x == "":
get = udB.get("calc")
if get:
udB.set("calc", get[:-1])
return await e.answer(str(get[:-1]))
elif x == "%":
get = udB.get("calc")
if get:
udB.set("calc", get + "/100")
return await e.answer(str(get + "/100"))
elif x == "÷":
get = udB.get("calc")
if get:
udB.set("calc", get + "/")
return await e.answer(str(get + "/"))
elif x == "x":
get = udB.get("calc")
if get:
udB.set("calc", get + "*")
return await e.answer(str(get + "*"))
elif x == "=":
get = udB.get("calc")
if get:
if get.endswith(("*", ".", "/", "-", "+")):
get = get[:-1]
out = await calcc(get, e)
try:
num = float(out)
return await e.answer(f"Answer : {num}", cache_time=0, alert=True)
except BaseException:
udB.delete("calc")
return await e.answer("Error", cache_time=0, alert=True)
return await e.answer("None")
else:
get = udB.get("calc")
if get:
udB.set("calc", get + x)
return await e.answer(str(get + x))
udB.set("calc", x)
return await e.answer(str(x))
@callback("recalc")
@owner
async def _(e):
m = [
"AC",
"C",
"",
"%",
"7",
"8",
"9",
"+",
"4",
"5",
"6",
"-",
"1",
"2",
"3",
"x",
"00",
"0",
".",
"÷",
]
tultd = [Button.inline(f"{x}", data=f"calc{x}") for x in m]
lst = list(zip(tultd[::4], tultd[1::4], tultd[2::4], tultd[3::4]))
lst.append([Button.inline("=", data="calc=")])
await e.edit("Noice Inline Calculator", buttons=lst)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -49,9 +49,8 @@ async def _(e):
return
x = get_source_channels()
th = await e.get_chat()
for xs in x:
if str(th.id) not in str(xs):
return
if str(th.id) not in x:
return
y = get_destinations()
for ys in y:
try:
@@ -88,7 +87,7 @@ async def _(e):
return
async for msg in ultroid_bot.iter_messages(int(c), reverse=True):
try:
await asyncio.sleep(1)
await asyncio.sleep(1.3)
await ultroid_bot.send_message(int(d), msg)
except BaseException:
pass

View File

@@ -14,10 +14,10 @@
• `{i}getlink`
Get link of group this cmd is used in.
• `{i}create (b|g|c) <group_name>`
• `{i}create (g|b|c) <group_name>`
Create group woth a specific name.
b - megagroup/supergroup
g - small group
g - megagroup/supergroup
b - small group
c - channel
"""
@@ -47,7 +47,9 @@ async def _(e):
return await eod(xx, "`Cant delete this chat`", time=10)
except no_admin:
return await eod(xx, "`I m not an admin`", time=10)
await e.client.send_message(Var.LOG_CHANNEL, f"#Deleted\nDeleted {e.chat_id}")
await e.client.send_message(
int(udB.get("LOG_CHANNEL")), f"#Deleted\nDeleted {e.chat_id}"
)
@ultroid_cmd(

157
plugins/compressor.py Normal file
View File

@@ -0,0 +1,157 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}compress <reply to video>`
optional `crf` and `stream`
Example : `{i}compress 27 | stream` or `{i}compress 28`
Encode the replied video according to CRF value.
Less CRF == High Quality, More Size
More CRF == Low Quality, Less Size
CRF Range = 20-51
Default = 27
"""
import asyncio
import os
import re
import time
from datetime import datetime as dt
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from telethon.tl.types import DocumentAttributeVideo
from . import *
@ultroid_cmd(pattern="compress ?((\\d+)(.*)|$)")
async def _(e):
crf = e.pattern_match.group(1)
if not crf:
crf = 27
to_stream = e.pattern_match.group(2)
vido = await e.get_reply_message()
if vido and vido.media:
if "video" in mediainfo(vido.media):
if hasattr(vido.media, "document"):
vfile = vido.media.document
name = vido.file.name
else:
vfile = vido.media
name = ""
if not name:
name = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"
xxx = await eor(e, "`Trying To Download...`")
c_time = time.time()
file = await downloader(
"resources/downloads/" + name,
vfile,
xxx,
c_time,
"Downloading " + name + "...",
)
o_size = os.path.getsize(file.name)
d_time = time.time()
diff = time_formatter((d_time - c_time) * 1000)
file_name = (file.name).split("/")[-1]
out = file_name.replace(file_name.split(".")[-1], " compressed.mkv")
await xxx.edit(
f"`Downloaded {file.name} of {humanbytes(o_size)} in {diff}.\nNow Compressing...`"
)
x, y = await bash(
f'mediainfo --fullscan """{file.name}""" | grep "Frame count"'
)
total_frames = x.split(":")[1].split("\n")[0]
progress = "progress.txt"
with open(progress, "w") as fk:
pass
proce = await asyncio.create_subprocess_shell(
f'ffmpeg -hide_banner -loglevel quiet -progress {progress} -i """{file.name}""" -preset ultrafast -c:v libx265 -crf {crf} -map 0:v -c:a aac -map 0:a -c:s copy -map 0:s? """{out}""" -y',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
while proce.returncode != 0:
await asyncio.sleep(3)
with open(progress, "r+") as fil:
text = fil.read()
frames = re.findall("frame=(\\d+)", text)
size = re.findall("total_size=(\\d+)", text)
if len(frames):
elapse = int(frames[-1])
if len(size):
size = int(size[-1])
per = elapse * 100 / int(total_frames)
progress_str = "`[{0}{1}] {2}%\n`".format(
"".join(["" for i in range(math.floor(per / 5))]),
"".join(["" for i in range(20 - math.floor(per / 5))]),
round(per, 2),
)
e_size = humanbytes(size)
await xxx.edit(progress_str + "\n" + "`" + e_size + "`")
os.remove(file.name)
c_size = os.path.getsize(out)
f_time = time.time()
difff = time_formatter((f_time - d_time) * 1000)
await xxx.edit(
f"`Compressed {humanbytes(o_size)} to {humanbytes(c_size)} in {difff}\nTrying to Upload...`"
)
differ = 100 - ((c_size / o_size) * 100)
caption = f"**Original Size: **`{humanbytes(o_size)}`\n"
caption += f"**Compressed Size: **`{humanbytes(c_size)}`\n"
caption += f"**Compression Ratio: **`{differ:.2f}%`\n"
caption += f"\n**Time Taken To Compress: **`{difff}`"
mmmm = await uploader(
out,
out,
f_time,
xxx,
"Uploading " + out + "...",
)
if to_stream and "| stream" in to_stream:
metadata = extractMetadata(createParser(out))
duration = metadata.get("duration").seconds
hi, _ = await bash(f'mediainfo "{out}" | grep "Height"')
wi, _ = await bash(f'mediainfo "{out}" | grep "Width"')
height = int(hi.split(":")[1].split()[0])
width = int(wi.split(":")[1].split()[0])
attributes = [
DocumentAttributeVideo(
duration=duration, w=width, h=height, supports_streaming=True
)
]
await e.client.send_file(
e.chat_id,
mmmm,
thumb="resources/extras/ultroid.jpg",
caption=caption,
attributes=attributes,
force_document=False,
reply_to=e.reply_to_msg_id,
)
else:
await e.client.send_file(
e.chat_id,
mmmm,
thumb="resources/extras/ultroid.jpg",
caption=caption,
force_document=True,
reply_to=e.reply_to_msg_id,
)
await xxx.delete()
os.remove(out)
else:
await eod(e, "`Reply To Video File Only`")
else:
await eod(e, "`Reply To Video File Only`")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -10,10 +10,10 @@
• `{i}mtoi <reply to media>`
media to image conversion
Media to image conversion
• `{i}mtos <reply to media>`
convert media to sticker.
Convert media to sticker.
• `{i}doc <filename.ext>`
Reply to a text msg to save it in a file.
@@ -22,14 +22,12 @@
Reply to a file to reveal it's text.
• `{i}rename <file name with extension>`
rename the file
Rename the file
• `{i}thumbnail <reply to image`
upload Your file with your custom thumbnail.
In Commands `{i}rename` and `{i}ul`
• `{i}thumbnail <reply to image/thumbnail file>`
Upload Your file with your custom thumbnail.
"""
import asyncio
import os
import time
@@ -37,6 +35,8 @@ import cv2
import requests
from PIL import Image
from telegraph import upload_file as uf
from telethon.tl.types import MessageMediaDocument as doc
from telethon.tl.types import MessageMediaPhoto as photu
from . import *
@@ -46,13 +46,21 @@ opn = []
@ultroid_cmd(pattern="thumbnail$")
async def _(e):
r = await e.get_reply_message()
if not (r and r.media):
return await eor(e, "`Reply to img`")
dl = await ultroid_bot.download_media(r.media)
pop = "`Reply to img or file with thumbnail.`"
if not r:
return await eor(e, pop)
if isinstance(r.media, photu):
dl = await ultroid_bot.download_media(r.media)
elif isinstance(r.media, doc):
if r.media.document.thumbs:
dl = await ultroid_bot.download_media(r, thumb=-1)
else:
return await eor(e, pop)
variable = uf(dl)
os.remove(dl)
nn = "https://telegra.ph" + variable[0]
udB.set("CUSTOM_THUMBNAIL", str(nn))
await bash(f"wget {nn} -O resources/extras/ultroid.jpg")
await eor(e, f"Added [This]({nn}) As Your Custom Thumbnail", link_preview=False)
@@ -78,17 +86,13 @@ async def imak(event):
else:
file = await event.download_media(reply)
os.rename(file, inp)
if Redis("CUSTOM_THUMBNAIL"):
await bash(
f"wget {Redis('CUSTOM_THUMBNAIL')} -O resources/extras/new_thumb.jpg"
)
k = time.time()
xxx = await uploader(inp, inp, k, xx, "Uploading...")
await ultroid_bot.send_file(
event.chat_id,
xxx,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
caption=f"`{xxx.name}`",
reply_to=reply,
)
@@ -155,11 +159,8 @@ async def _(event):
b.write(str(a.message))
b.close()
await xx.edit(f"**Packing into** `{input_str}`")
await asyncio.sleep(2)
await xx.edit(f"**Uploading** `{input_str}`")
await asyncio.sleep(2)
await event.client.send_file(
event.chat_id, input_str, thumb="resources/extras/new_thumb.jpg"
event.chat_id, input_str, thumb="resources/extras/ultroid.jpg"
)
await xx.delete()
os.remove(input_str)

View File

@@ -28,80 +28,14 @@
import os
from telethon import Button
from . import *
@in_pattern(
"send ?(.*)",
)
@in_owner
async def inline_handler(event):
builder = event.builder
input_str = event.pattern_match.group(1)
if input_str is None or input_str == "":
plugs = await event.builder.article(
title=f"Which plugin?",
text="No Module",
buttons=[
Button.switch_inline(
"Search Again..?",
query="send ",
same_peer=True,
),
],
)
await event.answer(plugs)
else:
try:
ultroid = builder.document(
f"plugins/{input_str}.py",
title=f"{input_str}.py",
description=f"Module {input_str} Found",
text=f"{input_str}.py use below button to paste in neko and raw..",
buttons=[
[
Button.switch_inline(
"Search Again..?",
query="send ",
same_peer=True,
),
],
[
Button.inline(
"Paste?",
data=f"pasta-plugins/{input_str}.py",
),
],
],
)
await event.answer([ultroid])
return
except BaseException:
ultroidcode = builder.article(
title=f"Module {input_str}.py Not Found",
description=f"No Such Module",
text=f"No Module Named {input_str}.py",
buttons=[
[
Button.switch_inline(
"Search Again",
query="send ",
same_peer=True,
),
],
],
)
await event.answer([ultroidcode])
return
@ultroid_cmd(
pattern="install",
)
async def install(event):
if not is_fullsudo(event.sender_id):
if not event.out and not is_fullsudo(event.sender_id):
return await eod(event, "`This Command Is Sudo Restricted.`")
await safeinstall(event)

177
plugins/devtools.py Normal file
View File

@@ -0,0 +1,177 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}bash <cmds>`
Run linux commands on telegram.
• `{i}eval <cmds>`
Evaluate python commands on telegram.
• `{i}sysinfo`
Shows System Info.
"""
import io
import sys
import traceback
from os import remove
from carbonnow import Carbon
from . import *
@ultroid_cmd(
pattern="sysinfo$",
)
async def _(e):
await eor(e, "`Sending...`")
x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
with open("neo.txt", "r") as neo:
p = (neo.read()).replace("\n\n", "")
ok = Carbon(code=p)
haa = await ok.save("neofetch")
await e.client.send_file(e.chat_id, haa)
remove("neofetch.jpg")
remove("neo.txt")
@ultroid_cmd(
pattern="bash",
)
async def _(event):
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
f"Developer Restricted!\nIf you know what this does, and want to proceed\n\n `{HNDLR}setredis I_DEV True`\n\nThis Might Be Dangerous.",
)
return
xx = await eor(event, "`Processing...`")
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(xx, "`No cmd given`", time=10)
reply_to_id = event.message.id
if event.reply_to_msg_id:
reply_to_id = event.reply_to_msg_id
stdout, stderr = await bash(cmd)
OUT = f"**☞ BASH\n\n• COMMAND:**\n`{cmd}` \n\n"
if stderr:
OUT += f"**• ERROR:** \n`{stderr}`\n\n"
if stdout:
_o = stdout.split("\n")
o = "\n".join(_o)
OUT += f"**• OUTPUT:**\n`{o}`"
if not stderr and not stdout:
OUT += f"**• OUTPUT:**\n`Success`"
if len(OUT) > 4096:
ultd = OUT.replace("`", "").replace("*", "").replace("_", "")
with io.BytesIO(str.encode(ultd)) as out_file:
out_file.name = "bash.txt"
await event.client.send_file(
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/ultroid.jpg",
allow_cache=False,
caption=f"`{cmd}`",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eor(xx, OUT)
p = print # ignore: pylint
@ultroid_cmd(
pattern="eval",
)
async def _(event):
if len(event.text) > 5:
if not event.text[5] == " ":
return
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
f"Developer Restricted!\nIf you know what this does, and want to proceed\n\n {HNDLR}setredis I_DEV True\n\nThis Might Be Dangerous.",
)
return
xx = await eor(event, "`Processing ...`")
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(xx, "`Give some python cmd`", time=5)
if event.reply_to_msg_id:
reply_to_id = event.reply_to_msg_id
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, stderr, exc = None, None, None
reply_to_id = event.message.id
try:
await aexec(cmd, event)
except Exception:
exc = traceback.format_exc()
stdout = redirected_output.getvalue()
stderr = redirected_error.getvalue()
sys.stdout = old_stdout
sys.stderr = old_stderr
evaluation = ""
if exc:
evaluation = exc
elif stderr:
evaluation = stderr
elif stdout:
evaluation = stdout
else:
evaluation = "Success"
final_output = (
"__►__ **EVALPy**\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(
cmd,
evaluation,
)
)
if len(final_output) > 4096:
ultd = final_output.replace("`", "").replace("*", "").replace("_", "")
with io.BytesIO(str.encode(ultd)) as out_file:
out_file.name = "eval.txt"
await ultroid_bot.send_file(
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/ultroid.jpg",
allow_cache=False,
caption=f"```{cmd}```",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eor(xx, final_output)
async def aexec(code, event):
e = message = event
client = event.client
exec(
f"async def __aexec(e, client): "
+ "\n message = event = e"
+ "".join(f"\n {l}" for l in code.split("\n")),
)
return await locals()["__aexec"](e, e.client)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -10,6 +10,7 @@
• `{i}ul <path/to/file>`
Upload file to telegram chat.
You Can Upload Folders too.
• `{i}ul <path/to/file> | stream`
Upload files as stream.
@@ -19,6 +20,8 @@
"""
import glob
import os
import time
from datetime import datetime as dt
@@ -107,19 +110,89 @@ async def download(event):
tt = time.time()
if not kk:
return await eod(xx, get_string("udl_3"))
elif os.path.isdir(kk):
if not os.listdir(kk):
return await eod(xx, "`This Directory is Empty.`")
ok = glob.glob(f"{kk}/*")
kk = [*sorted(ok)]
for kk in kk:
try:
try:
res = await uploader(kk, kk, tt, xx, "Uploading...")
except MessageNotModifiedError as err:
return await xx.edit(str(err))
title = kk.split("/")[-1]
if title.endswith((".mp3", ".m4a", ".opus", ".ogg")):
hmm = " | stream"
if " | stream" in hmm:
metadata = extractMetadata(createParser(res.name))
wi = 512
hi = 512
duration = 0
if metadata.has("width"):
wi = metadata.get("width")
if metadata.has("height"):
hi = metadata.get("height")
if metadata.has("duration"):
duration = metadata.get("duration").seconds
if metadata.has("artist"):
artist = metadata.get("artist")
else:
if udB.get("artist"):
artist = udB.get("artist")
else:
artist = ultroid_bot.first_name
if res.name.endswith(tuple([".mkv", ".mp4", ".avi"])):
attributes = [
DocumentAttributeVideo(
w=wi, h=hi, duration=duration, supports_streaming=True
)
]
elif res.name.endswith(tuple([".mp3", ".m4a", ".opus", ".ogg"])):
attributes = [
DocumentAttributeAudio(
duration=duration,
title=title.split(".")[0],
performer=artist,
)
]
else:
attributes = None
try:
x = await event.client.send_file(
event.chat_id,
res,
caption=f"`{title}`",
attributes=attributes,
supports_streaming=True,
thumb="resources/extras/ultroid.jpg",
)
except BaseException:
x = await event.client.send_file(
event.chat_id,
res,
caption=f"`{title}`",
thumb="resources/extras/ultroid.jpg",
)
else:
x = await event.client.send_file(
event.chat_id,
res,
caption=f"`{title}`",
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
except Exception as ve:
return await eor(xx, str(ve))
else:
try:
if Redis("CUSTOM_THUMBNAIL"):
await bash(
f"wget {Redis('CUSTOM_THUMBNAIL')} -O resources/extras/new_thumb.jpg"
)
try:
res = await uploader(kk, kk, tt, xx, "Uploading...")
except MessageNotModifiedError as err:
return await xx.edit(str(err))
if " | stream" in hmm and res.name.endswith(
tuple([".mkv", ".mp4", ".mp3", ".opus", ".m4a", ".ogg"])
):
if title.endswith((".mp3", ".m4a", ".opus", ".ogg")):
hmm = " | stream"
if " | stream" in hmm:
metadata = extractMetadata(createParser(res.name))
wi = 512
hi = 512
@@ -131,48 +204,72 @@ async def download(event):
if metadata.has("duration"):
duration = metadata.get("duration").seconds
if metadata.has("artist"):
metadata.get("artist")
if res.name.endswith(tuple([".mkv", ".mp4"])):
artist = metadata.get("artist")
else:
if udB.get("artist"):
artist = udB.get("artist")
else:
artist = ultroid_bot.first_name
if res.name.endswith(tuple([".mkv", ".mp4", ".avi"])):
attributes = [
DocumentAttributeVideo(
w=wi, h=hi, duration=duration, supports_streaming=True
)
]
if res.name.endswith(tuple([".mp3", ".m4a", ".opus", ".ogg"])):
elif res.name.endswith(tuple([".mp3", ".m4a", ".opus", ".ogg"])):
attributes = [
DocumentAttributeAudio(duration=duration, title=title)
DocumentAttributeAudio(
duration=duration,
title=title.split(".")[0],
performer=artist,
)
]
else:
attributes = None
try:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
caption=f"`{title}`",
attributes=attributes,
supports_streaming=True,
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
)
except BaseException:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
caption=f"`{title}`",
force_document=True,
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
)
else:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
caption=f"`{title}`",
force_document=True,
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
)
except Exception as ve:
return await eor(xx, str(ve))
e = datetime.now()
t = time_formatter(((e - s).seconds) * 1000)
if t != "":
await eor(xx, f"Uploaded `{kk}` in `{t}`")
if os.path.isdir(kk):
size = 0
for path, dirs, files in os.walk(kk):
for f in files:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
c = len(os.listdir(kk))
await xx.delete()
await ultroid_bot.send_message(
event.chat_id,
f"Uploaded Total - `{c}` files of `{humanbytes(size)}` in `{t}`",
)
else:
await eor(xx, f"Uploaded `{kk}` in `{t}`")
else:
await eor(xx, f"Uploaded `{kk}` in `0 second(s)`")

98
plugins/echo.py Normal file
View File

@@ -0,0 +1,98 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available
•`{i}addecho <reply to anyone>`
Start Auto Echo message of Replied user.
•`{i}remecho <reply to anyone>`
Turn It off
•`{i}listecho <reply to anyone>`
To Get list.
"""
from pyUltroid.functions.echo_db import *
from telethon.utils import get_display_name
from . import *
@ultroid_cmd(pattern="addecho ?(.*)")
async def echo(e):
r = await e.get_reply_message()
if r:
user = r.sender_id
else:
try:
user = e.text.split()[1]
if user.startswith("@"):
ok = await ultroid_bot.get_entity(user)
user = ok.id
else:
user = int(user)
except BaseException:
return await eod(e, "Reply To A user.")
if check_echo(e.chat_id, user):
return await eod(e, "Echo already activated for this user.")
add_echo(e.chat_id, user)
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
await eor(e, f"Activated Echo For {user}.")
@ultroid_cmd(pattern="remecho ?(.*)")
async def rm(e):
r = await e.get_reply_message()
if r:
user = r.sender_id
else:
try:
user = e.text.split()[1]
if user.startswith("@"):
ok = await ultroid_bot.get_entity(user)
user = ok.id
else:
user = int(user)
except BaseException:
return await eod(e, "Reply To A User.")
if check_echo(e.chat_id, user):
rem_echo(e.chat_id, user)
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
return await eor(e, f"Deactivated Echo For {user}.")
await eor(e, "Echo not activated for this user")
@ultroid_bot.on(events.NewMessage(incoming=True))
async def okk(e):
if check_echo(e.chat_id, e.sender_id):
try:
ok = await bot.get_messages(e.chat_id, ids=e.id)
return await ultroid_bot.send_message(e.chat_id, ok)
except Exception as er:
LOGS.info(er)
@ultroid_cmd(pattern="listecho$")
async def lstecho(e):
k = list_echo(e.chat_id)
if k:
user = "**Activated Echo For Users:**\n\n"
for x in k:
ok = await ultroid_bot.get_entity(int(x))
kk = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
user += "" + kk + "\n"
await eor(e, user)
else:
await eod(e, "`List is Empty, For echo`")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

118
plugins/extra.py Normal file
View File

@@ -0,0 +1,118 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}del <reply to message>`
Delete the replied message.
• `{i}edit <new message>`
Edit your last message or replied msg.
• `{i}copy <reply to message>`
Copy replied message / media.
• `{i}reply`
Reply the last sent msg to replied user.
"""
import asyncio
from telethon.events import NewMessage as NewMsg
from . import *
_new_msgs = {}
@ultroid_bot.on(
NewMsg(
outgoing=True,
),
)
async def newmsg(event):
if event.message.message == f"{HNDLR}reply":
return
_new_msgs[event.chat_id] = event.message
@ultroid_cmd(
pattern="del$",
)
async def delete_it(delme):
msg_src = await delme.get_reply_message()
if delme.reply_to_msg_id:
try:
await msg_src.delete()
await delme.delete()
except BaseException:
await eod(
delme,
f"Couldn't delete the message.\n\n**ERROR:**\n`{str(e)}`",
time=5,
)
@ultroid_cmd(
pattern="copy$",
)
async def copy(e):
reply = await e.get_reply_message()
if reply:
if reply.text and not reply.media:
await eor(e, reply.text)
else:
await reply.reply(reply)
if e.sender_id == ultroid_bot.uid:
await e.delete()
else:
await eod(e, "`Reply To any message`")
@ultroid_cmd(
pattern="edit",
)
async def editer(edit):
message = edit.text
chat = await edit.get_input_chat()
string = str(message[6:])
reply = await edit.get_reply_message()
if reply and reply.text:
try:
await reply.edit(string)
await edit.delete()
except BaseException:
pass
else:
i = 1
async for message in ultroid_bot.iter_messages(chat, ultroid_bot.uid):
if i == 2:
await message.edit(string)
await edit.delete()
break
i = i + 1
@ultroid_cmd(
pattern="reply$",
)
async def _(e):
if e.reply_to_msg_id and e.chat_id in _new_msgs:
msg = _new_msgs[e.chat_id]
chat = await e.get_input_chat()
await asyncio.wait(
[
e.client.delete_messages(chat, [e.id, msg.id]),
e.client.send_message(chat, msg, reply_to=e.reply_to_msg_id),
]
)
else:
await e.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -36,11 +36,10 @@ bot = "@MissRose_bot"
@ultroid_cmd(pattern="superfban ?(.*)")
async def _(event):
msg = await eor(event, "Starting a Mass-FedBan...")
fedList = []
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
if previous_message.media:
downloaded_file_name = await ultroid_bot.download_media(
downloaded_file_name = await ultroid.download_media(
previous_message,
"fedlist",
)
@@ -52,58 +51,50 @@ async def _(event):
except BaseException:
pass
arg = event.text.split(" ", maxsplit=2)
if len(arg) > 2:
try:
FBAN = arg[1]
REASON = arg[2]
else:
FBAN = arg[1]
REASON = " #TBMassBanned "
except IndexError:
try:
FBAN = arg[1]
except IndexError:
return await msg.edit("No user was designated.")
REASON = "#TBMassBanned "
else:
FBAN = previous_message.sender_id
try:
REASON = event.text.split(" ", maxsplit=1)[1]
except BaseException:
REASON = ""
if REASON.strip() == "":
REASON = " #TBMassBanned "
except IndexError:
REASON = "#TBMassBanned"
else:
arg = event.text.split(" ", maxsplit=2)
if len(arg) > 2:
try:
FBAN = arg[1]
REASON = arg[2]
except IndexError:
try:
FBAN = arg[1]
REASON = arg[2]
except BaseException:
return await msg.edit("`No user designated!`")
else:
try:
FBAN = arg[1]
REASON = " #TBMassBanned "
except BaseException:
return await msg.edit("`No user designated!`")
return await msg.edit("No user was designated.")
REASON = "#TBMassBanned"
try:
if str(FBAN) in DEVLIST:
await msg.edit("You can't ban my dev you noob!!")
return
elif isinstance(FBAN, str):
try:
x = await ultroid_bot(GetFullUserRequest(FBAN))
uid = x.user.id
if str(uid) in DEVLIST:
await msg.edit("You can't ban my dev you noob!!")
return
except Exception as e:
print(str(e))
return await msg.edit(str(e))
except Exception as e:
print(str(e))
return await msg.edit(str(e))
uid = int(FBAN)
except ValueError:
x = await ultroid(GetFullUserRequest(FBAN))
uid = x.user.id
if str(uid) in DEVLIST:
return await msg.edit("The user is my Dev and cannot be FBanned!")
if udB.get("FBAN_GROUP_ID"):
chat = int(udB.get("FBAN_GROUP_ID"))
else:
chat = await event.get_chat()
fedList = []
if not len(fedList):
for a in range(3):
async with ultroid_bot.conversation("@MissRose_bot") as bot_conv:
async with ultroid.conversation("@MissRose_bot") as bot_conv:
await bot_conv.send_message("/start")
await asyncio.sleep(3)
await bot_conv.send_message("/myfeds")
@@ -121,7 +112,7 @@ async def _(event):
fedfile = await bot_conv.get_response()
await asyncio.sleep(3)
if fedfile.media:
downloaded_file_name = await ultroid_bot.download_media(
downloaded_file_name = await ultroid.download_media(
fedfile,
"fedlist",
)
@@ -163,7 +154,7 @@ async def _(event):
return
await msg.edit(f"FBaning in {len(fedList)} feds.")
try:
await ultroid_bot.send_message(chat, f"/start")
await ultroid.send_message(chat, f"/start")
except BaseException:
await msg.edit("Specified FBan Group ID is incorrect.")
return
@@ -175,19 +166,19 @@ async def _(event):
exCount = 0
for fed in fedList:
if udB.get("EXCLUDE_FED") and fed in excludeFed:
await ultroid_bot.send_message(chat, f"{fed} Excluded.")
await ultroid.send_message(chat, f"{fed} Excluded.")
exCount += 1
continue
await ultroid_bot.send_message(chat, f"/joinfed {fed}")
await ultroid.send_message(chat, f"/joinfed {fed}")
await asyncio.sleep(3)
await ultroid_bot.send_message(chat, f"/fban {FBAN} {REASON}")
await ultroid.send_message(chat, f"/fban {uid} {REASON}")
await asyncio.sleep(3)
try:
os.remove("fedlist")
except Exception as e:
print(f"Error in removing FedAdmin file.\n{str(e)}")
await msg.edit(
f"SuperFBan Completed.\nTotal Feds - {len(fedList)}.\nExcluded - {exCount}.\n Affected {len(fedList) - exCount} feds.\n#TB",
f"SuperFBan Completed.\nTotal Feds - {len(fedList)}.\nExcluded - {exCount}.\nAffected {len(fedList) - exCount} feds.\n#TB",
)
@@ -198,7 +189,7 @@ async def _(event):
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
if previous_message.media:
downloaded_file_name = await ultroid_bot.download_media(
downloaded_file_name = await ultroid.download_media(
previous_message,
"fedlist",
)
@@ -238,20 +229,13 @@ async def _(event):
REASON = " #TBMassUnBanned "
except BaseException:
return await msg.edit("`No user designated!`")
try:
if str(FBAN) in DEVLIST:
await msg.edit("You can't ban my dev you noob!!")
return
except Exception as e:
print(str(e))
return await msg.edit(str(e))
if udB.get("FBAN_GROUP_ID"):
chat = int(udB.get("FBAN_GROUP_ID"))
else:
chat = await event.get_chat()
if not len(fedList):
for a in range(3):
async with ultroid_bot.conversation("@MissRose_bot") as bot_conv:
async with ultroid.conversation("@MissRose_bot") as bot_conv:
await bot_conv.send_message("/start")
await asyncio.sleep(3)
await bot_conv.send_message("/myfeds")
@@ -269,7 +253,7 @@ async def _(event):
fedfile = await bot_conv.get_response()
await asyncio.sleep(3)
if fedfile.media:
downloaded_file_name = await ultroid_bot.download_media(
downloaded_file_name = await ultroid.download_media(
fedfile,
"fedlist",
)
@@ -311,7 +295,7 @@ async def _(event):
return
await msg.edit(f"UnFBaning in {len(fedList)} feds.")
try:
await ultroid_bot.send_message(chat, f"/start")
await ultroid.send_message(chat, f"/start")
except BaseException:
await msg.edit("Specified FBan Group ID is incorrect.")
return
@@ -323,12 +307,12 @@ async def _(event):
exCount = 0
for fed in fedList:
if udB.get("EXCLUDE_FED") and fed in excludeFed:
await ultroid_bot.send_message(chat, f"{fed} Excluded.")
await ultroid.send_message(chat, f"{fed} Excluded.")
exCount += 1
continue
await ultroid_bot.send_message(chat, f"/joinfed {fed}")
await ultroid.send_message(chat, f"/joinfed {fed}")
await asyncio.sleep(3)
await ultroid_bot.send_message(chat, f"/unfban {FBAN} {REASON}")
await ultroid.send_message(chat, f"/unfban {FBAN} {REASON}")
await asyncio.sleep(3)
try:
os.remove("fedlist")

View File

@@ -22,6 +22,7 @@ import os
from pyUltroid.functions.filter_db import *
from telegraph import upload_file as uf
from telethon.tl.types import User
from telethon.utils import pack_bot_file_id
from . import *
@@ -81,6 +82,8 @@ async def lsnote(e):
@ultroid_bot.on(events.NewMessage())
async def fl(e):
if isinstance(e.sender, User) and e.sender.bot:
return
xx = (e.text).lower()
chat = e.chat_id
x = get_filter(int(chat))

143
plugins/forcesubscribe.py Normal file
View File

@@ -0,0 +1,143 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}fsub <chat username><id>`
Enable ForceSub in Used Chat !
• `{i}checkfsub`
Check/Get Active ForceSub Setting of Used Chat.
• `{i}remfsub`
Remove ForceSub from Used Chat !
Note - You Need to be Admin in Both Channel/Chats
in order to Use ForceSubscribe.
"""
import re
from pyUltroid.functions.forcesub_db import *
from telethon import events
from telethon.errors.rpcerrorlist import UserNotParticipantError
from telethon.tl.custom import Button
from telethon.tl.functions.channels import GetParticipantRequest
from telethon.tl.functions.messages import ExportChatInviteRequest
from . import *
@ultroid_bot.on(events.ChatAction())
async def forcesub(ult):
if not udB.get("FORCESUB"):
return
if not (ult.user_joined or ult.user_added):
return
if not get_forcesetting(ult.chat_id):
return
user = await ult.get_user()
if user.bot:
return
joinchat = get_forcesetting(ult.chat_id)
try:
await ultroid_bot(GetParticipantRequest(int(joinchat), user.id))
except UserNotParticipantError:
await ultroid_bot.edit_permissions(ult.chat_id, user.id, send_messages=False)
res = await ultroid_bot.inline_query(
asst.me.username, f"fsub {user.id}_{joinchat}"
)
await res[0].click(ult.chat_id, reply_to=ult.action_message.id)
@ultroid_cmd(pattern="fsub ?(.*)", admins_only=True, groups_only=True)
async def addfor(e):
match = e.pattern_match.group(1)
if not match:
return await eod(e, "Give Channel where you want User to Join !")
if match.startswith("@"):
ch = match
else:
try:
ch = int(match)
except BaseException:
return await eod(e, "Give Correct Channel Username or id")
try:
match = (await ultroid_bot.get_entity(ch)).id
except BaseException:
return await eod(e, "Give Correct Channel Username or id")
if not str(match).startswith("-100"):
match = int("-100" + str(match))
add_forcesub(e.chat_id, match)
await eor(e, "Added ForceSub in This Chat !")
@ultroid_cmd(pattern="remfsub$")
async def remor(e):
res = rem_forcesub(e.chat_id)
if not res:
return await eod(e, "ForceSub was not Active in this Chat !")
await eor(e, "Removed ForceSub...")
@ultroid_cmd(pattern="checkfsub$")
async def getfsr(e):
res = get_forcesetting(e.chat_id)
if not res:
return await eod(e, "ForceSub is Not Active In This Chat !")
cha = await ultroid_bot.get_entity(int(res))
await eor(e, f"**ForceSub Status** : `Active`\n- **{cha.title}** `({res})`")
@in_pattern("fsub ?(.*)")
@in_owner
async def fcall(e):
match = e.pattern_match.group(1)
spli = match.split("_")
user = await ultroid_bot.get_entity(int(spli[0]))
cl = await ultroid_bot.get_entity(int(spli[1]))
text = f"Hi [{user.first_name}](tg://user?id={user.id}), You Need to Join"
text += f" {cl.title} in order to Chat in this Group."
if not cl.username:
el = (await ultroid_bot(ExportChatInviteRequest(cl))).link
else:
el = "https://t.me/" + cl.username
res = [
await e.builder.article(
title="forcesub",
text=text,
buttons=[
[Button.url(text="Join Channel", url=el)],
[Button.inline("Unmute Me", data=f"unm_{match}")],
],
)
]
await e.answer(res)
@callback(re.compile("unm_(.*)"))
async def diesoon(e):
match = (e.data_match.group(1)).decode("UTF-8")
spli = match.split("_")
if not e.sender_id == int(spli[0]):
return await e.answer("This Message is Not for You", alert=True)
try:
await ultroid_bot(GetParticipantRequest(int(spli[1]), int(spli[0])))
except UserNotParticipantError:
return await e.answer(
"Please Join That Channel !\nThen Click This Button !", alert=True
)
await ultroid_bot.edit_permissions(
e.chat_id, int(spli[0]), send_messages=True, until_date=None
)
await e.edit("Thanks For Joining ! ")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

137
plugins/giftools.py Normal file
View File

@@ -0,0 +1,137 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available
•`{i}invertgif`
Make Gif Inverted(negative).
•`{i}bwgif`
Make Gif black and white
•`{i}vtog`
Reply To Video , It will Create Gif
Video to Gif
•`{i}gif <query>`
Send video regarding to query.
"""
import os
import random
import time
from datetime import datetime as dt
from . import *
@ultroid_cmd(pattern="bwgif$")
async def igif(e):
a = await e.get_reply_message()
if not (a and a.media):
return await eod(e, "`Reply To gif only`")
wut = mediainfo(a.media)
if "gif" not in wut:
return await eod(e, "`Reply To Gif Only`")
xx = await eor(e, "`Processing...`")
z = await ultroid_bot.download_media(a.media)
try:
await bash(f'ffmpeg -i "{z}" -vf format=gray ult.gif -y')
await e.client.send_file(e.chat_id, "ult.gif", support_stream=True)
os.remove(z)
os.remove("ult.gif")
await xx.delete()
except Exception as er:
LOGS.info(er)
@ultroid_cmd(pattern="invertgif$")
async def igif(e):
a = await e.get_reply_message()
if not (a and a.media):
return await eod(e, "`Reply To gif only`")
wut = mediainfo(a.media)
if "gif" not in wut:
return await eod(e, "`Reply To Gif Only`")
xx = await eor(e, "`Processing...`")
z = await ultroid_bot.download_media(a.media)
try:
await bash(
f'ffmpeg -i "{z}" -vf lutyuv="y=negval:u=negval:v=negval" ult.gif -y'
)
await e.client.send_file(e.chat_id, "ult.gif", support_stream=True)
os.remove(z)
os.remove("ult.gif")
await xx.delete()
except Exception as er:
LOGS.info(er)
@ultroid_cmd(pattern="gif ?(.*)")
async def gifs(ult):
get = ult.pattern_match.group(1)
xx = random.randint(0, 5)
n = 0
if ";" in get:
try:
n = int(get.split(";")[-1])
except BaseException:
pass
if not get:
return await eor(ult, "`{i}gif <query>`")
m = await eor(ult, "`Searching gif ...`")
gifs = await ultroid_bot.inline_query("gif", get)
if not n:
await gifs[xx].click(
ult.chat.id, reply_to=ult.reply_to_msg_id, silent=True, hide_via=True
)
else:
for x in range(n):
await gifs[x].click(
ult.chat.id, reply_to=ult.reply_to_msg_id, silent=True, hide_via=True
)
await m.delete()
@ultroid_cmd(pattern="vtog$")
async def vtogif(e):
a = await e.get_reply_message()
if not (a and a.media):
return await eod(e, "`Reply To video only`")
wut = mediainfo(a.media)
if "video" not in wut:
return await eod(e, "`Reply To Video Only`")
xx = await eor(e, "`Processing...`")
dur = a.media.document.attributes[0].duration
tt = time.time()
if int(dur) < 120:
z = await ultroid_bot.download_media(a.media)
await bash(
f'ffmpeg -i {z} -vf "fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 ult.gif -y'
)
await e.client.send_file(e.chat_id, "ult.gif", support_stream=True)
os.remove(z)
os.remove("ult.gif")
await xx.delete()
else:
filename = a.file.name
if not filename:
filename = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"
vid = await downloader(filename, a.media.document, xx, tt, "Downloading...")
z = vid.name
await bash(
f'ffmpeg -ss 3 -t 100 -i {z} -vf "fps=10,scale=320:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 ult.gif'
)
await e.client.send_file(e.chat_id, "ult.gif", support_stream=True)
os.remove(z)
os.remove("ult.gif")
await xx.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -9,19 +9,18 @@
✘ Commands Available -
• `{i}gban <reply user/ username>`
Globally Ban User.
• `{i}ungban`
Ban/Unban Globally.
• `{i}ungban <reply user/ username>`
Unban Globally.
• `{i}gstat <reply to user/userid/username>`
Check if user is GBanned.
• `{i}listgban`
List all GBanned users.
• `{i}gmute <reply user/ username>`
Globally Mute the User.
• `{i}ungmute <reply user/ username>`
UnMute Globally.
• `{i}ungmute`
Mute/UnMute Globally.
• `{i}gkick <reply user/ username>`
Globally Kick User.
@@ -31,15 +30,372 @@
• `{i}gucast <Message>`
Globally Send that msg in all Ur Chat Users.
•`{i}gpromote <reply to user> <channel/group/all> <rank>`
globally promote user where you are admin.
You can also set where To promote only groups or only channels or all.
Like. `gpromote group boss` ~ it promote repied user in all groups.
Or. `gpromote @username all sar` ~ it promote the users in all group and channel.
•`{i}gdemote`
Same function as gpromote.
"""
import os
from telethon import events
from telethon.tl.functions.channels import EditAdminRequest
from telethon.tl.types import ChatAdminRights
from . import *
@ultroid_cmd(pattern="gpromote ?(.*)")
async def _(e):
if not e.out and not is_fullsudo(e.sender_id):
return await eod(e, "`This Command Is Sudo Restricted.`")
x = e.pattern_match.group(1)
if not x:
return await eod(e, "`Incorrect Format`")
user = await e.get_reply_message()
if user:
ev = await eor(e, "`Promoting Replied User Globally`")
ok = e.text.split()
key = "all"
if len(ok) > 1:
if ("group" in ok[1]) or ("channel" in ok[1]):
key = ok[1]
rank = "AdMin"
if len(ok) > 2:
rank = ok[2]
c = 0
if e.is_private:
user.id = user.peer_id.user_id
else:
user.id = user.from_id.user_id
async for x in ultroid_bot.iter_dialogs():
if "group" in key.lower():
if x.is_group:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except BaseException:
pass
elif "channel" in key.lower():
if x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except BaseException:
pass
else:
if x.is_group or x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except Exception as er:
LOGS.info(er)
return await eor(ev, f"Promoted The Replied Users in Total : {c} {key} chats")
else:
k = e.text.split()
if not k[1]:
return await eod(e, "`Give someone's username/id or replied to user.")
user = k[1]
if user.isdigit():
user = int(user)
try:
name = await ultroid_bot.get_entity(user)
except BaseException:
return await eod(e, f"`No User Found Regarding {user}`")
ev = await eor(e, f"`Promoting {name.first_name} globally.`")
key = "all"
if len(k) > 2:
if ("group" in k[2]) or ("channel" in k[2]):
key = k[2]
rank = "AdMin"
if len(k) > 3:
rank = k[3]
c = 0
async for x in ultroid_bot.iter_dialogs():
if "group" in key.lower():
if x.is_group:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except BaseException:
pass
elif "channel" in key.lower():
if x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except BaseException:
pass
else:
if x.is_group or x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=True,
change_info=False,
ban_users=True,
delete_messages=True,
pin_messages=True,
),
rank,
),
)
c += 1
except BaseException:
pass
return await eor(ev, f"Promoted {name.first_name} in Total : {c} {key} chats.")
@ultroid_cmd(pattern="gdemote ?(.*)")
async def _(e):
if not e.out and not is_fullsudo(e.sender_id):
return await eod(e, "`This Command Is Sudo Restricted.`")
x = e.pattern_match.group(1)
if not x:
return await eod(e, "`Incorrect Format`")
user = await e.get_reply_message()
if user:
if e.is_private:
user.id = user.peer_id.user_id
else:
user.id = user.from_id.user_id
ev = await eor(e, "`Demoting Replied User Globally`")
ok = e.text.split()
key = "all"
if len(ok) > 1:
if ("group" in ok[1]) or ("channel" in ok[1]):
key = ok[1]
rank = "Not AdMin"
c = 0
async for x in ultroid_bot.iter_dialogs():
if "group" in key.lower():
if x.is_group:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
elif "channel" in key.lower():
if x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
else:
if x.is_group or x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user.id,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
return await eor(ev, f"Demoted The Replied Users in Total : {c} {key} chats")
else:
k = e.text.split()
if not k[1]:
return await eod(e, "`Give someone's username/id or replied to user.")
user = k[1]
if user.isdigit():
user = int(user)
try:
name = await ultroid_bot.get_entity(user)
except BaseException:
return await eod(e, f"`No User Found Regarding {user}`")
ev = await eor(e, f"`Demoting {name.first_name} globally.`")
key = "all"
if len(k) > 2:
if ("group" in k[2]) or ("channel" in k[2]):
key = k[2]
rank = "Not AdMin"
c = 0
async for x in ultroid_bot.iter_dialogs():
if "group" in key.lower():
if x.is_group:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
elif "channel" in key.lower():
if x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
else:
if x.is_group or x.is_channel:
try:
await ultroid_bot(
EditAdminRequest(
x.id,
user,
ChatAdminRights(
add_admins=False,
invite_users=False,
change_info=False,
ban_users=False,
delete_messages=False,
pin_messages=False,
),
rank,
),
)
c += 1
except BaseException:
pass
return await eor(ev, f"Demoted {name.first_name} in Total : {c} {key} chats.")
@ultroid_cmd(
pattern="ungban ?(.*)",
)
@@ -84,6 +440,8 @@ async def _(e):
pattern="gban ?(.*)",
)
async def _(e):
if not e.out and not is_fullsudo(e.sender_id):
return await eor(e, "`This Command Is Sudo Restricted.`")
xx = await eor(e, "`Gbanning...`")
reason = ""
if e.is_private:
@@ -235,6 +593,8 @@ async def gkick(e):
pattern="gmute ?(.*)",
)
async def _(e):
if not e.out and not is_fullsudo(e.sender_id):
return await eor(e, "`This Command Is Sudo Restricted.`")
xx = await eor(e, "`Gmuting...`")
if e.is_private:
userid = (await e.get_chat()).id
@@ -346,7 +706,7 @@ async def list_gengbanned(event):
name = i
msg += "**User**: " + name + "\n"
reason = get_gban_reason(i)
if reason is not None:
if reason is not None or "":
msg += f"**Reason**: {reason}\n\n"
else:
msg += "\n"
@@ -365,4 +725,39 @@ async def list_gengbanned(event):
await x.edit(gbanned_users)
@ultroid_cmd(pattern="gstat ?(.*)")
async def gstat_(e):
xx = await eor(e, get_string("com_1"))
if e.is_private:
userid = (await e.get_chat()).id
elif e.reply_to_msg_id:
userid = (await e.get_reply_message()).sender_id
elif e.pattern_match.group(1):
if (e.pattern_match.group(1)).isdigit():
try:
userid = (await e.client.get_entity(int(e.pattern_match.group(1)))).id
except ValueError as err:
return await eod(xx, f"{str(err)}", time=5)
else:
try:
userid = (await e.client.get_entity(str(e.pattern_match.group(1)))).id
except ValueError as err:
return await eod(xx, f"{str(err)}", time=5)
else:
return await eod(xx, "`Reply to some msg or add their id.`", time=5)
name = (await e.client.get_entity(userid)).first_name
msg = "**" + name + " is "
is_banned = is_gbanned(userid)
reason = get_gban_reason(userid)
if is_banned:
msg += "Globally Banned"
if reason:
msg += f" with reason** `{reason}`"
else:
msg += ".**"
else:
msg += "not Globally Banned.**"
await xx.edit(msg)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -40,6 +40,10 @@
• `{i}blue <reply to any media>`
just cool.
• `{i}csample <color name /color code>`
example : `{i}csample red`
`{i}csample #ffffff`
"""
import asyncio
@@ -49,6 +53,10 @@ import cv2
import numpy as np
from PIL import Image
from telegraph import upload_file as upf
from telethon.errors.rpcerrorlist import (
ChatSendMediaForbiddenError,
MessageDeleteForbiddenError,
)
from validators.url import url
from . import *
@@ -492,6 +500,27 @@ async def ultd(event):
os.remove(ultt)
@ultroid_cmd(pattern="csample (.*)")
async def sampl(ult):
color = ult.pattern_match.group(1)
if color:
img = Image.new("RGB", (200, 100), f"{color}")
img.save("csample.png")
try:
try:
await ult.delete()
await ultroid_bot.send_message(
ult.chat_id, f"Colour Sample for `{color}` !", file="csample.png"
)
except MessageDeleteForbiddenError:
await ult.reply(f"Colour Sample for `{color}` !", file="csample.png")
except ChatSendMediaForbiddenError:
await eor(ult, "Umm! Sending Media is disabled here!")
else:
await eor(ult, f"Wrong Color Name/Hex Code specified!")
@ultroid_cmd(
pattern="blue$",
)

51
plugins/locks.py Normal file
View File

@@ -0,0 +1,51 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}lock <msgs/media/sticker/gif/games/inline/polls/invites/pin/changeinfo>`
Lock the Used Setting in Used Group.
• `{i}unlock <msgs/media/sticker/gif/games/inline/polls/invites/pin/changeinfo>`
UNLOCK the Used Setting in Used Group.
"""
from pyUltroid.functions.all import lucks, unlucks
from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest
from . import *
@ultroid_cmd(pattern="lock ?(.*)", groups_only=True, admins_only=True)
async def lockho(e):
mat = e.pattern_match.group(1)
if not mat:
return await eod(e, "`What to Lock ?`")
try:
ml = lucks(mat)
except BaseException:
return await eod(e, "`Incorrect Input`")
await ultroid_bot(EditChatDefaultBannedRightsRequest(e.chat_id, ml))
await eor(e, f"Locked - `{mat}` ! ")
@ultroid_cmd(pattern="unlock ?(.*)", groups_only=True, admins_only=True)
async def unlckho(e):
mat = e.pattern_match.group(1)
if not mat:
return await eod(e, "`What to Lock ?`")
try:
ml = unlucks(mat)
except BaseException:
return await eod(e, "`Incorrect Input`")
await ultroid_bot(EditChatDefaultBannedRightsRequest(e.chat_id, ml))
await eor(e, f"Unlocked - `{mat}` ! ")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

114
plugins/logo.py Normal file
View File

@@ -0,0 +1,114 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}logo <text>`
Generate a logo of the given Text
Or Reply To image , to write ur text on it.
Or Reply To Font File, To write with that font.
"""
import os
import random
import time
from PIL import Image, ImageDraw, ImageFont
from telethon.tl.types import InputMessagesFilterPhotos
from . import *
@ultroid_cmd(pattern="logo ?(.*)")
async def logo_gen(event):
xx = await eor(event, get_string("com_1"))
name = event.pattern_match.group(1)
if not name:
await eod(xx, "`Give a name too!`")
bg_, font_ = "", ""
if event.reply_to_msg_id:
temp = await event.get_reply_message()
if temp.media:
if hasattr(temp.media, "document"):
if "font" in temp.file.mime_type:
font_ = await temp.download_media()
elif "pic" in mediainfo(temp.media):
bg_ = await temp.download_media()
else:
pics = []
async for i in ultroid.iter_messages(
"@UltroidLogos", filter=InputMessagesFilterPhotos
):
pics.append(i)
id_ = random.choice(pics)
bg_ = await id_.download_media()
fpath_ = "./resources/fonts/"
f = random.choice(os.listdir(fpath_))
font_ = fpath_ + f
if not bg_:
pics = []
async for i in ultroid.iter_messages(
"@UltroidLogos", filter=InputMessagesFilterPhotos
):
pics.append(i)
id_ = random.choice(pics)
bg_ = await id_.download_media()
if not font_:
fpath_ = "resources/fonts/"
f = random.choice(os.listdir(fpath_))
font_ = fpath_ + f
# next level logic, ignore
if len(name) < 8:
fnt_size = 150
strke = 10
elif len(name) > 10:
fnt_size = 50
strke = 5
else:
fnt_size = 130
strke = 20
img = Image.open(bg_)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_, fnt_size)
w, h = draw.textsize(name, font=font)
h += int(h * 0.21)
image_width, image_height = img.size
draw.text(
((image_width - w) / 2, (image_height - h) / 2),
name,
font=font,
fill=(255, 255, 255),
)
x = (image_width - w) / 2
y = (image_height - h) / 2
draw.text(
(x, y), name, font=font, fill="white", stroke_width=strke, stroke_fill="black"
)
flnme = f"ultd.png"
img.save(flnme, "png")
await xx.edit("`Done!`")
if os.path.exists(flnme):
tt = time.time()
up = await uploader(flnme, flnme, tt, xx, "Uploading...")
await ultroid.send_file(
event.chat_id,
file=up,
caption=f"Logo by [{OWNER_NAME}](tg://user?id={OWNER_ID})",
foce_document=True,
)
os.remove(flnme)
await xx.delete()
if os.path.exists(bg_):
os.remove(bg_)
if os.path.exists(font_):
if not font_.startswith("resources/fonts"):
os.remove(font_)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

77
plugins/megadl.py Normal file
View File

@@ -0,0 +1,77 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`{i}megadl <link>`
It Downloads and Upload Files from mega.nz links.
"""
import glob
import time
from datetime import datetime
from . import *
@ultroid_cmd(pattern="megadl ?(.*)")
async def _(e):
link = e.pattern_match.group(1)
if not os.path.isdir("mega"):
os.mkdir("mega")
else:
os.system("rm -rf mega")
os.mkdir("mega")
xx = await eor(e, f"Processing...\nTo Check Progress : `{HNDLR}ls mega`")
s = datetime.now()
x, y = await bash(f"megadl {link} --path mega")
afl = glob.glob("mega/*")
ok = [*sorted(afl)]
tt = time.time()
c = 0
k = []
for x in ok:
if os.path.isdir(x):
k.append(x)
break
if k:
await xx.edit(
"Your Unzipped File Saved in `mega` folder.\nDo `{i}ls mega` and browse storage\nUse `{i}ul <path>` To upload.".format(
i=HNDLR
)
)
else:
for kk in ok:
try:
res = await uploader(kk, kk, tt, xx, "Uploading...")
await ultroid_bot.send_file(
e.chat_id,
res,
caption="`" + kk.split("/")[-1] + "`",
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
c += 1
except Exception as er:
LOGS.info(er)
ee = datetime.now()
t = time_formatter(((ee - s).seconds) * 1000)
size = 0
for path, dirs, files in os.walk("mega"):
for f in files:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
await xx.delete()
await ultroid_bot.send_message(
e.chat_id,
f"Downloaded And Uploaded Total - `{c}` files of `{humanbytes(size)}` in `{t}`",
)
os.system("rm -rf mega")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -21,9 +21,10 @@
Unmute dmuted user in current chat.
• `{i}tmute <time> <reply to msg/ use id>`
time - m- minutes
h- hours
d- days
s- seconds
m- minutes
h- hours
d- days
Mute user in current chat with time.
"""

View File

@@ -24,6 +24,7 @@
Merge nd send the Pdf to collected from .pdsave.
"""
import glob
import os
import shutil
import time
@@ -38,8 +39,8 @@ from skimage.filters import threshold_local
from . import *
if not os.path.exists("pdf/"):
os.makedirs("pdf/")
if not os.path.isdir("pdf"):
os.mkdir("pdf")
@ultroid_cmd(
@@ -62,7 +63,7 @@ async def pdfseimg(event):
k,
"Downloading " + filename + "...",
)
await result.delete()
await xx.delete()
pdfp = "pdf/hehe.pdf"
pdfp.replace(".pdf", "")
pdf = PdfFileReader(pdfp)
@@ -73,12 +74,12 @@ async def pdfseimg(event):
with open(os.path.join("pdf/ult{}.png".format(num + 1)), "wb") as f:
pw.write(f)
os.remove(pdfp)
a = os.listdir("pdf/")
for z in a:
lst = [f"pdf/{z}"]
await event.client.send_file(event.chat_id, lst, album=True)
afl = glob.glob("pdf/*")
ok = [*sorted(afl)]
for z in ok:
await event.client.send_file(event.chat_id, z, album=True)
shutil.rmtree("pdf")
os.makedirs("pdf/")
os.mkdir("pdf")
await xx.delete()
if msg:
o = int(msg) - 1
@@ -115,7 +116,7 @@ async def pdfsetxt(event):
k,
"Downloading " + filename + "...",
)
await result.delete()
await xx.delete()
dl = result.name
if not msg:
pdf = PdfFileReader(dl)
@@ -134,7 +135,6 @@ async def pdfsetxt(event):
)
os.remove(text)
os.remove(dl)
await xx.delete()
return
if "_" in msg:
u, d = msg.split("_")
@@ -309,9 +309,11 @@ async def sendpdf(event):
else:
ok = "My PDF File.pdf"
merger = PdfFileMerger()
for item in os.listdir("pdf/"):
afl = glob.glob("pdf/*")
ok = [*sorted(afl)]
for item in ok:
if item.endswith("pdf"):
merger.append(f"pdf/{item}")
merger.append(item)
merger.write(ok)
await event.client.send_file(event.chat_id, ok, reply_to=event.reply_to_msg_id)
os.remove(ok)

60
plugins/pinterest.py Normal file
View File

@@ -0,0 +1,60 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}pntrst <link/id>`
Download and send pinterest pins.
"""
import os
from urllib.request import urlretrieve as donl
from bs4 import BeautifulSoup as bs
from requests import get
from . import *
_base = "https://pinterestdownloader.com/download?url="
def gib_link(link):
colon = "%3A"
slash = "%2F"
if link.startswith("https"):
return _base + link.replace(":", colon).replace("/", slash)
else:
return _base + f"https{colon}{slash}{slash}pin.it{slash}{link}"
@ultroid_cmd(
pattern="pntrst ?(.*)",
)
async def pinterest(e):
m = e.pattern_match.group(1)
get_link = get(gib_link(m)).text
hehe = bs(get_link, "html.parser")
hulu = hehe.find_all("a", {"class": "download_button"})
if len(hulu) < 1:
return await eod(e, "`Wrong link or private pin.`")
elif len(hulu) > 1:
donl(hulu[0]["href"], "pinterest.mp4")
donl(hulu[1]["href"], "pinterest.jpg")
await e.delete()
await e.client.send_file(
e.chat_id, "pinterest.mp4", thumb="pinterest.jpg", caption=f"Pin:- {m}"
)
os.remove("pinterest.mp4")
os.remove("pinterest.jpg")
else:
await e.delete()
await e.client.send_file(e.chat_id, hulu[0]["href"], caption=f"Pin:- {m}")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -25,6 +25,15 @@
• `{i}logpm`
Start logging again from that user.
• `{i}startarchive`
Will start adding new PMs to archive.
• `{i}stoparchive`
Will stop adding new PMs to archive.
• `{i}cleararchive`
Unarchive all chats.
"""
import re
@@ -44,7 +53,7 @@ LASTMSG = {}
if Redis("PMPIC"):
PMPIC = Redis("PMPIC")
else:
PMPIC = "https://telegra.ph/file/031957757a4f6a5191040.jpg"
PMPIC = "resources/extras/teamultroid.jpg"
UND = get_string("pmperm_1")
@@ -133,7 +142,7 @@ async def permitpm(event):
pl = udB.get("PMLOGGROUP")
if pl is not None:
return await event.forward_to(int(pl))
await event.forward_to(Var.LOG_CHANNEL)
await event.forward_to(int(udB.get("LOG_CHANNEL")))
sett = Redis("PMSETTING")
@@ -162,13 +171,16 @@ if sett == "True" and sett != "False":
await message.delete()
async for message in e.client.iter_messages(e.chat_id, search=UNS):
await message.delete()
if Var.LOG_CHANNEL:
name = await e.client.get_entity(e.chat_id)
name0 = str(name.first_name)
await e.client.send_message(
Var.LOG_CHANNEL,
f"#AutoApproved\nßecoz of outgoing msg\nUser - [{name0}](tg://user?id={e.chat_id})",
)
try:
await ultroid_bot.edit_folder(e.chat_id, folder=0)
except BaseException:
pass
name = await e.client.get_entity(e.chat_id)
name0 = str(name.first_name)
await asst.send_message(
int(udB.get("LOG_CHANNEL")),
f"#AutoApproved\nßecoz of outgoing msg\nUser - [{name0}](tg://user?id={e.chat_id})",
)
@ultroid_bot.on(
events.NewMessage(
@@ -184,6 +196,13 @@ if sett == "True" and sett != "False":
return
apprv = is_approved(user.id)
if not apprv and event.text != UND:
if Redis("MOVE_ARCHIVE") == "True":
try:
await event.client.edit_folder(user.id, folder=1)
except BaseException:
pass
if event.media:
await event.delete()
name = user.first_name
if user.last_name:
fullname = f"{name} {user.last_name}"
@@ -197,7 +216,7 @@ if sett == "True" and sett != "False":
except KeyError:
try:
await asst.send_message(
Var.LOG_CHANNEL,
int(udB.get("LOG_CHANNEL")),
f"Incoming PM from {mention}!",
buttons=[
Button.inline("Approve PM", data=f"approve_{user.id}"),
@@ -206,7 +225,7 @@ if sett == "True" and sett != "False":
)
except BaseException:
await ultroid.send_message(
Var.LOG_CHANNEL, f"Incoming PM from {mention}!"
int(udB.get("LOG_CHANNEL")), f"Incoming PM from {mention}!"
)
wrn = 1
if user.id in LASTMSG:
@@ -293,21 +312,37 @@ if sett == "True" and sett != "False":
del COUNT_PM[user.id]
del LASTMSG[user.id]
except KeyError:
if Var.LOG_CHANNEL:
await event.client.send_message(
Var.LOG_CHANNEL,
"PMPermit is messed! Pls restart the bot!!",
)
return LOGS.info("COUNT_PM is messed.")
await event.client.send_message(
int(udB.get("LOG_CHANNEL")),
"PMPermit is messed! Pls restart the bot!!",
)
return LOGS.info("COUNT_PM is messed.")
await event.client(BlockRequest(user.id))
await event.client(ReportSpamRequest(peer=user.id))
if Var.LOG_CHANNEL:
name = await event.client.get_entity(user.id)
name0 = str(name.first_name)
await event.client.send_message(
Var.LOG_CHANNEL,
f"[{name0}](tg://user?id={user.id}) was Blocked for spamming.",
)
name = await event.client.get_entity(user.id)
name0 = str(name.first_name)
await event.client.send_message(
int(udB.get("LOG_CHANNEL")),
f"[{name0}](tg://user?id={user.id}) was Blocked for spamming.",
)
@ultroid_cmd(
pattern="(start|stop|clear)archive$",
)
async def _(e):
x = e.pattern_match.group(1)
if x == "start":
udB.set("MOVE_ARCHIVE", "True")
await eod(e, "Now I will move new Unapproved DM's to archive")
elif x == "stop":
udB.set("MOVE_ARCHIVE", "False")
await eod(e, "Now I won't move new Unapproved DM's to archive")
elif x == "clear":
try:
await e.client.edit_folder(unpack=1)
await eod(e, "Unarchived all chats")
except Exception as mm:
await eod(e, str(mm))
@ultroid_cmd(
pattern="(a|approve)(?: |$)",
@@ -326,6 +361,10 @@ if sett == "True" and sett != "False":
uid = replied_user.id
if not is_approved(uid):
approve_user(uid)
try:
await apprvpm.client.edit_folder(uid, folder=0)
except BaseException:
pass
await apprvpm.edit(f"[{name0}](tg://user?id={uid}) `approved to PM!`")
await asyncio.sleep(3)
await apprvpm.delete()
@@ -345,6 +384,10 @@ if sett == "True" and sett != "False":
uid = user.id
if not is_approved(uid):
approve_user(uid)
try:
await apprvpm.client.edit_folder(uid, folder=0)
except BaseException:
pass
await apprvpm.edit(f"[{name0}](tg://user?id={uid}) `approved to PM!`")
async for message in apprvpm.client.iter_messages(user.id, search=UND):
await message.delete()
@@ -352,20 +395,18 @@ if sett == "True" and sett != "False":
await message.delete()
await asyncio.sleep(3)
await apprvpm.delete()
if Var.LOG_CHANNEL:
await apprvpm.client.send_message(
Var.LOG_CHANNEL,
f"#APPROVED\nUser: [{name0}](tg://user?id={uid})",
)
await apprvpm.client.send_message(
int(udB.get("LOG_CHANNEL")),
f"#APPROVED\nUser: [{name0}](tg://user?id={uid})",
)
else:
await apprvpm.edit("`User may already be approved.`")
await asyncio.sleep(5)
await apprvpm.delete()
if Var.LOG_CHANNEL:
await apprvpm.client.send_message(
Var.LOG_CHANNEL,
f"#APPROVED\nUser: [{name0}](tg://user?id={uid})",
)
await apprvpm.client.send_message(
int(udB.get("LOG_CHANNEL")),
f"#APPROVED\nUser: [{name0}](tg://user?id={uid})",
)
else:
await apprvpm.edit(NO_REPLY)
@@ -410,11 +451,10 @@ if sett == "True" and sett != "False":
await e.edit(f"[{name0}](tg://user?id={bbb.id}) `Disaproved to PM!`")
await asyncio.sleep(5)
await e.delete()
if Var.LOG_CHANNEL:
await e.client.send_message(
Var.LOG_CHANNEL,
f"[{name0}](tg://user?id={bbb.id}) was disapproved to PM you.",
)
await e.client.send_message(
int(udB.get("LOG_CHANNEL")),
f"[{name0}](tg://user?id={bbb.id}) was disapproved to PM you.",
)
else:
await e.edit(f"[{name0}](tg://user?id={bbb.id}) was never approved!")
await asyncio.sleep(5)
@@ -422,64 +462,57 @@ if sett == "True" and sett != "False":
else:
await e.edit(NO_REPLY)
@ultroid_cmd(
pattern="block$",
)
async def blockpm(block):
if block.reply_to_msg_id:
reply = await block.get_reply_message()
replied_user = await block.client.get_entity(reply.sender_id)
aname = replied_user.id
if str(aname) in DEVLIST:
return await eor(
block,
"`Lol, He is my Developer\nHe Can't Be Blocked`",
)
name0 = str(replied_user.first_name)
await block.client(BlockRequest(replied_user.id))
await block.edit("`You've been blocked!`")
uid = replied_user.id
elif block.is_private:
bbb = await block.get_chat()
if str(bbb.id) in DEVLIST:
return await eor(
block,
"`Lol, He is my Developer\nHe Can't Be Blocked`",
)
await block.client(BlockRequest(bbb.id))
aname = await block.client.get_entity(bbb.id)
await block.edit("`You've been blocked!`")
name0 = str(aname.first_name)
uid = bbb.id
else:
await block.edit(NO_REPLY)
try:
disapprove_user(uid)
except AttributeError:
pass
if Var.LOG_CHANNEL:
await block.client.send_message(
Var.LOG_CHANNEL,
f"#BLOCKED\nUser: [{name0}](tg://user?id={uid})",
)
@ultroid_cmd(
pattern="unblock$",
@ultroid_cmd(
pattern="block ?(.*)",
)
async def blockpm(block):
match = block.pattern_match.group(1)
if block.is_reply:
reply = await block.get_reply_message()
user = reply.sender_id
elif match:
user = await get_user_id(match)
elif block.is_private:
user = block.chat_id
else:
return await eod(block, NO_REPLY)
if str(user) in DEVLIST:
return await eor(
block,
"`Lol, He is my Developer\nHe Can't Be Blocked`",
)
await block.client(BlockRequest(user))
aname = await block.client.get_entity(user)
await eor(block, f"`{aname.first_name} has been blocked!`")
try:
disapprove_user(user)
except AttributeError:
pass
await ultroid_bot.send_message(
int(udB.get("LOG_CHANNEL")),
f"#BLOCKED\nUser: [{aname.first_name}](tg://user?id={user})",
)
async def unblockpm(unblock):
if unblock.reply_to_msg_id:
reply = await unblock.get_reply_message()
replied_user = await unblock.client.get_entity(reply.sender_id)
name0 = str(replied_user.first_name)
await unblock.client(UnblockRequest(replied_user.id))
await unblock.edit("`You have been unblocked.`")
else:
await unblock.edit(NO_REPLY)
if Var.LOG_CHANNEL:
await unblock.client.send_message(
Var.LOG_CHANNEL,
f"[{name0}](tg://user?id={replied_user.id}) was unblocked!.",
)
@ultroid_cmd(
pattern="unblock ?(.*)",
)
async def unblockpm(unblock):
match = unblock.pattern_match.group(1)
if unblock.is_reply:
reply = await unblock.get_reply_message()
user = reply.sender_id
elif match:
user = await get_user_id(match)
else:
return await eod(unblock, NO_REPLY)
try:
await unblock.client(UnblockRequest(user))
aname = await unblock.client.get_entity(user)
await eor(unblock, f"`{aname.first_name} has been UnBlocked!`")
except Exception as et:
await eod(unblock, f"ERROR - {str(et)}")
@callback(
@@ -494,6 +527,10 @@ async def apr_in(event):
await event.edit("It's a dev! Approved!")
if not is_approved(uid):
approve_user(uid)
try:
await ultroid_bot.edit_folder(uid, folder=0)
except BaseException:
pass
try:
user_name = (await ultroid.get_entity(uid)).first_name
except BaseException:

74
plugins/polls.py Normal file
View File

@@ -0,0 +1,74 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}poll <question> ; <option> ; <option>`
Get the Anonymous Poll with Given Options
• `{i}poll <question> ; <option> ; <option> | <type>`
Get the poll specified with desired type!
type should be any of `public`, `multiple` or `quiz`
• `{i}poll <question> ; <option> ; <option> | quiz_<answerno>`
Get the quiz poll where answerno is the number of option which is correct
"""
from telethon.tl.types import InputMediaPoll, Poll, PollAnswer
from . import *
@ultroid_cmd(
pattern="poll ?(.*)",
groups_only=True,
)
async def uri_poll(e):
match = e.pattern_match.group(1)
if not match:
return await eod(e, "`Give Proper Input...`")
if ";" not in match:
return await eod(e, "`Unable to Determine Options.`.")
ques = match.split(";")[0]
option = match.split(";")[1::]
publ = None
quizo = None
karzo = None
mpp = None
if "|" in match:
ptype = match.split(" | ")[1]
option = match.split("|")[0].split(";")[1::]
if "_" in ptype:
karzo = [str(int(ptype.split("_")[1]) - 1).encode()]
ptype = ptype.split("_")[0]
if ptype not in ["public", "quiz", "multiple"]:
return await eod(e, "`Invalid Poll Type...`")
if ptype == "public":
publ = True
if ptype == "quiz":
quizo = True
if ptype == "multiple":
mpp = True
if len(option) <= 1:
return await eod(e, "`Options Should be More than 1..`")
m = await eor(e, "`Processing... `")
OUT = []
for on in range(len(option)):
OUT.append(PollAnswer(option[on], str(on).encode()))
await ultroid_bot.send_file(
e.chat_id,
InputMediaPoll(
Poll(20, ques, OUT, multiple_choice=mpp, public_voters=publ, quiz=quizo),
correct_answers=karzo,
),
)
await m.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -159,6 +159,8 @@ async def gpoto(e):
if not ult and e.is_reply:
gs = await e.get_reply_message()
ult = gs.sender_id
if not (ult or e.is_reply):
ult = e.chat_id
try:
okla = await ultroid_bot.download_profile_photo(
ult,

110
plugins/qrcode.py Normal file
View File

@@ -0,0 +1,110 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`qrcode <text/reply to text>`
Makes qrcode of text
•`addqr <reply image> <text>`
Makes qr of text and add it to image.
•`qrdecode <reply to qrcode>`
It decodes the qrcode.
"""
import os
import cv2
import qrcode
from PIL import Image
from telethon.tl.types import MessageMediaDocument as doc
from telethon.tl.types import MessageMediaPhoto as photu
from . import *
@ultroid_cmd(pattern="qrcode ?(.*)")
async def cd(e):
reply = await e.get_reply_message()
msg = e.pattern_match.group(1)
if reply and reply.text:
msg = reply.text
elif msg:
msg = msg
else:
return await eod(e, "`Give Some Text or Reply")
kk = await eor(e, "`processing`")
pfp = await ultroid_bot.get_profile_photos(ultroid_bot.uid)
img = "resources/extras/teamultroid.jpg"
if len(pfp) >= 1:
img = await ultroid_bot.download_media(pfp[0])
ok = Image.open(img)
logo = ok.resize((60, 60))
cod = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
cod.add_data(msg)
cod.make()
imgg = cod.make_image().convert("RGB")
pstn = ((imgg.size[0] - logo.size[0]) // 2, (imgg.size[1] - logo.size[1]) // 2)
imgg.paste(logo, pstn)
imgg.save(img)
await ultroid_bot.send_file(e.chat_id, img, support_stream=True)
await kk.delete()
os.remove(img)
@ultroid_cmd(pattern="addqr ?(.*)")
async def qrwater(e):
msg = e.pattern_match.group(1)
r = await e.get_reply_message()
if not (msg and r and r.media):
return await eod(e, "`Reply Any Media and Give Text`")
kk = await eor(e, "`processing`")
if isinstance(r.media, photu):
dl = await ultroid_bot.download_media(r.media)
elif isinstance(r.media, doc):
dl = await ultroid_bot.download_media(r, thumb=-1)
else:
return
img_bg = Image.open(dl)
qr = qrcode.QRCode(box_size=5)
qr.add_data(msg)
qr.make()
img_qr = qr.make_image()
pos = (img_bg.size[0] - img_qr.size[0], img_bg.size[1] - img_qr.size[1])
img_bg.paste(img_qr, pos)
img_bg.save(dl)
await ultroid_bot.send_file(e.chat_id, dl, support_stream=True)
await kk.delete()
os.remove(dl)
@ultroid_cmd(pattern="qrdecode$")
async def decod(e):
r = await e.get_reply_message()
if not (r and r.media):
return await eod(e, "`Reply to Qrcode Media`")
kk = await eor(e, "`processing`")
if isinstance(r.media, photu):
dl = await ultroid_bot.download_media(r.media)
elif isinstance(r.media, doc):
dl = await ultroid_bot.download_media(r, thumb=-1)
else:
return
im = cv2.imread(dl)
try:
det = cv2.QRCodeDetector()
tx, y, z = det.detectAndDecode(im)
await kk.edit("**Decoded Text:\n\n**" + tx)
except BaseException:
await kk.edit("`Reply To Media in Which Qr image present.`")
os.remove(dl)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

65
plugins/resize.py Normal file
View File

@@ -0,0 +1,65 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`{i}size <reply to media>`
To get size of it.
•`{i}resize <number> <number>`
To resize image on x, y axis.
eg. `{i}resize 690 960`
"""
from PIL import Image
from . import *
@ultroid_cmd(pattern="size$")
async def size(e):
r = await e.get_reply_message()
if not (r and r.media):
return await eor(e, "`Reply To image`")
k = await eor(e, "`Processing...`")
if hasattr(r.media, "document"):
img = await ultroid_bot.download_media(r, thumb=-1)
else:
img = await ultroid_bot.download_media(r.media)
im = Image.open(img)
x, y = im.size
await k.edit(f"Dimension Of This Image Is\n`{x} : {y}`")
os.remove(img)
@ultroid_cmd(pattern="resize ?(.*)")
async def size(e):
r = await e.get_reply_message()
if not (r and r.media):
return await eor(e, "`Reply To image`")
sz = e.pattern_match.group(1)
if not sz:
return await eod(f"Give Some Size To Resize, Like `{HNDLR}resize 720 1080` ")
k = await eor(e, "`Processing...`")
if hasattr(r.media, "document"):
img = await ultroid_bot.download_media(r, thumb=-1)
else:
img = await ultroid_bot.download_media(r.media)
sz = sz.split()
if not len(sz) == 2:
return await eod(f"Give Some Size To Resize, Like `{HNDLR}resize 720 1080` ")
x, y = int(sz[0]), int(sz[1])
im = Image.open(img)
ok = im.resize((x, y))
ok.save(img, format="PNG", optimize=True)
await ultroid_bot.send_file(e.chat_id, img)
os.remove(img)
await k.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -9,7 +9,8 @@
✘ Commands Available -
• `{i}saavn <search query>`
`search song on saavn`
Download songs from Saavn
"""
import os
@@ -28,7 +29,7 @@ async def siesace(e):
if not song:
return await eod(e, "`Give me Something to Search")
hmm = time.time()
lol = await eor(e, "`...`")
lol = await eor(e, "`Searching on Saavn...`")
sung = song.replace(" ", "%20")
url = f"https://jostapi.herokuapp.com/saavn?query={sung}"
try:
@@ -48,6 +49,7 @@ async def siesace(e):
await ultroid_bot.send_file(
e.chat_id,
okk,
caption="`" + title + "`" + "\n`From Saavn`",
attributes=[
DocumentAttributeAudio(
duration=int(duration),

View File

@@ -22,7 +22,10 @@ async def saf(e):
return await eod(
e, "Reply to Any Message to save it to ur saved messages", time=5
)
await ultroid_bot.send_message(e.sender_id, x)
MLA = e.sender_id
if not MLA:
MLA = ultroid_bot.uid
await ultroid_bot.send_message(MLA, x)
await eod(e, "Message saved to Your Pm/Saved Messages.", time=5)

View File

@@ -208,7 +208,7 @@ async def _(event):
if not x:
return await eor(event, "`Give something to search`")
uu = await eor(event, "`Processing...`")
z = requests.get("https://combot.org/telegram/stickers?q=" + x).text
z = request.get("https://combot.org/telegram/stickers?q=" + x).text
xx = b(z, "lxml")
title = xx.find_all("div", "sticker-pack__title")
link = xx.find_all("a", target="_blank")

View File

@@ -8,12 +8,6 @@
"""
✘ Commands Available -
• `{i}bash <cmds>`
Run linux commands on telegram.
• `{i}eval <cmds>`
Evaluate python commands on telegram.
• `{i}circle`
Reply to a audio song or gif to get video note.
@@ -37,46 +31,28 @@
• `{i}tr <dest lang code> <(reply to) a message>`
Get translated message.
• `{i}sysinfo`
Shows System Info.
"""
import asyncio
import io
import os
import sys
import time
import traceback
from asyncio.exceptions import TimeoutError
from os import remove
from pathlib import Path
import cv2
import emoji
from carbonnow import Carbon
from googletrans import Translator
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantsBots, User
from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantsBots
from telethon.tl.types import DocumentAttributeVideo as video
from telethon.tl.types import User
from telethon.utils import pack_bot_file_id
from . import *
from . import humanbytes as hb
@ultroid_cmd(
pattern="sysinfo$",
)
async def _(e):
x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
with open("neo.txt", "r") as neo:
p = (neo.read()).replace("\n\n", "")
ok = Carbon(code=p)
haa = await ok.save("neofetch")
await e.client.send_file(e.chat_id, haa)
remove("neofetch.jpg")
remove("neo.txt")
@ultroid_cmd(
pattern="tr",
)
@@ -145,7 +121,9 @@ async def _(event):
await eor(event, "**Current Chat ID:** `{}`".format(str(event.chat_id)))
@ultroid_cmd(pattern="bots ?(.*)")
@ultroid_cmd(
pattern="bots ?(.*)",
)
async def _(ult):
await ult.edit("`...`")
if ult.is_private:
@@ -188,7 +166,9 @@ async def _(ult):
await eor(ult, mentions)
@ultroid_cmd(pattern="hl")
@ultroid_cmd(
pattern="hl",
)
async def _(ult):
try:
input = ult.text.split(" ", maxsplit=1)[1]
@@ -214,71 +194,47 @@ async def _(e):
output = cv2.resize(im, dsize, interpolation=cv2.INTER_AREA)
cv2.imwrite("img.png", output)
thumb = "img.png"
os.remove(bbbb)
except TypeError:
thumb = "./resources/extras/new_thumb.jpg"
c = await a.download_media(
"resources/downloads/",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, z, toime, "Dɴʟᴀᴅɪɴɢ..."),
),
bbbb = "resources/extras/ultroid.jpg"
im = cv2.imread(bbbb)
dsize = (320, 320)
output = cv2.resize(im, dsize, interpolation=cv2.INTER_AREA)
cv2.imwrite("img.png", output)
thumb = "img.png"
c = await downloader(
"resources/downloads/" + a.file.name,
a.media.document,
z,
toime,
"Dɴʟᴀᴅɪɴɢ...",
)
await z.edit("**Dɴʟᴀᴅᴇᴅ...\nN Cɴᴇʀᴛɪɴɢ...**")
cmd = [
"ffmpeg",
"-i",
c,
"-acodec",
"libmp3lame",
"-ac",
"2",
"-ab",
"144k",
"-ar",
"44100",
"comp.mp3",
]
proess = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
await bash(
f'ffmpeg -i "{c.name}" -preset ultrafast -acodec libmp3lame -ac 2 -ab 144 -ar 44100 comp.mp3'
)
stdout, stderr = await proess.communicate()
stderr.decode().strip()
stdout.decode().strip()
mcd = [
"ffmpeg",
"-y",
"-i",
thumb,
"-i",
"comp.mp3",
"-c:a",
"copy",
"circle.mp4",
]
process = await asyncio.create_subprocess_exec(
*mcd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
await bash(
f'ffmpeg -y -i "{thumb}" -i comp.mp3 -preset ultrafast -c:a copy circle.mp4'
)
stdout, stderr = await process.communicate()
stderr.decode().strip()
stdout.decode().strip()
taime = time.time()
foile = await uploader("circle.mp4", "circle.mp4", taime, z, "Uᴘʟᴀᴅɪɴɢ...")
f = "circle.mp4"
metadata = extractMetadata(createParser(f))
duration = metadata.get("duration").seconds
height = metadata.get("height")
width = metadata.get("width")
attributes = [video(duration=duration, w=width, h=height, round_message=True)]
await e.client.send_file(
e.chat_id,
"circle.mp4",
foile,
thumb=thumb,
video_note=True,
reply_to=a,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, z, taime, "Uᴘʟᴀᴅɪɴɢ..."),
),
video_note=True,
attributes=attributes,
)
await z.delete()
os.system("rm resources/downloads/*")
os.system("rm circle.mp4 comp.mp3 img.png")
os.remove(bbbb)
elif a.document and a.document.mime_type == "video/mp4":
z = await eor(e, "**Cʀᴇᴀᴛɪɴɢ Vɪᴅᴇ Nᴛᴇ**")
c = await a.download_media("resources/downloads/")
@@ -286,7 +242,7 @@ async def _(e):
e.chat_id,
c,
video_note=True,
thumb="resources/extras/new_thumb.jpg",
thumb="resources/extras/ultroid.jpg",
reply_to=a,
)
await z.delete()
@@ -295,7 +251,9 @@ async def _(e):
return await eor(e, "**Reply to a gif or audio file only**")
@ultroid_cmd(pattern="ls ?(.*)")
@ultroid_cmd(
pattern="ls ?(.*)",
)
async def _(e):
path = Path(e.pattern_match.group(1))
if not path:
@@ -317,7 +275,7 @@ async def _(e):
text = []
apk = []
exe = []
zip = []
zip_ = []
book = []
for file in sorted(files):
if os.path.isdir(file):
@@ -326,7 +284,7 @@ async def _(e):
pyfiles.append("🐍 " + str(file))
elif str(file).endswith(".json"):
jsons.append("🔮 " + str(file))
elif str(file).endswith((".mkv", ".mp4", ".avi")):
elif str(file).endswith((".mkv", ".mp4", ".avi", ".gif")):
vdos.append("🎥 " + str(file))
elif str(file).endswith((".mp3", ".ogg", ".m4a")):
audios.append("🔊 " + str(file))
@@ -337,9 +295,9 @@ async def _(e):
elif str(file).endswith((".apk", ".xapk")):
apk.append("📲 " + str(file))
elif str(file).endswith(".exe"):
set.append("" + str(file))
exe.append("" + str(file))
elif str(file).endswith((".zip", ".rar")):
zip.append("🗜 " + str(file))
zip_.append("🗜 " + str(file))
elif str(file).endswith((".pdf", ".epub")):
book.append("📗 " + str(file))
elif "." in str(file)[1:]:
@@ -350,7 +308,7 @@ async def _(e):
*sorted(folders),
*sorted(pyfiles),
*sorted(jsons),
*sorted(zip),
*sorted(zip_),
*sorted(vdos),
*sorted(pics),
*sorted(audios),
@@ -362,6 +320,8 @@ async def _(e):
*sorted(otherfiles),
]
text = ""
fls, fos = 0, 0
flc, foc = 0, 0
for i in omk:
emoji = i.split()[0]
name = i.split(maxsplit=1)[1]
@@ -374,160 +334,30 @@ async def _(e):
size += os.path.getsize(fp)
if hb(size):
text += emoji + f" `{nam}`" + " `" + hb(size) + "`\n"
fos += size
else:
text += emoji + f" `{nam}`" + "\n"
foc += 1
else:
if hb(int(os.path.getsize(name))):
text += (
emoji + f" `{nam}`" + " `" + hb(int(os.path.getsize(name))) + "`\n"
)
fls += int(os.path.getsize(name))
else:
text += emoji + f" `{nam}`" + "\n"
flc += 1
tfos, tfls, ttol = hb(fos), hb(fls), hb(fos + fls)
if not hb(fos):
tfos = "0 B"
if not hb(fls):
tfls = "0 B"
if not hb(fos + fls):
ttol = "0 B"
text += f"\n\n`Folders` : `{foc}` : `{tfos}`\n`Files` : `{flc}` : `{tfls}`\n`Total` : `{flc+foc}` : `{ttol}`"
await eor(e, text)
@ultroid_cmd(
pattern="bash",
)
async def _(event):
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
f"Developer Restricted!\nIf you know what this does, and want to proceed\n\n `{HNDLR}setredis I_DEV True`\n\nThis Might Be Dangerous.",
)
return
xx = await eor(event, "`Processing...`")
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(xx, "`No cmd given`", time=10)
reply_to_id = event.message.id
if event.reply_to_msg_id:
reply_to_id = event.reply_to_msg_id
time.time() + 100
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await process.communicate()
OUT = f"**☞ BASH\n\n• COMMAND:**\n`{cmd}` \n\n"
e = stderr.decode()
if e:
OUT += f"**• ERROR:** \n`{e}`\n"
o = stdout.decode()
if not o:
o = "Success"
OUT += f"**• OUTPUT:**\n`{o}`"
else:
_o = o.split("\n")
o = "\n".join(_o)
OUT += f"**• OUTPUT:**\n`{o}`"
if len(OUT) > 4096:
ultd = OUT.replace("`", "").replace("*", "").replace("_", "")
with io.BytesIO(str.encode(ultd)) as out_file:
out_file.name = "bash.txt"
await event.client.send_file(
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
allow_cache=False,
caption=f"`{cmd}`",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eor(xx, OUT)
p = print # ignore: pylint
@ultroid_cmd(
pattern="eval",
)
async def _(event):
if len(event.text) > 5:
if not event.text[5] == " ":
return
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
f"Developer Restricted!\nIf you know what this does, and want to proceed\n\n {HNDLR}setredis I_DEV True\n\nThis Might Be Dangerous.",
)
return
xx = await eor(event, "`Processing ...`")
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(xx, "`Give some python cmd`", time=5)
if event.reply_to_msg_id:
reply_to_id = event.reply_to_msg_id
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, stderr, exc = None, None, None
reply_to_id = event.message.id
try:
await aexec(cmd, event)
except Exception:
exc = traceback.format_exc()
stdout = redirected_output.getvalue()
stderr = redirected_error.getvalue()
sys.stdout = old_stdout
sys.stderr = old_stderr
evaluation = ""
if exc:
evaluation = exc
elif stderr:
evaluation = stderr
elif stdout:
evaluation = stdout
else:
evaluation = "Success"
final_output = (
"__►__ **EVALPy**\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(
cmd,
evaluation,
)
)
if len(final_output) > 4096:
ultd = final_output.replace("`", "").replace("*", "").replace("_", "")
with io.BytesIO(str.encode(ultd)) as out_file:
out_file.name = "eval.txt"
await ultroid_bot.send_file(
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
allow_cache=False,
caption=f"```{cmd}```",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eor(xx, final_output)
async def aexec(code, event):
e = message = event
client = event.client
exec(
f"async def __aexec(e, client): "
+ "\n message = event = e"
+ "".join(f"\n {l}" for l in code.split("\n")),
)
return await locals()["__aexec"](e, e.client)
@ultroid_cmd(
pattern="sg ?(.*)",
)

View File

@@ -4,24 +4,35 @@
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}update`
See changelogs if any update is available.
"""
from . import *
from git import Repo
from telethon.tl.functions.channels import ExportMessageLinkRequest as GetLink
from . import *
@ultroid_cmd(pattern="update$")
async def _(e):
x = await updater()
m = await updater()
branch = (Repo.init()).active_branch
if x is not None:
if m:
x = await ultroid_bot.asst.send_file(
int(udB.get("LOG_CHANNEL")),
"resources/extras/inline.jpg",
caption="• **Update Available** •",
force_document=False,
buttons=Button.inline("Changelogs", data="changes"),
)
Link = (await ultroid_bot(GetLink(x.peer_id.channel_id, x.id))).link
await eor(
e,
f'<strong><a href="t.me/c/{x.peer_id.channel_id}/{x.id}">[ChangeLogs]</a></strong>',
f'<strong><a href="{Link}">[ChangeLogs]</a></strong>',
parse_mode="html",
link_preview=False,
)
@@ -38,7 +49,13 @@ async def _(e):
@owner
async def updava(event):
await event.delete()
await updater()
await ultroid_bot.asst.send_file(
int(udB.get("LOG_CHANNEL")),
"resources/extras/inline.jpg",
caption="• **Update Available** •",
force_document=False,
buttons=Button.inline("Changelogs", data="changes"),
)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -11,9 +11,6 @@
• `{i}kickme`
Leaves the group in which it is used.
• `{i}calc <equation>`
A simple calculator.
• `{i}date`
Show Calender.
@@ -55,9 +52,7 @@ import calendar
import html
import io
import os
import sys
import time
import traceback
from datetime import datetime as dt
import pytz
@@ -71,6 +66,7 @@ from telethon.tl.functions.channels import (
InviteToChannelRequest,
LeaveChannelRequest,
)
from telethon.tl.functions.contacts import GetBlockedRequest
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.functions.photos import GetUserPhotosRequest
from telethon.tl.types import Channel, Chat, InputMediaPoll, Poll, PollAnswer, User
@@ -83,7 +79,7 @@ TMP_DOWNLOAD_DIRECTORY = "resources/downloads/"
# Telegraph Things
telegraph = Telegraph()
telegraph.create_account(short_name="Ultroid")
telegraph.create_account(short_name=OWNER_NAME)
# ================================================================#
@@ -105,56 +101,6 @@ async def date(event):
ultroid = await eor(event, f"`{k}\n\n{d}`")
@ultroid_cmd(
pattern="calc",
)
async def _(event):
x = await eor(event, get_string("com_1"))
cmd = event.text.split(" ", maxsplit=1)[1]
event.message.id
if event.reply_to_msg_id:
event.reply_to_msg_id
wtf = f"print({cmd})"
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
redirected_error = sys.stderr = io.StringIO()
stdout, stderr, exc = None, None, None
try:
await aexec(wtf, event)
except Exception:
exc = traceback.format_exc()
stdout = redirected_output.getvalue()
stderr = redirected_error.getvalue()
sys.stdout = old_stdout
sys.stderr = old_stderr
evaluation = ""
if exc:
evaluation = exc
elif stderr:
evaluation = stderr
elif stdout:
evaluation = stdout
else:
evaluation = "`Something went wrong`"
final_output = """
**EQUATION**:
`{}`
**SOLUTION**:
`{}`
""".format(
cmd,
evaluation,
)
await x.edit(final_output)
async def aexec(code, event):
exec(f"async def __aexec(event): " + "".join(f"\n {l}" for l in code.split("\n")))
return await locals()["__aexec"](event)
@ultroid_cmd(
pattern="chatinfo(?: |$)(.*)",
)
@@ -242,7 +188,7 @@ async def stats(
unread_mentions += dialog.unread_mentions_count
unread += dialog.unread_count
stop_time = time.time() - start_time
ct = (await ultroid_bot(GetBlockedRequest(1, 0))).count
full_name = inline_mention(await ultroid_bot.get_me())
response = f"🔸 **Stats for {full_name}** \n\n"
response += f"**Private Chats:** {private_chats} \n"
@@ -257,7 +203,8 @@ async def stats(
response += f"** •• **`Creator: {creator_in_channels}` \n"
response += f"** •• **`Admin Rights: {admin_in_broadcast_channels - creator_in_channels}` \n"
response += f"**Unread:** {unread} \n"
response += f"**Unread Mentions:** {unread_mentions} \n\n"
response += f"**Unread Mentions:** {unread_mentions} \n"
response += f"**Blocked Users:** {ct}\n\n"
response += f"**__It Took:__** {stop_time:.02f}s \n"
await ok.edit(response)
@@ -312,7 +259,7 @@ async def _(event):
.get("result")
.get("key")
)
q = f"paste-{key}"
q = f"paste {key}"
reply_text = f"• **Pasted to Nekobin :** [Neko](https://nekobin.com/{key})\n• **Raw Url :** : [Raw](https://nekobin.com/raw/{key})"
try:
ok = await ultroid_bot.inline_query(asst.me.username, q)
@@ -362,18 +309,18 @@ async def _(event):
dc_id = "Need a Profile Picture to check this"
str(e)
caption = """<b>Exᴛʀᴀᴛᴇᴅ Dᴀᴛᴀʙᴀsᴇ Fʀᴍ Tᴇʟᴇɢʀᴀᴍ's Dᴀᴛᴀʙᴀsᴇ<b>
<b>••Tᴇʟᴇɢʀᴀᴍ ID</b>: <code>{}</code>
<b>••Pᴇʀᴍᴀɴᴇɴᴛ Lɪɴᴋ</b>: <a href='tg://user?id={}'>Click Here</a>
<b>••Fɪʀsᴛ Nᴀᴍᴇ</b>: <code>{}</code>
<b>••Sᴇɴᴅ Nᴀᴍᴇ</b>: <code>{}</code>
<b>••Bɪ</b>: <code>{}</code>
<b>••D ID</b>: <code>{}</code>
<b>••N. Oғ PғPs</b> : <code>{}</code>
<b>••Is Rᴇsᴛʀɪᴛᴇᴅ</b>: <code>{}</code>
<b>••Vᴇʀɪғɪᴇᴅ</b>: <code>{}</code>
<b>••Is A Bᴛ</b>: <code>{}</code>
<b>••Gʀᴘs Iɴ Cᴍᴍɴ</b>: <code>{}</code>
""".format(
<b>••Tᴇʟᴇɢʀᴀᴍ ID</b>: <code>{}</code>
<b>••Pᴇʀᴍᴀɴᴇɴᴛ Lɪɴᴋ</b>: <a href='tg://user?id={}'>Click Here</a>
<b>••Fɪʀsᴛ Nᴀᴍᴇ</b>: <code>{}</code>
<b>••Sᴇɴᴅ Nᴀᴍᴇ</b>: <code>{}</code>
<b>••Bɪ</b>: <code>{}</code>
<b>••D ID</b>: <code>{}</code>
<b>••N. Oғ PғPs</b> : <code>{}</code>
<b>••Is Rᴇsᴛʀɪᴛᴇᴅ</b>: <code>{}</code>
<b>••Vᴇʀɪғɪᴇᴅ</b>: <code>{}</code>
<b>••Is A Bᴛ</b>: <code>{}</code>
<b>••Gʀᴘs Iɴ Cᴍᴍɴ</b>: <code>{}</code>
""".format(
user_id,
user_id,
first_name,
@@ -386,6 +333,14 @@ async def _(event):
replied_user.user.bot,
common_chats,
)
chk = is_gbanned(user_id)
if chk:
r = get_gban_reason(user_id)
caption += "<b>••Gʟʙᴀʟʟʏ Bᴀɴɴᴇᴅ</b>: <code>True</code>"
if r:
caption += f"<b>Rᴇᴀsɴ</b>: <code>{r}</code>"
else:
caption += "<b>••Gʟʙᴀʟʟʏ Bᴀɴɴᴇᴅ</b>: <code>False</code>"
message_id_to_reply = event.message.reply_to_msg_id
if not message_id_to_reply:
message_id_to_reply = event.message.id

View File

@@ -21,13 +21,16 @@ from . import *
@ultroid_cmd(pattern="get")
async def get_var(event):
x = await eor(event, get_string("com_1"))
if not event.out and not is_fullsudo(event.sender_id):
return await eod(event, "`This Command Is Sudo Restricted.`")
try:
opt = event.text.split(" ", maxsplit=2)[1]
except IndexError:
return await x.edit("get what?")
if len(event.text) > 4:
if " " in event.text[4]:
opt = event.text.split(" ", maxsplit=2)[1]
else:
return
else:
return
x = await eor(event, get_string("com_1"))
if not opt == "keys":
try:
varname = event.text.split(" ", maxsplit=2)[2]

View File

@@ -28,8 +28,11 @@
Remove access of Voice Chat Bot.
• **Voice Chat Bot Commands**
`/play ytsearch:song name`
`/play ytsearch : song-name`
`/play youtube link`
`/current`
`/skip`
`/exitVc`
"""
@@ -63,6 +66,7 @@ async def _(e):
try:
await e.client(stopvc(await get_call(e)))
await eor(e, "`Voice Chat Stopped...`")
vcdyno("off")
except Exception as ex:
await eor(e, f"`{str(ex)}`")
@@ -73,9 +77,11 @@ async def _(e):
async def _(e):
zz = await eor(e, "`VC bot started...`")
er, out = await bash("npm start")
LOGS.warning(er)
LOGS.info(er)
LOGS.info(out)
await zz.edit(f"Failed {er}")
vcdyno("on")
if er:
await zz.edit(f"Failed {er}\n\n{out}")
@ultroid_cmd(
@@ -197,4 +203,14 @@ async def _(e):
return await eod(xx, f"`{str(ex)}`", time=5)
@asst_cmd("exitVc")
async def evc(e):
if e.sender.id == ultroid_bot.uid:
vcdyno("off")
elif is_sudo(e.sender.id):
vcdyno("off")
elif is_vcsudo(e.sender.id):
vcdyno("off")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

177
plugins/warn.py Normal file
View File

@@ -0,0 +1,177 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available
•`{i}warn <reply to user> <reason>`
Gives Warn.
•`{i}resetwarn <reply to user>`
To reset All Warns.
•`{i}warns <reply to user>`
To Get List of Warnings of a user.
•`{i}setwarn <warn count> | <ban/mute/kick>`
Set Number in warn count for warnings
After putting " | " mark put action like ban/mute/kick
Its Default 3 kick
Example : `setwarn 5 | mute`
"""
from pyUltroid.functions.warn_db import *
from telethon.utils import get_display_name
from . import *
@ultroid_cmd(pattern="warn ?(.*)", groups_only=True, admins_only=True)
async def warn(e):
reply = await e.get_reply_message()
if len(e.text) > 5:
if " " not in e.text[5]:
return
if reply:
user = reply.from_id.user_id
reason = "unknown"
if e.pattern_match.group(1):
reason = e.text[5:]
else:
try:
user = e.text.split()[1]
if user.startswith("@"):
ok = await ultroid_bot.get_entity(user)
user = ok.id
else:
user = int(user)
except BaseException:
return await eod(e, "Reply To A User")
try:
reason = e.text.split(maxsplit=2)[-1]
except BaseException:
reason = "unknown"
count, r = warns(e.chat_id, user)
if not r:
r = reason
else:
r = r + "|$|" + reason
try:
x = udB.get("SETWARN")
number, action = int(x.split()[0]), x.split()[1]
except BaseException:
number, action = 3, "kick"
if ("ban" or "kick" or "mute") not in action:
action = "kick"
if count + 1 >= number:
if "ban" in action:
try:
await ultroid_bot.edit_permissions(e.chat_id, user, view_messages=False)
except BaseException:
return await eod(e, "`Something Went Wrong.`")
elif "kick" in action:
try:
await ultroid_bot.kick_participant(e.chat_id, user)
except BaseException:
return await eod(e, "`Something Went Wrong.`")
elif "mute" in action:
try:
await ultroid_bot.edit_permissions(
e.chat_id, user, until_date=None, send_messages=False
)
except BaseException:
return await eod(e, "`Something Went Wrong.`")
add_warn(e.chat_id, user, count + 1, r)
c, r = warns(e.chat_id, user)
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
r = r.split("|$|")
text = f"User {user} Got {action} Due to {count+1} Warns.\n\n"
for x in range(c):
text += f"•**{x+1}.** {r[x]}\n"
await eor(e, text)
return reset_warn(e.chat_id, ok.id)
add_warn(e.chat_id, user, count + 1, r)
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
await eor(
e,
f"**WARNING :** {count+1}/{number}\n**To :**{user}\n**Be Careful !!!**\n\n**Reason** : {reason}",
)
@ultroid_cmd(pattern="resetwarn ?(.*)", groups_only=True, admins_only=True)
async def rwarn(e):
reply = await e.get_reply_message()
if reply:
user = reply.from_id.user_id
else:
try:
user = e.text.split()[1]
if user.startswith("@"):
ok = await ultroid_bot.get_entity(user)
user = ok.id
else:
user = int(user)
except BaseException:
return await eor(e, "Reply To user")
reset_warn(e.chat_id, user)
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
await eor(e, f"Cleared All Warns of {user}.")
@ultroid_cmd(pattern="warns ?(.*)", groups_only=True, admins_only=True)
async def twarns(e):
reply = await e.get_reply_message()
if reply:
user = reply.from_id.user_id
else:
try:
user = e.text.split()[1]
if user.startswith("@"):
ok = await ultroid_bot.get_entity(user)
user = ok.id
else:
user = int(user)
except BaseException:
return await eod(e, "Reply To A User")
c, r = warns(e.chat_id, user)
if c and r:
ok = await ultroid_bot.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
r = r.split("|$|")
text = f"User {user} Got {c} Warns.\n\n"
for x in range(c):
text += f"•**{x+1}.** {r[x]}\n"
await eor(e, text)
else:
await eor(e, "`No Warnings`")
@ultroid_cmd(pattern="setwarn ?(.*)")
async def warnset(e):
ok = e.pattern_match.group(1)
if not ok:
return await eor(e, "stuff")
if "|" in ok:
try:
number, action = int(ok.split()[0]), ok.split()[1]
except BaseException:
return await eod(e, "`Incorrect Format`")
if ("ban" or "kick" or "mute") not in action:
return await eod(e, "`Only mute / ban / kick option suported`")
udB.set("SETWARN", f"{number} {action}")
return await eor(
e, f"Done Your Warn Count is now {number} and Action is {action}"
)
else:
await eod(e, "`Incorrect Format`")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -13,7 +13,10 @@
"""
import io
import requests
from selenium import webdriver
from . import *
@@ -38,19 +41,32 @@ async def webss(event):
r2 = requests.get("http://" + xurl)
except requests.ConnectionError:
return await eod(xx, "Invalid URL!", time=5)
lnk = f"https://shot.screenshotapi.net/screenshot?url={xurl}"
ok = requests.get(lnk).json()
try:
sshot = ok["screenshot"]
except BaseException:
return await eod(xx, "Something Went Wrong :(", time=10)
await xx.reply(
f"**WebShot Generated**\n**URL**: {xurl}",
file=sshot,
link_preview=False,
force_document=True,
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--test-type")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.binary_location = "/usr/bin/google-chrome"
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(xurl)
height = driver.execute_script(
"return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);"
)
width = driver.execute_script(
"return Math.max(document.body.scrollWidth, document.body.offsetWidth, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth);"
)
driver.set_window_size(width + 100, height + 100)
im_png = driver.get_screenshot_as_png()
driver.close()
with io.BytesIO(im_png) as sshot:
sshot.name = "webshot.png"
await xx.reply(
f"**WebShot Generated**\n**URL**: {xurl}",
file=sshot,
link_preview=False,
force_document=True,
)
await xx.delete()

View File

@@ -13,7 +13,6 @@
"""
import asyncio
import time
from telethon.errors.rpcerrorlist import BotInlineDisabledError as dis
@@ -36,19 +35,17 @@ async def _(event):
bb = await event.get_reply_message()
if bb.media:
ccc = time.time()
file_name = await event.client.download_media(
bb,
"./resources/downloads/",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
xx,
ccc,
"Downloading...",
),
),
)
try:
naam = await downloader(
bb.file.name,
bb.media.document,
xx,
ccc,
"Downloading " + bb.file.name + "...",
)
file_name = naam.name
except BaseException:
file_name = await event.client.download_media(bb)
else:
return await eod(xx, "`Reply to media file`", time=5)
try:

108
plugins/youtube.py Normal file
View File

@@ -0,0 +1,108 @@
"""
✘ Commands Available -
• `{i}yta <(youtube) link>`
Download audio from the link.
• `{i}ytv <(youtube) link>`
Download video from the link.
• `{i}ytsa <(youtube) search query>`
Search and download audio from youtube.
• `{i}ytsv <(youtube) link>`
Search and download video from youtube.
"""
from youtube_dl import YoutubeDL
from . import *
@ultroid_cmd(pattern="yt(a|v|sa|sv) ?(.*)")
async def download_from_youtube_(event):
opt = event.pattern_match.group(1)
if opt == "a":
ytd = YoutubeDL(
{
"format": "bestaudio",
"writethumbnail": True,
"addmetadata": True,
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "%(id)s.mp3",
}
)
url = event.pattern_match.group(2)
if not url:
return await eor(event, "Give me a (youtube) URL to download audio from!")
try:
request.get(url)
except BaseException:
return await eor(event, "`Give A Direct Audio Link To Download`")
xx = await eor(event, get_string("com_1"))
elif opt == "v":
ytd = YoutubeDL(
{
"format": "best",
"writethumbnail": True,
"addmetadata": True,
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "%(id)s.mp4",
}
)
url = event.pattern_match.group(2)
if not url:
return await eor(event, "Give me a (youtube) URL to download video from!")
try:
request.get(url)
except BaseException:
return await eor(event, "`Give A Direct Video Link To Download`")
xx = await eor(event, get_string("com_1"))
elif opt == "sa":
ytd = YoutubeDL(
{
"format": "bestaudio",
"writethumbnail": True,
"addmetadata": True,
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "%(id)s.mp3",
}
)
try:
query = event.text.split(" ", 1)[1]
except IndexError:
return await eor(
event, "Give me a (youtube) search query to download audio from!"
)
xx = await eor(event, "`Searching on YouTube...`")
url = await get_yt_link(query)
await xx.edit("`Downloading audio song...`")
elif opt == "sv":
ytd = YoutubeDL(
{
"format": "best",
"writethumbnail": True,
"addmetadata": True,
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "%(id)s.mp4",
}
)
try:
query = event.text.split(" ", 1)[1]
except IndexError:
return await eor(
event, "Give me a (youtube) search query to download video from!"
)
xx = await eor(event, "`Searching YouTube...`")
url = await get_yt_link(query)
await xx.edit("`Downloading video song...`")
else:
return
await download_yt(xx, event, url, ytd)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -8,87 +8,158 @@
"""
✘ Commands Available
• `{i}zip <reply to file>
zip the replied file
• `{i}unzip <reply to zip file>`
unzip the replied file.
• `{i}azip <reply to file>`
add file to batch for batch upload zip
• `{i}dozip`
upload batch zip the files u added from `{i}azip`
"""
import asyncio
import glob
import os
import time
import zipfile
from . import *
@ultroid_cmd(pattern="unzip$")
async def _(ult):
if not ult.is_reply:
return await eor(ult, "`Reply to a Zipfile..`")
gt = await ult.get_reply_message()
msg = await eor(ult, "`Processing...`")
if not (
gt.media
and gt.media.document
and gt.media.document.mime_type == "application/zip"
):
return await msg.edit("`Reply to a Zipfile...`")
k = time.time()
d = "resources/downloads/"
dnl = await ultroid_bot.download_media(
gt,
d,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, msg, k, "Downloading to my Storage..."),
),
)
place = "resources/downloads/extracted/"
with zipfile.ZipFile(dnl, "r") as zip_ref:
zip_ref.extractall(place)
filename = sorted(get_lst_of_files(place, []))
await msg.edit("Unzipping now")
THUMB = udB.get("THUMB_URL")
Enum = 0
Elist = "**Errors Occured while Unzip**\n\n"
for single_file in filename:
if os.path.exists(single_file):
caption_rts = os.path.basename(single_file)
try:
await ultroid_bot.send_file(
ult.chat_id,
single_file,
thumb=THUMB,
caption=f"**File Name :** {caption_rts}",
force_document=True,
reply_to=ult.message.id,
)
except Exception as e:
Enum += 1
Elist += f"{Enum}. {caption_rts}\n- __{str(e)}__\n"
os.remove(single_file)
os.remove(dnl)
await msg.edit(f"**Unzipped `{len(filename)-Enum}/{len(filename)}` Files**")
if Enum > 0:
if len(Elist) < 4096:
await ultroid_bot.send_message(Var.LOG_CHANNEL, Elist)
else:
file = open("UnzipError.txt", "w").write(Elist)
file.close()
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
"UnzipError.txt",
caption=f"`Error Occured on Unzip cmd",
@ultroid_cmd(pattern="zip$")
async def zipp(event):
reply = await event.get_reply_message()
t = time.time()
if not reply:
await eor(event, "Reply to any media/Document.")
return
xx = await eor(event, "`Processing...`")
if reply.media:
if hasattr(reply.media, "document"):
file = reply.media.document
image = await downloader(
reply.file.name, reply.media.document, xx, t, "Downloading..."
)
os.remove("UnzipError.txt")
file = image.name
else:
file = await event.download_media(reply)
inp = file.replace(file.split(".")[-1], "zip")
await bash(f"zip -r {inp} {file}")
k = time.time()
xxx = await uploader(inp, inp, k, xx, "Uploading...")
await ultroid_bot.send_file(
event.chat_id,
xxx,
force_document=True,
thumb="resources/extras/ultroid.jpg",
caption=f"`{xxx.name}`",
reply_to=reply,
)
os.remove(inp)
os.remove(file)
await xx.delete()
def get_lst_of_files(input_directory, output_lst):
filesinfolder = os.listdir(input_directory)
for file_name in filesinfolder:
current_file_name = os.path.join(input_directory, file_name)
if os.path.isdir(current_file_name):
return get_lst_of_files(current_file_name, output_lst)
output_lst.append(current_file_name)
return output_lst
@ultroid_cmd(pattern="unzip$")
async def unzipp(event):
reply = await event.get_reply_message()
t = time.time()
if not reply:
await eor(event, "Reply to any media/Document.")
return
xx = await eor(event, "`Processing...`")
if reply.media:
if hasattr(reply.media, "document"):
file = reply.media.document
mime_type = file.mime_type
if "application" not in mime_type:
return await xx.edit("`Reply To zipped File`")
image = await downloader(
reply.file.name, reply.media.document, xx, t, "Downloading..."
)
file = image.name
if not file.endswith(("zip", "rar", "exe")):
return await xx.edit("`Reply To zip File Only`")
else:
return await xx.edit("`Reply to zip file only`")
if not os.path.isdir("unzip"):
os.mkdir("unzip")
else:
os.system("rm -rf unzip")
os.mkdir("unzip")
await bash(f"7z x {file} -aoa -ounzip")
ok = glob.glob("unzip/*")
k = []
for x in ok:
if os.path.isdir(x):
k.append(x)
break
if k:
await xx.edit(
"Your Unzipped File Saved in `unzip` folder.\nDo `{i}ls unzip` and browse storage\nUse `{i}ul <path>` To upload.".format(
i=HNDLR
)
)
else:
for x in ok:
k = time.time()
xxx = await uploader(x, x, k, xx, "Uploading...")
await ultroid_bot.send_file(
event.chat_id,
xxx,
force_document=True,
thumb="resources/extras/ultroid.jpg",
caption=f"`{xxx.name}`",
)
await xx.delete()
@ultroid_cmd(pattern="addzip$")
async def azipp(event):
reply = await event.get_reply_message()
t = time.time()
if not reply:
await eor(event, "Reply to any media/Document.")
return
xx = await eor(event, "`Processing...`")
if not os.path.isdir("zip"):
os.mkdir("zip")
if reply.media:
if hasattr(reply.media, "document"):
file = reply.media.document
image = await downloader(
"zip/" + reply.file.name, reply.media.document, xx, t, "Downloading..."
)
file = image.name
else:
file = await event.download_media(reply.media, "zip/")
await xx.edit(
f"Downloaded `{file}` succesfully\nNow Reply To Other Files To Add And Zip all at once"
)
@ultroid_cmd(pattern="dozip$")
async def do_zip(event):
if not os.path.isdir("zip"):
return await eor(
event, "First All Files Via {i}addzip then doZip to zip all files at one."
)
xx = await eor(event, "`processing`")
await bash(f"zip -r ultroid.zip zip/*")
k = time.time()
xxx = await uploader("ultroid.zip", "ultroid.zip", k, xx, "Uploading...")
await ultroid_bot.send_file(
event.chat_id,
xxx,
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
os.system("rm -rf zip")
os.remove("ultroid.zip")
await xx.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})