id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
5,608 | from . import *
START = """
🪅 **Help Menu** 🪅
✘ /start : Check I am Alive or not.
✘ /help : Get This Message.
✘ /repo : Get Bot's Repo..
🧑💻 Join **@TeamUltroid**
"""
def get_buttons():
async def helpish(event):
if not event.is_private:
url = f"https://t.me/{asst.me.username}?start=start"
return await event.reply(
"Contact me in PM for help!", buttons=Button.url("Click me for Help", url)
)
if str(event.sender_id) in owner_and_sudos() and (
udB.get_key("DUAL_MODE") and (udB.get_key("DUAL_HNDLR") == "/")
):
return
await event.reply(START, buttons=get_buttons()) | null |
5,609 | from . import *
def get_buttons():
BTTS = []
keys = STRINGS.copy()
while keys:
BT = []
for i in list(keys)[:2]:
text = f"{MNGE} {i} {MNGE}"
BT.append(Button.inline(text, f"hlp_{i}"))
del keys[i]
BTTS.append(BT)
url = f"https://t.me/{asst.me.username}?startgroup=true"
BTTS.append([Button.url("Add me to Group", url)])
return BTTS
async def ehwhshd(e):
buttons = get_buttons()
buttons.append([Button.inline("<< Back", "open")])
await e.edit(buttons=buttons) | null |
5,610 | from . import *
START = """
🪅 **Help Menu** 🪅
✘ /start : Check I am Alive or not.
✘ /help : Get This Message.
✘ /repo : Get Bot's Repo..
🧑💻 Join **@TeamUltroid**
"""
def get_buttons():
BTTS = []
keys = STRINGS.copy()
while keys:
BT = []
for i in list(keys)[:2]:
text = f"{MNGE} {i} {MNGE}"
BT.append(Button.inline(text, f"hlp_{i}"))
del keys[i]
BTTS.append(BT)
url = f"https://t.me/{asst.me.username}?startgroup=true"
BTTS.append([Button.url("Add me to Group", url)])
return BTTS
async def home_aja(e):
await e.edit(START, buttons=get_buttons()) | null |
5,611 | from . import *
STRINGS = {"Admintools": ADMINTOOLS, "locks": LOCKS, "Utils": UTILITIES, "Misc": MISC}
async def do_something(event):
match = event.pattern_match.group(1).strip().decode("utf-8")
await event.edit(STRINGS[match], buttons=Button.inline("<< Back", "mnghome")) | null |
5,612 | import re
from . import *
STRINGS = {
1: """🎇 **Thanks for Deploying Ultroid Userbot!**
• Here, are the Some Basic stuff from, where you can Know, about its Usage.""",
2: """🎉** About Ultroid**
🧿 Ultroid is Pluggable and powerful Telethon Userbot, made in Python from Scratch. It is Aimed to Increase Security along with Addition of Other Useful Features.
❣ Made by **@TeamUltroid**""",
3: """**💡• FAQs •**
-> [Username Tracker](https://t.me/UltroidUpdates/24)
-> [Keeping Custom Addons Repo](https://t.me/UltroidUpdates/28)
-> [Disabling Deploy message](https://t.me/UltroidUpdates/27)
-> [Setting up TimeZone](https://t.me/UltroidUpdates/22)
-> [About Inline PmPermit](https://t.me/UltroidUpdates/21)
-> [About Dual Mode](https://t.me/UltroidUpdates/18)
-> [Custom Thumbnail](https://t.me/UltroidUpdates/13)
-> [About FullSudo](https://t.me/UltroidUpdates/11)
-> [Setting Up PmBot](https://t.me/UltroidUpdates/2)
-> [Also Check](https://t.me/UltroidUpdates/14)
**• To Know About Updates**
- Join @TeamUltroid.""",
4: f"""• `To Know All Available Commands`
- `{HNDLR}help`
- `{HNDLR}cmds`""",
5: """• **For Any Other Query or Suggestion**
- Move to **@UltroidSupportChat**.
• Thanks for Reaching till END.""",
}
async def init_depl(e):
CURRENT = int(e.data_match.group(1))
if CURRENT == 5:
return await e.edit(
STRINGS[5],
buttons=Button.inline("<< Back", "initbk_4"),
link_preview=False,
)
await e.edit(
STRINGS[CURRENT],
buttons=[
Button.inline("<<", f"initbk_{str(CURRENT - 1)}"),
Button.inline(">>", f"initft_{str(CURRENT + 1)}"),
],
link_preview=False,
) | null |
5,613 | import re
from . import *
STRINGS = {
1: """🎇 **Thanks for Deploying Ultroid Userbot!**
• Here, are the Some Basic stuff from, where you can Know, about its Usage.""",
2: """🎉** About Ultroid**
🧿 Ultroid is Pluggable and powerful Telethon Userbot, made in Python from Scratch. It is Aimed to Increase Security along with Addition of Other Useful Features.
❣ Made by **@TeamUltroid**""",
3: """**💡• FAQs •**
-> [Username Tracker](https://t.me/UltroidUpdates/24)
-> [Keeping Custom Addons Repo](https://t.me/UltroidUpdates/28)
-> [Disabling Deploy message](https://t.me/UltroidUpdates/27)
-> [Setting up TimeZone](https://t.me/UltroidUpdates/22)
-> [About Inline PmPermit](https://t.me/UltroidUpdates/21)
-> [About Dual Mode](https://t.me/UltroidUpdates/18)
-> [Custom Thumbnail](https://t.me/UltroidUpdates/13)
-> [About FullSudo](https://t.me/UltroidUpdates/11)
-> [Setting Up PmBot](https://t.me/UltroidUpdates/2)
-> [Also Check](https://t.me/UltroidUpdates/14)
**• To Know About Updates**
- Join @TeamUltroid.""",
4: f"""• `To Know All Available Commands`
- `{HNDLR}help`
- `{HNDLR}cmds`""",
5: """• **For Any Other Query or Suggestion**
- Move to **@UltroidSupportChat**.
• Thanks for Reaching till END.""",
}
async def ineiq(e):
CURRENT = int(e.data_match.group(1))
if CURRENT == 1:
return await e.edit(
STRINGS[1],
buttons=Button.inline("Start Back >>", "initft_2"),
link_preview=False,
)
await e.edit(
STRINGS[CURRENT],
buttons=[
Button.inline("<<", f"initbk_{str(CURRENT - 1)}"),
Button.inline(">>", f"initft_{str(CURRENT + 1)}"),
],
link_preview=False,
) | null |
5,614 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def _(e):
ok = (e.data_match.group(1)).decode("UTF-8")
index = None
if "|" in ok:
ok, index = ok.split("|")
with open(ok, "r") as hmm:
_, key = await get_paste(hmm.read())
link = f"https://spaceb.in/{key}"
raw = f"https://spaceb.in/api/v1/documents/{key}/raw"
if not _:
return await e.answer(key[:30], alert=True)
if ok.startswith("addons"):
key = "Addons"
elif ok.startswith("vcbot"):
key = "VCBot"
else:
key = "Official"
data = f"uh_{key}_"
if index is not None:
data += f"|{index}"
await e.edit(
"",
buttons=[
[Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)],
[Button.inline("« Bᴀᴄᴋ", data=data)],
],
)
async def _(e):
if not e.is_private:
return
url = GDrive._create_token_file()
await e.edit("Go to the below link and send the code!")
async with asst.conversation(e.sender_id) as conv:
await conv.send_message(url)
code = await conv.get_response()
if GDrive._create_token_file(code=code.text):
await conv.send_message(
"`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`",
buttons=Button.inline("Main Menu", data="setter"),
)
else:
await conv.send_message("Wrong code! Click authorise again.")
async def _(e):
if not e.is_private:
return
msg = (
"Send your FOLDER ID\n\n"
+ "For FOLDER ID:\n"
+ "1. Open Google Drive App.\n"
+ "2. Create Folder.\n"
+ "3. Make that folder public.\n"
+ "4. Send link of that folder."
)
await e.delete()
async with asst.conversation(e.sender_id, timeout=150) as conv:
await conv.send_message(msg)
repl = await conv.get_response()
id = repl.text
if id.startswith("https"):
id = id.split("?id=")[-1]
udB.set_key("GDRIVE_FOLDER_ID", id)
await repl.reply(
"`Success.`",
buttons=get_back_button("gdrive"),
)
async def _(e):
if not e.is_private:
return
await e.edit(
"Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)",
buttons=[
[
Button.inline("Folder ID", data="folderid"),
Button.inline("Authorise", data="authorise"),
],
[Button.inline("« Back", data="cbs_otvars")],
],
link_preview=False,
)
async def _(e):
udB.del_key("TAG_LOG")
await e.answer("Done!!! Tag Logger has been turned Off")
async def name(event):
await event.delete()
pru = event.sender_id
var = "PM_TEXT"
name = "PM Text"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
buttons=get_back_button("cbs_pmcstm"),
)
async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
)
async def name(event):
await event.delete()
pru = event.sender_id
var = "STARTMSG"
name = "Bot Welcome Message:"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_chatbot"),
)
async def send(eve):
key, name = (eve.data_match.group(1)).decode("UTF-8").split("_")
thumb = "resources/extras/inline.jpg"
await eve.answer("■ Sending ■")
data = f"uh_{key}_"
index = None
if "|" in name:
name, index = name.split("|")
key = "plugins" if key == "Official" else key.lower()
plugin = f"{key}/{name}.py"
_ = f"pasta-{plugin}"
if index is not None:
data += f"|{index}"
_ += f"|{index}"
buttons = [
[
Button.inline(
"« Pᴀsᴛᴇ »",
data=_,
)
],
[
Button.inline("« Bᴀᴄᴋ", data=data),
],
]
try:
await eve.edit(file=plugin, thumb=thumb, buttons=buttons)
except Exception as er:
await eve.answer(str(er), alert=True) | null |
5,615 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
from .. import *
async def Carbon(
code,
base_url="https://carbonara.solopov.dev/api/cook",
file_name="ultroid",
download=False,
rayso=False,
**kwargs,
):
if rayso:
base_url = "https://rayso-api-desvhu-33.koyeb.app/generate"
kwargs["text"] = code
kwargs["theme"] = kwargs.get("theme", "breeze")
kwargs["darkMode"] = kwargs.get("darkMode", True)
kwargs["title"] = kwargs.get("title", "Ultroid")
else:
kwargs["code"] = code
con = await async_searcher(base_url, post=True, json=kwargs, re_content=True)
if not download:
file = BytesIO(con)
file.name = file_name + ".jpg"
else:
try:
return json_parser(con.decode())
except Exception:
pass
file = file_name + ".jpg"
with open(file, "wb") as f:
f.write(con)
return file
async def changes(okk):
match = okk.data_match.group(1).decode("utf-8")
await okk.answer(get_string("clst_3"))
repo = Repo.init()
button = [[Button.inline("Update Now", data="updatenow")]]
changelog, tl_chnglog = await gen_chlog(
repo, f"HEAD..upstream/{repo.active_branch}"
)
cli = "\n\nClick the below button to update!"
if not match:
try:
if len(tl_chnglog) > 700:
tl_chnglog = f"{tl_chnglog[:700]}..."
button.append([Button.inline("View Complete", "changesall")])
await okk.edit("• Writing Changelogs 📝 •")
img = await Carbon(
file_name="changelog",
code=tl_chnglog,
backgroundColor=choice(ATRA_COL),
language="md",
)
return await okk.edit(
f"**• Ultroid Userbot •**{cli}", file=img, buttons=button
)
except Exception as er:
LOGS.exception(er)
changelog_str = changelog + cli
if len(changelog_str) > 1024:
await okk.edit(get_string("upd_4"))
await asyncio.sleep(2)
with open("ultroid_updates.txt", "w+") as file:
file.write(tl_chnglog)
await okk.edit(
get_string("upd_5"),
file="ultroid_updates.txt",
buttons=button,
)
remove("ultroid_updates.txt")
return
await okk.edit(
changelog_str,
buttons=button,
parse_mode="html",
) | null |
5,616 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
_buttons = {
"otvars": {
"text": "Other Variables to set for @TeamUltroid:",
"buttons": [
[
Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"),
Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"),
],
[
Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ", data="sudo"),
Button.inline("Hᴀɴᴅʟᴇʀ", data="hhndlr"),
],
[
Button.inline("Exᴛʀᴀ Pʟᴜɢɪɴs", data="plg"),
Button.inline("Aᴅᴅᴏɴs", data="eaddon"),
],
[
Button.inline("Eᴍᴏᴊɪ ɪɴ Hᴇʟᴘ", data="emoj"),
Button.inline("Sᴇᴛ ɢDʀɪᴠᴇ", data="gdrive"),
],
[
Button.inline("Iɴʟɪɴᴇ Pɪᴄ", data="inli_pic"),
Button.inline("Sᴜᴅᴏ HNDLR", data="shndlr"),
],
[Button.inline("Dᴜᴀʟ Mᴏᴅᴇ", "cbs_oofdm")],
[Button.inline("« Bᴀᴄᴋ", data="setter")],
],
},
"sfban": {
"text": "SuperFban Settings:",
"buttons": [
[Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")],
[Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="abs_sfexf")],
[Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
],
},
"apauto": {
"text": "This'll auto approve on outgoing messages",
"buttons": [
[Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")],
[Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")],
[Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
],
},
"alvcstm": {
"text": f"Customise your {HNDLR}alive. Choose from the below options -",
"buttons": [
[Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="abs_alvtx")],
[Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")],
[Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")],
[Button.inline("« Bᴀᴄᴋ", data="setter")],
],
},
"pmcstm": {
"text": "Customise your PMPERMIT Settings -",
"buttons": [
[
Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"),
Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"),
],
[
Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="cbs_apauto"),
Button.inline("PMLOGGER", data="pml"),
],
[
Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"),
Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"),
],
[Button.inline("PMPermit Type", data="cbs_pmtype")],
[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")],
],
},
"pmtype": {
"text": "Select the type of PMPermit needed.",
"buttons": [
[Button.inline("Inline", data="inpm_in")],
[Button.inline("Normal", data="inpm_no")],
[Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
],
},
"ppmset": {
"text": "PMPermit Settings:",
"buttons": [
[Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")],
[Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")],
[Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="cbs_pmcstm")],
[Button.inline("« Bᴀᴄᴋ", data="setter")],
],
},
"chatbot": {
"text": "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)",
"buttons": [
[
Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot"),
Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot"),
],
[
Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel"),
Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew"),
],
[Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")],
[Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")],
[Button.inline("« Bᴀᴄᴋ", data="setter")],
],
},
"vcb": {
"text": "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)",
"buttons": [
[Button.inline("VC Sᴇssɪᴏɴ", data="abs_vcs")],
[Button.inline("« Bᴀᴄᴋ", data="setter")],
],
},
"oofdm": {
"text": "About [Dual Mode](https://t.me/UltroidUpdates/18)",
"buttons": [
[
Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof"),
Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof"),
],
[Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")],
[Button.inline("« Back", data="cbs_otvars")],
],
},
"apiset": {
"text": get_string("ast_1"),
"buttons": [
[Button.inline("Remove.bg API", data="abs_rmbg")],
[Button.inline("DEEP API", data="abs_dapi")],
[Button.inline("OCR API", data="abs_oapi")],
[Button.inline("« Back", data="setter")],
],
},
}
async def _edit_to(event):
match = event.data_match.group(1).decode("utf-8")
data = _buttons.get(match)
if not data:
return
await event.edit(data["text"], buttons=data["buttons"], link_preview=False) | null |
5,617 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
_convo = {
"rmbg": {
"var": "RMBG_API",
"name": "Remove.bg API Key",
"text": get_string("ast_2"),
"back": "cbs_apiset",
},
"dapi": {
"var": "DEEP_AI",
"name": "Deep AI Api Key",
"text": "Get Your Deep Api from deepai.org and send here.",
"back": "cbs_apiset",
},
"oapi": {
"var": "OCR_API",
"name": "Ocr Api Key",
"text": "Get Your OCR api from ocr.space and send that Here.",
"back": "cbs_apiset",
},
"pmlgg": {
"var": "PMLOGGROUP",
"name": "Pm Log Group",
"text": "Send chat id of chat which you want to save as Pm log Group.",
"back": "pml",
},
"vcs": {
"var": "VC_SESSION",
"name": "Vc Session",
"text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.",
"back": "cbs_vcb",
},
"settag": {
"var": "TAG_LOG",
"name": "Tag Log Group",
"text": f"Make a group, add your assistant and make it admin.\nGet the `{HNDLR}id` of that group and send it here for tag logs.\n\nUse /cancel to cancel.",
"back": "taglog",
},
"alvtx": {
"var": "ALIVE_TEXT",
"name": "Alive Text",
"text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.",
"back": "cbs_alvcstm",
},
"sfexf": {
"var": "EXCLUDE_FED",
"name": "Excluded Fed",
"text": "Send the Fed IDs you want to exclude in the ban. Split by a space.\neg`id1 id2 id3`\nSet is as `None` if you dont want any.\nUse /cancel to go back.",
"back": "cbs_sfban",
},
}
async def convo_handler(event: events.CallbackQuery):
match = event.data_match.group(1).decode("utf-8")
if not _convo.get(match):
return
await event.delete()
get_ = _convo[match]
back = get_["back"]
async with event.client.conversation(event.sender_id) as conv:
await conv.send_message(get_["text"])
response = await conv.get_response()
themssg = response.message
try:
themssg = ast.literal_eval(themssg)
except Exception:
pass
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button(back),
)
await setit(event, get_["var"], themssg)
await conv.send_message(
f"{get_['name']} changed to `{themssg}`",
buttons=get_back_button(back),
) | null |
5,618 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def rhwhe(e):
if udB.get_key("DUAL_MODE"):
udB.del_key("DUAL_MODE")
key = "Off"
else:
udB.set_key("DUAL_MODE", "True")
key = "On"
Msg = f"Dual Mode : {key}"
await e.edit(Msg, buttons=get_back_button("cbs_otvars")) | null |
5,619 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
await event.delete()
pru = event.sender_id
var = "PM_TEXT"
name = "PM Text"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
buttons=get_back_button("cbs_pmcstm"),
)
async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
)
async def name(event):
await event.delete()
pru = event.sender_id
var = "STARTMSG"
name = "Bot Welcome Message:"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_chatbot"),
)
async def hndlrr(event):
await event.delete()
pru = event.sender_id
var = "DUAL_HNDLR"
name = "Dual Handler"
CH = udB.get_key(var) or "/"
async with event.client.conversation(pru) as conv:
await conv.send_message(
f"Send The Symbol Which u want as Handler/Trigger to use your Assistant bot\nUr Current Handler is [ `{CH}` ]\n\n use /cancel to cancel.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_otvars"),
) | null |
5,620 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
await event.delete()
pru = event.sender_id
var = "PM_TEXT"
name = "PM Text"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
buttons=get_back_button("cbs_pmcstm"),
)
async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
)
async def name(event):
await event.delete()
pru = event.sender_id
var = "STARTMSG"
name = "Bot Welcome Message:"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_chatbot"),
)
async def emoji(event):
await event.delete()
pru = event.sender_id
var = "EMOJI_IN_HELP"
name = f"Emoji in `{HNDLR}help` menu"
async with event.client.conversation(pru) as conv:
await conv.send_message("Send emoji u want to set 🙃.\n\nUse /cancel to cancel.")
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", HNDLR)):
await conv.send_message(
"Incorrect Emoji",
buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n",
buttons=get_back_button("cbs_otvars"),
) | null |
5,621 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
await event.delete()
pru = event.sender_id
var = "PM_TEXT"
name = "PM Text"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
buttons=get_back_button("cbs_pmcstm"),
)
async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
)
async def name(event):
await event.delete()
pru = event.sender_id
var = "STARTMSG"
name = "Bot Welcome Message:"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_chatbot"),
)
async def pluginch(event):
await event.delete()
pru = event.sender_id
var = "PLUGIN_CHANNEL"
name = "Plugin Channel"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"Send id or username of a channel from where u want to install all plugins\n\nOur Channel~ @ultroidplugins\n\nUse /cancel to cancel.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", HNDLR)):
await conv.send_message(
"Incorrect channel",
buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n After Setting All Things Do Restart",
buttons=get_back_button("cbs_otvars"),
) | null |
5,622 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
await event.delete()
pru = event.sender_id
var = "PM_TEXT"
name = "PM Text"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart",
buttons=get_back_button("cbs_pmcstm"),
)
async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
)
async def name(event):
await event.delete()
pru = event.sender_id
var = "STARTMSG"
name = "Bot Welcome Message:"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_chatbot"),
)
async def hndlrr(event):
await event.delete()
pru = event.sender_id
var = "HNDLR"
name = "Handler/ Trigger"
async with event.client.conversation(pru) as conv:
await conv.send_message(
f"Send The Symbol Which u want as Handler/Trigger to use bot\nUr Current Handler is [ `{HNDLR}` ]\n\n use /cancel to cancel.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", "#", "@")):
await conv.send_message(
"This cannot be used as handler",
buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_otvars"),
) | null |
5,623 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
async def name(event):
async def name(event):
async def hndlrr(event):
await event.delete()
pru = event.sender_id
var = "SUDO_HNDLR"
name = "Sudo Handler"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"Send The Symbol Which u want as Sudo Handler/Trigger to use bot\n\n use /cancel to cancel."
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", "#", "@")):
await conv.send_message(
"This cannot be used as handler",
buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_otvars"),
) | null |
5,624 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def tagloggrr(e):
BUTTON = [
[Button.inline("SET TAG LOG", data="abs_settag")],
[Button.inline("DELETE TAG LOG", data="deltag")],
get_back_button("cbs_otvars"),
]
await e.edit(
"Choose Options",
buttons=BUTTON,
) | null |
5,625 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmset(event):
BT = (
[Button.inline("Aᴅᴅᴏɴs Oғғ", data="edof")]
if udB.get_key("ADDONS")
else [Button.inline("Aᴅᴅᴏɴs Oɴ", data="edon")]
)
await event.edit(
"ADDONS~ Extra Plugins:",
buttons=[
BT,
[Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
],
) | null |
5,626 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def eddon(event):
var = "ADDONS"
await setit(event, var, "True")
await event.edit(
"Done! ADDONS has been turned on!!\n\n After Setting All Things Do Restart",
buttons=get_back_button("eaddon"),
) | null |
5,627 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def eddof(event):
udB.set_key("ADDONS", "False")
await event.edit(
"Done! ADDONS has been turned off!! After Setting All Things Do Restart",
buttons=get_back_button("eaddon"),
) | null |
5,628 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmset(event):
BT = (
[Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oғғ", data="ofsudo")]
if udB.get_key("SUDO")
else [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oɴ", data="onsudo")]
)
await event.edit(
f"SUDO MODE ~ Some peoples can use ur Bot which u selected. To know More use `{HNDLR}help sudo`",
buttons=[
BT,
[Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
],
) | null |
5,629 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def eddon(event):
var = "SUDO"
await setit(event, var, "True")
await event.edit(
"Done! SUDO MODE has been turned on!!\n\n After Setting All Things Do Restart",
buttons=get_back_button("sudo"),
) | null |
5,630 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def eddof(event):
var = "SUDO"
await setit(event, var, "False")
await event.edit(
"Done! SUDO MODE has been turned off!! After Setting All Things Do Restart",
buttons=get_back_button("sudo"),
) | null |
5,631 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def name(event):
async def name(event):
async def name(event):
async def sfgrp(event):
await event.delete()
name = "FBan Group ID"
var = "FBAN_GROUP_ID"
pru = event.sender_id
async with asst.conversation(pru) as conv:
await conv.send_message(
f"Make a group, add @MissRose_Bot, send `{HNDLR}id`, copy that and send it here.\nUse /cancel to go back.",
)
response = conv.wait_event(events.NewMessage(chats=pru))
response = await response
themssg = response.message.message
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
buttons=get_back_button("cbs_sfban"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
buttons=get_back_button("cbs_sfban"),
) | null |
5,632 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def dell(event):
try:
udB.del_key("ALIVE_PIC")
return await event.edit(
get_string("clst_5"), buttons=get_back_button("cbs_alabs_vcstm")
)
except BaseException as er:
LOGS.exception(er)
return await event.edit(
get_string("clst_4"),
buttons=get_back_button("cbs_alabs_vcstm"),
) | null |
5,633 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def inl_on(event):
var = "INLINE_PM"
await setit(event, var, "True")
await event.edit(
"Done!! PMPermit type has been set to inline!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
) | null |
5,634 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def inl_on(event):
var = "INLINE_PM"
await setit(event, var, "False")
await event.edit(
"Done!! PMPermit type has been set to normal!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
) | null |
5,635 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def set_wrns(event):
value = int(event.data_match.group(1).decode("UTF-8"))
if dn := udB.set_key("PMWARNS", value):
await event.edit(
f"PM Warns Set to {value}.\nNew users will have {value} chances in PMs before getting banned.",
buttons=get_back_button("cbs_pmcstm"),
)
else:
await event.edit(
f"Something went wrong, please check your {HNDLR}logs!",
buttons=get_back_button("cbs_pmcstm"),
) | null |
5,636 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def dell(event):
try:
udB.del_key("PMPIC")
return await event.edit(
get_string("clst_5"), buttons=get_back_button("cbs_pmcstm")
)
except BaseException as er:
LOGS.exception(er)
return await event.edit(
get_string("clst_4"),
buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
) | null |
5,637 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def apon(event):
var = "AUTOAPPROVE"
await setit(event, var, "True")
await event.edit(
"Done!! AUTOAPPROVE Started!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
) | null |
5,638 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def apof(event):
try:
udB.set_key("AUTOAPPROVE", "False")
return await event.edit(
"Done! AUTOAPPROVE Stopped!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
)
except BaseException as er:
LOGS.exception(er)
return await event.edit(
get_string("clst_4"),
buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
) | null |
5,639 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def l_vcs(event):
BT = (
[Button.inline("PMLOGGER OFF", data="pmlogof")]
if udB.get_key("PMLOG")
else [Button.inline("PMLOGGER ON", data="pmlog")]
)
await event.edit(
"PMLOGGER This Will Forward Ur Pm to Ur Private Group -",
buttons=[
BT,
[Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "abs_pmlgg")],
[Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
],
) | null |
5,640 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmlog(event):
await setit(event, "PMLOG", "True")
await event.edit(
"Done!! PMLOGGER Started!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]],
) | null |
5,641 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmlogof(event):
try:
udB.del_key("PMLOG")
return await event.edit(
"Done! PMLOGGER Stopped!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]],
)
except BaseException as er:
LOGS.exception(er)
return await event.edit(
get_string("clst_4"),
buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]],
) | null |
5,642 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmonn(event):
var = "PMSETTING"
await setit(event, var, "True")
await event.edit(
"Done! PMPermit has been turned on!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
) | null |
5,643 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def pmofff(event):
var = "PMSETTING"
await setit(event, var, "False")
await event.edit(
"Done! PMPermit has been turned off!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
) | null |
5,644 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def media(event):
await event.delete()
pru = event.sender_id
var = "ALIVE_PIC"
name = "Alive Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_alvcstm"),
)
except BaseException as er:
LOGS.exception(er)
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
media = await event.client.download_media(response, "alvpc")
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_alvcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_alvcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "PMPIC"
name = "PM Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "pmpc")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_pmcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "INLINE_PIC"
name = "Inline Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("setter"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "inlpic")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("setter"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("setter"),
)
async def hhh(e):
async with e.client.conversation(e.chat_id) as conv:
await conv.send_message("Send Any Media to keep at your Bot's welcome ")
msg = await conv.get_response()
if not msg.media or msg.text.startswith("/"):
return await conv.send_message(
"Terminated!", buttons=get_back_button("cbs_chatbot")
)
udB.set_key("STARTMEDIA", msg.file.id)
await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot")) | null |
5,645 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def media(event):
await event.delete()
pru = event.sender_id
var = "ALIVE_PIC"
name = "Alive Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_alvcstm"),
)
except BaseException as er:
LOGS.exception(er)
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
media = await event.client.download_media(response, "alvpc")
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_alvcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_alvcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "PMPIC"
name = "PM Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "pmpc")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_pmcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "INLINE_PIC"
name = "Inline Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("setter"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "inlpic")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("setter"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("setter"),
)
async def hhh(e):
async with e.client.conversation(e.chat_id) as conv:
await conv.send_message(
"Send message to set to Display, when user Press Info button in Bot Welcome!\n\nsend `False` to completely remove that button.."
)
msg = await conv.get_response()
if msg.media or msg.text.startswith("/"):
return await conv.send_message(
"Terminated!", buttons=get_back_button("cbs_chatbot")
)
udB.set_key("BOT_INFO_START", msg.text)
await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot")) | null |
5,646 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def heheh(event):
Ll = []
err = ""
async with event.client.conversation(event.chat_id) as conv:
await conv.send_message(
"• Send The Chat Id(s), which you want user to Join Before using Chat/Pm Bot\n\n• Send /clear to disable PmBot Force sub..\n• • Send /cancel to stop this process.."
)
await conv.send_message(
"Example : \n`-1001234567\n-100778888`\n\nFor Multiple Chat(s)."
)
try:
msg = await conv.get_response()
except AsyncTimeOut:
return await conv.send_message("**• TimeUp!**\nStart from /start back.")
if not msg.text or msg.text.startswith("/"):
timyork = "Cancelled!"
if msg.text == "/clear":
udB.del_key("PMBOT_FSUB")
timyork = "Done! Force Subscribe Stopped\nRestart your Bot!"
return await conv.send_message(
"Cancelled!", buttons=get_back_button("cbs_chatbot")
)
for chat in msg.message.split("\n"):
if chat.startswith("-") or chat.isdigit():
chat = int(chat)
try:
CHSJSHS = await event.client.get_entity(chat)
Ll.append(get_peer_id(CHSJSHS))
except Exception as er:
err += f"**{chat}** : {er}\n"
if err:
return await conv.send_message(err)
udB.set_key("PMBOT_FSUB", str(Ll))
await conv.send_message(
"Done!\nRestart Your Bot.", buttons=get_back_button("cbs_chatbot")
) | null |
5,647 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def chon(event):
var = "PMBOT"
await setit(event, var, "True")
Loader(path="assistant/pmbot.py", key="PM Bot").load()
if AST_PLUGINS.get("pmbot"):
for i, e in AST_PLUGINS["pmbot"]:
event.client.remove_event_handler(i)
for i, e in AST_PLUGINS["pmbot"]:
event.client.add_event_handler(i, events.NewMessage(**e))
await event.edit(
"Done! Now u Can Chat With People Via This Bot",
buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
) | null |
5,648 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def chon(event):
var = "PMBOT"
await setit(event, var, "False")
if AST_PLUGINS.get("pmbot"):
for i, e in AST_PLUGINS["pmbot"]:
event.client.remove_event_handler(i)
await event.edit(
"Done! Chat People Via This Bot Stopped.",
buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
) | null |
5,649 | import ast
import asyncio
import re
import sys
import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
from bs4 import BeautifulSoup as bs
from telegraph import upload_file as upl
from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progress
from pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_client
from pyUltroid.startup.loader import Loader
from . import *
async def update(eve):
repo = Repo()
ac_br = repo.active_branch
ups_rem = repo.remote("upstream")
if heroku_api:
import heroku3
try:
heroku = heroku3.from_key(heroku_api)
heroku_app = None
heroku_applications = heroku.apps()
except BaseException as er:
LOGS.exception(er)
return await eve.edit("`Wrong HEROKU_API.`")
for app in heroku_applications:
if app.name == app_name:
heroku_app = app
if not heroku_app:
await eve.edit("`Wrong HEROKU_APP_NAME.`")
repo.__del__()
return
await eve.edit(get_string("clst_1"))
ups_rem.fetch(ac_br)
repo.git.reset("--hard", "FETCH_HEAD")
heroku_git_url = heroku_app.git_url.replace(
"https://", f"https://api:{heroku_api}@"
)
if "heroku" in repo.remotes:
remote = repo.remote("heroku")
remote.set_url(heroku_git_url)
else:
remote = repo.create_remote("heroku", heroku_git_url)
try:
remote.push(refspec=f"HEAD:refs/heads/{ac_br}", force=True)
except GitCommandError as error:
await eve.edit(f"`Here is the error log:\n{error}`")
repo.__del__()
return
await eve.edit("`Successfully Updated!\nRestarting, please wait...`")
else:
await eve.edit(get_string("clst_1"))
call_back()
await bash("git pull && pip3 install -r requirements.txt")
execl(sys.executable, sys.executable, "-m", "pyUltroid")
async def _(e):
ok = (e.data_match.group(1)).decode("UTF-8")
index = None
if "|" in ok:
ok, index = ok.split("|")
with open(ok, "r") as hmm:
_, key = await get_paste(hmm.read())
link = f"https://spaceb.in/{key}"
raw = f"https://spaceb.in/api/v1/documents/{key}/raw"
if not _:
return await e.answer(key[:30], alert=True)
if ok.startswith("addons"):
key = "Addons"
elif ok.startswith("vcbot"):
key = "VCBot"
else:
key = "Official"
data = f"uh_{key}_"
if index is not None:
data += f"|{index}"
await e.edit(
"",
buttons=[
[Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)],
[Button.inline("« Bᴀᴄᴋ", data=data)],
],
)
async def _(e):
if not e.is_private:
return
url = GDrive._create_token_file()
await e.edit("Go to the below link and send the code!")
async with asst.conversation(e.sender_id) as conv:
await conv.send_message(url)
code = await conv.get_response()
if GDrive._create_token_file(code=code.text):
await conv.send_message(
"`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`",
buttons=Button.inline("Main Menu", data="setter"),
)
else:
await conv.send_message("Wrong code! Click authorise again.")
async def _(e):
if not e.is_private:
return
msg = (
"Send your FOLDER ID\n\n"
+ "For FOLDER ID:\n"
+ "1. Open Google Drive App.\n"
+ "2. Create Folder.\n"
+ "3. Make that folder public.\n"
+ "4. Send link of that folder."
)
await e.delete()
async with asst.conversation(e.sender_id, timeout=150) as conv:
await conv.send_message(msg)
repl = await conv.get_response()
id = repl.text
if id.startswith("https"):
id = id.split("?id=")[-1]
udB.set_key("GDRIVE_FOLDER_ID", id)
await repl.reply(
"`Success.`",
buttons=get_back_button("gdrive"),
)
async def _(e):
if not e.is_private:
return
await e.edit(
"Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)",
buttons=[
[
Button.inline("Folder ID", data="folderid"),
Button.inline("Authorise", data="authorise"),
],
[Button.inline("« Back", data="cbs_otvars")],
],
link_preview=False,
)
async def _(e):
udB.del_key("TAG_LOG")
await e.answer("Done!!! Tag Logger has been turned Off")
async def media(event):
await event.delete()
pru = event.sender_id
var = "ALIVE_PIC"
name = "Alive Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_alvcstm"),
)
except BaseException as er:
LOGS.exception(er)
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
media = await event.client.download_media(response, "alvpc")
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_alvcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_alvcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "PMPIC"
name = "PM Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("cbs_pmcstm"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "pmpc")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
elif response.sticker:
url = response.file.id
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("cbs_pmcstm"),
)
async def media(event):
await event.delete()
pru = event.sender_id
var = "INLINE_PIC"
name = "Inline Media"
async with event.client.conversation(pru) as conv:
await conv.send_message(
"**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.",
)
response = await conv.get_response()
try:
themssg = response.message
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
buttons=get_back_button("setter"),
)
except BaseException as er:
LOGS.exception(er)
media = await event.client.download_media(response, "inlpic")
if (
not (response.text).startswith("/")
and response.text != ""
and (not response.media or isinstance(response.media, MessageMediaWebPage))
):
url = text_to_url(response)
else:
try:
x = upl(media)
url = f"https://graph.org/{x[0]}"
remove(media)
except BaseException as er:
LOGS.exception(er)
return await conv.send_message(
"Terminated.",
buttons=get_back_button("setter"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
buttons=get_back_button("setter"),
)
FD_MEDIA = {}
from . import *
async def fast_download(download_url, filename=None, progress_callback=None):
if not aiohttp_client:
return await download_file(download_url, filename)[0], None
async with aiohttp_client() as session:
async with session.get(download_url, timeout=None) as response:
if not filename:
filename = unquote(download_url.rpartition("/")[-1])
total_size = int(response.headers.get("content-length", 0)) or None
downloaded_size = 0
start_time = time.time()
with open(filename, "wb") as f:
async for chunk in response.content.iter_chunked(1024):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
if progress_callback and total_size:
await _maybe_await(
progress_callback(downloaded_size, total_size)
)
return filename, time.time() - start_time
async def progress(current, total, event, start, type_of_ps, file_name=None):
now = time.time()
if No_Flood.get(event.chat_id):
if No_Flood[event.chat_id].get(event.id):
if (now - No_Flood[event.chat_id][event.id]) < 1.1:
return
else:
No_Flood[event.chat_id].update({event.id: now})
else:
No_Flood.update({event.chat_id: {event.id: now}})
diff = time.time() - start
if round(diff % 10.00) == 0 or current == total:
percentage = current * 100 / total
speed = current / diff
time_to_completion = round((total - current) / speed) * 1000
progress_str = "`[{0}{1}] {2}%`\n\n".format(
"".join("●" for i in range(math.floor(percentage / 5))),
"".join("" for i in range(20 - math.floor(percentage / 5))),
round(percentage, 2),
)
tmp = (
progress_str
+ "`{0} of {1}`\n\n`✦ Speed: {2}/s`\n\n`✦ ETA: {3}`\n\n".format(
humanbytes(current),
humanbytes(total),
humanbytes(speed),
time_formatter(time_to_completion),
)
)
if file_name:
await event.edit(
"`✦ {}`\n\n`File Name: {}`\n\n{}".format(type_of_ps, file_name, tmp)
)
else:
await event.edit("`✦ {}`\n\n{}".format(type_of_ps, tmp))
async def fdroid_dler(event):
uri = event.data_match.group(1).decode("utf-8")
if FD_MEDIA.get(uri):
return await event.edit(file=FD_MEDIA[uri])
await event.answer("• Starting Download •", alert=True)
await event.edit("• Downloading.. •")
URL = f"https://f-droid.org/packages/{uri}"
conte = await async_searcher(URL, re_content=True)
BSC = bs(conte, "html.parser", from_encoding="utf-8")
dl_ = BSC.find("p", "package-version-download").find("a")["href"]
title = BSC.find("h3", "package-name").text.strip()
thumb = BSC.find("img", "package-icon")["src"]
if thumb.startswith("/"):
thumb = f"https://f-droid.org{thumb}"
thumb, _ = await fast_download(thumb, filename=f"{uri}.png")
s_time = time.time()
file, _ = await fast_download(
dl_,
filename=f"{title}.apk",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
event,
s_time,
"Downloading...",
)
),
)
time.time()
n_file = await event.client.fast_uploader(
file, show_progress=True, event=event, message="Uploading...", to_delete=True
)
buttons = Button.switch_inline("Search Back", query="fdroid", same_peer=True)
try:
msg = await event.edit(
f"**• [{title}]({URL}) •**", file=n_file, thumb=thumb, buttons=buttons
)
except Exception as er:
LOGS.exception(er)
try:
msg = await event.client.edit_message(
await event.get_input_chat(),
event.message_id,
f"**• [{title}]({URL}) •**",
buttons=buttons,
thumb=thumb,
file=n_file,
)
except Exception as er:
os.remove(thumb)
LOGS.exception(er)
return await event.edit(f"**ERROR**: `{er}`", buttons=buttons)
if msg and hasattr(msg, "media"):
FD_MEDIA.update({uri: msg.media})
os.remove(thumb) | null |
5,650 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
ofox = "https://graph.org/file/231f0049fcd722824f13b.jpg"
from .. import *
async def get_ofox(codename):
ofox_baseurl = "https://api.orangefox.download/v3/"
releases = await async_searcher(
ofox_baseurl + "releases?codename=" + codename, re_json=True
)
device = await async_searcher(
ofox_baseurl + "devices/get?codename=" + codename, re_json=True
)
return device, releases
async def _(e):
try:
match = e.text.split(" ", maxsplit=1)[1]
except IndexError:
kkkk = e.builder.article(
title="Enter Device Codename",
thumb=wb(ofox, 0, "image/jpeg", []),
text="**OFᴏx🦊Rᴇᴄᴏᴠᴇʀʏ**\n\nYou didn't search anything",
buttons=Button.switch_inline("Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True),
)
return await e.answer([kkkk])
device, releases = await get_ofox(match)
if device.get("detail") is None:
fox = []
fullname = device["full_name"]
codename = device["codename"]
str(device["supported"])
maintainer = device["maintainer"]["name"]
link = f"https://orangefox.download/device/{codename}"
for data in releases["data"]:
release = data["type"]
version = data["version"]
size = humanbytes(data["size"])
release_date = datetime.utcfromtimestamp(data["date"]).strftime("%Y-%m-%d")
text = f"[\xad]({ofox})**OʀᴀɴɢᴇFᴏx Rᴇᴄᴏᴠᴇʀʏ Fᴏʀ**\n\n"
text += f"` Fᴜʟʟ Nᴀᴍᴇ: {fullname}`\n"
text += f"` Cᴏᴅᴇɴᴀᴍᴇ: {codename}`\n"
text += f"` Mᴀɪɴᴛᴀɪɴᴇʀ: {maintainer}`\n"
text += f"` Bᴜɪʟᴅ Tʏᴘᴇ: {release}`\n"
text += f"` Vᴇʀsɪᴏɴ: {version}`\n"
text += f"` Sɪᴢᴇ: {size}`\n"
text += f"` Bᴜɪʟᴅ Dᴀᴛᴇ: {release_date}`"
fox.append(
await e.builder.article(
title=f"{fullname}",
description=f"{version}\n{release_date}",
text=text,
thumb=wb(ofox, 0, "image/jpeg", []),
link_preview=True,
buttons=[
Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}"),
Button.switch_inline(
"Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True
),
],
)
)
await e.answer(
fox, switch_pm="OrangeFox Recovery Search.", switch_pm_param="start"
)
else:
await e.answer(
[], switch_pm="OrangeFox Recovery Search.", switch_pm_param="start"
) | null |
5,651 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
from .. import *
_webupload_cache = {}
async def _(e):
match = e.pattern_match.group(1)
chat_id, msg_id = match.split(":")
filename = _webupload_cache[int(chat_id)][int(msg_id)]
if "/" in filename:
filename = filename.split("/")[-1]
__cache = f"{chat_id}:{msg_id}"
buttons = [
[
Button.inline("anonfiles", data=f"flanonfiles//{__cache}"),
Button.inline("transfer", data=f"fltransfer//{__cache}"),
],
[
Button.inline("bayfiles", data=f"flbayfiles//{__cache}"),
Button.inline("x0.at", data=f"flx0.at//{__cache}"),
],
[
Button.inline("file.io", data=f"flfile.io//{__cache}"),
Button.inline("siasky", data=f"flsiasky//{__cache}"),
],
]
try:
lnk = [
await e.builder.article(
title=f"Upload {filename}",
text=f"**File:**\n{filename}",
buttons=buttons,
)
]
except BaseException as er:
LOGS.exception(er)
lnk = [
await e.builder.article(
title="fl2lnk",
text="File not found",
)
]
await e.answer(lnk, switch_pm="File to Link.", switch_pm_param="start") | null |
5,652 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
from .. import *
_webupload_cache = {}
async def webuploader(chat_id: int, msg_id: int, uploader: str):
file = _webupload_cache[int(chat_id)][int(msg_id)]
sites = {
"anonfiles": {"url": "https://api.anonfiles.com/upload", "json": True},
"siasky": {"url": "https://siasky.net/skynet/skyfile", "json": True},
"file.io": {"url": "https://file.io", "json": True},
"bayfiles": {"url": "https://api.bayfiles.com/upload", "json": True},
"x0.at": {"url": "https://x0.at/", "json": False},
"transfer": {"url": "https://transfer.sh", "json": False},
}
if uploader and uploader in sites:
url = sites[uploader]["url"]
json = sites[uploader]["json"]
with open(file, "rb") as data:
# todo: add progress bar
status = await async_searcher(
url, data={"file": data.read()}, post=True, re_json=json
)
if isinstance(status, dict):
if "skylink" in status:
return f"https://siasky.net/{status['skylink']}"
if status["status"] == 200 or status["status"] is True:
try:
link = status["link"]
except KeyError:
link = status["data"]["file"]["url"]["short"]
return link
del _webupload_cache[int(chat_id)][int(msg_id)]
return status
async def _(e):
t = (e.data).decode("UTF-8")
data = t[2:]
host = data.split("//")[0]
chat_id, msg_id = data.split("//")[1].split(":")
filename = _webupload_cache[int(chat_id)][int(msg_id)]
if "/" in filename:
filename = filename.split("/")[-1]
await e.edit(f"Uploading `{filename}` on {host}")
link = (await webuploader(chat_id, msg_id, host)).strip().replace("\n", "")
await e.edit(f"Uploaded `{filename}` on {host}.", buttons=Button.url("View", link)) | null |
5,653 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
SUP_BUTTONS = [
[
Button.url("• Repo •", url="https://github.com/TeamUltroid/Ultroid"),
Button.url("• Support •", url="t.me/UltroidSupportChat"),
],
]
ultpic = "https://graph.org/file/4136aa1650bc9d4109cc5.jpg"
async def repo(e):
res = [
await e.builder.article(
title="Ultroid Userbot",
description="Userbot | Telethon",
thumb=wb(ultpic, 0, "image/jpeg", []),
text="• **ULTROID USERBOT** •",
buttons=SUP_BUTTONS,
),
]
await e.answer(res, switch_pm="Ultroid Repo.", switch_pm_param="start") | null |
5,654 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
gugirl = "https://graph.org/file/0df54ae4541abca96aa11.jpg"
from .. import *
async def google_search(query):
query = query.replace(" ", "+")
_base = "https://google.com"
headers = {
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"User-Agent": choice(some_random_headers),
}
con = await async_searcher(_base + "/search?q=" + query, headers=headers)
soup = BeautifulSoup(con, "html.parser")
result = []
pdata = soup.find_all("a", href=re.compile("url="))
for data in pdata:
if not data.find("div"):
continue
try:
result.append(
{
"title": data.find("div").text,
"link": data["href"].split("&url=")[1].split("&ved=")[0],
"description": data.find_all("div")[-1].text,
}
)
except BaseException as er:
LOGS.exception(er)
return result
async def gsearch(q_event):
try:
match = q_event.text.split(maxsplit=1)[1]
except IndexError:
return await q_event.answer(
[], switch_pm="Google Search. Enter a query!", switch_pm_param="start"
)
searcher = []
gresults = await google_search(match)
for i in gresults:
try:
title = i["title"]
link = i["link"]
desc = i["description"]
searcher.append(
await q_event.builder.article(
title=title,
description=desc,
thumb=wb(gugirl, 0, "image/jpeg", []),
text=f"**Gᴏᴏɢʟᴇ Sᴇᴀʀᴄʜ**\n\n**••Tɪᴛʟᴇ••**\n`{title}`\n\n**••Dᴇsᴄʀɪᴘᴛɪᴏɴ••**\n`{desc}`",
link_preview=False,
buttons=[
[Button.url("Lɪɴᴋ", url=f"{link}")],
[
Button.switch_inline(
"Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
query="go ",
same_peer=True,
),
Button.switch_inline(
"Sʜᴀʀᴇ",
query=f"go {match}",
same_peer=False,
),
],
],
),
)
except IndexError:
break
await q_event.answer(searcher, switch_pm="Google Search.", switch_pm_param="start") | null |
5,655 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
apis = [
"QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV",
"QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn",
"QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR",
]
async def _(e):
try:
quer = e.text.split(" ", maxsplit=1)[1]
except IndexError:
return await e.answer(
[], switch_pm="Mod Apps Search. Enter app name!", switch_pm_param="start"
)
start = 0 * 3 + 1
da = base64.b64decode(choice(apis)).decode("ascii")
url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}"
data = await async_searcher(url, re_json=True)
search_items = data.get("items", [])
modss = []
for a in search_items:
title = a.get("title")
desc = a.get("snippet")
link = a.get("link")
text = f"**••Tɪᴛʟᴇ••** `{title}`\n\n"
text += f"**Dᴇsᴄʀɪᴘᴛɪᴏɴ** `{desc}`"
modss.append(
await e.builder.article(
title=title,
description=desc,
text=text,
link_preview=True,
buttons=[
[Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}")],
[
Button.switch_inline(
"Mᴏʀᴇ Mᴏᴅs",
query="mods ",
same_peer=True,
),
Button.switch_inline(
"Sʜᴀʀᴇ",
query=f"mods {quer}",
same_peer=False,
),
],
],
),
)
await e.answer(modss, switch_pm="Search Mod Applications.", switch_pm_param="start") | null |
5,656 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
APP_CACHE = {}
RECENTS = {}
PLAY_API = "https://googleplay.onrender.com/api/apps?q="
async def _(e):
try:
f = e.text.split(maxsplit=1)[1].lower()
except IndexError:
get_string("instu_1")
res = []
if APP_CACHE and RECENTS.get(e.sender_id):
res.extend(
APP_CACHE[a][0] for a in RECENTS[e.sender_id] if APP_CACHE.get(a)
)
return await e.answer(
res, switch_pm=get_string("instu_2"), switch_pm_param="start"
)
try:
return await e.answer(
APP_CACHE[f], switch_pm="Application Searcher.", switch_pm_param="start"
)
except KeyError:
pass
foles = []
url = PLAY_API + f.replace(" ", "+")
aap = await async_searcher(url, re_json=True)
for z in aap["results"][:50]:
url = "https://play.google.com/store/apps/details?id=" + z["appId"]
name = z["title"]
desc = unescape(z["summary"])[:300].replace("<br>", "\n") + "..."
dev = z["developer"]["devId"]
text = f"**••Aᴘᴘ Nᴀᴍᴇ••** [{name}]({url})\n"
text += f"**••Dᴇᴠᴇʟᴏᴘᴇʀ••** `{dev}`\n"
text += f"**••Dᴇsᴄʀɪᴘᴛɪᴏɴ••**\n`{desc}`"
foles.append(
await e.builder.article(
title=name,
description=dev,
thumb=wb(z["icon"], 0, "image/jpeg", []),
text=text,
link_preview=True,
buttons=[
[Button.url("Lɪɴᴋ", url=url)],
[
Button.switch_inline(
"Mᴏʀᴇ Aᴘᴘs",
query="app ",
same_peer=True,
),
Button.switch_inline(
"Sʜᴀʀᴇ",
query=f"app {f}",
same_peer=False,
),
],
],
),
)
APP_CACHE.update({f: foles})
if RECENTS.get(e.sender_id):
RECENTS[e.sender_id].append(f)
else:
RECENTS.update({e.sender_id: [f]})
await e.answer(foles, switch_pm="Application Searcher.", switch_pm_param="start") | null |
5,657 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
PISTON_URI = "https://emkc.org/api/v2/piston/"
PISTON_LANGS = {}
async def piston_run(event):
try:
lang = event.text.split()[1]
code = event.text.split(maxsplit=2)[2]
except IndexError:
result = await event.builder.article(
title="Bad Query",
description="Usage: [Language] [code]",
thumb=wb(
"https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
),
text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)',
)
return await event.answer([result])
if not PISTON_LANGS:
se = await async_searcher(f"{PISTON_URI}runtimes", re_json=True)
PISTON_LANGS.update({lang.pop("language"): lang for lang in se})
if lang in PISTON_LANGS.keys():
version = PISTON_LANGS[lang]["version"]
else:
result = await event.builder.article(
title="Unsupported Language",
description="Usage: [Language] [code]",
thumb=wb(
"https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
),
text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)',
)
return await event.answer([result])
output = await async_searcher(
f"{PISTON_URI}execute",
post=True,
json={
"language": lang,
"version": version,
"files": [{"content": code}],
},
re_json=True,
)
output = output["run"]["output"] or get_string("instu_4")
if len(output) > 3000:
output = f"{output[:3000]}..."
result = await event.builder.article(
title="Result",
description=output,
text=f"• **Language:**\n`{lang}`\n\n• **Code:**\n`{code}`\n\n• **Result:**\n`{output}`",
thumb=wb(
"https://graph.org/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", []
),
buttons=Button.switch_inline("Fork", query=event.text, same_peer=True),
)
await event.answer([result], switch_pm="• Piston •", switch_pm_param="start") | null |
5,658 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
async def do_magic(event):
try:
match = event.text.split(" ", maxsplit=1)[1].lower()
except IndexError:
return await event.answer(
[], switch_pm="Enter Query to Search", switch_pm_param="start"
)
if FDROID_.get(match):
return await event.answer(
FDROID_[match], switch_pm=f"• Results for {match}", switch_pm_param="start"
)
link = "https://search.f-droid.org/?q=" + match.replace(" ", "+")
content = await async_searcher(link, re_content=True)
BSC = bs(content, "html.parser", from_encoding="utf-8")
ress = []
for dat in BSC.find_all("a", "package-header")[:10]:
image = dat.find("img", "package-icon")["src"]
if image.endswith("/"):
image = "https://graph.org/file/a8dd4a92c5a53a89d0eff.jpg"
title = dat.find("h4", "package-name").text.strip()
desc = dat.find("span", "package-summary").text.strip()
text = f"• **Name :** `{title}`\n\n"
text += f"• **Description :** `{desc}`\n"
text += f"• **License :** `{dat.find('span', 'package-license').text.strip()}`"
imga = wb(image, 0, "image/jpeg", [])
ress.append(
await event.builder.article(
title=title,
type="photo",
description=desc,
text=text,
content=imga,
thumb=imga,
include_media=True,
buttons=[
Button.inline(
"• Download •", "fd" + dat["href"].split("packages/")[-1]
),
Button.switch_inline("• Share •", query=event.text),
],
)
)
msg = f"Showing {len(ress)} Results!" if ress else "No Results Found"
FDROID_.update({match: ress})
await event.answer(ress, switch_pm=msg, switch_pm_param="start") | null |
5,659 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
_bearer_collected = [
"AAAAAAAAAAAAAAAAAAAAALIKKgEAAAAA1DRuS%2BI7ZRKiagD6KHYmreaXomo%3DP5Vaje4UTtEkODg0fX7nCh5laSrchhtLxeyEqxXpv0w9ZKspLD",
"AAAAAAAAAAAAAAAAAAAAAL5iUAEAAAAAmo6FYRjqdKlI3cNziIm%2BHUQB9Xs%3DS31pj0mxARMTOk2g9dvQ1yP9wknvY4FPBPUlE00smJcncw4dPR",
"AAAAAAAAAAAAAAAAAAAAAN6sVgEAAAAAMMjMMWrwgGyv7YQOWN%2FSAsO5SGM%3Dg8MG9Jq93Rlllaok6eht7HvRCruN4Vpzp4NaVsZaaHHWSTzKI8",
]
async def twitter_search(event):
try:
match = event.text.split(maxsplit=1)[1].lower()
except IndexError:
return await event.answer(
[], switch_pm="Enter Query to Search", switch_pm_param="start"
)
try:
return await event.answer(
_ult_cache["twitter"][match],
switch_pm="• Twitter Search •",
switch_pm_param="start",
)
except KeyError:
pass
headers = {"Authorization": f"bearer {choice(_bearer_collected)}"}
res = await async_searcher(
f"https://api.twitter.com/1.1/users/search.json?q={match}",
headers=headers,
re_json=True,
)
reso = []
for user in res:
thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", [])
if user.get("profile_banner_url"):
url = user["profile_banner_url"]
text = f"[\xad]({url})• **Name :** `{user['name']}`\n"
else:
text = f"• **Name :** `{user['name']}`\n"
text += f"• **Description :** `{user['description']}`\n"
text += f"• **Username :** `@{user['screen_name']}`\n"
text += f"• **Followers :** `{user['followers_count']}` • **Following :** `{user['friends_count']}`\n"
pro_ = "https://twitter.com/" + user["screen_name"]
text += f"• **Link :** [Click Here]({pro_})\n_"
reso.append(
await event.builder.article(
title=user["name"],
description=user["description"],
url=pro_,
text=text,
thumb=thumb,
)
)
swi_ = f"🐦 Showing {len(reso)} Results!" if reso else "No User Found :("
await event.answer(reso, switch_pm=swi_, switch_pm_param="start")
if _ult_cache.get("twitter"):
_ult_cache["twitter"].update({match: reso})
else:
_ult_cache.update({"twitter": {match: reso}}) | null |
5,660 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
_savn_cache = {}
from .. import *
async def saavn_search(query: str):
async def savn_s(event):
try:
query = event.text.split(maxsplit=1)[1].lower()
except IndexError:
return await event.answer(
[], switch_pm="Enter Query to search 🔍", switch_pm_param="start"
)
if query in _savn_cache:
return await event.answer(
_savn_cache[query],
switch_pm=f"Showing Results for {query}",
switch_pm_param="start",
)
results = await saavn_search(query)
swi = "🎵 Saavn Search" if results else "No Results Found!"
res = []
for song in results:
thumb = wb(song["image"], 0, "image/jpeg", [])
text = f"• **Title :** {song['title']}"
text += f"\n• **Year :** {song['year']}"
text += f"\n• **Lang :** {song['language']}"
text += f"\n• **Artist :** {song['artists']}"
text += f"\n• **Release Date :** {song['release_date']}"
res.append(
await event.builder.article(
title=song["title"],
description=song["artists"],
type="audio",
text=text,
include_media=True,
buttons=Button.switch_inline(
"Search Again 🔍", query="saavn", same_peer=True
),
thumb=thumb,
content=wb(
song["url"],
0,
"audio/mp4",
[
Audio(
title=song["title"],
duration=int(song["duration"]),
performer=song["artists"],
)
],
),
)
)
await event.answer(res, switch_pm=swi, switch_pm_param="start")
_savn_cache.update({query: res}) | null |
5,661 | import base64
import inspect
from datetime import datetime
from html import unescape
from random import choice
from re import compile as re_compile
from bs4 import BeautifulSoup as bs
from telethon import Button
from telethon.tl.alltlobjects import LAYER, tlobjects
from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_search
from pyUltroid.fns.tools import (
_webupload_cache,
async_searcher,
get_ofox,
saavn_search,
webuploader,
)
from . import *
from . import _ult_cache
async def inline_tl(ult):
try:
match = ult.text.split(maxsplit=1)[1]
except IndexError:
text = f"**Telegram TlObjects Searcher.**\n__(Don't use if you don't know what it is!)__\n\n• Example Usage\n`@{asst.me.username} tl GetFullUserRequest`"
return await ult.answer(
[
await ult.builder.article(
title="How to Use?",
description="Tl Searcher by Ultroid",
url="https://t.me/TeamUltroid",
text=text,
)
],
switch_pm="Tl Search 🔍",
switch_pm_param="start",
)
res = []
for key in tlobjects.values():
if match.lower() in key.__name__.lower():
tyyp = "Function" if "tl.functions." in str(key) else "Type"
text = f"**Name:** `{key.__name__}`\n"
text += f"**Category:** `{tyyp}`\n"
text += f"\n`from {key.__module__} import {key.__name__}`\n\n"
if args := str(inspect.signature(key))[1:][:-1]:
text += "**Parameter:**\n"
for para in args.split(","):
text += " " * 4 + "`" + para + "`\n"
text += f"\n**Layer:** `{LAYER}`"
res.append(
await ult.builder.article(
title=key.__name__,
description=tyyp,
url="https://t.me/TeamUltroid",
text=text[:4000],
)
)
mo = f"Showing {len(res)} results!" if res else f"No Results for {match}!"
await ult.answer(res[:50], switch_pm=mo, switch_pm_param="start") | null |
5,662 | import os
import re
from telethon import Button
from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.helper import (
bash,
fast_download,
humanbytes,
numerize,
time_formatter,
)
from pyUltroid.fns.ytdl import dler, get_buttons, get_formats
from . import LOGS, asst, callback, in_pattern, udB
ytt = "https://graph.org/file/afd04510c13914a06dd03.jpg"
_yt_base_url = "https://www.youtube.com/watch?v="
BACK_BUTTON = {}
async def _(event):
try:
string = event.text.split(" ", maxsplit=1)[1]
except IndexError:
fuk = event.builder.article(
title="Search Something",
thumb=wb(ytt, 0, "image/jpeg", []),
text="**YᴏᴜTᴜʙᴇ Sᴇᴀʀᴄʜ**\n\nYou didn't search anything",
buttons=Button.switch_inline(
"Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
query="yt ",
same_peer=True,
),
)
await event.answer([fuk])
return
results = []
search = VideosSearch(string, limit=50)
nub = search.result()
nibba = nub["result"]
for v in nibba:
ids = v["id"]
link = _yt_base_url + ids
title = v["title"]
duration = v["duration"]
views = v["viewCount"]["short"]
publisher = v["channel"]["name"]
published_on = v["publishedTime"]
description = (
v["descriptionSnippet"][0]["text"]
if v.get("descriptionSnippet")
and len(v["descriptionSnippet"][0]["text"]) < 500
else "None"
)
thumb = f"https://i.ytimg.com/vi/{ids}/hqdefault.jpg"
text = f"**Title: [{title}]({link})**\n\n"
text += f"`Description: {description}\n\n"
text += f"「 Duration: {duration} 」\n"
text += f"「 Views: {views} 」\n"
text += f"「 Publisher: {publisher} 」\n"
text += f"「 Published on: {published_on} 」`"
desc = f"{title}\n{duration}"
file = wb(thumb, 0, "image/jpeg", [])
buttons = [
[
Button.inline("Audio", data=f"ytdl:audio:{ids}"),
Button.inline("Video", data=f"ytdl:video:{ids}"),
],
[
Button.switch_inline(
"Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
query="yt ",
same_peer=True,
),
Button.switch_inline(
"Sʜᴀʀᴇ",
query=f"yt {string}",
same_peer=False,
),
],
]
BACK_BUTTON.update({ids: {"text": text, "buttons": buttons}})
results.append(
await event.builder.article(
type="photo",
title=title,
description=desc,
thumb=file,
content=file,
text=text,
include_media=True,
buttons=buttons,
),
)
await event.answer(results[:50]) | null |
5,663 | import os
import re
from telethon import Button
from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.helper import (
bash,
fast_download,
humanbytes,
numerize,
time_formatter,
)
from pyUltroid.fns.ytdl import dler, get_buttons, get_formats
from . import LOGS, asst, callback, in_pattern, udB
_yt_base_url = "https://www.youtube.com/watch?v="
def get_formats(type, id, data):
if type == "audio":
audio = []
for _quality in ["64", "128", "256", "320"]:
_audio = {}
_audio.update(
{
"ytid": id,
"type": "audio",
"id": _quality,
"quality": _quality + "KBPS",
}
)
audio.append(_audio)
return audio
if type == "video":
video = []
size = 0
for vid in data["formats"]:
if vid["format_id"] == "251":
size += vid["filesize"] if vid.get("filesize") else 0
if vid["vcodec"] != "none":
_id = int(vid["format_id"])
_quality = str(vid["width"]) + "×" + str(vid["height"])
_size = size + (vid["filesize"] if vid.get("filesize") else 0)
_ext = "mkv" if vid["ext"] == "webm" else "mp4"
if _size < 2147483648: # Telegram's Limit of 2GB
_video = {}
_video.update(
{
"ytid": id,
"type": "video",
"id": str(_id) + "+251",
"quality": _quality,
"size": _size,
"ext": _ext,
}
)
video.append(_video)
return video
return []
def get_buttons(listt):
id = listt[0]["ytid"]
butts = [
Button.inline(
text=f"[{x['quality']}"
+ (f" {humanbytes(x['size'])}]" if x.get("size") else "]"),
data=f"ytdownload:{x['type']}:{x['id']}:{x['ytid']}"
+ (f":{x['ext']}" if x.get("ext") else ""),
)
for x in listt
]
buttons = list(zip(butts[::2], butts[1::2]))
if len(butts) % 2 == 1:
buttons.append((butts[-1],))
buttons.append([Button.inline("« Back", f"ytdl_back:{id}")])
return buttons
async def dler(event, url, opts: dict = {}, download=False):
await event.edit("`Getting Data...`")
if "quiet" not in opts:
opts["quiet"] = True
opts["username"] = udB.get_key("YT_USERNAME")
opts["password"] = udB.get_key("YT_PASSWORD")
if download:
await ytdownload(url, opts)
try:
return await extract_info(url, opts)
except Exception as e:
await event.edit(f"{type(e)}: {e}")
return
async def _(e):
_e = e.pattern_match.group(1).strip().decode("UTF-8")
_lets_split = _e.split(":")
_ytdl_data = await dler(e, _yt_base_url + _lets_split[1])
_data = get_formats(_lets_split[0], _lets_split[1], _ytdl_data)
_buttons = get_buttons(_data)
_text = (
"`Select Your Format.`"
if _buttons
else "`Error downloading from YouTube.\nTry Restarting your bot.`"
)
await e.edit(_text, buttons=_buttons) | null |
5,664 | import os
import re
from telethon import Button
from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.helper import (
bash,
fast_download,
humanbytes,
numerize,
time_formatter,
)
from pyUltroid.fns.ytdl import dler, get_buttons, get_formats
from . import LOGS, asst, callback, in_pattern, udB
_yt_base_url = "https://www.youtube.com/watch?v="
from . import *
async def bash(cmd, run_code=0):
"""
run any command in subprocess and get output or error."""
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await process.communicate()
err = stderr.decode().strip() or None
out = stdout.decode().strip()
if not run_code and err:
if match := re.match("\/bin\/sh: (.*): ?(\w+): not found", err):
return out, f"{match.group(2).upper()}_NOT_FOUND"
return out, err
async def fast_download(download_url, filename=None, progress_callback=None):
if not aiohttp_client:
return await download_file(download_url, filename)[0], None
async with aiohttp_client() as session:
async with session.get(download_url, timeout=None) as response:
if not filename:
filename = unquote(download_url.rpartition("/")[-1])
total_size = int(response.headers.get("content-length", 0)) or None
downloaded_size = 0
start_time = time.time()
with open(filename, "wb") as f:
async for chunk in response.content.iter_chunked(1024):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
if progress_callback and total_size:
await _maybe_await(
progress_callback(downloaded_size, total_size)
)
return filename, time.time() - start_time
def time_formatter(milliseconds):
minutes, seconds = divmod(int(milliseconds / 1000), 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
tmp = (
((str(weeks) + "w:") if weeks else "")
+ ((str(days) + "d:") if days else "")
+ ((str(hours) + "h:") if hours else "")
+ ((str(minutes) + "m:") if minutes else "")
+ ((str(seconds) + "s") if seconds else "")
)
if not tmp:
return "0s"
if tmp.endswith(":"):
return tmp[:-1]
return tmp
def humanbytes(size):
if not size:
return "0 B"
for unit in ["", "K", "M", "G", "T"]:
if size < 1024:
break
size /= 1024
if isinstance(size, int):
size = f"{size}{unit}B"
elif isinstance(size, float):
size = f"{size:.2f}{unit}B"
return size
def numerize(number):
if not number:
return None
unit = ""
for unit in ["", "K", "M", "B", "T"]:
if number < 1000:
break
number /= 1000
if isinstance(number, int):
number = f"{number}{unit}"
elif isinstance(number, float):
number = f"{number:.2f}{unit}"
return number
async def dler(event, url, opts: dict = {}, download=False):
await event.edit("`Getting Data...`")
if "quiet" not in opts:
opts["quiet"] = True
opts["username"] = udB.get_key("YT_USERNAME")
opts["password"] = udB.get_key("YT_PASSWORD")
if download:
await ytdownload(url, opts)
try:
return await extract_info(url, opts)
except Exception as e:
await event.edit(f"{type(e)}: {e}")
return
async def _(event):
url = event.pattern_match.group(1).strip().decode("UTF-8")
lets_split = url.split(":")
vid_id = lets_split[2]
link = _yt_base_url + vid_id
format = lets_split[1]
try:
ext = lets_split[3]
except IndexError:
ext = "mp3"
if lets_split[0] == "audio":
opts = {
"format": "bestaudio",
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
"outtmpl": f"%(id)s.{ext}",
"logtostderr": False,
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": ext,
"preferredquality": format,
},
{"key": "FFmpegMetadata"},
],
}
ytdl_data = await dler(event, link, opts, True)
title = ytdl_data["title"]
if ytdl_data.get("artist"):
artist = ytdl_data["artist"]
elif ytdl_data.get("creator"):
artist = ytdl_data["creator"]
elif ytdl_data.get("channel"):
artist = ytdl_data["channel"]
views = numerize(ytdl_data.get("view_count")) or 0
thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=f"{vid_id}.jpg")
likes = numerize(ytdl_data.get("like_count")) or 0
duration = ytdl_data.get("duration") or 0
description = (
ytdl_data["description"]
if len(ytdl_data["description"]) < 100
else ytdl_data["description"][:100]
)
description = description or "None"
filepath = f"{vid_id}.{ext}"
if not os.path.exists(filepath):
filepath = f"{filepath}.{ext}"
size = os.path.getsize(filepath)
file, _ = await event.client.fast_uploader(
filepath,
filename=f"{title}.{ext}",
show_progress=True,
event=event,
to_delete=True,
)
attributes = [
DocumentAttributeAudio(
duration=int(duration),
title=title,
performer=artist,
),
]
elif lets_split[0] == "video":
opts = {
"format": str(format),
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
"outtmpl": f"%(id)s.{ext}",
"logtostderr": False,
"postprocessors": [{"key": "FFmpegMetadata"}],
}
ytdl_data = await dler(event, link, opts, True)
title = ytdl_data["title"]
if ytdl_data.get("artist"):
artist = ytdl_data["artist"]
elif ytdl_data.get("creator"):
artist = ytdl_data["creator"]
elif ytdl_data.get("channel"):
artist = ytdl_data["channel"]
views = numerize(ytdl_data.get("view_count")) or 0
thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=f"{vid_id}.jpg")
try:
Image.open(thumb).save(thumb, "JPEG")
except Exception as er:
LOGS.exception(er)
thumb = None
description = (
ytdl_data["description"]
if len(ytdl_data["description"]) < 100
else ytdl_data["description"][:100]
)
likes = numerize(ytdl_data.get("like_count")) or 0
hi, wi = ytdl_data.get("height") or 720, ytdl_data.get("width") or 1280
duration = ytdl_data.get("duration") or 0
filepath = f"{vid_id}.mkv"
if not os.path.exists(filepath):
filepath = f"{filepath}.webm"
size = os.path.getsize(filepath)
file, _ = await event.client.fast_uploader(
filepath,
filename=f"{title}.mkv",
show_progress=True,
event=event,
to_delete=True,
)
attributes = [
DocumentAttributeVideo(
duration=int(duration),
w=wi,
h=hi,
supports_streaming=True,
),
]
description = description if description != "" else "None"
text = f"**Title: [{title}]({_yt_base_url}{vid_id})**\n\n"
text += f"`📝 Description: {description}\n\n"
text += f"「 Duration: {time_formatter(int(duration)*1000)} 」\n"
text += f"「 Artist: {artist} 」\n"
text += f"「 Views: {views} 」\n"
text += f"「 Likes: {likes} 」\n"
text += f"「 Size: {humanbytes(size)} 」`"
button = Button.switch_inline("Search More", query="yt ", same_peer=True)
try:
await event.edit(
text,
file=file,
buttons=button,
attributes=attributes,
thumb=thumb,
)
except (FilePartLengthInvalidError, MediaEmptyError):
file = await asst.send_message(
udB.get_key("LOG_CHANNEL"),
text,
file=file,
buttons=button,
attributes=attributes,
thumb=thumb,
)
await event.edit(text, file=file.media, buttons=button)
await bash(f"rm {vid_id}.jpg") | null |
5,665 | import os
import re
from telethon import Button
from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.helper import (
bash,
fast_download,
humanbytes,
numerize,
time_formatter,
)
from pyUltroid.fns.ytdl import dler, get_buttons, get_formats
from . import LOGS, asst, callback, in_pattern, udB
BACK_BUTTON = {}
async def ytdl_back(event):
id_ = event.data_match.group(1).decode("utf-8")
if not BACK_BUTTON.get(id_):
return await event.answer("Query Expired! Search again 🔍")
await event.edit(**BACK_BUTTON[id_]) | null |
5,666 | import os
from time import sleep
ULTROID = r"""
_ _ _ _ _ _
| | | | | | (_) | |
| | | | | |_ _ __ ___ _ __| |
| | | | | __| '__/ _ \| |/ _ |
| |__| | | |_| | | (_) | | (_| |
\____/|_|\__|_| \___/|_|\__,_|
"""
def spinner(x):
def clear_screen():
def get_api_id_and_hash():
def telethon_session():
try:
spinner("tele")
import telethon
x = "\bFound an existing installation of Telethon...\nSuccessfully Imported.\n\n"
except ImportError:
print("Installing Telethon...")
os.system("pip uninstall telethon -y && pip install -U telethon")
x = "\bDone. Installed and imported Telethon."
clear_screen()
print(ULTROID)
print(x)
# the imports
from telethon.errors.rpcerrorlist import (
ApiIdInvalidError,
PhoneNumberInvalidError,
UserIsBotError,
)
from telethon.sessions import StringSession
from telethon.sync import TelegramClient
API_ID, API_HASH = get_api_id_and_hash()
# logging in
try:
with TelegramClient(StringSession(), API_ID, API_HASH) as ultroid:
print("Generating a string session for •ULTROID•")
try:
ultroid.send_message(
"me",
f"**ULTROID** `SESSION`:\n\n`{ultroid.session.save()}`\n\n**Do not share this anywhere!**",
)
print(
"Your SESSION has been generated. Check your Telegram saved messages!"
)
return
except UserIsBotError:
print("You are trying to Generate Session for your Bot's Account?")
print("Here is That!\n{ultroid.session.save()}\n\n")
print("NOTE: You can't use that as User Session..")
except ApiIdInvalidError:
print(
"Your API ID/API HASH combination is invalid. Kindly recheck.\nQuitting..."
)
exit(0)
except ValueError:
print("API HASH must not be empty!\nQuitting...")
exit(0)
except PhoneNumberInvalidError:
print("The phone number is invalid!\nQuitting...")
exit(0)
except Exception as er:
print("Unexpected Error Occurred while Creating Session")
print(er)
print("If you think It as a Bug, Report to @UltroidSupportChat.\n\n") | null |
5,667 | import os
from time import sleep
ULTROID = r"""
_ _ _ _ _ _
| | | | | | (_) | |
| | | | | |_ _ __ ___ _ __| |
| | | | | __| '__/ _ \| |/ _ |
| |__| | | |_| | | (_) | | (_| |
\____/|_|\__|_| \___/|_|\__,_|
"""
def spinner(x):
if x == "tele":
print("Checking if Telethon is installed...")
else:
print("Checking if Pyrogram is installed...")
for _ in range(3):
for frame in r"-\|/-\|/":
print("\b", frame, sep="", end="", flush=True)
sleep(0.1)
def clear_screen():
# https://www.tutorialspoint.com/how-to-clear-screen-in-python#:~:text=In%20Python%20sometimes%20we%20have,screen%20by%20pressing%20Control%20%2B%20l%20.
if os.name == "posix":
os.system("clear")
else:
# for windows platfrom
os.system("cls")
def get_api_id_and_hash():
print(
"Get your API ID and API HASH from my.telegram.org or @ScrapperRoBot to proceed.\n\n",
)
try:
API_ID = int(input("Please enter your API ID: "))
except ValueError:
print("APP ID must be an integer.\nQuitting...")
exit(0)
API_HASH = input("Please enter your API HASH: ")
return API_ID, API_HASH
def pyro_session():
try:
spinner("pyro")
from pyrogram import Client
x = "\bFound an existing installation of Pyrogram...\nSuccessfully Imported.\n\n"
except BaseException:
print("Installing Pyrogram...")
os.system("pip install pyrogram tgcrypto")
x = "\bDone. Installed and imported Pyrogram."
from pyrogram import Client
clear_screen()
print(ULTROID)
print(x)
# generate a session
API_ID, API_HASH = get_api_id_and_hash()
print("Enter phone number when asked.\n\n")
try:
with Client(name="ultroid", api_id=API_ID, api_hash=API_HASH, in_memory=True) as pyro:
ss = pyro.export_session_string()
pyro.send_message(
"me",
f"`{ss}`\n\nAbove is your Pyrogram Session String for @TheUltroid. **DO NOT SHARE it.**",
)
print("Session has been sent to your saved messages!")
exit(0)
except Exception as er:
print("Unexpected error occurred while creating session, make sure to validate your inputs.")
print(er) | null |
5,668 | import os
a = r"""
_ _ _ _ _ _
| | | | | | (_) | |
| | | | | |_ _ __ ___ _ __| |
| | | | | __| '__/ _ \| |/ _ |
| |__| | | |_| | | (_) | | (_| |
\____/|_|\__|_| \___/|_|\__,_|
"""
def do_input(var):
val = input(f"Enter your {var}: ")
return f"{var}={val}\n"
def clear_screen():
# clear screen
_ = os.system("clear") if os.name == "posix" else os.system("cls")
def check_for_py():
print(
"Please make sure you have python installed. \nGet it from http://python.org/\n\n",
)
try:
ch = int(
input(
"Enter Choice:\n1. Continue, python is installed.\n2. Exit and install python.\n",
),
)
except BaseException:
print("Please run the script again, and enter the choice as a number!!")
exit(0)
if ch == 1:
pass
elif ch == 2:
print("Please install python and continue!")
exit(0)
else:
print("Weren't you taught how to read? Enter a choice!!")
return
def gen_session():
print("\nProcessing...")
# https://github.com/TeamUltroid/Ultroid/main/resources/startup/locals.py#L35
os.system("python3 resources/session/ssgen.py")
def start():
clear_screen()
check_for_py()
print(f"{a}\n\n")
print("Welcome to Ultroid, lets start setting up!\n\n")
print("Cloning the repository...\n\n")
os.system("rm -rf Ultroid")
os.system("git clone https://github.com/TeamUltroid/Ultroid")
print("\n\nDone")
os.chdir("Ultroid")
clear_screen()
print(a)
print("\n\nLet's start!\n")
# generate session if needed.
sessionisneeded = input(
"Do you want to generate a new session, or have an old session string? [generate/skip]",
)
if sessionisneeded == "generate":
gen_session()
elif sessionisneeded != "skip":
print(
'Please choose "generate" to generate a session string, or "skip" to pass on.\n\nPlease run the script again!',
)
exit(0)
# start bleck megik
print("\n\nLets start entering the variables.\n\n")
varrs = [
"API_ID",
"API_HASH",
"SESSION",
"REDIS_URI",
"REDIS_PASSWORD",
]
all_done = "# Ultroid Environment Variables.\n# Do not delete this file.\n\n"
for i in varrs:
all_done += do_input(i)
clear_screen()
print(a)
print("\n\nHere are the things you've entered.\nKindly check.")
print(all_done)
isitdone = input("\n\nIs it all correct? [y/n]")
if isitdone == "y" or isitdone != "n":
# https://github.com/TeamUltroid/Ultroid/blob/31b9eb1f4f8059e0ae66adb74cb6e8174df12eac/resources/startup/locals.py#L35
f = open(".env", "w")
f.write(all_done)
else:
print("Oh, let's redo these then.")
start()
clear_screen()
print("\nCongrats. All done!\nTime to start the bot!")
print("\nInstalling requirements... This might take a while...")
os.system("pip3 install --no-cache-dir -r requirements.txt")
ask = input(
"Enter 'yes/y' to Install other requirements, required for local deployment."
)
if ask.lower().startswith("y"):
print("Started Installing...")
os.system(
"pip3 install --no-cache-dir -r resources/startup/optional-requirements.txt"
)
else:
print("Skipped!")
clear_screen()
print(a)
print("\nStarting Ultroid...")
os.system("sh startup") | null |
5,669 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
system(f"pip install {all_}")
stem("pip3 uninstall -q colorama -y")
def clear():
system("clear") | null |
5,670 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
def with_header(text):
return HEADER + "\n\n" + text
print(
f"""
{Fore.BLACK}{Back.WHITE} _____________
▄▄ ▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄
█ █ █ █ █ █ █ ▄ █ █ █ █ █
█ █ █ █ █ █▄ ▄█ █ █ █ █ ▄ █ █ ▄ █
█ █▄█ █ █ █ █ █ █▄▄█▄█ █ █ █ █ █ █ █
█ █ █▄▄▄ █ █ █ ▄▄ █ █▄█ █ █ █▄█ █
█ █ █ █ █ █ █ █ █ █ █ █
█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█ █▄▄▄█ █▄▄▄█ █▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄▄▄▄█
{Style.RESET_ALL}
{Fore.GREEN}- ULTROID Termux Installation -
The Main Aim of this script is to deploy Ultroid with basic requirements and save your phone resources.
{Fore.RESET}
{COPYRIGHT}
"""
)
print("Press 'Any Key' to continue...")
input("")
print(with_header(INFO_TEXT))
print(with_header("Installing Mandatory requirements..."))
print(
with_header(
f"\n{Fore.GREEN}# Moving toward Installing Apt-Packages{Fore.RESET}\n\n"
)
)
print("---Enter---")
print(" - A = 'Ask Y/N for each'.")
print(" - I = 'Install all'")
print(" - S = 'Skip Apt installation.'")
print(" - E = Exit.\n")
print(
with_header(
f"""
{Fore.YELLOW}# Installing other non mandatory requirements.
(You can Install them, if you want command using them to work!){Fore.RESET}
{'- '.join(list(OPT_PACKAGES.keys()))}
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
)
)
print(f"\n{Fore.RED}#EXTRA Features...\n")
print(f"{Fore.YELLOW}* Do you want to get Ultroid Logs in Colors? [Y/N] ")
print(with_header(f"\n{Fore.GREEN}You are all Done! 🥳"))
print(f"Use 'bash startup' to try running Ultroid.{Fore.RESET}")
print(
"\nYou can head over to @UltroidSupportChat, if you get stuck somewhere, and need help."
)
print("\nMade with ❤️ by @TeamUltroid...")
def ask_and_wait(text, header: bool = False):
if header:
text = with_header(text)
print(text + "\nPress 'ANY Key' to Continue or 'Ctrl+C' to exit...\n")
input("") | null |
5,671 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
print(
f"""
{Fore.BLACK}{Back.WHITE} _____________
▄▄ ▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄
█ █ █ █ █ █ █ ▄ █ █ █ █ █
█ █ █ █ █ █▄ ▄█ █ █ █ █ ▄ █ █ ▄ █
█ █▄█ █ █ █ █ █ █▄▄█▄█ █ █ █ █ █ █ █
█ █ █▄▄▄ █ █ █ ▄▄ █ █▄█ █ █ █▄█ █
█ █ █ █ █ █ █ █ █ █ █ █
█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█ █▄▄▄█ █▄▄▄█ █▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄▄▄▄█
{Style.RESET_ALL}
{Fore.GREEN}- ULTROID Termux Installation -
The Main Aim of this script is to deploy Ultroid with basic requirements and save your phone resources.
{Fore.RESET}
{COPYRIGHT}
"""
)
print("Press 'Any Key' to continue...")
input("")
print(with_header(INFO_TEXT))
print(with_header("Installing Mandatory requirements..."))
print(
with_header(
f"\n{Fore.GREEN}# Moving toward Installing Apt-Packages{Fore.RESET}\n\n"
)
)
print("---Enter---")
print(" - A = 'Ask Y/N for each'.")
print(" - I = 'Install all'")
print(" - S = 'Skip Apt installation.'")
print(" - E = Exit.\n")
print(
with_header(
f"""
{Fore.YELLOW}# Installing other non mandatory requirements.
(You can Install them, if you want command using them to work!){Fore.RESET}
{'- '.join(list(OPT_PACKAGES.keys()))}
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
)
)
print(f"\n{Fore.RED}#EXTRA Features...\n")
print(f"{Fore.YELLOW}* Do you want to get Ultroid Logs in Colors? [Y/N] ")
print(with_header(f"\n{Fore.GREEN}You are all Done! 🥳"))
print(f"Use 'bash startup' to try running Ultroid.{Fore.RESET}")
print(
"\nYou can head over to @UltroidSupportChat, if you get stuck somewhere, and need help."
)
print("\nMade with ❤️ by @TeamUltroid...")
def ask_process_info_text():
strm = input("").lower().strip()
if strm == "e":
print("Exiting...")
exit(0)
elif strm != "a":
print("Invalid Input")
print("Enter 'A' to Continue or 'E' to exit...")
ask_process_info_text() | null |
5,672 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
APT_PACKAGES = ["ffmpeg", "neofetch", "mediainfo"]
def yes_no_apt():
yes_no = input("").strip().lower()
if yes_no in ["yes", "y"]:
return True
elif yes_no in ["no", "n"]:
return False
print("Invalid Input\nRe-Enter: ")
return yes_no_apt()
print(
f"""
{Fore.BLACK}{Back.WHITE} _____________
▄▄ ▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄
█ █ █ █ █ █ █ ▄ █ █ █ █ █
█ █ █ █ █ █▄ ▄█ █ █ █ █ ▄ █ █ ▄ █
█ █▄█ █ █ █ █ █ █▄▄█▄█ █ █ █ █ █ █ █
█ █ █▄▄▄ █ █ █ ▄▄ █ █▄█ █ █ █▄█ █
█ █ █ █ █ █ █ █ █ █ █ █
█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█ █▄▄▄█ █▄▄▄█ █▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄▄▄▄█
{Style.RESET_ALL}
{Fore.GREEN}- ULTROID Termux Installation -
The Main Aim of this script is to deploy Ultroid with basic requirements and save your phone resources.
{Fore.RESET}
{COPYRIGHT}
"""
)
print("Press 'Any Key' to continue...")
input("")
print(with_header(INFO_TEXT))
print(with_header("Installing Mandatory requirements..."))
system(f"pip install {all_}")
print(
with_header(
f"\n{Fore.GREEN}# Moving toward Installing Apt-Packages{Fore.RESET}\n\n"
)
)
print("---Enter---")
print(" - A = 'Ask Y/N for each'.")
print(" - I = 'Install all'")
print(" - S = 'Skip Apt installation.'")
print(" - E = Exit.\n")
print(
with_header(
f"""
{Fore.YELLOW}# Installing other non mandatory requirements.
(You can Install them, if you want command using them to work!){Fore.RESET}
{'- '.join(list(OPT_PACKAGES.keys()))}
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
)
)
print(f"\n{Fore.RED}#EXTRA Features...\n")
print(f"{Fore.YELLOW}* Do you want to get Ultroid Logs in Colors? [Y/N] ")
print(with_header(f"\n{Fore.GREEN}You are all Done! 🥳"))
print(f"Use 'bash startup' to try running Ultroid.{Fore.RESET}")
print(
"\nYou can head over to @UltroidSupportChat, if you get stuck somewhere, and need help."
)
print("\nMade with ❤️ by @TeamUltroid...")
system("pip3 uninstall -q colorama -y")
def ask_process_apt_install():
strm = input("").lower().strip()
if strm == "e":
print("Exiting...")
exit(0)
elif strm == "a":
for apt in APT_PACKAGES:
print(f"* Do you want to install '{apt}'? [Y/N] ")
if yes_no_apt():
print(f"Installing {apt}...")
system(f"apt install {apt} -y")
else:
print(f"- Discarded {apt}.\n")
elif strm == "i":
names = " ".join(APT_PACKAGES)
print("Installing all apt-packages...")
system(f"apt install {names} -y")
elif strm != "s":
print("Invalid Input\n* Enter Again...")
ask_process_apt_install() | null |
5,673 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
OPT_PACKAGES = {
"bs4": "Used for site-scrapping (used in commands like - .gadget and many more)",
"yt-dlp": "Used for Youtuble Related Downloads...",
"youtube-search-python": "Used for youtube video search..",
"pillow": "Used for Image-Conversion related task. (size - approx 50mb ) (required for kang, convert and many more.)",
"psutil": "Used for .usage command.",
"lottie": "Used for animated sticker related conversion.",
"apscheduler": "Used in autopic/nightmode (scheduling tasks.)",
# "git+https://github.com/1danish-00/google_trans_new.git": "Used for translation purposes.",
}
def yes_no_apt():
print(
f"""
{Fore.BLACK}{Back.WHITE} _____________
▄▄ ▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄
█ █ █ █ █ █ █ ▄ █ █ █ █ █
█ █ █ █ █ █▄ ▄█ █ █ █ █ ▄ █ █ ▄ █
█ █▄█ █ █ █ █ █ █▄▄█▄█ █ █ █ █ █ █ █
█ █ █▄▄▄ █ █ █ ▄▄ █ █▄█ █ █ █▄█ █
█ █ █ █ █ █ █ █ █ █ █ █
█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█ █▄▄▄█ █▄▄▄█ █▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄▄▄▄█
{Style.RESET_ALL}
{Fore.GREEN}- ULTROID Termux Installation -
The Main Aim of this script is to deploy Ultroid with basic requirements and save your phone resources.
{Fore.RESET}
{COPYRIGHT}
"""
)
print("Press 'Any Key' to continue...")
input("")
print(with_header(INFO_TEXT))
print(with_header("Installing Mandatory requirements..."))
system(f"pip install {all_}")
print(
with_header(
f"\n{Fore.GREEN}# Moving toward Installing Apt-Packages{Fore.RESET}\n\n"
)
)
print("---Enter---")
print(" - A = 'Ask Y/N for each'.")
print(" - I = 'Install all'")
print(" - S = 'Skip Apt installation.'")
print(" - E = Exit.\n")
print(
with_header(
f"""
{Fore.YELLOW}# Installing other non mandatory requirements.
(You can Install them, if you want command using them to work!){Fore.RESET}
{'- '.join(list(OPT_PACKAGES.keys()))}
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
)
)
print(f"\n{Fore.RED}#EXTRA Features...\n")
print(f"{Fore.YELLOW}* Do you want to get Ultroid Logs in Colors? [Y/N] ")
print(with_header(f"\n{Fore.GREEN}You are all Done! 🥳"))
print(f"Use 'bash startup' to try running Ultroid.{Fore.RESET}")
print(
"\nYou can head over to @UltroidSupportChat, if you get stuck somewhere, and need help."
)
print("\nMade with ❤️ by @TeamUltroid...")
system("pip3 uninstall -q colorama -y")
def ask_and_wait_opt():
strm = input("").strip().lower()
if strm == "e":
print("Exiting...")
exit(0)
elif strm == "a":
for opt in OPT_PACKAGES.keys():
print(
f"* {Fore.YELLOW}Do you want to install '{opt}'? [Y/N]\n- {OPT_PACKAGES[opt]}"
)
if yes_no_apt():
print(f"Installing {opt}...")
system(f"pip install {opt}")
else:
print(f"{Fore.YELLOW}- Discarded {opt}.\n")
elif strm == "i":
names = " ".join(OPT_PACKAGES.keys())
print(f"{Fore.YELLOW}Installing all packages...")
system(f"pip install {names}")
elif strm != "s":
print("Invalid Input\n* Enter Again...")
ask_and_wait_opt() | null |
5,674 | from datetime import datetime
from os import path, system
from time import sleep
from colorama import Back, Fore, Style
print(
f"""
{Fore.BLACK}{Back.WHITE} _____________
▄▄ ▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄
█ █ █ █ █ █ █ ▄ █ █ █ █ █
█ █ █ █ █ █▄ ▄█ █ █ █ █ ▄ █ █ ▄ █
█ █▄█ █ █ █ █ █ █▄▄█▄█ █ █ █ █ █ █ █
█ █ █▄▄▄ █ █ █ ▄▄ █ █▄█ █ █ █▄█ █
█ █ █ █ █ █ █ █ █ █ █ █
█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█ █▄▄▄█ █▄▄▄█ █▄█▄▄▄▄▄▄▄█▄▄▄█▄▄▄▄▄▄█
{Style.RESET_ALL}
{Fore.GREEN}- ULTROID Termux Installation -
The Main Aim of this script is to deploy Ultroid with basic requirements and save your phone resources.
{Fore.RESET}
{COPYRIGHT}
"""
)
print("Press 'Any Key' to continue...")
input("")
print(with_header(INFO_TEXT))
print(with_header("Installing Mandatory requirements..."))
print(
with_header(
f"\n{Fore.GREEN}# Moving toward Installing Apt-Packages{Fore.RESET}\n\n"
)
)
print("---Enter---")
print(" - A = 'Ask Y/N for each'.")
print(" - I = 'Install all'")
print(" - S = 'Skip Apt installation.'")
print(" - E = Exit.\n")
print(
with_header(
f"""
{Fore.YELLOW}# Installing other non mandatory requirements.
(You can Install them, if you want command using them to work!){Fore.RESET}
{'- '.join(list(OPT_PACKAGES.keys()))}
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
)
)
print(f"\n{Fore.RED}#EXTRA Features...\n")
print(f"{Fore.YELLOW}* Do you want to get Ultroid Logs in Colors? [Y/N] ")
inp = input("").strip().lower()
if inp in ["yes", "y"]:
print(f"{Fore.GREEN}*Spoking the Magical Mantras*")
system("pip install coloredlogs")
else:
print("Skipped!")
print(with_header(f"\n{Fore.GREEN}You are all Done! 🥳"))
print(f"Use 'bash startup' to try running Ultroid.{Fore.RESET}")
print(
"\nYou can head over to @UltroidSupportChat, if you get stuck somewhere, and need help."
)
print("\nMade with ❤️ by @TeamUltroid...")
def ask_make_env():
strm = input("").strip().lower()
if strm in ["yes", "y"]:
print(f"{Fore.YELLOW}* Creating .env file..")
with open(".env", "a") as file:
for var in ["API_ID", "API_HASH", "SESSION", "REDIS_URI", "REDIS_PASSWORD"]:
inp = input(f"Enter {var}\n- ")
file.write(f"{var}={inp}\n")
print("* Created '.env' file successfully! 😃")
else:
print("OK!") | null |
5,675 | import base64
import ipaddress
import struct
import sys
from telethon.errors.rpcerrorlist import AuthKeyDuplicatedError
from telethon.sessions.string import _STRUCT_PREFORMAT, CURRENT_VERSION, StringSession
from ..configs import Var
from . import *
from .BaseClient import UltroidClient
def validate_session(session, logger=LOGS, _exit=True):
from strings import get_string
if session:
# Telethon Session
if session.startswith(CURRENT_VERSION):
if len(session.strip()) != 353:
logger.exception(get_string("py_c1"))
sys.exit()
return StringSession(session)
# Pyrogram Session
elif len(session) in _PYRO_FORM.keys():
data_ = struct.unpack(
_PYRO_FORM[len(session)],
base64.urlsafe_b64decode(session + "=" * (-len(session) % 4)),
)
if len(session) in [351, 356]:
auth_id = 2
else:
auth_id = 3
dc_id, auth_key = data_[0], data_[auth_id]
return StringSession(
CURRENT_VERSION
+ base64.urlsafe_b64encode(
struct.pack(
_STRUCT_PREFORMAT.format(4),
dc_id,
ipaddress.ip_address(DC_IPV4[dc_id]).packed,
443,
auth_key,
)
).decode("ascii")
)
else:
logger.exception(get_string("py_c1"))
if _exit:
sys.exit()
logger.exception(get_string("py_c2"))
if _exit:
sys.exit()
class Var:
# mandatory
API_ID = (
int(sys.argv[1]) if len(sys.argv) > 1 else config("API_ID", default=6, cast=int)
)
API_HASH = (
sys.argv[2]
if len(sys.argv) > 2
else config("API_HASH", default="eb06d4abfb49dc3eeb1aeb98ae0f581e")
)
SESSION = sys.argv[3] if len(sys.argv) > 3 else config("SESSION", default=None)
REDIS_URI = (
sys.argv[4]
if len(sys.argv) > 4
else (config("REDIS_URI", default=None) or config("REDIS_URL", default=None))
)
REDIS_PASSWORD = (
sys.argv[5] if len(sys.argv) > 5 else config("REDIS_PASSWORD", default=None)
)
# extras
BOT_TOKEN = config("BOT_TOKEN", default=None)
LOG_CHANNEL = config("LOG_CHANNEL", default=0, cast=int)
HEROKU_APP_NAME = config("HEROKU_APP_NAME", default=None)
HEROKU_API = config("HEROKU_API", default=None)
VC_SESSION = config("VC_SESSION", default=None)
ADDONS = config("ADDONS", default=False, cast=bool)
VCBOT = config("VCBOT", default=False, cast=bool)
# for railway
REDISPASSWORD = config("REDISPASSWORD", default=None)
REDISHOST = config("REDISHOST", default=None)
REDISPORT = config("REDISPORT", default=None)
REDISUSER = config("REDISUSER", default=None)
# for sql
DATABASE_URL = config("DATABASE_URL", default=None)
# for MONGODB users
MONGO_URI = config("MONGO_URI", default=None)
from . import *
class UltroidClient(TelegramClient):
def __init__(
self,
session,
api_id=None,
api_hash=None,
bot_token=None,
udB=None,
logger: Logger = LOGS,
log_attempt=True,
exit_on_error=True,
*args,
**kwargs,
):
self._cache = {}
self._dialogs = []
self._handle_error = exit_on_error
self._log_at = log_attempt
self.logger = logger
self.udB = udB
kwargs["api_id"] = api_id or Var.API_ID
kwargs["api_hash"] = api_hash or Var.API_HASH
kwargs["base_logger"] = TelethonLogger
super().__init__(session, **kwargs)
self.run_in_loop(self.start_client(bot_token=bot_token))
self.dc_id = self.session.dc_id
def __repr__(self):
return "<Ultroid.Client :\n self: {}\n bot: {}\n>".format(
self.full_name, self._bot
)
def __dict__(self):
if self.me:
return self.me.to_dict()
async def start_client(self, **kwargs):
"""function to start client"""
if self._log_at:
self.logger.info("Trying to login.")
try:
await self.start(**kwargs)
except ApiIdInvalidError:
self.logger.critical("API ID and API_HASH combination does not match!")
sys.exit()
except (AuthKeyDuplicatedError, EOFError) as er:
if self._handle_error:
self.logger.critical("String session expired. Create new!")
return sys.exit()
self.logger.critical("String session expired.")
except (AccessTokenExpiredError, AccessTokenInvalidError):
# AccessTokenError can only occur for Bot account
# And at Early Process, Its saved in DB.
self.udB.del_key("BOT_TOKEN")
self.logger.critical(
"Bot token is expired or invalid. Create new from @Botfather and add in BOT_TOKEN env variable!"
)
sys.exit()
# Save some stuff for later use...
self.me = await self.get_me()
if self.me.bot:
me = f"@{self.me.username}"
else:
setattr(self.me, "phone", None)
me = self.full_name
if self._log_at:
self.logger.info(f"Logged in as {me}")
self._bot = await self.is_bot()
async def fast_uploader(self, file, **kwargs):
"""Upload files in a faster way"""
import os
from pathlib import Path
start_time = time.time()
path = Path(file)
filename = kwargs.get("filename", path.name)
# Set to True and pass event to show progress bar.
show_progress = kwargs.get("show_progress", False)
if show_progress:
event = kwargs["event"]
# Whether to use cached file for uploading or not
use_cache = kwargs.get("use_cache", True)
# Delete original file after uploading
to_delete = kwargs.get("to_delete", False)
message = kwargs.get("message", f"Uploading {filename}...")
by_bot = self._bot
size = os.path.getsize(file)
# Don't show progress bar when file size is less than 5MB.
if size < 5 * 2 ** 20:
show_progress = False
if use_cache and self._cache and self._cache.get("upload_cache"):
for files in self._cache["upload_cache"]:
if (
files["size"] == size
and files["path"] == path
and files["name"] == filename
and files["by_bot"] == by_bot
):
if to_delete:
try:
os.remove(file)
except FileNotFoundError:
pass
return files["raw_file"], time.time() - start_time
from pyUltroid.fns.FastTelethon import upload_file
from pyUltroid.fns.helper import progress
raw_file = None
while not raw_file:
with open(file, "rb") as f:
raw_file = await upload_file(
client=self,
file=f,
filename=filename,
progress_callback=(
lambda completed, total: self.loop.create_task(
progress(completed, total, event, start_time, message)
)
)
if show_progress
else None,
)
cache = {
"by_bot": by_bot,
"size": size,
"path": path,
"name": filename,
"raw_file": raw_file,
}
if self._cache.get("upload_cache"):
self._cache["upload_cache"].append(cache)
else:
self._cache.update({"upload_cache": [cache]})
if to_delete:
try:
os.remove(file)
except FileNotFoundError:
pass
return raw_file, time.time() - start_time
async def fast_downloader(self, file, **kwargs):
"""Download files in a faster way"""
# Set to True and pass event to show progress bar.
show_progress = kwargs.get("show_progress", False)
filename = kwargs.get("filename", "")
if show_progress:
event = kwargs["event"]
# Don't show progress bar when file size is less than 10MB.
if file.size < 10 * 2 ** 20:
show_progress = False
import mimetypes
from telethon.tl.types import DocumentAttributeFilename
from pyUltroid.fns.FastTelethon import download_file
from pyUltroid.fns.helper import progress
start_time = time.time()
# Auto-generate Filename
if not filename:
try:
if isinstance(file.attributes[-1], DocumentAttributeFilename):
filename = file.attributes[-1].file_name
except IndexError:
mimetype = file.mime_type
filename = (
mimetype.split("/")[0]
+ "-"
+ str(round(start_time))
+ mimetypes.guess_extension(mimetype)
)
message = kwargs.get("message", f"Downloading {filename}...")
raw_file = None
while not raw_file:
with open(filename, "wb") as f:
raw_file = await download_file(
client=self,
location=file,
out=f,
progress_callback=(
lambda completed, total: self.loop.create_task(
progress(completed, total, event, start_time, message)
)
)
if show_progress
else None,
)
return raw_file, time.time() - start_time
def run_in_loop(self, function):
"""run inside asyncio loop"""
return self.loop.run_until_complete(function)
def run(self):
"""run asyncio loop"""
self.run_until_disconnected()
def add_handler(self, func, *args, **kwargs):
"""Add new event handler, ignoring if exists"""
if func in [_[0] for _ in self.list_event_handlers()]:
return
self.add_event_handler(func, *args, **kwargs)
def utils(self):
return telethon_utils
def full_name(self):
"""full name of Client"""
return self.utils.get_display_name(self.me)
def uid(self):
"""Client's user id"""
return self.me.id
def to_dict(self):
return dict(inspect.getmembers(self))
async def parse_id(self, text):
try:
text = int(text)
except ValueError:
pass
return await self.get_peer_id(text)
def get_string(key: str, _res: bool = True) -> Any:
lang = ULTConfig.lang or "en"
try:
return languages[lang][key]
except KeyError:
try:
en_ = languages["en"][key]
tr = translate(en_, lang_tgt=lang).replace("\ N", "\n")
if en_.count("{}") != tr.count("{}"):
tr = en_
if languages.get(lang):
languages[lang][key] = tr
else:
languages.update({lang: {key: tr}})
return tr
except KeyError:
if not _res:
return
return f"Warning: could not load any string with the key `{key}`"
except TypeError:
pass
except Exception as er:
LOGS.exception(er)
if not _res:
return None
return languages["en"].get(key) or f"Failed to load language string '{key}'"
def vc_connection(udB, ultroid_bot):
from strings import get_string
VC_SESSION = Var.VC_SESSION or udB.get_key("VC_SESSION")
if VC_SESSION and VC_SESSION != Var.SESSION:
LOGS.info("Starting up VcClient.")
try:
return UltroidClient(
validate_session(VC_SESSION, _exit=False),
log_attempt=False,
exit_on_error=False,
)
except (AuthKeyDuplicatedError, EOFError):
LOGS.info(get_string("py_c3"))
udB.del_key("VC_SESSION")
except Exception as er:
LOGS.info("While creating Client for VC.")
LOGS.exception(er)
return ultroid_bot | null |
5,676 | import os
import subprocess
import sys
from shutil import rmtree
from decouple import config
from git import Repo
from .. import *
from ..dB._core import HELP
from ..loader import Loader
from . import *
from .utils import load_addons
def _after_load(loader, module, plugin_name=""):
if not module or plugin_name.startswith("_"):
return
from strings import get_help
if doc_ := get_help(plugin_name) or module.__doc__:
try:
doc = doc_.format(i=HNDLR)
except Exception as er:
loader._logger.exception(er)
loader._logger.info(f"Error in {plugin_name}: {module}")
return
if loader.key in HELP.keys():
update_cmd = HELP[loader.key]
try:
update_cmd.update({plugin_name: doc})
except BaseException as er:
loader._logger.exception(er)
else:
try:
HELP.update({loader.key: {plugin_name: doc}})
except BaseException as em:
loader._logger.exception(em)
import os
import sys
class Loader:
def __init__(self, path="plugins", key="Official", logger: Logger = LOGS):
self.path = path
self.key = key
self._logger = logger
def load(
self,
log=True,
func=import_module,
include=None,
exclude=None,
after_load=None,
load_all=False,
):
_single = os.path.isfile(self.path)
if include:
if log:
self._logger.info("Including: {}".format("• ".join(include)))
files = glob.glob(f"{self.path}/_*.py")
for file in include:
path = f"{self.path}/{file}.py"
if os.path.exists(path):
files.append(path)
elif _single:
files = [self.path]
else:
if load_all:
files = get_all_files(self.path, ".py")
else:
files = glob.glob(f"{self.path}/*.py")
if exclude:
for path in exclude:
if not path.startswith("_"):
with contextlib.suppress(ValueError):
files.remove(f"{self.path}/{path}.py")
if log and not _single:
self._logger.info(
f"• Installing {self.key} Plugins || Count : {len(files)} •"
)
for plugin in sorted(files):
if func == import_module:
plugin = plugin.replace(".py", "").replace("/", ".").replace("\\", ".")
try:
modl = func(plugin)
except ModuleNotFoundError as er:
modl = None
self._logger.error(f"{plugin}: '{er.name}' not installed!")
continue
except Exception as exc:
modl = None
self._logger.error(f"pyUltroid - {self.key} - ERROR - {plugin}")
self._logger.exception(exc)
continue
if _single and log:
self._logger.info(f"Successfully Loaded {plugin}!")
if callable(after_load):
if func == import_module:
plugin = plugin.split(".")[-1]
after_load(self, modl, plugin_name=plugin)
def load_addons(plugin_name):
base_name = plugin_name.split("/")[-1].split("\\")[-1].replace(".py", "")
if base_name.startswith("__"):
return
from pyUltroid import fns
from .. import HNDLR, LOGS, asst, udB, ultroid_bot
from .._misc import _supporter as config
from .._misc._assistant import asst_cmd, callback, in_pattern
from .._misc._decorators import ultroid_cmd
from .._misc._supporter import Config, admin_cmd, sudo_cmd
from .._misc._wrappers import eod, eor
from ..configs import Var
from ..dB._core import HELP
name = plugin_name.replace("/", ".").replace("\\", ".").replace(".py", "")
spec = util.spec_from_file_location(name, plugin_name)
mod = util.module_from_spec(spec)
for path in configPaths:
modules[path] = config
modules["pyUltroid.functions"] = fns
mod.LOG_CHANNEL = udB.get_key("LOG_CHANNEL")
mod.udB = udB
mod.asst = asst
mod.tgbot = asst
mod.ultroid_bot = ultroid_bot
mod.ub = ultroid_bot
mod.bot = ultroid_bot
mod.ultroid = ultroid_bot
mod.borg = ultroid_bot
mod.telebot = ultroid_bot
mod.jarvis = ultroid_bot
mod.friday = ultroid_bot
mod.eod = eod
mod.edit_delete = eod
mod.LOGS = LOGS
mod.in_pattern = in_pattern
mod.hndlr = HNDLR
mod.handler = HNDLR
mod.HNDLR = HNDLR
mod.CMD_HNDLR = HNDLR
mod.Config = Config
mod.Var = Var
mod.eor = eor
mod.edit_or_reply = eor
mod.asst_cmd = asst_cmd
mod.ultroid_cmd = ultroid_cmd
mod.on_cmd = ultroid_cmd
mod.callback = callback
mod.Redis = udB.get_key
mod.admin_cmd = admin_cmd
mod.sudo_cmd = sudo_cmd
mod.HELP = HELP.get("Addons", {})
mod.CMD_HELP = HELP.get("Addons", {})
spec.loader.exec_module(mod)
modules[name] = mod
doc = modules[name].__doc__.format(i=HNDLR) if modules[name].__doc__ else ""
if "Addons" in HELP.keys():
update_cmd = HELP["Addons"]
try:
update_cmd.update({base_name: doc})
except BaseException:
pass
else:
try:
HELP.update({"Addons": {base_name: doc}})
except BaseException as em:
pass
def load_other_plugins(addons=None, pmbot=None, manager=None, vcbot=None):
# for official
_exclude = udB.get_key("EXCLUDE_OFFICIAL") or config("EXCLUDE_OFFICIAL", None)
_exclude = _exclude.split() if _exclude else []
# "INCLUDE_ONLY" was added to reduce Big List in "EXCLUDE_OFFICIAL" Plugin
_in_only = udB.get_key("INCLUDE_ONLY") or config("INCLUDE_ONLY", None)
_in_only = _in_only.split() if _in_only else []
Loader().load(include=_in_only, exclude=_exclude, after_load=_after_load)
# for assistant
if not USER_MODE and not udB.get_key("DISABLE_AST_PLUGINS"):
_ast_exc = ["pmbot"]
if _in_only and "games" not in _in_only:
_ast_exc.append("games")
Loader(path="assistant").load(
log=False, exclude=_ast_exc, after_load=_after_load
)
# for addons
if addons:
if url := udB.get_key("ADDONS_URL"):
subprocess.run(f"git clone -q {url} addons", shell=True)
if os.path.exists("addons") and not os.path.exists("addons/.git"):
rmtree("addons")
if not os.path.exists("addons"):
subprocess.run(
f"git clone -q -b {Repo().active_branch} https://github.com/TeamUltroid/UltroidAddons.git addons",
shell=True,
)
else:
subprocess.run("cd addons && git pull -q && cd ..", shell=True)
if not os.path.exists("addons"):
subprocess.run(
"git clone -q https://github.com/TeamUltroid/UltroidAddons.git addons",
shell=True,
)
if os.path.exists("addons/addons.txt"):
# generally addons req already there so it won't take much time
# subprocess.run(
# "rm -rf /usr/local/lib/python3.*/site-packages/pip/_vendor/.wh*"
# )
subprocess.run(
f"{sys.executable} -m pip install --no-cache-dir -q -r ./addons/addons.txt",
shell=True,
)
_exclude = udB.get_key("EXCLUDE_ADDONS")
_exclude = _exclude.split() if _exclude else []
_in_only = udB.get_key("INCLUDE_ADDONS")
_in_only = _in_only.split() if _in_only else []
Loader(path="addons", key="Addons").load(
func=load_addons,
include=_in_only,
exclude=_exclude,
after_load=_after_load,
load_all=True,
)
if not USER_MODE:
# group manager
if manager:
Loader(path="assistant/manager", key="Group Manager").load()
# chat via assistant
if pmbot:
Loader(path="assistant/pmbot.py").load(log=False)
# vc bot
if vcbot and not vcClient._bot:
try:
import pytgcalls # ignore: pylint
if os.path.exists("vcbot"):
if os.path.exists("vcbot/.git"):
subprocess.run("cd vcbot && git pull", shell=True)
else:
rmtree("vcbot")
if not os.path.exists("vcbot"):
subprocess.run(
"git clone https://github.com/TeamUltroid/VcBot vcbot", shell=True
)
try:
if not os.path.exists("vcbot/downloads"):
os.mkdir("vcbot/downloads")
Loader(path="vcbot", key="VCBot").load(after_load=_after_load)
except FileNotFoundError as e:
LOGS.error(f"{e} Skipping VCBot Installation.")
except ModuleNotFoundError:
LOGS.error("'pytgcalls' not installed!\nSkipping loading of VCBOT.") | null |
5,677 |
def _fix_logging(handler):
handler._builtin_open = open
def _new_open(self):
open_func = self._builtin_open
return open_func(self.baseFilename, self.mode)
setattr(handler, "_open", _new_open) | null |
5,678 |
def _ask_input():
# Ask for Input even on Vps and other platforms.
def new_input(*args, **kwargs):
raise EOFError("args=" + str(args) + ", kwargs=" + str(kwargs))
__builtins__["input"] = new_input | null |
5,679 | import ast
import os
import sys
from .. import run_as_module
from . import *
Redis = MongoClient = psycopg2 = Database = None
if Var.REDIS_URI or Var.REDISHOST:
try:
from redis import Redis
except ImportError:
LOGS.info("Installing 'redis' for database.")
os.system(f"{sys.executable} -m pip install -q redis hiredis")
from redis import Redis
elif Var.MONGO_URI:
try:
from pymongo import MongoClient
except ImportError:
LOGS.info("Installing 'pymongo' for database.")
os.system(f"{sys.executable} -m pip install -q pymongo[srv]")
from pymongo import MongoClient
elif Var.DATABASE_URL:
try:
import psycopg2
except ImportError:
LOGS.info("Installing 'pyscopg2' for database.")
os.system(f"{sys.executable} -m pip install -q psycopg2-binary")
import psycopg2
else:
try:
from localdb import Database
except ImportError:
LOGS.info("Using local file as database.")
os.system(f"{sys.executable} -m pip install -q localdb.json")
from localdb import Database
class MongoDB(_BaseDatabase):
def __init__(self, key, dbname="UltroidDB"):
def __repr__(self):
def name(self):
def usage(self):
def ping(self):
def keys(self):
def set(self, key, value):
def delete(self, key):
def get(self, key):
def flushall(self):
class SqlDB(_BaseDatabase):
def __init__(self, url):
def name(self):
def usage(self):
def keys(self):
def get(self, variable):
def set(self, key, value):
def delete(self, key):
def flushall(self):
class RedisDB(_BaseDatabase):
def __init__(
self,
host,
port,
password,
platform="",
logger=LOGS,
*args,
**kwargs,
):
def name(self):
def usage(self):
class LocalDB(_BaseDatabase):
def __init__(self):
def name(self):
def keys(self):
def __repr__(self):
class Var:
def UltroidDB():
_er = False
from .. import HOSTED_ON
try:
if Redis:
return RedisDB(
host=Var.REDIS_URI or Var.REDISHOST,
password=Var.REDIS_PASSWORD or Var.REDISPASSWORD,
port=Var.REDISPORT,
platform=HOSTED_ON,
decode_responses=True,
socket_timeout=5,
retry_on_timeout=True,
)
elif MongoClient:
return MongoDB(Var.MONGO_URI)
elif psycopg2:
return SqlDB(Var.DATABASE_URL)
else:
LOGS.critical(
"No DB requirement fullfilled!\nPlease install redis, mongo or sql dependencies...\nTill then using local file as database."
)
return LocalDB()
except BaseException as err:
LOGS.exception(err)
exit() | null |
5,680 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
db_url = 0
class Var:
# mandatory
API_ID = (
int(sys.argv[1]) if len(sys.argv) > 1 else config("API_ID", default=6, cast=int)
)
API_HASH = (
sys.argv[2]
if len(sys.argv) > 2
else config("API_HASH", default="eb06d4abfb49dc3eeb1aeb98ae0f581e")
)
SESSION = sys.argv[3] if len(sys.argv) > 3 else config("SESSION", default=None)
REDIS_URI = (
sys.argv[4]
if len(sys.argv) > 4
else (config("REDIS_URI", default=None) or config("REDIS_URL", default=None))
)
REDIS_PASSWORD = (
sys.argv[5] if len(sys.argv) > 5 else config("REDIS_PASSWORD", default=None)
)
# extras
BOT_TOKEN = config("BOT_TOKEN", default=None)
LOG_CHANNEL = config("LOG_CHANNEL", default=0, cast=int)
HEROKU_APP_NAME = config("HEROKU_APP_NAME", default=None)
HEROKU_API = config("HEROKU_API", default=None)
VC_SESSION = config("VC_SESSION", default=None)
ADDONS = config("ADDONS", default=False, cast=bool)
VCBOT = config("VCBOT", default=False, cast=bool)
# for railway
REDISPASSWORD = config("REDISPASSWORD", default=None)
REDISHOST = config("REDISHOST", default=None)
REDISPORT = config("REDISPORT", default=None)
REDISUSER = config("REDISUSER", default=None)
# for sql
DATABASE_URL = config("DATABASE_URL", default=None)
# for MONGODB users
MONGO_URI = config("MONGO_URI", default=None)
async def autoupdate_local_database():
from .. import Var, asst, udB, ultroid_bot
global db_url
db_url = (
udB.get_key("TGDB_URL") or Var.TGDB_URL or ultroid_bot._cache.get("TGDB_URL")
)
if db_url:
_split = db_url.split("/")
_channel = _split[-2]
_id = _split[-1]
try:
await asst.edit_message(
int(_channel) if _channel.isdigit() else _channel,
message=_id,
file="database.json",
text="**Do not delete this file.**",
)
except MessageNotModifiedError:
return
except MessageIdInvalidError:
pass
try:
LOG_CHANNEL = (
udB.get_key("LOG_CHANNEL")
or Var.LOG_CHANNEL
or asst._cache.get("LOG_CHANNEL")
or "me"
)
msg = await asst.send_message(
LOG_CHANNEL, "**Do not delete this file.**", file="database.json"
)
asst._cache["TGDB_URL"] = msg.message_link
udB.set_key("TGDB_URL", msg.message_link)
except Exception as ex:
LOGS.error(f"Error on autoupdate_local_database: {ex}") | null |
5,681 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
The provided code snippet includes necessary dependencies for implementing the `update_envs` function. Write a Python function `def update_envs()` to solve the following problem:
Update Var. attributes to udB
Here is the function:
def update_envs():
"""Update Var. attributes to udB"""
from .. import udB
_envs = [*list(os.environ)]
if ".env" in os.listdir("."):
[_envs.append(_) for _ in list(RepositoryEnv(config._find_file(".")).data)]
for envs in _envs:
if (
envs in ["LOG_CHANNEL", "BOT_TOKEN", "BOTMODE", "DUAL_MODE", "language"]
or envs in udB.keys()
):
if _value := os.environ.get(envs):
udB.set_key(envs, _value)
else:
udB.set_key(envs, config.config.get(envs)) | Update Var. attributes to udB |
5,682 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
class ULTConfig:
lang = "en"
thumb = "resources/extras/ultroid.jpg"
from . import *
async def download_file(link, name, validate=False):
"""for files, without progress callback with aiohttp"""
async def _download(content):
if validate and "application/json" in content.headers.get("Content-Type"):
return None, await content.json()
with open(name, "wb") as file:
file.write(await content.read())
return name, ""
return await async_searcher(link, evaluate=_download)
async def startup_stuff():
from .. import udB
x = ["resources/auth", "resources/downloads"]
for x in x:
if not os.path.isdir(x):
os.mkdir(x)
CT = udB.get_key("CUSTOM_THUMBNAIL")
if CT:
path = "resources/extras/thumbnail.jpg"
ULTConfig.thumb = path
try:
await download_file(CT, path)
except Exception as er:
LOGS.exception(er)
elif CT is False:
ULTConfig.thumb = None
GT = udB.get_key("GDRIVE_AUTH_TOKEN")
if GT:
with open("resources/auth/gdrive_creds.json", "w") as t_file:
t_file.write(GT)
if udB.get_key("AUTH_TOKEN"):
udB.del_key("AUTH_TOKEN")
MM = udB.get_key("MEGA_MAIL")
MP = udB.get_key("MEGA_PASS")
if MM and MP:
with open(".megarc", "w") as mega:
mega.write(f"[Login]\nUsername = {MM}\nPassword = {MP}")
TZ = udB.get_key("TIMEZONE")
if TZ and timezone:
try:
timezone(TZ)
os.environ["TZ"] = TZ
time.tzset()
except AttributeError as er:
LOGS.debug(er)
except BaseException:
LOGS.critical(
"Incorrect Timezone ,\nCheck Available Timezone From Here https://graph.org/Ultroid-06-18-2\nSo Time is Default UTC"
)
os.environ["TZ"] = "UTC"
time.tzset() | null |
5,683 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
async def enable_inline(ultroid_bot, username):
async def autobot():
from .. import udB, ultroid_bot
if udB.get_key("BOT_TOKEN"):
return
await ultroid_bot.start()
LOGS.info("MAKING A TELEGRAM BOT FOR YOU AT @BotFather, Kindly Wait")
who = ultroid_bot.me
name = who.first_name + "'s Bot"
if who.username:
username = who.username + "_bot"
else:
username = "ultroid_" + (str(who.id))[5:] + "_bot"
bf = "@BotFather"
await ultroid_bot(UnblockRequest(bf))
await ultroid_bot.send_message(bf, "/cancel")
await asyncio.sleep(1)
await ultroid_bot.send_message(bf, "/newbot")
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages(bf, limit=1))[0].text
if isdone.startswith("That I cannot do.") or "20 bots" in isdone:
LOGS.critical(
"Please make a Bot from @BotFather and add it's token in BOT_TOKEN, as an env var and restart me."
)
import sys
sys.exit(1)
await ultroid_bot.send_message(bf, name)
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages(bf, limit=1))[0].text
if not isdone.startswith("Good."):
await ultroid_bot.send_message(bf, "My Assistant Bot")
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages(bf, limit=1))[0].text
if not isdone.startswith("Good."):
LOGS.critical(
"Please make a Bot from @BotFather and add it's token in BOT_TOKEN, as an env var and restart me."
)
import sys
sys.exit(1)
await ultroid_bot.send_message(bf, username)
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages(bf, limit=1))[0].text
await ultroid_bot.send_read_acknowledge("botfather")
if isdone.startswith("Sorry,"):
ran = randint(1, 100)
username = "ultroid_" + (str(who.id))[6:] + str(ran) + "_bot"
await ultroid_bot.send_message(bf, username)
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages(bf, limit=1))[0].text
if isdone.startswith("Done!"):
token = isdone.split("`")[1]
udB.set_key("BOT_TOKEN", token)
await enable_inline(ultroid_bot, username)
LOGS.info(
f"Done. Successfully created @{username} to be used as your assistant bot!"
)
else:
LOGS.info(
"Please Delete Some Of your Telegram bots at @Botfather or Set Var BOT_TOKEN with token of a bot"
)
import sys
sys.exit(1) | null |
5,684 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
from . import *
async def download_file(link, name, validate=False):
"""for files, without progress callback with aiohttp"""
async def _download(content):
if validate and "application/json" in content.headers.get("Content-Type"):
return None, await content.json()
with open(name, "wb") as file:
file.write(await content.read())
return name, ""
return await async_searcher(link, evaluate=_download)
async def autopilot():
from .. import asst, udB, ultroid_bot
channel = udB.get_key("LOG_CHANNEL")
new_channel = None
if channel:
try:
chat = await ultroid_bot.get_entity(channel)
except BaseException as err:
LOGS.exception(err)
udB.del_key("LOG_CHANNEL")
channel = None
if not channel:
async def _save(exc):
udB._cache["LOG_CHANNEL"] = ultroid_bot.me.id
await asst.send_message(
ultroid_bot.me.id, f"Failed to Create Log Channel due to {exc}.."
)
if ultroid_bot._bot:
msg_ = "'LOG_CHANNEL' not found! Add it in order to use 'BOTMODE'"
LOGS.error(msg_)
return await _save(msg_)
LOGS.info("Creating a Log Channel for You!")
try:
r = await ultroid_bot(
CreateChannelRequest(
title="My Ultroid Logs",
about="My Ultroid Log Group\n\n Join @TeamUltroid",
megagroup=True,
),
)
except ChannelsTooMuchError as er:
LOGS.critical(
"You Are in Too Many Channels & Groups , Leave some And Restart The Bot"
)
return await _save(str(er))
except BaseException as er:
LOGS.exception(er)
LOGS.info(
"Something Went Wrong , Create A Group and set its id on config var LOG_CHANNEL."
)
return await _save(str(er))
new_channel = True
chat = r.chats[0]
channel = get_peer_id(chat)
udB.set_key("LOG_CHANNEL", channel)
assistant = True
try:
await ultroid_bot.get_permissions(int(channel), asst.me.username)
except UserNotParticipantError:
try:
await ultroid_bot(InviteToChannelRequest(int(channel), [asst.me.username]))
except BaseException as er:
LOGS.info("Error while Adding Assistant to Log Channel")
LOGS.exception(er)
assistant = False
except BaseException as er:
assistant = False
LOGS.exception(er)
if assistant and new_channel:
try:
achat = await asst.get_entity(int(channel))
except BaseException as er:
achat = None
LOGS.info("Error while getting Log channel from Assistant")
LOGS.exception(er)
if achat and not achat.admin_rights:
rights = ChatAdminRights(
add_admins=True,
invite_users=True,
change_info=True,
ban_users=True,
delete_messages=True,
pin_messages=True,
anonymous=False,
manage_call=True,
)
try:
await ultroid_bot(
EditAdminRequest(
int(channel), asst.me.username, rights, "Assistant"
)
)
except ChatAdminRequiredError:
LOGS.info(
"Failed to promote 'Assistant Bot' in 'Log Channel' due to 'Admin Privileges'"
)
except BaseException as er:
LOGS.info("Error while promoting assistant in Log Channel..")
LOGS.exception(er)
if isinstance(chat.photo, ChatPhotoEmpty):
photo, _ = await download_file(
"https://graph.org/file/27c6812becf6f376cbb10.jpg", "channelphoto.jpg"
)
ll = await ultroid_bot.upload_file(photo)
try:
await ultroid_bot(
EditPhotoRequest(int(channel), InputChatUploadedPhoto(ll))
)
except BaseException as er:
LOGS.exception(er)
os.remove(photo) | null |
5,685 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
from . import *
async def download_file(link, name, validate=False):
async def customize():
from .. import asst, udB, ultroid_bot
rem = None
try:
chat_id = udB.get_key("LOG_CHANNEL")
if asst.me.photo:
return
LOGS.info("Customising Ur Assistant Bot in @BOTFATHER")
UL = f"@{asst.me.username}"
if not ultroid_bot.me.username:
sir = ultroid_bot.me.first_name
else:
sir = f"@{ultroid_bot.me.username}"
file = random.choice(
[
"https://graph.org/file/92cd6dbd34b0d1d73a0da.jpg",
"https://graph.org/file/a97973ee0425b523cdc28.jpg",
"resources/extras/ultroid_assistant.jpg",
]
)
if not os.path.exists(file):
file, _ = await download_file(file, "profile.jpg")
rem = True
msg = await asst.send_message(
chat_id, "**Auto Customisation** Started on @Botfather"
)
await asyncio.sleep(1)
await ultroid_bot.send_message("botfather", "/cancel")
await asyncio.sleep(1)
await ultroid_bot.send_message("botfather", "/setuserpic")
await asyncio.sleep(1)
isdone = (await ultroid_bot.get_messages("botfather", limit=1))[0].text
if isdone.startswith("Invalid bot"):
LOGS.info("Error while trying to customise assistant, skipping...")
return
await ultroid_bot.send_message("botfather", UL)
await asyncio.sleep(1)
await ultroid_bot.send_file("botfather", file)
await asyncio.sleep(2)
await ultroid_bot.send_message("botfather", "/setabouttext")
await asyncio.sleep(1)
await ultroid_bot.send_message("botfather", UL)
await asyncio.sleep(1)
await ultroid_bot.send_message(
"botfather", f"✨ Hello ✨!! I'm Assistant Bot of {sir}"
)
await asyncio.sleep(2)
await ultroid_bot.send_message("botfather", "/setdescription")
await asyncio.sleep(1)
await ultroid_bot.send_message("botfather", UL)
await asyncio.sleep(1)
await ultroid_bot.send_message(
"botfather",
f"✨ Powerful Ultroid Assistant Bot ✨\n✨ Master ~ {sir} ✨\n\n✨ Powered By ~ @TeamUltroid ✨",
)
await asyncio.sleep(2)
await msg.edit("Completed **Auto Customisation** at @BotFather.")
if rem:
os.remove(file)
LOGS.info("Customisation Done")
except Exception as e:
LOGS.exception(e) | null |
5,686 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
def load_addons(plugin_name):
base_name = plugin_name.split("/")[-1].split("\\")[-1].replace(".py", "")
if base_name.startswith("__"):
return
from pyUltroid import fns
from .. import HNDLR, LOGS, asst, udB, ultroid_bot
from .._misc import _supporter as config
from .._misc._assistant import asst_cmd, callback, in_pattern
from .._misc._decorators import ultroid_cmd
from .._misc._supporter import Config, admin_cmd, sudo_cmd
from .._misc._wrappers import eod, eor
from ..configs import Var
from ..dB._core import HELP
name = plugin_name.replace("/", ".").replace("\\", ".").replace(".py", "")
spec = util.spec_from_file_location(name, plugin_name)
mod = util.module_from_spec(spec)
for path in configPaths:
modules[path] = config
modules["pyUltroid.functions"] = fns
mod.LOG_CHANNEL = udB.get_key("LOG_CHANNEL")
mod.udB = udB
mod.asst = asst
mod.tgbot = asst
mod.ultroid_bot = ultroid_bot
mod.ub = ultroid_bot
mod.bot = ultroid_bot
mod.ultroid = ultroid_bot
mod.borg = ultroid_bot
mod.telebot = ultroid_bot
mod.jarvis = ultroid_bot
mod.friday = ultroid_bot
mod.eod = eod
mod.edit_delete = eod
mod.LOGS = LOGS
mod.in_pattern = in_pattern
mod.hndlr = HNDLR
mod.handler = HNDLR
mod.HNDLR = HNDLR
mod.CMD_HNDLR = HNDLR
mod.Config = Config
mod.Var = Var
mod.eor = eor
mod.edit_or_reply = eor
mod.asst_cmd = asst_cmd
mod.ultroid_cmd = ultroid_cmd
mod.on_cmd = ultroid_cmd
mod.callback = callback
mod.Redis = udB.get_key
mod.admin_cmd = admin_cmd
mod.sudo_cmd = sudo_cmd
mod.HELP = HELP.get("Addons", {})
mod.CMD_HELP = HELP.get("Addons", {})
spec.loader.exec_module(mod)
modules[name] = mod
doc = modules[name].__doc__.format(i=HNDLR) if modules[name].__doc__ else ""
if "Addons" in HELP.keys():
update_cmd = HELP["Addons"]
try:
update_cmd.update({base_name: doc})
except BaseException:
pass
else:
try:
HELP.update({"Addons": {base_name: doc}})
except BaseException as em:
pass
async def plug(plugin_channels):
from .. import ultroid_bot
from .utils import load_addons
if ultroid_bot._bot:
LOGS.info("Plugin Channels can't be used in 'BOTMODE'")
return
if os.path.exists("addons") and not os.path.exists("addons/.git"):
shutil.rmtree("addons")
if not os.path.exists("addons"):
os.mkdir("addons")
if not os.path.exists("addons/__init__.py"):
with open("addons/__init__.py", "w") as f:
f.write("from plugins import *\n\nbot = ultroid_bot")
LOGS.info("• Loading Plugins from Plugin Channel(s) •")
for chat in plugin_channels:
LOGS.info(f"{'•'*4} {chat}")
try:
async for x in ultroid_bot.iter_messages(
chat, search=".py", filter=InputMessagesFilterDocument, wait_time=10
):
plugin = "addons/" + x.file.name.replace("_", "-").replace("|", "-")
if not os.path.exists(plugin):
await asyncio.sleep(0.6)
if x.text == "#IGNORE":
continue
plugin = await x.download_media(plugin)
try:
load_addons(plugin)
except Exception as e:
LOGS.info(f"Ultroid - PLUGIN_CHANNEL - ERROR - {plugin}")
LOGS.exception(e)
os.remove(plugin)
except Exception as er:
LOGS.exception(er) | null |
5,687 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
from .. import *
async def fetch_ann():
from .. import asst, udB
from ..fns.tools import async_searcher
get_ = udB.get_key("OLDANN") or []
chat_id = udB.get_key("LOG_CHANNEL")
try:
updts = await async_searcher(
"https://ultroid-api.vercel.app/announcements", post=True, re_json=True
)
for upt in updts:
key = list(upt.keys())[0]
if key not in get_:
cont = upt[key]
if isinstance(cont, dict) and cont.get("lang"):
if cont["lang"] != (udB.get_key("language") or "en"):
continue
cont = cont["msg"]
if isinstance(cont, str):
await asst.send_message(chat_id, cont)
elif isinstance(cont, dict) and cont.get("chat"):
await asst.forward_messages(chat_id, cont["msg_id"], cont["chat"])
else:
LOGS.info(cont)
LOGS.info(
"Invalid Type of Announcement Detected!\nMake sure you are on latest version.."
)
get_.append(key)
udB.set_key("OLDANN", get_)
except Exception as er:
LOGS.exception(er) | null |
5,688 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
from . import *
def inline_mention(user, custom=None, html=False):
async def updater():
async def ready():
from .. import asst, udB, ultroid_bot
chat_id = udB.get_key("LOG_CHANNEL")
spam_sent = None
if not udB.get_key("INIT_DEPLOY"): # Detailed Message at Initial Deploy
MSG = """🎇 **Thanks for Deploying Ultroid Userbot!**
• Here, are the Some Basic stuff from, where you can Know, about its Usage."""
PHOTO = "https://graph.org/file/54a917cc9dbb94733ea5f.jpg"
BTTS = Button.inline("• Click to Start •", "initft_2")
udB.set_key("INIT_DEPLOY", "Done")
else:
MSG = f"**Ultroid has been deployed!**\n➖➖➖➖➖➖➖➖➖➖\n**UserMode**: {inline_mention(ultroid_bot.me)}\n**Assistant**: @{asst.me.username}\n➖➖➖➖➖➖➖➖➖➖\n**Support**: @TeamUltroid\n➖➖➖➖➖➖➖➖➖➖"
BTTS, PHOTO = None, None
prev_spam = udB.get_key("LAST_UPDATE_LOG_SPAM")
if prev_spam:
try:
await ultroid_bot.delete_messages(chat_id, int(prev_spam))
except Exception as E:
LOGS.info("Error while Deleting Previous Update Message :" + str(E))
if await updater():
BTTS = Button.inline("Update Available", "updtavail")
try:
spam_sent = await asst.send_message(chat_id, MSG, file=PHOTO, buttons=BTTS)
except ValueError as e:
try:
await (await ultroid_bot.send_message(chat_id, str(e))).delete()
spam_sent = await asst.send_message(chat_id, MSG, file=PHOTO, buttons=BTTS)
except Exception as g:
LOGS.info(g)
except Exception as el:
LOGS.info(el)
try:
spam_sent = await ultroid_bot.send_message(chat_id, MSG)
except Exception as ef:
LOGS.exception(ef)
if spam_sent and not spam_sent.media:
udB.set_key("LAST_UPDATE_LOG_SPAM", spam_sent.id) | null |
5,689 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
async def WasItRestart(udb):
key = udb.get_key("_RESTART")
if not key:
return
from .. import asst, ultroid_bot
try:
data = key.split("_")
who = asst if data[0] == "bot" else ultroid_bot
await who.edit_message(
int(data[1]), int(data[2]), "__Restarted Successfully.__"
)
except Exception as er:
LOGS.exception(er)
udb.del_key("_RESTART") | null |
5,690 | import asyncio
import os
import random
import shutil
import time
from random import randint
from ..configs import Var
from telethon.errors import (
ChannelsTooMuchError,
ChatAdminRequiredError,
MessageIdInvalidError,
MessageNotModifiedError,
UserNotParticipantError,
)
from telethon.tl.custom import Button
from telethon.tl.functions.channels import (
CreateChannelRequest,
EditAdminRequest,
EditPhotoRequest,
InviteToChannelRequest,
)
from telethon.tl.functions.contacts import UnblockRequest
from telethon.tl.types import (
ChatAdminRights,
ChatPhotoEmpty,
InputChatUploadedPhoto,
InputMessagesFilterDocument,
)
from telethon.utils import get_peer_id
from decouple import config, RepositoryEnv
from .. import LOGS, ULTConfig
from ..fns.helper import download_file, inline_mention, updater
def _version_changes(udb):
for _ in [
"BOT_USERS",
"BOT_BLS",
"VC_SUDOS",
"SUDOS",
"CLEANCHAT",
"LOGUSERS",
"PLUGIN_CHANNEL",
"CH_SOURCE",
"CH_DESTINATION",
"BROADCAST",
]:
key = udb.get_key(_)
if key and str(key)[0] != "[":
key = udb.get(_)
new_ = [
int(z) if z.isdigit() or (z.startswith("-") and z[1:].isdigit()) else z
for z in key.split()
]
udb.set_key(_, new_) | null |
5,691 | from asyncio import sleep
from telethon.errors import MessageDeleteForbiddenError, MessageNotModifiedError
from telethon.tl.custom import Message
from telethon.tl.types import MessageService
async def _try_delete(event):
try:
return await event.delete()
except (MessageDeleteForbiddenError):
pass
except BaseException as er:
from . import LOGS
LOGS.error("Error while Deleting Message..")
LOGS.exception(er) | null |
5,692 | from .. import udB
def get_stuff():
return udB.get_key("FILTERS") or {}
def rem_all_filter(chat):
ok = get_stuff()
if ok.get(chat):
ok.pop(chat)
udB.set_key("FILTERS", ok) | null |
5,693 | from .. import udB
def add_black_chat(chat_id):
chat = udB.get_key("BLACKLIST_CHATS") or []
if chat_id not in chat:
chat.append(chat_id)
return udB.set_key("BLACKLIST_CHATS", chat) | null |
5,694 | from .. import udB
def rem_black_chat(chat_id):
chat = udB.get_key("BLACKLIST_CHATS") or []
if chat_id in chat:
chat.remove(chat_id)
return udB.set_key("BLACKLIST_CHATS", chat) | null |
5,695 | from .. import udB
def get_stuff():
return udB.get_key("BOTCHAT") or {}
def add_stuff(msg_id, user_id):
ok = get_stuff()
ok.update({msg_id: user_id})
return udB.set_key("BOTCHAT", ok) | null |
5,696 | from .. import udB
def get_stuff():
return udB.get_key("BOTCHAT") or {}
def get_who(msg_id):
ok = get_stuff()
if ok.get(msg_id):
return ok[msg_id] | null |
5,697 | from .. import udB
def get_vcsudos():
return udB.get_key("VC_SUDOS") or []
def add_vcsudo(id):
sudos = get_vcsudos()
sudos.append(id)
return udB.set_key("VC_SUDOS", sudos) | null |
5,698 | from .. import udB
def get_vcsudos():
return udB.get_key("VC_SUDOS") or []
def is_vcsudo(id):
return id in get_vcsudos()
def del_vcsudo(id):
if is_vcsudo(id):
sudos = get_vcsudos()
sudos.remove(id)
return udB.set_key("VC_SUDOS", sudos) | null |
5,699 | from .. import udB
def get_stuff():
def rem_all_note(chat):
ok = get_stuff()
if ok.get(int(chat)):
ok.pop(int(chat))
return udB.set_key("NOTE", ok) | null |
5,700 | import asyncio
import hashlib
import logging
import math
import os
from collections import defaultdict
from typing import (
AsyncGenerator,
Awaitable,
BinaryIO,
DefaultDict,
List,
Optional,
Tuple,
Union,
)
from telethon import TelegramClient, helpers, utils
from telethon.crypto import AuthKey
from telethon.helpers import _maybe_await
from telethon.network import MTProtoSender
from telethon.tl.alltlobjects import LAYER
from telethon.tl.functions import InvokeWithLayerRequest
from telethon.tl.functions.auth import (
ExportAuthorizationRequest,
ImportAuthorizationRequest,
)
from telethon.tl.functions.upload import (
GetFileRequest,
SaveBigFilePartRequest,
SaveFilePartRequest,
)
from telethon.tl.types import (
Document,
InputDocumentFileLocation,
InputFile,
InputFileBig,
InputFileLocation,
InputPeerPhotoFileLocation,
InputPhotoFileLocation,
TypeInputFile,
)
async def _internal_transfer_to_telegram(
client: TelegramClient,
response: BinaryIO,
filename: str,
progress_callback: callable,
) -> Tuple[TypeInputFile, int]:
file_id = helpers.generate_random_long()
file_size = os.path.getsize(response.name)
hash_md5 = hashlib.md5()
uploader = ParallelTransferrer(client)
part_size, part_count, is_large = await uploader.init_upload(file_id, file_size)
buffer = bytearray()
for data in stream_file(response):
if progress_callback:
try:
await _maybe_await(progress_callback(response.tell(), file_size))
except BaseException:
pass
if not is_large:
hash_md5.update(data)
if len(buffer) == 0 and len(data) == part_size:
await uploader.upload(data)
continue
new_len = len(buffer) + len(data)
if new_len >= part_size:
cutoff = part_size - len(buffer)
buffer.extend(data[:cutoff])
await uploader.upload(bytes(buffer))
buffer.clear()
buffer.extend(data[cutoff:])
else:
buffer.extend(data)
if len(buffer) > 0:
await uploader.upload(bytes(buffer))
await uploader.finish_upload()
if is_large:
return InputFileBig(file_id, part_count, filename), file_size
return InputFile(file_id, part_count, filename, hash_md5.hexdigest()), file_size
async def upload_file(
client: TelegramClient,
file: BinaryIO,
filename: str,
progress_callback: callable = None,
) -> TypeInputFile:
return (
await _internal_transfer_to_telegram(client, file, filename, progress_callback)
)[0] | null |
5,701 | import json
import math
import os
import random
import re
import secrets
import ssl
from io import BytesIO
from json.decoder import JSONDecodeError
from traceback import format_exc
import requests
from .. import *
from ..exceptions import DependencyMissingError
from . import some_random_headers
from .helper import async_searcher, bash, run_async
from urllib.parse import quote, unquote
from telethon import Button
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
def text_set(text):
lines = []
if len(text) <= 55:
lines.append(text)
else:
all_lines = text.split("\n")
for line in all_lines:
if len(line) <= 55:
lines.append(line)
else:
k = len(line) // 55
for z in range(1, k + 2):
lines.append(line[((z - 1) * 55) : (z * 55)])
return lines[:25] | null |
5,702 | import json
import math
import os
import random
import re
import secrets
import ssl
from io import BytesIO
from json.decoder import JSONDecodeError
from traceback import format_exc
import requests
from .. import *
from ..exceptions import DependencyMissingError
from . import some_random_headers
from .helper import async_searcher, bash, run_async
from urllib.parse import quote, unquote
from telethon import Button
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
def get_stored_msg(hash):
async def get_stored_file(event, hash):
from .. import udB
msg_id = get_stored_msg(hash)
if not msg_id:
return
try:
msg = await asst.get_messages(udB.get_key("LOG_CHANNEL"), ids=msg_id)
except Exception as er:
LOGS.warning(f"FileStore, Error: {er}")
return
if not msg_id:
return await asst.send_message(
event.chat_id, "__Message was deleted by owner!__", reply_to=event.id
)
await asst.send_message(event.chat_id, msg.text, file=msg.media, reply_to=event.id) | null |
5,703 | import base64
import os
import random
import re
import string
from logging import WARNING
from random import choice, randrange, shuffle
from traceback import format_exc
from pyUltroid.exceptions import DependencyMissingError
from telethon.tl import types
from telethon.utils import get_display_name, get_peer_id
from .. import *
from .._misc._wrappers import eor
from . import some_random_headers
from .helper import async_searcher
from .tools import check_filename, json_parser
async def randomchannel(
tochat, channel, range1, range2, caption=None, client=ultroid_bot
):
do = randrange(range1, range2)
async for x in client.iter_messages(channel, add_offset=do, limit=1):
caption = caption or x.text
try:
await client.send_message(tochat, caption, file=x.media)
except BaseException:
pass | null |
5,704 | import base64
import os
import random
import re
import string
from logging import WARNING
from random import choice, randrange, shuffle
from traceback import format_exc
from pyUltroid.exceptions import DependencyMissingError
from telethon.tl import types
from telethon.utils import get_display_name, get_peer_id
from .. import *
from .._misc._wrappers import eor
from . import some_random_headers
from .helper import async_searcher
from .tools import check_filename, json_parser
from . import *
async def async_searcher(
url: str,
post: bool = False,
head: bool = False,
headers: dict = None,
evaluate=None,
object: bool = False,
re_json: bool = False,
re_content: bool = False,
*args,
**kwargs,
):
if aiohttp_client:
async with aiohttp_client(headers=headers) as client:
method = client.head if head else (client.post if post else client.get)
data = await method(url, *args, **kwargs)
if evaluate:
return await evaluate(data)
if re_json:
return await data.json()
if re_content:
return await data.read()
if head or object:
return data
return await data.text()
# elif requests:
# method = requests.head if head else (requests.post if post else requests.get)
# data = method(url, headers=headers, *args, **kwargs)
# if re_json:
# return data.json()
# if re_content:
# return data.content
# if head or object:
# return data
# return data.text
else:
raise DependencyMissingError("install 'aiohttp' to use this.")
from .. import *
def json_parser(data, indent=None, ascii=False):
parsed = {}
try:
if isinstance(data, str):
parsed = json.loads(str(data))
if indent:
parsed = json.dumps(
json.loads(str(data)), indent=indent, ensure_ascii=ascii
)
elif isinstance(data, dict):
parsed = data
if indent:
parsed = json.dumps(data, indent=indent, ensure_ascii=ascii)
except JSONDecodeError:
parsed = eval(data)
return parsed
async def YtDataScraper(url: str):
to_return = {}
data = json_parser(
BeautifulSoup(
await async_searcher(url),
"html.parser",
)
.find_all("script")[41]
.text[20:-1]
)["contents"]
_common_data = data["twoColumnWatchNextResults"]["results"]["results"]["contents"]
common_data = _common_data[0]["videoPrimaryInfoRenderer"]
try:
description_data = _common_data[1]["videoSecondaryInfoRenderer"]["description"][
"runs"
]
except (KeyError, IndexError):
description_data = [{"text": "U hurrr from here"}]
description = "".join(
description_datum["text"] for description_datum in description_data
)
to_return["title"] = common_data["title"]["runs"][0]["text"]
to_return["views"] = (
common_data["viewCount"]["videoViewCountRenderer"]["shortViewCount"][
"simpleText"
]
or common_data["viewCount"]["videoViewCountRenderer"]["viewCount"]["simpleText"]
)
to_return["publish_date"] = common_data["dateText"]["simpleText"]
to_return["likes"] = (
common_data["videoActions"]["menuRenderer"]["topLevelButtons"][0][
"toggleButtonRenderer"
]["defaultText"]["simpleText"]
# or like_dislike[0]["toggleButtonRenderer"]["defaultText"]["accessibility"][
# "accessibilityData"
# ]["label"]
)
to_return["description"] = description
return to_return | null |
5,705 | import base64
import os
import random
import re
import string
from logging import WARNING
from random import choice, randrange, shuffle
from traceback import format_exc
from pyUltroid.exceptions import DependencyMissingError
from telethon.tl import types
from telethon.utils import get_display_name, get_peer_id
from .. import *
from .._misc._wrappers import eor
from . import some_random_headers
from .helper import async_searcher
from .tools import check_filename, json_parser
async def eor(event, text=None, time=None, link_preview=False, edit_time=None, **args):
LIST = {}
async def allcmds(event, telegraph):
txt = ""
for z in LIST.keys():
txt += f"PLUGIN NAME: {z}\n"
for zz in LIST[z]:
txt += HNDLR + zz + "\n"
txt += "\n\n"
t = telegraph.create_page(title="Ultroid All Cmds", content=[txt])
await eor(event, f"All Ultroid Cmds : [Click Here]({t['url']})", link_preview=False) | null |
5,706 | import base64
import os
import random
import re
import string
from logging import WARNING
from random import choice, randrange, shuffle
from traceback import format_exc
from pyUltroid.exceptions import DependencyMissingError
try:
from aiohttp import ContentTypeError
except ImportError:
ContentTypeError = None
from telethon.tl import types
from telethon.utils import get_display_name, get_peer_id
from .. import *
from .._misc._wrappers import eor
from . import some_random_headers
from .helper import async_searcher
from .tools import check_filename, json_parser
try:
import aiohttp
except ImportError:
aiohttp = None
class DependencyMissingError(ImportError):
...
from .. import *
def check_filename(filroid):
if os.path.exists(filroid):
no = 1
while True:
ult = "{0}_{2}{1}".format(*os.path.splitext(filroid) + (no,))
if os.path.exists(ult):
no += 1
else:
return ult
return filroid
async def ReTrieveFile(input_file_name):
if not aiohttp:
raise DependencyMissingError("This function needs 'aiohttp' to be installed.")
RMBG_API = udB.get_key("RMBG_API")
headers = {"X-API-Key": RMBG_API}
files = {"image_file": open(input_file_name, "rb").read()}
async with aiohttp.ClientSession() as ses:
async with ses.post(
"https://api.remove.bg/v1.0/removebg", headers=headers, data=files
) as out:
contentType = out.headers.get("content-type")
if "image" not in contentType:
return False, (await out.json())
name = check_filename("ult-rmbg.png")
with open(name, "wb") as file:
file.write(await out.read())
return True, name | null |
5,707 | import base64
import os
import random
import re
import string
from logging import WARNING
from random import choice, randrange, shuffle
from traceback import format_exc
from pyUltroid.exceptions import DependencyMissingError
from telethon.tl import types
from telethon.utils import get_display_name, get_peer_id
from .. import *
from .._misc._wrappers import eor
from . import some_random_headers
from .helper import async_searcher
from .tools import check_filename, json_parser
from . import *
async def async_searcher(
url: str,
post: bool = False,
head: bool = False,
headers: dict = None,
evaluate=None,
object: bool = False,
re_json: bool = False,
re_content: bool = False,
*args,
**kwargs,
):
async def get_random_user_data():
base_url = "https://randomuser.me/api/"
cc = await async_searcher(
"https://random-data-api.com/api/business_credit_card/random_card", re_json=True
)
card = (
"**CARD_ID:** "
+ str(cc["credit_card_number"])
+ f" {cc['credit_card_expiry_date']}\n"
+ f"**C-ID :** {cc['id']}"
)
data_ = (await async_searcher(base_url, re_json=True))["results"][0]
_g = data_["gender"]
gender = "🤵🏻♂" if _g == "male" else "🤵🏻♀"
name = data_["name"]
loc = data_["location"]
dob = data_["dob"]
msg = """
{} **Name:** {}.{} {}
**Street:** {} {}
**City:** {}
**State:** {}
**Country:** {}
**Postal Code:** {}
**Email:** {}
**Phone:** {}
**Card:** {}
**Birthday:** {}
""".format(
gender,
name["title"],
name["first"],
name["last"],
loc["street"]["number"],
loc["street"]["name"],
loc["city"],
loc["state"],
loc["country"],
loc["postcode"],
data_["email"],
data_["phone"],
card,
dob["date"][:10],
)
pic = data_["picture"]["large"]
return msg, pic | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.