diff --git a/plugins/admintools.py b/plugins/admintools.py
index 0d402ff2d6..8853c9d36f 100644
--- a/plugins/admintools.py
+++ b/plugins/admintools.py
@@ -392,12 +392,13 @@ async def _(e):
msg = await e.get_reply_message()
name = msg.sender
- try:
- await e.client.delete_messages(e.chat_id, from_user=msg.sender_id)
- await e.eor(get_string("purgeall_2").format(name.first_name), time=5)
- except Exception as er:
- return await e.eor(str(er), time=5)
-
+ async for message in e.client.iter_messages(e.chat_id, from_user=msg.sender.id):
+ try:
+ await e.client.delete_messages(e.chat_id, [message.id])
+ except Exception as er:
+ await e.eor(str(er), time=5)
+ return
+ await e.eor(get_string("purgeall_2").format(name.first_name), time=5)
@ultroid_cmd(pattern="pinned", manager=True, groups_only=True)
async def djshsh(event):
diff --git a/plugins/beautify.py b/plugins/beautify.py
index 903ab13197..60eb2d8e72 100644
--- a/plugins/beautify.py
+++ b/plugins/beautify.py
@@ -108,7 +108,9 @@ async def pass_on(ult):
try:
from playwright.async_api import async_playwright
except ImportError:
- await ult.eor("`playwright` is not installed!\nPlease install it to use this command..")
+ await ult.eor(
+ "`playwright` is not installed!\nPlease install it to use this command.."
+ )
return
proc = await ult.eor(get_string("com_1"))
spli = ult.text.split()
@@ -139,26 +141,21 @@ async def pass_on(ult):
text = msg.message
title = get_display_name(msg.sender)
name = token_hex(8) + ".png"
- data = {
- "darkMode": dark,
- "theme": theme,
- "title": title
- }
+ data = {"darkMode": dark, "theme": theme, "title": title}
url = f"https://ray.so/#{urlencode(data)}"
async with async_playwright() as play:
chrome = await play.chromium.launch()
page = await chrome.new_page()
await page.goto(url)
await page.wait_for_load_state("networkidle")
- elem = await page.query_selector("textarea[class='Editor_textarea__sAyL_']")
+ await page.wait_for_selector("div[class='Editor_editor__Jz9sW']")
+ elem = await page.query_selector("div[class='Editor_editor__Jz9sW']")
await elem.type(text)
- button = await page.query_selector("button[class='ExportButton_button__d___t']")
+ button = await page.query_selector(".ExportButton_button__MA4PI")
await button.click()
async with page.expect_download() as dl:
dled = await dl.value
await dled.save_as(name)
- await proc.reply(
- file=name
- )
+ await proc.reply(file=name)
await proc.try_delete()
os.remove(name)
diff --git a/plugins/bot.py b/plugins/bot.py
index f8d5367e08..e5f4389d9e 100644
--- a/plugins/bot.py
+++ b/plugins/bot.py
@@ -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()
diff --git a/plugins/stickertools.py b/plugins/stickertools.py
index 9191aa90e6..01e7db1abb 100644
--- a/plugins/stickertools.py
+++ b/plugins/stickertools.py
@@ -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
# .
"""
-โ Commands Available -
+โ Commands Available -
โข `{i}destroy `
To destroy the sticker.
@@ -61,10 +61,10 @@
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(
diff --git a/plugins/tools.py b/plugins/tools.py
index a1f3628236..e61831f0d7 100644
--- a/plugins/tools.py
+++ b/plugins/tools.py
@@ -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( (.*)|$)")
diff --git a/plugins/warn.py b/plugins/warn.py
index b6ffcc108f..76822093a0 100644
--- a/plugins/warn.py
+++ b/plugins/warn.py
@@ -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 |")
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 |", 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 |", time=5
+ )
diff --git a/plugins/weather.py b/plugins/weather.py
new file mode 100644
index 0000000000..26420330ec
--- /dev/null
+++ b/plugins/weather.py
@@ -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
+# .
+
+"""
+**Get Weather Data using OpenWeatherMap API**
+โ Commands Available -
+
+โข `{i}weather`
+ Shows the Weather of Cities
+
+โข `{i}air`
+ 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"
+ )
diff --git a/plugins/webupload.py b/plugins/webupload.py
index 2a6c5f57ee..146d001412 100644
--- a/plugins/webupload.py
+++ b/plugins/webupload.py
@@ -19,17 +19,15 @@
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"))
+ xx = await event.eor(get_pstring("com_1"))
match = event.pattern_match.group(1).strip()
if event.chat_id not in _webupload_cache:
_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)
diff --git a/pyUltroid/fns/tools.py b/pyUltroid/fns/tools.py
index 2571314329..428433c938 100644
--- a/pyUltroid/fns/tools.py
+++ b/pyUltroid/fns/tools.py
@@ -233,34 +233,72 @@ async def saavn_search(query: str):
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):