Few fixes and addition (#444)

This commit is contained in:
TrueSaiyan
2025-02-20 21:18:27 +08:00
committed by GitHub
parent ab9f0c7254
commit dace7972f3
8 changed files with 355 additions and 92 deletions

View File

@@ -398,7 +398,6 @@ 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()

View File

@@ -251,6 +251,14 @@ async def _(event):
with open("ultroid.log", "r") as f:
file = f.read()[-4000:]
return await event.eor(f"`{file}`")
elif (
opt.isdigit() and 5 <= int(opt) <= 100
): # Check if input is a number between 10 and 100
num_lines = int(opt)
with open("ultroid.log", "r") as f:
lines = f.readlines()[-num_lines:]
file = "".join(lines)
return await event.eor(f"`{file}`")
else:
await def_logs(event, file)
await event.try_delete()

View File

@@ -1,11 +1,11 @@
# Ultroid - UserBot
# Copyright (C) 2021-2023 TeamUltroid
# Ultroid ~ UserBot
# Copyright (C) 2024 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 -
Commands Available -
• `{i}destroy <reply to animated sticker>`
To destroy the sticker.
@@ -61,10 +61,10 @@ from . import (
get_string,
inline_mention,
mediainfo,
ultroid_cmd,
quotly,
types,
udB,
ultroid_cmd,
)
@@ -94,7 +94,7 @@ async def pack_kangish(_):
docs = _get_stiks.documents
else:
docs = []
files = glob.glob(cmdtext + "/*")
files = glob.glob(f"{cmdtext}/*")
exte = files[-1]
if exte.endswith(".tgs"):
typee = "anim"
@@ -115,9 +115,11 @@ async def pack_kangish(_):
stiks.append(
types.InputStickerSetItem(
document=x,
emoji=random.choice(["😐", "👍", "😂"])
if local
else (i.attributes[1]).alt,
emoji=(
random.choice(["😐", "👍", "😂"])
if local
else (i.attributes[1]).alt
),
)
)
try:
@@ -366,6 +368,14 @@ async def hehe(args):
os.remove(photo)
except BaseException:
pass
try:
os.remove("AnimatedSticker.tgs")
except BaseException:
pass
try:
os.remove("ult.webp")
except BaseException:
pass
@ultroid_cmd(

View File

@@ -338,55 +338,83 @@ 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)
name, username = string.split("Usernames**")
name = name.split("Names")[1]
return name, username
def mentionuser(name, userid):
return f"[{name}](tg://user?id={userid})"
@ultroid_cmd(
pattern="sg( (.*)|$)",
pattern="sg(|u)(?:\\s|$)([\\s\\S]*)",
fullsudo=True,
)
async def lastname(steal):
mat = steal.pattern_match.group(1).strip()
message = await steal.get_reply_message()
if mat:
try:
user_id = await steal.client.parse_id(mat)
except ValueError:
user_id = mat
elif message:
user_id = message.sender_id
else:
return await steal.eor("`Use this command with reply or give Username/id...`")
chat = "@SangMataInfo_bot"
id = f"/search_id {user_id}"
lol = await steal.eor(get_string("com_1"))
async def sangmata(event):
"To get name/username history."
cmd = event.pattern_match.group(1)
user = event.pattern_match.group(2)
reply = await event.get_reply_message()
if not user and reply:
user = str(reply.sender_id)
if not user:
await event.edit(
"`Reply to user's text message to get name/username history or give userid/username`",
)
await asyncio.sleep(10)
return await event.delete()
try:
async with steal.client.conversation(chat) as conv:
if user.isdigit():
userinfo = await ultroid_bot.get_entity(int(user))
else:
userinfo = await ultroid_bot.get_entity(user)
except ValueError:
userinfo = None
if not isinstance(userinfo, types.User):
await event.edit("`Can't fetch the user...`")
await asyncio.sleep(10)
return await event.delete()
await event.edit("`Processing...`")
async with event.client.conversation("@SangMata_beta_bot") as conv:
try:
await conv.send_message(f"{userinfo.id}")
except YouBlockedUserError:
await catub(unblock("SangMata_beta_bot"))
await conv.send_message(f"{userinfo.id}")
responses = []
while True:
try:
msg = await conv.send_message(id)
response = await conv.get_response()
respond = await conv.get_response()
responds = await conv.get_response()
except YouBlockedUserError:
return await lol.edit("Please unblock @sangmatainfo_bot and try again")
if (
(response and response.text == "No records found")
or (respond and respond.text == "No records found")
or (responds and responds.text == "No records found")
):
await lol.edit("No records found for this user")
await steal.client.delete_messages(conv.chat_id, [msg.id, response.id])
elif response.text.startswith("🔗"):
await lol.edit(respond.message)
await lol.reply(responds.message)
elif respond.text.startswith("🔗"):
await lol.edit(response.message)
await lol.reply(responds.message)
else:
await lol.edit(respond.message)
await lol.reply(response.message)
await steal.client.delete_messages(
conv.chat_id,
[msg.id, responds.id, respond.id, response.id],
)
except AsyncTimeout:
await lol.edit("Error: @SangMataInfo_bot is not responding!.")
response = await conv.get_response(timeout=2)
except asyncio.TimeoutError:
break
responses.append(response.text)
await event.client.send_read_acknowledge(conv.chat_id)
if not responses:
await event.edit("`Bot can't fetch results`")
await asyncio.sleep(10)
await event.delete()
if "No records found" in responses or "No data available" in responses:
await event.edit("`The user doesn't have any record`")
await asyncio.sleep(10)
await event.delete()
names, usernames = sanga_seperator(responses)
check = (usernames, "Username") if cmd == "u" else (names, "Name")
user_name = (
f"{userinfo.first_name} {userinfo.last_name}"
if userinfo.last_name
else userinfo.first_name
)
output = f"**➜ User Info :** {mentionuser(user_name, userinfo.id)}\n**➜ {check[1]} History :**\n{check[0]}"
await event.edit(output)
@ultroid_cmd(pattern="webshot( (.*)|$)")

View File

@@ -166,15 +166,21 @@ async def twarns(e):
async def warnset(e):
ok = e.pattern_match.group(1).strip()
if not ok:
return await e.eor("stuff")
return await e.eor("Invalid format. Correct usage: .setwarns <number>|<action>")
if "|" in ok:
try:
number, action = int(ok.split()[0]), ok.split()[1]
except BaseException:
return await e.eor(get_string("schdl_2"), time=5)
if ("ban" or "kick" or "mute") not in action:
return await e.eor("`Only mute / ban / kick option suported`", time=5)
number, action = ok.split("|")
number = int(number.strip())
action = action.strip()
except ValueError:
return await e.eor(
"Invalid format. Correct usage: .setwarns <number>|<action>", time=5
)
if action not in ["ban", "mute", "kick"]:
return await e.eor("Only mute / ban / kick options are supported", time=5)
udB.set_key("SETWARN", f"{number} {action}")
await e.eor(f"Done Your Warn Count is now {number} and Action is {action}")
await e.eor(f"Done. Your Warn Count is now {number} and Action is {action}")
else:
await e.eor(get_string("schdl_2"), time=5)
await e.eor(
"Invalid format. Correct usage: .setwarns <number>|<action>", time=5
)

176
plugins/weather.py Normal file
View File

@@ -0,0 +1,176 @@
# Ultroid ~ UserBot
# Copyright (C) 2023-2024 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/>.
"""
**Get Weather Data using OpenWeatherMap API**
❍ Commands Available -
• `{i}weather` <city name>
Shows the Weather of Cities
• `{i}air` <city name>
Shows the Air Condition of Cities
"""
import datetime
import time
from datetime import timedelta
import aiohttp
import pytz
from . import async_searcher, get_string, udB, ultroid_cmd
async def get_timezone(offset_seconds, use_utc=False):
offset = timedelta(seconds=offset_seconds)
hours, remainder = divmod(offset.seconds, 3600)
sign = "+" if offset.total_seconds() >= 0 else "-"
timezone = "UTC" if use_utc else "GMT"
if use_utc:
for m in pytz.all_timezones:
tz = pytz.timezone(m)
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
return f"{m} ({timezone}{sign}{hours:02d})"
else:
for m in pytz.all_timezones:
tz = pytz.timezone(m)
if m.startswith("Australia/"):
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
return f"{m} ({timezone}{sign}{hours:02d})"
for m in pytz.all_timezones:
tz = pytz.timezone(m)
now = datetime.datetime.now(tz)
if now.utcoffset() == offset:
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:
async with session.get(url) as response:
data = await response.json()
if "list" in data:
air_pollution = data["list"][0]
return air_pollution
else:
return None
@ultroid_cmd(pattern="weather ?(.*)")
async def weather(event):
if event.fwd_from:
return
msg = await event.eor(get_string("com_1"))
x = udB.get_key("OPENWEATHER_API")
if x is None:
await event.eor(
"No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",
time=8,
)
return
input_str = event.pattern_match.group(1)
if not input_str:
await event.eor("No Location was Given...", time=5)
return
elif input_str == "butler":
await event.eor("search butler,au for australila", time=5)
sample_url = f"https://api.openweathermap.org/data/2.5/weather?q={input_str}&APPID={x}&units=metric"
try:
response_api = await async_searcher(sample_url, re_json=True)
if response_api["cod"] == 200:
country_time_zone = int(response_api["timezone"])
tz = f"{await get_timezone(country_time_zone)}"
sun_rise_time = int(response_api["sys"]["sunrise"]) + country_time_zone
sun_set_time = int(response_api["sys"]["sunset"]) + country_time_zone
await msg.edit(
f"{response_api['name']}, {response_api['sys']['country']}\n\n"
f"╭────────────────•\n"
f"╰➢ **𝖶𝖾𝖺𝗍𝗁𝖾𝗋:** {response_api['weather'][0]['description']}\n"
f"╰➢ **𝖳𝗂𝗆𝖾𝗓𝗈𝗇𝖾:** {tz}\n"
f"╰➢ **𝖲𝗎𝗇𝗋𝗂𝗌𝖾:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_rise_time))}\n"
f"╰➢ **𝖲𝗎𝗇𝗌𝖾𝗍:** {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(sun_set_time))}\n"
f"╰➢ **𝖶𝗂𝗇𝖽:** {await getWindinfo(response_api['wind']['speed'], response_api['wind']['deg'])}\n"
f"╰➢ **𝖳𝖾𝗆𝗉𝖾𝗋𝖺𝗍𝗎𝗋𝖾:** {response_api['main']['temp']}°C\n"
f"╰➢ **𝖥𝖾𝖾𝗅𝗌 𝗅𝗂𝗄𝖾:** {response_api['main']['feels_like']}°C\n"
f"╰➢ **𝖬𝗂𝗇𝗂𝗆𝗎𝗆:** {response_api['main']['temp_min']}°C\n"
f"╰➢ **𝖬𝖺𝗑𝗂𝗆𝗎𝗆:** {response_api['main']['temp_max']}°C\n"
f"╰➢ **𝖯𝗋𝖾𝗌𝗌𝗎𝗋𝖾:** {response_api['main']['pressure']} hPa\n"
f"╰➢ **𝖧𝗎𝗆𝗂𝖽𝗂𝗍𝗒:** {response_api['main']['humidity']}%\n"
f"╰➢ **𝖵𝗂𝗌𝗂𝖻𝗂𝗅𝗂𝗍𝗒:** {response_api['visibility']} m\n"
f"╰➢ **𝖢𝗅𝗈𝗎𝖽𝗌:** {response_api['clouds']['all']}%\n"
f"╰────────────────•\n\n"
)
else:
await msg.edit(response_api["message"])
except Exception as e:
await event.eor(f"An unexpected error occurred: {str(e)}", time=5)
@ultroid_cmd(pattern="air ?(.*)")
async def air_pollution(event):
if event.fwd_from:
return
msg = await event.eor(get_string("com_1"))
x = udB.get_key("OPENWEATHER_API")
if x is None:
await event.eor(
"No API found. Get One from [Here](https://api.openweathermap.org)\nAnd Add it in OPENWEATHER_API Redis Key",
time=8,
)
return
input_str = event.pattern_match.group(1)
if not input_str:
await event.eor("`No Location was Given...`", time=5)
return
if input_str.lower() == "perth":
geo_url = f"https://geocode.xyz/perth%20au?json=1"
else:
geo_url = f"https://geocode.xyz/{input_str}?json=1"
geo_data = await async_searcher(geo_url, re_json=True)
try:
longitude = geo_data["longt"]
latitude = geo_data["latt"]
except KeyError as e:
LOGS.info(e)
await event.eor("`Unable to find coordinates for the given location.`", time=5)
return
try:
city = geo_data["standard"]["city"]
prov = geo_data["standard"]["prov"]
except KeyError as e:
LOGS.info(e)
await event.eor("`Unable to find city for the given coordinates.`", time=5)
return
air_pollution_data = await get_air_pollution_data(latitude, longitude, x)
if air_pollution_data is None:
await event.eor(
"`Unable to fetch air pollution data for the given location.`", time=5
)
return
await msg.edit(
f"{city}, {prov}\n\n"
f"╭────────────────•\n"
f"╰➢ **𝖠𝖰𝖨:** {air_pollution_data['main']['aqi']}\n"
f"╰➢ **𝖢𝖺𝗋𝖻𝗈𝗇 𝖬𝗈𝗇𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['co']}µg/m³\n"
f"╰➢ **𝖭𝗈𝗂𝗍𝗋𝗈𝗀𝖾𝗇 𝖬𝗈𝗇𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['no']}µg/m³\n"
f"╰➢ **𝖭𝗂𝗍𝗋𝗈𝗀𝖾𝗇 𝖣𝗂𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['no2']}µg/m³\n"
f"╰➢ **𝖮𝗓𝗈𝗇𝖾:** {air_pollution_data['components']['o3']}µg/m³\n"
f"╰➢ **𝖲𝗎𝗅𝗉𝗁𝗎𝗋 𝖣𝗂𝗈𝗑𝗂𝖽𝖾:** {air_pollution_data['components']['so2']}µg/m³\n"
f"╰➢ **𝖠𝗆𝗆𝗈𝗇𝗂𝖺:** {air_pollution_data['components']['nh3']}µg/m³\n"
f"╰➢ **𝖥𝗂𝗇𝖾 𝖯𝖺𝗋𝗍𝗂𝖼𝗅𝖾𝗌 (PM₂.₅):** {air_pollution_data['components']['pm2_5']}\n"
f"╰➢ **𝖢𝗈𝖺𝗋𝗌𝖾 𝖯𝖺𝗋𝗍𝗂𝖼𝗅𝖾𝗌 (PM₁₀):** {air_pollution_data['components']['pm10']}\n"
f"╰────────────────•\n\n"
)

View File

@@ -19,9 +19,7 @@ from pyUltroid.fns.tools import _webupload_cache
from . import Button, asst, get_string, ultroid_cmd
@ultroid_cmd(
pattern="webupload( (.*)|$)",
)
@ultroid_cmd(pattern="webupload( (.*)|$)")
async def _(event):
xx = await event.eor(get_string("com_1"))
match = event.pattern_match.group(1).strip()
@@ -29,7 +27,7 @@ async def _(event):
_webupload_cache.update({int(event.chat_id): {}})
if match:
if not os.path.exists(match):
return await xx.eor("`File doesn't exist.`")
return await xx.eor("File doesn't exist.")
_webupload_cache[event.chat_id][event.id] = match
elif event.reply_to_msg_id:
reply = await event.get_reply_message()
@@ -42,7 +40,7 @@ async def _(event):
)
_webupload_cache[int(event.chat_id)][int(event.id)] = file.name
else:
return await xx.eor("`Reply to file or give file path...`")
return await xx.eor("Reply to file or give file path...")
if not event.client._bot:
results = await event.client.inline_query(
asst.me.username, f"fl2lnk {event.chat_id}:{event.id}"
@@ -54,16 +52,16 @@ async def _(event):
__cache = f"{event.chat_id}:{event.id}"
buttons = [
[
Button.inline("anonfiles", data=f"flanonfiles//{__cache}"),
Button.inline("catbox", data=f"flcatbox//{__cache}"),
Button.inline("transfer", data=f"fltransfer//{__cache}"),
],
[
Button.inline("bayfiles", data=f"flbayfiles//{__cache}"),
Button.inline("x0.at", data=f"flx0.at//{__cache}"),
Button.inline("filebin", data=f"flfilebin//{__cache}"),
Button.inline("0x0.st", data=f"fl0x0.st//{__cache}"),
],
[
Button.inline("file.io", data=f"flfile.io//{__cache}"),
Button.inline("siasky", data=f"flsiasky//{__cache}"),
],
]
await xx.edit("**Choose Server to Upload File...**", buttons=buttons)
await xx.edit("Choose Server to Upload File...", buttons=buttons)

View File

@@ -233,34 +233,72 @@ _webupload_cache = {}
async def webuploader(chat_id: int, msg_id: int, uploader: str):
file = _webupload_cache[int(chat_id)][int(msg_id)]
LOGS.info("webuploader function called with uploader: %s", uploader)
if chat_id in _webupload_cache and msg_id in _webupload_cache[chat_id]:
file = _webupload_cache[chat_id][msg_id]
else:
return "File not found in cache."
sites = {
"anonfiles": {"url": "https://api.anonfiles.com/upload", "json": True},
"siasky": {"url": "https://siasky.net/skynet/skyfile", "json": True},
"file.io": {"url": "https://file.io", "json": True},
"bayfiles": {"url": "https://api.bayfiles.com/upload", "json": True},
"x0.at": {"url": "https://x0.at/", "json": False},
"file.io": {"url": "https://file.io/", "json": True},
"0x0.st": {"url": "https://0x0.st", "json": False},
"transfer": {"url": "https://transfer.sh", "json": False},
"catbox": {"url": "https://catbox.moe/user/api.php", "json": False},
"filebin": {"url": "https://filebin.net", "json": False},
}
if uploader and uploader in sites:
url = sites[uploader]["url"]
json = sites[uploader]["json"]
with open(file, "rb") as data:
# todo: add progress bar
status = await async_searcher(
url, data={"file": data.read()}, post=True, re_json=json
)
if isinstance(status, dict):
if "skylink" in status:
return f"https://siasky.net/{status['skylink']}"
if status["status"] == 200 or status["status"] is True:
json_format = sites[uploader]["json"]
else:
return "Uploader not supported or invalid."
files = {"file": open(file, "rb")} # Adjusted for both formats
try:
if uploader == "filebin":
cmd = f"curl -X POST --data-binary '@{file}' -H 'filename: \"{file}\"' \"{url}\""
response = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if response.returncode == 0:
response_json = json.loads(response.stdout)
bin_id = response_json.get("bin", {}).get("id")
if bin_id:
filebin_url = f"https://filebin.net/{bin_id}"
return filebin_url
else:
return "Failed to extract bin ID from Filebin response"
else:
return f"Failed to upload file to Filebin: {response.stderr.strip()}"
elif uploader == "catbox":
cmd = f"curl -F reqtype=fileupload -F time=24h -F 'fileToUpload=@{file}' {url}"
elif uploader == "0x0.st":
cmd = f"curl -F 'file=@{file}' {url}"
elif uploader == "file.io" or uploader == "siasky":
try:
link = status["link"]
except KeyError:
link = status["data"]["file"]["url"]["short"]
return link
del _webupload_cache[int(chat_id)][int(msg_id)]
return status
status = await async_searcher(
url, data=files, post=True, re_json=json_format
)
except Exception as e:
return f"Failed to upload file: {e}"
if isinstance(status, dict):
if "skylink" in status:
return f"https://siasky.net/{status['skylink']}"
if status.get("status") == 200:
return status.get("link")
else:
raise ValueError("Uploader not supported")
response = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if response.returncode == 0:
return response.stdout.strip()
else:
return f"Failed to upload file: {response.stderr.strip()}"
except Exception as e:
return f"Failed to upload file: {e}"
del _webupload_cache.get(chat_id, {})[msg_id]
return "Failed to get valid URL for the uploaded file."
def get_all_files(path, extension=None):