Release v0.0.6

Co-authored-by: Aakash <BLUE-DEVIL1134@users.noreply.github.com>
Co-authored-by: Aditya <me@xditya.me>
Co-authored-by: Danish <danish@ultroid.tech>
Co-authored-by: buddhhu <buddhuu@users.noreply.github.com>
Co-authored-by: sppidy <sppidy@users.noreply.github.com>
Co-authored-by: Arnab Paryali <Arnabxd@users.noreply.github.com>
Co-authored-by: divkix <divkix@users.noreply.github.com>
Co-authored-by: hellboi_atul <hellboi-atul@users.noreply.github.com>
Co-authored-by: Programming Error <error@notavailable.live>
Co-authored-by: New-dev0 <New-dev0@notavailable.live>
This commit is contained in:
Akash Pattnaik
2021-05-08 18:37:32 +05:30
parent adb2e3e66c
commit 7eb5e58721
80 changed files with 4875 additions and 965 deletions

View File

@@ -3,8 +3,7 @@
API_ID=
API_HASH=
SESSION=
BOT_USERNAME=
BOT_TOKEN=
REDIS_URI=
REDIS_PASSWORD=
LOG_CHANNEL=
LOG_CHANNEL=

4
.gitignore vendored
View File

@@ -18,4 +18,6 @@ addons/
ultroid.log
target/npmlist.json
node_modules
glitch_me/
glitch_me/
.idea
venv/

View File

@@ -3,19 +3,14 @@
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
FROM ultroidteam/ultroid:0.0.3
#RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \
# dpkg -i ./google-chrome-stable_current_amd64.deb; apt -fqqy install && \
# rm ./google-chrome-stable_current_amd64.deb
#RUN wget -O chromedriver.zip http://chromedriver.storage.googleapis.com/$(curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip && \
# unzip chromedriver.zip chromedriver -d /usr/bin/ && \
# rm chromedriver.zip
RUN curl --silent --location https://deb.nodesource.com/setup_15.x | bash -
RUN apt-get install -y nodejs
FROM programmingerror/ultroid:v0.0.1
RUN git clone https://github.com/TeamUltroid/Ultroid.git /root/TeamUltroid/
RUN git clone https://github.com/1Danish-00/glitch_me.git && pip install -e ./glitch_me
WORKDIR /root/TeamUltroid/
RUN pip install -r requirements.txt
RUN rm -rf /usr/local/lib/python3.9/site-packages/.wh*
RUN npm install -g npm@7.9.0 && npm install
RUN pip3 install -r requirements.txt
RUN npm install -g npm@7.11.2 -g
RUN npm install
RUN npm run build

View File

