format: auto-format code by ruff.
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
@@ -37,6 +37,7 @@ GDrive = GDriveManager() if GDriveManager else None
|
||||
uploader = CatboxUploader()
|
||||
# --------------------------------------------------------------------#
|
||||
|
||||
|
||||
def text_to_url(event):
|
||||
"""function to get media url (with|without) Webpage"""
|
||||
if isinstance(event.media, MessageMediaWebPage):
|
||||
@@ -325,6 +326,7 @@ async def update(eve):
|
||||
await bash("pip3 install -r requirements.txt --break-system-packages")
|
||||
execl(sys.executable, sys.executable, "-m", "pyUltroid")
|
||||
|
||||
|
||||
@callback(re.compile("changes(.*)"), owner=True)
|
||||
async def changes(okk):
|
||||
match = okk.data_match.group(1).decode("utf-8")
|
||||
@@ -559,7 +561,9 @@ async def emoji(event):
|
||||
var = "EMOJI_IN_HELP"
|
||||
name = f"Emoji in `{HNDLR}help` menu"
|
||||
async with event.client.conversation(pru) as conv:
|
||||
await conv.send_message("Send emoji u want to set 🙃.\n\nUse /cancel to cancel.")
|
||||
await conv.send_message(
|
||||
"Send emoji u want to set 🙃.\n\nUse /cancel to cancel."
|
||||
)
|
||||
response = conv.wait_event(events.NewMessage(chats=pru))
|
||||
response = await response
|
||||
themssg = response.message.message
|
||||
|
||||
@@ -37,6 +37,7 @@ aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg"
|
||||
|
||||
akipyLOGS = getLogger("akipy")
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="akinator")
|
||||
async def akina(e):
|
||||
sta = Akinator()
|
||||
@@ -108,7 +109,10 @@ async def okah(e):
|
||||
# Game is not won yet, continue asking questions
|
||||
buttons = [
|
||||
[Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]],
|
||||
[Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]],
|
||||
[
|
||||
Button.inline(o, f"aka_{ch}_{mid}_{o}")
|
||||
for o in ["Probably", "Probably Not"]
|
||||
],
|
||||
]
|
||||
await e.edit(gm.question, buttons=buttons)
|
||||
|
||||
@@ -140,6 +144,7 @@ async def eiagx(e):
|
||||
|
||||
GIMAGE = "https://graph.org/file/1c51015bae5205a65fd69.jpg"
|
||||
|
||||
|
||||
@asst_cmd(pattern="startgame", owner=True)
|
||||
async def magic(event):
|
||||
buttons = [
|
||||
@@ -244,10 +249,17 @@ async def choose_cata(event):
|
||||
if TRIVIA_CHATS[chat].get("cancel") is not None:
|
||||
break
|
||||
ansi = str(uuid.uuid1()).split("-")[0].encode()
|
||||
opts = [PollAnswer(TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi)]
|
||||
opts = [
|
||||
PollAnswer(
|
||||
TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi
|
||||
)
|
||||
]
|
||||
[
|
||||
opts.append(
|
||||
PollAnswer(TextWithEntities(unescape(a), entities=[]), str(uuid.uuid1()).split("-")[0].encode())
|
||||
PollAnswer(
|
||||
TextWithEntities(unescape(a), entities=[]),
|
||||
str(uuid.uuid1()).split("-")[0].encode(),
|
||||
)
|
||||
)
|
||||
for a in q["incorrect_answers"]
|
||||
]
|
||||
@@ -256,8 +268,7 @@ async def choose_cata(event):
|
||||
Poll(
|
||||
0,
|
||||
TextWithEntities(
|
||||
f"[{copper+1}]. " + unescape(q["question"]),
|
||||
entities=[]
|
||||
f"[{copper + 1}]. " + unescape(q["question"]), entities=[]
|
||||
),
|
||||
answers=opts,
|
||||
public_voters=True,
|
||||
|
||||
@@ -5,6 +5,7 @@ import sys
|
||||
|
||||
vars = ["API_ID", "API_HASH", "SESSION"]
|
||||
|
||||
|
||||
def _check(z):
|
||||
new = []
|
||||
for var in vars:
|
||||
@@ -14,6 +15,7 @@ def _check(z):
|
||||
new.append(ent)
|
||||
return True, new
|
||||
|
||||
|
||||
for z in range(5):
|
||||
n = str(z + 1)
|
||||
if z == 0:
|
||||
@@ -21,7 +23,17 @@ for z in range(5):
|
||||
fine, out = _check(str(z))
|
||||
if fine:
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-m", "pyUltroid", out[0], out[1], out[2], out[3], out[4], n],
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"pyUltroid",
|
||||
out[0],
|
||||
out[1],
|
||||
out[2],
|
||||
out[3],
|
||||
out[4],
|
||||
n,
|
||||
],
|
||||
stdin=None,
|
||||
stderr=None,
|
||||
stdout=None,
|
||||
@@ -36,4 +48,3 @@ except Exception as er:
|
||||
print(er)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ async def DummyHandler(ult):
|
||||
# force subscribe
|
||||
if (
|
||||
udB.get_key("FORCESUB")
|
||||
and ((ult.user_joined or ult.user_added))
|
||||
and (ult.user_joined or ult.user_added)
|
||||
and get_forcesetting(ult.chat_id)
|
||||
):
|
||||
user = await ult.get_user()
|
||||
@@ -92,7 +92,7 @@ async def DummyHandler(ult):
|
||||
view_messages=False,
|
||||
)
|
||||
await ult.respond(
|
||||
f'**@UltroidBans:** Banned user detected and banned!\n`{str(is_banned)}`.\nBan reason: {is_banned["reason"]}',
|
||||
f"**@UltroidBans:** Banned user detected and banned!\n`{str(is_banned)}`.\nBan reason: {is_banned['reason']}",
|
||||
)
|
||||
|
||||
except BaseException:
|
||||
|
||||
@@ -398,6 +398,7 @@ async def _(e):
|
||||
except Exception as er:
|
||||
return await e.eor(str(er), time=5)
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="pinned", manager=True, groups_only=True)
|
||||
async def djshsh(event):
|
||||
chat = await event.get_chat()
|
||||
|
||||
@@ -27,7 +27,7 @@ from . import (
|
||||
udB,
|
||||
ultroid_bot,
|
||||
ultroid_cmd,
|
||||
upload_file
|
||||
upload_file,
|
||||
)
|
||||
|
||||
old_afk_msg = []
|
||||
|
||||
@@ -37,14 +37,14 @@ ENDPOINTS = {
|
||||
"gpt": "https://api.openai.com/v1/chat/completions",
|
||||
"antr": "https://api.anthropic.com/v1/messages",
|
||||
"gemini": "https://generativelanguage.googleapis.com/v1beta/chat/completions",
|
||||
"deepseek": "https://api.deepseek.com/chat/completions"
|
||||
"deepseek": "https://api.deepseek.com/chat/completions",
|
||||
}
|
||||
|
||||
DEFAULT_MODELS = {
|
||||
"gpt": "gpt-4o-mini",
|
||||
"antr": "claude-3-opus-20240229",
|
||||
"gemini": "gemini-1.5-flash",
|
||||
"deepseek": "deepseek-chat"
|
||||
"deepseek": "deepseek-chat",
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ def get_model(provider):
|
||||
"gpt": "OPENAI_MODEL",
|
||||
"antr": "ANTHROPIC_MODEL",
|
||||
"gemini": "GEMINI_MODEL",
|
||||
"deepseek": "DEEPSEEK_MODEL"
|
||||
"deepseek": "DEEPSEEK_MODEL",
|
||||
}
|
||||
return udB.get_key(model_keys[provider]) or DEFAULT_MODELS[provider]
|
||||
|
||||
@@ -96,7 +96,7 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
data = {
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"stream": stream
|
||||
"stream": stream,
|
||||
}
|
||||
if not stream:
|
||||
response = await async_searcher(
|
||||
@@ -104,23 +104,27 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
headers=headers,
|
||||
post=True,
|
||||
json=data,
|
||||
re_json=True
|
||||
re_json=True,
|
||||
)
|
||||
yield response["choices"][0]["message"]["content"]
|
||||
return
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
ENDPOINTS[provider],
|
||||
headers=headers,
|
||||
json=data
|
||||
ENDPOINTS[provider], headers=headers, json=data
|
||||
) as resp:
|
||||
async for line in resp.content:
|
||||
if line:
|
||||
try:
|
||||
json_line = json.loads(line.decode('utf-8').strip().strip('data:').strip())
|
||||
if 'choices' in json_line and json_line['choices']:
|
||||
content = json_line['choices'][0].get('delta', {}).get('content', '')
|
||||
json_line = json.loads(
|
||||
line.decode("utf-8").strip().strip("data:").strip()
|
||||
)
|
||||
if "choices" in json_line and json_line["choices"]:
|
||||
content = (
|
||||
json_line["choices"][0]
|
||||
.get("delta", {})
|
||||
.get("content", "")
|
||||
)
|
||||
if content:
|
||||
yield content
|
||||
except Exception:
|
||||
@@ -132,7 +136,7 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
data = {
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"stream": stream
|
||||
"stream": stream,
|
||||
}
|
||||
if not stream:
|
||||
response = await async_searcher(
|
||||
@@ -140,23 +144,21 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
headers=headers,
|
||||
post=True,
|
||||
json=data,
|
||||
re_json=True
|
||||
re_json=True,
|
||||
)
|
||||
yield response["content"][0]["text"]
|
||||
return
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
ENDPOINTS[provider],
|
||||
headers=headers,
|
||||
json=data
|
||||
ENDPOINTS[provider], headers=headers, json=data
|
||||
) as resp:
|
||||
async for line in resp.content:
|
||||
if line:
|
||||
try:
|
||||
json_line = json.loads(line.decode('utf-8').strip())
|
||||
if 'content' in json_line:
|
||||
content = json_line['content'][0]['text']
|
||||
json_line = json.loads(line.decode("utf-8").strip())
|
||||
if "content" in json_line:
|
||||
content = json_line["content"][0]["text"]
|
||||
if content:
|
||||
yield content
|
||||
except Exception:
|
||||
@@ -168,9 +170,9 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": prompt}
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"stream": stream
|
||||
"stream": stream,
|
||||
}
|
||||
|
||||
if not stream:
|
||||
@@ -180,15 +182,20 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
headers=headers,
|
||||
post=True,
|
||||
json=data,
|
||||
re_json=True
|
||||
re_json=True,
|
||||
)
|
||||
if "error" in response:
|
||||
error = response["error"]
|
||||
if error.get("code") == 429:
|
||||
retry_delay = None
|
||||
for detail in error.get("details", []):
|
||||
if detail.get("@type") == "type.googleapis.com/google.rpc.RetryInfo":
|
||||
retry_delay = detail.get("retryDelay", "60s").rstrip("s")
|
||||
if (
|
||||
detail.get("@type")
|
||||
== "type.googleapis.com/google.rpc.RetryInfo"
|
||||
):
|
||||
retry_delay = detail.get(
|
||||
"retryDelay", "60s"
|
||||
).rstrip("s")
|
||||
error_msg = f"⚠️ Rate limit exceeded. Please try again in {retry_delay} seconds."
|
||||
if "free_tier" in str(error):
|
||||
error_msg += "\nConsider upgrading to a paid tier for higher quotas."
|
||||
@@ -205,16 +212,21 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.post(
|
||||
ENDPOINTS[provider],
|
||||
headers=headers,
|
||||
json=data
|
||||
ENDPOINTS[provider], headers=headers, json=data
|
||||
) as resp:
|
||||
if resp.status == 429:
|
||||
error_data = await resp.json()
|
||||
retry_delay = "60"
|
||||
for detail in error_data.get("error", {}).get("details", []):
|
||||
if detail.get("@type") == "type.googleapis.com/google.rpc.RetryInfo":
|
||||
retry_delay = detail.get("retryDelay", "60s").rstrip("s")
|
||||
for detail in error_data.get("error", {}).get(
|
||||
"details", []
|
||||
):
|
||||
if (
|
||||
detail.get("@type")
|
||||
== "type.googleapis.com/google.rpc.RetryInfo"
|
||||
):
|
||||
retry_delay = detail.get(
|
||||
"retryDelay", "60s"
|
||||
).rstrip("s")
|
||||
yield f"⚠️ Rate limit exceeded. Please try again in {retry_delay} seconds."
|
||||
return
|
||||
|
||||
@@ -225,15 +237,22 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
|
||||
async for line in resp.content:
|
||||
if line:
|
||||
text = line.decode('utf-8').strip()
|
||||
if text.startswith('data: '):
|
||||
text = line.decode("utf-8").strip()
|
||||
if text.startswith("data: "):
|
||||
data = text[6:] # Remove 'data: ' prefix
|
||||
if data == '[DONE]':
|
||||
if data == "[DONE]":
|
||||
break
|
||||
try:
|
||||
json_data = json.loads(data)
|
||||
if 'choices' in json_data and json_data['choices']:
|
||||
content = json_data['choices'][0].get('delta', {}).get('content', '')
|
||||
if (
|
||||
"choices" in json_data
|
||||
and json_data["choices"]
|
||||
):
|
||||
content = (
|
||||
json_data["choices"][0]
|
||||
.get("delta", {})
|
||||
.get("content", "")
|
||||
)
|
||||
if content:
|
||||
yield content
|
||||
except json.JSONDecodeError:
|
||||
@@ -247,7 +266,7 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
data = {
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"stream": stream
|
||||
"stream": stream,
|
||||
}
|
||||
if not stream:
|
||||
response = await async_searcher(
|
||||
@@ -255,23 +274,25 @@ async def get_ai_response(provider, prompt, api_key, stream=False):
|
||||
headers=headers,
|
||||
post=True,
|
||||
json=data,
|
||||
re_json=True
|
||||
re_json=True,
|
||||
)
|
||||
yield response["choices"][0]["message"]["content"]
|
||||
return
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
ENDPOINTS[provider],
|
||||
headers=headers,
|
||||
json=data
|
||||
ENDPOINTS[provider], headers=headers, json=data
|
||||
) as resp:
|
||||
async for line in resp.content:
|
||||
if line:
|
||||
try:
|
||||
json_line = json.loads(line.decode('utf-8').strip())
|
||||
if 'choices' in json_line and json_line['choices']:
|
||||
content = json_line['choices'][0].get('delta', {}).get('content', '')
|
||||
json_line = json.loads(line.decode("utf-8").strip())
|
||||
if "choices" in json_line and json_line["choices"]:
|
||||
content = (
|
||||
json_line["choices"][0]
|
||||
.get("delta", {})
|
||||
.get("content", "")
|
||||
)
|
||||
if content:
|
||||
yield content
|
||||
except Exception:
|
||||
@@ -291,7 +312,9 @@ async def gemini_ai(event):
|
||||
|
||||
api_key = udB.get_key("GEMINI_API_KEY")
|
||||
if not api_key:
|
||||
return await event.eor("⚠️ Please set Gemini API key using `setdb GEMINI_API_KEY your_api_key`")
|
||||
return await event.eor(
|
||||
"⚠️ Please set Gemini API key using `setdb GEMINI_API_KEY your_api_key`"
|
||||
)
|
||||
|
||||
msg = await event.eor("🤔 Thinking...")
|
||||
model = get_model("gemini")
|
||||
@@ -322,6 +345,7 @@ async def gemini_ai(event):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="antr( (.*)|$)")
|
||||
async def anthropic_ai(event):
|
||||
"""Use Anthropic Claude"""
|
||||
@@ -331,7 +355,9 @@ async def anthropic_ai(event):
|
||||
|
||||
api_key = udB.get_key("ANTHROPIC_KEY")
|
||||
if not api_key:
|
||||
return await event.eor("⚠️ Please set Anthropic API key using `setdb ANTHROPIC_KEY your_api_key`")
|
||||
return await event.eor(
|
||||
"⚠️ Please set Anthropic API key using `setdb ANTHROPIC_KEY your_api_key`"
|
||||
)
|
||||
|
||||
msg = await event.eor("🤔 Thinking...")
|
||||
model = get_model("antr")
|
||||
@@ -362,6 +388,7 @@ async def anthropic_ai(event):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="gpt( (.*)|$)")
|
||||
async def openai_ai(event):
|
||||
"""Use OpenAI GPT"""
|
||||
@@ -371,7 +398,9 @@ async def openai_ai(event):
|
||||
|
||||
api_key = udB.get_key("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
return await event.eor("⚠️ Please set GPT API key using `setdb OPENAI_API_KEY your_api_key`")
|
||||
return await event.eor(
|
||||
"⚠️ Please set GPT API key using `setdb OPENAI_API_KEY your_api_key`"
|
||||
)
|
||||
|
||||
msg = await event.eor("🤔 Thinking...")
|
||||
model = get_model("gpt")
|
||||
@@ -402,6 +431,7 @@ async def openai_ai(event):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="deepseek( (.*)|$)")
|
||||
async def deepseek_ai(event):
|
||||
"""Use DeepSeek AI"""
|
||||
@@ -411,7 +441,9 @@ async def deepseek_ai(event):
|
||||
|
||||
api_key = udB.get_key("DEEPSEEK_API_KEY")
|
||||
if not api_key:
|
||||
return await event.eor("⚠️ Please set DeepSeek API key using `setdb DEEPSEEK_API_KEY your_api_key`")
|
||||
return await event.eor(
|
||||
"⚠️ Please set DeepSeek API key using `setdb DEEPSEEK_API_KEY your_api_key`"
|
||||
)
|
||||
|
||||
msg = await event.eor("🤔 Thinking...")
|
||||
model = get_model("deepseek")
|
||||
@@ -442,4 +474,3 @@ async def deepseek_ai(event):
|
||||
await msg.edit(formatted_response + response)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ from . import (
|
||||
mediainfo,
|
||||
stdr,
|
||||
time_formatter,
|
||||
ultroid_cmd
|
||||
ultroid_cmd,
|
||||
)
|
||||
|
||||
__doc__ = get_help("help_audiotools")
|
||||
@@ -149,7 +149,11 @@ async def ex_aud(e):
|
||||
f_time = time.time()
|
||||
try:
|
||||
n_file, _ = await e.client.fast_uploader(
|
||||
out_file, show_progress=True, event=e, message="Uploading...", to_delete=True
|
||||
out_file,
|
||||
show_progress=True,
|
||||
event=e,
|
||||
message="Uploading...",
|
||||
to_delete=True,
|
||||
)
|
||||
|
||||
except FileNotFoundError:
|
||||
|
||||
@@ -33,10 +33,10 @@ async def get_google_images(query: str):
|
||||
|
||||
# Domains to exclude
|
||||
excluded_domains = [
|
||||
'gstatic.com',
|
||||
'google.com',
|
||||
'googleusercontent.com',
|
||||
'ssl.google.com'
|
||||
"gstatic.com",
|
||||
"google.com",
|
||||
"googleusercontent.com",
|
||||
"ssl.google.com",
|
||||
]
|
||||
|
||||
def is_valid_url(url):
|
||||
@@ -53,7 +53,7 @@ async def get_google_images(query: str):
|
||||
search_match = re.search(search_pattern, html, re.DOTALL)
|
||||
if search_match:
|
||||
search_content = search_match.group(1)
|
||||
url_pattern = r'https://[^\"]*?\.(?:jpg|jpeg|png|webp)'
|
||||
url_pattern = r"https://[^\"]*?\.(?:jpg|jpeg|png|webp)"
|
||||
url_matches = re.finditer(url_pattern, search_content, re.IGNORECASE)
|
||||
for url_match in url_matches:
|
||||
url = url_match.group(0)
|
||||
@@ -66,7 +66,7 @@ async def get_google_images(query: str):
|
||||
matches = re.finditer(pattern, html, re.DOTALL)
|
||||
for match in matches:
|
||||
div_content = match.group(1)
|
||||
url_pattern = r'https://[^\"]*?\.(?:jpg|jpeg|png|webp)'
|
||||
url_pattern = r"https://[^\"]*?\.(?:jpg|jpeg|png|webp)"
|
||||
url_matches = re.finditer(url_pattern, div_content, re.IGNORECASE)
|
||||
for url_match in url_matches:
|
||||
url = url_match.group(0)
|
||||
@@ -84,7 +84,7 @@ async def get_google_images(query: str):
|
||||
|
||||
# Final fallback to data URLs if still no results
|
||||
if not img_urls:
|
||||
pattern = r'data:image/(?:jpeg|png|webp);base64,[^\"]*'
|
||||
pattern = r"data:image/(?:jpeg|png|webp);base64,[^\"]*"
|
||||
matches = re.finditer(pattern, html, re.IGNORECASE)
|
||||
for match in matches:
|
||||
url = match.group(0)
|
||||
@@ -117,7 +117,9 @@ async def autopic(e):
|
||||
for lie in images:
|
||||
if udB.get_key("AUTOPIC") != search:
|
||||
return
|
||||
download_path, stime = await fast_download(lie, "resources/downloads/autopic.jpg")
|
||||
download_path, stime = await fast_download(
|
||||
lie, "resources/downloads/autopic.jpg"
|
||||
)
|
||||
img = Image.open(download_path)
|
||||
img.save("resources/downloads/autopic.jpg")
|
||||
file = await e.client.upload_file("resources/downloads/autopic.jpg")
|
||||
|
||||
@@ -148,6 +148,7 @@ async def uconverter(event):
|
||||
return
|
||||
await xx.delete()
|
||||
|
||||
|
||||
@ultroid_cmd(
|
||||
pattern="doc( (.*)|$)",
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ fn = functions
|
||||
)
|
||||
async def _(e):
|
||||
xx = await e.eor(get_string("com_1"))
|
||||
x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
|
||||
x, y = await bash("neofetch|sed 's/\x1b\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
|
||||
if y and y.endswith("NOT_FOUND"):
|
||||
return await xx.edit(f"Error: `{y}`")
|
||||
with open("neo.txt", "r", encoding="utf-8") as neo:
|
||||
@@ -323,29 +323,28 @@ def _stringify(text=None, *args, **kwargs):
|
||||
async def aexec(code, event):
|
||||
# Create a dedicated namespace for execution
|
||||
exec_globals = {
|
||||
'print': _stringify,
|
||||
'p': _stringify,
|
||||
'message': event,
|
||||
'event': event,
|
||||
'client': event.client,
|
||||
'reply': await event.get_reply_message(),
|
||||
'chat': event.chat_id,
|
||||
'u': u,
|
||||
'__builtins__': __builtins__,
|
||||
'__name__': __name__
|
||||
"print": _stringify,
|
||||
"p": _stringify,
|
||||
"message": event,
|
||||
"event": event,
|
||||
"client": event.client,
|
||||
"reply": await event.get_reply_message(),
|
||||
"chat": event.chat_id,
|
||||
"u": u,
|
||||
"__builtins__": __builtins__,
|
||||
"__name__": __name__,
|
||||
}
|
||||
|
||||
# Format the async function definition
|
||||
wrapped_code = (
|
||||
'async def __aexec(e, client):\n' +
|
||||
'\n'.join(f' {line}' for line in code.split('\n'))
|
||||
wrapped_code = "async def __aexec(e, client):\n" + "\n".join(
|
||||
f" {line}" for line in code.split("\n")
|
||||
)
|
||||
|
||||
try:
|
||||
# Execute the wrapped code in our custom namespace
|
||||
exec(wrapped_code, exec_globals)
|
||||
# Get the defined async function
|
||||
func = exec_globals['__aexec']
|
||||
func = exec_globals["__aexec"]
|
||||
# Execute it with proper parameters
|
||||
return await func(event, event.client)
|
||||
except Exception as e:
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
•`{i}gif <query>`
|
||||
Send video regarding to query.
|
||||
"""
|
||||
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
•`{i}glitch <reply to media>`
|
||||
gives a glitchy gif.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from . import bash, get_string, mediainfo, ultroid_cmd
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
`gpromote @username all sar` ~ promote the user in all group & channel
|
||||
• `{i}gdemote` - `demote user globally`
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
@@ -463,11 +464,9 @@ async def gcast(event):
|
||||
not keym.contains(chat)
|
||||
and int(f"-100{str(chat)}") not in NOSPAM_CHAT
|
||||
and (
|
||||
(
|
||||
event.text[2:7] != "admin"
|
||||
or (x.entity.admin_rights or x.entity.creator)
|
||||
)
|
||||
)
|
||||
):
|
||||
try:
|
||||
if btn:
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
• `{i}thankmembers on/off`
|
||||
Send a thank you sticker on hitting a members count of 100*x in your groups.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from . import upload_file as uf
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
• `{i}pixelator <reply image>`
|
||||
Create a Pixelated Image..
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from . import LOGS, con
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
• `{i}unlock <msgs/media/sticker/gif/games/inline/polls/invites/pin/changeinfo>`
|
||||
UNLOCK the Used Setting in Used Group.
|
||||
"""
|
||||
|
||||
from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest
|
||||
|
||||
from pyUltroid.fns.admins import lock_unlock
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
Or Reply To Font File, To write with that font.
|
||||
|
||||
"""
|
||||
|
||||
import glob
|
||||
import os
|
||||
import random
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
Rotate any video/photo/media..
|
||||
Note : for video it should be angle of 90's
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime as dt
|
||||
|
||||
@@ -51,7 +51,7 @@ async def diela(e):
|
||||
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'
|
||||
te += f"• [{eve.text}]({eve['href']})\n"
|
||||
await m.edit(te, link_preview=False)
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
d- days
|
||||
Mute user in current chat with time.
|
||||
"""
|
||||
|
||||
from telethon import events
|
||||
from telethon.utils import get_display_name
|
||||
|
||||
|
||||
@@ -117,7 +117,9 @@ async def open_grp():
|
||||
),
|
||||
)
|
||||
)
|
||||
await ultroid_bot.send_message(chat, "**NightMode Off**\n\nGroup Opened 🥳.")
|
||||
await ultroid_bot.send_message(
|
||||
chat, "**NightMode Off**\n\nGroup Opened 🥳."
|
||||
)
|
||||
except Exception as er:
|
||||
LOGS.info(er)
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
set notes in group so all can use it.
|
||||
type `#(Keyword of note)` to get it
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from . import upload_file as uf
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
• `{i}pdsend `
|
||||
Merge & send the pdf, collected from .pdsave.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
Get the quiz poll where answerno is the number of option which is correct
|
||||
|
||||
"""
|
||||
|
||||
from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, TextWithEntities
|
||||
|
||||
from . import get_string, ultroid_cmd
|
||||
@@ -57,10 +58,20 @@ async def uri_poll(e):
|
||||
if len(option) <= 1:
|
||||
return await e.eor("`Options Should be More than 1..`", time=5)
|
||||
m = await e.eor(get_string("com_1"))
|
||||
OUT = [PollAnswer(TextWithEntities(option[on], entities=[]), str(on).encode()) for on in range(len(option))]
|
||||
OUT = [
|
||||
PollAnswer(TextWithEntities(option[on], entities=[]), str(on).encode())
|
||||
for on in range(len(option))
|
||||
]
|
||||
await e.respond(
|
||||
file=InputMediaPoll(
|
||||
Poll(20, TextWithEntities(ques, entities=[]), OUT, multiple_choice=mpp, public_voters=publ, quiz=quizo),
|
||||
Poll(
|
||||
20,
|
||||
TextWithEntities(ques, entities=[]),
|
||||
OUT,
|
||||
multiple_choice=mpp,
|
||||
public_voters=publ,
|
||||
quiz=quizo,
|
||||
),
|
||||
correct_answers=karzo,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
Ex: `{i}poto 10` - uploads starting 10 pfps of user.
|
||||
Upload the photo of Chat/User if Available.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from telethon.tl.functions.account import UpdateProfileRequest
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
• `{i}qrdecode <reply to qrcode>`
|
||||
`It decodes the qrcode.`
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from pyUltroid import ULTConfig
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
To resize image on x, y axis.
|
||||
eg. `{i}resize 690 960`
|
||||
"""
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from . import HNDLR, eor, get_string, os, ultroid_cmd
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
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 pyUltroid.fns.admins import ban_time
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
• `{i}reverse`
|
||||
Reply an Image or sticker to find its sauce.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
• Use :
|
||||
type `$(ur snip word)` get setted reply.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from . import upload_file as uf
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
• `{i}wall <query>`
|
||||
Search Hd Wallpaper as Per ur Wish..
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime as dt
|
||||
@@ -62,6 +63,7 @@ from .beautify import all_col
|
||||
File = []
|
||||
scraper = create_scraper()
|
||||
|
||||
|
||||
@ultroid_cmd(
|
||||
pattern="getaudio$",
|
||||
)
|
||||
@@ -251,8 +253,10 @@ Zodiac -: {sign}
|
||||
reply_to=event.reply_to_msg_id,
|
||||
)
|
||||
|
||||
|
||||
session = Session()
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="sticker( (.*)|$)")
|
||||
async def _(event):
|
||||
x = event.pattern_match.group(1).strip()
|
||||
@@ -261,7 +265,7 @@ async def _(event):
|
||||
uu = await event.eor(get_string("com_1"))
|
||||
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
||||
}
|
||||
|
||||
max_retries = 3
|
||||
@@ -270,8 +274,7 @@ async def _(event):
|
||||
while retry_count < max_retries:
|
||||
try:
|
||||
response = scraper.get(
|
||||
f"https://combot.org/telegram/stickers?q={x}",
|
||||
headers=headers
|
||||
f"https://combot.org/telegram/stickers?q={x}", headers=headers
|
||||
).content
|
||||
|
||||
# Check if response contains Cloudflare challenge
|
||||
@@ -315,6 +318,7 @@ async def _(event):
|
||||
except Exception as e:
|
||||
await uu.edit(f"`Error: {str(e)}`\nTry again later.")
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="wall( (.*)|$)")
|
||||
async def wall(event):
|
||||
inp = event.pattern_match.group(1).strip()
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
• `{i}round <reply to any media>`
|
||||
To extract round sticker.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import io
|
||||
import os
|
||||
|
||||
@@ -22,7 +22,14 @@ from . import ultroid_cmd, get_string, LOGS
|
||||
|
||||
from telethon import TelegramClient
|
||||
from telethon.tl.functions.channels import GetFullChannelRequest
|
||||
from telethon.tl.types import User, UserFull, InputPeerSelf, InputPrivacyValueAllowAll, Channel, InputUserSelf
|
||||
from telethon.tl.types import (
|
||||
User,
|
||||
UserFull,
|
||||
InputPeerSelf,
|
||||
InputPrivacyValueAllowAll,
|
||||
Channel,
|
||||
InputUserSelf,
|
||||
)
|
||||
from telethon.tl.functions.stories import SendStoryRequest, GetStoriesByIDRequest
|
||||
from telethon.tl.functions.users import GetFullUserRequest
|
||||
from telethon.events import NewMessage
|
||||
@@ -40,9 +47,7 @@ async def setStory(event: NewMessage.Event):
|
||||
SendStoryRequest(
|
||||
InputPeerSelf(),
|
||||
reply.media,
|
||||
privacy_rules=[
|
||||
InputPrivacyValueAllowAll()
|
||||
]
|
||||
privacy_rules=[InputPrivacyValueAllowAll()],
|
||||
)
|
||||
)
|
||||
await msg.eor("🔥 **Story is Live!**", time=5)
|
||||
@@ -73,10 +78,7 @@ async def downloadUserStories(event: NewMessage.Event):
|
||||
|
||||
# Using GetStoriesByIDRequest to fetch the specific story
|
||||
stories_response = await event.client(
|
||||
GetStoriesByIDRequest(
|
||||
entity.id,
|
||||
id=[story_id]
|
||||
)
|
||||
GetStoriesByIDRequest(entity.id, id=[story_id])
|
||||
)
|
||||
print(stories_response)
|
||||
|
||||
@@ -87,11 +89,8 @@ async def downloadUserStories(event: NewMessage.Event):
|
||||
for story in stories_response.stories:
|
||||
client: TelegramClient = event.client
|
||||
file = await client.download_media(story.media)
|
||||
caption = story.caption if hasattr(story, 'caption') else ""
|
||||
await message.reply(
|
||||
caption,
|
||||
file=file
|
||||
)
|
||||
caption = story.caption if hasattr(story, "caption") else ""
|
||||
await message.reply(caption, file=file)
|
||||
os.remove(file)
|
||||
|
||||
return await message.eor("**Uploaded Story!**", time=5)
|
||||
@@ -140,11 +139,8 @@ async def downloadUserStories(event: NewMessage.Event):
|
||||
for story in stories.stories[:5]:
|
||||
client: TelegramClient = event.client
|
||||
file = await client.download_media(story.media)
|
||||
caption = story.caption if hasattr(story, 'caption') else ""
|
||||
await message.reply(
|
||||
caption,
|
||||
file=file
|
||||
)
|
||||
caption = story.caption if hasattr(story, "caption") else ""
|
||||
await message.reply(caption, file=file)
|
||||
os.remove(file)
|
||||
|
||||
await message.eor("**Uploaded Stories!**", time=5)
|
||||
@@ -33,6 +33,7 @@
|
||||
• `{i}webshot <url>`
|
||||
Get a screenshot of the webpage.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import io
|
||||
import os
|
||||
@@ -335,7 +336,6 @@ async def _(e):
|
||||
await e.delete()
|
||||
|
||||
|
||||
|
||||
def sanga_seperator(sanga_list):
|
||||
string = "".join(info[info.find("\n") + 1 :] for info in sanga_list)
|
||||
string = re.sub(r"^$\n", "", string, flags=re.MULTILINE)
|
||||
@@ -460,4 +460,3 @@ async def webss(event):
|
||||
)
|
||||
os.remove(pic)
|
||||
await xx.delete()
|
||||
|
||||
|
||||
@@ -32,13 +32,19 @@ twitter_client = None
|
||||
# Get path to cookies file
|
||||
COOKIES_FILE = "resources/auth/twitter_cookies.json"
|
||||
|
||||
|
||||
async def get_client():
|
||||
global twitter_client
|
||||
if twitter_client:
|
||||
return twitter_client
|
||||
|
||||
if not all(udB.get_key(key) for key in ["TWITTER_USERNAME", "TWITTER_EMAIL", "TWITTER_PASSWORD"]):
|
||||
raise Exception("Set TWITTER_USERNAME, TWITTER_EMAIL and TWITTER_PASSWORD in vars first!")
|
||||
if not all(
|
||||
udB.get_key(key)
|
||||
for key in ["TWITTER_USERNAME", "TWITTER_EMAIL", "TWITTER_PASSWORD"]
|
||||
):
|
||||
raise Exception(
|
||||
"Set TWITTER_USERNAME, TWITTER_EMAIL and TWITTER_PASSWORD in vars first!"
|
||||
)
|
||||
|
||||
# Create auth directory if it doesn't exist
|
||||
os.makedirs(os.path.dirname(COOKIES_FILE), exist_ok=True)
|
||||
@@ -48,13 +54,12 @@ async def get_client():
|
||||
auth_info_1=udB.get_key("TWITTER_USERNAME"),
|
||||
auth_info_2=udB.get_key("TWITTER_EMAIL"),
|
||||
password=udB.get_key("TWITTER_PASSWORD"),
|
||||
cookies_file=COOKIES_FILE
|
||||
cookies_file=COOKIES_FILE,
|
||||
)
|
||||
twitter_client = client
|
||||
return client
|
||||
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="tw( (.*)|$)")
|
||||
async def tweet_cmd(event):
|
||||
"""Post a tweet"""
|
||||
@@ -66,7 +71,9 @@ async def tweet_cmd(event):
|
||||
try:
|
||||
client = await get_client()
|
||||
tweet = await client.create_tweet(text=text)
|
||||
await msg.edit(f"✨ **Successfully Posted!**\n\n🔗 https://x.com/{tweet.user.screen_name}/status/{tweet.id}")
|
||||
await msg.edit(
|
||||
f"✨ **Successfully Posted!**\n\n🔗 https://x.com/{tweet.user.screen_name}/status/{tweet.id}"
|
||||
)
|
||||
except Exception as e:
|
||||
await msg.edit(f"❌ **Error:**\n`{str(e)}`")
|
||||
|
||||
@@ -82,6 +89,7 @@ async def twitter_details(event):
|
||||
try:
|
||||
client = await get_client()
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed_url = urlparse(match)
|
||||
if parsed_url.hostname in ["twitter.com", "x.com"]:
|
||||
tweet_id = parsed_url.path.split("/")[-1].split("?")[0]
|
||||
@@ -126,10 +134,7 @@ async def twitter_user(event):
|
||||
if user.profile_image_url:
|
||||
image_url = user.profile_image_url.replace("_normal.", ".")
|
||||
await event.client.send_file(
|
||||
event.chat_id,
|
||||
file=image_url,
|
||||
caption=text,
|
||||
force_document=False
|
||||
event.chat_id, file=image_url, caption=text, force_document=False
|
||||
)
|
||||
await msg.delete()
|
||||
else:
|
||||
@@ -171,28 +176,31 @@ async def twitter_media(event):
|
||||
await event.client.send_file(
|
||||
event.chat_id,
|
||||
media.url,
|
||||
caption=caption if media_count == 0 else None # Only add caption to first media
|
||||
caption=caption
|
||||
if media_count == 0
|
||||
else None, # Only add caption to first media
|
||||
)
|
||||
media_count += 1
|
||||
elif media.type == "video":
|
||||
if hasattr(media, "video_info") and isinstance(media.video_info, dict):
|
||||
variants = media.video_info.get("variants", [])
|
||||
mp4_variants = [
|
||||
v for v in variants
|
||||
v
|
||||
for v in variants
|
||||
if v.get("content_type") == "video/mp4" and "bitrate" in v
|
||||
]
|
||||
if mp4_variants:
|
||||
best_video = max(mp4_variants, key=lambda x: x["bitrate"])
|
||||
video_caption = caption if media_count == 0 else "" # Only add tweet text to first media
|
||||
video_caption = (
|
||||
caption if media_count == 0 else ""
|
||||
) # Only add tweet text to first media
|
||||
if video_caption:
|
||||
video_caption += f"\n🎥 Video Quality: {best_video['bitrate'] / 1000:.0f}kbps"
|
||||
else:
|
||||
video_caption = f"🎥 Video Quality: {best_video['bitrate'] / 1000:.0f}kbps"
|
||||
|
||||
await event.client.send_file(
|
||||
event.chat_id,
|
||||
best_video["url"],
|
||||
caption=video_caption
|
||||
event.chat_id, best_video["url"], caption=video_caption
|
||||
)
|
||||
media_count += 1
|
||||
|
||||
|
||||
@@ -266,9 +266,7 @@ async def _(event):
|
||||
done, data = await get_paste(message)
|
||||
if not done and data.get("error"):
|
||||
return await xx.eor(data["error"])
|
||||
reply_text = (
|
||||
f"• **Pasted to SpaceBin :** [Space]({data['link']})\n• **Raw Url :** : [Raw]({data['raw']})"
|
||||
)
|
||||
reply_text = f"• **Pasted to SpaceBin :** [Space]({data['link']})\n• **Raw Url :** : [Raw]({data['raw']})"
|
||||
try:
|
||||
if event.client._bot:
|
||||
return await xx.eor(reply_text)
|
||||
@@ -718,13 +716,17 @@ async def get_video_duration(file_path):
|
||||
print("Error running ffprobe:", e)
|
||||
return None
|
||||
|
||||
|
||||
async def get_thumbnail(file_path, thumbnail_path):
|
||||
try:
|
||||
await asyncio.create_subprocess_exec(
|
||||
"ffmpeg",
|
||||
"-i", file_path,
|
||||
"-ss", "00:00:04",
|
||||
"-vframes", "1", # Extract a single frame as the thumbnail
|
||||
"-i",
|
||||
file_path,
|
||||
"-ss",
|
||||
"00:00:04",
|
||||
"-vframes",
|
||||
"1", # Extract a single frame as the thumbnail
|
||||
thumbnail_path,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
@@ -732,6 +734,7 @@ async def get_thumbnail(file_path, thumbnail_path):
|
||||
except Exception as e:
|
||||
print(f"Error extracting thumbnail: {e}")
|
||||
|
||||
|
||||
@ultroid_cmd(pattern="getmsg( ?(.*)|$)")
|
||||
async def get_restricted_msg(event):
|
||||
match = event.pattern_match.group(1).strip()
|
||||
@@ -767,7 +770,12 @@ async def get_restricted_msg(event):
|
||||
|
||||
if message.media:
|
||||
if isinstance(message.media, (MessageMediaPhoto, MessageMediaDocument)):
|
||||
media_path, _ = await event.client.fast_downloader(message.document, show_progress=True, event=xx, message=get_string("com_5"))
|
||||
media_path, _ = await event.client.fast_downloader(
|
||||
message.document,
|
||||
show_progress=True,
|
||||
event=xx,
|
||||
message=get_string("com_5"),
|
||||
)
|
||||
|
||||
caption = message.text or ""
|
||||
|
||||
@@ -794,7 +802,9 @@ async def get_restricted_msg(event):
|
||||
)
|
||||
)
|
||||
await xx.edit(get_string("com_6"))
|
||||
media_path, _ = await event.client.fast_uploader(media_path.name, event=xx, show_progress=True, to_delete=True)
|
||||
media_path, _ = await event.client.fast_uploader(
|
||||
media_path.name, event=xx, show_progress=True, to_delete=True
|
||||
)
|
||||
|
||||
try:
|
||||
await event.client.send_file(
|
||||
@@ -826,4 +836,3 @@ async def get_restricted_msg(event):
|
||||
await event.eor("`Cannot process this type of media.`")
|
||||
else:
|
||||
await event.eor("`No media found in the message.`")
|
||||
|
||||
|
||||
@@ -51,12 +51,14 @@ async def get_timezone(offset_seconds, use_utc=False):
|
||||
return f"{m} ({timezone}{sign}{hours:02d})"
|
||||
return "Timezone not found"
|
||||
|
||||
|
||||
async def getWindinfo(speed: str, degree: str) -> str:
|
||||
dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
|
||||
ix = round(degree / (360.00 / len(dirs)))
|
||||
kmph = str(float(speed) * 3.6) + " km/h"
|
||||
return f"[{dirs[ix % len(dirs)]}] {kmph}"
|
||||
|
||||
|
||||
async def get_air_pollution_data(latitude, longitude, api_key):
|
||||
url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={latitude}&lon={longitude}&appid={api_key}"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
• `{i}ud <word>`
|
||||
Fetch word defenition from urbandictionary.
|
||||
"""
|
||||
|
||||
import io
|
||||
|
||||
from pyUltroid.fns.misc import get_synonyms_or_antonyms
|
||||
@@ -35,7 +36,7 @@ async def mean(event):
|
||||
url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{wrd}"
|
||||
out = await async_searcher(url, re_json=True)
|
||||
try:
|
||||
return await event.eor(f'**{out["title"]}**')
|
||||
return await event.eor(f"**{out['title']}**")
|
||||
except (KeyError, TypeError):
|
||||
pass
|
||||
defi = out[0]["meanings"][0]["definitions"][0]
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
• `{i}ytsv <(youtube) search query>`
|
||||
Search and download video from youtube.
|
||||
"""
|
||||
|
||||
from pyUltroid.fns.ytdl import download_yt, get_yt_link
|
||||
|
||||
from . import get_string, requests, ultroid_cmd
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
To set Password: `{i}dozip <password>`
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ async def eor(event, text=None, time=None, link_preview=False, edit_time=None, *
|
||||
text,
|
||||
link_preview=link_preview,
|
||||
reply_to=reply_to,
|
||||
**args
|
||||
**args,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
@@ -52,7 +52,7 @@ async def eod(event, text=None, **kwargs):
|
||||
async def _try_delete(event):
|
||||
try:
|
||||
return await event.delete()
|
||||
except (MessageDeleteForbiddenError):
|
||||
except MessageDeleteForbiddenError:
|
||||
pass
|
||||
except BaseException as er:
|
||||
from . import LOGS
|
||||
|
||||
@@ -10,13 +10,10 @@ Exceptions which can be raised by py-Ultroid Itself.
|
||||
"""
|
||||
|
||||
|
||||
class pyUltroidError(Exception):
|
||||
...
|
||||
class pyUltroidError(Exception): ...
|
||||
|
||||
|
||||
class DependencyMissingError(ImportError):
|
||||
...
|
||||
class DependencyMissingError(ImportError): ...
|
||||
|
||||
|
||||
class RunningAsFunctionLibError(pyUltroidError):
|
||||
...
|
||||
class RunningAsFunctionLibError(pyUltroidError): ...
|
||||
|
||||
@@ -138,7 +138,7 @@ def lock_unlock(query, lock=True):
|
||||
rights = types.ChatBannedRights(None)
|
||||
_do = lock
|
||||
if query == "msgs":
|
||||
for i in ["send_messages", "invite_users", "pin_messages" "change_info"]:
|
||||
for i in ["send_messages", "invite_users", "pin_messageschange_info"]:
|
||||
setattr(rights, i, _do)
|
||||
elif query == "media":
|
||||
setattr(rights, "send_media", _do)
|
||||
|
||||
@@ -62,6 +62,7 @@ except ImportError:
|
||||
|
||||
uploader = CatboxUploader()
|
||||
|
||||
|
||||
async def randomchannel(
|
||||
tochat, channel, range1, range2, caption=None, client=ultroid_bot
|
||||
):
|
||||
@@ -195,7 +196,7 @@ async def unsplashsearch(query, limit=None, shuf=True):
|
||||
all_ = res.find_all("img", srcset=re.compile("images.unsplash.com/photo"))
|
||||
if shuf:
|
||||
shuffle(all_)
|
||||
return list(map(lambda e: e['src'], all_[:limit]))
|
||||
return list(map(lambda e: e["src"], all_[:limit]))
|
||||
|
||||
|
||||
# ---------------- Random User Gen ----------------
|
||||
|
||||
@@ -391,32 +391,28 @@ class LogoHelper:
|
||||
async def get_paste(data: str, extension: str = "txt"):
|
||||
try:
|
||||
url = "https://spaceb.in/api/"
|
||||
res = await async_searcher(url, json={"content": data, "extension": extension}, post=True, re_json=True)
|
||||
res = await async_searcher(
|
||||
url, json={"content": data, "extension": extension}, post=True, re_json=True
|
||||
)
|
||||
return True, {
|
||||
"link": f"https://spaceb.in/{res['payload']['id']}",
|
||||
"raw": f"https://spaceb.in/{res['payload']['id']}/raw"
|
||||
"raw": f"https://spaceb.in/{res['payload']['id']}/raw",
|
||||
}
|
||||
except Exception:
|
||||
try:
|
||||
url = "https://dpaste.org/api/"
|
||||
data = {
|
||||
'format': 'json',
|
||||
'content': data.encode('utf-8'),
|
||||
'lexer': extension,
|
||||
'expires': '604800', # expire in week
|
||||
"format": "json",
|
||||
"content": data.encode("utf-8"),
|
||||
"lexer": extension,
|
||||
"expires": "604800", # expire in week
|
||||
}
|
||||
res = await async_searcher(url, data=data, post=True, re_json=True)
|
||||
return True, {
|
||||
"link": res["url"],
|
||||
"raw": f'{res["url"]}/raw'
|
||||
}
|
||||
return True, {"link": res["url"], "raw": f"{res['url']}/raw"}
|
||||
except Exception as e:
|
||||
LOGS.info(e)
|
||||
return None, {
|
||||
"link": None,
|
||||
"raw": None,
|
||||
"error": str(e)
|
||||
}
|
||||
return None, {"link": None, "raw": None, "error": str(e)}
|
||||
|
||||
|
||||
# https://stackoverflow.com/a/74563494
|
||||
|
||||
@@ -434,18 +430,9 @@ async def get_google_images(query):
|
||||
|
||||
# Google Custom Search API credentials
|
||||
google_keys = [
|
||||
{
|
||||
"key": "AIzaSyAj75v6vHWLJdJaYcj44tLz7bdsrh2g7Y0",
|
||||
"cx": "712a54749d99a449e"
|
||||
},
|
||||
{
|
||||
"key": "AIzaSyDFQQwPLCzcJ9FDao-B7zDusBxk8GoZ0HY",
|
||||
"cx": "001bbd139705f44a6"
|
||||
},
|
||||
{
|
||||
"key": "AIzaSyD0sRNZUa8-0kq9LAREDAFKLNO1HPmikRU",
|
||||
"cx": "4717c609c54e24250"
|
||||
}
|
||||
{"key": "AIzaSyAj75v6vHWLJdJaYcj44tLz7bdsrh2g7Y0", "cx": "712a54749d99a449e"},
|
||||
{"key": "AIzaSyDFQQwPLCzcJ9FDao-B7zDusBxk8GoZ0HY", "cx": "001bbd139705f44a6"},
|
||||
{"key": "AIzaSyD0sRNZUa8-0kq9LAREDAFKLNO1HPmikRU", "cx": "4717c609c54e24250"},
|
||||
]
|
||||
key_index = random.randint(0, len(google_keys) - 1)
|
||||
GOOGLE_API_KEY = google_keys[key_index]["key"]
|
||||
@@ -472,13 +459,17 @@ async def get_google_images(query):
|
||||
google_images = []
|
||||
for item in response["items"]:
|
||||
try:
|
||||
google_images.append({
|
||||
google_images.append(
|
||||
{
|
||||
"title": item.get("title", ""),
|
||||
"link": item.get("contextLink", ""), # Page containing image
|
||||
"source": item.get("displayLink", ""),
|
||||
"thumbnail": item.get("image", {}).get("thumbnailLink", item["link"]),
|
||||
"original": item["link"] # Original image URL
|
||||
})
|
||||
"thumbnail": item.get("image", {}).get(
|
||||
"thumbnailLink", item["link"]
|
||||
),
|
||||
"original": item["link"], # Original image URL
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
LOGS.warning(f"Failed to process image result: {str(e)}")
|
||||
continue
|
||||
@@ -507,6 +498,7 @@ async def get_chatbot_reply(message):
|
||||
except Exception:
|
||||
LOGS.info(f"**ERROR:**`{format_exc()}`")
|
||||
|
||||
|
||||
def check_filename(filroid):
|
||||
if os.path.exists(filroid):
|
||||
no = 1
|
||||
@@ -724,7 +716,6 @@ def translate(text, lang_tgt="en", lang_src="auto", timeout=60, detect=False):
|
||||
return (text, None) if detect else text
|
||||
|
||||
|
||||
|
||||
def cmd_regex_replace(cmd):
|
||||
return (
|
||||
cmd.replace("$", "")
|
||||
@@ -744,8 +735,7 @@ def cmd_regex_replace(cmd):
|
||||
# ------------------------#
|
||||
|
||||
|
||||
class LottieException(Exception):
|
||||
...
|
||||
class LottieException(Exception): ...
|
||||
|
||||
|
||||
class TgConverter:
|
||||
@@ -839,7 +829,9 @@ class TgConverter:
|
||||
input_, name=output[:-5], remove=remove
|
||||
)
|
||||
if output.endswith(".gif"):
|
||||
out, er = await bash(f"ffmpeg -i '{input_}' -an -sn -c:v copy '{output}.mp4' -y")
|
||||
out, er = await bash(
|
||||
f"ffmpeg -i '{input_}' -an -sn -c:v copy '{output}.mp4' -y"
|
||||
)
|
||||
LOGS.info(f"FFmpeg output: {out}, Error: {er}")
|
||||
else:
|
||||
out, er = await bash(f"ffmpeg -i '{input_}' '{output}' -y")
|
||||
@@ -899,7 +891,9 @@ class TgConverter:
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
raise DependencyMissingError("This function needs 'cv2' to be installed.")
|
||||
raise DependencyMissingError(
|
||||
"This function needs 'cv2' to be installed."
|
||||
)
|
||||
|
||||
img = cv2.VideoCapture(input_)
|
||||
success, frame = img.read()
|
||||
@@ -977,7 +971,9 @@ class TgConverter:
|
||||
input_file, convert_to="gif", remove_old=remove_old
|
||||
)
|
||||
if gif_file:
|
||||
return await TgConverter.create_webm(gif_file, outname, remove=True)
|
||||
return await TgConverter.create_webm(
|
||||
gif_file, outname, remove=True
|
||||
)
|
||||
|
||||
# Json -> Tgs
|
||||
elif ext == "json":
|
||||
@@ -1001,7 +997,9 @@ class TgConverter:
|
||||
for exte in ["png", "jpg", "jpeg", "webp"]:
|
||||
if recycle_type(exte):
|
||||
name = outname + "." + exte
|
||||
result = TgConverter.to_image(input_file, name, remove=remove_old)
|
||||
result = TgConverter.to_image(
|
||||
input_file, name, remove=remove_old
|
||||
)
|
||||
if result:
|
||||
return result
|
||||
|
||||
@@ -1039,7 +1037,9 @@ class TgConverter:
|
||||
input_file, name, remove=remove_old
|
||||
)
|
||||
|
||||
LOGS.error(f"No valid conversion found for {input_file} to {convert_to or allowed_formats}")
|
||||
LOGS.error(
|
||||
f"No valid conversion found for {input_file} to {convert_to or allowed_formats}"
|
||||
)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -73,7 +73,6 @@ if run_as_module:
|
||||
handlers=[FileHandler(file), StreamHandler()],
|
||||
)
|
||||
try:
|
||||
|
||||
import coloredlogs
|
||||
|
||||
coloredlogs.install(level=None, logger=LOGS, fmt=_LOG_FORMAT)
|
||||
|
||||
@@ -90,6 +90,7 @@ async def autoupdate_local_database():
|
||||
def update_envs():
|
||||
"""Update Var. attributes to udB"""
|
||||
from .. import udB
|
||||
|
||||
_envs = [*list(os.environ)]
|
||||
if ".env" in os.listdir("."):
|
||||
[_envs.append(_) for _ in list(RepositoryEnv(config._find_file(".")).data)]
|
||||
@@ -432,7 +433,6 @@ async def plug(plugin_channels):
|
||||
LOGS.exception(er)
|
||||
|
||||
|
||||
|
||||
async def ready():
|
||||
from .. import asst, udB, ultroid_bot
|
||||
|
||||
|
||||
@@ -46,7 +46,6 @@ def _after_load(loader, module, plugin_name=""):
|
||||
|
||||
|
||||
def load_other_plugins(addons=None, pmbot=None, manager=None, vcbot=None):
|
||||
|
||||
# for official
|
||||
_exclude = udB.get_key("EXCLUDE_OFFICIAL") or config("EXCLUDE_OFFICIAL", None)
|
||||
_exclude = _exclude.split() if _exclude else []
|
||||
|
||||
@@ -56,6 +56,7 @@ def telethon_session():
|
||||
try:
|
||||
spinner("tele")
|
||||
import telethon
|
||||
|
||||
x = "\bFound an existing installation of Telethon...\nSuccessfully Imported.\n\n"
|
||||
except ImportError:
|
||||
print("Installing Telethon...")
|
||||
@@ -132,7 +133,9 @@ def pyro_session():
|
||||
API_ID, API_HASH = get_api_id_and_hash()
|
||||
print("Enter phone number when asked.\n\n")
|
||||
try:
|
||||
with Client(name="ultroid", api_id=API_ID, api_hash=API_HASH, in_memory=True) as pyro:
|
||||
with Client(
|
||||
name="ultroid", api_id=API_ID, api_hash=API_HASH, in_memory=True
|
||||
) as pyro:
|
||||
ss = pyro.export_session_string()
|
||||
pyro.send_message(
|
||||
"me",
|
||||
@@ -141,7 +144,9 @@ def pyro_session():
|
||||
print("Session has been sent to your saved messages!")
|
||||
exit(0)
|
||||
except Exception as er:
|
||||
print("Unexpected error occurred while creating session, make sure to validate your inputs.")
|
||||
print(
|
||||
"Unexpected error occurred while creating session, make sure to validate your inputs."
|
||||
)
|
||||
print(er)
|
||||
|
||||
|
||||
|
||||
@@ -230,7 +230,7 @@ print(
|
||||
{Fore.YELLOW}# Installing other non mandatory requirements.
|
||||
(You can Install them, if you want command using them to work!){Fore.RESET}
|
||||
|
||||
{'- '.join(list(OPT_PACKAGES.keys()))}
|
||||
{"- ".join(list(OPT_PACKAGES.keys()))}
|
||||
|
||||
Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]"""
|
||||
)
|
||||
|
||||
@@ -21,7 +21,6 @@ a = r"""
|
||||
|
||||
|
||||
def start():
|
||||
|
||||
clear_screen()
|
||||
check_for_py()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user