@@ -15,8 +15,7 @@
[![Open Source Love svg2](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)](https://github.com/TeamUltroid/Ultroid)
[![Contributors](https://img.shields.io/github/contributors/TeamUltroid/Ultroid?style=flat-square&color=green)](https://github.com/TeamUltroid/Ultroid/graphs/contributors)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)
[![License](https://img.shields.io/badge/License-AGPL-blue)](https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE)
[![HitCount](http://hits.dwyl.com/Teamultroid/Teamultroid/Ultroid.svg)](http://hits.dwyl.com/Teamultroid/Teamultroid/Ultroid)
[![License](https://img.shields.io/badge/License-AGPL-blue)](https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE)
[![Sparkline](https://stars.medv.io/Teamultroid/Ultroid.svg)](https://stars.medv.io/TeamUltroid/Ultroid)
----
@@ -104,3 +103,4 @@ Ultroid is licensed under [GNU Affero General Public License](https://www.gnu.or
* [![TeamUltroid-Devs](https://img.shields.io/static/v1?label=Teamultroid&message=devs&color=critical)](https://t.me/UltroidDevs)
* [Lonami](https://github.com/LonamiWebs/) for [Telethon.](https://github.com/LonamiWebs/Telethon)
* [AndrewLaneX](https://github.com/AndrewLaneX) for [tgcalls.](http://github.com/tgcallsjs/tgcalls)

View File

@@ -22,10 +22,6 @@
"description": "You api hash, from my.telegram.org or @ScrapperRoBot.",
"value": ""
},
"BOT_USERNAME": {
"description": "Make a bot from @BotFather, and enter it's username here, with '@'",
"value": ""
},
"BOT_TOKEN": {
"description": "Make a bot from @BotFather, and enter it's api token here.",
"value": ""
@@ -56,5 +52,15 @@
"description": "Create a private group. Add @missrose_bot and your BOT_USERNAME bot. Do /id. Paste that here",
"value": ""
}
},
"formation": {
"worker": {
"quantity": 1,
"size": "free"
},
"web": {
"quantity": 0,
"size": "free"
}
}
}
}

View File

@@ -14,8 +14,6 @@ import requests
from bs4 import BeautifulSoup
from orangefoxapi import OrangeFoxAPI
from play_scraper import search
from rextester_py import rexec_aio
from rextester_py.rextester_aio import UnknownLanguage
from search_engine_parser import GoogleSearch, YahooSearch
from telethon import Button
from telethon.tl.types import InputWebDocument as wb
@@ -28,14 +26,6 @@ gugirl = "https://telegra.ph/file/0df54ae4541abca96aa11.jpg"
yeah = "https://telegra.ph/file/e3c67885e16a194937516.jpg"
ps = "https://telegra.ph/file/de0b8d9c858c62fae3b6e.jpg"
ultpic = "https://telegra.ph/file/4136aa1650bc9d4109cc5.jpg"
rex_langs = """ada, bash, brainfuck, c (clang), c, c (vc),
c#, c++ (clang), c++, c++ (vc++), d, elixir,
erlang, f#, fortran, go, haskell, java, js,
kotlin, lisp, lua, mysql, nasm, node,
objective-c, ocaml, octave, oracle, pascal,
perl, php, postgresql, prolog, python,
python3, r, ruby, scala, scheme, sql server,
swift, tcl, vb.net"""
ofox_api = OrangeFoxAPI()
@@ -156,6 +146,11 @@ async def repo(e):
text="• **ULTROID USERBOT** •",
buttons=[
[Button.url("Repo", url="https://github.com/TeamUltroid/Ultroid")],
[
Button.url(
"Addons", url="https://github.com/TeamUltroid/UltroidAddons"
)
],
[Button.url("Support", url="t.me/UltroidSupport")],
],
),

View File

@@ -36,4 +36,5 @@ async def settt(event):
udB.set("language", f"{lang}")
await event.edit(
f"Your language has been set to {languages[lang]['natively']} [{lang}].",
buttons=get_back_button("lang"),
)

View File

@@ -5,8 +5,10 @@
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import os
import re
from os import execl, remove
import requests
from telegraph import Telegraph
from telegraph import upload_file as upl
@@ -22,6 +24,109 @@ auth_url = r["auth_url"]
TOKEN_FILE = "resources/auths/auth_token.txt"
@callback("updatenow")
@owner
async def update(eve):
repo = Repo()
ac_br = repo.active_branch
ups_rem = repo.remote("upstream")
if Var.HEROKU_API:
import heroku3
heroku = heroku3.from_key(Var.HEROKU_API)
heroku_app = None
heroku_applications = heroku.apps()
for app in heroku_applications:
if app.name == Var.HEROKU_APP_NAME:
heroku_app = app
if heroku_app is None:
await eve.edit("`Invalid Heroku credentials for updating userbot dyno.`")
repo.__del__()
return
await eve.edit(
"`Userbot dyno build in progress, please wait for it to complete.`"
)
ups_rem.fetch(ac_br)
repo.git.reset("--hard", "FETCH_HEAD")
heroku_git_url = heroku_app.git_url.replace(
"https://", "https://api:" + Var.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:
try:
ups_rem.pull(ac_br)
except GitCommandError:
repo.git.reset("--hard", "FETCH_HEAD")
await updateme_requirements()
await eve.edit(
"`Successfully Updated!\nBot is restarting... Wait for a second!`"
)
execl(sys.executable, sys.executable, "-m", "pyUltroid")
@callback("changes")
@owner
async def changes(okk):
repo = Repo.init()
ac_br = repo.active_branch
changelog, tl_chnglog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")
changelog_str = changelog + f"\n\nClick the below button to update!"
tldr_str = tl_chnglog + f"\n\nClick the below button to update!"
if len(changelog_str) > 1024:
await okk.edit(get_string("upd_4"))
file = open(f"ultroid_updates.txt", "w+")
file.write(tldr_str)
file.close()
await okk.edit(
get_string("upd_5"),
file="ultroid_updates.txt",
buttons=Button.inline("Update Now", data="updatenow"),
)
remove(f"ultroid_updates.txt")
return
else:
await okk.edit(
changelog_str,
buttons=Button.inline("Update Now", data="updatenow"),
parse_mode="html",
)
@callback(re.compile("pasta-(.*)"))
@owner
async def _(e):
ok = e.data_match.group(1)
hmm = open(ok)
hmmm = hmm.read()
hmm.close()
key = (
requests.post("https://nekobin.com/api/documents", json={"content": hmmm})
.json()
.get("result")
.get("key")
)
await e.edit(
f"Pasted to Nekobin\n 👉[Link](https://nekobin.com/{key})\n 👉[Raw Link](https://nekobin.com/raw/{key})",
buttons=Button.switch_inline(
"Search Again..?",
query="send ",
same_peer=True,
),
link_preview=False,
)
@callback("authorise")
@owner
async def _(e):
@@ -54,7 +159,7 @@ async def _(e):
+ "1. Open Google Drive App.\n"
+ "2. Create Folder.\n"
+ "3. Make that folder public.\n"
+ "4. Copy link of that folder."
+ "4. Copy link of that folder.\n"
+ "5. Send all characters which is after id= .",
)
async with ultroid_bot.asst.conversation(e.sender_id) as conv:
@@ -492,7 +597,7 @@ async def media(event):
try:
x = upl(media)
url = f"https://telegra.ph/{x[0]}"
os.remove(media)
remove(media)
except BaseException:
return await conv.send_message(
"Terminated.",
@@ -561,6 +666,11 @@ async def name(event):
buttons=get_back_button("pmcstm"),
)
else:
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
buttons=get_back_button("pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
"{} changed to {}\n\nAfter Setting All Things Do restart".format(
@@ -633,7 +743,7 @@ async def media(event):
try:
x = upl(media)
url = f"https://telegra.ph/{x[0]}"
os.remove(media)
remove(media)
except BaseException:
return await conv.send_message(
"Terminated.",
@@ -783,7 +893,7 @@ async def chbot(event):
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ᴇʟ", data="bwel")],
[Button.inline("« Bᴀ", data="setter")],
],
link_preview=False,

View File

@@ -17,7 +17,7 @@ from . import *
# if incoming
@asst.on(events.NewMessage(func=lambda e: e.is_private))
@asst.on(events.NewMessage(incoming=True, func=lambda e: e.is_private))
async def on_new_mssg(event):
incoming = event.raw_text
who = event.sender_id

View File

@@ -14,7 +14,7 @@ from . import *
# outgoing
@asst.on(events.NewMessage(func=lambda e: e.is_private))
@asst.on(events.NewMessage(incoming=True, func=lambda e: e.is_private))
async def on_out_mssg(event):
x = await event.get_reply_message()
if x is None:

View File

@@ -16,6 +16,15 @@ from plugins import *
from . import *
Owner_info_msg = f"""
**Owner** - {OWNER_NAME}
**OwnerID** - `{OWNER_ID}`
**Message Forwards** - {udB.get("PMBOT")}
__Ultroid {ultroid_version}, powered by @TeamUltroid__
"""
@asst_cmd("start")
async def assistant(event):
@@ -31,23 +40,33 @@ async def assistant(event):
ok = ""
if event.is_private and event.sender_id in sed:
return
u = await event.client.get_entity(event.chat_id)
if not udB.get("STARTMSG"):
if udB.get("PMBOT") == "True":
ok = "You can contact my master using this bot!!\n\nSend your Message, I will Deliver it To Master."
await event.reply(
f"Hey there, this is Ultroid Assistant of {OWNER_NAME}!\n\n{ok}",
buttons=[Button.url("Know More", url="https://t.me/TeamUltroid")],
f"Hey there [{get_display_name(u)}](tg://user?id={u.id}), this is Ultroid Assistant of [{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.uid})!\n\n{ok}",
buttons=[Button.inline("Info.", data="ownerinfo")],
)
else:
u = await event.client.get_entity(event.chat_id)
me = f"[{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.uid})"
mention = f"[{get_display_name(u)}](tg://user?id={u.id})"
await event.reply(
Redis("STARTMSG").format(me=me, mention=mention),
buttons=[Button.url("Know More", url="https://t.me/TeamUltroid")],
buttons=[Button.inline("Info.", data="ownerinfo")],
)
@callback("ownerinfo")
async def own(event):
await event.edit(Owner_info_msg, buttons=[Button.inline("Close", data="closeit")])
@callback("closeit")
async def closet(lol):
await lol.delete()
@asst_cmd("start ?(.*)")
@owner
async def ultroid(event):

View File

@@ -134,7 +134,7 @@ async def _(sur):
if sur.is_private and sur.sender_id != ultroid_bot.uid:
chat = sur.sender_id
whome = asst
MSG += f"\nGet at {Var.BOT_USERNAME}"
MSG += f"\nGet at {asst.me.username}"
try:
await whome.send_file(
chat,
@@ -217,7 +217,7 @@ async def _(fuk):
if event.is_private and event.sender_id != ultroid_bot.uid:
chat = fuk.sender_id
whome = asst
MSG += f"\nGet at {Var.BOT_USERNAME}"
MSG += f"\nGet at {asst.me.username}"
try:
await whome.send_file(
chat,

2
commit
View File

@@ -1,2 +0,0 @@
Spam
dd

2293
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,7 @@
"dotenv": "^8.2.0",
"envalid": "^7.0.0",
"redis": "^3.0.2",
"telegraf": "^4.0.2",
"telegraf": "^4.3.0",
"tgcalls": "^0.1.2",
"ws": "^7.4.3"
},

View File

@@ -7,7 +7,6 @@
import time
from pyUltroid import *
from pyUltroid.dB import *
from pyUltroid.dB.core import *
from pyUltroid.functions.all import *
@@ -28,11 +27,16 @@ except ModuleNotFoundError:
"git clone https://github.com/1Danish-00/glitch_me.git && pip install -e ./glitch_me"
)
start_time = time.time()
ultroid_version = "v0.0.5"
ultroid_version = "v0.0.6"
OWNER_NAME = ultroid_bot.me.first_name
OWNER_ID = ultroid_bot.me.id
List = []
Dict = {}
N = 0
def grt(seconds: int) -> str:
count = 0

View File

@@ -5,11 +5,11 @@
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from pyUltroid.dB.database import Var
from support import *
from telethon.errors.rpcerrorlist import BotInlineDisabledError as dis
from telethon.errors.rpcerrorlist import BotMethodInvalidError as bmi
from telethon.errors.rpcerrorlist import BotMethodInvalidError
from telethon.errors.rpcerrorlist import BotResponseTimeoutError as rep
from telethon.tl.custom import Button
from . import *
@@ -19,7 +19,7 @@ from . import *
)
async def ult(ult):
plug = ult.pattern_match.group(1)
tgbot = Var.BOT_USERNAME
tgbot = asst.me.username
if plug:
try:
if plug in HELP:
@@ -38,14 +38,50 @@ async def ult(ult):
for d in LIST[plug]:
x += HNDLR + d
x += "\n"
x += "\n© @TeamUltroid"
await eor(ult, x)
except BaseException:
await eod(ult, get_string("help_1").format(plug), time=5)
except BaseException:
await eor(ult, "Error 🤔 occured.")
else:
# if BOT_MODE:
# await ultroid_bot.send_message(
# ult.chat_id,
# f"Bot of {ultroid_bot.me.first_name}",
# buttons=[Button.inline(text="Open Help", data="open")],
# )
# return
try:
results = await ultroid_bot.inline_query(tgbot, "ultd")
except BotMethodInvalidError:
z = []
for x in LIST.values():
for y in x:
z.append(y)
cmd = len(z) + 10
bnn = asst.me.username
return await ultroid_bot.send_message(
ult.chat_id,
get_string("inline_4").format(
OWNER_NAME,
len(PLUGINS) - 5,
len(ADDONS),
cmd,
),
buttons=[
[
Button.inline("• Pʟɢɪɴs", data="hrrrr"),
Button.inline("• Aᴅᴅɴs", data="frrr"),
],
[
Button.inline("Oɴᴇʀ•ᴛʟ", data="ownr"),
Button.inline("Iɴʟɪɴᴇ•Pʟɢɪɴs", data="inlone"),
],
[Button.url("Sᴇᴛᴛɪɴɢs⚙", url=f"https://t.me/{bnn}?start=set")],
[Button.inline("••Cʟᴇ••", data="close")],
],
)
except rep:
return await eor(
ult,
@@ -53,10 +89,5 @@ async def ult(ult):
)
except dis:
return await eor(ult, get_string("help_3"))
except bmi:
return await eor(
ult,
get_string("help_4").format(tgbot),
)
await results[0].click(ult.chat_id, reply_to=ult.reply_to_msg_id, hide_via=True)
await ult.delete()

View File

@@ -10,7 +10,7 @@ import re
import time
from datetime import datetime
from math import ceil
from platform import python_version as pyver
from platform import python_version as PyVer
from git import Repo
from pyUltroid import __version__ as UltVer
@@ -26,14 +26,14 @@ ULTROID_PIC = "https://telegra.ph/file/031957757a4f6a5191040.jpg"
helps = get_string("inline_1")
add_ons = udB.get("ADDONS")
if add_ons:
if add_ons == "True" or add_ons is None:
zhelps = get_string("inline_2")
else:
zhelps = get_string("inline_3")
# ============================================#
@inline
@in_pattern("")
@in_owner
async def e(o):
if len(o.text) == 0:
@@ -46,7 +46,7 @@ async def e(o):
ultroid_version,
UltVer,
uptime,
pyver(),
PyVer(),
__version__,
Repo().active_branch,
)
@@ -71,7 +71,7 @@ async def e(o):
await o.answer(res, switch_pm=f"👥 ULTROID PORTAL", switch_pm_param="start")
if Var.BOT_USERNAME is not None and asst is not None:
if asst.me is not None:
@inline
@in_owner
@@ -85,11 +85,7 @@ if Var.BOT_USERNAME is not None and asst is not None:
for y in x:
z.append(y)
cmd = len(z) + 10
bn = Var.BOT_USERNAME
if bn.startswith("@"):
bnn = bn.replace("@", "")
else:
bnn = bn
bnn = asst.me.username
result = builder.article(
title="Help Menu",
description="Help Menu - UserBot | Telethon ",
@@ -136,8 +132,6 @@ if Var.BOT_USERNAME is not None and asst is not None:
)
await event.answer([result] if result else None)
@inline
@in_owner
@callback("ownr")
@owner
async def setting(event):
@@ -209,20 +203,13 @@ if Var.BOT_USERNAME is not None and asst is not None:
),
],
[
Button.switch_inline(
"Rᴇx Tᴇsᴛᴇʀ",
query="rex",
same_peer=True,
),
Button.switch_inline(
"ɪᴘAʀᴛ Sᴇᴀʀʜ",
query="clipart frog",
same_peer=True,
),
],
[
Button.switch_inline(
"OʀᴀɴɢᴇFx🦊Rᴇᴇʀʏ",
"OʀᴀɴɢᴇFx🦊",
query="ofox beryllium",
same_peer=True,
),
@@ -325,11 +312,7 @@ if Var.BOT_USERNAME is not None and asst is not None:
@callback("open")
@owner
async def opner(event):
bn = Var.BOT_USERNAME
if bn.startswith("@"):
bnn = bn.replace("@", "")
else:
bnn = bn
bnn = asst.me.username
buttons = [
[
Button.inline("• Pʟɢɪɴs ", data="hrrrr"),

View File

@@ -7,12 +7,14 @@
from telethon.errors import ChatSendInlineForbiddenError
from telethon.errors.rpcerrorlist import BotMethodInvalidError as bmi
from . import *
REPOMSG = (
"• **ULTROID USERBOT** •\n\n",
"• Repo - [Click Here](https://github.com/TeamUltroid/Ultroid)\n",
"• Addons - [Click Here](https://github.com/TeamUltroid/UltroidAddons)\n",
"• Support - @UltroidSupport",
)
@@ -20,9 +22,9 @@ REPOMSG = (
@ultroid_cmd(pattern="repo$")
async def repify(e):
try:
q = await ultroid_bot.inline_query(Var.BOT_USERNAME, "repo")
q = await ultroid_bot.inline_query(asst.me.username, "repo")
await q[0].click(e.chat_id)
if e.sender_id == ultroid_bot.uid:
await e.delete()
except ChatSendInlineForbiddenError:
except ChatSendInlineForbiddenError or bmi:
await eor(e, REPOMSG)

142
plugins/_userlogs.py Normal file
View File

@@ -0,0 +1,142 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from telethon.utils import get_display_name
from telethon.errors.rpcerrorlist import MediaEmptyError as mee
from . import *
import re
# taglogger
@ultroid_bot.on(
events.NewMessage(
incoming=True,
func=lambda e: (e.mentioned),
),
)
async def all_messages_catcher(e):
if udB.get("TAG_LOG"):
try:
NEEDTOLOG = int(udB.get("TAG_LOG"))
except Exception:
return LOGS.warning("you given Wrong Grp/Channel ID in TAG_LOG.")
x = await ultroid_bot.get_entity(e.sender_id)
if x.bot or x.verified:
return
y = await ultroid_bot.get_entity(e.chat_id)
where_n = get_display_name(y)
who_n = get_display_name(x)
where_l = f"https://t.me/c/{y.id}/{e.id}"
send = await ultroid_bot.get_messages(e.chat_id, ids=e.id)
try:
if x.username:
who_l = f"https://t.me/{x.username}"
await asst.send_message(
NEEDTOLOG,
send,
buttons=[[Button.url(who_n, who_l)],[Button.url(where_n, where_l)]],
)
else:
await asst.send_message(
NEEDTOLOG,
send,
buttons=[[Button.inline(who_n, data=f"who{x.id}")],[Button.url(where_n, where_l)]],
)
except mee:
if x.username:
who_l = f"https://t.me/{x.username}"
await asst.send_message(
NEEDTOLOG,
"`Unsupported Media`",
buttons=[[Button.url(who_n, who_l)],[Button.url(where_n, where_l)]],
)
else:
await asst.send_message(
NEEDTOLOG,
"`Unsupported Media`",
buttons=[[Button.inline(who_n, data=f"who{x.id}")],[Button.url(where_n, where_l)]],
)
except Exception as er:
LOGS.info(str(er))
await ultroid_bot.send_message(NEEDTOLOG, f"Please Add Your Assistant Bot - @{asst.me.username} as admin here.")
else:
return
@callback(re.compile(b"who(.*)"))
async def _(e):
wah = e.pattern_match.group(1).decode("UTF-8")
y = await ultroid_bot.get_entity(int(wah))
who = f"[{get_display_name(y)}](tg://user?id={y.id})"
x = await e.reply(f"Mention By user : {who}")
await asyncio.sleep(6)
await x.delete()
# log for assistant
@asst.on(events.ChatAction)
async def when_asst_added_to_chat(event):
if event.user_added:
user = await event.get_user()
chat = (await event.get_chat()).title
tmp = event.added_by
add = tmp.id
if user.id == (await asst.get_me()).id:
if add == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|bot"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\nYou had added me to {chat}."
)
else:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|bot"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\n`{add}` added me to {chat}."
)
# log for user's new joins
@ultroid.on(events.ChatAction)
async def when_ultd_added_to_chat(event):
if event.user_added:
user = await event.get_user()
chat = (await event.get_chat()).title
tmp = event.added_by
add = tmp.id
if user.id == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#ADD_LOG\n\n`{add}` just added you to {chat}."
)
elif event.user_joined:
user = await event.get_user()
chat = (await event.get_chat()).title
if user.id == OWNER_ID:
# , buttons=Button.inline("Leave Chat", data=f"leave_ch_{event.chat_id}|user"))
return await asst.send_message(
Var.LOG_CHANNEL, f"#JOIN_LOG\n\nYou just joined {chat}."
)
"""
@callback(
re.compile(
b"leave_ch_(.*)",
),
)
@owner
async def leave_ch_at(event):
cht = event.data_match.group(1).decode("UTF-8")
ch_id, client = cht.split("|")
if client == "bot":
await asst.delete_dialog(ch_id)
elif client == "user":
await ultroid.delete_dialog(ch_id)
await event.edit(f"Left `{ch_id}`")
"""

View File

@@ -42,7 +42,7 @@ async def _(e):
put = e.pattern_match.group(1)
if put:
try:
results = await ultroid_bot.inline_query(Var.BOT_USERNAME, f"msg {put}")
results = await ultroid_bot.inline_query(asst.me.username, f"msg {put}")
except rep:
return await eor(
e,

View File

@@ -312,13 +312,20 @@ async def unp(ult):
@ultroid_cmd(
pattern="purge$",
pattern="purge ?(.*)",
)
async def fastpurger(purg):
chat = await purg.get_input_chat()
match = purg.pattern_match.group(1)
if match and purg.text[6] == " ":
p = 0
async for msg in ultroid_bot.iter_messages(purg.chat_id, limit=int(match)):
await msg.delete()
p += 0
return await eod(purg, f"Purged {p} Messages! ")
msgs = []
count = 0
if not purg.reply_to_msg_id:
if not (purg.reply_to_msg_id or match):
return await eod(purg, "`Reply to a message to purge from.`", time=10)
async for msg in ultroid_bot.iter_messages(chat, min_id=purg.reply_to_msg_id):
msgs.append(msg)
@@ -343,14 +350,33 @@ async def fastpurger(purg):
@ultroid_cmd(
pattern="purgeme$",
pattern="purgeme ?(.*)",
)
async def fastpurgerme(purg):
num = purg.pattern_match.group(1)
if num and not purg.is_reply:
try:
nnt = int(num)
except BaseException:
await eod(purg, "`Give a Valid Input.. `")
return
mp = 0
async for mm in ultroid_bot.iter_messages(
purg.chat_id, limit=nnt, from_user="me"
):
await mm.delete()
mp += 1
await eod(purg, f"Purged {mp} Messages!")
return
chat = await purg.get_input_chat()
msgs = []
count = 0
if not purg.reply_to_msg_id:
return await eod(purg, "`Reply to a message to purge from.`", time=10)
if not (purg.reply_to_msg_id or num):
return await eod(
purg,
"`Reply to a message to purge from or use it like ``purgeme <num>`",
time=10,
)
async for msg in ultroid_bot.iter_messages(
chat,
from_user="me",

View File

@@ -23,7 +23,6 @@ from telethon import events
from telethon.tl.functions.account import GetPrivacyRequest
from telethon.tl.types import InputPrivacyKeyStatusTimestamp, PrivacyValueAllowAll
from . import *
global USER_AFK
@@ -161,6 +160,8 @@ async def on_afk(event):
@ultroid_cmd(pattern=r"afk ?(.*)")
async def _(event):
if not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
reply = await event.get_reply_message()
global USER_AFK
global afk_time

View File

@@ -24,12 +24,14 @@ tr = Translator()
@ultroid_cmd(pattern="autocorrect")
async def acc(e):
if not is_fullsudo(ult.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
if Redis("AUTOCORRECT") != "True":
udB.set("AUTOCORRECT", "True")
await eor(e, "AUTOCORRECT Feature On")
await eod(e, "AUTOCORRECT Feature On")
else:
udB.delete("AUTOCORRECT")
await eor(e, "AUTOCORRECT Feature Off")
await eof(e, "AUTOCORRECT Feature Off")
@ultroid_bot.on(events.NewMessage(outgoing=True))
@@ -47,7 +49,10 @@ async def gramme(event):
xx = GingerIt()
x = xx.parse(t)
res = x["result"]
await event.edit(res)
try:
await event.edit(res)
except BaseException:
pass
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -8,18 +8,21 @@
"""
✘ Commands Available -
`{i}autopic <search query>`
{i}autopic <search query>
Will change your profile pic at defined intervals with pics related to the given topic.
`{i}stoppic`
{i}stoppic
Stop the AutoPic command.
"""
import asyncio
import os
import random
import urllib
from telethon import functions
import requests as r
from bs4 import BeautifulSoup as bs
from telethon.tl.functions.messages import GetWebPagePreviewRequest as getweb
from telethon.tl.functions.photos import UploadProfilePhotoRequest
from . import *
@@ -28,36 +31,41 @@ from . import *
async def autopic(e):
search = e.pattern_match.group(1)
if not search:
return await eor(e, get_string("autopic_1"))
clls = returnpage(search)
return await eod(e, get_string("autopic_1"))
clls = autopicsearch(search)
if len(clls) == 0:
return await eor(e, get_string("autopic_2").format(search))
if not len(clls) == 1:
num = random.randrange(0, len(clls) - 1)
else:
num = 0
page = clls[num]
title = page["title"]
await eor(e, get_string("autopic_3").format(title))
return await eod(e, get_string("autopic_2").format(search))
await eor(e, get_string("autopic_3").format(search))
udB.set("AUTOPIC", "True")
while True:
ge = udB.get("AUTOPIC")
if not ge == "True":
return
animepp(page["href"])
file = await ultroid_bot.upload_file("autopic.jpg")
await ultroid_bot(functions.photos.UploadProfilePhotoRequest(file))
os.remove("autopic.jpg")
await asyncio.sleep(1100)
for lie in clls:
au = "https://unsplash.com" + lie["href"]
et = await ultroid_bot(getweb(au))
try:
kar = await ultroid_bot.download_media(et.webpage.photo)
except AttributeError:
ct = r.get(au).content
bsc = bs(ct, "html.parser", from_encoding="utf-8")
ft = bsc.find_all("img", "_2UpQX")
li = ft[0]["src"]
kar = "autopic.png"
urllib.request.urlretrieve(li, kar)
file = await ultroid_bot.upload_file(kar)
await ultroid_bot(UploadProfilePhotoRequest(file))
os.remove(kar)
await asyncio.sleep(1100)
@ultroid_cmd(pattern="stoppic$")
async def stoppo(ult):
gt = udB.get("AUTOPIC")
if not gt == "True":
return await eor(ult, "`AUTOPIC was not in used !!`")
return await eod(ult, "AUTOPIC was not in used !!")
udB.set("AUTOPIC", "None")
await eor(ult, "`AUTOPIC Stopped !!`")
await eod(ult, "AUTOPIC Stopped !!")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -21,10 +21,8 @@
'And u Must be Admin in that Chat'
"""
import re
from pyUltroid.functions.blacklist_db import *
from telethon.tl.types import ChannelParticipantsAdmins
from . import *
@@ -34,12 +32,14 @@ async def af(e):
if e.is_group:
if not e._chat.admin_rights:
return await eod(e, "`You are Not Admin Here`")
wrd = (e.pattern_match.group(1)).lower()
wrd = e.pattern_match.group(1)
chat = e.chat_id
if not (wrd):
return await eod(e, "`Give the word to blacklist..`")
wrd = e.text[10:]
add_blacklist(int(chat), wrd)
wrd = e.text[11:]
heh = wrd.split(" ")
for z in heh:
add_blacklist(int(chat), z.lower())
await eor(e, f"Done : `{wrd}` Blacklisted here.")
@@ -48,11 +48,14 @@ async def rf(e):
if e.is_group:
if not e._chat.admin_rights:
return await eod(e, "`You are Not Admin Here`")
wrd = (e.pattern_match.group(1)).lower()
wrd = e.pattern_match.group(1)
chat = e.chat_id
if not wrd:
return await eod(e, "`Give the word to remove from blacklist..`")
rem_blacklist(int(chat), wrd)
wrd = e.text[14:]
heh = wrd.split(" ")
for z in heh:
rem_blacklist(int(chat), z.lower())
await eor(e, f"Done : `{wrd}` Removed from Blacklist.")
@@ -73,29 +76,13 @@ async def lsnote(e):
async def bl(e):
chat = e.chat_id
x = get_blacklist(int(chat))
xx = (e.text).lower()
if x and xx:
if " " in xx:
xx = xx.split(" ")
kk = ""
for c in xx:
kk = re.search(str(c), str(x), flags=re.IGNORECASE)
if kk:
async for l in ultroid_bot.iter_participants(
e.chat_id, filter=ChannelParticipantsAdmins
):
if l.id == e.sender_id:
return
await e.delete()
else:
k = re.search(xx, x, flags=re.IGNORECASE)
if k:
async for l in ultroid_bot.iter_participants(
e.chat_id, filter=ChannelParticipantsAdmins
):
if l.id == e.sender_id:
return
if x and e.text:
xx = ((e.text).lower()).split()
yy = x.split("$|")
for z in xx:
if z in yy:
await e.delete()
break
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -18,31 +18,26 @@
View all plugin names.
• `{i}restart`
s - soft restart
To restart your bot.
• `{i}logs`
Get the last 100 lines from heroku logs.
• `{i}logs (sys)`
Get the full terminal logs.
• `{i}usage`
Get app usage details.
• `{i}logs heroku`
Get the latest 100 lines of heroku logs.
• `{i}shutdown`
Turn off your bot.
"""
import math
import shutil
import time
from datetime import datetime as dt
from platform import python_version as pyver
import heroku3
import psutil
import requests
from git import Repo
from pyUltroid import __version__ as UltVer
from search_engine_parser.core.utils import get_rand_user_agent as grua
from telethon import __version__
from telethon.errors.rpcerrorlist import ChatSendMediaForbiddenError
@@ -88,17 +83,19 @@ async def lol(ult):
return await eor(ult, als)
elif pic is not None and "telegra" in pic:
try:
await ult.reply(als, file=pic)
await ultroid_bot.send_message(
ult.chat_id, als, file=pic, link_preview=False
)
await ult.delete()
except ChatSendMediaForbiddenError:
await eor(ult, als)
await eor(ult, als, link_preview=False)
else:
try:
await ultroid_bot.send_message(ult.chat_id, file=pic)
await ultroid_bot.send_message(ult.chat_id, als)
await ultroid_bot.send_message(ult.chat_id, als, link_preview=False)
await ult.delete()
except ChatSendMediaForbiddenError:
await eor(ult, als)
await eor(ult, als, link_preview=False)
@ultroid_cmd(
@@ -124,17 +121,73 @@ async def cmds(event):
pattern="restart$",
)
async def restartbt(ult):
if not Var.HEROKU_API:
if Var.HEROKU_API:
await eor(ult, "`Restarting..`")
await bash("pkill python3 && python3 -m pyUltroid")
try:
await restart(ult)
except BaseException:
await bash("pkill python3 && python3 -m pyUltroid")
else:
await restart(ult)
await bash("pkill python3 && python3 -m pyUltroid")
@ultroid_cmd(pattern="shutdown")
async def shutdownbot(ult):
try:
dyno = ult.text.split(" ", maxsplit=1)[1]
except IndexError:
dyno = None
if dyno:
if dyno not in ["userbot", "vcbot", "web", "worker"]:
await eor(ult, "Invalid Dyno Type specified !")
return
await shutdown(ult, dyno)
else:
await shutdown(ult)
@ultroid_cmd(
pattern="logs$",
pattern="logs",
)
async def _(ult):
async def get_logs(event):
try:
opt = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await def_logs(event)
if opt == "heroku":
await heroku_logs(event)
elif opt == "sys":
await def_logs(event)
else:
await def_logs(event)
async def heroku_logs(event):
if HEROKU_API is None and HEROKU_APP_NAME is None:
return await eor(
event, "Please set `HEROKU_APP_NAME` and `HEROKU_API` in vars."
)
await eor(event, "`Downloading Logs...`")
ok = app.get_log()
with open("ultroid-heroku.log", "w") as log:
log.write(ok)
key = (
requests.post("https://nekobin.com/api/documents", json={"content": ok})
.json()
.get("result")
.get("key")
)
url = f"https://nekobin.com/{key}"
await ultroid.send_file(
event.chat_id,
file="ultroid-heroku.log",
thumb="resources/extras/logo_rdm.png",
caption=f"**Ultroid Heroku Logs.**\nPasted [here]({url}) too!",
)
os.remove("ultroid-heroku.log")
async def def_logs(ult):
xx = await eor(ult, "`Processing...`")
with open("ultroid.log") as f:
k = f.read()
@@ -148,89 +201,11 @@ async def _(ult):
await ultroid.send_file(
ult.chat_id,
file="ultroid.log",
thumb="resources/extras/logo_rdm.png",
caption=f"**Ultroid Logs.**\nPasted [here](https://nekobin.com/{key}) too!",
thumb="resources/extras/new_thumb.jpg",
caption=f"**Ultroid Logs.**\nPasted [here]({url}) too!",
)
await xx.edit("Done")
await xx.delete()
@ultroid_cmd(
pattern="usage$",
)
async def dyno_usage(dyno):
if not HEROKU_API and HEROKU_APP_NAME:
return
dyn = await eor(dyno, "`Processing...`")
useragent = grua()
user_id = Heroku.account().id
headers = {
"User-Agent": useragent,
"Authorization": f"Bearer {Var.HEROKU_API}",
"Accept": "application/vnd.heroku+json; version=3.account-quotas",
}
path = "/accounts/" + user_id + "/actions/get-quota"
r = requests.get(heroku_api + path, headers=headers)
if r.status_code != 200:
return await dyno.edit(
"`Error: something bad happened`\n\n" f">.`{r.reason}`\n",
)
result = r.json()
quota = result["account_quota"]
quota_used = result["quota_used"]
remaining_quota = quota - quota_used
percentage = math.floor(remaining_quota / quota * 100)
minutes_remaining = remaining_quota / 60
hours = math.floor(minutes_remaining / 60)
minutes = math.floor(minutes_remaining % 60)
App = result["apps"]
try:
App[0]["quota_used"]
except IndexError:
AppQuotaUsed = 0
AppPercentage = 0
else:
AppQuotaUsed = App[0]["quota_used"] / 60
AppPercentage = math.floor(App[0]["quota_used"] * 100 / quota)
AppHours = math.floor(AppQuotaUsed / 60)
AppMinutes = math.floor(AppQuotaUsed % 60)
total, used, free = shutil.disk_usage(".")
cpuUsage = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
disk = psutil.disk_usage("/").percent
upload = humanbytes(psutil.net_io_counters().bytes_sent)
down = humanbytes(psutil.net_io_counters().bytes_recv)
TOTAL = humanbytes(total)
USED = humanbytes(used)
FREE = humanbytes(free)
return await eod(
dyn,
get_string("usage").format(
Var.HEROKU_APP_NAME,
AppHours,
AppMinutes,
AppPercentage,
hours,
minutes,
percentage,
TOTAL,
USED,
FREE,
upload,
down,
cpuUsage,
memory,
disk,
),
)
@ultroid_cmd(
pattern="shutdown$",
)
async def shht(event):
await eor(event, get_string("shutdown").format(OWNER_NAME))
await ultroid_bot.disconnect()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -207,37 +207,12 @@ async def sending(event):
await x.edit("Sending....")
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
if previous_message.sticker or previous_message.poll:
await x.edit(f"Reply `{hndlr}forward` for stickers and polls.")
return
if (
previous_message.gif
or previous_message.audio
or previous_message.voice
or previous_message.video
or previous_message.video_note
or previous_message.contact
or previous_message.game
or previous_message.geo
or previous_message.invoice
):
await x.edit(f"Not supported. Try `{hndlr}forward`")
return
if not previous_message.web_preview and previous_message.photo:
file = await ultroid_bot.download_file(previous_message.media)
uploaded_doc = await ultroid_bot.upload_file(file, file_name="img.png")
raw_text = previous_message.text
if previous_message.poll:
return await x.edit(f"Reply `{hndlr}forward` for polls.")
if previous_message:
for channel in channels:
try:
if previous_message.photo:
await ultroid_bot.send_file(
int(channel),
InputMediaUploadedPhoto(file=uploaded_doc),
force_document=False,
caption=raw_text,
link_preview=False,
)
await ultroid_bot.send_message(int(channel), previous_message)
sent_count += 1
await x.edit(
f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
@@ -246,19 +221,8 @@ async def sending(event):
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
f"Error in sending at {channel}.",
f"Error in sending at {channel}.\n\n{error}",
)
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
"Error! " + str(error),
)
if (
error
== "The message cannot be empty unless a file is provided"
):
return await x.edit(
f"For sending files, upload in Saved Messages and reply {hndlr}forward to in.",
)
except BaseException:
pass
error_count += 1
@@ -274,51 +238,6 @@ async def sending(event):
)
except BaseException:
pass
else:
raw_text = previous_message.text
for channel in channels:
try:
await ultroid_bot.send_message(
int(channel),
raw_text,
link_preview=False,
)
sent_count += 1
await x.edit(
f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
)
except Exception as error:
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
f"Error in sending at {channel}.",
)
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
"Error! " + str(error),
)
if (
error
== "The message cannot be empty unless a file is provided"
):
return await x.edit(
f"For sending files, upload in Saved Messages and reply {hndlr}forward to in.",
)
except BaseException:
pass
error_count += 1
await x.edit(
f"Sent : {sent_count}\nError : {error_count}\nTotal : {len(channels)}",
)
await x.edit(f"{sent_count} messages sent with {error_count} errors.")
if error_count > 0:
try:
await ultroid_bot.send_message(
Var.LOG_CHANNEL,
f"{error_count} Errors",
)
except BaseException:
await x.edit("Set up log channel for checking errors.")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -177,7 +177,7 @@ all_col = [
pattern="carbon",
)
async def crbn(event):
xxxx = await eor(event, "Processing")
xxxx = await eor(event, get_string("com_1"))
if event.reply_to_msg_id:
temp = await event.get_reply_message()
if temp.media:

View File

@@ -88,7 +88,7 @@ async def _(e):
return
async for msg in ultroid_bot.iter_messages(int(c), reverse=True):
try:
await asyncio.sleep(0.7)
await asyncio.sleep(1)
await ultroid_bot.send_message(int(d), msg)
except BaseException:
pass

View File

@@ -9,7 +9,7 @@
✘ Commands Available -
• `{i}delchat`
Delete the group this cmd is used in.
Delete the group this cmd is used in.
• `{i}getlink`
Get link of group this cmd is used in.
@@ -23,8 +23,12 @@
from telethon.errors import ChatAdminRequiredError as no_admin
from telethon.tl.functions.messages import DeleteChatUserRequest, CreateChatRequest, ExportChatInviteRequest
from telethon.tl.functions.channels import DeleteChannelRequest
from telethon.tl.functions.channels import CreateChannelRequest, DeleteChannelRequest
from telethon.tl.functions.messages import (
CreateChatRequest,
DeleteChatUserRequest,
ExportChatInviteRequest,
)
from . import *
@@ -34,6 +38,8 @@ from . import *
groups_only=True,
)
async def _(e):
if BOT_MODE:
return await eor(e, "You Cant Use This Command in BOT_MODE")
xx = await eor(e, "`Processing...`")
try:
await e.client(DeleteChannelRequest(e.chat_id))
@@ -63,6 +69,8 @@ async def _(e):
pattern="create (b|g|c)(?: |$)(.*)",
)
async def _(e):
if BOT_MODE:
return await eor(e, "You Cant use this Command in BOT_MODE")
type_of_group = e.pattern_match.group(1)
group_name = e.pattern_match.group(2)
xx = await eor(e, "`Processing...`")

68
plugins/clean_action.py Normal file
View File

@@ -0,0 +1,68 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`{i}addclean`
Clean all Upcoming action msg in added chat like someone joined/left/pin etc.
•`{i}remclean`
Remove chat from database.
•`{i}listclean`
To get list of all chats where its activated.
"""
from pyUltroid.functions.clean_db import *
from . import *
@ultroid_cmd(pattern="addclean$", admins_only=True)
async def _(e):
add_clean(e.chat_id)
await eod(e, "Added Clean Action Setting For this Chat")
async for x in ultroid_bot.iter_messages(e.chat_id, limit=3000):
if x.action:
await x.delete()
@ultroid_cmd(pattern="remclean$")
async def _(e):
rem_clean(e.chat_id)
await eod(e, "Removed Clean Action Setting For this Chat")
@ultroid_cmd(pattern="listclean$")
async def _(e):
k = udB.get("CLEANCHAT")
if k:
k = k.split(" ")
o = ""
for x in k:
try:
title = (await ultroid_bot.get_entity(int(x))).title
except BaseException:
title = "`Invalid ID`"
o += x + " " + title + "\n"
await eor(e, o)
else:
await eod(e, "`No Chat Added`")
@ultroid_bot.on(events.ChatAction())
async def _(event):
if is_clean_added(event.chat_id):
try:
await event.delete()
except BaseException:
pass
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -24,23 +24,42 @@
• `{i}rename <file name with extension>`
rename the file
• `{i}thumbnail <reply to image`
upload Your file with your custom thumbnail.
In Commands `{i}rename` and `{i}ul`
"""
import asyncio
import os
import time
import cv2
import requests
from PIL import Image
from telegraph import upload_file as uf
from . import *
opn = []
@ultroid_cmd(pattern="thumbnail$")
async def _(e):
r = await e.get_reply_message()
if not (r and r.media):
return await eor(e, "`Reply to img`")
dl = await ultroid_bot.download_media(r.media)
variable = uf(dl)
os.remove(dl)
nn = "https://telegra.ph" + variable[0]
udB.set("CUSTOM_THUMBNAIL", str(nn))
await eor(e, f"Added [This]({nn}) As Your Custom Thumbnail", link_preview=False)
@ultroid_cmd(pattern="rename ?(.*)")
async def imak(event):
reply = await event.get_reply_message()
t = time.time()
if not reply:
await eor(event, "Reply to any media/Document.")
return
@@ -49,9 +68,30 @@ async def imak(event):
await eor(event, "Give The name nd extension of file")
return
xx = await eor(event, "`Processing...`")
image = await ultroid_bot.download_media(reply)
os.rename(image, inp)
await ultroid_bot.send_file(event.chat_id, inp, force_document=True, reply_to=reply)
if reply.media:
if hasattr(reply.media, "document"):
file = reply.media.document
image = await downloader(
reply.file.name, reply.media.document, xx, t, "Downloading..."
)
file = image.name
else:
file = await event.download_media(reply)
os.rename(file, inp)
if Redis("CUSTOM_THUMBNAIL"):
await bash(
f"wget {Redis('CUSTOM_THUMBNAIL')} -O resources/extras/new_thumb.jpg"
)
k = time.time()
xxx = await uploader(inp, inp, k, xx, "Uploading...")
await ultroid_bot.send_file(
event.chat_id,
xxx,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
caption=f"`{xxx.name}`",
reply_to=reply,
)
os.remove(inp)
await xx.delete()
@@ -118,7 +158,9 @@ async def _(event):
await asyncio.sleep(2)
await xx.edit(f"**Uploading** `{input_str}`")
await asyncio.sleep(2)
await event.client.send_file(event.chat_id, input_str)
await event.client.send_file(
event.chat_id, input_str, thumb="resources/extras/new_thumb.jpg"
)
await xx.delete()
os.remove(input_str)
@@ -149,6 +191,7 @@ async def _(event):
await xx.edit(
f"**MESSAGE EXCEEDS TELEGRAM LIMITS**\n\nSo Pasted It On [NEKOBIN](https://nekobin.com/{key})"
)
os.remove(b)
else:
return await eod(xx, "`Reply to a readable file`", time=5)
else:

View File

@@ -40,38 +40,26 @@ from . import *
async def inline_handler(event):
builder = event.builder
input_str = event.pattern_match.group(1)
plug = [*PLUGINS]
plugs = []
if input_str is None or input_str == "":
for i in plug:
try:
plugs.append(
await event.builder.document(
f"./plugins/{i}.py",
title=f"{i}.py",
description=f"Module Found",
text=f"{i}.py use .paste to paste in neko and raw..",
buttons=[
[
Button.switch_inline(
"Search Again..?",
query="send ",
same_peer=True,
),
],
],
),
)
except BaseException:
pass
plugs = await event.builder.article(
title=f"Which plugin?",
text="No Module",
buttons=[
Button.switch_inline(
"Search Again..?",
query="send ",
same_peer=True,
),
],
)
await event.answer(plugs)
else:
try:
ultroid = builder.document(
f"./plugins/{input_str}.py",
f"plugins/{input_str}.py",
title=f"{input_str}.py",
description=f"Module {input_str} Found",
text=f"{input_str}.py use .paste to paste in neko and raw..",
text=f"{input_str}.py use below button to paste in neko and raw..",
buttons=[
[
Button.switch_inline(
@@ -80,6 +68,12 @@ async def inline_handler(event):
same_peer=True,
),
],
[
Button.inline(
"Paste?",
data=f"pasta-plugins/{input_str}.py",
),
],
],
)
await event.answer([ultroid])
@@ -107,6 +101,8 @@ async def inline_handler(event):
pattern="install",
)
async def install(event):
if not is_fullsudo(event.sender_id):
return await eod(event, "`This Command Is Sudo Restricted.`")
await safeinstall(event)

46
plugins/dayevents.py Normal file
View File

@@ -0,0 +1,46 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}eod` or `{i}eod <dd/mm>`
`Get Event of the Day`
"""
import re
from datetime import datetime as dr
import requests as r
from bs4 import BeautifulSoup as bs
from . import *
@ultroid_cmd(pattern="eod ?(.*)")
async def diela(e):
match = e.pattern_match.group(1)
m = await eor(e, "`Processing... `")
li = "https://daysoftheyear.com"
te = "♻️ **Events of the Day**\n\n"
if match:
date = match.split("/")[0]
month = match.split("/")[1]
li += "/days/2021/" + month + "/" + date
te = f"♻️ **Events for {match}/2021**\n\n"
else:
da = dr.today().strftime("%F").split("-")
li += "/days/2021/" + da[1] + "/" + da[2]
ct = r.get(li).content
bt = bs(ct, "html.parser", from_encoding="utf-8")
ml = bt.find_all("a", "js-link-target", href=re.compile("daysoftheyear.com/days"))
for eve in ml[:5]:
te += "" + f'[{eve.text}]({eve["href"]})\n'
await m.edit(te, link_preview=False)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -11,15 +11,22 @@
• `{i}ul <path/to/file>`
Upload file to telegram chat.
• `{i}ul <path/to/file> | stream`
Upload files as stream.
• `{i}dl <filename(optional)>`
Reply to file to download.
"""
import asyncio
import time
from datetime import datetime as dt
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from telethon.errors.rpcerrorlist import MessageNotModifiedError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from . import *
@@ -27,54 +34,59 @@ from . import *
pattern="dl ?(.*)",
)
async def download(event):
if not event.is_reply:
if not event.reply_to_msg_id:
return await eor(event, "`Reply to a Media Message`")
xx = await eor(event, get_string("com_1"))
kk = event.pattern_match.group(1)
s = dt.now()
k = time.time()
if event.reply_to_msg_id:
ok = await event.get_reply_message()
if not ok.media:
return await eod(xx, get_string("udl_1"), time=5)
else:
if not kk:
d = "resources/downloads/"
o = await event.client.download_media(
ok,
d,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
xx,
k,
"Downloading...",
),
),
)
if hasattr(ok.media, "document"):
file = ok.media.document
mime_type = file.mime_type
if event.pattern_match.group(1):
filename = event.pattern_match.group(1)
else:
d = f"resources/downloads/{kk}"
o = await event.client.download_media(
ok,
d,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
xx,
k,
"Downloading...",
file_name=d,
),
),
filename = ok.file.name
if not filename:
if "audio" in mime_type:
filename = "audio_" + dt.now().isoformat("_", "seconds") + ".ogg"
elif "video" in mime_type:
filename = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"
try:
result = await downloader(
"resources/downloads/" + filename,
file,
xx,
k,
"Downloading " + filename + "...",
)
except MessageNotModifiedError as err:
return await xx.edit(str(err))
file_name = result.name
else:
d = "resources/downloads/"
file_name = await event.client.download_media(
ok,
d,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
xx,
k,
"Downloading...",
),
),
)
e = datetime.now()
t = time_formatter(((e - s).seconds) * 1000)
if t:
await eod(xx, get_string("udl_2").format(o, t))
if t != "":
await eor(xx, get_string("udl_2").format(file_name, t))
else:
await eod(xx, f"Downloaded `{o}` in `0 second(s)`")
await eor(xx, f"Downloaded `{file_name}` in `0 second(s)`")
@ultroid_cmd(
@@ -82,48 +94,87 @@ async def download(event):
)
async def download(event):
xx = await eor(event, get_string("com_1"))
kk = event.pattern_match.group(1)
hmm = event.pattern_match.group(1)
try:
kk = hmm.split(" | ")[0]
except BaseException:
pass
try:
title = kk.split("/")[-1]
except BaseException:
title = hmm
s = dt.now()
tt = time.time()
if not kk:
return await eod(xx, get_string("udl_3"))
else:
try:
x = await event.client.send_file(
event.chat_id,
kk,
caption=kk,
force_document=True,
thumb="resources/extras/logo_rdm.png",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
xx,
tt,
"Uploading...",
file_name=kk,
),
),
)
except ValueError as ve:
return await eod(xx, str(ve))
except BaseException:
if Redis("CUSTOM_THUMBNAIL"):
await bash(
f"wget {Redis('CUSTOM_THUMBNAIL')} -O resources/extras/new_thumb.jpg"
)
try:
await ultroid_bot.send_message(event.chat_id, kk)
return await kk.delete()
except BaseException:
pass
res = await uploader(kk, kk, tt, xx, "Uploading...")
except MessageNotModifiedError as err:
return await xx.edit(str(err))
if " | stream" in hmm and res.name.endswith(
tuple([".mkv", ".mp4", ".mp3", ".opus", ".m4a", ".ogg"])
):
metadata = extractMetadata(createParser(res.name))
wi = 512
hi = 512
duration = 0
if metadata.has("width"):
wi = metadata.get("width")
if metadata.has("height"):
hi = metadata.get("height")
if metadata.has("duration"):
duration = metadata.get("duration").seconds
if metadata.has("artist"):
metadata.get("artist")
if res.name.endswith(tuple([".mkv", ".mp4"])):
attributes = [
DocumentAttributeVideo(
w=wi, h=hi, duration=duration, supports_streaming=True
)
]
if res.name.endswith(tuple([".mp3", ".m4a", ".opus", ".ogg"])):
attributes = [
DocumentAttributeAudio(duration=duration, title=title)
]
try:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
attributes=attributes,
supports_streaming=True,
thumb="resources/extras/new_thumb.jpg",
)
except BaseException:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
)
else:
x = await event.client.send_file(
event.chat_id,
res,
caption=title,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
)
except Exception as ve:
return await eor(xx, str(ve))
e = datetime.now()
t = time_formatter(((e - s).seconds) * 1000)
try:
await x.edit(f"`{kk}`\nTime Taken: `{t}`")
except BaseException:
pass
if t:
await eod(xx, f"Uploaded `{kk}` in `{t}`", time=5)
if t != "":
await eor(xx, f"Uploaded `{kk}` in `{t}`")
else:
await eod(xx, f"Uploaded `{kk}` in `0 second(s)`")
await eor(xx, f"Uploaded `{kk}` in `0 second(s)`")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

84
plugins/evalJs.py Normal file
View File

@@ -0,0 +1,84 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}evaljs <javaScriptCommands>`
Evaluate JavaScript code and upload.
"""
# Inbuilt
import os
import time
from threading import Thread
# Ultroid
from . import *
async def evalJs(
event,
startTime: float,
command: str = "",
):
scriptFile = open(
"./src/ecmaHelper/evalJs.run.js",
"w",
encoding="utf-8",
)
scriptFile.write(str(command))
scriptFile.close()
os.system(f"node ./src/ecmaHelper/eval.d.js")
if os.path.exists("./src/ecmaHelper/evalJs.result.d.txt"):
await ultroid_bot.send_file(
event.chat.id,
"./src/ecmaHelper/evalJs.result.d.txt",
force_document=True,
caption=f"**☞ evalJS\n\n• Command:**\n`{command}` \n\n**• TimeTaken:**\n`{time.time() - startTime:.2f}s` \n\n**• Result:**\n`[Info]: Uploaded File For Better Visualisation Of Indents.`",
)
else:
await ultroid_bot.send_file(
event.chat.id,
"./src/ecmaHelper/evalJs.result.d.txt",
force_document=True,
caption=f"**☞ evalJS\n\n• Command:**\n`{command}` \n\n**• TimeTaken:**\n`{time.time() - startTime:.2f}` \n\n**• Result:**\n`[Warning]: Unexpected Error Occured !`",
)
await event.delete()
file = open("./src/ecmaHelper/evalJs.result.d.txt", encoding="utf-8", mode="w")
file.write("'use-strict';\n")
file.close()
# The Command Is `.evaljs`
@ultroid_cmd(
pattern="evaljs",
)
async def evaluateJs(event):
start = time.time()
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
return await eor(
event,
f"Developer Restricted!\nIf you know what this does, and want to proceed\n\n`{HNDLR}setredis I_DEV True`\n\nThis Might Be Dangerous.",
)
xx = await eor(event, "`Running Thread ...`")
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(xx, "`Give some JS command`", time=5)
if cmd and cmd != "":
Thread(
target=await evalJs(
xx,
command=cmd,
startTime=start,
)
).start()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

75
plugins/fakeaction.py Normal file
View File

@@ -0,0 +1,75 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}ftyping <time/in secs>`
`Show Fake Typing in current chat. `
• `{i}faudio <time/in secs>`
`Show Fake Recording Action in current chat. `
• `{i}fvideo <time/in secs>`
`Show Fake video action in current chat. `
• `{i}fgame <time/in secs>`
`Show Fake Game Playing Action in current chat. `
"""
from . import *
@ultroid_cmd(pattern="ftyping ?(.*)")
async def _(e):
t = e.pattern_match.group(1)
if not (t or t.isdigit()):
t = 100
else:
t = int(t)
await eod(e, f"Starting Fake Typing For {t} sec.")
async with e.client.action(e.chat_id, "typing"):
await asyncio.sleep(t)
@ultroid_cmd(pattern="faudio ?(.*)")
async def _(e):
t = e.pattern_match.group(1)
if not (t or t.isdigit()):
t = 100
else:
t = int(t)
await eod(e, f"Starting Fake audio recording For {t} sec.")
async with e.client.action(e.chat_id, "record-audio"):
await asyncio.sleep(t)
@ultroid_cmd(pattern="fvideo ?(.*)")
async def _(e):
t = e.pattern_match.group(1)
if not (t or t.isdigit()):
t = 100
else:
t = int(t)
await eod(e, f"Starting Fake video recording For {t} sec.")
async with e.client.action(e.chat_id, "record-video"):
await asyncio.sleep(t)
@ultroid_cmd(pattern="fgame ?(.*)")
async def _(e):
t = e.pattern_match.group(1)
if not (t or t.isdigit()):
t = 100
else:
t = int(t)
await eod(e, f"Starting Fake Game Playing For {t} sec.")
async with e.client.action(e.chat_id, "game"):
await asyncio.sleep(t)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -84,7 +84,7 @@ async def _(event):
if str(FBAN) in DEVLIST:
await msg.edit("You can't ban my dev you noob!!")
return
elif FBAN.startswith("@"):
elif isinstance(FBAN, str):
try:
x = await ultroid_bot(GetFullUserRequest(FBAN))
uid = x.user.id
@@ -187,7 +187,7 @@ async def _(event):
except Exception as e:
print(f"Error in removing FedAdmin file.\n{str(e)}")
await msg.edit(
f"SuperFBan Completed.\nTotal Feds - {len(fedlist)}.\nExcluded - {exCount}.\n Affected {len(fedList) - exCount} feds.\n#TB",
f"SuperFBan Completed.\nTotal Feds - {len(fedList)}.\nExcluded - {exCount}.\n Affected {len(fedList) - exCount} feds.\n#TB",
)
@@ -335,7 +335,7 @@ async def _(event):
except Exception as e:
print(f"Error in removing FedAdmin file.\n{str(e)}")
await msg.edit(
f"SuperUnFBan Completed.\nTotal Feds - {len(fedlist)}.\nExcluded - {exCount}.\n Affected {len(fedList) - exCount} feds.\n#TB",
f"SuperUnFBan Completed.\nTotal Feds - {len(fedList)}.\nExcluded - {exCount}.\n Affected {len(fedList) - exCount} feds.\n#TB",
)

View File

@@ -28,7 +28,6 @@
"""
import asyncio
import os
import time
from datetime import datetime
@@ -43,7 +42,7 @@ TOKEN_FILE = "resources/auths/auth_token.txt"
)
async def files(event):
if not os.path.exists(TOKEN_FILE):
return await eod(event, get_string("gdrive_6").format(Var.BOT_USERNAME))
return await eod(event, get_string("gdrive_6").format(asst.me.username))
http = authorize(TOKEN_FILE, None)
await eor(event, list_files(http))
@@ -54,7 +53,7 @@ async def files(event):
async def _(event):
mone = await eor(event, get_string("com_1"))
if not os.path.exists(TOKEN_FILE):
return await eod(mone, get_string("gdrive_6").format(Var.BOT_USERNAME))
return await eod(mone, get_string("gdrive_6").format(asst.me.username))
input_str = event.pattern_match.group(1)
required_file_name = None
start = datetime.now()
@@ -62,26 +61,25 @@ async def _(event):
if event.reply_to_msg_id and not input_str:
reply_message = await event.get_reply_message()
try:
downloaded_file_name = await event.client.download_media(
reply_message,
"resources/downloads",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(
d,
t,
mone,
dddd,
"Downloading...",
),
),
downloaded_file_name = await downloader(
"resources/downloads/" + reply_message.file.name,
reply_message.media.document,
mone,
dddd,
"Downloading...",
)
filename = downloaded_file_name.name
except TypeError:
filename = await event.client.download_media(
"resources/downloads", reply_message.media
)
except Exception as e:
return await eod(mone, str(e), time=10)
end = datetime.now()
ms = (end - start).seconds
required_file_name = downloaded_file_name
required_file_name = filename
await mone.edit(
f"Downloaded to `{downloaded_file_name}` in {ms} seconds.",
f"Downloaded to `{filename}` in {ms} seconds.",
)
elif input_str:
input_str = input_str.strip()
@@ -120,7 +118,7 @@ async def _(event):
)
async def sch(event):
if not os.path.exists(TOKEN_FILE):
return await eod(event, get_string("gdrive_6").format(Var.BOT_USERNAME))
return await eod(event, get_string("gdrive_6").format(asst.me.username))
http = authorize(TOKEN_FILE, None)
input_str = event.pattern_match.group(1).strip()
a = await eor(event, f"Searching for {input_str} in G-Drive.")
@@ -143,7 +141,7 @@ async def sch(event):
)
async def _(event):
if not os.path.exists(TOKEN_FILE):
return await eod(mone, get_string("gdrive_6").format(Var.BOT_USERNAME))
return await eod(mone, get_string("gdrive_6").format(asst.me.username))
input_str = event.pattern_match.group(1)
if os.path.isdir(input_str):
http = authorize(TOKEN_FILE, None)

View File

@@ -14,6 +14,9 @@
• `{i}ungban <reply user/ username>`
Unban Globally.
• `{i}listgban`
List all GBanned users.
• `{i}gmute <reply user/ username>`
Globally Mute the User.
@@ -30,6 +33,8 @@
Globally Send that msg in all Ur Chat Users.
"""
import os
from telethon import events
from . import *
@@ -69,6 +74,7 @@ async def _(e):
except BaseException:
pass
ungban(userid)
delete_gban_reason(userid)
await xx.edit(
f"`Ungbanned` [{name}](tg://user?id={userid}) `in {chats} chats.\nRemoved from gbanwatch.`",
)
@@ -79,21 +85,35 @@ async def _(e):
)
async def _(e):
xx = await eor(e, "`Gbanning...`")
reason = ""
if e.is_private:
userid = (await e.get_chat()).id
try:
reason = e.text.split(" ", maxsplit=1)[1]
except IndexError:
reason = ""
elif e.reply_to_msg_id:
userid = (await e.get_reply_message()).sender_id
try:
reason = e.text.split(" ", maxsplit=1)[1]
except IndexError:
reason = ""
elif e.pattern_match.group(1):
usr = e.text.split(" ", maxsplit=2)[1]
if (e.pattern_match.group(1)).isdigit():
try:
userid = (await e.client.get_entity(int(e.pattern_match.group(1)))).id
userid = (await e.client.get_entity(int(usr))).id
except ValueError as err:
return await eod(xx, f"{str(err)}", time=5)
else:
try:
userid = (await e.client.get_entity(str(e.pattern_match.group(1)))).id
userid = (await e.client.get_entity(str(usr))).id
except ValueError as err:
return await eod(xx, f"{str(err)}", time=5)
try:
reason = e.text.split(" ", maxsplit=2)[2]
except IndexError:
reason = ""
else:
return await eod(xx, "`Reply to some msg or add their id.`", tome=5)
name = (await e.client.get_entity(userid)).first_name
@@ -116,15 +136,19 @@ async def _(e):
except BaseException:
pass
gban(userid)
await xx.edit(
f"`Gbanned` [{name}](tg://user?id={userid}) `in {chats} chats.\nAdded to gbanwatch.`",
)
add_gban_reason(userid, reason)
gb_msg = f"**#Gbanned** [{name}](tg://user?id={userid}) `in {chats} chats and added to gbanwatch!`"
if reason != "":
gb_msg += f"\n**Reason** - {reason}"
await xx.edit(gb_msg)
@ultroid_cmd(
pattern="gcast ?(.*)",
)
async def gcast(event):
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
xx = event.pattern_match.group(1)
if not xx:
return eor(event, "`Give some text to Globally Broadcast`")
@@ -148,6 +172,8 @@ async def gcast(event):
pattern="gucast ?(.*)",
)
async def gucast(event):
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
xx = event.pattern_match.group(1)
if not xx:
return eor(event, "`Give some text to Globally Broadcast`")
@@ -296,11 +322,47 @@ async def _(e):
user.id,
view_messages=False,
)
gban_watch = f"`Gbanned User` [{user.first_name}](tg://user?id={user.id}) `Spotted\n"
gban_watch += f"Banned Successfully`"
reason = get_gban_reason(user.id)
gban_watch = f"#GBanned_User Joined.\n\n**User** - [{user.first_name}](tg://user?id={user.id})\n"
if reason is not None:
gban_watch += f"**Reason**: {reason}\n\n"
gban_watch += f"`User Banned.`"
await e.reply(gban_watch)
except BaseException:
pass
@ultroid_cmd(pattern="listgban")
async def list_gengbanned(event):
users = gbanned_user()
x = await eor(event, get_string("com_1"))
msg = ""
if not udB.get("GBAN"):
return await x.edit("`You haven't GBanned anyone!`")
for i in users:
try:
name = (await ultroid.get_entity(int(i))).first_name
except BaseException:
name = i
msg += "**User**: " + name + "\n"
reason = get_gban_reason(i)
if reason is not None:
msg += f"**Reason**: {reason}\n\n"
else:
msg += "\n"
gbanned_users = f"**List of users GBanned by {OWNER_NAME}**:\n\n{msg}"
if len(gbanned_users) > 4096:
f = open("gbanned.txt", "w")
f.write(gbanned_users.replace("`", "").replace("*", ""))
f.close()
await x.reply(
file="gbanned.txt",
caption=f"List of users GBanned by [{OWNER_NAME}](tg://user?id={OWNER_ID})",
)
os.remove("gbanned.txt")
await x.delete()
else:
await x.edit(gbanned_users)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -12,6 +12,7 @@
For doing google search.
• `{i}img <query>`
`{i}img <query> ; <no of results>`
For doing Images search.
• `{i}reverse <query>`
@@ -25,6 +26,7 @@ import requests
from bs4 import BeautifulSoup as bs
from PIL import Image
from search_engine_parser import GoogleSearch
from search_engine_parser.core.exceptions import NoResultsOrTrafficError as GoglError
from strings import get_string
@@ -38,7 +40,10 @@ async def google(event):
return await event.edit("`Give something to search..`")
x = await eor(event, get_string("com_2"))
gs = GoogleSearch()
res = await gs.async_search(f"{inp}", cache=False)
try:
res = await gs.async_search(f"{inp}", cache=False)
except GoglError as e:
return await eor(event, str(e))
out = ""
for i in range(len(res["links"])):
text = res["titles"][i]
@@ -64,6 +69,7 @@ async def goimg(event):
if ";" in query:
try:
lmt = int(query.split(";")[1])
query = query.split(";")[0]
except BaseExceptaion:
lmt = 5
else:

View File

@@ -16,7 +16,7 @@
"""
from telethon.tl import functions
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import (
ChannelParticipantsKicked,
ChatBannedRights,
@@ -85,7 +85,7 @@ async def _(event):
if "empty" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
y -= 1
@@ -96,7 +96,7 @@ async def _(event):
if "month" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
m -= 1
@@ -107,7 +107,7 @@ async def _(event):
if "week" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
w -= 1
@@ -118,7 +118,7 @@ async def _(event):
if "offline" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
o -= 1
@@ -129,7 +129,7 @@ async def _(event):
if "online" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
q -= 1
@@ -140,7 +140,7 @@ async def _(event):
if "recently" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
r -= 1
@@ -151,7 +151,7 @@ async def _(event):
if "bot" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
b -= 1
@@ -162,7 +162,7 @@ async def _(event):
if "deleted" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
d -= 1
@@ -173,7 +173,7 @@ async def _(event):
if "none" in input_str:
try:
await event.client(
functions.channels.EditBannedRequest(event.chat_id, i, rights),
EditBannedRequest(event.chat_id, i, rights),
)
c += 1
n -= 1

View File

@@ -13,11 +13,12 @@
"""
import os
import time
from datetime import datetime as dt
from . import *
@ultroid_cmd(pattern="mediainfo$")
async def mi(e):
r = await e.get_reply_message()
@@ -27,12 +28,34 @@ async def mi(e):
murl = r.media.stringify()
url = make_html_telegraph("Mediainfo", "Ultroid", f"<code>{murl}</code>")
ee = await eor(e, f"**[{xx}]({url})**\n\n`Loading More...`", link_preview=False)
dl = await ultroid_bot.download_media(r.media)
out, er = await bash(f"mediainfo {dl}")
os.remove(dl)
taime = time.time()
if hasattr(r.media, "document"):
file = r.media.document
mime_type = file.mime_type
filename = r.file.name
if not filename:
if "audio" in mime_type:
filename = "audio_" + dt.now().isoformat("_", "seconds") + ".ogg"
elif "video" in mime_type:
filename = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"
dl = await downloader(
"resources/downloads/" + filename,
file,
ee,
taime,
f"`**[{xx}]({url})**\n\n`Loading More...",
)
naam = dl.name
else:
naam = await ultroid_bot.download_media(r.media)
out, er = await bash(f"mediainfo '{naam}' --Output=HTML")
urll = make_html_telegraph("Mediainfo", "Ultroid", out)
if er:
return await ee.edit(f"**[{xx}]({url})**", link_preview=False)
await ee.edit(f"**[{xx}]({url})**\n\n{out}")
await ee.edit(
f"**[{xx}]({url})**\n\n[More Explained Info]({urll})", link_preview=False
)
os.remove(naam)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -27,6 +27,8 @@
Start logging again from that user.
"""
import re
from pyUltroid.functions.logusers_db import *
from pyUltroid.functions.pmpermit_db import *
from telethon import events
@@ -193,6 +195,19 @@ if sett == "True" and sett != "False":
try:
wrn = COUNT_PM[user.id] + 1
except KeyError:
try:
await asst.send_message(
Var.LOG_CHANNEL,
f"Incoming PM from {mention}!",
buttons=[
Button.inline("Approve PM", data=f"approve_{user.id}"),
Button.inline("Block PM", data=f"block_{user.id}"),
],
)
except BaseException:
await ultroid.send_message(
Var.LOG_CHANNEL, f"Incoming PM from {mention}!"
)
wrn = 1
if user.id in LASTMSG:
prevmsg = LASTMSG[user.id]
@@ -332,7 +347,6 @@ if sett == "True" and sett != "False":
approve_user(uid)
await apprvpm.edit(f"[{name0}](tg://user?id={uid}) `approved to PM!`")
async for message in apprvpm.client.iter_messages(user.id, search=UND):
await message.delete()
async for message in apprvpm.client.iter_messages(user.id, search=UNS):
await message.delete()
@@ -468,4 +482,129 @@ if sett == "True" and sett != "False":
)
@callback(
re.compile(
b"approve_(.*)",
),
)
@owner
async def apr_in(event):
uid = int(event.data_match.group(1).decode("UTF-8"))
if str(uid) in DEVLIST:
await event.edit("It's a dev! Approved!")
if not is_approved(uid):
approve_user(uid)
try:
user_name = (await ultroid.get_entity(uid)).first_name
except BaseException:
user_name = ""
await event.edit(
f"[{user_name}](tg://user?id={uid}) `approved to PM!`",
buttons=[
Button.inline("Disapprove PM", data=f"disapprove_{uid}"),
Button.inline("Block", data=f"block_{uid}"),
],
)
async for message in ultroid.iter_messages(uid, search=UND):
await message.delete()
async for message in ultroid.iter_messages(uid, search=UNS):
await message.delete()
await event.answer("Approved.")
x = await ultroid.send_message(uid, "You have been approved to PM me!")
await asyncio.sleep(5)
await x.delete()
else:
await event.edit(
"`User may already be approved.`",
buttons=[
Button.inline("Disapprove PM", data=f"disapprove_{uid}"),
Button.inline("Block", data=f"block_{uid}"),
],
)
@callback(
re.compile(
b"disapprove_(.*)",
),
)
@owner
async def disapr_in(event):
uid = int(event.data_match.group(1).decode("UTF-8"))
if is_approved(uid):
disapprove_user(uid)
try:
user_name = (await ultroid.get_entity(uid)).first_name
except BaseException:
user_name = ""
await event.edit(
f"[{user_name}](tg://user?id={uid}) `disapproved from PMs!`",
buttons=[
Button.inline("Approve PM", data=f"approve_{uid}"),
Button.inline("Block", data=f"block_{uid}"),
],
)
await event.answer("DisApproved.")
x = await ultroid.send_message(uid, "You have been disapproved from PMing me!")
await asyncio.sleep(5)
await x.delete()
else:
await event.edit(
"`User was never approved!`",
buttons=[
Button.inline("Disapprove PM", data=f"disapprove_{uid}"),
Button.inline("Block", data=f"block_{uid}"),
],
)
@callback(
re.compile(
b"block_(.*)",
),
)
@owner
async def blck_in(event):
uid = int(event.data_match.group(1).decode("UTF-8"))
await ultroid(BlockRequest(uid))
try:
user_name = (await ultroid.get_entity(uid)).first_name
except BaseException:
user_name = ""
await event.answer("Blocked.")
await event.edit(
f"[{user_name}](tg://user?id={uid}) has been **blocked!**",
buttons=Button.inline("UnBlock", data=f"unblock_{uid}"),
)
@callback(
re.compile(
b"unblock_(.*)",
),
)
@owner
async def unblck_in(event):
uid = int(event.data_match.group(1).decode("UTF-8"))
await ultroid(UnblockRequest(uid))
try:
user_name = (await ultroid.get_entity(uid)).first_name
except BaseException:
user_name = ""
await event.answer("UnBlocked.")
await event.edit(
f"[{user_name}](tg://user?id={uid}) has been **unblocked!**",
buttons=[
Button.inline("Block", data=f"block_{uid}"),
Button.inline("Close", data="deletedissht"),
],
)
@callback("deletedissht")
async def ytfuxist(e):
await e.answer("Deleted.")
await e.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -27,8 +27,12 @@
import asyncio
import os
from telethon.tl import functions
from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.tl.functions.photos import (
DeletePhotosRequest,
GetUserPhotosRequest,
UploadProfilePhotoRequest,
)
from telethon.tl.types import InputPhoto
from . import *
@@ -45,7 +49,7 @@ async def _(ult):
ok = await eor(ult, "...")
set = ult.pattern_match.group(1)
try:
await ultroid_bot(functions.account.UpdateProfileRequest(about=set))
await ultroid_bot(UpdateProfileRequest(about=set))
await ok.edit(f"Profile bio changed to\n`{set}`")
except Exception as ex:
await ok.edit("Error occured.\n`{}`".format(str(ex)))
@@ -68,7 +72,7 @@ async def _(ult):
first_name, last_name = names.split("//", 1)
try:
await ultroid_bot(
functions.account.UpdateProfileRequest(
UpdateProfileRequest(
first_name=first_name,
last_name=last_name,
),
@@ -102,7 +106,7 @@ async def _(ult):
await ok.edit("`Uploading it to my profile...`")
file = await ultroid_bot.upload_file(photo)
try:
await ultroid_bot(functions.photos.UploadProfilePhotoRequest(file))
await ultroid_bot(UploadProfilePhotoRequest(file))
except Exception as ex:
await ok.edit("Error occured.\n`{}`".format(str(ex)))
else:

View File

@@ -10,26 +10,17 @@
**DataBase Commands, do not use if you don't know what it is.**
• `{i}redisusage`
Check Storaged Data Capacity.
• `{i}setredis key | value`
Redis Set Value.
e.g :
`{i}setredis hi there`
`{i}setredis hi there | ultroid here`
• `{i}getredis key`
Redis Get Value
• `{i}delredis key`
Delete Key from Redis DB
• `{i}renredis old keyname | new keyname`
Update Key Name
• `{i}getkeys`
Get the list of keys stored in Redis
"""
import re
@@ -41,6 +32,9 @@ from . import *
pattern="setredis ?(.*)",
)
async def _(ult):
if not ult.out:
if not is_fullsudo(ult.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
ok = await eor(ult, "`...`")
try:
delim = " " if re.search("[|]", ult.pattern_match.group(1)) is None else " | "
@@ -57,25 +51,13 @@ async def _(ult):
await ok.edit("`Something Went Wrong`")
@ultroid_cmd(
pattern="getredis ?(.*)",
)
async def _(ult):
ok = await eor(ult, "`Fetching data from Redis`")
val = ult.pattern_match.group(1)
if val == "":
return await ult.edit(f"Please use `{hndlr}getkeys <keyname>`")
try:
value = Redis(val)
await ok.edit(f"Key: `{val}`\nValue: `{value}`")
except BaseException:
await ok.edit("`Something Went Wrong`")
@ultroid_cmd(
pattern="delredis ?(.*)",
)
async def _(ult):
if not ult.out:
if not is_fullsudo(ult.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
ok = await eor(ult, "`Deleting data from Redis ...`")
try:
key = ult.pattern_match.group(1)
@@ -89,6 +71,9 @@ async def _(ult):
pattern="renredis ?(.*)",
)
async def _(ult):
if not ult.out:
if not is_fullsudo(ult.sender_id):
return await eod(ult, "`This Command Is Sudo Restricted.`")
ok = await eor(ult, "`...`")
delim = " " if re.search("[|]", ult.pattern_match.group(1)) is None else " | "
data = ult.pattern_match.group(1).split(delim)
@@ -107,33 +92,4 @@ async def _(ult):
await ok.edit("Key not found")
@ultroid_cmd(
pattern="getkeys$",
)
async def _(ult):
ok = await eor(ult, "`Fetching Keys ...`")
keys = sorted(udB.keys())
msg = ""
for x in keys:
if x.isdigit() or x.startswith("-"):
pass
else:
msg += f"• `{x}`" + "\n"
await ok.edit(f"**List of Redis Keys :**\n{msg}")
@ultroid_cmd(
pattern="redisusage$",
)
async def _(ult):
ok = await eor(ult, "`Calculating ...`")
x = 30 * 1024 * 1024
z = 0
for n in udB.keys():
z += udB.memory_usage(n)
a = humanbytes(z) + "/" + humanbytes(x)
b = str(round(z / x * 100, 3)) + "%" + " Used"
await ok.edit(f"{a}\n{b}")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

66
plugins/saavn.py Normal file
View File

@@ -0,0 +1,66 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}saavn <search query>`
`search song on saavn`
"""
import os
import time
from urllib.request import urlretrieve
import requests as r
from telethon.tl.types import DocumentAttributeAudio
from . import *
@ultroid_cmd(pattern="saavn ?(.*)")
async def siesace(e):
song = e.pattern_match.group(1)
if not song:
return await eod(e, "`Give me Something to Search")
hmm = time.time()
lol = await eor(e, "`...`")
sung = song.replace(" ", "%20")
url = f"https://jostapi.herokuapp.com/saavn?query={sung}"
try:
k = (r.get(url)).json()[0]
except IndexError:
return await eod(e, "`Song Not Found.. `")
title = k["song"]
urrl = k["media_url"]
img = k["image"]
duration = k["duration"]
singers = k["singers"]
urlretrieve(urrl, title + ".mp3")
urlretrieve(img, title + ".jpg")
okk = await uploader(
title + ".mp3", title + ".mp3", hmm, lol, "Uploading " + title + "..."
)
await ultroid_bot.send_file(
e.chat_id,
okk,
attributes=[
DocumentAttributeAudio(
duration=int(duration),
title=title,
performer=singers,
)
],
supports_streaming=True,
thumb=title + ".jpg",
)
await lol.delete()
os.remove(title + ".mp3")
os.remove(title + ".jpg")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -22,8 +22,8 @@ async def saf(e):
return await eod(
e, "Reply to Any Message to save it to ur saved messages", time=5
)
await ultroid_bot.send_message("me", x)
await eod(e, "Message saved at saved messages", time=5)
await ultroid_bot.send_message(e.sender_id, x)
await eod(e, "Message saved to Your Pm/Saved Messages.", time=5)
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

58
plugins/schedule_msg.py Normal file
View File

@@ -0,0 +1,58 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
•`{i}schedule <text/reply to msg> <time>`
In time u can use second as number, or like 1h or 1m
eg. `{i}schedule Hello 100` It deliver msg after 100 sec.
eg. `{i}schedule Hello 1h` It deliver msg after an hour.
"""
from datetime import timedelta
from . import *
@ultroid_cmd(pattern="schedule ?(.*)")
async def _(e):
x = e.pattern_match.group(1)
xx = await e.get_reply_message()
if x and not xx:
y = x.split(" ")[-1]
k = x.replace(y, "")
if y.isdigit():
await ultroid_bot.send_message(
e.chat_id, k, schedule=timedelta(seconds=int(y))
)
await eod(e, "`Scheduled msg Succesfully`")
else:
try:
z = await ban_time(e, y)
await ultroid_bot.send_message(e.chat_id, k, schedule=z)
await eod(e, "`Scheduled msg Succesfully`")
except BaseException:
await eod(e, "`Incorrect Format`")
elif xx and x:
if x.isdigit():
await e.client.send_message(
e.chat_id, xx, schedule=timedelta(seconds=int(x))
)
await eod(e, "`Scheduled msg Succesfully`")
else:
try:
z = await ban_time(e, x)
await ultroid_bot.send_message(e.chat_id, xx, schedule=z)
await eod(e, "`Scheduled msg Succesfully`")
except BaseException:
await eod(e, "`Incorrect Format`")
else:
return await eod(e, "`Incorrect Format`")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -92,26 +92,28 @@ async def adaudroid(event):
)
async def hbd(event):
if not event.pattern_match.group(1):
await eor(event, "`Put input in dd/mm/yyyy format`")
return
return await eor(event, "`Put input in dd/mm/yyyy format`")
if event.reply_to_msg_id:
kk = await event.get_reply_message()
nam = await ultroid_bot.get_entity(kk.from_id)
name = nam.first_name
else:
a = await ultroid_bot.get_me()
name = a.first_name
name = ultroid_bot.me.first_name
zn = pytz.timezone("Asia/Kolkata")
abhi = dt.now(zn)
n = event.text
q = n[5:]
p = n[5:7]
r = n[8:10]
s = n[11:]
kk = q.split("/")
p = kk[0]
r = kk[1]
s = kk[2]
day = int(p)
month = r
paida = q
jn = dt.strptime(paida, "%d/%m/%Y")
try:
jn = dt.strptime(paida, "%d/%m/%Y")
except BaseException:
return await eor(event, "`Put input in dd/mm/yyyy format`")
jnm = zn.localize(jn)
zinda = abhi - jnm
barsh = (zinda.total_seconds()) / (365.242 * 24 * 3600)
@@ -209,7 +211,7 @@ async def _(event):
z = requests.get("https://combot.org/telegram/stickers?q=" + x).text
xx = b(z, "lxml")
title = xx.find_all("div", "sticker-pack__title")
link = xx.find_all("a", {"class": "sticker-pack__btn"})
link = xx.find_all("a", target="_blank")
if not link:
return await uu.edit("Found Nothing")
a = "SᴛɪᴋEʀs Aɪʟᴀʙʟᴇ ~"

View File

@@ -18,10 +18,8 @@
List all sudo users.
"""
import re
from pyUltroid.misc._decorators import sed
from telethon.tl.functions.users import GetFullUserRequest
from . import *
@@ -30,9 +28,10 @@ from . import *
pattern="addsudo ?(.*)",
)
async def _(ult):
inputs = ult.pattern_match.group(1)
if Var.BOT_MODE:
try:
if ult.sender_id != Var.OWNER_ID:
if ult.sender_id != int(Redis(OWNER_ID)):
return await eod(ult, "`Sudo users can't add new sudos!`", time=10)
except BaseException:
pass
@@ -42,82 +41,61 @@ async def _(ult):
ok = await eor(ult, "`Updating SUDO Users List ...`")
if ult.reply_to_msg_id:
replied_to = await ult.get_reply_message()
id = replied_to.sender.id
user = await ult.client(GetFullUserRequest(int(id)))
id = await get_user_id(replied_to.sender_id)
name = (await ult.client.get_entity(int(id))).first_name
sed.append(id)
mmm = ""
if id == ultroid_bot.me.id:
return await ok.edit("You cant add yourself as Sudo User...")
mmm += "You cant add yourself as Sudo User..."
elif is_sudo(id):
return await ok.edit(
f"[{user.user.first_name}](tg://user?id={id}) `is already a SUDO User ...`",
)
mmm += f"[{name}](tg://user?id={id}) `is already a SUDO User ...`"
elif add_sudo(id):
udB.set("SUDO", "True")
return await ok.edit(
f"**Added [{user.user.first_name}](tg://user?id={id}) as SUDO User**",
)
mmm += f"**Added [{name}](tg://user?id={id}) as SUDO User**"
else:
return await ok.edit("`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`")
mmm += "`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`"
await eod(ok, mmm, time=5)
args = ult.pattern_match.group(1).strip()
if re.search(r"[\s]", args) is not None:
args = args.split(" ")
msg = ""
sudos = get_sudos()
for item in args:
user = ""
try:
user = await ult.client(GetFullUserRequest(int(item)))
except BaseException:
pass
if not hasattr(user, "user"):
msg += f"• `{item}` __Invalid UserID__\n"
elif item in sudos:
msg += f"• [{user.user.first_name}](tg://user?id={item}) __Already a SUDO__\n"
elif add_sudo(item.strip()):
msg += (
f"• [{user.user.first_name}](tg://user?id={item}) __Added SUDO__\n"
)
if inputs:
id = await get_user_id(inputs)
try:
name = (await ult.client.get_entity(int(id))).first_name
except BaseException:
name = ""
sed.append(id)
mmm = ""
if id == ultroid_bot.me.id:
mmm += "You cant add yourself as Sudo User..."
elif is_sudo(id):
if name != "":
mmm += f"[{name}](tg://user?id={id}) `is already a SUDO User ...`"
else:
msg += f"`{item}` __Failed to Add SUDO__\n"
return await ok.edit(f"**Adding Sudo Users :**\n{msg}")
id = args.strip()
user = ""
try:
user = await ult.client(GetFullUserRequest(int(i)))
except BaseException:
pass
if not id.isdigit():
return await ok.edit("`Integer(s) Expected`")
elif not hasattr(user, "user"):
return await ok.edit("`Invalid UserID`")
elif is_sudo(id):
return await ok.edit(
f"[{user.user.first_name}](tg://user?id={id}) `is already a SUDO User ...`",
)
elif add_sudo(id):
udB.set("SUDO", "True")
return await ok.edit(
f"**Added [{user.user.first_name}](tg://user?id={id}) as SUDO User**\n\nDo Restart",
)
mmm += f"`{id} is already a SUDO User...`"
elif add_sudo(id):
udB.set("SUDO", "True")
if name != "":
mmm += f"**Added [{name}](tg://user?id={id}) as SUDO User**"
else:
mmm += f"**Added **`{id}`** as SUDO User**"
else:
mmm += "`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`"
await eod(ok, mmm, time=5)
else:
return await ok.edit(f"**Failed to add `{id}` as SUDO User ... **")
return await eod(ok, "`Reply to a msg or add it's id/username.`", time=5)
@ultroid_cmd(
pattern="delsudo ?(.*)",
)
async def _(ult):
inputs = ult.pattern_match.group(1)
if Var.BOT_MODE:
try:
if ult.sender_id != Var.OWNER_ID:
return await eor(
if ult.sender_id != int(Redis(OWNER_ID)):
return await eod(
ult,
"You are sudo user, You cant add other sudo user.",
time=5,
)
except BaseException:
pass
@@ -127,68 +105,39 @@ async def _(ult):
ok = await eor(ult, "`Updating SUDO Users List ...`")
if ult.reply_to_msg_id:
replied_to = await ult.get_reply_message()
id = replied_to.sender.id
user = await ult.client(GetFullUserRequest(int(id)))
id = await get_user_id(replied_to.sender_id)
name = (await ult.client.get_entity(int(id))).first_name
sed.remove(id)
mmm = ""
if not is_sudo(id):
return await ok.edit(
f"[{user.user.first_name}](tg://user?id={id}) `wasn't a SUDO User ...`",
)
mmm += f"[{name}](tg://user?id={id}) `wasn't a SUDO User ...`"
elif del_sudo(id):
return await ok.edit(
f"**Removed [{user.user.first_name}](tg://user?id={id}) from SUDO User(s)**",
)
mmm += f"**Removed [{name}](tg://user?id={id}) from SUDO User(s)**"
else:
return await ok.edit("`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`")
mmm += "`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`"
await eod(ok, mmm, time=5)
args = ult.pattern_match.group(1)
if re.search(r"[\s]", args) is not None:
args = args.split(" ")
msg = ""
sudos = get_sudos()
for item in args:
user = ""
try:
user = await ult.client(GetFullUserRequest(int(item)))
except BaseException:
pass
if not hasattr(user, "user"):
msg += f"• `{item}` __Invalid UserID__\n"
elif item in sudos and del_sudo(item):
msg += (
f"• [{user.user.first_name}](tg://user?id={id}) __Removed SUDO__\n"
)
elif item not in sudos:
msg += (
f"• [{user.user.first_name}](tg://user?id={id}) __Wasn't a SUDO__\n"
)
if inputs:
id = await get_user_id(inputs)
try:
name = (await ult.client.get_entity(int(id))).first_name
except BaseException:
name = ""
sed.remove(id)
mmm = ""
if not is_sudo(id):
if name != "":
mmm += f"[{name}](tg://user?id={id}) `wasn't a SUDO User ...`"
else:
msg += f"`{item}` __Failed to Remove SUDO__\n"
return await ok.edit(msg)
id = args.strip()
user = ""
try:
user = await ult.client(GetFullUserRequest(int(i)))
except BaseException:
pass
if not id.isdigit():
return await ok.edit("`Integer(s) Expected`")
elif not hasattr(user, "user"):
return await ok.edit("`Invalid UserID`")
elif not is_sudo(id):
return await ok.edit(
f"[{user.user.first_name}](tg://user?id={id}) wasn't a SUDO user ...",
)
elif del_sudo(id):
return await ok.edit(
f"**Removed [{user.user.first_name}](tg://user?id={id}) from SUDO User**",
)
else:
return await ok.edit(f"**Failed to Remove `{id}` as SUDO User ... **")
mmm += f"`{id} wasn't a SUDO User...`"
elif del_sudo(id):
if name != "":
mmm += f"**Removed [{name}](tg://user?id={id}) from SUDO User(s)**"
else:
mmm += f"**Removed **`{id}`** from SUDO User(s)**"
else:
mmm += "`SEEMS LIKE THIS FUNCTION CHOOSE TO BREAK ITSELF`"
await eod(ok, mmm, time=5)
@ultroid_cmd(
@@ -196,18 +145,18 @@ async def _(ult):
)
async def _(ult):
ok = await eor(ult, "`...`")
sudos = get_sudos()
if "" in sudos:
return await ok.edit("`No SUDO User was assigned ...`")
sudos = Redis("SUDOS")
if sudos == "" or sudos is None:
return await eod(ult, "`No SUDO User was assigned ...`", time=5)
sumos = sudos.split(" ")
msg = ""
for i in sudos:
user = ""
for i in sumos:
try:
user = await ok.client(GetFullUserRequest(int(i.strip())))
name = (await ult.client.get_entity(int(i))).first_name
except BaseException:
pass
if hasattr(user, "user"):
msg += f"• [{user.user.first_name}](tg://user?id={i}) ( `{i}` )\n"
name = ""
if name != "":
msg += f"• [{name}](tg://user?id={i}) ( `{i}` )\n"
else:
msg += f"• `{i}` -> Invalid User\n"
m = udB.get("SUDO") if udB.get("SUDO") else "False"

View File

@@ -17,6 +17,9 @@
• `{i}circle`
Reply to a audio song or gif to get video note.
• `{i}ls`
Get all the Files inside a Directory.
• `{i}bots`
Shows the number of bots in the current chat with their perma-link.
@@ -33,29 +36,54 @@
• `{i}tr <dest lang code> <(reply to) a message>`
Get translated message.
• `{i}sysinfo`
Shows System Info.
"""
import asyncio
import io
import os
import sys
import time
import traceback
from asyncio.exceptions import TimeoutError
from os import remove
from pathlib import Path
import cv2
import emoji
from carbonnow import Carbon
from googletrans import Translator
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantsBots, User
from telethon.utils import pack_bot_file_id
from . import *
from . import humanbytes as hb
@ultroid_cmd(
pattern="sysinfo$",
)
async def _(e):
x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
with open("neo.txt", "r") as neo:
p = (neo.read()).replace("\n\n", "")
ok = Carbon(code=p)
haa = await ok.save("neofetch")
await e.client.send_file(e.chat_id, haa)
remove("neofetch.jpg")
remove("neo.txt")
@ultroid_cmd(
pattern="tr",
)
async def _(event):
if len(event.text) > 3:
if not event.text[3] == " ":
return
input = event.text[4:6]
txt = event.text[7:]
xx = await eor(event, "`Translating...`")
@@ -74,13 +102,13 @@ async def _(event):
try:
tt = translator.translate(text, dest=lan)
output_str = f"**TRANSLATED** from {tt.src} to {lan}\n{tt.text}"
await eod(xx, output_str)
await eor(xx, output_str)
except Exception as exc:
await eod(xx, str(exc), time=10)
@ultroid_cmd(
pattern="id$",
pattern="id ?(.*)",
)
async def _(event):
if event.reply_to_msg_id:
@@ -92,7 +120,7 @@ async def _(event):
event,
"**Current Chat ID:** `{}`\n**From User ID:** `{}`\n**Bot API File ID:** `{}`".format(
str(event.chat_id),
str(r_msg.sender.id),
str(r_msg.sender_id),
bot_api_file_id,
),
)
@@ -101,9 +129,18 @@ async def _(event):
event,
"**Chat ID:** `{}`\n**User ID:** `{}`".format(
str(event.chat_id),
str(r_msg.sender.id),
str(r_msg.sender_id),
),
)
elif event.pattern_match.group(1):
ids = await get_user_id(event.pattern_match.group(1))
return await eor(
event,
"**Chat ID:** `{}`\n**User ID:** `{}`".format(
str(event.chat_id),
str(ids),
),
)
else:
await eor(event, "**Current Chat ID:** `{}`".format(str(event.chat_id)))
@@ -148,7 +185,7 @@ async def _(ult):
)
except Exception as e:
mentions += " " + str(e) + "\n"
await eod(ult, mentions)
await eor(ult, mentions)
@ultroid_cmd(pattern="hl")
@@ -157,7 +194,7 @@ async def _(ult):
input = ult.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eod(ult, "`Input some link`", time=5)
await eod(ult, "[](" + input + ")", link_preview=False)
await eor(ult, "[](" + input + ")", link_preview=False)
@ultroid_cmd(
@@ -178,7 +215,7 @@ async def _(e):
cv2.imwrite("img.png", output)
thumb = "img.png"
except TypeError:
thumb = "./resources/extras/thumb.jpg"
thumb = "./resources/extras/new_thumb.jpg"
c = await a.download_media(
"resources/downloads/",
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
@@ -245,17 +282,117 @@ async def _(e):
elif a.document and a.document.mime_type == "video/mp4":
z = await eor(e, "**Cʀᴇᴀᴛɪɴɢ Vɪᴅᴇ Nᴛᴇ**")
c = await a.download_media("resources/downloads/")
await e.client.send_file(e.chat_id, c, video_note=True, reply_to=a)
await e.client.send_file(
e.chat_id,
c,
video_note=True,
thumb="resources/extras/new_thumb.jpg",
reply_to=a,
)
await z.delete()
os.remove(c)
else:
return await eor(e, "**Reply to a gif or audio file only**")
@ultroid_cmd(pattern="ls ?(.*)")
async def _(e):
path = Path(e.pattern_match.group(1))
if not path:
path = Path(".")
else:
if not os.path.isdir(path):
return await eod(e, "`Incorrect Directory.`")
if not os.listdir(path):
return await eod(e, "`This Directory is Empty.`")
files = path.iterdir()
pyfiles = []
jsons = []
vdos = []
audios = []
pics = []
others = []
otherfiles = []
folders = []
text = []
apk = []
exe = []
zip = []
book = []
for file in sorted(files):
if os.path.isdir(file):
folders.append("📂 " + str(file))
elif str(file).endswith(".py"):
pyfiles.append("🐍 " + str(file))
elif str(file).endswith(".json"):
jsons.append("🔮 " + str(file))
elif str(file).endswith((".mkv", ".mp4", ".avi")):
vdos.append("🎥 " + str(file))
elif str(file).endswith((".mp3", ".ogg", ".m4a")):
audios.append("🔊 " + str(file))
elif str(file).endswith((".jpg", ".jpeg", ".png", ".webp")):
pics.append("🖼 " + str(file))
elif str(file).endswith((".txt", ".text", ".log")):
text.append("📄 " + str(file))
elif str(file).endswith((".apk", ".xapk")):
apk.append("📲 " + str(file))
elif str(file).endswith(".exe"):
set.append("" + str(file))
elif str(file).endswith((".zip", ".rar")):
zip.append("🗜 " + str(file))
elif str(file).endswith((".pdf", ".epub")):
book.append("📗 " + str(file))
elif "." in str(file)[1:]:
others.append("🏷 " + str(file))
else:
otherfiles.append("📒 " + str(file))
omk = [
*sorted(folders),
*sorted(pyfiles),
*sorted(jsons),
*sorted(zip),
*sorted(vdos),
*sorted(pics),
*sorted(audios),
*sorted(apk),
*sorted(exe),
*sorted(book),
*sorted(text),
*sorted(others),
*sorted(otherfiles),
]
text = ""
for i in omk:
emoji = i.split()[0]
name = i.split(maxsplit=1)[1]
nam = name.split("/")[-1]
if os.path.isdir(name):
size = 0
for path, dirs, files in os.walk(name):
for f in files:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
if hb(size):
text += emoji + f" `{nam}`" + " `" + hb(size) + "`\n"
else:
text += emoji + f" `{nam}`" + "\n"
else:
if hb(int(os.path.getsize(name))):
text += (
emoji + f" `{nam}`" + " `" + hb(int(os.path.getsize(name))) + "`\n"
)
else:
text += emoji + f" `{nam}`" + "\n"
await eor(e, text)
@ultroid_cmd(
pattern="bash",
)
async def _(event):
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
@@ -297,19 +434,28 @@ async def _(event):
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
allow_cache=False,
caption=f"`{cmd}`",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eod(xx, OUT)
await eor(xx, OUT)
p = print # ignore: pylint
@ultroid_cmd(
pattern="eval",
)
async def _(event):
if len(event.text) > 5:
if not event.text[5] == " ":
return
if not event.out and not is_fullsudo(event.sender_id):
return await eor(event, "`This Command Is Sudo Restricted.`")
if Redis("I_DEV") != "True":
await eor(
event,
@@ -347,7 +493,7 @@ async def _(event):
else:
evaluation = "Success"
final_output = (
"__►__ **EVAL**\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(
"__►__ **EVALPy**\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(
cmd,
evaluation,
)
@@ -360,13 +506,14 @@ async def _(event):
event.chat_id,
out_file,
force_document=True,
thumb="resources/extras/new_thumb.jpg",
allow_cache=False,
caption=f"```{cmd}```",
reply_to=reply_to_id,
)
await xx.delete()
else:
await eod(xx, final_output)
await eor(xx, final_output)
async def aexec(code, event):
@@ -385,6 +532,8 @@ async def aexec(code, event):
pattern="sg ?(.*)",
)
async def lastname(steal):
if BOT_MODE:
return await eor(steal, "`You cant Use This command in BOT_MODE..`")
mat = steal.pattern_match.group(1)
if not (steal.is_reply or mat):
await eor(steal, "`Use this command with reply or give Username/id...`")

59
plugins/unsplash.py Normal file
View File

@@ -0,0 +1,59 @@
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
{i}unsplash <search query> ; <no of pics>
Unsplash Image Search.
"""
import urllib
import requests as r
from bs4 import BeautifulSoup as bs
from . import *
@ultroid_cmd(pattern="unsplash ?(.*)")
async def searchunsl(ult):
match = ult.pattern_match.group(1)
if not match:
return await eor(ult, "Give me Something to Search")
if ";" in match:
num = int(match.split(";")[1])
query = match.split(";")[0]
else:
num = 5
query = match
tep = await eor(ult, "`Processing... `")
res = autopicsearch(query)
if len(res) == 0:
return await eod(ult, "No Results Found !")
qas = res[:num]
dir = "resources/downloads"
CL = []
nl = 0
for rp in qas:
li = "https://unsplash.com" + rp["href"]
ct = r.get(li).content
bst = bs(ct, "html.parser", from_encoding="utf-8")
ft = bst.find_all("img", "_2UpQX")[0]["src"]
Hp = dir + "img" + f"{nl}.png"
urllib.request.urlretrieve(ft, Hp)
CL.append(Hp)
nl += 1
await bot.send_file(
ult.chat_id, CL, caption=f"Uploaded {len(qas)} Images\n", album=True
)
await tep.delete()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -8,186 +8,37 @@
✘ Commands Available -
• `{i}update`
See changelogs if any update is available.
• `{i}update now`
(Force)Update your bots to the latest version.
"""
import asyncio
import sys
from os import execl, path, remove
from . import *
from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError
from . import HELP, get_string, ultroid_version
UPSTREAM_REPO_URL = "https://github.com/TeamUltroid/Ultroid"
requirements_path = path.join(
path.dirname(path.dirname(path.dirname(__file__))),
"requirements.txt",
)
async def gen_chlog(repo, diff):
ac_br = repo.active_branch.name
ch_log = tldr_log = ""
ch = f"<b>Ultroid {ultroid_version} updates for <a href={UPSTREAM_REPO_URL}/tree/{ac_br}>[{ac_br}]</a>:</b>"
ch_tl = f"Ultroid {ultroid_version} updates for {ac_br}:"
d_form = "%d/%m/%y || %H:%M"
for c in repo.iter_commits(diff):
ch_log += f"\n\n💬 <b>{c.count()}</b> 🗓 <b>[{c.committed_datetime.strftime(d_form)}]</b>\n<b><a href={UPSTREAM_REPO_URL.rstrip('/')}/commit/{c}>[{c.summary}]</a></b> 👨‍💻 <code>{c.author}</code>"
tldr_log += f"\n\n💬 {c.count()} 🗓 [{c.committed_datetime.strftime(d_form)}]\n[{c.summary}] 👨‍💻 {c.author}"
if ch_log:
return str(ch + ch_log), str(ch_tl + tldr_log)
else:
return ch_log, tldr_log
async def updateme_requirements():
reqs = str(requirements_path)
try:
process = await asyncio.create_subprocess_shell(
" ".join([sys.executable, "-m", "pip", "install", "-r", reqs]),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await process.communicate()
return process.returncode
except Exception as e:
return repr(e)
@ultroid_cmd(
pattern="update ?(.*)",
)
async def upstream(ups):
pagal = await eor(ups, get_string("upd_1"))
conf = ups.pattern_match.group(1)
off_repo = UPSTREAM_REPO_URL
try:
txt = get_string("upd_2")
repo = Repo()
except NoSuchPathError as error:
await eod(pagal, f"{txt}\n`directory {error} is not found`", time=10)
repo.__del__()
return
except GitCommandError as error:
await eod(pagal, f"{txt}\n`Early failure! {error}`", time=10)
repo.__del__()
return
except InvalidGitRepositoryError as error:
if conf != "now":
await eod(
pagal,
f"**Unfortunately, the directory {error} does not seem to be a git repository.Or Maybe it just needs a sync verification with {GIT_REPO_NAME} But we can fix that by force updating the userbot using** `.update now.`",
time=30,
)
return
repo = Repo.init()
origin = repo.create_remote("upstream", off_repo)
origin.fetch()
repo.create_head("dev", origin.refs.dev)
repo.heads.dev.set_tracking_branch(origin.refs.dev)
repo.heads.dev.checkout(True)
ac_br = repo.active_branch.name
try:
repo.create_remote("upstream", off_repo)
except BaseException:
pass
ups_rem = repo.remote("upstream")
ups_rem.fetch(ac_br)
changelog, tl_chnglog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")
if "now" not in conf:
if changelog:
changelog_str = (
changelog + f"\n\nUse <code>{hndlr}update now</code> to update!"
)
tldr_str = tl_chnglog + f"\n\nUse {hndlr}update now to update!"
if len(changelog_str) > 4096:
await eor(pagal, get_string("upd_4"))
file = open(f"ultroid_updates.txt", "w+")
file.write(tldr_str)
file.close()
await ups.client.send_file(
ups.chat_id,
f"ultroid_updates.txt",
caption=get_string("upd_5").format(hndlr),
reply_to=ups.id,
)
remove(f"ultroid_updates.txt")
return
else:
return await eod(pagal, changelog_str, parse_mode="html")
else:
await eod(
pagal,
get_string("upd_7").format(ac_br, UPSTREAM_REPO_URL, ac_br),
time=10,
)
repo.__del__()
return
if Var.HEROKU_API is not None:
import heroku3
heroku = heroku3.from_key(Var.HEROKU_API)
heroku_app = None
heroku_applications = heroku.apps()
if not Var.HEROKU_APP_NAME:
await eod(
pagal,
"`Please set up the `HEROKU_APP_NAME` variable to be able to update userbot.`",
time=10,
)
repo.__del__()
return
for app in heroku_applications:
if app.name == Var.HEROKU_APP_NAME:
heroku_app = app
break
if heroku_app is None:
await eod(
pagal,
f"{txt}\n`Invalid Heroku credentials for updating userbot dyno.`",
time=10,
)
repo.__del__()
return
@ultroid_cmd(pattern="update$")
async def _(e):
x = await updater()
branch = (Repo.init()).active_branch
if x is not None:
await eor(
pagal,
"`Userbot dyno build in progress, please wait for it to complete.`",
e,
f'<strong><a href="t.me/c/{x.peer_id.channel_id}/{x.id}">[ChangeLogs]</a></strong>',
parse_mode="html",
link_preview=False,
)
ups_rem.fetch(ac_br)
repo.git.reset("--hard", "FETCH_HEAD")
heroku_git_url = heroku_app.git_url.replace(
"https://",
"https://api:" + Var.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 eod(pagal, f"{txt}\n`Here is the error log:\n{error}`", time=10)
repo.__del__()
return
await eod(pagal, "`Successfully Updated!\nRestarting, please wait...`", time=60)
else:
# Classic Updater, pretty straightforward.
try:
ups_rem.pull(ac_br)
except GitCommandError:
repo.git.reset("--hard", "FETCH_HEAD")
await updateme_requirements()
await eod(
pagal,
"`Successfully Updated!\nBot is restarting... Wait for a second!`",
await eor(
e,
f'<code>Your BOT is </code><strong>up-to-date</strong><code> with </code><strong><a href="https://github.com/TeamUltroid/Ultroid/tree/{branch}">[{branch}]</a></strong>',
parse_mode="html",
link_preview=False,
)
# Spin a new instance of bot
execl(sys.executable, sys.executable, "-m", "pyUltroid")
return
@callback("updtavail")
@owner
async def updava(event):
await event.delete()
await updater()
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

137
plugins/usage.py Normal file
View File

@@ -0,0 +1,137 @@
"""
✘ Commands Available
• `{i}usage`
Get overall usage.
• `{i}usage heroku`
Get heroku stats.
• `{i}usage redis`
Get redis usage.
"""
import math
import shutil
import heroku3
import psutil
import requests
from search_engine_parser.core.utils import get_rand_user_agent as grua
from . import *
HEROKU_API = None
HEROKU_APP_NAME = None
try:
if Var.HEROKU_API and Var.HEROKU_APP_NAME:
HEROKU_API = Var.HEROKU_API
HEROKU_APP_NAME = Var.HEROKU_APP_NAME
Heroku = heroku3.from_key(Var.HEROKU_API)
app = Heroku.app(Var.HEROKU_APP_NAME)
except BaseException:
HEROKU_API = None
HEROKU_APP_NAME = None
@ultroid_cmd(pattern="usage")
async def usage_finder(event):
x = await eor(event, get_string("com_1"))
try:
opt = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await x.edit(get_full_usage())
if opt == "redis":
return await x.edit(redis_usage())
elif opt == "heroku":
is_hk, hk = heroku_usage()
await x.edit(hk)
else:
await eor(x, "`The what?`", time=5)
def heroku_usage():
if HEROKU_API is None and HEROKU_APP_NAME is None:
return False, "You do not use heroku, bruh!"
useragent = grua()
user_id = Heroku.account().id
headers = {
"User-Agent": useragent,
"Authorization": f"Bearer {Var.HEROKU_API}",
"Accept": "application/vnd.heroku+json; version=3.account-quotas",
}
her_url = f"https://api.heroku.com/accounts/{user_id}/actions/get-quota"
r = requests.get(her_url, headers=headers)
if r.status_code != 200:
return (
True,
f"**ERROR**\n`{r.reason}`",
)
result = r.json()
quota = result["account_quota"]
quota_used = result["quota_used"]
remaining_quota = quota - quota_used
percentage = math.floor(remaining_quota / quota * 100)
minutes_remaining = remaining_quota / 60
hours = math.floor(minutes_remaining / 60)
minutes = math.floor(minutes_remaining % 60)
App = result["apps"]
try:
App[0]["quota_used"]
except IndexError:
AppQuotaUsed = 0
AppPercentage = 0
else:
AppQuotaUsed = App[0]["quota_used"] / 60
AppPercentage = math.floor(App[0]["quota_used"] * 100 / quota)
AppHours = math.floor(AppQuotaUsed / 60)
AppMinutes = math.floor(AppQuotaUsed % 60)
total, used, free = shutil.disk_usage(".")
cpuUsage = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
disk = psutil.disk_usage("/").percent
upload = humanbytes(psutil.net_io_counters().bytes_sent)
down = humanbytes(psutil.net_io_counters().bytes_recv)
TOTAL = humanbytes(total)
USED = humanbytes(used)
FREE = humanbytes(free)
return True, get_string("usage").format(
Var.HEROKU_APP_NAME,
AppHours,
AppMinutes,
AppPercentage,
hours,
minutes,
percentage,
TOTAL,
USED,
FREE,
upload,
down,
cpuUsage,
memory,
disk,
)
def redis_usage():
x = 30 * 1024 * 1024
z = 0
for n in udB.keys():
z += udB.memory_usage(n)
a = humanbytes(z) + "/" + humanbytes(x)
b = str(round(z / x * 100, 3)) + "%"
return f"**REDIS**\n\n**Storage Used**: {a}\n**Usage percentage**: {b}"
def get_full_usage():
is_hk, hk = heroku_usage()
if is_hk is False:
her = ""
else:
her = hk
rd = redis_usage()
msg = her + "\n\n" + rd
return msg

View File

@@ -64,10 +64,13 @@ import pytz
import requests
from telegraph import Telegraph
from telegraph import upload_file as uf
from telethon import functions
from telethon.events import NewMessage
from telethon.tl.custom import Dialog
from telethon.tl.functions.channels import LeaveChannelRequest, InviteToChannelRequest
from telethon.tl.functions.channels import (
GetAdminedPublicChannelsRequest,
InviteToChannelRequest,
LeaveChannelRequest,
)
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.functions.photos import GetUserPhotosRequest
from telethon.tl.types import Channel, Chat, InputMediaPoll, Poll, PollAnswer, User
@@ -84,13 +87,8 @@ telegraph.create_account(short_name="Ultroid")
# ================================================================#
@ultroid_cmd(
pattern="kickme$",
groups_only=True,
)
@ultroid_cmd(pattern="kickme$", groups_only=True, allow_sudo=False)
async def leave(ult):
if ult.sender_id != ultroid_bot.uid:
return
await eor(ult, f"`{ultroid_bot.me.first_name} has left this group, bye!!.`")
await ultroid_bot(LeaveChannelRequest(ult.chat_id))
@@ -178,7 +176,9 @@ async def info(event):
pattern="listreserved$",
)
async def _(event):
result = await ultroid_bot(functions.channels.GetAdminedPublicChannelsRequest())
if BOT_MODE:
return await eor(ult, "You Cant Use this Command in BOT MODE")
result = await ultroid_bot(GetAdminedPublicChannelsRequest())
output_str = ""
r = result.chats
for channel_obj in r:
@@ -195,6 +195,8 @@ async def _(event):
async def stats(
event: NewMessage.Event,
) -> None:
if BOT_MODE:
return await eor(ult, "You Cant Use this Command in BOT_MODE")
ok = await eor(event, "`Collecting stats...`")
start_time = time.time()
private_chats = 0
@@ -313,7 +315,7 @@ async def _(event):
q = f"paste-{key}"
reply_text = f"• **Pasted to Nekobin :** [Neko](https://nekobin.com/{key})\n• **Raw Url :** : [Raw](https://nekobin.com/raw/{key})"
try:
ok = await ultroid_bot.inline_query(Var.BOT_USERNAME, q)
ok = await ultroid_bot.inline_query(asst.me.username, q)
await ok[0].click(event.chat_id, reply_to=event.reply_to_msg_id, hide_via=True)
await xx.delete()
except BaseException:
@@ -404,6 +406,8 @@ async def _(event):
groups_only=True,
)
async def _(ult):
if BOT_MODE:
return await eor(ult, "You Cant Use this Command in BOT_MODE")
xx = await eor(ult, get_string("com_1"))
to_add_users = ult.pattern_match.group(1)
if not ult.is_channel and ult.is_group:

90
plugins/variables.py Normal file
View File

@@ -0,0 +1,90 @@
"""
✘ Commands Available -
• `{i}get var <variable name>`
Get value of the given variable name.
• `{i}get type <variable name>`
Get variable type.
• `{i}get redis <key>`
Get redis value of the given key.
• `{i}get keys`
Get all redis keys.
"""
import os
from . import *
@ultroid_cmd(pattern="get")
async def get_var(event):
x = await eor(event, get_string("com_1"))
if not event.out and not is_fullsudo(event.sender_id):
return await eod(event, "`This Command Is Sudo Restricted.`")
try:
opt = event.text.split(" ", maxsplit=2)[1]
except IndexError:
return await x.edit("get what?")
if not opt == "keys":
try:
varname = event.text.split(" ", maxsplit=2)[2]
except IndexError:
return await eod(x, "Such a var doesn't exist!", time=5)
if opt == "var":
c = 0
# try redis
val = udB.get(varname)
if val is not None:
c += 1
return await x.edit(
f"**Variable** - `{varname}`\n**Value**: `{val}`\n**Type**: Redis Key."
)
# try env vars
val = os.getenv(varname)
if val is not None:
c += 1
return await x.edit(
f"**Variable** - `{varname}`\n**Value**: `{val}`\n**Type**: Env Var."
)
if c == 0:
return await eod(x, "Such a var doesn't exist!", time=5)
elif opt == "type":
c = 0
# try redis
val = udB.get(varname)
if val is not None:
c += 1
return await x.edit(f"**Variable** - `{varname}`\n**Type**: Redis Key.")
# try env vars
val = os.getenv(varname)
if val is not None:
c += 1
return await x.edit(f"**Variable** - `{varname}`\n**Type**: Env Var.")
if c == 0:
return await eod(x, "Such a var doesn't exist!", time=5)
elif opt == "redis":
val = udB.get(varname)
if val is not None:
return await x.edit(f"**Key** - `{varname}`\n**Value**: `{val}`")
else:
return await eod(x, "No such key!", time=5)
elif opt == "keys":
keys = sorted(udB.keys())
msg = ""
for i in keys:
if i.isdigit() or i.startswith("-") or i.startswith("GBAN_REASON_"):
pass
else:
msg += f"• `{i}`" + "\n"
await x.edit(f"**List of Redis Keys :**\n{msg}")
HELP.update({f"{__name__.split('.')[1]}": f"{__doc__.format(i=HNDLR)}"})

View File

@@ -53,7 +53,7 @@ async def _(event):
return await eod(xx, "`Reply to media file`", time=5)
try:
results = await ultroid_bot.inline_query(
Var.BOT_USERNAME,
asst.me.username,
f"fl2lnk {file_name}",
)
except rep:

View File

@@ -1,9 +1 @@
py-Ultroid==2021.4.16
gingerit
Telethon==1.21.1
git+https://github.com/buddhhu/search-engine-parser.git
git+https://github.com/buddhhu/ofox.git
git+https://github.com/ProgrammingError/rextester_py.git
google-assistant-grpc
tenacity
google-assistant-sdk
py-Ultroid==2021.5.8

View File

@@ -9,6 +9,7 @@ google-api-python-client==1.7.11
googletrans==3.1.0a0
heroku3
httplib2==0.13.1
html-telegraph-poster
lottie
moviepy
numpy

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

View File

@@ -88,7 +88,7 @@ def start():
clear_screen()
print("\nCongrats. All done!\nTime to start the bot!")
print("\nInstalling requirements... This might take a while...")
os.system("pip3 install -r ./resources/extras/local-requirements.txt")
os.system("pip3 install -r resources/extras/local-requirements.txt")
clear_screen()
print(a)
print("\nStarting Ultroid...")

24
src/ecmaHelper/eval.d.js Normal file
View File

@@ -0,0 +1,24 @@
// Ultroid - UserBot
// Copyright (C) 2020 TeamUltroid
//
// This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
// PLease read the GNU Affero General Public License in
// <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
const { exec } = require('child_process');
const { appendFileSync, truncate } = require('fs');
(async () => {
truncate('./src/ecmaHelper/evalJs.result.d.txt', 0, function() {
console.log('Result File Truncated')
const evalJs = exec('node ./src/ecmaHelper/evalJs.run.js');
evalJs.stdout.on('data', (data) => {
appendFileSync('./src/ecmaHelper/evalJs.result.d.txt', `${data.toString()}\n`, () => {});
});
evalJs.stderr.on('data', (error) => {
appendFileSync('./src/ecmaHelper/evalJs.result.d.txt', `${error}\n`, () => {});
});
});
})();

View File

@@ -0,0 +1 @@
'use-strict';

View File

@@ -0,0 +1 @@
'use-strict';

View File

@@ -0,0 +1,9 @@
// Ultroid - UserBot
// Copyright (C) 2020 TeamUltroid
//
// This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
// PLease read the GNU Affero General Public License in
// <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
'use-strict';
sgrywryhio

View File

@@ -36,7 +36,10 @@ export const songHandler = Composer.command('current', async ctx => {
...Markup.inlineKeyboard([
[
Markup.button.callback('Pause', `pause:${id}`),
Markup.button.callback('Skip', `skip:${id}`)
Markup.button.callback('Skip', `skip:${id}`),
],
[
Markup.button.callback('Exit', `exitVc`),
]
])
})

4
src/handlers/excape.html.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
declare module 'escapeHtml' {
const escapeHtml: (html: string) => string;
export default escapeHtml;
}

41
src/handlers/exitVc.ts Normal file
View File

@@ -0,0 +1,41 @@
/**
* Ultroid - UserBot
* Copyright (C) 2020 TeamUltroid
*
* This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
* PLease read the GNU Affero General Public License in
* <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
**/
import { Composer } from 'telegraf';
import { closeConnection, leaveVc } from '../tgcalls';
export const exitVcHandler = Composer.action('exitVc', async ctx => {
const chat = ctx.callbackQuery.message?.chat;
if (!chat) {
await ctx.answerCbQuery("Invalid Request");
return false;
}
if (chat.type !== 'supergroup') {
await ctx.answerCbQuery("Invalid Request");
return false;
}
closeConnection();
leaveVc(chat.id);
await ctx.answerCbQuery("Leaving Voicechat");
})
export const exitCommand = Composer.command('exitVc', async ctx => {
const { chat } = ctx.message;
if (chat.type !== 'supergroup') {
return;
}
closeConnection();
leaveVc(chat.id);
await ctx.reply("Left Voice Chat.");
})

View File

@@ -14,6 +14,7 @@ import { queueHandler } from './queue';
import { pauseCBHandler } from './pause-resume';
import { skipCBHandler, skipCommand } from './skip';
import { songHandler } from './current';
import { exitVcHandler, exitCommand } from './exitVc';
export const initHandlers = (): void => {
bot.use(playHandler);
@@ -22,4 +23,6 @@ export const initHandlers = (): void => {
bot.use(skipCBHandler);
bot.use(skipCommand);
bot.use(songHandler);
bot.use(exitVcHandler);
bot.use(exitCommand);
};

View File

@@ -43,6 +43,9 @@ export const pauseCBHandler = Composer.action(/^pause:[a-zA-Z0-9.\-_]+$/, checkE
[
Markup.button.callback('Resume', `pause:${id}`),
Markup.button.callback('Skip', `skip${id}`)
],
[
Markup.button.callback('Exit', `exitVc`),
]
])
});
@@ -57,6 +60,9 @@ export const pauseCBHandler = Composer.action(/^pause:[a-zA-Z0-9.\-_]+$/, checkE
[
Markup.button.callback('Pause', `pause:${id}`),
Markup.button.callback('Skip', `skip:${id}`)
],
[
Markup.button.callback('Exit', `exitVc`),
]
])
});

View File

@@ -18,16 +18,14 @@ export const playHandler = Composer.command('play', async ctx => {
const { chat } = ctx.message;
if (chat.type !== 'supergroup') {
await ctx.reply('I can only play in groups.');
return;
return await ctx.reply('I can only play in groups.');
}
const [commandEntity] = ctx.message.entities!;
const [ commandEntity ] = ctx.message.entities!;
const text = ctx.message.text.slice(commandEntity.length + 1) || deunionize(ctx.message.reply_to_message)?.text;
if (!text) {
await ctx.reply('You need to specify a YouTube URL / Search Keyword.');
return;
return await ctx.reply('You need to specify a YouTube URL / Search Keyword.');
}
const index = await addToQueue(chat, text, {
@@ -52,6 +50,9 @@ export const playHandler = Composer.command('play', async ctx => {
[
Markup.button.callback('Pause', `pause:${id}`),
Markup.button.callback('Skip', `skip:${id}`)
],
[
Markup.button.callback('Exit', `exitVc`),
]
])
})
@@ -66,9 +67,6 @@ export const playHandler = Composer.command('play', async ctx => {
`<b>At position ${index}.</b>\n` +
`<b>Requested By :</b> <a href="tg://user?id=${from.id}">${from.f_name}</a>`, {
disable_web_page_preview: true,
// ...Markup.inlineKeyboard([
// [Markup.button.callback('Delete from Queue', `delq:${queueId}`)]
// ])
});
} else {
await log("Queue not found in " + chat.title)

View File

@@ -8,7 +8,7 @@
**/
import { Composer } from 'telegraf';
import { getQueue } from '../tgcalls';
import { getQueue, leaveVc, getCurrentSong, closeConnection } from '../tgcalls';
import escapeHtml from '@youtwitface/escape-html';
import { getDuration } from '../utils';
@@ -29,4 +29,10 @@ export const queueHandler = Composer.command('queue', async ctx => {
: 'The queue is empty.';
await ctx.replyWithHTML(message, { disable_web_page_preview: true });
const song = getCurrentSong(chat.id);
if (song === null && queue?.length == 0) {
closeConnection();
leaveVc(chat.id);
}
});

View File

@@ -10,6 +10,7 @@
import { Composer } from 'telegraf';
import { skip } from '../tgcalls';
import checkExpired from '../middlewares/checkExpired';
import { leaveVc } from '../tgcalls';
export const skipCBHandler = Composer.action(/^skip:[a-zA-Z0-9.\-_]+$/, checkExpired, async ctx => {
const chat = ctx.callbackQuery.message?.chat;
@@ -31,6 +32,7 @@ export const skipCBHandler = Composer.action(/^skip:[a-zA-Z0-9.\-_]+$/, checkExp
} else {
await ctx.answerCbQuery("There's no song playing..");
setTimeout(async () => await ctx.deleteMessage(), 1000);
leaveVc(chat.id);
}
})
@@ -43,4 +45,8 @@ export const skipCommand = Composer.command('skip', async ctx => {
const skipped = skip(chat.id);
ctx.reply(skipped ? 'Skipped.' : "There's no song playing.");
if (!skipped) {
leaveVc(chat.id);
}
})

View File

@@ -54,10 +54,10 @@ interface CachedConnection {
const ws = new WebSocket(env.WEBSOCKET_URL);
const cache = new Map<number, CachedConnection>();
var connection: TGCalls<{ chat: Chat.SupergroupChat; }>;
const ffmpegOptions = "-preset ultrafast -c copy -acodec pcm_s16le -f s16le -ac 1 -ar 65000 pipe:1";
ws.on('message', response => {
ws.on('message', (response: any) => {
const { _, data } = JSON.parse(response.toString());
switch (_) {
@@ -68,9 +68,9 @@ ws.on('message', response => {
}
break;
}
// case 'left_vc': {
// break;
// }
case 'left_vc': {
break;
}
default:
break;
}
@@ -116,9 +116,11 @@ export const getSongInfo = async (url: string): Promise<DownloadedSong['info']>
const ytdlChunks: string[] = [];
const ytdl = spawn('youtube-dl', ['-x', '--print-json', '-g', `ytsearch:"${url}"`]);
ytdl.stderr.on('data', data => console.error(data.toString()));
ytdl.stderr.on('data', (data) => {
console.error(data.toString())
});
ytdl.stdout.on('data', data => {
ytdl.stdout.on('data', (data) => {
ytdlChunks.push(data.toString());
});
@@ -140,12 +142,16 @@ export const getSongInfo = async (url: string): Promise<DownloadedSong['info']>
});
};
const createConnection = async (chat: Chat.SupergroupChat): Promise<void> => {
export const closeConnection = async(): Promise<void> => {
connection.close();
}
const createConnection = async(chat: Chat.SupergroupChat): Promise<void> => {
if (cache.has(chat.id)) {
return;
}
const connection = new TGCalls({ chat });
connection = new TGCalls({ chat });
const stream = new Stream();
const queue: {
url: string,
@@ -164,7 +170,7 @@ const createConnection = async (chat: Chat.SupergroupChat): Promise<void> => {
leftVC: false
};
connection.joinVoiceCall = payload => {
connection.joinVoiceCall = (payload: { source: number | undefined; ufrag: any; pwd: any; hash: any; setup: any; fingerprint: any; params: { chat: any; }; }) => {
cachedConnection.source = payload.source;
return new Promise(resolve => {
cachedConnection.joinResolve = resolve;
@@ -208,7 +214,10 @@ const createConnection = async (chat: Chat.SupergroupChat): Promise<void> => {
...Markup.inlineKeyboard([
[
Markup.button.callback('Pause', `pause:${id}`),
Markup.button.callback('Skip', `skip:${id}`)
Markup.button.callback('Skip', `skip:${id}`),
],
[
Markup.button.callback('Exit', `exitVc`),
]
])
})
@@ -241,9 +250,16 @@ const createConnection = async (chat: Chat.SupergroupChat): Promise<void> => {
export const leaveVc = (chatId: number) => {
if (cache.has(chatId)) {
const { stream } = cache.get(chatId)!;
stream.emit('leave');
try {
stream.emit('leave');
} catch (error) {
console.log(error.toString());
stream.emit('leave');
}
process.exit(0);
} else {
return false;
}
return false;
}
export const addToQueue = async (chat: Chat.SupergroupChat, url: string, by: Queue['from']): Promise<number | null> => {
@@ -300,7 +316,7 @@ export const getQueue = (chatId: number): Queue[] | null => {
const { queue } = cache.get(chatId)!;
return Array.from(queue);
}
return null;
return [];
};
export const removeQueue = (chatId: number, id: number): boolean => {

View File

@@ -14,7 +14,6 @@ com_2: "`Searching...`"
help_1: "`{}` is not a valid plugin!"
help_2: "The bot did not respond to the inline query.\nConsider using `{}restart`"
help_3: "`Please turn on inline mode for your bot from` @Botfather."
help_4: "Hey, \nYou are on Bot Mode. \nBot Mode Users Cant Get Help Directly ... \nInstead Copy Paste The Following in The Chat and Click The Pop Up \n\n `@{} ultd`"
# autopic
autopic_1: "Heya Give me some Text .."
@@ -31,7 +30,7 @@ Aᴅᴅɴs ~ {}**"
inline_3: "[Uʟᴛʀɪᴅ Sᴘᴘʀᴛ](t.me/ultroidsupport)\n\n
**Hᴇʟᴘ Mᴇɴ Oғ {}.\n\n
Aᴅᴅɴs ~ {}\n\n
G Aɴᴅ Aᴅᴅ `ADDONS` Vᴀʀ Wɪᴛʜ Vᴀʟᴇ Tʀ**"
D **`.setredis ADDONS True`** ᴀɴᴅ ʀᴇsᴛᴀʀᴛ ᴛᴏ ɢᴇᴛ ᴀᴅᴅɴs.**"
inline_4: "** Bᴛ Oғ {}\n\nMᴀɪɴ Mᴇɴ\n\nPʟɢɪɴs ~ {}\nAᴅᴅɴs ~ {}\nTᴛᴀʟ Cᴍᴍᴀɴᴅs ~ {}**"
inline_5: "**Mᴇɴ Hᴀs Bᴇᴇɴ Cʟsᴇᴅ**"
@@ -75,16 +74,19 @@ alive_1: "**The Ultroid Userbot...**\n\n
log: "**Heroku** Ultroid Logs.\nPasted [here]({}) too!"
ping: "**Pong !!** `{}ms`\n**Uptime** - `{}`"
usage: "**⚙️ Dyno Usage ⚙️**:\n\n
-> `Dyno usage for` **{}**:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
-> `Dyno hours quota remaining this month`:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
**Total Disk Space: {}\n\n**
**Used: {} Free: {}\n\n**
**📊Data Usage📊\n\nUpload: {}\nDown: {}\n\n**
**CPU: {}%\nRAM: {}%\nDISK: {}%**"
-> **Dyno usage for** `{}`:\n
• **{}h** **{}m** |** `[{}%]`\n
-> **Dyno hours quota remaining this month**:\n
• **{}h** **{}m |** `[{}%]`\n\n
**Total Disk Space**: `{}`\n
**Used**: `{}`\n
**Free**: `{}`\n\n
**📊 Data Usage 📊\n
**Upload**: `{}`\n
**Down**: `{}`\n\n
**CPU**: `{}%`\n
**RAM**: `{}%`\n
**DISK**: `{}%`"
shutdown: "GoodBye {}.\n`Shutting down...`"
# broadcast
@@ -176,8 +178,8 @@ upd_1: "`Checking for updates, please wait....`"
upd_2: "`Oops.. Updater cannot continue due to some problems.`\n\n**LOGTRACE:**\n"
upd_3: "**New UPDATE available for [[{}]]({}/tree/{}):\n\nCHANGELOG**\n\n{}"
upd_4: "`Changelog is too big, view the file to see it.`"
upd_5: "Use `{}update now` to update."
upd_6: "{}\n\nUse `{}update now` to update."
upd_5: "Click the below button to update."
upd_6: "Click the below button to update."
upd_7: "\n`Your BOT is` **up-to-date** `with` **[[{}]]({}/tree/{})**\n"
# upload download

194
strings/strings/hi.yml Normal file
View File

@@ -0,0 +1,194 @@
name: Hindi
natively: हिंदी
authors:
- New-dev0
# commons
com_1: "`प्रक्रिया शुरू...`"
com_2: "`खोज शुरू...`"
# help
help_1: "`{}` वैध प्लगइन नहीं है!"
help_2: "बॉट ने इनलाइन क्वेरी का जवाब नहीं दिया.\n`{}restart` कमांड का प्रयास करें !"
help_3: "`कृपया अपने बॉट के लिए इनलाइन मोड चालू करें` @Botfather से."
# autopic
autopic_1: "मुझे कुछ पाठ प्रदान करो..."
autopic_2: "`{}` के लिए कोई परिणाम नहीं मिले"
autopic_3: "`{}` के लिए परिणाम मिले आपकी खोज से संबंधित !\nऑटोपिक शुरू करा गया !"
# inline
inline_1: "[उल्ट्रॉइड सपोर्ट](t.me/ultroidsupport)\n\n
**{} का मदद मेनू.\n\n
प्लग-इन ~ {}**"
inline_2: "[उल्ट्रॉइड सपोर्ट](t.me/ultroidsupport)\n\n
**{} का मदद मेनू.\n\n
एडऑन ~ {}**"
inline_3: "[उल्ट्रॉइड सपोर्ट](t.me/ultroidsupport)\n\n
**{} का मदद मेनू.\n\n
एडऑन ~ {}\n\n
जाओ और जोड़ो `ADDONS` Vᴀʀ Tʀᴇ मूल्य के साथ !**"
inline_4: "**{} का बॉट\n\nमुख्य मेन्यू\n\nप्लग-इन ~ {}\nएडऑन ~ {}\nकुल आदेश ~ {}**"
inline_5: "**मेनू बंद कर दिया गया है !**"
# tagnotif
tagnot_1: "{} में आपको टैग किया हैं {} में\n\n```{}```\n\n[📨 Message 📨]({})"
tagnot_2: "{} में आपको टैग किया हैं {} में\n\n [📨 Message 📨]({})"
# whisper
wspr_1: "@{} आपके लिए गुप्त संदेश.\nपढ़ने के बाद अपना संदेश हटाएं.\nया अगला संदेश अपडेट नहीं किया जाएगा."
wspr_2: "संदेश हटाया गया !"
# afk
afk_1: "`अब नहीं रहा Afk\n\n
दूर था ~ {}`"
afk_2: "#AFK\n
AFK मोड फालस किया गया.\n
दूर था `{}`"
afk_3: "`मैं अभी AFK हु.\n
अंतिम बार देखा गया {} पहले.`\n\n
**कारण:** `{}`"
afk_4: "`मैं अभी AFK हु.\n\n
अंतिम बार देखा गया {} पहले.`"
afk_5: "`AFK जा रहा.`\n\n
**कारण:** `{}`"
afk_6: "मैं अभी AFK जा रहा.."
afk_7: "मैं अभी AFK हु. कारण - {}"
afk_8: "मैं अभी AFK हु."
# bot
alive_1: "**उल्ट्रॉइड उपयोगकर्ता बॉट...**\n\n
**{}**\n\n
┏━━━━━━━━━━━━━━━━━━━━━\n
┣ **मालिक** - `{}`\n
┣ **संस्करण** - `{}`\n
┣ **पाय-उल्ट्रॉइड** - `{}`\n
┣ **सक्रिय अवधि** - `{}`\n
┣ **पाइथन** - `{}`\n
┣ **टेलीथोन** - `{}`\n
┣ **ब्रा-च** - `{}`\n
┗━━━━━━━━━━━━━━━━━━━━━"
log: "**हिरोकू** उल्ट्रॉइड लॉग.\n चिपकाया गया [यहाँ]({}) too!"
ping: "**पओंग !!** `{}ms`\n**सक्रिय अवधि** - `{}`"
usage: "**⚙️ दायनो उपयोग ⚙️**:\n\n
-> `दायनो उपयोग ` **{}** के लिये:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
-> `दायनो इस महीने में घंटों कोटा शेष है`:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
**कुल डिस्क स्थान: {}\n\n**
**उपयुक्त: {} खली: {}\n\n**
**📊डेटा उपयोग📊\n\nडालना: {}\nडाउनलोड: {}\n\n**
**CPU: {}%\nRAM: {}%\nDISK: {}%**"
shutdown: "अलविदा {}.\n`बंद करा जरा हैं...`"
# broadcast
bd_1: "`db में जोड़ना...`"
bd_2: "`Db में सभी एडमिन चैनल जोड़ने की कोशिश कर रहा है...`"
bd_3: "**किया गया.**\nडेटाबेस में पहले से ही चैट हैं: {}\nनयी जोड़ी गयी: {}"
bd_4: "चैनल जोड़े गए!"
bd_5: "`डेटाबेस में जोड़ा गया!`"
bd_6: "`चैनल पहले से ही डेटाबेस में है!`"
# carbon
carbon_1: "प्रक्रिया शुरू..."
carbon_2: "[{}](tg://user?id={}) द्वारा कार्बोनेटेड !"
# chats
chats_1: "`प्रक्रिया शुरू......`"
chats_2: "`इस चैट को हटा नहीं सकते`"
chats_3: "`मैं एडमिन नहीं हूं`"
chats_4: "#Deleted\nहटाए गए {}"
chats_5: "आपका [{}]({}) समूह बान गया!"
chats_6: "जूदो @TeamUltroid"
# converter
cvt_1: "किसी भी मीडिया / दस्तावेज़ को जवाब दें."
cvt_2: "फ़ाइल का नाम और विस्तार दें !"
cvt_3: "`प्रक्रिया शुरू...`"
cvt_4: "किसी भी मीडिया को जवाब दें.."
# core
core_1: "मॉड्यूल मिला"
core_2: "{}.py .paste का प्रयोग करें पेस्ट करने के लिए neko और raw में.."
core_3: "फिर से खोजो..?"
core_4: "मॉड्यूल {} मिला"
core_5: "{}.py .paste का प्रयोग करें पेस्ट करने के लिए neko और raw में...."
core_6: "मॉड्यूल {}.py नहीं मिला"
core_7: "ऐसा कोई मॉड्यूल नहीं"
core_8: "कोई मॉड्यूल नहीं {}.py नाम का"
core_9: "`प्लगइन का नाम दें जिसे आप अनलोड करना चाहते हैं`"
core_10: "`{}` का **अनलोड सफल हुआ.**"
core_11: "**आप आधिकारिक प्लगइन्स को अनलोड नहीं कर सकते**"
core_12: "*कोई प्लगइन ** `{}` नाम का नहीं"
core_13: "`प्लगइन का नाम दें जिसे आप अनइंस्टॉल करना चाहते हैं`"
core_14: "**अनइंस्टॉल** `{}` **सफलतापूर्वक.**"
core_15: "**आप आधिकारिक प्लगइन्स को अनइंस्टॉल नहीं कर सकते**"
core_16: "`प्लगइन का नाम दें जिसे आप लोड करना चाहते हैं`"
core_17: "**सफलतापूर्वक** `{}` लोड हुआ गया !"
core_18: "**लोड नहीं हो सका** `{}` **निम्नलिखित त्रुटि के कारण.**\n`{}`"
# fedutils
sf_1: "मास-फेडबन शुरू करा गया..."
sf_2: "`कोई उपयोगकर्ता निर्दिष्ट नहीं है!`"
sf_3: "आप मेरे निर्माता पर प्रतिबंध नहीं लगा सकते!!"
sf_4: "`Rose जवाब नहीं दे रही है, या, प्लगइन दुर्व्यवहार कर रहा है`"
sf_5: "आप हर 5 मिनट में केवल एक बार फीड कमांड का उपयोग कर सकते हैं"
sf_6: "5 मिनट के बाद फिर से प्रयास करें."
sf_7: "FedAdminList एकत्र करने में असमर्थ. पुन: प्रयास ({}/3)..."
sf_8: "त्रुटि"
sf_9: "FedAdminList एकत्र करने में असमर्थ."
sf_10: "FBaning {} feds."
sf_11: "निर्दिष्ट Fban ग्रुप आईडी गलत है."
sf_12: "{} निकाले गए."
sf_13: "FedAdmin फ़ाइल निकालने में त्रुटि.\n{}"
sf_14: सुपरफेडबैन पूरा हुआ".\nकुल फेड - {}.\nनिकाले गए - {}.\n सफ़लता {} फेड."
sf_15: "मास-अनफेडबैन शुरू करा गया..."
sf_16: "सुपर-अनफेडबैन पूरा हुआ.\nकुल फेड - {}.\nनिकाले गए - {}.\n सफ़लता {} फेड."
sf_17: "`मुझे किसी को आईडी दें, या किसी को संदेश की जांच के लिए उत्तर दें. फ़ेडस्टैट्स प्राप्त करने के लिए`"
sf_18: "फेड की सूची {} में प्रतिबंधित कर दिया गया है.\n\nउल्ट्रॉइड के द्वारा प्राप्त किया गया."
sf_19: "**त्रुटि**\n `अनब्लॉक `@MissRose_Bot`और फिर प्रयत्न करें!"
sf_20: "`जानकारी निकाला जा रहा हैं...`"
sf_21: "\n\nFedInfo उल्ट्रॉइड द्वारा प्राप्त किया गया."
# gdrive
gdrive_1: "`आपने पहले ही Google डिस्क के साथ अधिकृत कर लिया है`"
gdrive_2: "[यहाँ जाये](https://console.developers.google.com/flows/enableapi?apiid=drive) और अपना `GDRIVE_CLIENT_ID` and `GDRIVE_CLIENT_SECRET`\n\n
अपना GDRIVE_CLIENT_ID और GDRIVE_CLIENT_SECRET भेजो.\n`GDRIVE_CLIENT_ID GDRIVE_CLIENT_SECRET` space( ) से अलग."
gdrive_3: "`गलत ग्राहक(Client) आईडी`"
gdrive_4: "`कुछ गलत हो गया! फेर से `/auth` भजे.\nअगर ऐसा ही होता है संपर्क - `@TheUltroid"
gdrive_5: "`सफलता !\nआप Google Drive उपयोग करने के लिए पूरी तरह तैयार हैं. उल्ट्रॉइड उपयोगकर्ता बॉट के साथ.`"
gdrive_6: "`यहाँ जाये `{}` और ``/auth.` भेज दें`"
gdrive_7: "**सफलतापूर्वक अपलोड की गई फ़ाइल G-Drive पर:**\n\n[{}]({})"
# pmpermit
pmperm_1: "कृपया मेरे जवाब के लिए प्रतीक्षा करें या आपको अवरुद्ध और स्पैम के रूप में रिपोर्ट किया जाएगा !"
pmperm_2: "आप मेरे मास्टर के पीएम पर स्पैम कर रहे थे, जो मुझे अच्छा नहीं लगा.\nआपको अगली सूचना तक ब्लॉक किया गया है और SPAM के रूप में रिपोर्ट किया गया है."
pmperm_3: "किसी के संदेश का जवाब दें या इस आदेश को private chat में आज़माएं।"
# updater
upd_1: "`अपडेट की जाँच, कृपया प्रतीक्षा करें....`"
upd_2: "`ओह .. अपडेटर कुछ समस्याओं के कारण जारी नहीं रह सकता.`\n\n**उपदेश:**\n"
upd_3: "**[[{}]]({}/tree/{}) के लिए नया अपडेट उपलब्ध है :\n\nबदलाव :**\n\n{}"
upd_4: "`चैंज बहुत बड़ा है, इसे देखने के लिए फ़ाइल देखें.`"
upd_5: "अपडेट करने के लिए `{}update now` का प्रयोग करे"
upd_6: "{}\n\nअपडेट करने के लिए `{}update now` का प्रयोग करे"
upd_7: "\n`आपका बॉट` **अपटूडेट है** **[[{}]]({}/tree/{})** `के साथ`\n"
# upload download
udl_1: "`उस फ़ाइल / मीडिया का उत्तर दें जिसे आप डाउनलोड करना चाहते हैं...`"
udl_2: "डाउनलोड सफल..\n\nकिया गया - `{}`\nमें `{}`"
udl_3: "`फ़ाइल करने के लिए एक विशिष्ट पथ दें !`"
# words
wrd_1: "**शब्द** - `{}`\n\n**अर्थ** - \n"
wrd_2: "**शब्द** - `{}`\n\n**समानार्थक शब्द** - \n"
wrd_3: "**शब्द** - `{}`\n\n**विलोम शब्द** - \n"
# ---------------------------------------------------#
# assisant
ast_1: "वह एपीआई (API) चुनें जिसे आप सेट करना चाहते हैं."
ast_2: "**remove.bg एपीआई**\nremove.bg से अपनी एपीआई कुंजी दर्ज करें.\n\nऑपरेशन को समाप्त करने के लिए /cancel उपयोग करें."
ast_3: "नमस्ते {}. कृपया विकल्पों के माध्यम से ब्राउज़ करें"

195
strings/strings/it.yml Normal file
View File

@@ -0,0 +1,195 @@
name: Italian
natively: italiano
authors:
- Simben12
# commons
com_1: "`In lavorazione...`"
com_2: "`Ricerca in corso ...`"
# help
help_1: "`{}` Non è un plugin valido!"
help_2: "Il bot non ha risposto alla query in linea.\nConsidera l'utilizzo `{}restart`"
help_3: "`Attiva la modalità inline per il tuo bot da @ Botfather."
help_4: "Hey, \nSei in modalità Bot. \nGli utenti in modalità Bot non possono ottenere aiuto direttamente...\nInvece, copia e incolla quanto segue nella chat e fai clic sul popup\n\n `@{} ultd`"
# autopic
autopic_1: "Heya dammi un messaggio..."
autopic_2: "Nessun risultato trovato per `{}`"
autopic_3: "Hai una raccolta`{}` correlata alla tua ricerca! \nAvvio di Autopic!"
# inline
inline_1: "[Supporto Ultroid](t.me/ultroidsupport)\n\n
**Menù di aiuto di {}.\n\n
ɢɪɴs ~ {}**"
inline_2: "[Supporto Ultroid](t.me/ultroidsupport)\n\n
**Menù di aiuto di {}.\n\n
Aᴅᴅɴs ~ {}**"
inline_3: "[Supporto Ultroid](t.me/ultroidsupport)\n\n
**Menù di aiuto di {}.\n\n
Aᴅᴅɴs ~ {}\n\n
Vai e aggiungi la variabile ADDONS con valore true**"
inline_4: "** Bot di {}\n\nMᴀɪɴ Mᴇɴ\n\nPʟɢɪɴs ~ {}\nAᴅᴅɴs ~ {}\nComandi Totali~ {}**"
inline_5: "**Menu è stato chiuso**"
# tagnotif
tagnot_1: "{} ti ha taggato in {}\n\n```{}```\n\n[📨 Messaggio 📨]({})"
tagnot_2: "{} ti ha taggato in {}\n\n [📨 Messaggio 📨]({})"
# whisper
wspr_1: "@{} Messaggio segreto per te \nElimina l tuo messaggio dopo averlo letto \nOppure il messaggio successivo non verrà aggiornato."
wspr_2: "Messaggio eliminato"
# afk
afk_1: "`Non più AFK.\n\n
Era via per ~ {}`"
afk_2: "#AFK\n
Imposta la modalità AFK su False.\n
Era AFK per`{}`"
afk_3: "`Attualmente sono AFK.\n
Ultima visualizzazione {} fa \n\n
**Ragione:** `{}`"
afk_4: "`Attualmente sono AFK.\n\n
Ultima visualizzazione {} fa.`"
afk_5: "`Andando AFK.`\n\n
**Ragione:** `{}`"
afk_6: "Sto andando AFK."
afk_7: "Attualmente AFK con ragione {}"
afk_8: "Attualmente AFK."
# bot
alive_1: "**L'Ultroid Userbot...**\n\n
**{}**\n\n
┏━━━━━━━━━━━━━━━━━━━━━\n
┣ **Owner** - `{}`\n
┣ **Version** - `{}`\n
┣ **Py-Ultroid** - `{}`\n
┣ **UpTime** - `{}`\n
┣ **Python** - `{}`\n
┣ **Telethon** - `{}`\n
┣ **Branch** - `{}`\n
┗━━━━━━━━━━━━━━━━━━━━━"
log: "**Heroku** Logs di Ultroid.\nIncollati [qui]({})!"
ping: "**Pong !!** `{}ms`\n**Uptime** - `{}`"
usage: "**⚙️ Utilizzo di Dyno ⚙️**:\n\n
-> `Utilizzo di Dyno per` **{}**:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
-> `Dyno hours quota remaining this month`:\n
• `{}`**h** `{}`**m**
**|** [`{}`**%**]\n\n
**Total Disk Space: {}\n\n**
**Used: {} Free: {}\n\n**
**📊Data Usage📊\n\nUpload: {}\nDown: {}\n\n**
**CPU: {}%\nRAM: {}%\nDISK: {}%**"
shutdown: "Addio {}.\n`Spegnendo...`"
# broadcast
bd_1: "`Aggiungendo a db...`"
bd_2: "`Tentativo di aggiungere tutti i canali di amministrazione a db ...`"
bd_3: "**Fatto.**\nChat già nel database: {}\nAppena aggiunto: {}"
bd_4: "Canali aggiunti!"
bd_5: "`Aggiunto al database!`"
bd_6: "`Questo canale è già nel database!`"
# carbon
carbon_1: "In lavorazione"
carbon_2: "Carbonised by [{}](tg://user?id={})"
# chats
chats_1: "`In lavorazione...`"
chats_2: "`Impossibile eliminare questa chat`"
chats_3: "`Non sono un admin`"
chats_4: "#Deleted\nDeleted {}"
chats_5: "Il tuo [{}]({}) Gruppo fatto capo!"
chats_6: "Entra in @TeamUltroid"
# converter
cvt_1: "Rispondi a qualsiasi media / documento."
cvt_2: "Dare il nome e l'estensione del file"
cvt_3: "`In lavorazione...`"
cvt_4: "Rispondi a qualsiasi media."
# core
core_1: "Modulo Trovato"
core_2: "{}.py use .paste da incollare in neko and raw.."
core_3: "Cercare Ancora..?"
core_4: "Modulo {} Trovato"
core_5: "{}.py use .paste da incollare in neko and raw.."
core_6: "Modulo {}.py Non Trovato"
core_7: "Nessun modulo del genere"
core_8: "Nessun modulo nominato {}.py"
core_9: "`Dai il nome del plugin che vuoi scaricare`"
core_10: "**Disinstallato** `{}` **con successo.**"
core_11: "**Non puoi disinstallare i plugin ufficiali**"
core_12: "**Nessun plugin denominato** `{}`"
core_13: "`Dare il nome del plugin che si desidera disinstallare`"
core_14: "**Disinstallato** `{}` **con successo.**"
core_15: "**Non puoi disinstallare i plugin ufficialis**"
core_16: "`Dai il nome del plugin che vuoi caricare`"
core_17: "**Scaricato con successo** `{}`"
core_18: "**Impossibile caricare** `{}` **a causa del seguente errore.**\n`{}`"
# fedutils
sf_1: "Avvio di un Mass-FedBan..."
sf_2: "`Nessun utente designato!`"
sf_3: "Non puoi mettere al bando il mio dev noob!!"
sf_4: "`Sembra che rose non stia rispondendo o che il plugin si stia comportando male`"
sf_5: "Puoi usare i comandi fed solo una volta ogni 5 minuti"
sf_6: "Riprova dopo 5 minuti."
sf_7: "Impossibile raccogliere FedAdminList. Nuovo tentativo ({}/3)..."
sf_8: "Errore"
sf_9: "Impossibile raccogliere FedAdminList."
sf_10: "FBaning in {} feds."
sf_11: "L'ID gruppo FBan specificato non è corretto."
sf_12: "{} Escluso."
sf_13: "Errore nella rimozione del file FedAdmin.\n{}"
sf_14: "SuperFBan completato.\nFederali totali - {}.\nEsclusi - {}.\n Colpiti {} federali.\n#TB"
sf_15: "Avvio di un Mass-UnFedBan..."
sf_16: "SuperUnFBan Completato.\nFederali totali - {}.\nEsclusi - {}.\n Colpiti {} federali.\n#TB"
sf_17: "`Dammi l'ID di qualcuno o rispondi al messaggio di qualcuno per controllare il suo fedstat.`"
sf_18: "Elenco dei federali {} è stato bannato\n\nRaccolti utilizzando Ultroid."
sf_19: "**Errore**\n `Sblocca` @MissRose_Bot `e riprova ancora!"
sf_20: "`Estrazione di informazioni...`"
sf_21: "\n\nFedInfo estratto da Ultroid"
# gdrive
gdrive_1: "`Hai già autorizzato con Google Drive`"
gdrive_2: "Vai [qui](https://console.developers.google.com/flows/enableapi?apiid=drive) e prendi il tuo `GDRIVE_CLIENT_ID` e `GDRIVE_CLIENT_SECRET`\n\n
Invia il tuo GDRIVE_CLIENT_ID e GDRIVE_CLIENT_SECRET come questo.\n`GDRIVE_CLIENT_ID GDRIVE_CLIENT_SECRET` separati dagli spazi."
gdrive_3: "`Client Id sbagliato`"
gdrive_4: "`Qualcosa è andato storto! Invia `/auth` di nuovo.\nSe lo stesso accade, contatta '@TheUltroid"
gdrive_5: "`Successo!\nSei pronto per utilizzare Google Drive con Ultroid Userbot.`"
gdrive_6: "`Vai a `{}` e invia ``/auth.`"
gdrive_7: "**File caricato con successo su G-Drive:**\n\n[{}]({})"
# pmpermit
pmperm_1: "Per favore aspetta che risponda o verrai bloccato e segnalato come spam!!"
pmperm_2: "Stavi inviando spam al PM del mio Master, cosa che non mi è piaciuta. \ Sei stato BLOCCATO e segnalato come SPAM, fino a nuovo avviso."
pmperm_3: "Rispondi al messaggio di qualcuno o prova questo comando in privato."
# updater
upd_1: "`Controllo aggiornamenti, attendere prego....`"
upd_2: "`Oops.. Il programma di aggiornamento non può continuare a causa di alcuni problemi.`\n\n**LOGTRACE:**\n"
upd_3: "**Nuovo UPDATE disponibile per [[{}]]({}/tree/{}):\n\nCHANGELOG**\n\n{}"
upd_4: "`Il log delle modifiche è troppo grande, visualizza il file per vederlo.`"
upd_5: "Usa `{}update now` per aggiornare."
upd_6: "{}\n\nUsa `{}update now` per aggiornare."
upd_7: "\n`Your BOT is` **up-to-date** `with` **[[{}]]({}/tree/{})**\n"
# upload download
udl_1: "`Rispondi al file / supporto che desideri scaricare...`"
udl_2: "Download riuscito..\nTo\n`{}`\nin `{}`"
udl_3: "`Dare un percorso specifico al file`"
# words
wrd_1: "**Word** - `{}`\n\n**Meanings** - \n"
wrd_2: "**Word** - `{}`\n\n**Synonyms** - \n"
wrd_3: "**Word** - `{}`\n\n**Antonyms** - \n"
# ---------------------------------------------------#
# assisant
ast_1: "Scegli quale API desideri impostare."
ast_2: "**remove.bg API**\nInserisci la tua chiave API da remove.bg.\n\nUsa /cancel per terminare l'operazione."
ast_3: "Ciao {}. Si prega di sfogliare le opzioni"

View File

@@ -14,10 +14,9 @@ from telethon.tl.functions.phone import (
)
from telethon.tl.types import DataJSON
bot = TelegramClient(None, Var.API_ID, Var.API_HASH).start(bot_token=Var.BOT_TOKEN)
if vcbot is not None:
if vcbot:
bot = TelegramClient(None, Var.API_ID, Var.API_HASH).start(bot_token=Var.BOT_TOKEN)
async def get_entity(chat):
try:
@@ -31,9 +30,9 @@ if vcbot:
try:
chat = await get_entity(data["chat"])
except ValueError:
stree = (await vcbot.get_me()).first_name
name = (await vcbot.get_me()).first_name
return await bot.send_message(
data["chat"]["id"], f"`Please add {stree} in this group.`"
data["chat"]["id"], f"Please add `{name}`` in this group."
)
except Exception as ex:
return await bot.send_message(data["chat"]["id"], "`" + str(ex) + "`")
@@ -102,45 +101,39 @@ if vcbot:
},
}
async def leave_vc(data):
await bot.send_message(Var.LOG_CHANNEL, "Received Leave Request")
try:
await get_entity(data["chat"]["id"])
except Exception as ex:
return await bot.send_message(
data["chat"]["id"], "Exception in Get_Entity : `" + str(ex) + "`"
)
try:
full_chat = await vcbot(GetFullChannelRequest(chat))
except Exception as ex:
return await bot.send_message(
async def leave_call(data):
try:
full_chat = await vcbot(
GetFullChannelRequest(
data["chat"]["id"],
"Exception in GetFullChannelRequest `" + str(ex) + "`",
)
try:
call = full_chat.full_chat.call
# call = await vcbot(GetGroupCallRequest(full_chat.full_chat.call))
except BaseException:
call = None
try:
result = await vcbot(
LeaveGroupCallRequest(
call=call,
source=data["source"],
),
)
await bot.send_message(
Var.LOG_CHANNEL,
f"`Left Voice Chat in {(await bot.get_entity(data['chat']['id'])).title}`",
)
except Exception as ex:
return await bot.send_message(
data["chat"]["id"],
"Exception in LeaveGRoupCallRequest: `" + str(ex) + "`",
)
return {"_": "left_vc", "data": {"chat_id": data["chat"]["id"]}}
)
except Exception as ex:
return await bot.send_message(
data["chat"]["id"],
"Exception in GetFullChannelRequest ```" + str(ex) + "```",
)
try:
call = full_chat.full_chat.call
except BaseException:
call = None
try:
await vcbot(
LeaveGroupCallRequest(
call=call,
source=data["source"],
),
)
await bot.send_message(
Var.LOG_CHANNEL,
f"Left Voice Chat in `{data['chat']['title']}`",
)
except Exception as ex:
return await bot.send_message(
data["chat"]["id"],
"Exception in LeaveGroupCallRequest: `" + str(ex) + "`",
)
return {"_": "left_vc", "data": {"chat_id": data["chat"]["id"]}}
async def websocket_handler(request):
ws = web.WebSocketResponse()
@@ -158,8 +151,16 @@ if vcbot:
if data["_"] == "join":
response = await join_call(data["data"])
# if data["_"] == "leave":
# response = await leave_vc(data["data"])
if data["_"] == "leave":
await bot.send_message(
Var.LOG_CHANNEL,
f"Received **Leave Request** In `{data['data']['chat']['title']}`",
)
await bot.send_message(
data["data"]["chat"]["id"],
f"Received **Leave Request** In `{data['data']['chat']['title']}`",
)
response = await leave_call(data["data"])
if response is not None:
await ws.send_json(response)