chore(userbot): apply ruff check --fix and ruff format
- ruff check --fix: 210 auto-fixed errors (import sorting, trailing whitespace, unused imports, f-string fixups, deprecated annotations) - ruff format: 104 files reformatted to consistent style - 268 non-auto-fixable issues remain (S113 requests timeout, etc.)
This commit is contained in:
@@ -3,10 +3,10 @@ from flask import Flask
|
|||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route('/')
|
||||||
def hello_world():
|
def hello_world():
|
||||||
return "This is Moon"
|
return 'This is Moon'
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == '__main__':
|
||||||
app.run()
|
app.run()
|
||||||
|
|||||||
+36
-41
@@ -1,83 +1,80 @@
|
|||||||
import re
|
|
||||||
import requests
|
|
||||||
import random
|
import random
|
||||||
|
import re
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
|
import requests
|
||||||
from bs4 import BeautifulSoup as bs
|
from bs4 import BeautifulSoup as bs
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message, InputMediaPhoto
|
|
||||||
from pyrogram.errors import RPCError
|
from pyrogram.errors import RPCError
|
||||||
|
from pyrogram.types import InputMediaPhoto, Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("icon", prefix) & filters.me)
|
@Client.on_message(filters.command('icon', prefix) & filters.me)
|
||||||
async def search_icon(_, message: Message):
|
async def search_icon(_, message: Message):
|
||||||
if not len(message.command) == 2:
|
if not len(message.command) == 2:
|
||||||
return await message.edit_text(
|
return await message.edit_text('Please provide some text to search icons from Flaticon.com.')
|
||||||
"Please provide some text to search icons from Flaticon.com."
|
|
||||||
)
|
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
|
|
||||||
await message.edit_text("Searching for icons...")
|
await message.edit_text('Searching for icons...')
|
||||||
search_query = query.replace(" ", "%20")
|
search_query = query.replace(' ', '%20')
|
||||||
url = f"https://www.flaticon.com/search?word={search_query}"
|
url = f'https://www.flaticon.com/search?word={search_query}'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
html_content = requests.get(url).text
|
html_content = requests.get(url).text
|
||||||
soup = bs(html_content, "html.parser")
|
soup = bs(html_content, 'html.parser')
|
||||||
results = soup.find_all(
|
results = soup.find_all(
|
||||||
"img",
|
'img',
|
||||||
src=re.compile(r"https://cdn-icons-png.flaticon.com/128/[0-9]+/[0-9]+.png"),
|
src=re.compile(r'https://cdn-icons-png.flaticon.com/128/[0-9]+/[0-9]+.png'),
|
||||||
)
|
)
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
return await message.edit("No results found.")
|
return await message.edit('No results found.')
|
||||||
|
|
||||||
random.shuffle(results)
|
random.shuffle(results)
|
||||||
icons = []
|
icons = []
|
||||||
for i in range(5):
|
for i in range(5):
|
||||||
icons.append(results[i]["src"].replace("128", "512"))
|
icons.append(results[i]['src'].replace('128', '512'))
|
||||||
|
|
||||||
for icon in icons:
|
for icon in icons:
|
||||||
await message.reply_document(icon)
|
await message.reply_document(icon)
|
||||||
|
|
||||||
return await message.delete()
|
return await message.delete()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(f"An error occurred: {e}")
|
await message.edit(f'An error occurred: {e}')
|
||||||
print(f"Error: {e}")
|
print(f'Error: {e}')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("freepik", prefix) & filters.me)
|
@Client.on_message(filters.command('freepik', prefix) & filters.me)
|
||||||
async def freepik_search(client: Client, message: Message):
|
async def freepik_search(client: Client, message: Message):
|
||||||
parts = message.text.split(" ", 1)
|
parts = message.text.split(' ', 1)
|
||||||
if len(parts) < 2:
|
if len(parts) < 2:
|
||||||
await message.edit_text("Please provide a search query!")
|
await message.edit_text('Please provide a search query!')
|
||||||
return
|
return
|
||||||
|
|
||||||
query = parts[1]
|
query = parts[1]
|
||||||
limit = 5
|
limit = 5
|
||||||
if " ; " in query:
|
if ' ; ' in query:
|
||||||
match, limit_str = query.split(" ; ", 1)
|
match, limit_str = query.split(' ; ', 1)
|
||||||
try:
|
try:
|
||||||
limit = int(limit_str)
|
limit = int(limit_str)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await message.edit_text("Invalid limit! Using the default value of 5.")
|
await message.edit_text('Invalid limit! Using the default value of 5.')
|
||||||
else:
|
else:
|
||||||
match = query
|
match = query
|
||||||
|
|
||||||
match = match.replace(" ", "%20")
|
match = match.replace(' ', '%20')
|
||||||
await message.edit_text("Searching Freepik...")
|
await message.edit_text('Searching Freepik...')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
url = f"https://www.freepik.com/api/regular/search?locale=en&term={match}"
|
url = f'https://www.freepik.com/api/regular/search?locale=en&term={match}'
|
||||||
json_content = requests.get(url).json()
|
json_content = requests.get(url).json()
|
||||||
results = []
|
results = []
|
||||||
for i in json_content["items"]:
|
for i in json_content['items']:
|
||||||
results.append(i["preview"]["url"])
|
results.append(i['preview']['url'])
|
||||||
|
|
||||||
if results is None:
|
if results is None:
|
||||||
return await message.edit_text("No results found.")
|
return await message.edit_text('No results found.')
|
||||||
|
|
||||||
random.shuffle(results)
|
random.shuffle(results)
|
||||||
img_urls = results[:limit]
|
img_urls = results[:limit]
|
||||||
@@ -89,27 +86,25 @@ async def freepik_search(client: Client, message: Message):
|
|||||||
media_group.append(InputMediaPhoto(media=BytesIO(icon.content)))
|
media_group.append(InputMediaPhoto(media=BytesIO(icon.content)))
|
||||||
|
|
||||||
if not media_group:
|
if not media_group:
|
||||||
await message.edit_text("No images could be downloaded.")
|
await message.edit_text('No images could be downloaded.')
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await client.send_media_group(chat_id=message.chat.id, media=media_group)
|
await client.send_media_group(chat_id=message.chat.id, media=media_group)
|
||||||
except RPCError:
|
except RPCError:
|
||||||
await message.edit_text(
|
await message.edit_text('Failed to send some images. Retrying individually...')
|
||||||
"Failed to send some images. Retrying individually..."
|
|
||||||
)
|
|
||||||
for media in media_group:
|
for media in media_group:
|
||||||
try:
|
try:
|
||||||
await message.reply_photo(photo=media.media)
|
await message.reply_photo(photo=media.media)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"Error sending image: {e}")
|
await message.edit_text(f'Error sending image: {e}')
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"Failed to fetch data: {e}")
|
await message.edit_text(f'Failed to fetch data: {e}')
|
||||||
print(f"Error: {e}")
|
print(f'Error: {e}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["icons"] = {
|
modules_help['icons'] = {
|
||||||
"icon [query]": "Search for icons on Flaticon.",
|
'icon [query]': 'Search for icons on Flaticon.',
|
||||||
"freepik [query] [limit]": "Search for images on Freepik. Limit is optional and defaults to 5.",
|
'freepik [query] [limit]': 'Search for images on Freepik. Limit is optional and defaults to 5.',
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-21
@@ -1,52 +1,47 @@
|
|||||||
import os
|
|
||||||
import base64
|
import base64
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["imgur"], prefix) & filters.me)
|
@Client.on_message(filters.command(['imgur'], prefix) & filters.me)
|
||||||
async def imgur(_, message: Message):
|
async def imgur(_, message: Message):
|
||||||
# Check if a reply exists
|
# Check if a reply exists
|
||||||
msg = await message.edit_text("🎉 Please wait. trying to upload...")
|
msg = await message.edit_text('🎉 Please wait. trying to upload...')
|
||||||
if message.reply_to_message and message.reply_to_message.photo:
|
if message.reply_to_message and message.reply_to_message.photo:
|
||||||
# Download the photo
|
# Download the photo
|
||||||
photo_path = await message.reply_to_message.download()
|
photo_path = await message.reply_to_message.download()
|
||||||
# Read the photo file and encode as base64
|
# Read the photo file and encode as base64
|
||||||
with open(photo_path, "rb") as file:
|
with open(photo_path, 'rb') as file:
|
||||||
data = file.read()
|
data = file.read()
|
||||||
base64_data = base64.b64encode(data)
|
base64_data = base64.b64encode(data)
|
||||||
# Set API endpoint and headers for image upload
|
# Set API endpoint and headers for image upload
|
||||||
url = "https://api.imgur.com/3/image"
|
url = 'https://api.imgur.com/3/image'
|
||||||
headers = {"Authorization": "Client-ID a10ad04550b0648"}
|
headers = {'Authorization': 'Client-ID a10ad04550b0648'}
|
||||||
# Upload image to Imgur and get URL
|
# Upload image to Imgur and get URL
|
||||||
response = requests.post(url, headers=headers, data={"image": base64_data})
|
response = requests.post(url, headers=headers, data={'image': base64_data})
|
||||||
result = response.json()
|
result = response.json()
|
||||||
await msg.edit_text(result["data"]["link"])
|
await msg.edit_text(result['data']['link'])
|
||||||
elif message.reply_to_message and message.reply_to_message.animation:
|
elif message.reply_to_message and message.reply_to_message.animation:
|
||||||
# Download the animation (GIF)
|
# Download the animation (GIF)
|
||||||
animation_path = await message.reply_to_message.download()
|
animation_path = await message.reply_to_message.download()
|
||||||
# Read the animation file and encode as base64
|
# Read the animation file and encode as base64
|
||||||
with open(animation_path, "rb") as file:
|
with open(animation_path, 'rb') as file:
|
||||||
data = file.read()
|
data = file.read()
|
||||||
base64_data = base64.b64encode(data)
|
base64_data = base64.b64encode(data)
|
||||||
# Set API endpoint and headers for animation upload
|
# Set API endpoint and headers for animation upload
|
||||||
url = "https://api.imgur.com/3/image"
|
url = 'https://api.imgur.com/3/image'
|
||||||
headers = {"Authorization": "Client-ID a10ad04550b0648"}
|
headers = {'Authorization': 'Client-ID a10ad04550b0648'}
|
||||||
# Upload animation to Imgur and get URL
|
# Upload animation to Imgur and get URL
|
||||||
response = requests.post(url, headers=headers, data={"image": base64_data})
|
response = requests.post(url, headers=headers, data={'image': base64_data})
|
||||||
result = response.json()
|
result = response.json()
|
||||||
await msg.edit_text(result["data"]["link"])
|
await msg.edit_text(result['data']['link'])
|
||||||
else:
|
else:
|
||||||
await msg.edit_text(
|
await msg.edit_text('Please reply to a photo or animation (GIF) to upload to Imgur.')
|
||||||
"Please reply to a photo or animation (GIF) to upload to Imgur."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
modules_help["imgur"] = {
|
modules_help['imgur'] = {
|
||||||
"imgur [img]*": "upload a photo or animation (GIF) to imgur",
|
'imgur [img]*': 'upload a photo or animation (GIF) to imgur',
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-26
@@ -1,55 +1,47 @@
|
|||||||
from pyrogram import Client, filters
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
from utils.misc import prefix, modules_help
|
|
||||||
|
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageNotModified
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import pygments
|
import pygments
|
||||||
from pygments.formatters import ImageFormatter
|
from pygments.formatters import ImageFormatter
|
||||||
from pygments.lexers import Python3Lexer
|
from pygments.lexers import Python3Lexer
|
||||||
|
from pyrogram import Client, filters
|
||||||
|
from pyrogram.errors import MessageNotModified
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ncode", prefix) & filters.me)
|
@Client.on_message(filters.command('ncode', prefix) & filters.me)
|
||||||
async def coder_print(client, message: Message):
|
async def coder_print(client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
reply_message = message.reply_to_message
|
reply_message = message.reply_to_message
|
||||||
if reply_message.media:
|
if reply_message.media:
|
||||||
download_path = await client.download_media(reply_message)
|
download_path = await client.download_media(reply_message)
|
||||||
with open(download_path, "r") as file:
|
with open(download_path) as file:
|
||||||
code = file.read()
|
code = file.read()
|
||||||
if os.path.exists(download_path):
|
if os.path.exists(download_path):
|
||||||
os.remove(download_path)
|
os.remove(download_path)
|
||||||
pygments.highlight(
|
pygments.highlight(
|
||||||
f"{code}",
|
f'{code}',
|
||||||
Python3Lexer(),
|
Python3Lexer(),
|
||||||
ImageFormatter(font_name="DejaVu Sans Mono", line_numbers=True),
|
ImageFormatter(font_name='DejaVu Sans Mono', line_numbers=True),
|
||||||
"result.png",
|
'result.png',
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
sent_message = await message.edit_text(
|
sent_message = await message.edit_text('Pasting this code on my page...')
|
||||||
"Pasting this code on my page..."
|
|
||||||
)
|
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
document="result.png",
|
document='result.png',
|
||||||
caption="Code highlighted by Pygments",
|
caption='Code highlighted by Pygments',
|
||||||
reply_to_message_id=message.id,
|
reply_to_message_id=message.id,
|
||||||
)
|
)
|
||||||
except MessageNotModified:
|
except MessageNotModified:
|
||||||
pass
|
pass
|
||||||
await sent_message.delete()
|
await sent_message.delete()
|
||||||
if os.path.exists("result.png"):
|
if os.path.exists('result.png'):
|
||||||
os.remove("result.png")
|
os.remove('result.png')
|
||||||
else:
|
else:
|
||||||
return await message.reply_text("Please reply to a text or a file.")
|
return await message.reply_text('Please reply to a text or a file.')
|
||||||
else:
|
else:
|
||||||
return await message.reply_text("Please reply to a text or a file.")
|
return await message.reply_text('Please reply to a text or a file.')
|
||||||
|
|
||||||
|
|
||||||
modules_help["ncode"] = {
|
modules_help['ncode'] = {'ncode': 'Highlight the code using Pygments and send it as an image.'}
|
||||||
"ncode": "Highlight the code using Pygments and send it as an image."
|
|
||||||
}
|
|
||||||
|
|||||||
+24
-35
@@ -1,13 +1,14 @@
|
|||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message, InputMediaPhoto
|
|
||||||
from io import BytesIO
|
|
||||||
from PIL import Image
|
|
||||||
import requests
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from PIL import Image
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import InputMediaPhoto, Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
# Pinterest API URL
|
# Pinterest API URL
|
||||||
API_URL = "https://bk9.fun/pinterest/search?q="
|
API_URL = 'https://bk9.fun/pinterest/search?q='
|
||||||
|
|
||||||
|
|
||||||
def resize_image(image_bytes):
|
def resize_image(image_bytes):
|
||||||
@@ -17,13 +18,13 @@ def resize_image(image_bytes):
|
|||||||
if img.size > max_size:
|
if img.size > max_size:
|
||||||
img.thumbnail(max_size)
|
img.thumbnail(max_size)
|
||||||
output = BytesIO()
|
output = BytesIO()
|
||||||
img.save(output, format="JPEG")
|
img.save(output, format='JPEG')
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
return output
|
return output
|
||||||
image_bytes.seek(0) # Reset pointer if not resized
|
image_bytes.seek(0) # Reset pointer if not resized
|
||||||
return image_bytes
|
return image_bytes
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error resizing image: {e}")
|
print(f'Error resizing image: {e}')
|
||||||
return image_bytes
|
return image_bytes
|
||||||
|
|
||||||
|
|
||||||
@@ -34,69 +35,57 @@ async def download_image(url):
|
|||||||
img_bytes = BytesIO(response.content)
|
img_bytes = BytesIO(response.content)
|
||||||
return resize_image(img_bytes)
|
return resize_image(img_bytes)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error downloading image: {e}")
|
print(f'Error downloading image: {e}')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("pinterest", prefix) & filters.me)
|
@Client.on_message(filters.command('pinterest', prefix) & filters.me)
|
||||||
async def pinterest_search(client: Client, message: Message):
|
async def pinterest_search(client: Client, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit(
|
await message.edit('Usage: `pinterest [number] <query>`', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Usage: `pinterest [number] <query>`", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
num_pics = int(message.command[1]) if message.command[1].isdigit() else 10
|
num_pics = int(message.command[1]) if message.command[1].isdigit() else 10
|
||||||
query = " ".join(message.command[2:])
|
query = ' '.join(message.command[2:])
|
||||||
|
|
||||||
# Update status
|
# Update status
|
||||||
status_message = await message.edit(
|
status_message = await message.edit('Searching for images...', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Searching for images...", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
url = f"{API_URL}{query}"
|
url = f'{API_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if data.get("status"):
|
if data.get('status'):
|
||||||
urls = [item["images_url"] for item in data.get("BK9", [])[:num_pics]]
|
urls = [item['images_url'] for item in data.get('BK9', [])[:num_pics]]
|
||||||
images = [download_image(img_url) for img_url in urls]
|
images = [download_image(img_url) for img_url in urls]
|
||||||
|
|
||||||
# Download images
|
# Download images
|
||||||
downloaded_images = await asyncio.gather(*images)
|
downloaded_images = await asyncio.gather(*images)
|
||||||
|
|
||||||
media = [
|
media = [InputMediaPhoto(media=img_bytes) for img_bytes in downloaded_images if img_bytes]
|
||||||
InputMediaPhoto(media=img_bytes)
|
|
||||||
for img_bytes in downloaded_images
|
|
||||||
if img_bytes
|
|
||||||
]
|
|
||||||
|
|
||||||
if media:
|
if media:
|
||||||
await status_message.edit(
|
await status_message.edit('Uploading pictures...', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Uploading pictures...", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
while media:
|
while media:
|
||||||
batch = media[:10]
|
batch = media[:10]
|
||||||
media = media[10:]
|
media = media[10:]
|
||||||
await message.reply_media_group(batch)
|
await message.reply_media_group(batch)
|
||||||
await status_message.delete() # Delete status message after uploading
|
await status_message.delete() # Delete status message after uploading
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit('No valid images found.', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"No valid images found.", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit(
|
||||||
"No images found for the given query.",
|
'No images found for the given query.',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit(
|
||||||
"An error occurred, please try again later.",
|
'An error occurred, please try again later.',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["pinterest"] = {
|
modules_help['pinterest'] = {
|
||||||
"pinterest [number]* [query]": "Get images from Pinterest. Default number of images is 10",
|
'pinterest [number]* [query]': 'Get images from Pinterest. Default number of images is 10',
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-32
@@ -1,26 +1,27 @@
|
|||||||
from utils.misc import modules_help, prefix
|
import os
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
from modules.url import generate_screenshot
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from modules.url import generate_screenshot
|
from utils.misc import modules_help, prefix
|
||||||
import os
|
|
||||||
|
|
||||||
# API endpoints for reverse image search engines
|
# API endpoints for reverse image search engines
|
||||||
SEARCH_ENGINES = {
|
SEARCH_ENGINES = {
|
||||||
"lens": "https://lens.google.com/uploadbyurl?url={image}",
|
'lens': 'https://lens.google.com/uploadbyurl?url={image}',
|
||||||
"reverse": "https://www.google.com/searchbyimage?sbisrc=4chanx&image_url={image}&safe=off",
|
'reverse': 'https://www.google.com/searchbyimage?sbisrc=4chanx&image_url={image}&safe=off',
|
||||||
"tineye": "https://www.tineye.com/search?url={image}",
|
'tineye': 'https://www.tineye.com/search?url={image}',
|
||||||
"bing": "https://www.bing.com/images/search?view=detailv2&iss=sbi&form=SBIVSP&sbisrc=UrlPaste&q=imgurl:{image}",
|
'bing': 'https://www.bing.com/images/search?view=detailv2&iss=sbi&form=SBIVSP&sbisrc=UrlPaste&q=imgurl:{image}',
|
||||||
"yandex": "https://yandex.com/images/search?source=collections&&url={image}&rpt=imageview",
|
'yandex': 'https://yandex.com/images/search?source=collections&&url={image}&rpt=imageview',
|
||||||
"saucenao": "https://saucenao.com/search.php?db=999&url={image}",
|
'saucenao': 'https://saucenao.com/search.php?db=999&url={image}',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("risearch", prefix) & filters.reply)
|
@Client.on_message(filters.command('risearch', prefix) & filters.reply)
|
||||||
async def reverse_image_search(client: Client, message: Message):
|
async def reverse_image_search(client: Client, message: Message):
|
||||||
if not message.reply_to_message or not message.reply_to_message.photo:
|
if not message.reply_to_message or not message.reply_to_message.photo:
|
||||||
await message.reply_text(
|
await message.reply_text(
|
||||||
f"Please reply to an image with <code>{prefix}risearch [engine]</code> or <code>{prefix}risearch</code>."
|
f'Please reply to an image with <code>{prefix}risearch [engine]</code> or <code>{prefix}risearch</code>.'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -31,16 +32,14 @@ async def reverse_image_search(client: Client, message: Message):
|
|||||||
else list(SEARCH_ENGINES.keys())
|
else list(SEARCH_ENGINES.keys())
|
||||||
)
|
)
|
||||||
|
|
||||||
invalid_engines = [
|
invalid_engines = [engine for engine in engines_to_use if engine not in SEARCH_ENGINES]
|
||||||
engine for engine in engines_to_use if engine not in SEARCH_ENGINES
|
|
||||||
]
|
|
||||||
if invalid_engines:
|
if invalid_engines:
|
||||||
await message.reply_text(
|
await message.reply_text(
|
||||||
f"Invalid engine(s): {', '.join(invalid_engines)}. Available: {', '.join(SEARCH_ENGINES.keys())}"
|
f'Invalid engine(s): {", ".join(invalid_engines)}. Available: {", ".join(SEARCH_ENGINES.keys())}'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
processing_message = await message.edit_text("Processing the image...")
|
processing_message = await message.edit_text('Processing the image...')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Download and upload the image
|
# Download and upload the image
|
||||||
@@ -48,7 +47,7 @@ async def reverse_image_search(client: Client, message: Message):
|
|||||||
img_url = upload_image(photo_path)
|
img_url = upload_image(photo_path)
|
||||||
print(img_url)
|
print(img_url)
|
||||||
if not img_url:
|
if not img_url:
|
||||||
await processing_message.edit("Error: Could not upload the image.")
|
await processing_message.edit('Error: Could not upload the image.')
|
||||||
return
|
return
|
||||||
|
|
||||||
# Perform searches for the selected engines
|
# Perform searches for the selected engines
|
||||||
@@ -56,7 +55,7 @@ async def reverse_image_search(client: Client, message: Message):
|
|||||||
search_url = SEARCH_ENGINES[engine].format(image=img_url)
|
search_url = SEARCH_ENGINES[engine].format(image=img_url)
|
||||||
await send_screenshot(client, message, search_url, engine)
|
await send_screenshot(client, message, search_url, engine)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await processing_message.edit(f"An error occurred: {e}")
|
await processing_message.edit(f'An error occurred: {e}')
|
||||||
finally:
|
finally:
|
||||||
if photo_path and os.path.exists(photo_path):
|
if photo_path and os.path.exists(photo_path):
|
||||||
os.remove(photo_path)
|
os.remove(photo_path)
|
||||||
@@ -65,15 +64,13 @@ async def reverse_image_search(client: Client, message: Message):
|
|||||||
def upload_image(photo_path):
|
def upload_image(photo_path):
|
||||||
"""Uploads an image to tmpfiles.org and returns the direct download URL."""
|
"""Uploads an image to tmpfiles.org and returns the direct download URL."""
|
||||||
try:
|
try:
|
||||||
with open(photo_path, "rb") as image_file:
|
with open(photo_path, 'rb') as image_file:
|
||||||
response = requests.post(
|
response = requests.post('https://tmpfiles.org/api/v1/upload', files={'file': image_file})
|
||||||
"https://tmpfiles.org/api/v1/upload", files={"file": image_file}
|
|
||||||
)
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
url = data["data"]["url"]
|
url = data['data']['url']
|
||||||
pic_url = url.split("/")[-2] + "/" + url.split("/")[-1]
|
pic_url = url.split('/')[-2] + '/' + url.split('/')[-1]
|
||||||
direct_download_url = url.replace(f"/{pic_url}", f"/dl/{pic_url}")
|
direct_download_url = url.replace(f'/{pic_url}', f'/dl/{pic_url}')
|
||||||
print(direct_download_url)
|
print(direct_download_url)
|
||||||
return direct_download_url
|
return direct_download_url
|
||||||
else:
|
else:
|
||||||
@@ -89,17 +86,15 @@ async def send_screenshot(client, message, url, engine_name):
|
|||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
screenshot_data,
|
screenshot_data,
|
||||||
caption=f"<b>{engine_name.capitalize()} Result</b>\nURL: <code>{url}</code>",
|
caption=f'<b>{engine_name.capitalize()} Result</b>\nURL: <code>{url}</code>',
|
||||||
reply_to_message_id=message.id,
|
reply_to_message_id=message.id,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.reply(
|
await message.reply(f'Failed to take screenshot for {engine_name.capitalize()}.')
|
||||||
f"Failed to take screenshot for {engine_name.capitalize()}."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Add module details to help
|
# Add module details to help
|
||||||
modules_help["risearch"] = {
|
modules_help['risearch'] = {
|
||||||
"risearch": f"Reply to a photo with `{prefix}risearch [engine]` (e.g., `{prefix}risearch lens`, `{prefix}risearch bing`) "
|
'risearch': f'Reply to a photo with `{prefix}risearch [engine]` (e.g., `{prefix}risearch lens`, `{prefix}risearch bing`) '
|
||||||
f"\nor use `{prefix}risearch` to analyze the image with all engines.",
|
f'\nor use `{prefix}risearch` to analyze the image with all engines.',
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-43
@@ -1,64 +1,60 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
import requests
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
import requests
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
class AioHttp:
|
class AioHttp:
|
||||||
async def get_json(self, link):
|
async def get_json(self, link):
|
||||||
headers = {
|
headers = {
|
||||||
"accept": "*/*",
|
'accept': '*/*',
|
||||||
"accept-language": "en-US",
|
'accept-language': 'en-US',
|
||||||
"cache-control": "no-cache",
|
'cache-control': 'no-cache',
|
||||||
"client-geo-region": "global",
|
'client-geo-region': 'global',
|
||||||
"dnt": "1",
|
'dnt': '1',
|
||||||
"pragma": "no-cache",
|
'pragma': 'no-cache',
|
||||||
"priority": "u=1, i",
|
'priority': 'u=1, i',
|
||||||
"sec-ch-ua": '"Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"',
|
'sec-ch-ua': '"Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"',
|
||||||
"sec-ch-ua-mobile": "?0",
|
'sec-ch-ua-mobile': '?0',
|
||||||
"sec-ch-ua-platform": '"Windows"',
|
'sec-ch-ua-platform': '"Windows"',
|
||||||
"sec-fetch-dest": "empty",
|
'sec-fetch-dest': 'empty',
|
||||||
"sec-fetch-mode": "cors",
|
'sec-fetch-mode': 'cors',
|
||||||
"sec-fetch-site": "same-origin",
|
'sec-fetch-site': 'same-origin',
|
||||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
|
||||||
}
|
}
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session, session.get(link, headers=headers) as resp:
|
||||||
async with session.get(link, headers=headers) as resp:
|
|
||||||
return await resp.json()
|
return await resp.json()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("unsplash", prefix) & filters.me)
|
@Client.on_message(filters.command('unsplash', prefix) & filters.me)
|
||||||
async def unsplash(client: Client, message: Message):
|
async def unsplash(client: Client, message: Message):
|
||||||
if len(message.command) > 1 and isinstance(message.command[1], str):
|
if len(message.command) > 1 and isinstance(message.command[1], str):
|
||||||
keyword = message.command[1]
|
keyword = message.command[1]
|
||||||
unsplash_dir = "downloads/unsplash/"
|
unsplash_dir = 'downloads/unsplash/'
|
||||||
if not os.path.exists(unsplash_dir):
|
if not os.path.exists(unsplash_dir):
|
||||||
os.makedirs(unsplash_dir)
|
os.makedirs(unsplash_dir)
|
||||||
|
|
||||||
if len(message.command) > 2 and 2 <= int(message.command[2]) <= 10:
|
if len(message.command) > 2 and 2 <= int(message.command[2]) <= 10:
|
||||||
await message.edit(
|
await message.edit('<b>Getting Pictures</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Getting Pictures</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
count = int(message.command[2])
|
count = int(message.command[2])
|
||||||
images = []
|
images = []
|
||||||
data = await AioHttp().get_json(
|
data = await AioHttp().get_json(
|
||||||
f"https://unsplash.com/napi/search/photos?page=1&per_page={count}&query={keyword}"
|
f'https://unsplash.com/napi/search/photos?page=1&per_page={count}&query={keyword}'
|
||||||
)
|
)
|
||||||
while len(images) < count:
|
while len(images) < count:
|
||||||
for ia in range(len(images), count):
|
for ia in range(len(images), count):
|
||||||
img = data["results"][ia]["urls"]["raw"]
|
img = data['results'][ia]['urls']['raw']
|
||||||
if img.startswith("https://images.unsplash.com/photo"):
|
if img.startswith('https://images.unsplash.com/photo'):
|
||||||
image_content = requests.get(img).content
|
image_content = requests.get(img).content
|
||||||
with open(f"{unsplash_dir}/unsplash_{ia}.jpg", "wb") as f:
|
with open(f'{unsplash_dir}/unsplash_{ia}.jpg', 'wb') as f:
|
||||||
f.write(image_content)
|
f.write(image_content)
|
||||||
imgr = f"{unsplash_dir}/unsplash_{ia}.jpg"
|
imgr = f'{unsplash_dir}/unsplash_{ia}.jpg'
|
||||||
images.append(imgr)
|
images.append(imgr)
|
||||||
else:
|
else:
|
||||||
images.append(img)
|
images.append(img)
|
||||||
@@ -72,23 +68,19 @@ async def unsplash(client: Client, message: Message):
|
|||||||
shutil.rmtree(unsplash_dir)
|
shutil.rmtree(unsplash_dir)
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit('<b>Getting Picture</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Getting Picture</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
data = await AioHttp().get_json(
|
data = await AioHttp().get_json(
|
||||||
f"https://unsplash.com/napi/search/photos?page=1&per_page=1&query={keyword}"
|
f'https://unsplash.com/napi/search/photos?page=1&per_page=1&query={keyword}'
|
||||||
)
|
|
||||||
img = data["results"][0]["urls"]["raw"]
|
|
||||||
await asyncio.gather(
|
|
||||||
message.delete(), client.send_document(message.chat.id, str(img))
|
|
||||||
)
|
)
|
||||||
|
img = data['results'][0]['urls']['raw']
|
||||||
|
await asyncio.gather(message.delete(), client.send_document(message.chat.id, str(img)))
|
||||||
|
|
||||||
|
|
||||||
modules_help["unsplash"] = {
|
modules_help['unsplash'] = {
|
||||||
"unsplash": f"[keyword]*",
|
'unsplash': '[keyword]*',
|
||||||
"unsplash": f"[keyword]* [number of results you want]*\n"
|
'unsplash': '[keyword]* [number of results you want]*\n'
|
||||||
"Makes a request to <code>unsplash.com</code> and sends the image with the keyword you provided.\n\n"
|
'Makes a request to <code>unsplash.com</code> and sends the image with the keyword you provided.\n\n'
|
||||||
"<b>Note:</b>\n1. The number of results you can get is limited to 10.\n"
|
'<b>Note:</b>\n1. The number of results you can get is limited to 10.\n'
|
||||||
"2. Keyword is required and should be of one word only!.\n"
|
'2. Keyword is required and should be of one word only!.\n'
|
||||||
"3. Images are sent as document to maintain quality.",
|
'3. Images are sent as document to maintain quality.',
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-36
@@ -1,12 +1,13 @@
|
|||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message, InputMediaPhoto
|
|
||||||
from io import BytesIO
|
|
||||||
from PIL import Image
|
|
||||||
import requests
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from PIL import Image
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import InputMediaPhoto, Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
API_URL = "https://bk9.fun/search/unsplash?q="
|
API_URL = 'https://bk9.fun/search/unsplash?q='
|
||||||
|
|
||||||
|
|
||||||
def resize_image(image_bytes):
|
def resize_image(image_bytes):
|
||||||
@@ -16,13 +17,13 @@ def resize_image(image_bytes):
|
|||||||
if img.size > max_size:
|
if img.size > max_size:
|
||||||
img.thumbnail(max_size)
|
img.thumbnail(max_size)
|
||||||
output = BytesIO()
|
output = BytesIO()
|
||||||
img.save(output, format="JPEG")
|
img.save(output, format='JPEG')
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
return output
|
return output
|
||||||
image_bytes.seek(0) # Reset pointer if not resized
|
image_bytes.seek(0) # Reset pointer if not resized
|
||||||
return image_bytes
|
return image_bytes
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error resizing image: {e}")
|
print(f'Error resizing image: {e}')
|
||||||
return image_bytes
|
return image_bytes
|
||||||
|
|
||||||
|
|
||||||
@@ -34,70 +35,58 @@ async def download_image(url):
|
|||||||
resized_img_bytes = resize_image(img_bytes)
|
resized_img_bytes = resize_image(img_bytes)
|
||||||
return resized_img_bytes
|
return resized_img_bytes
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error downloading image: {e}")
|
print(f'Error downloading image: {e}')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["unsplash2", "usp2"], prefix) & filters.me)
|
@Client.on_message(filters.command(['unsplash2', 'usp2'], prefix) & filters.me)
|
||||||
async def imgsearch(client: Client, message: Message):
|
async def imgsearch(client: Client, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit(
|
await message.edit('Usage: `img [number] <query>`', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Usage: `img [number] <query>`", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
num_pics = int(message.command[1]) if message.command[1].isdigit() else 10
|
num_pics = int(message.command[1]) if message.command[1].isdigit() else 10
|
||||||
query = " ".join(message.command[2:])
|
query = ' '.join(message.command[2:])
|
||||||
|
|
||||||
# Update status
|
# Update status
|
||||||
status_message = await message.edit(
|
status_message = await message.edit('Searching for images...', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Searching for images...", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
url = f"{API_URL}{query}"
|
url = f'{API_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if data.get("status"):
|
if data.get('status'):
|
||||||
urls = data.get("BK9", [])[:num_pics]
|
urls = data.get('BK9', [])[:num_pics]
|
||||||
images = [download_image(img_url) for img_url in urls]
|
images = [download_image(img_url) for img_url in urls]
|
||||||
|
|
||||||
# Download images
|
# Download images
|
||||||
downloaded_images = await asyncio.gather(*images)
|
downloaded_images = await asyncio.gather(*images)
|
||||||
|
|
||||||
media = [
|
media = [InputMediaPhoto(media=img_bytes) for img_bytes in downloaded_images if img_bytes]
|
||||||
InputMediaPhoto(media=img_bytes)
|
|
||||||
for img_bytes in downloaded_images
|
|
||||||
if img_bytes
|
|
||||||
]
|
|
||||||
|
|
||||||
if media:
|
if media:
|
||||||
await status_message.edit(
|
await status_message.edit('Uploading pictures...', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"Uploading pictures...", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
while media:
|
while media:
|
||||||
batch = media[:10]
|
batch = media[:10]
|
||||||
media = media[10:]
|
media = media[10:]
|
||||||
await message.reply_media_group(batch)
|
await message.reply_media_group(batch)
|
||||||
await status_message.delete() # Delete status message after uploading
|
await status_message.delete() # Delete status message after uploading
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit('No valid images found.', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"No valid images found.", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit(
|
||||||
"No images found for the given query.",
|
'No images found for the given query.',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit(
|
||||||
"An error occurred, please try again later.",
|
'An error occurred, please try again later.',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["unsplash2"] = {
|
modules_help['unsplash2'] = {
|
||||||
"unsplash2 [number]* [query]": "Get HD images. Default number of images is 10",
|
'unsplash2 [number]* [query]': 'Get HD images. Default number of images is 10',
|
||||||
"usp2 [number]* [query]": "Get HD images. Default number of images is 10",
|
'usp2 [number]* [query]': 'Get HD images. Default number of images is 10',
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-24
@@ -1,23 +1,23 @@
|
|||||||
from datetime import datetime
|
|
||||||
import sys
|
import sys
|
||||||
from pyrogram import Client
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pyrogram import Client
|
||||||
from utils import config
|
from utils import config
|
||||||
|
|
||||||
common_params = {
|
common_params = {
|
||||||
"api_id": config.api_id,
|
'api_id': config.api_id,
|
||||||
"api_hash": config.api_hash,
|
'api_hash': config.api_hash,
|
||||||
"hide_password": True,
|
'hide_password': True,
|
||||||
"test_mode": config.test_server,
|
'test_mode': config.test_server,
|
||||||
}
|
}
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == '__main__':
|
||||||
if config.STRINGSESSION:
|
if config.STRINGSESSION:
|
||||||
common_params["session_string"] = config.STRINGSESSION
|
common_params['session_string'] = config.STRINGSESSION
|
||||||
|
|
||||||
app = Client("my_account", **common_params)
|
app = Client('my_account', **common_params)
|
||||||
|
|
||||||
if config.db_type in ["mongo", "mongodb"]:
|
if config.db_type in ['mongo', 'mongodb']:
|
||||||
from pymongo import MongoClient, errors
|
from pymongo import MongoClient, errors
|
||||||
|
|
||||||
db = MongoClient(config.db_url)
|
db = MongoClient(config.db_url)
|
||||||
@@ -26,27 +26,27 @@ if __name__ == "__main__":
|
|||||||
except errors.ConnectionFailure as e:
|
except errors.ConnectionFailure as e:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"MongoDB server isn't available! "
|
"MongoDB server isn't available! "
|
||||||
f"Provided url: {config.db_url}. "
|
f'Provided url: {config.db_url}. '
|
||||||
"Enter valid URL and restart installation"
|
'Enter valid URL and restart installation'
|
||||||
) from e
|
) from e
|
||||||
|
|
||||||
install_type = sys.argv[1] if len(sys.argv) > 1 else "3"
|
install_type = sys.argv[1] if len(sys.argv) > 1 else '3'
|
||||||
if install_type == "1":
|
if install_type == '1':
|
||||||
restart = "pm2 restart Moon"
|
restart = 'pm2 restart Moon'
|
||||||
elif install_type == "2":
|
elif install_type == '2':
|
||||||
restart = "sudo systemctl restart Moon"
|
restart = 'sudo systemctl restart Moon'
|
||||||
else:
|
else:
|
||||||
restart = "cd Moon-Userbot/ && python main.py"
|
restart = 'cd Moon-Userbot/ && python main.py'
|
||||||
|
|
||||||
app.start()
|
app.start()
|
||||||
try:
|
try:
|
||||||
app.send_message(
|
app.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"<b>[{datetime.now()}] Userbot launched! \n"
|
f'<b>[{datetime.now()}] Userbot launched! \n'
|
||||||
"Custom modules: @moonub_modules\n"
|
'Custom modules: @moonub_modules\n'
|
||||||
f"For restart, enter:</b>\n"
|
f'For restart, enter:</b>\n'
|
||||||
f"<code>{restart}</code>",
|
f'<code>{restart}</code>',
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR]: Sending Message to me failed! {e}")
|
print(f'[ERROR]: Sending Message to me failed! {e}')
|
||||||
app.stop()
|
app.stop()
|
||||||
|
|||||||
+51
-60
@@ -39,92 +39,88 @@
|
|||||||
# "pySmartDL",
|
# "pySmartDL",
|
||||||
# ]
|
# ]
|
||||||
# ///
|
# ///
|
||||||
import os
|
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import sqlite3
|
|
||||||
import platform
|
import platform
|
||||||
|
import sqlite3
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
from pyrogram import Client, idle, errors
|
|
||||||
from pyrogram.enums.parse_mode import ParseMode
|
|
||||||
from pyrogram.raw.functions.account import GetAuthorizations, DeleteAccount
|
|
||||||
import requests
|
import requests
|
||||||
|
from pyrogram import Client, errors, idle
|
||||||
|
from pyrogram.enums.parse_mode import ParseMode
|
||||||
|
from pyrogram.raw.functions.account import DeleteAccount, GetAuthorizations
|
||||||
from utils import config
|
from utils import config
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import gitrepo, userbot_version
|
from utils.misc import userbot_version
|
||||||
from utils.scripts import restart
|
|
||||||
from utils.rentry import rentry_cleanup_job
|
|
||||||
from utils.module import ModuleManager
|
from utils.module import ModuleManager
|
||||||
|
from utils.rentry import rentry_cleanup_job
|
||||||
|
from utils.scripts import restart
|
||||||
|
|
||||||
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
|
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
|
||||||
if SCRIPT_PATH != os.getcwd():
|
if os.getcwd() != SCRIPT_PATH:
|
||||||
os.chdir(SCRIPT_PATH)
|
os.chdir(SCRIPT_PATH)
|
||||||
|
|
||||||
common_params = {
|
common_params = {
|
||||||
"api_id": config.api_id,
|
'api_id': config.api_id,
|
||||||
"api_hash": config.api_hash,
|
'api_hash': config.api_hash,
|
||||||
"hide_password": True,
|
'hide_password': True,
|
||||||
"workdir": SCRIPT_PATH,
|
'workdir': SCRIPT_PATH,
|
||||||
"app_version": userbot_version,
|
'app_version': userbot_version,
|
||||||
"device_model": f"mUserbot",
|
'device_model': 'mUserbot',
|
||||||
"system_version": platform.version() + " " + platform.machine(),
|
'system_version': platform.version() + ' ' + platform.machine(),
|
||||||
"sleep_threshold": 30,
|
'sleep_threshold': 30,
|
||||||
"test_mode": config.test_server,
|
'test_mode': config.test_server,
|
||||||
"parse_mode": ParseMode.HTML,
|
'parse_mode': ParseMode.HTML,
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.STRINGSESSION:
|
if config.STRINGSESSION:
|
||||||
common_params["session_string"] = config.STRINGSESSION
|
common_params['session_string'] = config.STRINGSESSION
|
||||||
|
|
||||||
app = Client("my_account", **common_params)
|
app = Client('my_account', **common_params)
|
||||||
|
|
||||||
|
|
||||||
def load_missing_modules():
|
def load_missing_modules():
|
||||||
all_modules = db.get("custom.modules", "allModules", [])
|
all_modules = db.get('custom.modules', 'allModules', [])
|
||||||
if not all_modules:
|
if not all_modules:
|
||||||
return
|
return
|
||||||
|
|
||||||
custom_modules_path = f"{SCRIPT_PATH}/modules/custom_modules"
|
custom_modules_path = f'{SCRIPT_PATH}/modules/custom_modules'
|
||||||
os.makedirs(custom_modules_path, exist_ok=True)
|
os.makedirs(custom_modules_path, exist_ok=True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
resp = requests.get(
|
resp = requests.get(
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt",
|
'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt',
|
||||||
timeout=10,
|
timeout=10,
|
||||||
)
|
)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
logging.error(
|
logging.error(
|
||||||
"Failed to fetch custom modules list: HTTP %s",
|
'Failed to fetch custom modules list: HTTP %s',
|
||||||
resp.status_code,
|
resp.status_code,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
f = resp.text
|
f = resp.text
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error("Failed to fetch custom modules list: %s", e)
|
logging.error('Failed to fetch custom modules list: %s', e)
|
||||||
return
|
return
|
||||||
modules_dict = {
|
modules_dict = {line.split('/')[-1].split()[0]: line.strip() for line in f.splitlines()}
|
||||||
line.split("/")[-1].split()[0]: line.strip() for line in f.splitlines()
|
|
||||||
}
|
|
||||||
|
|
||||||
for module_name in all_modules:
|
for module_name in all_modules:
|
||||||
module_path = f"{custom_modules_path}/{module_name}.py"
|
module_path = f'{custom_modules_path}/{module_name}.py'
|
||||||
if not os.path.exists(module_path) and module_name in modules_dict:
|
if not os.path.exists(module_path) and module_name in modules_dict:
|
||||||
url = f"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py"
|
url = f'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py'
|
||||||
resp = requests.get(url)
|
resp = requests.get(url)
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
with open(module_path, "wb") as f:
|
with open(module_path, 'wb') as f:
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
logging.info("Loaded missing module: %s", module_name)
|
logging.info('Loaded missing module: %s', module_name)
|
||||||
else:
|
else:
|
||||||
logging.warning("Failed to load module: %s", module_name)
|
logging.warning('Failed to load module: %s', module_name)
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||||
handlers=[logging.FileHandler("moonlogs.txt"), logging.StreamHandler()],
|
handlers=[logging.FileHandler('moonlogs.txt'), logging.StreamHandler()],
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
)
|
)
|
||||||
DeleteAccount.__new__ = None
|
DeleteAccount.__new__ = None
|
||||||
@@ -132,49 +128,44 @@ async def main():
|
|||||||
try:
|
try:
|
||||||
await app.start()
|
await app.start()
|
||||||
except sqlite3.OperationalError as e:
|
except sqlite3.OperationalError as e:
|
||||||
if str(e) == "database is locked" and os.name == "posix":
|
if str(e) == 'database is locked' and os.name == 'posix':
|
||||||
logging.warning(
|
logging.warning('Session file is locked. Trying to kill blocking process...')
|
||||||
"Session file is locked. Trying to kill blocking process..."
|
subprocess.run(['fuser', '-k', 'my_account.session'], check=True)
|
||||||
)
|
|
||||||
subprocess.run(["fuser", "-k", "my_account.session"], check=True)
|
|
||||||
restart()
|
restart()
|
||||||
raise
|
raise
|
||||||
except (errors.NotAcceptable, errors.Unauthorized) as e:
|
except (errors.NotAcceptable, errors.Unauthorized) as e:
|
||||||
logging.error(
|
logging.error(
|
||||||
"%s: %s\nMoving session file to my_account.session-old...",
|
'%s: %s\nMoving session file to my_account.session-old...',
|
||||||
e.__class__.__name__,
|
e.__class__.__name__,
|
||||||
e,
|
e,
|
||||||
)
|
)
|
||||||
os.rename("./my_account.session", "./my_account.session-old")
|
os.rename('./my_account.session', './my_account.session-old')
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
load_missing_modules()
|
load_missing_modules()
|
||||||
module_manager = ModuleManager.get_instance()
|
module_manager = ModuleManager.get_instance()
|
||||||
await module_manager.load_modules(app)
|
await module_manager.load_modules(app)
|
||||||
|
|
||||||
if info := db.get("core.updater", "restart_info"):
|
if info := db.get('core.updater', 'restart_info'):
|
||||||
text = {
|
text = {
|
||||||
"restart": "<b>Restart completed!</b>",
|
'restart': '<b>Restart completed!</b>',
|
||||||
"update": "<b>Update process completed!</b>",
|
'update': '<b>Update process completed!</b>',
|
||||||
}[info["type"]]
|
}[info['type']]
|
||||||
try:
|
try:
|
||||||
await app.edit_message_text(info["chat_id"], info["message_id"], text)
|
await app.edit_message_text(info['chat_id'], info['message_id'], text)
|
||||||
except errors.RPCError:
|
except errors.RPCError:
|
||||||
pass
|
pass
|
||||||
db.remove("core.updater", "restart_info")
|
db.remove('core.updater', 'restart_info')
|
||||||
|
|
||||||
# required for sessionkiller module
|
# required for sessionkiller module
|
||||||
if db.get("core.sessionkiller", "enabled", False):
|
if db.get('core.sessionkiller', 'enabled', False):
|
||||||
db.set(
|
db.set(
|
||||||
"core.sessionkiller",
|
'core.sessionkiller',
|
||||||
"auths_hashes",
|
'auths_hashes',
|
||||||
[
|
[auth.hash for auth in (await app.invoke(GetAuthorizations())).authorizations],
|
||||||
auth.hash
|
|
||||||
for auth in (await app.invoke(GetAuthorizations())).authorizations
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
logging.info("Moon-Userbot started!")
|
logging.info('Moon-Userbot started!')
|
||||||
|
|
||||||
app.loop.create_task(rentry_cleanup_job())
|
app.loop.create_task(rentry_cleanup_job())
|
||||||
|
|
||||||
@@ -183,5 +174,5 @@ async def main():
|
|||||||
await app.stop()
|
await app.stop()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == '__main__':
|
||||||
app.run(main())
|
app.run(main())
|
||||||
|
|||||||
@@ -2,20 +2,16 @@ from asyncio import sleep
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
digits = {
|
digits = {str(i): el for i, el in enumerate(['0️⃣', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣'])}
|
||||||
str(i): el
|
|
||||||
for i, el in enumerate(["0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"])
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def prettify(val: int) -> str:
|
def prettify(val: int) -> str:
|
||||||
return "".join(digits[i] for i in str(val))
|
return ''.join(digits[i] for i in str(val))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ghoul", prefix) & filters.me)
|
@Client.on_message(filters.command('ghoul', prefix) & filters.me)
|
||||||
async def ghoul_counter(_, message: Message):
|
async def ghoul_counter(_, message: Message):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
@@ -33,9 +29,7 @@ async def ghoul_counter(_, message: Message):
|
|||||||
await msg.edit(prettify(counter))
|
await msg.edit(prettify(counter))
|
||||||
await sleep(1)
|
await sleep(1)
|
||||||
|
|
||||||
await msg.edit("<b>🤡 GHOUL 🤡</b>")
|
await msg.edit('<b>🤡 GHOUL 🤡</b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["1000-7"] = {
|
modules_help['1000-7'] = {'ghoul [count_from]': 'counting from 1000 (or given [count_from] to 0 as a ghoul'}
|
||||||
"ghoul [count_from]": "counting from 1000 (or given [count_from] to 0 as a ghoul"
|
|
||||||
}
|
|
||||||
|
|||||||
+93
-104
@@ -16,60 +16,57 @@
|
|||||||
|
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
|
|
||||||
from pyrogram.enums import ChatType
|
|
||||||
from pyrogram import Client, ContinuePropagation, filters
|
from pyrogram import Client, ContinuePropagation, filters
|
||||||
|
from pyrogram.enums import ChatType
|
||||||
from pyrogram.errors import (
|
from pyrogram.errors import (
|
||||||
UserAdminInvalid,
|
|
||||||
ChatAdminRequired,
|
ChatAdminRequired,
|
||||||
RPCError,
|
RPCError,
|
||||||
|
UserAdminInvalid,
|
||||||
)
|
)
|
||||||
from pyrogram.raw import functions
|
from pyrogram.raw import functions
|
||||||
from pyrogram.types import Message, ChatPermissions
|
from pyrogram.types import ChatPermissions, Message
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.scripts import format_exc, with_reply
|
|
||||||
from utils.misc import modules_help, prefix
|
|
||||||
|
|
||||||
from utils.handlers import (
|
from utils.handlers import (
|
||||||
BanHandler,
|
|
||||||
UnbanHandler,
|
|
||||||
KickHandler,
|
|
||||||
KickDeletedAccountsHandler,
|
|
||||||
TimeMuteHandler,
|
|
||||||
TimeUnmuteHandler,
|
|
||||||
TimeMuteUsersHandler,
|
|
||||||
UnmuteHandler,
|
|
||||||
MuteHandler,
|
|
||||||
DemoteHandler,
|
|
||||||
PromoteHandler,
|
|
||||||
AntiChannelsHandler,
|
AntiChannelsHandler,
|
||||||
DeleteHistoryHandler,
|
|
||||||
AntiRaidHandler,
|
AntiRaidHandler,
|
||||||
|
BanHandler,
|
||||||
|
DeleteHistoryHandler,
|
||||||
|
DemoteHandler,
|
||||||
|
KickDeletedAccountsHandler,
|
||||||
|
KickHandler,
|
||||||
|
MuteHandler,
|
||||||
|
PromoteHandler,
|
||||||
|
TimeMuteHandler,
|
||||||
|
TimeMuteUsersHandler,
|
||||||
|
TimeUnmuteHandler,
|
||||||
|
UnbanHandler,
|
||||||
|
UnmuteHandler,
|
||||||
)
|
)
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
|
from utils.scripts import format_exc, with_reply
|
||||||
|
|
||||||
|
db_cache: dict = db.get_collection('core.ats')
|
||||||
db_cache: dict = db.get_collection("core.ats")
|
|
||||||
|
|
||||||
|
|
||||||
def update_cache():
|
def update_cache():
|
||||||
db_cache.clear()
|
db_cache.clear()
|
||||||
db_cache.update(db.get_collection("core.ats"))
|
db_cache.update(db.get_collection('core.ats'))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.group & ~filters.me)
|
@Client.on_message(filters.group & ~filters.me)
|
||||||
async def admintool_handler(_, message: Message):
|
async def admintool_handler(_, message: Message):
|
||||||
if message.sender_chat and (
|
if message.sender_chat and (
|
||||||
message.sender_chat.type == "supergroup"
|
message.sender_chat.type == 'supergroup'
|
||||||
or message.sender_chat.id == db_cache.get(f"linked{message.chat.id}", 0)
|
or message.sender_chat.id == db_cache.get(f'linked{message.chat.id}', 0)
|
||||||
):
|
):
|
||||||
raise ContinuePropagation
|
raise ContinuePropagation
|
||||||
|
|
||||||
if message.sender_chat and db_cache.get(f"antich{message.chat.id}", False):
|
if message.sender_chat and db_cache.get(f'antich{message.chat.id}', False):
|
||||||
with suppress(RPCError):
|
with suppress(RPCError):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await message.chat.ban_member(message.sender_chat.id)
|
await message.chat.ban_member(message.sender_chat.id)
|
||||||
|
|
||||||
tmuted_users = db_cache.get(f"c{message.chat.id}", [])
|
tmuted_users = db_cache.get(f'c{message.chat.id}', [])
|
||||||
if (
|
if (
|
||||||
message.from_user
|
message.from_user
|
||||||
and message.from_user.id in tmuted_users
|
and message.from_user.id in tmuted_users
|
||||||
@@ -79,7 +76,7 @@ async def admintool_handler(_, message: Message):
|
|||||||
with suppress(RPCError):
|
with suppress(RPCError):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
if db_cache.get(f"antiraid{message.chat.id}", False):
|
if db_cache.get(f'antiraid{message.chat.id}', False):
|
||||||
with suppress(RPCError):
|
with suppress(RPCError):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
if message.from_user:
|
if message.from_user:
|
||||||
@@ -87,11 +84,9 @@ async def admintool_handler(_, message: Message):
|
|||||||
elif message.sender_chat:
|
elif message.sender_chat:
|
||||||
await message.chat.ban_member(message.sender_chat.id)
|
await message.chat.ban_member(message.sender_chat.id)
|
||||||
|
|
||||||
if message.new_chat_members and db_cache.get(
|
if message.new_chat_members and db_cache.get(f'welcome_enabled{message.chat.id}', False):
|
||||||
f"welcome_enabled{message.chat.id}", False
|
|
||||||
):
|
|
||||||
await message.reply(
|
await message.reply(
|
||||||
db_cache.get(f"welcome_text{message.chat.id}"),
|
db_cache.get(f'welcome_text{message.chat.id}'),
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -111,88 +106,88 @@ async def get_user_and_name(message):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["ban"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ban'], prefix) & filters.me)
|
||||||
async def ban_command(client: Client, message: Message):
|
async def ban_command(client: Client, message: Message):
|
||||||
handler = BanHandler(client, message)
|
handler = BanHandler(client, message)
|
||||||
await handler.handle_ban()
|
await handler.handle_ban()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["unban"], prefix) & filters.me)
|
@Client.on_message(filters.command(['unban'], prefix) & filters.me)
|
||||||
async def unban_command(client: Client, message: Message):
|
async def unban_command(client: Client, message: Message):
|
||||||
handler = UnbanHandler(client, message)
|
handler = UnbanHandler(client, message)
|
||||||
await handler.handle_unban()
|
await handler.handle_unban()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["kick"], prefix) & filters.me)
|
@Client.on_message(filters.command(['kick'], prefix) & filters.me)
|
||||||
async def kick_command(client: Client, message: Message):
|
async def kick_command(client: Client, message: Message):
|
||||||
handler = KickHandler(client, message)
|
handler = KickHandler(client, message)
|
||||||
await handler.handle_kick()
|
await handler.handle_kick()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["kickdel"], prefix) & filters.me)
|
@Client.on_message(filters.command(['kickdel'], prefix) & filters.me)
|
||||||
async def kickdel_cmd(client: Client, message: Message):
|
async def kickdel_cmd(client: Client, message: Message):
|
||||||
handler = KickDeletedAccountsHandler(client, message)
|
handler = KickDeletedAccountsHandler(client, message)
|
||||||
await handler.kick_deleted_accounts()
|
await handler.kick_deleted_accounts()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["tmute"], prefix) & filters.me)
|
@Client.on_message(filters.command(['tmute'], prefix) & filters.me)
|
||||||
async def tmute_command(client: Client, message: Message):
|
async def tmute_command(client: Client, message: Message):
|
||||||
handler = TimeMuteHandler(client, message)
|
handler = TimeMuteHandler(client, message)
|
||||||
await handler.handle_tmute()
|
await handler.handle_tmute()
|
||||||
update_cache()
|
update_cache()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["tunmute"], prefix) & filters.me)
|
@Client.on_message(filters.command(['tunmute'], prefix) & filters.me)
|
||||||
async def tunmute_command(client: Client, message: Message):
|
async def tunmute_command(client: Client, message: Message):
|
||||||
handler = TimeUnmuteHandler(client, message)
|
handler = TimeUnmuteHandler(client, message)
|
||||||
await handler.handle_tunmute()
|
await handler.handle_tunmute()
|
||||||
update_cache()
|
update_cache()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["tmute_users"], prefix) & filters.me)
|
@Client.on_message(filters.command(['tmute_users'], prefix) & filters.me)
|
||||||
async def tunmute_users_command(client: Client, message: Message):
|
async def tunmute_users_command(client: Client, message: Message):
|
||||||
handler = TimeMuteUsersHandler(client, message)
|
handler = TimeMuteUsersHandler(client, message)
|
||||||
await handler.list_tmuted_users()
|
await handler.list_tmuted_users()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["unmute"], prefix) & filters.me)
|
@Client.on_message(filters.command(['unmute'], prefix) & filters.me)
|
||||||
async def unmute_command(client: Client, message: Message):
|
async def unmute_command(client: Client, message: Message):
|
||||||
handler = UnmuteHandler(client, message)
|
handler = UnmuteHandler(client, message)
|
||||||
await handler.handle_unmute()
|
await handler.handle_unmute()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["mute"], prefix) & filters.me)
|
@Client.on_message(filters.command(['mute'], prefix) & filters.me)
|
||||||
async def mute_command(client: Client, message: Message):
|
async def mute_command(client: Client, message: Message):
|
||||||
handler = MuteHandler(client, message)
|
handler = MuteHandler(client, message)
|
||||||
await handler.handle_mute()
|
await handler.handle_mute()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["demote"], prefix) & filters.me)
|
@Client.on_message(filters.command(['demote'], prefix) & filters.me)
|
||||||
async def demote_command(client: Client, message: Message):
|
async def demote_command(client: Client, message: Message):
|
||||||
handler = DemoteHandler(client, message)
|
handler = DemoteHandler(client, message)
|
||||||
await handler.handle_demote()
|
await handler.handle_demote()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["promote"], prefix) & filters.me)
|
@Client.on_message(filters.command(['promote'], prefix) & filters.me)
|
||||||
async def promote_command(client: Client, message: Message):
|
async def promote_command(client: Client, message: Message):
|
||||||
handler = PromoteHandler(client, message)
|
handler = PromoteHandler(client, message)
|
||||||
await handler.handle_promote()
|
await handler.handle_promote()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["antich"], prefix))
|
@Client.on_message(filters.command(['antich'], prefix))
|
||||||
async def anti_channels(client: Client, message: Message):
|
async def anti_channels(client: Client, message: Message):
|
||||||
handler = AntiChannelsHandler(client, message)
|
handler = AntiChannelsHandler(client, message)
|
||||||
await handler.handle_anti_channels()
|
await handler.handle_anti_channels()
|
||||||
update_cache()
|
update_cache()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["delete_history", "dh"], prefix))
|
@Client.on_message(filters.command(['delete_history', 'dh'], prefix))
|
||||||
async def delete_history(client: Client, message: Message):
|
async def delete_history(client: Client, message: Message):
|
||||||
handler = DeleteHistoryHandler(client, message)
|
handler = DeleteHistoryHandler(client, message)
|
||||||
await handler.handle_delete_history()
|
await handler.handle_delete_history()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["report_spam", "rs"], prefix))
|
@Client.on_message(filters.command(['report_spam', 'rs'], prefix))
|
||||||
@with_reply
|
@with_reply
|
||||||
async def report_spam(client: Client, message: Message):
|
async def report_spam(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
@@ -210,33 +205,33 @@ async def report_spam(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Message</a> from {name} was reported</b>")
|
await message.edit(f'<b>Message</a> from {name} was reported</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("pin", prefix) & filters.me)
|
@Client.on_message(filters.command('pin', prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def pin(_, message: Message):
|
async def pin(_, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.reply_to_message.pin()
|
await message.reply_to_message.pin()
|
||||||
await message.edit("<b>Pinned!</b>")
|
await message.edit('<b>Pinned!</b>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("unpin", prefix) & filters.me)
|
@Client.on_message(filters.command('unpin', prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def unpin(_, message: Message):
|
async def unpin(_, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.reply_to_message.unpin()
|
await message.reply_to_message.unpin()
|
||||||
await message.edit("<b>Unpinned!</b>")
|
await message.edit('<b>Unpinned!</b>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ro", prefix) & filters.me)
|
@Client.on_message(filters.command('ro', prefix) & filters.me)
|
||||||
async def ro(client: Client, message: Message):
|
async def ro(client: Client, message: Message):
|
||||||
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
||||||
await message.edit("<b>Invalid chat type</b>")
|
await message.edit('<b>Invalid chat type</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -250,42 +245,39 @@ async def ro(client: Client, message: Message):
|
|||||||
perms.can_invite_users,
|
perms.can_invite_users,
|
||||||
perms.can_pin_messages,
|
perms.can_pin_messages,
|
||||||
]
|
]
|
||||||
db.set("core.ats", f"ro{message.chat.id}", perms_list)
|
db.set('core.ats', f'ro{message.chat.id}', perms_list)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await client.set_chat_permissions(message.chat.id, ChatPermissions())
|
await client.set_chat_permissions(message.chat.id, ChatPermissions())
|
||||||
except (UserAdminInvalid, ChatAdminRequired):
|
except (UserAdminInvalid, ChatAdminRequired):
|
||||||
await message.edit("<b>No rights</b>")
|
await message.edit('<b>No rights</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Read-only mode activated!\nTurn off with:</b><code>{prefix}unro</code>')
|
||||||
"<b>Read-only mode activated!\n"
|
|
||||||
f"Turn off with:</b><code>{prefix}unro</code>"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("unro", prefix) & filters.me)
|
@Client.on_message(filters.command('unro', prefix) & filters.me)
|
||||||
async def unro(client: Client, message: Message):
|
async def unro(client: Client, message: Message):
|
||||||
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
||||||
await message.edit("<b>Invalid chat type</b>")
|
await message.edit('<b>Invalid chat type</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
perms_list = db.get(
|
perms_list = db.get(
|
||||||
"core.ats",
|
'core.ats',
|
||||||
f"ro{message.chat.id}",
|
f'ro{message.chat.id}',
|
||||||
[True, True, False, False, False, False, False],
|
[True, True, False, False, False, False, False],
|
||||||
)
|
)
|
||||||
|
|
||||||
common_perms = {
|
common_perms = {
|
||||||
"can_send_messages": perms_list[0],
|
'can_send_messages': perms_list[0],
|
||||||
"can_send_media_messages": perms_list[1],
|
'can_send_media_messages': perms_list[1],
|
||||||
"can_send_polls": perms_list[2],
|
'can_send_polls': perms_list[2],
|
||||||
"can_add_web_page_previews": perms_list[3],
|
'can_add_web_page_previews': perms_list[3],
|
||||||
"can_change_info": perms_list[4],
|
'can_change_info': perms_list[4],
|
||||||
"can_invite_users": perms_list[5],
|
'can_invite_users': perms_list[5],
|
||||||
"can_pin_messages": perms_list[6],
|
'can_pin_messages': perms_list[6],
|
||||||
}
|
}
|
||||||
|
|
||||||
perms = ChatPermissions(**common_perms)
|
perms = ChatPermissions(**common_perms)
|
||||||
@@ -293,61 +285,58 @@ async def unro(client: Client, message: Message):
|
|||||||
try:
|
try:
|
||||||
await client.set_chat_permissions(message.chat.id, perms)
|
await client.set_chat_permissions(message.chat.id, perms)
|
||||||
except (UserAdminInvalid, ChatAdminRequired):
|
except (UserAdminInvalid, ChatAdminRequired):
|
||||||
await message.edit("<b>No rights</b>")
|
await message.edit('<b>No rights</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Read-only mode disabled!</b>")
|
await message.edit('<b>Read-only mode disabled!</b>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("antiraid", prefix) & filters.me)
|
@Client.on_message(filters.command('antiraid', prefix) & filters.me)
|
||||||
async def antiraid(client: Client, message: Message):
|
async def antiraid(client: Client, message: Message):
|
||||||
handler = AntiRaidHandler(client, message)
|
handler = AntiRaidHandler(client, message)
|
||||||
await handler.handle_antiraid()
|
await handler.handle_antiraid()
|
||||||
update_cache()
|
update_cache()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["welcome", "wc"], prefix) & filters.me)
|
@Client.on_message(filters.command(['welcome', 'wc'], prefix) & filters.me)
|
||||||
async def welcome(_, message: Message):
|
async def welcome(_, message: Message):
|
||||||
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
if message.chat.type not in [ChatType.GROUP, ChatType.SUPERGROUP]:
|
||||||
return await message.edit("<b>Unsupported chat type</b>")
|
return await message.edit('<b>Unsupported chat type</b>')
|
||||||
|
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
text = message.text.split(maxsplit=1)[1]
|
text = message.text.split(maxsplit=1)[1]
|
||||||
db.set("core.ats", f"welcome_enabled{message.chat.id}", True)
|
db.set('core.ats', f'welcome_enabled{message.chat.id}', True)
|
||||||
db.set("core.ats", f"welcome_text{message.chat.id}", text)
|
db.set('core.ats', f'welcome_text{message.chat.id}', text)
|
||||||
|
|
||||||
await message.edit(
|
await message.edit(f'<b>Welcome enabled in this chat\nText:</b> <code>{text}</code>')
|
||||||
f"<b>Welcome enabled in this chat\nText:</b> <code>{text}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
db.set("core.ats", f"welcome_enabled{message.chat.id}", False)
|
db.set('core.ats', f'welcome_enabled{message.chat.id}', False)
|
||||||
await message.edit("<b>Welcome disabled in this chat</b>")
|
await message.edit('<b>Welcome disabled in this chat</b>')
|
||||||
|
|
||||||
update_cache()
|
update_cache()
|
||||||
|
|
||||||
|
|
||||||
modules_help["admintool"] = {
|
modules_help['admintool'] = {
|
||||||
"ban [reply]/[username/id]* [reason] [report_spam] [delete_history]": "ban user in chat",
|
'ban [reply]/[username/id]* [reason] [report_spam] [delete_history]': 'ban user in chat',
|
||||||
"unban [reply]/[username/id]* [reason]": "unban user in chat",
|
'unban [reply]/[username/id]* [reason]': 'unban user in chat',
|
||||||
"kick [reply]/[userid]* [reason] [report_spam] [delete_history]": "kick user out of chat",
|
'kick [reply]/[userid]* [reason] [report_spam] [delete_history]': 'kick user out of chat',
|
||||||
"mute [reply]/[userid]* [reason] [1m]/[1h]/[1d]/[1w]": "mute user in chat",
|
'mute [reply]/[userid]* [reason] [1m]/[1h]/[1d]/[1w]': 'mute user in chat',
|
||||||
"unmute [reply]/[userid]* [reason]": "unmute user in chat",
|
'unmute [reply]/[userid]* [reason]': 'unmute user in chat',
|
||||||
"promote [reply]/[userid]* [prefix]": "promote user in chat",
|
'promote [reply]/[userid]* [prefix]': 'promote user in chat',
|
||||||
"demote [reply]/[userid]* [reason]": "demote user in chat",
|
'demote [reply]/[userid]* [reason]': 'demote user in chat',
|
||||||
"tmute [reply]/[username/id]* [reason]": "delete all new messages from user in chat",
|
'tmute [reply]/[username/id]* [reason]': 'delete all new messages from user in chat',
|
||||||
"tunmute [reply]/[username/id]* [reason]": "stop deleting all messages from user in chat",
|
'tunmute [reply]/[username/id]* [reason]': 'stop deleting all messages from user in chat',
|
||||||
"tmute_users": "list of tmuted (.tmute) users",
|
'tmute_users': 'list of tmuted (.tmute) users',
|
||||||
"antich [enable/disable]": "turn on/off blocking channels in this chat",
|
'antich [enable/disable]': 'turn on/off blocking channels in this chat',
|
||||||
"delete_history [reply]/[username/id]* [reason]": "delete history from member in chat",
|
'delete_history [reply]/[username/id]* [reason]': 'delete history from member in chat',
|
||||||
"report_spam [reply]*": "report spam message in chat",
|
'report_spam [reply]*': 'report spam message in chat',
|
||||||
"pin [reply]*": "Pin replied message",
|
'pin [reply]*': 'Pin replied message',
|
||||||
"unpin [reply]*": "Unpin replied message",
|
'unpin [reply]*': 'Unpin replied message',
|
||||||
"ro": "enable read-only mode",
|
'ro': 'enable read-only mode',
|
||||||
"unro": "disable read-only mode",
|
'unro': 'disable read-only mode',
|
||||||
"antiraid [on|off]": "when enabled, anyone who writes message will be blocked. Useful in raids. "
|
'antiraid [on|off]': 'when enabled, anyone who writes message will be blocked. Useful in raids. '
|
||||||
"Running without arguments equals to toggling state",
|
'Running without arguments equals to toggling state',
|
||||||
"welcome [text]*": "enable auto-welcome to new users in groups. "
|
'welcome [text]*': 'enable auto-welcome to new users in groups. Running without text equals to disable',
|
||||||
"Running without text equals to disable",
|
'kickdel': 'Kick all deleted accounts',
|
||||||
"kickdel": "Kick all deleted accounts",
|
|
||||||
}
|
}
|
||||||
|
|||||||
+84
-104
@@ -14,12 +14,12 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from collections.abc import AsyncGenerator
|
||||||
from time import perf_counter
|
from time import perf_counter
|
||||||
from typing import AsyncGenerator, List, Optional, Union
|
from typing import Optional
|
||||||
|
|
||||||
from pyrogram import Client, enums, filters, raw, types, utils
|
from pyrogram import Client, enums, filters, raw, types, utils
|
||||||
from pyrogram.types.object import Object
|
from pyrogram.types.object import Object
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ class Chat(Object):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
client: "Client" = None,
|
client: 'Client' = None,
|
||||||
id: id,
|
id: id,
|
||||||
type: type,
|
type: type,
|
||||||
is_verified: bool = None,
|
is_verified: bool = None,
|
||||||
@@ -41,7 +41,7 @@ class Chat(Object):
|
|||||||
username: str = None,
|
username: str = None,
|
||||||
first_name: str = None,
|
first_name: str = None,
|
||||||
last_name: str = None,
|
last_name: str = None,
|
||||||
photo: "types.ChatPhoto" = None,
|
photo: 'types.ChatPhoto' = None,
|
||||||
bio: str = None,
|
bio: str = None,
|
||||||
description: str = None,
|
description: str = None,
|
||||||
dc_id: int = None,
|
dc_id: int = None,
|
||||||
@@ -51,12 +51,12 @@ class Chat(Object):
|
|||||||
sticker_set_name: str = None,
|
sticker_set_name: str = None,
|
||||||
can_set_sticker_set: bool = None,
|
can_set_sticker_set: bool = None,
|
||||||
members_count: int = None,
|
members_count: int = None,
|
||||||
restrictions: List["types.Restriction"] = None,
|
restrictions: list['types.Restriction'] = None,
|
||||||
permissions: "types.ChatPermissions" = None,
|
permissions: 'types.ChatPermissions' = None,
|
||||||
distance: int = None,
|
distance: int = None,
|
||||||
linked_chat: "types.Chat" = None,
|
linked_chat: 'types.Chat' = None,
|
||||||
send_as_chat: "types.Chat" = None,
|
send_as_chat: 'types.Chat' = None,
|
||||||
available_reactions: Optional["types.ChatReactions"] = None,
|
available_reactions: Optional['types.ChatReactions'] = None,
|
||||||
is_admin: bool = False,
|
is_admin: bool = False,
|
||||||
deactivated: bool = False,
|
deactivated: bool = False,
|
||||||
):
|
):
|
||||||
@@ -94,98 +94,82 @@ class Chat(Object):
|
|||||||
self.deactivated = deactivated
|
self.deactivated = deactivated
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_user_chat(client, user: raw.types.User) -> "Chat":
|
def _parse_user_chat(client, user: raw.types.User) -> 'Chat':
|
||||||
peer_id = user.id
|
peer_id = user.id
|
||||||
|
|
||||||
return Chat(
|
return Chat(
|
||||||
id=peer_id,
|
id=peer_id,
|
||||||
type=enums.ChatType.BOT if user.bot else enums.ChatType.PRIVATE,
|
type=enums.ChatType.BOT if user.bot else enums.ChatType.PRIVATE,
|
||||||
is_verified=getattr(user, "verified", None),
|
is_verified=getattr(user, 'verified', None),
|
||||||
is_restricted=getattr(user, "restricted", None),
|
is_restricted=getattr(user, 'restricted', None),
|
||||||
is_scam=getattr(user, "scam", None),
|
is_scam=getattr(user, 'scam', None),
|
||||||
is_fake=getattr(user, "fake", None),
|
is_fake=getattr(user, 'fake', None),
|
||||||
is_support=getattr(user, "support", None),
|
is_support=getattr(user, 'support', None),
|
||||||
username=user.username,
|
username=user.username,
|
||||||
first_name=user.first_name,
|
first_name=user.first_name,
|
||||||
last_name=user.last_name,
|
last_name=user.last_name,
|
||||||
photo=types.ChatPhoto._parse(client, user.photo, peer_id, user.access_hash),
|
photo=types.ChatPhoto._parse(client, user.photo, peer_id, user.access_hash),
|
||||||
restrictions=types.List(
|
restrictions=types.List([types.Restriction._parse(r) for r in user.restriction_reason]) or None,
|
||||||
[types.Restriction._parse(r) for r in user.restriction_reason]
|
dc_id=getattr(getattr(user, 'photo', None), 'dc_id', None),
|
||||||
)
|
|
||||||
or None,
|
|
||||||
dc_id=getattr(getattr(user, "photo", None), "dc_id", None),
|
|
||||||
client=client,
|
client=client,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_chat_chat(client, chat: raw.types.Chat) -> "Chat":
|
def _parse_chat_chat(client, chat: raw.types.Chat) -> 'Chat':
|
||||||
peer_id = -chat.id
|
peer_id = -chat.id
|
||||||
return Chat(
|
return Chat(
|
||||||
id=peer_id,
|
id=peer_id,
|
||||||
type=enums.ChatType.GROUP,
|
type=enums.ChatType.GROUP,
|
||||||
title=chat.title,
|
title=chat.title,
|
||||||
is_creator=getattr(chat, "creator", None),
|
is_creator=getattr(chat, 'creator', None),
|
||||||
photo=types.ChatPhoto._parse(
|
photo=types.ChatPhoto._parse(client, getattr(chat, 'photo', None), peer_id, 0),
|
||||||
client, getattr(chat, "photo", None), peer_id, 0
|
permissions=types.ChatPermissions._parse(getattr(chat, 'default_banned_rights', None)),
|
||||||
),
|
members_count=getattr(chat, 'participants_count', None),
|
||||||
permissions=types.ChatPermissions._parse(
|
dc_id=getattr(getattr(chat, 'photo', None), 'dc_id', None),
|
||||||
getattr(chat, "default_banned_rights", None)
|
has_protected_content=getattr(chat, 'noforwards', None),
|
||||||
),
|
|
||||||
members_count=getattr(chat, "participants_count", None),
|
|
||||||
dc_id=getattr(getattr(chat, "photo", None), "dc_id", None),
|
|
||||||
has_protected_content=getattr(chat, "noforwards", None),
|
|
||||||
client=client,
|
client=client,
|
||||||
is_admin=bool(getattr(chat, "admin_rights", False)),
|
is_admin=bool(getattr(chat, 'admin_rights', False)),
|
||||||
deactivated=chat.deactivated,
|
deactivated=chat.deactivated,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_channel_chat(client, channel: raw.types.Channel) -> "Chat":
|
def _parse_channel_chat(client, channel: raw.types.Channel) -> 'Chat':
|
||||||
peer_id = utils.get_channel_id(channel.id)
|
peer_id = utils.get_channel_id(channel.id)
|
||||||
restriction_reason = getattr(channel, "restriction_reason", [])
|
restriction_reason = getattr(channel, 'restriction_reason', [])
|
||||||
|
|
||||||
return Chat(
|
return Chat(
|
||||||
id=peer_id,
|
id=peer_id,
|
||||||
type=(
|
type=(enums.ChatType.SUPERGROUP if getattr(channel, 'megagroup', None) else enums.ChatType.CHANNEL),
|
||||||
enums.ChatType.SUPERGROUP
|
is_verified=getattr(channel, 'verified', None),
|
||||||
if getattr(channel, "megagroup", None)
|
is_restricted=getattr(channel, 'restricted', None),
|
||||||
else enums.ChatType.CHANNEL
|
is_creator=getattr(channel, 'creator', None),
|
||||||
),
|
is_scam=getattr(channel, 'scam', None),
|
||||||
is_verified=getattr(channel, "verified", None),
|
is_fake=getattr(channel, 'fake', None),
|
||||||
is_restricted=getattr(channel, "restricted", None),
|
|
||||||
is_creator=getattr(channel, "creator", None),
|
|
||||||
is_scam=getattr(channel, "scam", None),
|
|
||||||
is_fake=getattr(channel, "fake", None),
|
|
||||||
title=channel.title,
|
title=channel.title,
|
||||||
username=getattr(channel, "username", None),
|
username=getattr(channel, 'username', None),
|
||||||
photo=types.ChatPhoto._parse(
|
photo=types.ChatPhoto._parse(
|
||||||
client,
|
client,
|
||||||
getattr(channel, "photo", None),
|
getattr(channel, 'photo', None),
|
||||||
peer_id,
|
peer_id,
|
||||||
getattr(channel, "access_hash", 0),
|
getattr(channel, 'access_hash', 0),
|
||||||
),
|
),
|
||||||
restrictions=types.List(
|
restrictions=types.List([types.Restriction._parse(r) for r in restriction_reason]) or None,
|
||||||
[types.Restriction._parse(r) for r in restriction_reason]
|
permissions=types.ChatPermissions._parse(getattr(channel, 'default_banned_rights', None)),
|
||||||
)
|
members_count=getattr(channel, 'participants_count', None),
|
||||||
or None,
|
dc_id=getattr(getattr(channel, 'photo', None), 'dc_id', None),
|
||||||
permissions=types.ChatPermissions._parse(
|
has_protected_content=getattr(channel, 'noforwards', None),
|
||||||
getattr(channel, "default_banned_rights", None)
|
is_admin=bool(getattr(channel, 'admin_rights', False)),
|
||||||
),
|
|
||||||
members_count=getattr(channel, "participants_count", None),
|
|
||||||
dc_id=getattr(getattr(channel, "photo", None), "dc_id", None),
|
|
||||||
has_protected_content=getattr(channel, "noforwards", None),
|
|
||||||
is_admin=bool(getattr(channel, "admin_rights", False)),
|
|
||||||
client=client,
|
client=client,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse(
|
def _parse(
|
||||||
client,
|
client,
|
||||||
message: Union[raw.types.Message, raw.types.MessageService],
|
message: raw.types.Message | raw.types.MessageService,
|
||||||
users: dict,
|
users: dict,
|
||||||
chats: dict,
|
chats: dict,
|
||||||
is_chat: bool,
|
is_chat: bool,
|
||||||
) -> "Chat":
|
) -> 'Chat':
|
||||||
from_id = utils.get_raw_peer_id(message.from_id)
|
from_id = utils.get_raw_peer_id(message.from_id)
|
||||||
peer_id = utils.get_raw_peer_id(message.peer_id)
|
peer_id = utils.get_raw_peer_id(message.peer_id)
|
||||||
chat_id = (peer_id or from_id) if is_chat else (from_id or peer_id)
|
chat_id = (peer_id or from_id) if is_chat else (from_id or peer_id)
|
||||||
@@ -211,9 +195,9 @@ class Dialog(Object):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
client: "Client" = None,
|
client: 'Client' = None,
|
||||||
chat: "types.Chat",
|
chat: 'types.Chat',
|
||||||
top_message: "types.Message",
|
top_message: 'types.Message',
|
||||||
unread_messages_count: int,
|
unread_messages_count: int,
|
||||||
unread_mentions_count: int,
|
unread_mentions_count: int,
|
||||||
unread_mark: bool,
|
unread_mark: bool,
|
||||||
@@ -229,7 +213,7 @@ class Dialog(Object):
|
|||||||
self.is_pinned = is_pinned
|
self.is_pinned = is_pinned
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse(client, dialog: "raw.types.Dialog", messages, users, chats) -> "Dialog":
|
def _parse(client, dialog: 'raw.types.Dialog', messages, users, chats) -> 'Dialog':
|
||||||
return Dialog(
|
return Dialog(
|
||||||
chat=Chat._parse_dialog(client, dialog.peer, users, chats),
|
chat=Chat._parse_dialog(client, dialog.peer, users, chats),
|
||||||
top_message=messages.get(utils.get_peer_id(dialog.peer)),
|
top_message=messages.get(utils.get_peer_id(dialog.peer)),
|
||||||
@@ -241,9 +225,7 @@ class Dialog(Object):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def get_dialogs(
|
async def get_dialogs(self: 'Client', limit: int = 0) -> AsyncGenerator['types.Dialog', None] | None:
|
||||||
self: "Client", limit: int = 0
|
|
||||||
) -> Optional[AsyncGenerator["types.Dialog", None]]:
|
|
||||||
current = 0
|
current = 0
|
||||||
total = limit or (1 << 31) - 1
|
total = limit or (1 << 31) - 1
|
||||||
limit = min(100, total)
|
limit = min(100, total)
|
||||||
@@ -287,7 +269,7 @@ async def get_dialogs(
|
|||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("admlist", prefix) & filters.me)
|
@Client.on_message(filters.command('admlist', prefix) & filters.me)
|
||||||
async def admlist(client: Client, message: types.Message):
|
async def admlist(client: Client, message: types.Message):
|
||||||
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
|
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
|
||||||
|
|
||||||
@@ -298,48 +280,46 @@ async def admlist(client: Client, message: types.Message):
|
|||||||
owned_usernamed_chats = []
|
owned_usernamed_chats = []
|
||||||
async for dialog in get_dialogs(client):
|
async for dialog in get_dialogs(client):
|
||||||
chat = dialog.chat
|
chat = dialog.chat
|
||||||
if getattr(chat, "deactivated", False):
|
if getattr(chat, 'deactivated', False):
|
||||||
continue
|
continue
|
||||||
if getattr(chat, "is_creator", False) and getattr(chat, "username", None):
|
if getattr(chat, 'is_creator', False) and getattr(chat, 'username', None):
|
||||||
owned_usernamed_chats.append(chat)
|
owned_usernamed_chats.append(chat)
|
||||||
elif getattr(chat, "is_creator", False):
|
elif getattr(chat, 'is_creator', False):
|
||||||
owned_chats.append(chat)
|
owned_chats.append(chat)
|
||||||
elif getattr(chat, "is_admin", False):
|
elif getattr(chat, 'is_admin', False):
|
||||||
adminned_chats.append(chat)
|
adminned_chats.append(chat)
|
||||||
|
|
||||||
text = "<b>Adminned chats:</b>\n"
|
text = '<b>Adminned chats:</b>\n'
|
||||||
for index, chat in enumerate(adminned_chats):
|
for index, chat in enumerate(adminned_chats):
|
||||||
cid = str(chat.id).replace("-100", "")
|
cid = str(chat.id).replace('-100', '')
|
||||||
text += f"{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n"
|
text += f'{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n'
|
||||||
|
|
||||||
text += "\n<b>Owned chats:</b>\n"
|
text += '\n<b>Owned chats:</b>\n'
|
||||||
for index, chat in enumerate(owned_chats):
|
for index, chat in enumerate(owned_chats):
|
||||||
cid = str(chat.id).replace("-100", "")
|
cid = str(chat.id).replace('-100', '')
|
||||||
text += f"{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n"
|
text += f'{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n'
|
||||||
|
|
||||||
text += "\n<b>Owned chats with username:</b>\n"
|
text += '\n<b>Owned chats with username:</b>\n'
|
||||||
for index, chat in enumerate(owned_usernamed_chats):
|
for index, chat in enumerate(owned_usernamed_chats):
|
||||||
cid = str(chat.id).replace("-100", "")
|
cid = str(chat.id).replace('-100', '')
|
||||||
text += f"{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n"
|
text += f'{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n'
|
||||||
|
|
||||||
stop = perf_counter()
|
stop = perf_counter()
|
||||||
total_count = (
|
total_count = len(adminned_chats) + len(owned_chats) + len(owned_usernamed_chats)
|
||||||
len(adminned_chats) + len(owned_chats) + len(owned_usernamed_chats)
|
|
||||||
)
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
text + "\n"
|
text + '\n'
|
||||||
f"<b><u>Total:</u></b> {total_count}"
|
f'<b><u>Total:</u></b> {total_count}'
|
||||||
f"\n<b><u>Adminned chats:</u></b> {len(adminned_chats)}\n"
|
f'\n<b><u>Adminned chats:</u></b> {len(adminned_chats)}\n'
|
||||||
f"<b><u>Owned chats:</u></b> {len(owned_chats)}\n"
|
f'<b><u>Owned chats:</u></b> {len(owned_chats)}\n'
|
||||||
f"<b><u>Owned chats with username:</u></b> {len(owned_usernamed_chats)}\n\n"
|
f'<b><u>Owned chats with username:</u></b> {len(owned_usernamed_chats)}\n\n'
|
||||||
f"Done in {round(stop - start, 3)} seconds.",
|
f'Done in {round(stop - start, 3)} seconds.',
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("admcount", prefix) & filters.me)
|
@Client.on_message(filters.command('admcount', prefix) & filters.me)
|
||||||
async def admcount(client: Client, message: types.Message):
|
async def admcount(client: Client, message: types.Message):
|
||||||
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
|
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
|
||||||
|
|
||||||
@@ -350,31 +330,31 @@ async def admcount(client: Client, message: types.Message):
|
|||||||
owned_usernamed_chats = 0
|
owned_usernamed_chats = 0
|
||||||
async for dialog in get_dialogs(client):
|
async for dialog in get_dialogs(client):
|
||||||
chat = dialog.chat
|
chat = dialog.chat
|
||||||
if getattr(chat, "deactivated", False):
|
if getattr(chat, 'deactivated', False):
|
||||||
continue
|
continue
|
||||||
if getattr(chat, "is_creator", False) and getattr(chat, "username", None):
|
if getattr(chat, 'is_creator', False) and getattr(chat, 'username', None):
|
||||||
owned_usernamed_chats += 1
|
owned_usernamed_chats += 1
|
||||||
elif getattr(chat, "is_creator", False):
|
elif getattr(chat, 'is_creator', False):
|
||||||
owned_chats += 1
|
owned_chats += 1
|
||||||
elif getattr(chat, "is_admin", False):
|
elif getattr(chat, 'is_admin', False):
|
||||||
adminned_chats += 1
|
adminned_chats += 1
|
||||||
|
|
||||||
stop = perf_counter()
|
stop = perf_counter()
|
||||||
total_count = adminned_chats + owned_chats + owned_usernamed_chats
|
total_count = adminned_chats + owned_chats + owned_usernamed_chats
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b><u>Total:</u></b> {total_count}"
|
f'<b><u>Total:</u></b> {total_count}'
|
||||||
f"\n<b><u>Adminned chats:</u></b> {adminned_chats}\n"
|
f'\n<b><u>Adminned chats:</u></b> {adminned_chats}\n'
|
||||||
f"<b><u>Owned chats:</u></b> {owned_chats}\n"
|
f'<b><u>Owned chats:</u></b> {owned_chats}\n'
|
||||||
f"<b><u>Owned chats with username:</u></b> {owned_usernamed_chats}\n\n"
|
f'<b><u>Owned chats with username:</u></b> {owned_usernamed_chats}\n\n'
|
||||||
f"Done in {round(stop - start, 3)} seconds.\n\n"
|
f'Done in {round(stop - start, 3)} seconds.\n\n'
|
||||||
f"<b>Get full list: </b><code>{prefix}admlist</code>",
|
f'<b>Get full list: </b><code>{prefix}admlist</code>',
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
modules_help["admlist"] = {
|
modules_help['admlist'] = {
|
||||||
"admcount": "Get count of adminned and owned chats",
|
'admcount': 'Get count of adminned and owned chats',
|
||||||
"admlist": "Get list of adminned and owned chats",
|
'admlist': 'Get list of adminned and owned chats',
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-34
@@ -17,72 +17,62 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
from pyrogram import Client, filters, types
|
from pyrogram import Client, filters, types
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
# avoid using global variables
|
# avoid using global variables
|
||||||
afk_info = db.get(
|
afk_info = db.get(
|
||||||
"core.afk",
|
'core.afk',
|
||||||
"afk_info",
|
'afk_info',
|
||||||
{
|
{
|
||||||
"start": 0,
|
'start': 0,
|
||||||
"is_afk": False,
|
'is_afk': False,
|
||||||
"reason": "",
|
'reason': '',
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
is_afk = filters.create(lambda _, __, ___: afk_info["is_afk"])
|
is_afk = filters.create(lambda _, __, ___: afk_info['is_afk'])
|
||||||
is_support = filters.create(lambda _, __, message: message.chat.is_support)
|
is_support = filters.create(lambda _, __, message: message.chat.is_support)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(
|
||||||
is_afk
|
is_afk & (filters.private | filters.mentioned) & ~filters.channel & ~filters.me & ~filters.bot & ~is_support
|
||||||
& (filters.private | filters.mentioned)
|
|
||||||
& ~filters.channel
|
|
||||||
& ~filters.me
|
|
||||||
& ~filters.bot
|
|
||||||
& ~is_support
|
|
||||||
)
|
)
|
||||||
async def afk_handler(_, message: types.Message):
|
async def afk_handler(_, message: types.Message):
|
||||||
start = datetime.datetime.fromtimestamp(afk_info["start"])
|
start = datetime.datetime.fromtimestamp(afk_info['start'])
|
||||||
end = datetime.datetime.now().replace(microsecond=0)
|
end = datetime.datetime.now().replace(microsecond=0)
|
||||||
afk_time = end - start
|
afk_time = end - start
|
||||||
await message.reply(
|
await message.reply(f"<b>I'm AFK {afk_time}\nReason:</b> <i>{afk_info['reason']}</i>")
|
||||||
f"<b>I'm AFK {afk_time}\nReason:</b> <i>{afk_info['reason']}</i>"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("afk", prefix) & filters.me)
|
@Client.on_message(filters.command('afk', prefix) & filters.me)
|
||||||
async def afk(_, message):
|
async def afk(_, message):
|
||||||
if len(message.text.split()) >= 2:
|
if len(message.text.split()) >= 2:
|
||||||
reason = message.text.split(" ", maxsplit=1)[1]
|
reason = message.text.split(' ', maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
reason = "None"
|
reason = 'None'
|
||||||
|
|
||||||
afk_info["start"] = int(datetime.datetime.now().timestamp())
|
afk_info['start'] = int(datetime.datetime.now().timestamp())
|
||||||
afk_info["is_afk"] = True
|
afk_info['is_afk'] = True
|
||||||
afk_info["reason"] = reason
|
afk_info['reason'] = reason
|
||||||
|
|
||||||
await message.edit(f"<b>I'm going AFK.\n" f"Reason:</b> <i>{reason}</i>")
|
await message.edit(f"<b>I'm going AFK.\nReason:</b> <i>{reason}</i>")
|
||||||
|
|
||||||
db.set("core.afk", "afk_info", afk_info)
|
db.set('core.afk', 'afk_info', afk_info)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("unafk", prefix) & filters.me)
|
@Client.on_message(filters.command('unafk', prefix) & filters.me)
|
||||||
async def unafk(_, message):
|
async def unafk(_, message):
|
||||||
if afk_info["is_afk"]:
|
if afk_info['is_afk']:
|
||||||
start = datetime.datetime.fromtimestamp(afk_info["start"])
|
start = datetime.datetime.fromtimestamp(afk_info['start'])
|
||||||
end = datetime.datetime.now().replace(microsecond=0)
|
end = datetime.datetime.now().replace(microsecond=0)
|
||||||
afk_time = end - start
|
afk_time = end - start
|
||||||
await message.edit(
|
await message.edit(f"<b>I'm not AFK anymore.\nI was afk {afk_time}</b>")
|
||||||
f"<b>I'm not AFK anymore.\n" f"I was afk {afk_time}</b>"
|
afk_info['is_afk'] = False
|
||||||
)
|
|
||||||
afk_info["is_afk"] = False
|
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>You weren't afk</b>")
|
await message.edit("<b>You weren't afk</b>")
|
||||||
|
|
||||||
db.set("core.afk", "afk_info", afk_info)
|
db.set('core.afk', 'afk_info', afk_info)
|
||||||
|
|
||||||
|
|
||||||
modules_help["afk"] = {"afk [reason]": "Go to afk", "unafk": "Get out of AFK"}
|
modules_help['afk'] = {'afk [reason]': 'Go to afk', 'unafk': 'Get out of AFK'}
|
||||||
|
|||||||
+35
-48
@@ -1,129 +1,116 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, import_library
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
genai = import_library("google.generativeai", "google-generativeai")
|
genai = import_library('google.generativeai', 'google-generativeai')
|
||||||
|
|
||||||
from utils.config import gemini_key
|
from utils.config import gemini_key
|
||||||
|
|
||||||
genai.configure(api_key=gemini_key)
|
genai.configure(api_key=gemini_key)
|
||||||
|
|
||||||
generation_config_cook = {
|
generation_config_cook = {
|
||||||
"temperature": 0.35,
|
'temperature': 0.35,
|
||||||
"top_p": 0.95,
|
'top_p': 0.95,
|
||||||
"top_k": 40,
|
'top_k': 40,
|
||||||
"max_output_tokens": 1024,
|
'max_output_tokens': 1024,
|
||||||
}
|
}
|
||||||
|
|
||||||
model = genai.GenerativeModel("gemini-1.5-flash-latest")
|
model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
||||||
model_cook = genai.GenerativeModel(
|
model_cook = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config=generation_config_cook)
|
||||||
model_name="gemini-1.5-flash-latest", generation_config=generation_config_cook
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("getai", prefix) & filters.me)
|
@Client.on_message(filters.command('getai', prefix) & filters.me)
|
||||||
async def getai(_, message: Message):
|
async def getai(_, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.edit_text("<code>Please Wait...</code>")
|
await message.edit_text('<code>Please Wait...</code>')
|
||||||
try:
|
try:
|
||||||
base_img = await message.reply_to_message.download()
|
base_img = await message.reply_to_message.download()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return await message.edit_text("<code>Please reply to an image...</code>")
|
return await message.edit_text('<code>Please reply to an image...</code>')
|
||||||
|
|
||||||
img = Image.open(base_img)
|
img = Image.open(base_img)
|
||||||
prompt = "Get details of given image, be as accurate as possible."
|
prompt = 'Get details of given image, be as accurate as possible.'
|
||||||
|
|
||||||
response = model.generate_content([prompt, img])
|
response = model.generate_content([prompt, img])
|
||||||
|
|
||||||
await message.edit_text(
|
await message.edit_text(f'**Detail Of Image:** {response.text}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"**Detail Of Image:** {response.text}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
os.remove(base_img)
|
os.remove(base_img)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("aicook", prefix) & filters.me)
|
@Client.on_message(filters.command('aicook', prefix) & filters.me)
|
||||||
async def aicook(_, message: Message):
|
async def aicook(_, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
try:
|
try:
|
||||||
await message.edit_text("<code>Cooking...</code>")
|
await message.edit_text('<code>Cooking...</code>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
base_img = await message.reply_to_message.download()
|
base_img = await message.reply_to_message.download()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return await message.edit_text(
|
return await message.edit_text('<code>Please reply to an image...</code>')
|
||||||
"<code>Please reply to an image...</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
img = Image.open(base_img)
|
img = Image.open(base_img)
|
||||||
cook_img = [
|
cook_img = [
|
||||||
"Accurately identify the baked good in the image and provide an appropriate and recipe consistent with your analysis. ",
|
'Accurately identify the baked good in the image and provide an appropriate and recipe consistent with your analysis. ',
|
||||||
img,
|
img,
|
||||||
]
|
]
|
||||||
|
|
||||||
response = model_cook.generate_content(cook_img)
|
response = model_cook.generate_content(cook_img)
|
||||||
|
|
||||||
await message.edit_text(
|
await message.edit_text(f'{response.text}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"{response.text}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
os.remove(base_img)
|
os.remove(base_img)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(str(e))
|
await message.edit_text(str(e))
|
||||||
return await message.edit_text("<code>Please reply to an image...</code>")
|
return await message.edit_text('<code>Please reply to an image...</code>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("aiseller", prefix) & filters.me)
|
@Client.on_message(filters.command('aiseller', prefix) & filters.me)
|
||||||
async def aiseller(_, message: Message):
|
async def aiseller(_, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
try:
|
try:
|
||||||
await message.edit_text("<code>Generating...</code>")
|
await message.edit_text('<code>Generating...</code>')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
taud = message.text.split(maxsplit=1)[1]
|
taud = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
return await message.edit_text(
|
return await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}aiseller [target audience] [reply to product image]</code>"
|
f'<b>Usage: </b><code>{prefix}aiseller [target audience] [reply to product image]</code>'
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
base_img = await message.reply_to_message.download()
|
base_img = await message.reply_to_message.download()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return await message.edit_text(
|
return await message.edit_text('<code>Please reply to an image...</code>')
|
||||||
"<code>Please reply to an image...</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
img = Image.open(base_img)
|
img = Image.open(base_img)
|
||||||
sell_img = [
|
sell_img = [
|
||||||
"Given an image of a product and its target audience, write an engaging marketing description",
|
'Given an image of a product and its target audience, write an engaging marketing description',
|
||||||
"Product Image: ",
|
'Product Image: ',
|
||||||
img,
|
img,
|
||||||
"Target Audience: ",
|
'Target Audience: ',
|
||||||
taud,
|
taud,
|
||||||
]
|
]
|
||||||
|
|
||||||
response = model.generate_content(sell_img)
|
response = model.generate_content(sell_img)
|
||||||
|
|
||||||
await message.edit_text(
|
await message.edit_text(f'{response.text}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"{response.text}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
os.remove(base_img)
|
os.remove(base_img)
|
||||||
return
|
return
|
||||||
except Exception:
|
except Exception:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}aiseller [target audience] [reply to product image]</code>"
|
f'<b>Usage: </b><code>{prefix}aiseller [target audience] [reply to product image]</code>'
|
||||||
)
|
)
|
||||||
return await message.edit_text("<code>Please reply to an image...</code>")
|
return await message.edit_text('<code>Please reply to an image...</code>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["aimage"] = {
|
modules_help['aimage'] = {
|
||||||
"getai [reply to image]*": "Get details of image with Ai",
|
'getai [reply to image]*': 'Get details of image with Ai',
|
||||||
"aicook [reply to image]*": "Generate Cooking instrunctions of the given food image",
|
'aicook [reply to image]*': 'Generate Cooking instrunctions of the given food image',
|
||||||
"aiseller [target audience] [reply to product image]*": "Generate a promotional message for the given image product for the given target audience",
|
'aiseller [target audience] [reply to product image]*': 'Generate a promotional message for the given image product for the given target audience',
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-25
@@ -1,51 +1,45 @@
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from random import randint
|
from random import randint
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
from requests import get
|
|
||||||
from PIL import Image, ImageFont, ImageDraw
|
|
||||||
from textwrap import wrap
|
from textwrap import wrap
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from requests import get
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("amogus", prefix) & filters.me)
|
@Client.on_message(filters.command('amogus', prefix) & filters.me)
|
||||||
async def amogus(client: Client, message: Message):
|
async def amogus(client: Client, message: Message):
|
||||||
text = " ".join(message.command[1:])
|
text = ' '.join(message.command[1:])
|
||||||
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>amgus, tun tun tun tun tun tun tun tudududn tun tun...</b>",
|
'<b>amgus, tun tun tun tun tun tun tun tudududn tun tun...</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
clr = randint(1, 12)
|
clr = randint(1, 12)
|
||||||
|
|
||||||
url = "https://raw.githubusercontent.com/The-MoonTg-project/AmongUs/master/"
|
url = 'https://raw.githubusercontent.com/The-MoonTg-project/AmongUs/master/'
|
||||||
font = ImageFont.truetype(BytesIO(get(url + "bold.ttf").content), 60)
|
font = ImageFont.truetype(BytesIO(get(url + 'bold.ttf').content), 60)
|
||||||
imposter = Image.open(BytesIO(get(f"{url}{clr}.png").content))
|
imposter = Image.open(BytesIO(get(f'{url}{clr}.png').content))
|
||||||
|
|
||||||
text_ = "\n".join(["\n".join(wrap(part, 30)) for part in text.split("\n")])
|
text_ = '\n'.join(['\n'.join(wrap(part, 30)) for part in text.split('\n')])
|
||||||
bbox = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textbbox(
|
bbox = ImageDraw.Draw(Image.new('RGB', (1, 1))).multiline_textbbox((0, 0), text_, font, stroke_width=2)
|
||||||
(0, 0), text_, font, stroke_width=2
|
|
||||||
)
|
|
||||||
# w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
# w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||||
w, h = bbox[2], bbox[3]
|
w, h = bbox[2], bbox[3]
|
||||||
text = Image.new("RGBA", (w + 30, h + 30))
|
text = Image.new('RGBA', (w + 30, h + 30))
|
||||||
ImageDraw.Draw(text).multiline_text(
|
ImageDraw.Draw(text).multiline_text((15, 15), text_, '#FFF', font, stroke_width=2, stroke_fill='#000')
|
||||||
(15, 15), text_, "#FFF", font, stroke_width=2, stroke_fill="#000"
|
|
||||||
)
|
|
||||||
w = imposter.width + text.width + 10
|
w = imposter.width + text.width + 10
|
||||||
h = max(imposter.height, text.height)
|
h = max(imposter.height, text.height)
|
||||||
|
|
||||||
image = Image.new("RGBA", (w, h))
|
image = Image.new('RGBA', (w, h))
|
||||||
image.paste(imposter, (0, h - imposter.height), imposter)
|
image.paste(imposter, (0, h - imposter.height), imposter)
|
||||||
image.paste(text, (w - text.width, 0), text)
|
image.paste(text, (w - text.width, 0), text)
|
||||||
image.thumbnail((512, 512))
|
image.thumbnail((512, 512))
|
||||||
|
|
||||||
output = BytesIO()
|
output = BytesIO()
|
||||||
output.name = "imposter.webp"
|
output.name = 'imposter.webp'
|
||||||
image.save(output)
|
image.save(output)
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
|
|
||||||
@@ -53,6 +47,4 @@ async def amogus(client: Client, message: Message):
|
|||||||
await client.send_sticker(message.chat.id, output)
|
await client.send_sticker(message.chat.id, output)
|
||||||
|
|
||||||
|
|
||||||
modules_help["amogus"] = {
|
modules_help['amogus'] = {'amogus [text]': 'amgus, tun tun tun tun tun tun tun tudududn tun tun'}
|
||||||
"amogus [text]": "amgus, tun tun tun tun tun tun tun tudududn tun tun"
|
|
||||||
}
|
|
||||||
|
|||||||
+60
-80
@@ -5,92 +5,78 @@ from io import BytesIO
|
|||||||
from random import choice, randint
|
from random import choice, randint
|
||||||
from textwrap import wrap
|
from textwrap import wrap
|
||||||
|
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
|
||||||
from click import edit
|
|
||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, filters, enums
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.scripts import edit_or_reply, ReplyCheck
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
from utils.scripts import ReplyCheck, edit_or_reply
|
||||||
|
|
||||||
|
|
||||||
async def amongus_gen(text: str, clr: int) -> str:
|
async def amongus_gen(text: str, clr: int) -> str:
|
||||||
url = (
|
url = 'https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/Amongus/'
|
||||||
"https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/Amongus/"
|
|
||||||
)
|
|
||||||
font = ImageFont.truetype(
|
font = ImageFont.truetype(
|
||||||
BytesIO(
|
BytesIO(
|
||||||
requests.get(
|
requests.get('https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/fonts/bold.ttf').content
|
||||||
"https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/fonts/bold.ttf"
|
|
||||||
).content
|
|
||||||
),
|
),
|
||||||
60,
|
60,
|
||||||
)
|
)
|
||||||
imposter = Image.open(BytesIO(requests.get(f"{url}{clr}.png").content))
|
imposter = Image.open(BytesIO(requests.get(f'{url}{clr}.png').content))
|
||||||
text_ = "\n".join("\n".join(wrap(part, 30)) for part in text.split("\n"))
|
text_ = '\n'.join('\n'.join(wrap(part, 30)) for part in text.split('\n'))
|
||||||
bbox = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textbbox(
|
bbox = ImageDraw.Draw(Image.new('RGB', (1, 1))).multiline_textbbox((0, 0), text_, font, stroke_width=2)
|
||||||
(0, 0), text_, font, stroke_width=2
|
|
||||||
)
|
|
||||||
w, h = bbox[2], bbox[3]
|
w, h = bbox[2], bbox[3]
|
||||||
text = Image.new("RGBA", (w + 30, h + 30))
|
text = Image.new('RGBA', (w + 30, h + 30))
|
||||||
ImageDraw.Draw(text).multiline_text(
|
ImageDraw.Draw(text).multiline_text((15, 15), text_, '#FFF', font, stroke_width=2, stroke_fill='#000')
|
||||||
(15, 15), text_, "#FFF", font, stroke_width=2, stroke_fill="#000"
|
|
||||||
)
|
|
||||||
w = imposter.width + text.width + 10
|
w = imposter.width + text.width + 10
|
||||||
h = max(imposter.height, text.height)
|
h = max(imposter.height, text.height)
|
||||||
image = Image.new("RGBA", (w, h))
|
image = Image.new('RGBA', (w, h))
|
||||||
image.paste(imposter, (0, h - imposter.height), imposter)
|
image.paste(imposter, (0, h - imposter.height), imposter)
|
||||||
image.paste(text, (w - text.width, 0), text)
|
image.paste(text, (w - text.width, 0), text)
|
||||||
image.thumbnail((512, 512))
|
image.thumbnail((512, 512))
|
||||||
output = BytesIO()
|
output = BytesIO()
|
||||||
output.name = "imposter.webp"
|
output.name = 'imposter.webp'
|
||||||
image.save(output, "WebP")
|
image.save(output, 'WebP')
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
async def get_imposter_img(text: str) -> BytesIO:
|
async def get_imposter_img(text: str) -> BytesIO:
|
||||||
background = requests.get(
|
background = requests.get(
|
||||||
f"https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/imposter/impostor{randint(1, 22)}.png"
|
f'https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/imposter/impostor{randint(1, 22)}.png'
|
||||||
).content
|
).content
|
||||||
font = requests.get(
|
font = requests.get(
|
||||||
"https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/fonts/roboto_regular.ttf"
|
'https://github.com/TgCatUB/CatUserbot-Resources/raw/master/Resources/fonts/roboto_regular.ttf'
|
||||||
).content
|
).content
|
||||||
font = BytesIO(font)
|
font = BytesIO(font)
|
||||||
font = ImageFont.truetype(font, 30)
|
font = ImageFont.truetype(font, 30)
|
||||||
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
|
image = Image.new('RGBA', (1, 1), (0, 0, 0, 0))
|
||||||
draw = ImageDraw.Draw(image)
|
draw = ImageDraw.Draw(image)
|
||||||
bbox = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textbbox(
|
bbox = ImageDraw.Draw(Image.new('RGB', (1, 1))).multiline_textbbox((0, 0), text, font, stroke_width=2)
|
||||||
(0, 0), text, font, stroke_width=2
|
|
||||||
)
|
|
||||||
w, h = bbox[2], bbox[3]
|
w, h = bbox[2], bbox[3]
|
||||||
image = Image.open(BytesIO(background))
|
image = Image.open(BytesIO(background))
|
||||||
x, y = image.size
|
x, y = image.size
|
||||||
draw = ImageDraw.Draw(image)
|
draw = ImageDraw.Draw(image)
|
||||||
draw.multiline_text(
|
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill='white', align='center')
|
||||||
((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center"
|
|
||||||
)
|
|
||||||
output = BytesIO()
|
output = BytesIO()
|
||||||
output.name = "impostor.png"
|
output.name = 'impostor.png'
|
||||||
image.save(output, "PNG")
|
image.save(output, 'PNG')
|
||||||
output.seek(0)
|
output.seek(0)
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("amongus", prefix) & filters.me)
|
@Client.on_message(filters.command('amongus', prefix) & filters.me)
|
||||||
async def amongus_cmd(client: Client, message: Message):
|
async def amongus_cmd(client: Client, message: Message):
|
||||||
text = " ".join(message.command[1:]) if len(message.command) > 1 else ""
|
text = ' '.join(message.command[1:]) if len(message.command) > 1 else ''
|
||||||
reply = message.reply_to_message
|
reply = message.reply_to_message
|
||||||
await message.edit("tun tun tun...")
|
await message.edit('tun tun tun...')
|
||||||
if not text and reply:
|
if not text and reply:
|
||||||
text = reply.text or reply.caption or ""
|
text = reply.text or reply.caption or ''
|
||||||
|
|
||||||
clr = re.findall(r"-c\d+", text)
|
clr = re.findall(r'-c\d+', text)
|
||||||
try:
|
try:
|
||||||
clr = clr[0]
|
clr = clr[0]
|
||||||
clr = clr.replace("-c", "")
|
clr = clr.replace('-c', '')
|
||||||
text = text.replace(f"-c{clr}", "")
|
text = text.replace(f'-c{clr}', '')
|
||||||
clr = int(clr)
|
clr = int(clr)
|
||||||
if clr > 12 or clr < 1:
|
if clr > 12 or clr < 1:
|
||||||
clr = randint(1, 12)
|
clr = randint(1, 12)
|
||||||
@@ -99,9 +85,9 @@ async def amongus_cmd(client: Client, message: Message):
|
|||||||
|
|
||||||
if not text:
|
if not text:
|
||||||
if not reply:
|
if not reply:
|
||||||
text = f"{message.from_user.first_name} Was a traitor!"
|
text = f'{message.from_user.first_name} Was a traitor!'
|
||||||
else:
|
else:
|
||||||
text = f"{reply.from_user.first_name} Was a traitor!"
|
text = f'{reply.from_user.first_name} Was a traitor!'
|
||||||
|
|
||||||
imposter_file = await amongus_gen(text, clr)
|
imposter_file = await amongus_gen(text, clr)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
@@ -112,22 +98,22 @@ async def amongus_cmd(client: Client, message: Message):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("imposter", prefix) & filters.me)
|
@Client.on_message(filters.command('imposter', prefix) & filters.me)
|
||||||
async def imposter_cmd(client: Client, message: Message):
|
async def imposter_cmd(client: Client, message: Message):
|
||||||
remain = randint(1, 2)
|
remain = randint(1, 2)
|
||||||
imps = ["wasn't the impostor", "was the impostor"]
|
imps = ["wasn't the impostor", 'was the impostor']
|
||||||
|
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
user = message.reply_to_message.from_user
|
user = message.reply_to_message.from_user
|
||||||
text = f"{user.first_name} {choice(imps)}."
|
text = f'{user.first_name} {choice(imps)}.'
|
||||||
else:
|
else:
|
||||||
args = message.text.split()[1:]
|
args = message.text.split()[1:]
|
||||||
if args:
|
if args:
|
||||||
text = " ".join(args)
|
text = ' '.join(args)
|
||||||
else:
|
else:
|
||||||
text = f"{message.from_user.first_name} {choice(imps)}."
|
text = f'{message.from_user.first_name} {choice(imps)}.'
|
||||||
|
|
||||||
text += f"\n{remain} impostor(s) remain."
|
text += f'\n{remain} impostor(s) remain.'
|
||||||
imposter_file = await get_imposter_img(text)
|
imposter_file = await get_imposter_img(text)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
@@ -137,9 +123,9 @@ async def imposter_cmd(client: Client, message: Message):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["imp", "impn"], prefix) & filters.me)
|
@Client.on_message(filters.command(['imp', 'impn'], prefix) & filters.me)
|
||||||
async def imp_animation(client: Client, message: Message):
|
async def imp_animation(client: Client, message: Message):
|
||||||
name = " ".join(message.command[1:]) if len(message.command) > 1 else ""
|
name = ' '.join(message.command[1:]) if len(message.command) > 1 else ''
|
||||||
if not name:
|
if not name:
|
||||||
reply = message.reply_to_message
|
reply = message.reply_to_message
|
||||||
if reply:
|
if reply:
|
||||||
@@ -148,61 +134,55 @@ async def imp_animation(client: Client, message: Message):
|
|||||||
name = message.from_user.first_name
|
name = message.from_user.first_name
|
||||||
cmd = message.command[0].lower()
|
cmd = message.command[0].lower()
|
||||||
|
|
||||||
text1 = await edit_or_reply(message, "Uhmm... Something is wrong here!!")
|
text1 = await edit_or_reply(message, 'Uhmm... Something is wrong here!!')
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
await text1.delete()
|
await text1.delete()
|
||||||
|
|
||||||
stcr1 = await client.send_sticker(message.chat.id, "CAADAQADRwADnjOcH98isYD5RJTwAg")
|
stcr1 = await client.send_sticker(message.chat.id, 'CAADAQADRwADnjOcH98isYD5RJTwAg')
|
||||||
text2 = await message.reply(
|
text2 = await message.reply(f'<b>{message.from_user.first_name}:</b> I have to call discussion')
|
||||||
f"<b>{message.from_user.first_name}:</b> I have to call discussion"
|
|
||||||
)
|
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
await stcr1.delete()
|
await stcr1.delete()
|
||||||
await text2.delete()
|
await text2.delete()
|
||||||
|
|
||||||
stcr2 = await client.send_sticker(message.chat.id, "CAADAQADRgADnjOcH9odHIXtfgmvAg")
|
stcr2 = await client.send_sticker(message.chat.id, 'CAADAQADRgADnjOcH9odHIXtfgmvAg')
|
||||||
text3 = await message.reply(
|
text3 = await message.reply(f'<b>{message.from_user.first_name}:</b> We have to eject the imposter or will lose')
|
||||||
f"<b>{message.from_user.first_name}:</b> We have to eject the imposter or will lose"
|
|
||||||
)
|
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
await stcr2.delete()
|
await stcr2.delete()
|
||||||
await text3.delete()
|
await text3.delete()
|
||||||
|
|
||||||
stcr3 = await client.send_sticker(message.chat.id, "CAADAQADOwADnjOcH77v3Ap51R7gAg")
|
stcr3 = await client.send_sticker(message.chat.id, 'CAADAQADOwADnjOcH77v3Ap51R7gAg')
|
||||||
text4 = await message.reply("<b>Others:</b> Where???")
|
text4 = await message.reply('<b>Others:</b> Where???')
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
await text4.edit("<b>Others:</b> Who??")
|
await text4.edit('<b>Others:</b> Who??')
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
await text4.edit(
|
await text4.edit(f'<b>{message.from_user.first_name}:</b> Its {name}, I saw {name} using vent')
|
||||||
f"<b>{message.from_user.first_name}:</b> Its {name}, I saw {name} using vent"
|
|
||||||
)
|
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
await text4.edit(f"<b>Others:</b> Okay.. Vote {name}")
|
await text4.edit(f'<b>Others:</b> Okay.. Vote {name}')
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
await stcr3.delete()
|
await stcr3.delete()
|
||||||
await text4.delete()
|
await text4.delete()
|
||||||
|
|
||||||
stcr4 = await client.send_sticker(message.chat.id, "CAADAQADLwADnjOcH-wxu-ehy6NRAg")
|
stcr4 = await client.send_sticker(message.chat.id, 'CAADAQADLwADnjOcH-wxu-ehy6NRAg')
|
||||||
event = await message.reply(f"{name} is ejected.......")
|
event = await message.reply(f'{name} is ejected.......')
|
||||||
|
|
||||||
# Ejection animation
|
# Ejection animation
|
||||||
for _ in range(9):
|
for _ in range(9):
|
||||||
await asyncio.sleep(0.5)
|
await asyncio.sleep(0.5)
|
||||||
curr_pos = _ + 1
|
curr_pos = _ + 1
|
||||||
spaces_before = "ㅤ" * curr_pos
|
spaces_before = 'ㅤ' * curr_pos
|
||||||
await event.edit(f"{spaces_before}ඞ{'ㅤ' * (9 - curr_pos)}")
|
await event.edit(f'{spaces_before}ඞ{"ㅤ" * (9 - curr_pos)}')
|
||||||
|
|
||||||
await asyncio.sleep(0.5)
|
await asyncio.sleep(0.5)
|
||||||
await event.edit("ㅤㅤㅤㅤㅤㅤㅤㅤㅤ")
|
await event.edit('ㅤㅤㅤㅤㅤㅤㅤㅤㅤ')
|
||||||
await asyncio.sleep(0.2)
|
await asyncio.sleep(0.2)
|
||||||
await stcr4.delete()
|
await stcr4.delete()
|
||||||
|
|
||||||
if cmd == "imp":
|
if cmd == 'imp':
|
||||||
text = f". 。 • ゚ 。 .\n . . 。 。 . \n\n . 。 ඞ 。 . • •\n\n ゚{name} was an Imposter. 。 . 。 . 。 . \n . 。 . \n ' 0 Impostor remains 。 . . 。 . 。 . 。 . . . , 。\n ゚ . . , 。 . . 。"
|
text = f". 。 • ゚ 。 .\n . . 。 。 . \n\n . 。 ඞ 。 . • •\n\n ゚{name} was an Imposter. 。 . 。 . 。 . \n . 。 . \n ' 0 Impostor remains 。 . . 。 . 。 . 。 . . . , 。\n ゚ . . , 。 . . 。"
|
||||||
sticker_id = "CAADAQADLQADnjOcH39IqwyR6Q_0Ag"
|
sticker_id = 'CAADAQADLQADnjOcH39IqwyR6Q_0Ag'
|
||||||
else:
|
else:
|
||||||
text = f". 。 • ゚ 。 .\n . . 。 。 . \n\n . 。 ඞ 。 . • •\n\n ゚{name} was not an Imposter. 。 . 。 . 。 . \n . 。 . \n ' 1 Impostor remains 。 . . 。 . 。 . 。 . . . , 。\n ゚ . . , 。 . . 。"
|
text = f". 。 • ゚ 。 .\n . . 。 。 . \n\n . 。 ඞ 。 . • •\n\n ゚{name} was not an Imposter. 。 . 。 . 。 . \n . 。 . \n ' 1 Impostor remains 。 . . 。 . 。 . 。 . . . , 。\n ゚ . . , 。 . . 。"
|
||||||
sticker_id = "CAADAQADQAADnjOcH-WOkB8DEctJAg"
|
sticker_id = 'CAADAQADQAADnjOcH-WOkB8DEctJAg'
|
||||||
|
|
||||||
await event.edit(text)
|
await event.edit(text)
|
||||||
await asyncio.sleep(4)
|
await asyncio.sleep(4)
|
||||||
@@ -210,9 +190,9 @@ async def imp_animation(client: Client, message: Message):
|
|||||||
await client.send_sticker(message.chat.id, sticker_id)
|
await client.send_sticker(message.chat.id, sticker_id)
|
||||||
|
|
||||||
|
|
||||||
modules_help["amongus"] = {
|
modules_help['amongus'] = {
|
||||||
"amongus": "Create Among Us themed sticker [text/reply] [-c1 to -c12 for colors]",
|
'amongus': 'Create Among Us themed sticker [text/reply] [-c1 to -c12 for colors]',
|
||||||
"imposter": "Create Among Us imposter image [username/reply]",
|
'imposter': 'Create Among Us imposter image [username/reply]',
|
||||||
"imp": "Create Among Us ejection animation (imposter)",
|
'imp': 'Create Among Us ejection animation (imposter)',
|
||||||
"impn": "Create Among Us ejection animation (not imposter)",
|
'impn': 'Create Among Us ejection animation (not imposter)',
|
||||||
}
|
}
|
||||||
|
|||||||
+236
-249
File diff suppressed because one or more lines are too long
@@ -1,78 +1,73 @@
|
|||||||
import os
|
import os
|
||||||
import requests
|
|
||||||
import aiofiles
|
import aiofiles
|
||||||
|
import requests
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message, InputMediaPhoto
|
|
||||||
from pyrogram.errors import MediaCaptionTooLong
|
from pyrogram.errors import MediaCaptionTooLong
|
||||||
|
from pyrogram.types import InputMediaPhoto, Message
|
||||||
from utils.misc import prefix, modules_help
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
url = "https://api.safone.co"
|
url = 'https://api.safone.co'
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"Accept-Language": "en-US,en;q=0.9",
|
'Accept-Language': 'en-US,en;q=0.9',
|
||||||
"Connection": "keep-alive",
|
'Connection': 'keep-alive',
|
||||||
"DNT": "1",
|
'DNT': '1',
|
||||||
"Referer": "https://api.safone.co/docs",
|
'Referer': 'https://api.safone.co/docs',
|
||||||
"Sec-Fetch-Dest": "empty",
|
'Sec-Fetch-Dest': 'empty',
|
||||||
"Sec-Fetch-Mode": "cors",
|
'Sec-Fetch-Mode': 'cors',
|
||||||
"Sec-Fetch-Site": "same-origin",
|
'Sec-Fetch-Site': 'same-origin',
|
||||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
||||||
"accept": "application/json",
|
'accept': 'application/json',
|
||||||
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
||||||
"sec-ch-ua-mobile": "?0",
|
'sec-ch-ua-mobile': '?0',
|
||||||
"sec-ch-ua-platform": '"Linux"',
|
'sec-ch-ua-platform': '"Linux"',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("anime_search", prefix) & filters.me)
|
@Client.on_message(filters.command('anime_search', prefix) & filters.me)
|
||||||
async def anime_search(client: Client, message: Message):
|
async def anime_search(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
message.edit_text(
|
message.edit_text("What should i search? You didn't provided me with any value to search")
|
||||||
"What should i search? You didn't provided me with any value to search"
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(url=f'{url}/anime/search?query={query}', headers=headers, timeout=5)
|
||||||
url=f"{url}/anime/search?query={query}", headers=headers, timeout=5
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
averageScore = result["averageScore"]
|
averageScore = result['averageScore']
|
||||||
try:
|
try:
|
||||||
coverImage_url = result["imageUrl"]
|
coverImage_url = result['imageUrl']
|
||||||
coverImage = requests.get(url=coverImage_url).content
|
coverImage = requests.get(url=coverImage_url).content
|
||||||
async with aiofiles.open("coverImage.jpg", mode="wb") as f:
|
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
|
||||||
await f.write(coverImage)
|
await f.write(coverImage)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
coverImage = None
|
coverImage = None
|
||||||
|
|
||||||
title = result["title"]["english"]
|
title = result['title']['english']
|
||||||
trailer = result["trailer"]["id"]
|
trailer = result['trailer']['id']
|
||||||
description = result["description"]
|
description = result['description']
|
||||||
episodes = result["episodes"]
|
episodes = result['episodes']
|
||||||
genres = ", ".join(result["genres"])
|
genres = ', '.join(result['genres'])
|
||||||
isAdult = result["isAdult"]
|
isAdult = result['isAdult']
|
||||||
status = result["status"]
|
status = result['status']
|
||||||
studios = ", ".join(result["studios"])
|
studios = ', '.join(result['studios'])
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_media_group(
|
await client.send_media_group(
|
||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Episodes:</b> <code>{episodes}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Episodes:</b> <code>{episodes}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -85,7 +80,7 @@ async def anime_search(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Episodes:</b> <code>{episodes}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Episodes:</b> <code>{episodes}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -93,56 +88,52 @@ async def anime_search(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists("coverImage.jpg"):
|
if os.path.exists('coverImage.jpg'):
|
||||||
os.remove("coverImage.jpg")
|
os.remove('coverImage.jpg')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("manga_search", prefix) & filters.me)
|
@Client.on_message(filters.command('manga_search', prefix) & filters.me)
|
||||||
async def manga_search(client: Client, message: Message):
|
async def manga_search(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
message.edit_text(
|
message.edit_text("What should i search? You didn't provided me with any value to search")
|
||||||
"What should i search? You didn't provided me with any value to search"
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(url=f'{url}/anime/manga?query={query}', headers=headers, timeout=5)
|
||||||
url=f"{url}/anime/manga?query={query}", headers=headers, timeout=5
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
averageScore = result["averageScore"]
|
averageScore = result['averageScore']
|
||||||
try:
|
try:
|
||||||
coverImage_url = result["imageUrl"]
|
coverImage_url = result['imageUrl']
|
||||||
coverImage = requests.get(url=coverImage_url).content
|
coverImage = requests.get(url=coverImage_url).content
|
||||||
async with aiofiles.open("coverImage.jpg", mode="wb") as f:
|
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
|
||||||
await f.write(coverImage)
|
await f.write(coverImage)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
coverImage = None
|
coverImage = None
|
||||||
|
|
||||||
title = result["title"]["english"]
|
title = result['title']['english']
|
||||||
trailer = result["trailer"]["id"]
|
trailer = result['trailer']['id']
|
||||||
description = result["description"]
|
description = result['description']
|
||||||
chapters = result["chapters"]
|
chapters = result['chapters']
|
||||||
genres = ", ".join(result["genres"])
|
genres = ', '.join(result['genres'])
|
||||||
isAdult = result["isAdult"]
|
isAdult = result['isAdult']
|
||||||
status = result["status"]
|
status = result['status']
|
||||||
studios = ", ".join(result["studios"])
|
studios = ', '.join(result['studios'])
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_media_group(
|
await client.send_media_group(
|
||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Chapters:</b> <code>{chapters}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Chapters:</b> <code>{chapters}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -155,7 +146,7 @@ async def manga_search(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Chapters:</b> <code>{chapters}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Average Score:</b> <code>{averageScore}</code>\n<b>Status:</b> <code>{status}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Chapters:</b> <code>{chapters}</code>\n<b>Is Adult:</b> <code>{isAdult}</code>\n<b>Studios:</b> <code>{studios}</code>\n<b>Description:</b> <code>{description}</code>\n<b>Trailer:</b> <a href='https://youtu.be/{trailer}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -163,54 +154,50 @@ async def manga_search(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists("coverImage.jpg"):
|
if os.path.exists('coverImage.jpg'):
|
||||||
os.remove("coverImage.jpg")
|
os.remove('coverImage.jpg')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("character", prefix) & filters.me)
|
@Client.on_message(filters.command('character', prefix) & filters.me)
|
||||||
async def character(client: Client, message: Message):
|
async def character(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
message.edit_text(
|
message.edit_text("What should i search? You didn't provided me with any value to search")
|
||||||
"What should i search? You didn't provided me with any value to search"
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(url=f'{url}/anime/character?query={query}', headers=headers, timeout=5)
|
||||||
url=f"{url}/anime/character?query={query}", headers=headers, timeout=5
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
coverImage_url = result["image"]["large"]
|
coverImage_url = result['image']['large']
|
||||||
coverImage = requests.get(url=coverImage_url).content
|
coverImage = requests.get(url=coverImage_url).content
|
||||||
async with aiofiles.open("coverImage.jpg", mode="wb") as f:
|
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
|
||||||
await f.write(coverImage)
|
await f.write(coverImage)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
coverImage = None
|
coverImage = None
|
||||||
|
|
||||||
age = result["age"]
|
age = result['age']
|
||||||
description = result["description"]
|
description = result['description']
|
||||||
height = result["height"]
|
height = result['height']
|
||||||
name = result["name"]["full"]
|
name = result['name']['full']
|
||||||
native_name = result["name"]["native"]
|
native_name = result['name']['native']
|
||||||
read_more = result["siteUrl"]
|
read_more = result['siteUrl']
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_media_group(
|
await client.send_media_group(
|
||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"**Name:** `{name}`\n**Native Name:** `{native_name}`\n**Age:** `{age}`\n**Height:** {height}\n**Description:** `{description}`[read more...]({read_more})",
|
caption=f'**Name:** `{name}`\n**Native Name:** `{native_name}`\n**Age:** `{age}`\n**Height:** {height}\n**Description:** `{description}`[read more...]({read_more})',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -223,8 +210,8 @@ async def character(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"**Name:** `{name}`\n**Native Name:** `{native_name}`\n**Age:** `{age}`\n**Height:** {height}\n**Description:** `{description}`[read more...]({read_more})",
|
caption=f'**Name:** `{name}`\n**Native Name:** `{native_name}`\n**Age:** `{age}`\n**Height:** {height}\n**Description:** `{description}`[read more...]({read_more})',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -232,12 +219,12 @@ async def character(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists("coverImage.jpg"):
|
if os.path.exists('coverImage.jpg'):
|
||||||
os.remove("coverImage.jpg")
|
os.remove('coverImage.jpg')
|
||||||
|
|
||||||
|
|
||||||
modules_help["anilist"] = {
|
modules_help['anilist'] = {
|
||||||
"anime_search": "Search for anime on Anilist",
|
'anime_search': 'Search for anime on Anilist',
|
||||||
"manga_search": "Search for manga on Anilist",
|
'manga_search': 'Search for manga on Anilist',
|
||||||
"character": "Search for character on Anilist",
|
'character': 'Search for character on Anilist',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
from pyrogram import Client, filters, enums
|
from io import BytesIO
|
||||||
|
|
||||||
|
from aiohttp import ClientSession
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
from aiohttp import ClientSession
|
|
||||||
from io import BytesIO
|
|
||||||
|
|
||||||
session = ClientSession()
|
session = ClientSession()
|
||||||
|
|
||||||
@@ -25,8 +26,10 @@ class Post:
|
|||||||
if self.large_file_url
|
if self.large_file_url
|
||||||
else (
|
else (
|
||||||
self.source
|
self.source
|
||||||
if self.source and "pximg" not in self.source
|
if self.source and 'pximg' not in self.source
|
||||||
else await self.pximg if self.source else None
|
else await self.pximg
|
||||||
|
if self.source
|
||||||
|
else None
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -41,16 +44,14 @@ class Post:
|
|||||||
|
|
||||||
|
|
||||||
async def random():
|
async def random():
|
||||||
async with session.get(
|
async with session.get(url='https://danbooru.donmai.us/posts/random.json') as response:
|
||||||
url="https://danbooru.donmai.us/posts/random.json"
|
return Post(await response.json(encoding='utf-8'), session)
|
||||||
) as response:
|
|
||||||
return Post(await response.json(encoding="utf-8"), session)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["arnd", "arandom"], prefix) & filters.me)
|
@Client.on_message(filters.command(['arnd', 'arandom'], prefix) & filters.me)
|
||||||
async def anime_handler(client: Client, message: Message):
|
async def anime_handler(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Searching art</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Searching art</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
ra = await random()
|
ra = await random()
|
||||||
img = await ra.image
|
img = await ra.image
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
@@ -63,7 +64,7 @@ async def anime_handler(client: Client, message: Message):
|
|||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["anime"] = {
|
modules_help['anime'] = {
|
||||||
"arnd": "Random anime art (May get caught 18+)",
|
'arnd': 'Random anime art (May get caught 18+)',
|
||||||
"arandom": "Random anime art (May get caught 18+)",
|
'arandom': 'Random anime art (May get caught 18+)',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,40 +17,38 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
def get_neko_media(query):
|
def get_neko_media(query):
|
||||||
return requests.get(f"https://nekos.life/api/v2/img/{query}").json()["url"]
|
return requests.get(f'https://nekos.life/api/v2/img/{query}').json()['url']
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("neko", prefix) & filters.me)
|
@Client.on_message(filters.command('neko', prefix) & filters.me)
|
||||||
async def neko(_, message: Message):
|
async def neko(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Neko type isn't provided\n"
|
f"<b>Neko type isn't provided\nYou can get available neko types with <code>{prefix}neko_types</code></b>"
|
||||||
f"You can get available neko types with <code>{prefix}neko_types</code></b>"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
query = message.command[1]
|
query = message.command[1]
|
||||||
await message.edit("<b>Loading...</b>")
|
await message.edit('<b>Loading...</b>')
|
||||||
try:
|
try:
|
||||||
await message.edit(f"{get_neko_media(query)}", disable_web_page_preview=False)
|
await message.edit(f'{get_neko_media(query)}', disable_web_page_preview=False)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["nekotypes", "neko_types"], prefix) & filters.me)
|
@Client.on_message(filters.command(['nekotypes', 'neko_types'], prefix) & filters.me)
|
||||||
async def neko_types_func(_, message: Message):
|
async def neko_types_func(_, message: Message):
|
||||||
neko_types = """hug kiss tickle lewd neko pat lizard 8ball cat chat fact smug woof gasm goose cuddle avatar slap gecg feed fox_girl meow wallpaper spank waifu ngif name owoify spoiler why"""
|
neko_types = """hug kiss tickle lewd neko pat lizard 8ball cat chat fact smug woof gasm goose cuddle avatar slap gecg feed fox_girl meow wallpaper spank waifu ngif name owoify spoiler why"""
|
||||||
await message.edit(" ".join(f"<code>{n}</code>" for n in neko_types.split()))
|
await message.edit(' '.join(f'<code>{n}</code>' for n in neko_types.split()))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["nekospam", "neko_spam"], prefix) & filters.me)
|
@Client.on_message(filters.command(['nekospam', 'neko_spam'], prefix) & filters.me)
|
||||||
async def neko_spam(client: Client, message: Message):
|
async def neko_spam(client: Client, message: Message):
|
||||||
query = message.command[1]
|
query = message.command[1]
|
||||||
amount = int(message.command[2])
|
amount = int(message.command[2])
|
||||||
@@ -65,8 +63,8 @@ async def neko_spam(client: Client, message: Message):
|
|||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
|
|
||||||
modules_help["neko"] = {
|
modules_help['neko'] = {
|
||||||
"neko [type]*": "Get neko media",
|
'neko [type]*': 'Get neko media',
|
||||||
"neko_types": "Available neko types",
|
'neko_types': 'Available neko types',
|
||||||
"neko_spam [type]* [amount]*": "Start spam with neko media",
|
'neko_spam [type]* [amount]*': 'Start spam with neko media',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
from random import choice, randint
|
from random import randint
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["aniq", "aq"], prefix) & filters.me)
|
@Client.on_message(filters.command(['aniq', 'aq'], prefix) & filters.me)
|
||||||
async def aniquotes_handler(client: Client, message: Message):
|
async def aniquotes_handler(client: Client, message: Message):
|
||||||
if message.reply_to_message and message.reply_to_message.text:
|
if message.reply_to_message and message.reply_to_message.text:
|
||||||
query = message.reply_to_message.text[:512]
|
query = message.reply_to_message.text[:512]
|
||||||
@@ -17,27 +16,25 @@ async def aniquotes_handler(client: Client, message: Message):
|
|||||||
query = message.text.split(maxsplit=1)[1][:512]
|
query = message.text.split(maxsplit=1)[1][:512]
|
||||||
else:
|
else:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>[💮 Aniquotes] <i>Please enter text to create sticker.</i></b>",
|
'<b>[💮 Aniquotes] <i>Please enter text to create sticker.</i></b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
result = await client.get_inline_bot_results("@quotafbot", query)
|
result = await client.get_inline_bot_results('@quotafbot', query)
|
||||||
return await message.reply_inline_bot_result(
|
return await message.reply_inline_bot_result(
|
||||||
query_id=result.query_id,
|
query_id=result.query_id,
|
||||||
result_id=result.results[randint(1, 2)].id,
|
result_id=result.results[randint(1, 2)].id,
|
||||||
reply_to_message_id=(
|
reply_to_message_id=(message.reply_to_message.id if message.reply_to_message else None),
|
||||||
message.reply_to_message.id if message.reply_to_message else None
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.reply(
|
return await message.reply(
|
||||||
f"<b>[💮 Aniquotes]</b>\n<code>{format_exc(e)}</code>",
|
f'<b>[💮 Aniquotes]</b>\n<code>{format_exc(e)}</code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["aniquotes"] = {
|
modules_help['aniquotes'] = {
|
||||||
"aq [text]": "Create animated sticker with text",
|
'aq [text]': 'Create animated sticker with text',
|
||||||
}
|
}
|
||||||
|
|||||||
+85
-119
@@ -19,14 +19,11 @@ import os
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.raw import functions
|
from pyrogram.raw import functions
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.config import pm_limit
|
from utils.config import pm_limit
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
anti_pm_enabled = filters.create(
|
anti_pm_enabled = filters.create(lambda _, __, ___: db.get('core.antipm', 'status', False))
|
||||||
lambda _, __, ___: db.get("core.antipm", "status", False)
|
|
||||||
)
|
|
||||||
|
|
||||||
in_contact_list = filters.create(lambda _, __, message: message.from_user.is_contact)
|
in_contact_list = filters.create(lambda _, __, message: message.from_user.is_contact)
|
||||||
|
|
||||||
@@ -35,14 +32,7 @@ is_support = filters.create(lambda _, __, message: message.chat.is_support)
|
|||||||
USER_WARNINGS = {}
|
USER_WARNINGS = {}
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(filters.private & ~filters.me & ~filters.bot & ~in_contact_list & ~is_support & anti_pm_enabled)
|
||||||
filters.private
|
|
||||||
& ~filters.me
|
|
||||||
& ~filters.bot
|
|
||||||
& ~in_contact_list
|
|
||||||
& ~is_support
|
|
||||||
& anti_pm_enabled
|
|
||||||
)
|
|
||||||
async def anti_pm_handler(client: Client, message: Message):
|
async def anti_pm_handler(client: Client, message: Message):
|
||||||
user_id = message.from_user.id
|
user_id = message.from_user.id
|
||||||
ids = message.chat.id
|
ids = message.chat.id
|
||||||
@@ -50,7 +40,7 @@ async def anti_pm_handler(client: Client, message: Message):
|
|||||||
u_n = b_f.first_name
|
u_n = b_f.first_name
|
||||||
user = await client.get_users(ids)
|
user = await client.get_users(ids)
|
||||||
u_f = user.first_name
|
u_f = user.first_name
|
||||||
default_text = db.get("core.antipm", "antipm_msg", None)
|
default_text = db.get('core.antipm', 'antipm_msg', None)
|
||||||
if default_text is None:
|
if default_text is None:
|
||||||
default_text = f"""<b>Hello, {u_f}!
|
default_text = f"""<b>Hello, {u_f}!
|
||||||
This is the Assistant Of {u_n}.</b>
|
This is the Assistant Of {u_n}.</b>
|
||||||
@@ -61,23 +51,19 @@ Do not spam further messages else I may have to block you!</i>
|
|||||||
<b><u>Currently You Have <code>{USER_WARNINGS.get(user_id, 0)}</code> Warnings.</u></b>
|
<b><u>Currently You Have <code>{USER_WARNINGS.get(user_id, 0)}</code> Warnings.</u></b>
|
||||||
"""
|
"""
|
||||||
else:
|
else:
|
||||||
default_text = default_text.format(
|
default_text = default_text.format(user=u_f, my_name=u_n, warns=USER_WARNINGS.get(user_id, 0))
|
||||||
user=u_f, my_name=u_n, warns=USER_WARNINGS.get(user_id, 0)
|
|
||||||
)
|
|
||||||
|
|
||||||
if db.get("core.antipm", "spamrep", False):
|
if db.get('core.antipm', 'spamrep', False):
|
||||||
user_info = await client.resolve_peer(ids)
|
user_info = await client.resolve_peer(ids)
|
||||||
await client.invoke(functions.messages.ReportSpam(peer=user_info))
|
await client.invoke(functions.messages.ReportSpam(peer=user_info))
|
||||||
|
|
||||||
if db.get("core.antipm", "block", False):
|
if db.get('core.antipm', 'block', False):
|
||||||
await client.block_user(user_id)
|
await client.block_user(user_id)
|
||||||
|
|
||||||
if db.get("core.antipm", f"disallowusers{ids}") == user_id != db.get(
|
if db.get('core.antipm', f'disallowusers{ids}') == user_id != db.get('core.antipm', f'allowusers{ids}') or db.get(
|
||||||
"core.antipm", f"allowusers{ids}"
|
'core.antipm', f'disallowusers{ids}'
|
||||||
) or db.get("core.antipm", f"disallowusers{ids}") != user_id != db.get(
|
) != user_id != db.get('core.antipm', f'allowusers{ids}'):
|
||||||
"core.antipm", f"allowusers{ids}"
|
default_pic = db.get('core.antipm', 'antipm_pic', None)
|
||||||
):
|
|
||||||
default_pic = db.get("core.antipm", "antipm_pic", None)
|
|
||||||
if default_pic and os.path.exists(default_pic):
|
if default_pic and os.path.exists(default_pic):
|
||||||
await client.send_photo(message.chat.id, default_pic, caption=default_text)
|
await client.send_photo(message.chat.id, default_pic, caption=default_text)
|
||||||
else:
|
else:
|
||||||
@@ -91,166 +77,146 @@ Do not spam further messages else I may have to block you!</i>
|
|||||||
if USER_WARNINGS[user_id] > pm_limit:
|
if USER_WARNINGS[user_id] > pm_limit:
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
"<b>Ehm...! That was your Last warn, Bye Bye see you L0L</b>",
|
'<b>Ehm...! That was your Last warn, Bye Bye see you L0L</b>',
|
||||||
)
|
)
|
||||||
await client.block_user(user_id)
|
await client.block_user(user_id)
|
||||||
del USER_WARNINGS[user_id]
|
del USER_WARNINGS[user_id]
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["antipm", "anti_pm"], prefix) & filters.me)
|
@Client.on_message(filters.command(['antipm', 'anti_pm'], prefix) & filters.me)
|
||||||
async def anti_pm(_, message: Message):
|
async def anti_pm(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
if db.get("core.antipm", "status", False):
|
if db.get('core.antipm', 'status', False):
|
||||||
await message.edit(
|
await message.edit(f'<b>Anti-PM status: enabled\nDisable with: </b><code>{prefix}antipm disable</code>')
|
||||||
"<b>Anti-PM status: enabled\n"
|
|
||||||
f"Disable with: </b><code>{prefix}antipm disable</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Anti-PM status: disabled\nEnable with: </b><code>{prefix}antipm enable</code>')
|
||||||
"<b>Anti-PM status: disabled\n"
|
elif message.command[1] in ['enable', 'on', '1', 'yes', 'true']:
|
||||||
f"Enable with: </b><code>{prefix}antipm enable</code>"
|
db.set('core.antipm', 'status', True)
|
||||||
)
|
await message.edit('<b>Anti-PM enabled!</b>')
|
||||||
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
|
elif message.command[1] in ['disable', 'off', '0', 'no', 'false']:
|
||||||
db.set("core.antipm", "status", True)
|
db.set('core.antipm', 'status', False)
|
||||||
await message.edit("<b>Anti-PM enabled!</b>")
|
await message.edit('<b>Anti-PM disabled!</b>')
|
||||||
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
|
|
||||||
db.set("core.antipm", "status", False)
|
|
||||||
await message.edit("<b>Anti-PM disabled!</b>")
|
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: {prefix}antipm [enable|disable]</b>")
|
await message.edit(f'<b>Usage: {prefix}antipm [enable|disable]</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["antipm_report"], prefix) & filters.me)
|
@Client.on_message(filters.command(['antipm_report'], prefix) & filters.me)
|
||||||
async def antipm_report(_, message: Message):
|
async def antipm_report(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
if db.get("core.antipm", "spamrep", False):
|
if db.get('core.antipm', 'spamrep', False):
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Spam-reporting enabled.\n"
|
f'<b>Spam-reporting enabled.\nDisable with: </b><code>{prefix}antipm_report disable</code>'
|
||||||
f"Disable with: </b><code>{prefix}antipm_report disable</code>"
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Spam-reporting disabled.\n"
|
f'<b>Spam-reporting disabled.\nEnable with: </b><code>{prefix}antipm_report enable</code>'
|
||||||
f"Enable with: </b><code>{prefix}antipm_report enable</code>"
|
|
||||||
)
|
)
|
||||||
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
|
elif message.command[1] in ['enable', 'on', '1', 'yes', 'true']:
|
||||||
db.set("core.antipm", "spamrep", True)
|
db.set('core.antipm', 'spamrep', True)
|
||||||
await message.edit("<b>Spam-reporting enabled!</b>")
|
await message.edit('<b>Spam-reporting enabled!</b>')
|
||||||
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
|
elif message.command[1] in ['disable', 'off', '0', 'no', 'false']:
|
||||||
db.set("core.antipm", "spamrep", False)
|
db.set('core.antipm', 'spamrep', False)
|
||||||
await message.edit("<b>Spam-reporting disabled!</b>")
|
await message.edit('<b>Spam-reporting disabled!</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: {prefix}antipm_report [enable|disable]</b>")
|
await message.edit(f'<b>Usage: {prefix}antipm_report [enable|disable]</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["antipm_block"], prefix) & filters.me)
|
@Client.on_message(filters.command(['antipm_block'], prefix) & filters.me)
|
||||||
async def antipm_block(_, message: Message):
|
async def antipm_block(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
if db.get("core.antipm", "block", False):
|
if db.get('core.antipm', 'block', False):
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Blocking users enabled.\n"
|
f'<b>Blocking users enabled.\nDisable with: </b><code>{prefix}antipm_block disable</code>'
|
||||||
f"Disable with: </b><code>{prefix}antipm_block disable</code>"
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Blocking users disabled.\n"
|
f'<b>Blocking users disabled.\nEnable with: </b><code>{prefix}antipm_block enable</code>'
|
||||||
f"Enable with: </b><code>{prefix}antipm_block enable</code>"
|
|
||||||
)
|
)
|
||||||
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
|
elif message.command[1] in ['enable', 'on', '1', 'yes', 'true']:
|
||||||
db.set("core.antipm", "block", True)
|
db.set('core.antipm', 'block', True)
|
||||||
await message.edit("<b>Blocking users enabled!</b>")
|
await message.edit('<b>Blocking users enabled!</b>')
|
||||||
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
|
elif message.command[1] in ['disable', 'off', '0', 'no', 'false']:
|
||||||
db.set("core.antipm", "block", False)
|
db.set('core.antipm', 'block', False)
|
||||||
await message.edit("<b>Blocking users disabled!</b>")
|
await message.edit('<b>Blocking users disabled!</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: {prefix}antipm_block [enable|disable]</b>")
|
await message.edit(f'<b>Usage: {prefix}antipm_block [enable|disable]</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["a"], prefix) & filters.me)
|
@Client.on_message(filters.command(['a'], prefix) & filters.me)
|
||||||
async def add_contact(_, message: Message):
|
async def add_contact(_, message: Message):
|
||||||
ids = message.chat.id
|
ids = message.chat.id
|
||||||
|
|
||||||
db.set("core.antipm", f"allowusers{ids}", ids)
|
db.set('core.antipm', f'allowusers{ids}', ids)
|
||||||
if ids in USER_WARNINGS:
|
if ids in USER_WARNINGS:
|
||||||
del USER_WARNINGS[ids]
|
del USER_WARNINGS[ids]
|
||||||
await message.edit("User Approved!")
|
await message.edit('User Approved!')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["d"], prefix) & filters.me)
|
@Client.on_message(filters.command(['d'], prefix) & filters.me)
|
||||||
async def del_contact(_, message: Message):
|
async def del_contact(_, message: Message):
|
||||||
ids = message.chat.id
|
ids = message.chat.id
|
||||||
|
|
||||||
db.set("core.antipm", f"disallowusers{ids}", ids)
|
db.set('core.antipm', f'disallowusers{ids}', ids)
|
||||||
db.remove("core.antipm", f"allowusers{ids}")
|
db.remove('core.antipm', f'allowusers{ids}')
|
||||||
await message.edit("User DisApproved!")
|
await message.edit('User DisApproved!')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["setantipmmsg", "sam"], prefix) & filters.me)
|
@Client.on_message(filters.command(['setantipmmsg', 'sam'], prefix) & filters.me)
|
||||||
async def set_antipm_msg(_, message: Message):
|
async def set_antipm_msg(_, message: Message):
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
db.set("core.antipm", "antipm_msg", None)
|
db.set('core.antipm', 'antipm_msg', None)
|
||||||
await message.edit("antipm message set to default.")
|
await message.edit('antipm message set to default.')
|
||||||
return
|
return
|
||||||
|
|
||||||
msg = message.reply_to_message
|
msg = message.reply_to_message
|
||||||
afk_msg = msg.text or msg.caption
|
afk_msg = msg.text or msg.caption
|
||||||
|
|
||||||
if not afk_msg:
|
if not afk_msg:
|
||||||
return await message.edit(
|
return await message.edit('Reply to a text or caption message to set it as your antipm message.')
|
||||||
"Reply to a text or caption message to set it as your antipm message."
|
|
||||||
)
|
|
||||||
|
|
||||||
if len(afk_msg) > 200:
|
if len(afk_msg) > 200:
|
||||||
return await message.edit(
|
return await message.edit('antipm message is too long. It should be less than 200 characters.')
|
||||||
"antipm message is too long. It should be less than 200 characters."
|
|
||||||
)
|
|
||||||
|
|
||||||
if "{user}" not in afk_msg:
|
if '{user}' not in afk_msg:
|
||||||
return await message.edit(
|
return await message.edit('antipm message must contain <code>{user}</code> to mention the user.')
|
||||||
"antipm message must contain <code>{user}</code> to mention the user."
|
if '{my_name}' not in afk_msg:
|
||||||
)
|
return await message.edit('antipm message must contain <code>{my_name}</code> to mention your name.')
|
||||||
if "{my_name}" not in afk_msg:
|
if '{warns}' not in afk_msg:
|
||||||
return await message.edit(
|
return await message.edit('antipm message must contain <code>{warns}</code> to mention the warns count.')
|
||||||
"antipm message must contain <code>{my_name}</code> to mention your name."
|
|
||||||
)
|
|
||||||
if "{warns}" not in afk_msg:
|
|
||||||
return await message.edit(
|
|
||||||
"antipm message must contain <code>{warns}</code> to mention the warns count."
|
|
||||||
)
|
|
||||||
|
|
||||||
old_afk_msg = db.get("core.antipm", "antipm_msg", None)
|
old_afk_msg = db.get('core.antipm', 'antipm_msg', None)
|
||||||
if old_afk_msg:
|
if old_afk_msg:
|
||||||
db.remove("core.antipm", "antipm_msg")
|
db.remove('core.antipm', 'antipm_msg')
|
||||||
db.set("core.antipm", "antipm_msg", afk_msg)
|
db.set('core.antipm', 'antipm_msg', afk_msg)
|
||||||
await message.edit(f"antipm message set to:\n\n{afk_msg}")
|
await message.edit(f'antipm message set to:\n\n{afk_msg}')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["setantipmpic", "sap"], prefix) & filters.me)
|
@Client.on_message(filters.command(['setantipmpic', 'sap'], prefix) & filters.me)
|
||||||
async def set_antipm_pic(_, message: Message):
|
async def set_antipm_pic(_, message: Message):
|
||||||
if not message.reply_to_message or not message.reply_to_message.photo:
|
if not message.reply_to_message or not message.reply_to_message.photo:
|
||||||
db.set("core.antipm", "antipm_pic", None)
|
db.set('core.antipm', 'antipm_pic', None)
|
||||||
await message.edit("antipm picture set to default.")
|
await message.edit('antipm picture set to default.')
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("Setting antipm picture...")
|
await message.edit('Setting antipm picture...')
|
||||||
|
|
||||||
photo = await message.reply_to_message.download("antipm_pic.jpg")
|
photo = await message.reply_to_message.download('antipm_pic.jpg')
|
||||||
|
|
||||||
old_antipm_pic = db.get("core.antipm", "antipm_pic", None)
|
old_antipm_pic = db.get('core.antipm', 'antipm_pic', None)
|
||||||
if old_antipm_pic:
|
if old_antipm_pic:
|
||||||
db.remove("core.antipm", "antipm_pic")
|
db.remove('core.antipm', 'antipm_pic')
|
||||||
db.set("core.antipm", "antipm_pic", photo)
|
db.set('core.antipm', 'antipm_pic', photo)
|
||||||
await message.edit("antipm picture set successfully.")
|
await message.edit('antipm picture set successfully.')
|
||||||
|
|
||||||
|
|
||||||
modules_help["antipm"] = {
|
modules_help['antipm'] = {
|
||||||
"antipm [enable|disable]*": "Enable Pm permit",
|
'antipm [enable|disable]*': 'Enable Pm permit',
|
||||||
"antipm_report [enable|disable]*": "Enable spam reporting",
|
'antipm_report [enable|disable]*': 'Enable spam reporting',
|
||||||
"antipm_block [enable|disable]*": "Enable user blocking",
|
'antipm_block [enable|disable]*': 'Enable user blocking',
|
||||||
"setantipmmsg [reply to message]*": "Set antipm message. Use {user} to mention the user and {my_name} to mention your name and {warns} to mention the warns count.",
|
'setantipmmsg [reply to message]*': 'Set antipm message. Use {user} to mention the user and {my_name} to mention your name and {warns} to mention the warns count.',
|
||||||
"sam [reply to message]*": "Set antipm message. Use {user} to mention the user and {my_name} to mention your name and {warns} to mention the warns count.",
|
'sam [reply to message]*': 'Set antipm message. Use {user} to mention the user and {my_name} to mention your name and {warns} to mention the warns count.',
|
||||||
"setantipmpic [reply to photo]*": "Set antipm picture.",
|
'setantipmpic [reply to photo]*': 'Set antipm picture.',
|
||||||
"sap [reply to photo]*": "Set antipm picture.",
|
'sap [reply to photo]*': 'Set antipm picture.',
|
||||||
"a": "Approve User",
|
'a': 'Approve User',
|
||||||
"d": "DisApprove User",
|
'd': 'DisApprove User',
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-63
@@ -1,10 +1,8 @@
|
|||||||
import uuid
|
|
||||||
import re
|
import re
|
||||||
|
import uuid
|
||||||
|
|
||||||
from aiohttp import ClientSession, FormData
|
from aiohttp import ClientSession, FormData
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@@ -12,15 +10,14 @@ def id_generator() -> str:
|
|||||||
return str(uuid.uuid4())
|
return str(uuid.uuid4())
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["bbox", "blackbox"], prefix) & filters.me)
|
@Client.on_message(filters.command(['bbox', 'blackbox'], prefix) & filters.me)
|
||||||
async def blackbox(client, message):
|
async def blackbox(client, message):
|
||||||
m = message
|
m = message
|
||||||
msg = await m.edit_text("🔍")
|
msg = await m.edit_text('🔍')
|
||||||
|
|
||||||
if len(m.text.split()) == 1:
|
if len(m.text.split()) == 1:
|
||||||
return await msg.edit_text(
|
return await msg.edit_text(
|
||||||
"Type some query buddy 🐼\n"
|
f'Type some query buddy 🐼\n{prefix}blackbox text with reply to the photo or just text'
|
||||||
f"{prefix}blackbox text with reply to the photo or just text"
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
@@ -30,105 +27,95 @@ async def blackbox(client, message):
|
|||||||
image = None
|
image = None
|
||||||
|
|
||||||
if m.reply_to_message and (
|
if m.reply_to_message and (
|
||||||
m.reply_to_message.photo
|
m.reply_to_message.photo or (m.reply_to_message.sticker and not m.reply_to_message.sticker.is_video)
|
||||||
or (
|
|
||||||
m.reply_to_message.sticker
|
|
||||||
and not m.reply_to_message.sticker.is_video
|
|
||||||
)
|
|
||||||
):
|
):
|
||||||
file_name = f"blackbox_{m.chat.id}.jpeg"
|
file_name = f'blackbox_{m.chat.id}.jpeg'
|
||||||
file_path = await m.reply_to_message.download(file_name=file_name)
|
file_path = await m.reply_to_message.download(file_name=file_name)
|
||||||
with open(file_path, "rb") as file:
|
with open(file_path, 'rb') as file:
|
||||||
image = file.read()
|
image = file.read()
|
||||||
|
|
||||||
if image:
|
if image:
|
||||||
data = FormData()
|
data = FormData()
|
||||||
data.add_field("fileName", file_name)
|
data.add_field('fileName', file_name)
|
||||||
data.add_field("userId", user_id)
|
data.add_field('userId', user_id)
|
||||||
data.add_field(
|
data.add_field('image', image, filename=file_name, content_type='image/jpeg')
|
||||||
"image", image, filename=file_name, content_type="image/jpeg"
|
api_url = 'https://www.blackbox.ai/api/upload'
|
||||||
)
|
|
||||||
api_url = "https://www.blackbox.ai/api/upload"
|
|
||||||
try:
|
try:
|
||||||
async with session.post(api_url, data=data) as response:
|
async with session.post(api_url, data=data) as response:
|
||||||
response_json = await response.json()
|
response_json = await response.json()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await msg.edit(f"❌ Error: {str(e)}")
|
return await msg.edit(f'❌ Error: {str(e)}')
|
||||||
|
|
||||||
messages = [
|
messages = [
|
||||||
{
|
{
|
||||||
"role": "user",
|
'role': 'user',
|
||||||
"content": response_json["response"] + "\n#\n" + prompt,
|
'content': response_json['response'] + '\n#\n' + prompt,
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
data = {
|
data = {
|
||||||
"messages": messages,
|
'messages': messages,
|
||||||
"user_id": user_id,
|
'user_id': user_id,
|
||||||
"codeModelMode": True,
|
'codeModelMode': True,
|
||||||
"agentMode": {},
|
'agentMode': {},
|
||||||
"trendingAgentMode": {},
|
'trendingAgentMode': {},
|
||||||
}
|
}
|
||||||
headers = {"Content-Type": "application/json"}
|
headers = {'Content-Type': 'application/json'}
|
||||||
url = "https://www.blackbox.ai/api/chat"
|
url = 'https://www.blackbox.ai/api/chat'
|
||||||
try:
|
try:
|
||||||
async with session.post(
|
async with session.post(url, headers=headers, json=data) as response:
|
||||||
url, headers=headers, json=data
|
|
||||||
) as response:
|
|
||||||
response_text = await response.text()
|
response_text = await response.text()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await msg.edit(f"❌ Error: {str(e)}")
|
return await msg.edit(f'❌ Error: {str(e)}')
|
||||||
|
|
||||||
cleaned_response_text = re.sub(
|
cleaned_response_text = re.sub(
|
||||||
r"^\$?@?\$?v=undefined-rv\d+@?\$?|\$?@?\$?v=v\d+\.\d+-rv\d+@?\$?",
|
r'^\$?@?\$?v=undefined-rv\d+@?\$?|\$?@?\$?v=v\d+\.\d+-rv\d+@?\$?',
|
||||||
"",
|
'',
|
||||||
response_text,
|
response_text,
|
||||||
)
|
)
|
||||||
text = cleaned_response_text.strip()[2:]
|
text = cleaned_response_text.strip()[2:]
|
||||||
if "$~~~$" in text:
|
if '$~~~$' in text:
|
||||||
text = re.sub(r"\$~~~\$.*?\$~~~\$", "", text, flags=re.DOTALL)
|
text = re.sub(r'\$~~~\$.*?\$~~~\$', '', text, flags=re.DOTALL)
|
||||||
rdata = {"reply": text}
|
rdata = {'reply': text}
|
||||||
|
|
||||||
return await msg.edit_text(text=rdata["reply"])
|
return await msg.edit_text(text=rdata['reply'])
|
||||||
else:
|
else:
|
||||||
reply = m.reply_to_message
|
reply = m.reply_to_message
|
||||||
if reply and reply.text:
|
if reply and reply.text:
|
||||||
prompt = f"Old conversation:\n{reply.text}\n\nQuestion:\n{prompt}"
|
prompt = f'Old conversation:\n{reply.text}\n\nQuestion:\n{prompt}'
|
||||||
messages = [{"role": "user", "content": prompt}]
|
messages = [{'role': 'user', 'content': prompt}]
|
||||||
data = {
|
data = {
|
||||||
"messages": messages,
|
'messages': messages,
|
||||||
"user_id": user_id,
|
'user_id': user_id,
|
||||||
"codeModelMode": True,
|
'codeModelMode': True,
|
||||||
"agentMode": {},
|
'agentMode': {},
|
||||||
"trendingAgentMode": {},
|
'trendingAgentMode': {},
|
||||||
}
|
}
|
||||||
headers = {"Content-Type": "application/json"}
|
headers = {'Content-Type': 'application/json'}
|
||||||
url = "https://www.blackbox.ai/api/chat"
|
url = 'https://www.blackbox.ai/api/chat'
|
||||||
try:
|
try:
|
||||||
async with session.post(
|
async with session.post(url, headers=headers, json=data) as response:
|
||||||
url, headers=headers, json=data
|
|
||||||
) as response:
|
|
||||||
response_text = await response.text()
|
response_text = await response.text()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await msg.edit(f"❌ Error: {str(e)}")
|
return await msg.edit(f'❌ Error: {str(e)}')
|
||||||
|
|
||||||
cleaned_response_text = re.sub(
|
cleaned_response_text = re.sub(
|
||||||
r"^\$?@?\$?v=undefined-rv\d+@?\$?|\$?@?\$?v=v\d+\.\d+-rv\d+@?\$?",
|
r'^\$?@?\$?v=undefined-rv\d+@?\$?|\$?@?\$?v=v\d+\.\d+-rv\d+@?\$?',
|
||||||
"",
|
'',
|
||||||
response_text,
|
response_text,
|
||||||
)
|
)
|
||||||
text = cleaned_response_text.strip()[2:]
|
text = cleaned_response_text.strip()[2:]
|
||||||
if "$~~~$" in text:
|
if '$~~~$' in text:
|
||||||
text = re.sub(r"\$~~~\$.*?\$~~~\$", "", text, flags=re.DOTALL)
|
text = re.sub(r'\$~~~\$.*?\$~~~\$', '', text, flags=re.DOTALL)
|
||||||
rdata = {"reply": text}
|
rdata = {'reply': text}
|
||||||
|
|
||||||
return await msg.edit_text(text=rdata["reply"])
|
return await msg.edit_text(text=rdata['reply'])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await msg.edit(f"�� Error: {str(e)}")
|
return await msg.edit(f'�� Error: {str(e)}')
|
||||||
finally:
|
finally:
|
||||||
await session.close()
|
await session.close()
|
||||||
|
|
||||||
|
|
||||||
modules_help["blackbox"] = {
|
modules_help['blackbox'] = {
|
||||||
"blackbox [query]*": "Ask anything to Blackbox",
|
'blackbox [query]*': 'Ask anything to Blackbox',
|
||||||
"bbox [query]*": "Ask anything to Blackbox",
|
'bbox [query]*': 'Ask anything to Blackbox',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,14 @@ import asyncio
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("calc", prefix) & filters.me)
|
@Client.on_message(filters.command('calc', prefix) & filters.me)
|
||||||
async def calc(_, message: Message):
|
async def calc(_, message: Message):
|
||||||
if len(message.command) <= 1:
|
if len(message.command) <= 1:
|
||||||
return
|
return
|
||||||
args = " ".join(message.command[1:])
|
args = ' '.join(message.command[1:])
|
||||||
try:
|
try:
|
||||||
result = str(eval(args))
|
result = str(eval(args))
|
||||||
|
|
||||||
@@ -19,28 +18,24 @@ async def calc(_, message: Message):
|
|||||||
for x in range(0, len(result), 4096):
|
for x in range(0, len(result), 4096):
|
||||||
if i == 0:
|
if i == 0:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<i>{args}</i><b>=</b><code>{result[x:x + 4000]}</code>",
|
f'<i>{args}</i><b>=</b><code>{result[x : x + 4000]}</code>',
|
||||||
parse_mode="HTML",
|
parse_mode='HTML',
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.reply(
|
await message.reply(f'<code>{result[x : x + 4096]}</code>', parse_mode='HTML')
|
||||||
f"<code>{result[x:x + 4096]}</code>", parse_mode="HTML"
|
|
||||||
)
|
|
||||||
i += 1
|
i += 1
|
||||||
await asyncio.sleep(0.18)
|
await asyncio.sleep(0.18)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<i>{args}</i><b>=</b><code>{result}</code>', parse_mode='HTML')
|
||||||
f"<i>{args}</i><b>=</b><code>{result}</code>", parse_mode="HTML"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(f"<i>{args}=</i><b>=</b><code>{e}</code>", parse_mode="HTML")
|
await message.edit(f'<i>{args}=</i><b>=</b><code>{e}</code>', parse_mode='HTML')
|
||||||
|
|
||||||
|
|
||||||
modules_help["calculator"] = {
|
modules_help['calculator'] = {
|
||||||
"calc [expression]*": "solve a math problem\n"
|
'calc [expression]*': 'solve a math problem\n'
|
||||||
"+ – addition\n"
|
'+ – addition\n'
|
||||||
"– – subtraction\n"
|
'– – subtraction\n'
|
||||||
"* – multiplication\n"
|
'* – multiplication\n'
|
||||||
"/ – division\n"
|
'/ – division\n'
|
||||||
"** – degree"
|
'** – degree'
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-19
@@ -1,57 +1,52 @@
|
|||||||
import base64, os
|
import os
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, import_library
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
clarifai = import_library("clarifai")
|
clarifai = import_library('clarifai')
|
||||||
|
|
||||||
from clarifai.client.model import Model
|
from clarifai.client.model import Model
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("cdxl", prefix) & filters.me)
|
@Client.on_message(filters.command('cdxl', prefix) & filters.me)
|
||||||
async def cdxl(c: Client, message: Message):
|
async def cdxl(c: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit_text("<code>Please Wait...</code>")
|
await message.edit_text('<code>Please Wait...</code>')
|
||||||
|
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
prompt = message.text.split(maxsplit=1)[1]
|
prompt = message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
prompt = message.reply_to_message.text
|
prompt = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}vdxl [prompt/reply to prompt]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}vdxl [prompt/reply to prompt]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
inference_params = dict(width=1024, height=1024, steps=50, cfg_scale=9.0)
|
inference_params = dict(width=1024, height=1024, steps=50, cfg_scale=9.0)
|
||||||
|
|
||||||
model_prediction = Model(
|
model_prediction = Model(
|
||||||
"https://clarifai.com/stability-ai/stable-diffusion-2/models/stable-diffusion-xl"
|
'https://clarifai.com/stability-ai/stable-diffusion-2/models/stable-diffusion-xl'
|
||||||
).predict_by_bytes(
|
).predict_by_bytes(prompt.encode(), input_type='text', inference_params=inference_params)
|
||||||
prompt.encode(), input_type="text", inference_params=inference_params
|
|
||||||
)
|
|
||||||
|
|
||||||
output_base64 = model_prediction.outputs[0].data.image.base64
|
output_base64 = model_prediction.outputs[0].data.image.base64
|
||||||
|
|
||||||
with open("sdxl_out.png", "wb") as f:
|
with open('sdxl_out.png', 'wb') as f:
|
||||||
f.write(output_base64)
|
f.write(output_base64)
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await c.send_photo(
|
await c.send_photo(
|
||||||
chat_id,
|
chat_id,
|
||||||
photo=f"sdxl_out.png",
|
photo='sdxl_out.png',
|
||||||
caption=f"<b>Prompt:</b><code>{prompt}</code>",
|
caption=f'<b>Prompt:</b><code>{prompt}</code>',
|
||||||
)
|
)
|
||||||
os.remove(f"sdxl_out.png")
|
os.remove('sdxl_out.png')
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["cdxl"] = {
|
modules_help['cdxl'] = {
|
||||||
"cdxl [prompt/reply to prompt]*": "Text to Image with SDXL model",
|
'cdxl [prompt/reply to prompt]*': 'Text to Image with SDXL model',
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-32
@@ -1,49 +1,48 @@
|
|||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
|
||||||
from utils.config import cohere_key
|
from utils.config import cohere_key
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, import_library, restart
|
from utils.scripts import format_exc, import_library, restart
|
||||||
|
|
||||||
cohere = import_library("cohere")
|
cohere = import_library('cohere')
|
||||||
|
|
||||||
co = cohere.Client(cohere_key)
|
co = cohere.Client(cohere_key)
|
||||||
|
|
||||||
chatai_users = db.getaiusers()
|
chatai_users = db.getaiusers()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("addai", prefix) & filters.me)
|
@Client.on_message(filters.command('addai', prefix) & filters.me)
|
||||||
async def adduser(_, message: Message):
|
async def adduser(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
user_id = message.text.split(maxsplit=1)[1]
|
user_id = message.text.split(maxsplit=1)[1]
|
||||||
if user_id.isdigit():
|
if user_id.isdigit():
|
||||||
user_id = int(user_id)
|
user_id = int(user_id)
|
||||||
db.addaiuser(user_id)
|
db.addaiuser(user_id)
|
||||||
await message.edit_text("<b>User ID Added</b>")
|
await message.edit_text('<b>User ID Added</b>')
|
||||||
restart()
|
restart()
|
||||||
else:
|
else:
|
||||||
await message.edit_text("<b>User ID is invalid.</b>")
|
await message.edit_text('<b>User ID is invalid.</b>')
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
await message.edit_text(f"<b>Usage: </b><code>{prefix}addai [user_id]</code>")
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}addai [user_id]</code>')
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("remai", prefix) & filters.me)
|
@Client.on_message(filters.command('remai', prefix) & filters.me)
|
||||||
async def remuser(_, message: Message):
|
async def remuser(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
user_id = message.text.split(maxsplit=1)[1]
|
user_id = message.text.split(maxsplit=1)[1]
|
||||||
if user_id.isdigit():
|
if user_id.isdigit():
|
||||||
user_id = int(user_id)
|
user_id = int(user_id)
|
||||||
db.remaiuser(user_id)
|
db.remaiuser(user_id)
|
||||||
await message.edit_text("<b>User ID Removed</b>")
|
await message.edit_text('<b>User ID Removed</b>')
|
||||||
restart()
|
restart()
|
||||||
else:
|
else:
|
||||||
await message.edit_text("<b>User ID is invalid.</b>")
|
await message.edit_text('<b>User ID is invalid.</b>')
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
await message.edit_text(f"<b>Usage: </b><code>{prefix}remai [user_id]</code>")
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}remai [user_id]</code>')
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@@ -62,44 +61,40 @@ async def chatbot(_, message: Message):
|
|||||||
|
|
||||||
prompt = message.text
|
prompt = message.text
|
||||||
|
|
||||||
db.add_chat_history(user_id, {"role": "USER", "message": prompt})
|
db.add_chat_history(user_id, {'role': 'USER', 'message': prompt})
|
||||||
|
|
||||||
response = co.chat(
|
response = co.chat(
|
||||||
chat_history=chat_history,
|
chat_history=chat_history,
|
||||||
model="command-r-plus",
|
model='command-r-plus',
|
||||||
message=prompt,
|
message=prompt,
|
||||||
temperature=0.3,
|
temperature=0.3,
|
||||||
connectors=[{"id": "web-search", "options": {"site": "wikipedia.com"}}],
|
connectors=[{'id': 'web-search', 'options': {'site': 'wikipedia.com'}}],
|
||||||
prompt_truncation="AUTO",
|
prompt_truncation='AUTO',
|
||||||
)
|
)
|
||||||
|
|
||||||
db.add_chat_history(user_id, {"role": "CHATBOT", "message": response.text})
|
db.add_chat_history(user_id, {'role': 'CHATBOT', 'message': response.text})
|
||||||
|
|
||||||
await message.reply_text(
|
await message.reply_text(f'{response.text}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"{response.text}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.reply_text(f"An error occurred: {format_exc(e)}")
|
await message.reply_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("chatoff", prefix) & filters.me)
|
@Client.on_message(filters.command('chatoff', prefix) & filters.me)
|
||||||
async def chatoff(_, message: Message):
|
async def chatoff(_, message: Message):
|
||||||
db.remove("core.chatbot", "chatai_users")
|
db.remove('core.chatbot', 'chatai_users')
|
||||||
await message.reply_text("<b>ChatBot is off now</b>")
|
await message.reply_text('<b>ChatBot is off now</b>')
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("listai", prefix) & filters.me)
|
@Client.on_message(filters.command('listai', prefix) & filters.me)
|
||||||
async def listai(_, message: Message):
|
async def listai(_, message: Message):
|
||||||
await message.edit_text(
|
await message.edit_text(f"<b>User ID's Currently in AI ChatBot List:</b>\n <code>{chatai_users}</code>")
|
||||||
f"<b>User ID's Currently in AI ChatBot List:</b>\n <code>{chatai_users}</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
modules_help["chatbot"] = {
|
modules_help['chatbot'] = {
|
||||||
"addai [user_id]*": "Add A user to AI ChatBot List",
|
'addai [user_id]*': 'Add A user to AI ChatBot List',
|
||||||
"remai [user_id]*": "Remove A user from AI ChatBot List",
|
'remai [user_id]*': 'Remove A user from AI ChatBot List',
|
||||||
"listai": "List A user from AI ChatBot List",
|
'listai': 'List A user from AI ChatBot List',
|
||||||
"chatoff": "Turn off AI ChatBot",
|
'chatoff': 'Turn off AI ChatBot',
|
||||||
}
|
}
|
||||||
|
|||||||
+52
-65
@@ -3,38 +3,37 @@ import os
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
from PIL import Image, ImageDraw, ImageFilter, ImageOps
|
from PIL import Image, ImageDraw, ImageFilter, ImageOps
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
from utils.scripts import import_library, format_exc
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
|
VideoFileClip = import_library('moviepy', 'moviepy==2.2.1').VideoFileClip
|
||||||
VideoFileClip = import_library("moviepy", "moviepy==2.2.1").VideoFileClip
|
|
||||||
|
|
||||||
im = None
|
im = None
|
||||||
|
|
||||||
|
|
||||||
def process_img(filename):
|
def process_img(filename):
|
||||||
global im
|
global im
|
||||||
im = Image.open(f"downloads/{filename}")
|
im = Image.open(f'downloads/{filename}')
|
||||||
w, h = im.size
|
w, h = im.size
|
||||||
img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
|
img = Image.new('RGBA', (w, h), (0, 0, 0, 0))
|
||||||
img.paste(im, (0, 0))
|
img.paste(im, (0, 0))
|
||||||
m = min(w, h)
|
m = min(w, h)
|
||||||
img = img.crop(((w - m) // 2, (h - m) // 2, (w + m) // 2, (h + m) // 2))
|
img = img.crop(((w - m) // 2, (h - m) // 2, (w + m) // 2, (h + m) // 2))
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
mask = Image.new("L", (w, h), 0)
|
mask = Image.new('L', (w, h), 0)
|
||||||
draw = ImageDraw.Draw(mask)
|
draw = ImageDraw.Draw(mask)
|
||||||
draw.ellipse((10, 10, w - 10, h - 10), fill=255)
|
draw.ellipse((10, 10, w - 10, h - 10), fill=255)
|
||||||
mask = mask.filter(ImageFilter.GaussianBlur(2))
|
mask = mask.filter(ImageFilter.GaussianBlur(2))
|
||||||
img = ImageOps.fit(img, (w, h))
|
img = ImageOps.fit(img, (w, h))
|
||||||
img.putalpha(mask)
|
img.putalpha(mask)
|
||||||
im = BytesIO()
|
im = BytesIO()
|
||||||
im.name = "img.webp"
|
im.name = 'img.webp'
|
||||||
img.save(im)
|
img.save(im)
|
||||||
im.seek(0)
|
im.seek(0)
|
||||||
|
|
||||||
@@ -44,103 +43,91 @@ video = None
|
|||||||
|
|
||||||
def process_vid(filename):
|
def process_vid(filename):
|
||||||
global video
|
global video
|
||||||
video = VideoFileClip(f"downloads/{filename}")
|
video = VideoFileClip(f'downloads/{filename}')
|
||||||
w, h = video.size
|
w, h = video.size
|
||||||
m = min(w, h)
|
m = min(w, h)
|
||||||
box = {
|
box = {
|
||||||
"x1": (w - m) // 2,
|
'x1': (w - m) // 2,
|
||||||
"y1": (h - m) // 2,
|
'y1': (h - m) // 2,
|
||||||
"x2": (w + m) // 2,
|
'x2': (w + m) // 2,
|
||||||
"y2": (h + m) // 2,
|
'y2': (h + m) // 2,
|
||||||
}
|
}
|
||||||
video = video.cropped(**box)
|
video = video.cropped(**box)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["circle", "round"], prefix) & filters.me)
|
@Client.on_message(filters.command(['circle', 'round'], prefix) & filters.me)
|
||||||
async def circle(_, message: Message):
|
async def circle(_, message: Message):
|
||||||
try:
|
try:
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
return await message.reply(
|
return await message.reply(
|
||||||
"<b>Reply is required for this command</b>",
|
'<b>Reply is required for this command</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
if message.reply_to_message.photo:
|
if message.reply_to_message.photo:
|
||||||
filename = "circle.jpg"
|
filename = 'circle.jpg'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif message.reply_to_message.sticker:
|
elif message.reply_to_message.sticker:
|
||||||
if message.reply_to_message.sticker.is_video:
|
if message.reply_to_message.sticker.is_video:
|
||||||
return await message.reply(
|
return await message.reply(
|
||||||
"<b>Video stickers is not supported</b>",
|
'<b>Video stickers is not supported</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
filename = "circle.webp"
|
filename = 'circle.webp'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif message.reply_to_message.video:
|
elif message.reply_to_message.video:
|
||||||
filename = "circle.mp4"
|
filename = 'circle.mp4'
|
||||||
typ = "video"
|
typ = 'video'
|
||||||
elif message.reply_to_message.document:
|
elif message.reply_to_message.document:
|
||||||
_filename = message.reply_to_message.document.file_name.casefold()
|
_filename = message.reply_to_message.document.file_name.casefold()
|
||||||
if _filename.endswith(".png"):
|
if _filename.endswith('.png'):
|
||||||
filename = "circle.png"
|
filename = 'circle.png'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif _filename.endswith(".jpg"):
|
elif _filename.endswith('.jpg'):
|
||||||
filename = "circle.jpg"
|
filename = 'circle.jpg'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif _filename.endswith(".jpeg"):
|
elif _filename.endswith('.jpeg'):
|
||||||
filename = "circle.jpeg"
|
filename = 'circle.jpeg'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif _filename.endswith(".webp"):
|
elif _filename.endswith('.webp'):
|
||||||
filename = "circle.webp"
|
filename = 'circle.webp'
|
||||||
typ = "photo"
|
typ = 'photo'
|
||||||
elif _filename.endswith(".mp4"):
|
elif _filename.endswith('.mp4'):
|
||||||
filename = "circle.mp4"
|
filename = 'circle.mp4'
|
||||||
typ = "video"
|
typ = 'video'
|
||||||
else:
|
else:
|
||||||
return await message.reply(
|
return await message.reply('<b>Invalid file type</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Invalid file type</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
return await message.reply(
|
return await message.reply('<b>Invalid file type</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Invalid file type</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
if typ == "photo":
|
if typ == 'photo':
|
||||||
await message.edit(
|
await message.edit('<b>Processing image</b>📷', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Processing image</b>📷", parse_mode=enums.ParseMode.HTML
|
await message.reply_to_message.download(f'downloads/{filename}')
|
||||||
)
|
|
||||||
await message.reply_to_message.download(f"downloads/{filename}")
|
|
||||||
await asyncio.get_event_loop().run_in_executor(None, process_img, filename)
|
await asyncio.get_event_loop().run_in_executor(None, process_img, filename)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
return await message.reply_sticker(
|
return await message.reply_sticker(sticker=im, reply_to_message_id=message.reply_to_message.id)
|
||||||
sticker=im, reply_to_message_id=message.reply_to_message.id
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit('<b>Processing video</b>🎥', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Processing video</b>🎥", parse_mode=enums.ParseMode.HTML
|
await message.reply_to_message.download(f'downloads/{filename}')
|
||||||
)
|
|
||||||
await message.reply_to_message.download(f"downloads/{filename}")
|
|
||||||
await asyncio.get_event_loop().run_in_executor(None, process_vid, filename)
|
await asyncio.get_event_loop().run_in_executor(None, process_vid, filename)
|
||||||
|
|
||||||
await message.edit("<b>Saving video</b>📼", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Saving video</b>📼', parse_mode=enums.ParseMode.HTML)
|
||||||
await asyncio.get_event_loop().run_in_executor(
|
await asyncio.get_event_loop().run_in_executor(None, video.write_videofile, 'downloads/result.mp4')
|
||||||
None, video.write_videofile, "downloads/result.mp4"
|
|
||||||
)
|
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await message.reply_video_note(
|
await message.reply_video_note(
|
||||||
video_note="downloads/result.mp4",
|
video_note='downloads/result.mp4',
|
||||||
duration=int(video.duration),
|
duration=int(video.duration),
|
||||||
reply_to_message_id=message.reply_to_message.id,
|
reply_to_message_id=message.reply_to_message.id,
|
||||||
)
|
)
|
||||||
if isinstance(video, VideoFileClip):
|
if isinstance(video, VideoFileClip):
|
||||||
video.close()
|
video.close()
|
||||||
os.remove(f"downloads/{filename}")
|
os.remove(f'downloads/{filename}')
|
||||||
os.remove("downloads/result.mp4")
|
os.remove('downloads/result.mp4')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.reply(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.reply(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["circle"] = {
|
modules_help['circle'] = {
|
||||||
"round": "Round a photo or video.",
|
'round': 'Round a photo or video.',
|
||||||
"circle": "Circle a photo or video.",
|
'circle': 'Circle a photo or video.',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,11 +17,10 @@
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.raw import functions
|
from pyrogram.raw import functions
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["clear_@"], prefix) & filters.me)
|
@Client.on_message(filters.command(['clear_@'], prefix) & filters.me)
|
||||||
async def solo_mention_clear(client: Client, message: Message):
|
async def solo_mention_clear(client: Client, message: Message):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
peer = await client.resolve_peer(message.chat.id)
|
peer = await client.resolve_peer(message.chat.id)
|
||||||
@@ -29,24 +28,20 @@ async def solo_mention_clear(client: Client, message: Message):
|
|||||||
await client.invoke(request)
|
await client.invoke(request)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["clear_all_@"], prefix) & filters.me)
|
@Client.on_message(filters.command(['clear_all_@'], prefix) & filters.me)
|
||||||
async def global_mention_clear(client: Client, message: Message):
|
async def global_mention_clear(client: Client, message: Message):
|
||||||
counter: int = 0
|
counter: int = 0
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Clearing all mentions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats')
|
||||||
f"<b>Clearing all mentions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats"
|
|
||||||
)
|
|
||||||
async for dialog in client.get_dialogs():
|
async for dialog in client.get_dialogs():
|
||||||
peer = await client.resolve_peer(dialog.chat.id)
|
peer = await client.resolve_peer(dialog.chat.id)
|
||||||
request = functions.messages.ReadMentions(peer=peer)
|
request = functions.messages.ReadMentions(peer=peer)
|
||||||
await client.invoke(request)
|
await client.invoke(request)
|
||||||
counter += 1
|
counter += 1
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Clearing all mentions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats')
|
||||||
f"<b>Clearing all mentions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats"
|
|
||||||
)
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["clear_reacts"], prefix) & filters.me)
|
@Client.on_message(filters.command(['clear_reacts'], prefix) & filters.me)
|
||||||
async def solo_reaction_clear(client: Client, message: Message):
|
async def solo_reaction_clear(client: Client, message: Message):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
peer = await client.resolve_peer(message.chat.id)
|
peer = await client.resolve_peer(message.chat.id)
|
||||||
@@ -54,26 +49,22 @@ async def solo_reaction_clear(client: Client, message: Message):
|
|||||||
await client.invoke(request)
|
await client.invoke(request)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["clear_all_reacts"], prefix) & filters.me)
|
@Client.on_message(filters.command(['clear_all_reacts'], prefix) & filters.me)
|
||||||
async def global_reaction_clear(client: Client, message: Message):
|
async def global_reaction_clear(client: Client, message: Message):
|
||||||
counter: int = 0
|
counter: int = 0
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Clearing all reactions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats')
|
||||||
f"<b>Clearing all reactions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats"
|
|
||||||
)
|
|
||||||
async for dialog in client.get_dialogs():
|
async for dialog in client.get_dialogs():
|
||||||
peer = await client.resolve_peer(dialog.chat.id)
|
peer = await client.resolve_peer(dialog.chat.id)
|
||||||
request = functions.messages.ReadReactions(peer=peer)
|
request = functions.messages.ReadReactions(peer=peer)
|
||||||
await client.invoke(request)
|
await client.invoke(request)
|
||||||
counter += 1
|
counter += 1
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Clearing all reactions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats')
|
||||||
f"<b>Clearing all reactions...</b>\n\n<b>Cleared:</b> <code>{counter}</code> chats"
|
|
||||||
)
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
modules_help["clear_notifs"] = {
|
modules_help['clear_notifs'] = {
|
||||||
"clear_@": "clear all mentions in this chat",
|
'clear_@': 'clear all mentions in this chat',
|
||||||
"clear_all_@": "clear all mentions in all chats",
|
'clear_all_@': 'clear all mentions in all chats',
|
||||||
"clear_reacts": "clear all reactions in this chat",
|
'clear_reacts': 'clear all reactions in this chat',
|
||||||
"clear_all_reacts": "clear all reactions in all chats (except private chats)",
|
'clear_all_reacts': 'clear all reactions in all chats (except private chats)',
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-54
@@ -1,26 +1,24 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
from json import tool
|
|
||||||
from utils.scripts import import_library
|
|
||||||
from utils.config import cohere_key
|
|
||||||
|
|
||||||
cohere = import_library("cohere")
|
from utils.config import cohere_key
|
||||||
|
from utils.scripts import import_library
|
||||||
|
|
||||||
|
cohere = import_library('cohere')
|
||||||
|
|
||||||
import cohere
|
import cohere
|
||||||
|
|
||||||
co = cohere.Client(cohere_key)
|
co = cohere.Client(cohere_key)
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from pyrogram import Client, enums, filters
|
||||||
from utils.scripts import format_exc
|
|
||||||
from utils.db import db
|
|
||||||
from utils.rentry import paste as rentry_paste
|
|
||||||
|
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageTooLong
|
from pyrogram.errors import MessageTooLong
|
||||||
|
from pyrogram.types import Message
|
||||||
|
from utils.db import db
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
|
from utils.rentry import paste as rentry_paste
|
||||||
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("cohere", prefix) & filters.me)
|
@Client.on_message(filters.command('cohere', prefix) & filters.me)
|
||||||
async def cohere(c: Client, message: Message):
|
async def cohere(c: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
user_id = message.from_user.id
|
user_id = message.from_user.id
|
||||||
@@ -31,104 +29,94 @@ async def cohere(c: Client, message: Message):
|
|||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
prompt = message.reply_to_message.text
|
prompt = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}cohere [prompt/reply to message]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}cohere [prompt/reply to message]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
db.add_chat_history(user_id, {"role": "USER", "message": prompt})
|
db.add_chat_history(user_id, {'role': 'USER', 'message': prompt})
|
||||||
|
|
||||||
await message.edit_text("<code>Umm, lemme think...</code>")
|
await message.edit_text('<code>Umm, lemme think...</code>')
|
||||||
|
|
||||||
response = co.chat_stream(
|
response = co.chat_stream(
|
||||||
chat_history=chat_history,
|
chat_history=chat_history,
|
||||||
model="command-r-plus",
|
model='command-r-plus',
|
||||||
message=prompt,
|
message=prompt,
|
||||||
temperature=0.8,
|
temperature=0.8,
|
||||||
tools=[{"name": "internet_search"}],
|
tools=[{'name': 'internet_search'}],
|
||||||
connectors=[],
|
connectors=[],
|
||||||
prompt_truncation="OFF",
|
prompt_truncation='OFF',
|
||||||
)
|
)
|
||||||
output = ""
|
output = ''
|
||||||
tool_message = ""
|
tool_message = ''
|
||||||
data = []
|
data = []
|
||||||
for event in response:
|
for event in response:
|
||||||
if event.event_type == "tool-calls-chunk":
|
if event.event_type == 'tool-calls-chunk':
|
||||||
if event.tool_call_delta and event.tool_call_delta.text is None:
|
if event.tool_call_delta and event.tool_call_delta.text is None:
|
||||||
tool_message += ""
|
tool_message += ''
|
||||||
else:
|
else:
|
||||||
tool_message += event.text
|
tool_message += event.text
|
||||||
if event.event_type == "search-results":
|
if event.event_type == 'search-results':
|
||||||
data.append(event.documents)
|
data.append(event.documents)
|
||||||
if event.event_type == "text-generation":
|
if event.event_type == 'text-generation':
|
||||||
output += event.text
|
output += event.text
|
||||||
if output == "":
|
if output == '':
|
||||||
output = "I can't seem to find an answer to that"
|
output = "I can't seem to find an answer to that"
|
||||||
|
|
||||||
db.add_chat_history(user_id, {"role": "CHATBOT", "message": output})
|
db.add_chat_history(user_id, {'role': 'CHATBOT', 'message': output})
|
||||||
|
|
||||||
await message.edit_text(f"<code>{tool_message}</code>")
|
await message.edit_text(f'<code>{tool_message}</code>')
|
||||||
|
|
||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = data[0]
|
data = data[0]
|
||||||
references = ""
|
references = ''
|
||||||
reference_dict = {}
|
reference_dict = {}
|
||||||
for item in data:
|
for item in data:
|
||||||
title = item["title"]
|
title = item['title']
|
||||||
url = item["url"]
|
url = item['url']
|
||||||
if title not in reference_dict:
|
if title not in reference_dict:
|
||||||
reference_dict[title] = url
|
reference_dict[title] = url
|
||||||
|
|
||||||
i = 1
|
i = 1
|
||||||
for title, url in reference_dict.items():
|
for title, url in reference_dict.items():
|
||||||
references += f"**{i}.** [{title}]({url})\n"
|
references += f'**{i}.** [{title}]({url})\n'
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"**Question:**`{prompt}`\n**Answer:** {output}\n\n**References:**\n{references}",
|
f'**Question:**`{prompt}`\n**Answer:** {output}\n\n**References:**\n{references}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
except IndexError:
|
except IndexError:
|
||||||
references = ""
|
references = ''
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"**Question:**`{prompt}`\n**Answer:** {output}\n",
|
f'**Question:**`{prompt}`\n**Answer:** {output}\n',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
await message.edit_text(
|
await message.edit_text('<code>Output is too long... Pasting to rentry...</code>')
|
||||||
"<code>Output is too long... Pasting to rentry...</code>"
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
output = output + "\n\n" + references if references else output
|
output = output + '\n\n' + references if references else output
|
||||||
rentry_url, edit_code = await rentry_paste(
|
rentry_url, edit_code = await rentry_paste(text=output, return_edit=True)
|
||||||
text=output, return_edit=True
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
await message.edit_text(
|
await message.edit_text('<b>Error:</b> <code>Failed to paste to rentry</code>')
|
||||||
"<b>Error:</b> <code>Failed to paste to rentry</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
await c.send_message(
|
await c.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Output:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>",
|
f'<b>Output:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["cohere"] = {
|
modules_help['cohere'] = {
|
||||||
"cohere": "Chat with cohere ai"
|
'cohere': 'Chat with cohere ai' + '\nSupports Chat History\n' + 'Supports real time internet search'
|
||||||
+ "\nSupports Chat History\n"
|
|
||||||
+ "Supports real time internet search"
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,93 +1,64 @@
|
|||||||
import random
|
import random
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import import_library
|
from utils.scripts import import_library
|
||||||
|
|
||||||
requests = import_library("requests")
|
requests = import_library('requests')
|
||||||
PIL = import_library("PIL", "pillow")
|
PIL = import_library('PIL', 'pillow')
|
||||||
|
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["dem"], prefix) & filters.me)
|
@Client.on_message(filters.command(['dem'], prefix) & filters.me)
|
||||||
async def demotivator(client: Client, message: Message):
|
async def demotivator(client: Client, message: Message):
|
||||||
await message.edit(
|
await message.edit('<code>Process of demotivation...</code>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<code>Process of demotivation...</code>", parse_mode=enums.ParseMode.HTML
|
font = requests.get('https://github.com/The-MoonTg-project/files/blob/main/Times%20New%20Roman.ttf?raw=true')
|
||||||
)
|
|
||||||
font = requests.get(
|
|
||||||
"https://github.com/The-MoonTg-project/files/blob/main/Times%20New%20Roman.ttf?raw=true"
|
|
||||||
)
|
|
||||||
f = font.content
|
f = font.content
|
||||||
template_dem = requests.get(
|
template_dem = requests.get('https://raw.githubusercontent.com/files/main/demotivator.png')
|
||||||
"https://raw.githubusercontent.com/files/main/demotivator.png"
|
|
||||||
)
|
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
words = ["random", "text", "typing", "fuck"]
|
words = ['random', 'text', 'typing', 'fuck']
|
||||||
if message.reply_to_message.photo:
|
if message.reply_to_message.photo:
|
||||||
donwloads = await client.download_media(
|
donwloads = await client.download_media(message.reply_to_message.photo.file_id)
|
||||||
message.reply_to_message.photo.file_id
|
photo = Image.open(f'{donwloads}')
|
||||||
)
|
|
||||||
photo = Image.open(f"{donwloads}")
|
|
||||||
resize_photo = photo.resize((469, 312))
|
resize_photo = photo.resize((469, 312))
|
||||||
text = (
|
text = message.text.split(' ', maxsplit=1)[1] if len(message.text.split()) > 1 else random.choice(words)
|
||||||
message.text.split(" ", maxsplit=1)[1]
|
|
||||||
if len(message.text.split()) > 1
|
|
||||||
else random.choice(words)
|
|
||||||
)
|
|
||||||
im = Image.open(BytesIO(template_dem.content))
|
im = Image.open(BytesIO(template_dem.content))
|
||||||
im.paste(resize_photo, (65, 48))
|
im.paste(resize_photo, (65, 48))
|
||||||
text_font = ImageFont.truetype(BytesIO(f), 22)
|
text_font = ImageFont.truetype(BytesIO(f), 22)
|
||||||
text_draw = ImageDraw.Draw(im)
|
text_draw = ImageDraw.Draw(im)
|
||||||
text_draw.multiline_text(
|
text_draw.multiline_text((299, 412), text, font=text_font, fill=(255, 255, 255), anchor='ms')
|
||||||
(299, 412), text, font=text_font, fill=(255, 255, 255), anchor="ms"
|
im.save(f'downloads/{message.id}.png')
|
||||||
)
|
await message.reply_to_message.reply_photo(f'downloads/{message.id}.png')
|
||||||
im.save(f"downloads/{message.id}.png")
|
|
||||||
await message.reply_to_message.reply_photo(f"downloads/{message.id}.png")
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
elif message.reply_to_message.sticker:
|
elif message.reply_to_message.sticker:
|
||||||
if not message.reply_to_message.sticker.is_animated:
|
if not message.reply_to_message.sticker.is_animated:
|
||||||
donwloads = await client.download_media(
|
donwloads = await client.download_media(message.reply_to_message.sticker.file_id)
|
||||||
message.reply_to_message.sticker.file_id
|
photo = Image.open(f'{donwloads}')
|
||||||
)
|
|
||||||
photo = Image.open(f"{donwloads}")
|
|
||||||
resize_photo = photo.resize((469, 312))
|
resize_photo = photo.resize((469, 312))
|
||||||
text = (
|
text = message.text.split(' ', maxsplit=1)[1] if len(message.text.split()) > 1 else random.choice(words)
|
||||||
message.text.split(" ", maxsplit=1)[1]
|
|
||||||
if len(message.text.split()) > 1
|
|
||||||
else random.choice(words)
|
|
||||||
)
|
|
||||||
im = Image.open(BytesIO(template_dem.content))
|
im = Image.open(BytesIO(template_dem.content))
|
||||||
im.paste(resize_photo, (65, 48))
|
im.paste(resize_photo, (65, 48))
|
||||||
text_font = ImageFont.truetype(BytesIO(f), 22)
|
text_font = ImageFont.truetype(BytesIO(f), 22)
|
||||||
text_draw = ImageDraw.Draw(im)
|
text_draw = ImageDraw.Draw(im)
|
||||||
text_draw.multiline_text(
|
text_draw.multiline_text((299, 412), text, font=text_font, fill=(255, 255, 255), anchor='ms')
|
||||||
(299, 412), text, font=text_font, fill=(255, 255, 255), anchor="ms"
|
im.save(f'downloads/{message.id}.png')
|
||||||
)
|
await message.reply_to_message.reply_photo(f'downloads/{message.id}.png')
|
||||||
im.save(f"downloads/{message.id}.png")
|
|
||||||
await message.reply_to_message.reply_photo(
|
|
||||||
f"downloads/{message.id}.png"
|
|
||||||
)
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Animated stickers are not supported</b>",
|
'<b>Animated stickers are not supported</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Need to answer the photo/sticker</b>",
|
'<b>Need to answer the photo/sticker</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit('<b>Need to answer the photo/sticker</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Need to answer the photo/sticker</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
modules_help["demotivator"] = {
|
modules_help['demotivator'] = {'dem [text]*': 'Reply to the picture to make a demotivator out of it'}
|
||||||
"dem [text]*": "Reply to the picture to make a demotivator out of it"
|
|
||||||
}
|
|
||||||
|
|||||||
+19
-25
@@ -1,60 +1,54 @@
|
|||||||
import os
|
import os
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import import_library
|
from utils.scripts import import_library
|
||||||
|
|
||||||
lottie = import_library("lottie")
|
lottie = import_library('lottie')
|
||||||
from lottie.exporters import exporters
|
from lottie.exporters import exporters
|
||||||
from lottie.importers import importers
|
from lottie.importers import importers
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("destroy", prefix) & filters.me)
|
@Client.on_message(filters.command('destroy', prefix) & filters.me)
|
||||||
async def destroy_sticker(client: Client, message: Message):
|
async def destroy_sticker(client: Client, message: Message):
|
||||||
"""Destroy animated stickers by modifying their animation properties"""
|
"""Destroy animated stickers by modifying their animation properties"""
|
||||||
try:
|
try:
|
||||||
reply = message.reply_to_message
|
reply = message.reply_to_message
|
||||||
if not reply or not reply.sticker or not reply.sticker.is_animated:
|
if not reply or not reply.sticker or not reply.sticker.is_animated:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"**Please reply to an animated sticker!**",
|
'**Please reply to an animated sticker!**',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
|
|
||||||
edit_msg = await message.edit(
|
edit_msg = await message.edit('**🔄 Destroying sticker...**', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"**🔄 Destroying sticker...**", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
# Download sticker
|
# Download sticker
|
||||||
tgs_path = await reply.download()
|
tgs_path = await reply.download()
|
||||||
if not tgs_path or not os.path.exists(tgs_path):
|
if not tgs_path or not os.path.exists(tgs_path):
|
||||||
return await edit_msg.edit(
|
return await edit_msg.edit('**❌ Download failed!**', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"**❌ Download failed!**", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
# Conversion process
|
# Conversion process
|
||||||
json_path = "temp.json"
|
json_path = 'temp.json'
|
||||||
output_path = "MoonUB.tgs"
|
output_path = 'MoonUB.tgs'
|
||||||
|
|
||||||
importer = importers.get_from_filename(tgs_path)
|
importer = importers.get_from_filename(tgs_path)
|
||||||
if not importer:
|
if not importer:
|
||||||
return await edit_msg.edit(
|
return await edit_msg.edit('**❌ JSON conversion failed!**', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
"**❌ JSON conversion failed!**", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
animation = importer.process(tgs_path)
|
animation = importer.process(tgs_path)
|
||||||
exporter = exporters.get_from_filename(json_path)
|
exporter = exporters.get_from_filename(json_path)
|
||||||
exporter.process(animation, json_path)
|
exporter.process(animation, json_path)
|
||||||
|
|
||||||
# Modify JSON data
|
# Modify JSON data
|
||||||
with open(json_path, "r+") as f:
|
with open(json_path, 'r+') as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
modified = (
|
modified = (
|
||||||
content.replace("[1]", "[2]")
|
content.replace('[1]', '[2]')
|
||||||
.replace("[2]", "[3]")
|
.replace('[2]', '[3]')
|
||||||
.replace("[3]", "[4]")
|
.replace('[3]', '[4]')
|
||||||
.replace("[4]", "[5]")
|
.replace('[4]', '[5]')
|
||||||
.replace("[5]", "[6]")
|
.replace('[5]', '[6]')
|
||||||
)
|
)
|
||||||
f.seek(0)
|
f.seek(0)
|
||||||
f.write(modified)
|
f.write(modified)
|
||||||
@@ -70,7 +64,7 @@ async def destroy_sticker(client: Client, message: Message):
|
|||||||
await edit_msg.delete()
|
await edit_msg.delete()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(f"**❌ Error:** `{e}`", parse_mode=enums.ParseMode.MARKDOWN)
|
await message.edit(f'**❌ Error:** `{e}`', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
finally:
|
finally:
|
||||||
# Cleanup temporary files
|
# Cleanup temporary files
|
||||||
for file_path in [tgs_path, json_path, output_path]:
|
for file_path in [tgs_path, json_path, output_path]:
|
||||||
@@ -78,7 +72,7 @@ async def destroy_sticker(client: Client, message: Message):
|
|||||||
try:
|
try:
|
||||||
os.remove(file_path)
|
os.remove(file_path)
|
||||||
except Exception as clean_error:
|
except Exception as clean_error:
|
||||||
print(f"Cleanup error: {clean_error}")
|
print(f'Cleanup error: {clean_error}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["destroy"] = {"destroy [reply]": "Modify and destroy animated stickers"}
|
modules_help['destroy'] = {'destroy [reply]': 'Modify and destroy animated stickers'}
|
||||||
|
|||||||
+8
-15
@@ -1,33 +1,26 @@
|
|||||||
from pyrogram import Client, filters, enums
|
import asyncio
|
||||||
|
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
import asyncio
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("dice", prefix) & filters.me)
|
@Client.on_message(filters.command('dice', prefix) & filters.me)
|
||||||
async def dice_text(client: Client, message: Message):
|
async def dice_text(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
value = int(message.command[1])
|
value = int(message.command[1])
|
||||||
if value not in range(1, 7):
|
if value not in range(1, 7):
|
||||||
raise AssertionError
|
raise AssertionError
|
||||||
except (ValueError, IndexError, AssertionError):
|
except (ValueError, IndexError, AssertionError):
|
||||||
return await message.edit(
|
return await message.edit('<b>Invalid value</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Invalid value</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
message.dice = type("bruh", (), {"value": 0})()
|
message.dice = type('bruh', (), {'value': 0})()
|
||||||
while message.dice.value != value:
|
while message.dice.value != value:
|
||||||
message = (
|
message = (await asyncio.gather(message.delete(), client.send_dice(message.chat.id)))[1]
|
||||||
await asyncio.gather(
|
|
||||||
message.delete(), client.send_dice(message.chat.id)
|
|
||||||
)
|
|
||||||
)[1]
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["dice"] = {
|
modules_help['dice'] = {'dice [1-6]*': 'Generate dice with specified value. Works only in groups'}
|
||||||
"dice [1-6]*": "Generate dice with specified value. Works only in groups"
|
|
||||||
}
|
|
||||||
|
|||||||
+127
-137
@@ -3,7 +3,7 @@
|
|||||||
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
|
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
#
|
#
|
||||||
""" Userbot module containing various sites direct links generators"""
|
"""Userbot module containing various sites direct links generators"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
@@ -14,139 +14,135 @@ from subprocess import PIPE, Popen
|
|||||||
import requests
|
import requests
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from humanize import naturalsize
|
from humanize import naturalsize
|
||||||
|
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
def subprocess_run(cmd):
|
def subprocess_run(cmd):
|
||||||
reply = ""
|
reply = ''
|
||||||
cmd_args = cmd.split()
|
cmd_args = cmd.split()
|
||||||
subproc = Popen(
|
subproc = Popen(
|
||||||
cmd_args,
|
cmd_args,
|
||||||
stdout=PIPE,
|
stdout=PIPE,
|
||||||
stderr=PIPE,
|
stderr=PIPE,
|
||||||
universal_newlines=True,
|
universal_newlines=True,
|
||||||
executable="bash",
|
executable='bash',
|
||||||
)
|
)
|
||||||
talk = subproc.communicate()
|
talk = subproc.communicate()
|
||||||
exitCode = subproc.returncode
|
exitCode = subproc.returncode
|
||||||
if exitCode != 0:
|
if exitCode != 0:
|
||||||
reply += (
|
reply += (
|
||||||
"```An error was detected while running the subprocess:\n"
|
'```An error was detected while running the subprocess:\n'
|
||||||
f"exit code: {exitCode}\n"
|
f'exit code: {exitCode}\n'
|
||||||
f"stdout: {talk[0]}\n"
|
f'stdout: {talk[0]}\n'
|
||||||
f"stderr: {talk[1]}```"
|
f'stderr: {talk[1]}```'
|
||||||
)
|
)
|
||||||
return reply
|
return reply
|
||||||
return talk
|
return talk
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("direct", prefix) & filters.me)
|
@Client.on_message(filters.command('direct', prefix) & filters.me)
|
||||||
async def direct_link_generator(_, m: Message):
|
async def direct_link_generator(_, m: Message):
|
||||||
if len(m.command) > 1:
|
if len(m.command) > 1:
|
||||||
message = m.text.split(maxsplit=1)[1]
|
message = m.text.split(maxsplit=1)[1]
|
||||||
elif m.reply_to_message:
|
elif m.reply_to_message:
|
||||||
message = m.reply_to_message.text
|
message = m.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await m.edit(f"<b>Usage: </b><code>{prefix}direct [url]</code>")
|
await m.edit(f'<b>Usage: </b><code>{prefix}direct [url]</code>')
|
||||||
return
|
return
|
||||||
reply = ""
|
reply = ''
|
||||||
links = re.findall(r"\bhttps?://.*\.\S+", message)
|
links = re.findall(r'\bhttps?://.*\.\S+', message)
|
||||||
if not links:
|
if not links:
|
||||||
reply = "`No links found!`"
|
reply = '`No links found!`'
|
||||||
await m.edit(reply, parse_mode=enums.ParseMode.MARKDOWN)
|
await m.edit(reply, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
for link in links:
|
for link in links:
|
||||||
if "drive.google.com" in link:
|
if 'drive.google.com' in link:
|
||||||
reply += gdrive(link)
|
reply += gdrive(link)
|
||||||
elif "yadi.sk" in link:
|
elif 'yadi.sk' in link:
|
||||||
reply += yandex_disk(link)
|
reply += yandex_disk(link)
|
||||||
elif "cloud.mail.ru" in link:
|
elif 'cloud.mail.ru' in link:
|
||||||
reply += cm_ru(link)
|
reply += cm_ru(link)
|
||||||
elif "mediafire.com" in link:
|
elif 'mediafire.com' in link:
|
||||||
reply += mediafire(link)
|
reply += mediafire(link)
|
||||||
elif "sourceforge.net" in link:
|
elif 'sourceforge.net' in link:
|
||||||
reply += sourceforge(link)
|
reply += sourceforge(link)
|
||||||
elif "osdn.net" in link:
|
elif 'osdn.net' in link:
|
||||||
reply += osdn(link)
|
reply += osdn(link)
|
||||||
elif "androidfilehost.com" in link:
|
elif 'androidfilehost.com' in link:
|
||||||
reply += androidfilehost(link)
|
reply += androidfilehost(link)
|
||||||
else:
|
else:
|
||||||
reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + " is not supported"
|
reply += re.findall(r'\bhttps?://(.*?[^/]+)', link)[0] + ' is not supported'
|
||||||
await m.edit(reply, parse_mode=enums.ParseMode.MARKDOWN)
|
await m.edit(reply, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
def gdrive(url: str) -> str:
|
def gdrive(url: str) -> str:
|
||||||
"""GDrive direct links generator"""
|
"""GDrive direct links generator"""
|
||||||
drive = "https://drive.google.com"
|
drive = 'https://drive.google.com'
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://drive\.google\.com\S+", url)[0]
|
link = re.findall(r'\bhttps?://drive\.google\.com\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No Google drive links found`\n"
|
reply = '`No Google drive links found`\n'
|
||||||
return reply
|
return reply
|
||||||
file_id = ""
|
file_id = ''
|
||||||
reply = ""
|
reply = ''
|
||||||
if link.find("view") != -1:
|
if link.find('view') != -1:
|
||||||
file_id = link.split("/")[-2]
|
file_id = link.split('/')[-2]
|
||||||
elif link.find("open?id=") != -1:
|
elif link.find('open?id=') != -1:
|
||||||
file_id = link.split("open?id=")[1].strip()
|
file_id = link.split('open?id=')[1].strip()
|
||||||
elif link.find("uc?id=") != -1:
|
elif link.find('uc?id=') != -1:
|
||||||
file_id = link.split("uc?id=")[1].strip()
|
file_id = link.split('uc?id=')[1].strip()
|
||||||
url = f"{drive}/uc?export=download&id={file_id}"
|
url = f'{drive}/uc?export=download&id={file_id}'
|
||||||
download = requests.get(url, stream=True, allow_redirects=False)
|
download = requests.get(url, stream=True, allow_redirects=False)
|
||||||
cookies = download.cookies
|
cookies = download.cookies
|
||||||
try:
|
try:
|
||||||
# In case of small file size, Google downloads directly
|
# In case of small file size, Google downloads directly
|
||||||
dl_url = download.headers["location"]
|
dl_url = download.headers['location']
|
||||||
page = BeautifulSoup(download.content, "html.parser")
|
page = BeautifulSoup(download.content, 'html.parser')
|
||||||
if "accounts.google.com" in dl_url: # non-public file
|
if 'accounts.google.com' in dl_url: # non-public file
|
||||||
reply += "`Link is not public!`\n"
|
reply += '`Link is not public!`\n'
|
||||||
return reply
|
return reply
|
||||||
name = "Direct Download Link"
|
name = 'Direct Download Link'
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# In case of download warning page
|
# In case of download warning page
|
||||||
page = BeautifulSoup(download.content, "html.parser")
|
page = BeautifulSoup(download.content, 'html.parser')
|
||||||
if download.headers is not None:
|
if download.headers is not None:
|
||||||
dl_url = download.headers.get("location")
|
dl_url = download.headers.get('location')
|
||||||
page_element = page.find("a", {"id": "uc-download-link"})
|
page_element = page.find('a', {'id': 'uc-download-link'})
|
||||||
if page_element is not None:
|
if page_element is not None:
|
||||||
export = drive + page_element.get("href")
|
export = drive + page_element.get('href')
|
||||||
name = page.find("span", {"class": "uc-name-size"}).text
|
name = page.find('span', {'class': 'uc-name-size'}).text
|
||||||
response = requests.get(
|
response = requests.get(export, stream=True, allow_redirects=False, cookies=cookies)
|
||||||
export, stream=True, allow_redirects=False, cookies=cookies
|
dl_url = response.headers['location']
|
||||||
)
|
if 'accounts.google.com' in dl_url:
|
||||||
dl_url = response.headers["location"]
|
name = page.find('span', {'class': 'uc-name-size'}).text
|
||||||
if "accounts.google.com" in dl_url:
|
reply += 'Link is not public!'
|
||||||
name = page.find("span", {"class": "uc-name-size"}).text
|
|
||||||
reply += "Link is not public!"
|
|
||||||
return reply
|
return reply
|
||||||
if "=sharing" in dl_url:
|
if '=sharing' in dl_url:
|
||||||
name = page.find("span", {"class": "uc-name-size"}).text
|
name = page.find('span', {'class': 'uc-name-size'}).text
|
||||||
reply += "```Provide GDrive Link not directc sharing of GDrive!```"
|
reply += '```Provide GDrive Link not directc sharing of GDrive!```'
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
reply += f"[{name}]({dl_url})\n"
|
reply += f'[{name}]({dl_url})\n'
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
def yandex_disk(url: str) -> str:
|
def yandex_disk(url: str) -> str:
|
||||||
"""Yandex.Disk direct links generator
|
"""Yandex.Disk direct links generator
|
||||||
Based on https://github.com/wldhx/yadisk-direct"""
|
Based on https://github.com/wldhx/yadisk-direct"""
|
||||||
reply = ""
|
reply = ''
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*yadi\.sk\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No Yandex.Disk links found`\n"
|
reply = '`No Yandex.Disk links found`\n'
|
||||||
return reply
|
return reply
|
||||||
api = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}"
|
api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
|
||||||
try:
|
try:
|
||||||
dl_url = requests.get(api.format(link)).json()["href"]
|
dl_url = requests.get(api.format(link)).json()['href']
|
||||||
name = dl_url.split("filename=")[1].split("&disposition")[0]
|
name = dl_url.split('filename=')[1].split('&disposition')[0]
|
||||||
reply += f"[{name}]({dl_url})\n"
|
reply += f'[{name}]({dl_url})\n'
|
||||||
except KeyError:
|
except KeyError:
|
||||||
reply += "`Error: File not found / Download limit reached`\n"
|
reply += '`Error: File not found / Download limit reached`\n'
|
||||||
return reply
|
return reply
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
@@ -154,13 +150,13 @@ def yandex_disk(url: str) -> str:
|
|||||||
def cm_ru(url: str) -> str:
|
def cm_ru(url: str) -> str:
|
||||||
"""cloud.mail.ru direct links generator
|
"""cloud.mail.ru direct links generator
|
||||||
Using https://github.com/JrMasterModelBuilder/cmrudl.py"""
|
Using https://github.com/JrMasterModelBuilder/cmrudl.py"""
|
||||||
reply = ""
|
reply = ''
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*cloud\.mail\.ru\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*cloud\.mail\.ru\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No cloud.mail.ru links found`\n"
|
reply = '`No cloud.mail.ru links found`\n'
|
||||||
return reply
|
return reply
|
||||||
cmd = f"bin/cmrudl -s {link}"
|
cmd = f'bin/cmrudl -s {link}'
|
||||||
result = subprocess_run(cmd)
|
result = subprocess_run(cmd)
|
||||||
try:
|
try:
|
||||||
result = result[0].splitlines()[-1]
|
result = result[0].splitlines()[-1]
|
||||||
@@ -170,121 +166,116 @@ def cm_ru(url: str) -> str:
|
|||||||
return reply
|
return reply
|
||||||
except IndexError:
|
except IndexError:
|
||||||
return reply
|
return reply
|
||||||
dl_url = data["download"]
|
dl_url = data['download']
|
||||||
name = data["file_name"]
|
name = data['file_name']
|
||||||
size = naturalsize(int(data["file_size"]))
|
size = naturalsize(int(data['file_size']))
|
||||||
reply += f"[{name} ({size})]({dl_url})\n"
|
reply += f'[{name} ({size})]({dl_url})\n'
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
def mediafire(url: str) -> str:
|
def mediafire(url: str) -> str:
|
||||||
"""MediaFire direct links generator"""
|
"""MediaFire direct links generator"""
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*mediafire\.com\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No MediaFire links found`\n"
|
reply = '`No MediaFire links found`\n'
|
||||||
return reply
|
return reply
|
||||||
reply = ""
|
reply = ''
|
||||||
page = BeautifulSoup(requests.get(link).content, "lxml")
|
page = BeautifulSoup(requests.get(link).content, 'lxml')
|
||||||
info = page.find("a", {"aria-label": "Download file"})
|
info = page.find('a', {'aria-label': 'Download file'})
|
||||||
dl_url = info.get("href")
|
dl_url = info.get('href')
|
||||||
size = re.findall(r"\(.*\)", info.text)[0]
|
size = re.findall(r'\(.*\)', info.text)[0]
|
||||||
name = page.find("div", {"class": "filename"}).text
|
name = page.find('div', {'class': 'filename'}).text
|
||||||
reply += f"[{name} {size}]({dl_url})\n"
|
reply += f'[{name} {size}]({dl_url})\n'
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
def sourceforge(url: str) -> str:
|
def sourceforge(url: str) -> str:
|
||||||
"""SourceForge direct links generator"""
|
"""SourceForge direct links generator"""
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*sourceforge\.net\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*sourceforge\.net\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No SourceForge links found`\n"
|
reply = '`No SourceForge links found`\n'
|
||||||
return reply
|
return reply
|
||||||
file_path = re.findall(r"files(.*)/download", link)[0]
|
file_path = re.findall(r'files(.*)/download', link)[0]
|
||||||
reply = f"Mirrors for __{file_path.split('/')[-1]}__\n"
|
reply = f'Mirrors for __{file_path.split("/")[-1]}__\n'
|
||||||
project = re.findall(r"projects?/(.*?)/files", link)[0]
|
project = re.findall(r'projects?/(.*?)/files', link)[0]
|
||||||
mirrors = (
|
mirrors = f'https://sourceforge.net/settings/mirror_choices?projectname={project}&filename={file_path}'
|
||||||
f"https://sourceforge.net/settings/mirror_choices?"
|
page = BeautifulSoup(requests.get(mirrors).content, 'html.parser')
|
||||||
f"projectname={project}&filename={file_path}"
|
info = page.find('ul', {'id': 'mirrorList'}).findAll('li')
|
||||||
)
|
|
||||||
page = BeautifulSoup(requests.get(mirrors).content, "html.parser")
|
|
||||||
info = page.find("ul", {"id": "mirrorList"}).findAll("li")
|
|
||||||
for mirror in info[1:]:
|
for mirror in info[1:]:
|
||||||
name = re.findall(r"\((.*)\)", mirror.text.strip())[0]
|
name = re.findall(r'\((.*)\)', mirror.text.strip())[0]
|
||||||
dl_url = (
|
dl_url = f'https://{mirror["id"]}.dl.sourceforge.net/project/{project}/{file_path}'
|
||||||
f'https://{mirror["id"]}.dl.sourceforge.net/project/{project}/{file_path}'
|
reply += f'[{name}]({dl_url}) '
|
||||||
)
|
|
||||||
reply += f"[{name}]({dl_url}) "
|
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
def osdn(url: str) -> str:
|
def osdn(url: str) -> str:
|
||||||
"""OSDN direct links generator"""
|
"""OSDN direct links generator"""
|
||||||
osdn_link = "https://osdn.net"
|
osdn_link = 'https://osdn.net'
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*osdn\.net\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No OSDN links found`\n"
|
reply = '`No OSDN links found`\n'
|
||||||
return reply
|
return reply
|
||||||
page = BeautifulSoup(requests.get(link, allow_redirects=True).content, "lxml")
|
page = BeautifulSoup(requests.get(link, allow_redirects=True).content, 'lxml')
|
||||||
info = page.find("a", {"class": "mirror_link"})
|
info = page.find('a', {'class': 'mirror_link'})
|
||||||
link = urllib.parse.unquote(osdn_link + info["href"])
|
link = urllib.parse.unquote(osdn_link + info['href'])
|
||||||
reply = f"Mirrors for __{link.split('/')[-1]}__\n"
|
reply = f'Mirrors for __{link.split("/")[-1]}__\n'
|
||||||
mirrors = page.find("form", {"id": "mirror-select-form"}).findAll("tr")
|
mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr')
|
||||||
for data in mirrors[1:]:
|
for data in mirrors[1:]:
|
||||||
mirror = data.find("input")["value"]
|
mirror = data.find('input')['value']
|
||||||
name = re.findall(r"\((.*)\)", data.findAll("td")[-1].text.strip())[0]
|
name = re.findall(r'\((.*)\)', data.findAll('td')[-1].text.strip())[0]
|
||||||
dl_url = re.sub(r"m=(.*)&f", f"m={mirror}&f", link)
|
dl_url = re.sub(r'm=(.*)&f', f'm={mirror}&f', link)
|
||||||
reply += f"[{name}]({dl_url}) "
|
reply += f'[{name}]({dl_url}) '
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
def androidfilehost(url: str) -> str:
|
def androidfilehost(url: str) -> str:
|
||||||
"""AFH direct links generator"""
|
"""AFH direct links generator"""
|
||||||
try:
|
try:
|
||||||
link = re.findall(r"\bhttps?://.*androidfilehost.*fid.*\S+", url)[0]
|
link = re.findall(r'\bhttps?://.*androidfilehost.*fid.*\S+', url)[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
reply = "`No AFH links found`\n"
|
reply = '`No AFH links found`\n'
|
||||||
return reply
|
return reply
|
||||||
fid = re.findall(r"\?fid=(.*)", link)[0]
|
fid = re.findall(r'\?fid=(.*)', link)[0]
|
||||||
session = requests.Session()
|
session = requests.Session()
|
||||||
user_agent = useragent()
|
user_agent = useragent()
|
||||||
headers = {"user-agent": user_agent}
|
headers = {'user-agent': user_agent}
|
||||||
res = session.get(link, headers=headers, allow_redirects=True)
|
res = session.get(link, headers=headers, allow_redirects=True)
|
||||||
headers = {
|
headers = {
|
||||||
"origin": "https://androidfilehost.com",
|
'origin': 'https://androidfilehost.com',
|
||||||
"accept-encoding": "gzip, deflate, br",
|
'accept-encoding': 'gzip, deflate, br',
|
||||||
"accept-language": "en-US,en;q=0.9",
|
'accept-language': 'en-US,en;q=0.9',
|
||||||
"user-agent": user_agent,
|
'user-agent': user_agent,
|
||||||
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||||
"x-mod-sbb-ctype": "xhr",
|
'x-mod-sbb-ctype': 'xhr',
|
||||||
"accept": "*/*",
|
'accept': '*/*',
|
||||||
"referer": f"https://androidfilehost.com/?fid={fid}",
|
'referer': f'https://androidfilehost.com/?fid={fid}',
|
||||||
"authority": "androidfilehost.com",
|
'authority': 'androidfilehost.com',
|
||||||
"x-requested-with": "XMLHttpRequest",
|
'x-requested-with': 'XMLHttpRequest',
|
||||||
}
|
}
|
||||||
data = {"submit": "submit", "action": "getdownloadmirrors", "fid": f"{fid}"}
|
data = {'submit': 'submit', 'action': 'getdownloadmirrors', 'fid': f'{fid}'}
|
||||||
mirrors = None
|
mirrors = None
|
||||||
reply = ""
|
reply = ''
|
||||||
error = "`Error: Can't find Mirrors for the link`\n"
|
error = "`Error: Can't find Mirrors for the link`\n"
|
||||||
try:
|
try:
|
||||||
req = session.post(
|
req = session.post(
|
||||||
"https://androidfilehost.com/libs/otf/mirrors.otf.php",
|
'https://androidfilehost.com/libs/otf/mirrors.otf.php',
|
||||||
headers=headers,
|
headers=headers,
|
||||||
data=data,
|
data=data,
|
||||||
cookies=res.cookies,
|
cookies=res.cookies,
|
||||||
)
|
)
|
||||||
mirrors = req.json()["MIRRORS"]
|
mirrors = req.json()['MIRRORS']
|
||||||
except (json.decoder.JSONDecodeError, TypeError):
|
except (json.decoder.JSONDecodeError, TypeError):
|
||||||
reply += error
|
reply += error
|
||||||
if not mirrors:
|
if not mirrors:
|
||||||
reply += error
|
reply += error
|
||||||
return reply
|
return reply
|
||||||
for item in mirrors:
|
for item in mirrors:
|
||||||
name = item["name"]
|
name = item['name']
|
||||||
dl_url = item["url"]
|
dl_url = item['url']
|
||||||
reply += f"[{name}]({dl_url}) "
|
reply += f'[{name}]({dl_url}) '
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
|
|
||||||
@@ -294,20 +285,19 @@ def useragent():
|
|||||||
"""
|
"""
|
||||||
useragents = BeautifulSoup(
|
useragents = BeautifulSoup(
|
||||||
requests.get(
|
requests.get(
|
||||||
"https://developers.whatismybrowser.com/"
|
'https://developers.whatismybrowser.com/useragents/explore/operating_system_name/android/'
|
||||||
"useragents/explore/operating_system_name/android/"
|
|
||||||
).content,
|
).content,
|
||||||
"lxml",
|
'lxml',
|
||||||
).findAll("td", {"class": "useragent"})
|
).findAll('td', {'class': 'useragent'})
|
||||||
if not useragents:
|
if not useragents:
|
||||||
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
|
return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
|
||||||
user_agent = choice(useragents)
|
user_agent = choice(useragents)
|
||||||
return user_agent.text
|
return user_agent.text
|
||||||
|
|
||||||
|
|
||||||
modules_help["direct"] = {
|
modules_help['direct'] = {
|
||||||
"direct": "Url/reply to Url\
|
'direct': 'Url/reply to Url\
|
||||||
\n\n<b>Syntax : </b><code>.direct [url/reply] </code>\
|
\n\n<b>Syntax : </b><code>.direct [url/reply] </code>\
|
||||||
\n<b>Usage :</b> Generates direct download link from supported URL(s)\
|
\n<b>Usage :</b> Generates direct download link from supported URL(s)\
|
||||||
\n\n<b>Supported websites : </b><code>Google Drive - MEGA.nz - Cloud Mail - Yandex.Disk - AFH - MediaFire - SourceForge - OSDN</code>"
|
\n\n<b>Supported websites : </b><code>Google Drive - MEGA.nz - Cloud Mail - Yandex.Disk - AFH - MediaFire - SourceForge - OSDN</code>'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, requirements_list, prefix
|
from utils.misc import prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("duck", prefix) & filters.me)
|
@Client.on_message(filters.command('duck', prefix) & filters.me)
|
||||||
async def duckgo(client: Client, message: Message):
|
async def duckgo(client: Client, message: Message):
|
||||||
input_str = " ".join(message.command[1:])
|
input_str = ' '.join(message.command[1:])
|
||||||
sample_url = "https://duckduckgo.com/?q={}".format(input_str.replace(" ", "+"))
|
sample_url = 'https://duckduckgo.com/?q={}'.format(input_str.replace(' ', '+'))
|
||||||
if sample_url:
|
if sample_url:
|
||||||
link = sample_url.rstrip()
|
link = sample_url.rstrip()
|
||||||
await message.edit_text(
|
await message.edit_text(f'Let me 🦆 DuckDuckGo that for you:\n🔎 [{input_str}]({link})')
|
||||||
"Let me 🦆 DuckDuckGo that for you:\n🔎 [{}]({})".format(input_str, link)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text("something is wrong. please try again later.")
|
await message.edit_text('something is wrong. please try again later.')
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
from random import randint
|
from random import randint
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("durov", prefix) & filters.me)
|
@Client.on_message(filters.command('durov', prefix) & filters.me)
|
||||||
async def durov(_, message: Message):
|
async def durov(_, message: Message):
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Random post from channel: https://t.me/durov/{randint(21, 36500)}</b>",
|
f'<b>Random post from channel: https://t.me/durov/{randint(21, 36500)}</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["durov"] = {"durov": "Send random post from durov channel"}
|
modules_help['durov'] = {'durov': 'Send random post from durov channel'}
|
||||||
|
|||||||
@@ -16,7 +16,6 @@
|
|||||||
|
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
# if your module has packages from PyPi
|
# if your module has packages from PyPi
|
||||||
@@ -29,30 +28,26 @@ from utils.misc import modules_help, prefix
|
|||||||
# if it isn't installed
|
# if it isn't installed
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("example_edit", prefix) & filters.me)
|
@Client.on_message(filters.command('example_edit', prefix) & filters.me)
|
||||||
async def example_edit(client: Client, message: Message):
|
async def example_edit(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.edit("<code>This is an example module</code>")
|
await message.edit('<code>This is an example module</code>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(
|
await message.edit(f'<code>[{e.error_code}: {enums.MessageType.TEXT}] - {e.error_details}</code>')
|
||||||
f"<code>[{e.error_code}: {enums.MessageType.TEXT}] - {e.error_details}</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("example_send", prefix) & filters.me)
|
@Client.on_message(filters.command('example_send', prefix) & filters.me)
|
||||||
async def example_send(client: Client, message: Message):
|
async def example_send(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
await client.send_message(message.chat.id, "<b>This is an example module</b>")
|
await client.send_message(message.chat.id, '<b>This is an example module</b>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(
|
await message.edit(f'<code>[{e.error_code}: {enums.MessageType.TEXT}] - {e.error_details}</code>')
|
||||||
f"<code>[{e.error_code}: {enums.MessageType.TEXT}] - {e.error_details}</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# This adds instructions for your module
|
# This adds instructions for your module
|
||||||
modules_help["example"] = {
|
modules_help['example'] = {
|
||||||
"example_send": "example send",
|
'example_send': 'example send',
|
||||||
"example_edit": "example edit",
|
'example_edit': 'example edit',
|
||||||
}
|
}
|
||||||
|
|
||||||
# modules_help["example"] = { "example_send [text]": "example send" }
|
# modules_help["example"] = { "example_send [text]": "example send" }
|
||||||
|
|||||||
+27
-33
@@ -4,55 +4,49 @@ from random import randint
|
|||||||
import aiohttp
|
import aiohttp
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
async def download_sticker(url, filename):
|
async def download_sticker(url, filename):
|
||||||
headers = {
|
headers = {
|
||||||
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
|
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
|
||||||
"accept-language": "en-US,en;q=0.9;q=0.8",
|
'accept-language': 'en-US,en;q=0.9;q=0.8',
|
||||||
"cache-control": "no-cache",
|
'cache-control': 'no-cache',
|
||||||
"dnt": "1",
|
'dnt': '1',
|
||||||
"pragma": "no-cache",
|
'pragma': 'no-cache',
|
||||||
"priority": "u=0, i",
|
'priority': 'u=0, i',
|
||||||
"sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Microsoft Edge";v="138"',
|
'sec-ch-ua': '"Not)A;Brand";v="8", "Chromium";v="138", "Microsoft Edge";v="138"',
|
||||||
"sec-ch-ua-mobile": "?0",
|
'sec-ch-ua-mobile': '?0',
|
||||||
"sec-ch-ua-platform": '"Windows"',
|
'sec-ch-ua-platform': '"Windows"',
|
||||||
"sec-fetch-dest": "document",
|
'sec-fetch-dest': 'document',
|
||||||
"sec-fetch-mode": "navigate",
|
'sec-fetch-mode': 'navigate',
|
||||||
"sec-fetch-site": "none",
|
'sec-fetch-site': 'none',
|
||||||
"sec-fetch-user": "?1",
|
'sec-fetch-user': '?1',
|
||||||
"upgrade-insecure-requests": "1",
|
'upgrade-insecure-requests': '1',
|
||||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
|
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0',
|
||||||
}
|
}
|
||||||
cookies = {"country": "US", "lang": "en"}
|
cookies = {'country': 'US', 'lang': 'en'}
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session, session.get(url, headers=headers, cookies=cookies) as response:
|
||||||
async with session.get(url, headers=headers, cookies=cookies) as response:
|
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
with open(filename, "wb") as f:
|
with open(filename, 'wb') as f:
|
||||||
f.write(await response.read())
|
f.write(await response.read())
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["f"], prefix) & filters.me)
|
@Client.on_message(filters.command(['f'], prefix) & filters.me)
|
||||||
async def random_stiker(client: Client, message: Message):
|
async def random_stiker(client: Client, message: Message):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
random = randint(1, 63)
|
random = randint(1, 63)
|
||||||
index = f"00{random}" if random < 10 else f"0{random}"
|
index = f'00{random}' if random < 10 else f'0{random}'
|
||||||
sticker = (
|
sticker = f'https://www.chpic.su/_data/stickers/f/FforRespect/FforRespect_{index}.webp'
|
||||||
f"https://www.chpic.su/_data/stickers/f/FforRespect/FforRespect_{index}.webp"
|
await download_sticker(sticker, 'f.webp')
|
||||||
)
|
if os.path.exists('f.webp'):
|
||||||
await download_sticker(sticker, "f.webp")
|
|
||||||
if os.path.exists("f.webp"):
|
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
"f.webp",
|
'f.webp',
|
||||||
reply_to_message_id=message.reply_to_message.id
|
reply_to_message_id=message.reply_to_message.id if message.reply_to_message else None,
|
||||||
if message.reply_to_message
|
|
||||||
else None,
|
|
||||||
)
|
)
|
||||||
os.remove("f.webp")
|
os.remove('f.webp')
|
||||||
|
|
||||||
|
|
||||||
modules_help["f"] = {"f": "Send f to pay respect"}
|
modules_help['f'] = {'f': 'Send f to pay respect'}
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
from asyncio import sleep
|
from asyncio import sleep
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.raw import functions
|
from pyrogram.raw import functions
|
||||||
from pyrogram.types import Message, InputReplyToMessage
|
from pyrogram.types import InputReplyToMessage, Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
commands = {
|
commands = {
|
||||||
"ftype": enums.ChatAction.TYPING,
|
'ftype': enums.ChatAction.TYPING,
|
||||||
"faudio": enums.ChatAction.UPLOAD_AUDIO,
|
'faudio': enums.ChatAction.UPLOAD_AUDIO,
|
||||||
"fvideo": enums.ChatAction.UPLOAD_VIDEO,
|
'fvideo': enums.ChatAction.UPLOAD_VIDEO,
|
||||||
"fphoto": enums.ChatAction.UPLOAD_PHOTO,
|
'fphoto': enums.ChatAction.UPLOAD_PHOTO,
|
||||||
"fdocument": enums.ChatAction.UPLOAD_DOCUMENT,
|
'fdocument': enums.ChatAction.UPLOAD_DOCUMENT,
|
||||||
"flocation": enums.ChatAction.FIND_LOCATION,
|
'flocation': enums.ChatAction.FIND_LOCATION,
|
||||||
"frvideo": enums.ChatAction.RECORD_VIDEO,
|
'frvideo': enums.ChatAction.RECORD_VIDEO,
|
||||||
"frvoice": enums.ChatAction.RECORD_AUDIO,
|
'frvoice': enums.ChatAction.RECORD_AUDIO,
|
||||||
"frvideor": enums.ChatAction.RECORD_VIDEO_NOTE,
|
'frvideor': enums.ChatAction.RECORD_VIDEO_NOTE,
|
||||||
"fvideor": enums.ChatAction.UPLOAD_VIDEO_NOTE,
|
'fvideor': enums.ChatAction.UPLOAD_VIDEO_NOTE,
|
||||||
"fgame": enums.ChatAction.PLAYING,
|
'fgame': enums.ChatAction.PLAYING,
|
||||||
"fcontact": enums.ChatAction.CHOOSE_CONTACT,
|
'fcontact': enums.ChatAction.CHOOSE_CONTACT,
|
||||||
"fstop": enums.ChatAction.CANCEL,
|
'fstop': enums.ChatAction.CANCEL,
|
||||||
"fscrn": "screenshot",
|
'fscrn': 'screenshot',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -39,12 +39,10 @@ async def fakeactions_handler(client: Client, message: Message):
|
|||||||
action = commands[cmd]
|
action = commands[cmd]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if action != "screenshot":
|
if action != 'screenshot':
|
||||||
if sec and action != enums.ChatAction.CANCEL:
|
if sec and action != enums.ChatAction.CANCEL:
|
||||||
while sec > 0:
|
while sec > 0:
|
||||||
await client.send_chat_action(
|
await client.send_chat_action(chat_id=message.chat.id, action=action)
|
||||||
chat_id=message.chat.id, action=action
|
|
||||||
)
|
|
||||||
await sleep(1)
|
await sleep(1)
|
||||||
sec -= 1
|
sec -= 1
|
||||||
return await client.send_chat_action(chat_id=message.chat.id, action=action)
|
return await client.send_chat_action(chat_id=message.chat.id, action=action)
|
||||||
@@ -53,36 +51,30 @@ async def fakeactions_handler(client: Client, message: Message):
|
|||||||
await client.invoke(
|
await client.invoke(
|
||||||
functions.messages.SendScreenshotNotification(
|
functions.messages.SendScreenshotNotification(
|
||||||
peer=await client.resolve_peer(message.chat.id),
|
peer=await client.resolve_peer(message.chat.id),
|
||||||
reply_to=InputReplyToMessage(
|
reply_to=InputReplyToMessage(reply_to_message_id=message.reply_to_message.id),
|
||||||
reply_to_message_id=message.reply_to_message.id
|
|
||||||
),
|
|
||||||
random_id=client.rnd_id(),
|
random_id=client.rnd_id(),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
await sleep(0.1)
|
await sleep(0.1)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return await client.send_message(
|
return await client.send_message('me', 'Error in <b>fakeactions</b>reply to message is required')
|
||||||
"me", f"Error in <b>fakeactions</b>" "reply to message is required"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await client.send_message(
|
return await client.send_message('me', 'Error in <b>fakeactions</b> module:\n' + format_exc(e))
|
||||||
"me", f"Error in <b>fakeactions</b>" f" module:\n" + format_exc(e)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
modules_help["fakeactions"] = {
|
modules_help['fakeactions'] = {
|
||||||
"ftype [sec]": "Typing... action",
|
'ftype [sec]': 'Typing... action',
|
||||||
"faudio [sec]": "Sending voice... action",
|
'faudio [sec]': 'Sending voice... action',
|
||||||
"fvideo [sec]": "Sending video... action",
|
'fvideo [sec]': 'Sending video... action',
|
||||||
"fphoto [sec]": "Sending photo... action",
|
'fphoto [sec]': 'Sending photo... action',
|
||||||
"fdocument [sec]": "Sending document... action",
|
'fdocument [sec]': 'Sending document... action',
|
||||||
"flocation [sec]": "Find location... action",
|
'flocation [sec]': 'Find location... action',
|
||||||
"fcontact [sec]": "Sending contact... action",
|
'fcontact [sec]': 'Sending contact... action',
|
||||||
"frvideo [sec]": "Recording video... action",
|
'frvideo [sec]': 'Recording video... action',
|
||||||
"frvoice [sec]": "Recording voice... action",
|
'frvoice [sec]': 'Recording voice... action',
|
||||||
"frvideor [sec]": "Recording round video... action",
|
'frvideor [sec]': 'Recording round video... action',
|
||||||
"fvideor [sec]": "Uploading round video... action",
|
'fvideor [sec]': 'Uploading round video... action',
|
||||||
"fgame [sec]": "Playing game... action",
|
'fgame [sec]': 'Playing game... action',
|
||||||
"fstop": "Stop actions",
|
'fstop': 'Stop actions',
|
||||||
"fscrn [amount] [reply_to_message]*": "Make screenshot action",
|
'fscrn [amount] [reply_to_message]*': 'Make screenshot action',
|
||||||
}
|
}
|
||||||
|
|||||||
+47
-86
@@ -22,18 +22,17 @@ from pyrogram.types import (
|
|||||||
InputMediaVideo,
|
InputMediaVideo,
|
||||||
Message,
|
Message,
|
||||||
)
|
)
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
def get_filters_chat(chat_id):
|
def get_filters_chat(chat_id):
|
||||||
return db.get("core.filters", f"{chat_id}", {})
|
return db.get('core.filters', f'{chat_id}', {})
|
||||||
|
|
||||||
|
|
||||||
def set_filters_chat(chat_id, filters_):
|
def set_filters_chat(chat_id, filters_):
|
||||||
return db.set("core.filters", f"{chat_id}", filters_)
|
return db.set('core.filters', f'{chat_id}', filters_)
|
||||||
|
|
||||||
|
|
||||||
async def contains_filter(_, __, m):
|
async def contains_filter(_, __, m):
|
||||||
@@ -48,21 +47,17 @@ contains = filters.create(contains_filter)
|
|||||||
async def filters_main_handler(client: Client, message: Message):
|
async def filters_main_handler(client: Client, message: Message):
|
||||||
value = get_filters_chat(message.chat.id)[message.text.lower()]
|
value = get_filters_chat(message.chat.id)[message.text.lower()]
|
||||||
try:
|
try:
|
||||||
await client.get_messages(int(value["CHAT_ID"]), int(value["MESSAGE_ID"]))
|
await client.get_messages(int(value['CHAT_ID']), int(value['MESSAGE_ID']))
|
||||||
except errors.RPCError as exc:
|
except errors.RPCError as exc:
|
||||||
raise ContinuePropagation from exc
|
raise ContinuePropagation from exc
|
||||||
|
|
||||||
if value.get("MEDIA_GROUP"):
|
if value.get('MEDIA_GROUP'):
|
||||||
messages_grouped = await client.get_media_group(
|
messages_grouped = await client.get_media_group(int(value['CHAT_ID']), int(value['MESSAGE_ID']))
|
||||||
int(value["CHAT_ID"]), int(value["MESSAGE_ID"])
|
|
||||||
)
|
|
||||||
media_grouped_list = []
|
media_grouped_list = []
|
||||||
for _ in messages_grouped:
|
for _ in messages_grouped:
|
||||||
if _.photo:
|
if _.photo:
|
||||||
if _.caption:
|
if _.caption:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaPhoto(_.photo.file_id, _.caption.HTML))
|
||||||
InputMediaPhoto(_.photo.file_id, _.caption.HTML)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(InputMediaPhoto(_.photo.file_id))
|
media_grouped_list.append(InputMediaPhoto(_.photo.file_id))
|
||||||
elif _.video:
|
elif _.video:
|
||||||
@@ -76,20 +71,14 @@ async def filters_main_handler(client: Client, message: Message):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaVideo(_.video.file_id, _.caption.HTML))
|
||||||
InputMediaVideo(_.video.file_id, _.caption.HTML)
|
|
||||||
)
|
|
||||||
elif _.video.thumbs:
|
elif _.video.thumbs:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaVideo(_.video.file_id, _.video.thumbs[0].file_id))
|
||||||
InputMediaVideo(_.video.file_id, _.video.thumbs[0].file_id)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(InputMediaVideo(_.video.file_id))
|
media_grouped_list.append(InputMediaVideo(_.video.file_id))
|
||||||
elif _.audio:
|
elif _.audio:
|
||||||
if _.caption:
|
if _.caption:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaAudio(_.audio.file_id, _.caption.HTML))
|
||||||
InputMediaAudio(_.audio.file_id, _.caption.HTML)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(InputMediaAudio(_.audio.file_id))
|
media_grouped_list.append(InputMediaAudio(_.audio.file_id))
|
||||||
elif _.document:
|
elif _.document:
|
||||||
@@ -103,77 +92,54 @@ async def filters_main_handler(client: Client, message: Message):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaDocument(_.document.file_id, _.caption.HTML))
|
||||||
InputMediaDocument(_.document.file_id, _.caption.HTML)
|
|
||||||
)
|
|
||||||
elif _.document.thumbs:
|
elif _.document.thumbs:
|
||||||
media_grouped_list.append(
|
media_grouped_list.append(InputMediaDocument(_.document.file_id, _.document.thumbs[0].file_id))
|
||||||
InputMediaDocument(
|
|
||||||
_.document.file_id, _.document.thumbs[0].file_id
|
|
||||||
)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
media_grouped_list.append(InputMediaDocument(_.document.file_id))
|
media_grouped_list.append(InputMediaDocument(_.document.file_id))
|
||||||
await client.send_media_group(
|
await client.send_media_group(message.chat.id, media_grouped_list, reply_to_message_id=message.id)
|
||||||
message.chat.id, media_grouped_list, reply_to_message_id=message.id
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await client.copy_message(
|
await client.copy_message(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
int(value["CHAT_ID"]),
|
int(value['CHAT_ID']),
|
||||||
int(value["MESSAGE_ID"]),
|
int(value['MESSAGE_ID']),
|
||||||
reply_to_message_id=message.id,
|
reply_to_message_id=message.id,
|
||||||
)
|
)
|
||||||
raise ContinuePropagation
|
raise ContinuePropagation
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["filter"], prefix) & filters.me)
|
@Client.on_message(filters.command(['filter'], prefix) & filters.me)
|
||||||
async def filter_handler(client: Client, message: Message):
|
async def filter_handler(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
if len(message.text.split()) < 2:
|
if len(message.text.split()) < 2:
|
||||||
return await message.edit(
|
return await message.edit(f'<b>Usage</b>: <code>{prefix}filter [name] (Reply required)</code>')
|
||||||
f"<b>Usage</b>: <code>{prefix}filter [name] (Reply required)</code>"
|
|
||||||
)
|
|
||||||
name = message.text.split(maxsplit=1)[1].lower()
|
name = message.text.split(maxsplit=1)[1].lower()
|
||||||
chat_filters = get_filters_chat(message.chat.id)
|
chat_filters = get_filters_chat(message.chat.id)
|
||||||
if name in chat_filters.keys():
|
if name in chat_filters.keys():
|
||||||
return await message.edit(
|
return await message.edit(f'<b>Filter</b> <code>{name}</code> already exists.')
|
||||||
f"<b>Filter</b> <code>{name}</code> already exists."
|
|
||||||
)
|
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
return await message.edit("<b>Reply to message</b> please.")
|
return await message.edit('<b>Reply to message</b> please.')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
chat = await client.get_chat(db.get("core.notes", "chat_id", 0))
|
chat = await client.get_chat(db.get('core.notes', 'chat_id', 0))
|
||||||
except (errors.RPCError, ValueError, KeyError):
|
except (errors.RPCError, ValueError, KeyError):
|
||||||
# group is not accessible or isn't created
|
# group is not accessible or isn't created
|
||||||
chat = await client.create_supergroup(
|
chat = await client.create_supergroup('Userbot_Notes_Filters', "Don't touch this group, please")
|
||||||
"Userbot_Notes_Filters", "Don't touch this group, please"
|
db.set('core.notes', 'chat_id', chat.id)
|
||||||
)
|
|
||||||
db.set("core.notes", "chat_id", chat.id)
|
|
||||||
|
|
||||||
chat_id = chat.id
|
chat_id = chat.id
|
||||||
|
|
||||||
if message.reply_to_message.media_group_id:
|
if message.reply_to_message.media_group_id:
|
||||||
get_media_group = [
|
get_media_group = [_.id for _ in await client.get_media_group(message.chat.id, message.reply_to_message.id)]
|
||||||
_.id
|
|
||||||
for _ in await client.get_media_group(
|
|
||||||
message.chat.id, message.reply_to_message.id
|
|
||||||
)
|
|
||||||
]
|
|
||||||
try:
|
try:
|
||||||
message_id = await client.forward_messages(
|
message_id = await client.forward_messages(chat_id, message.chat.id, get_media_group)
|
||||||
chat_id, message.chat.id, get_media_group
|
|
||||||
)
|
|
||||||
except errors.ChatForwardsRestricted:
|
except errors.ChatForwardsRestricted:
|
||||||
await message.edit(
|
await message.edit('<b>Forwarding messages is restricted by chat admins</b>')
|
||||||
"<b>Forwarding messages is restricted by chat admins</b>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
filter_ = {
|
filter_ = {
|
||||||
"MESSAGE_ID": str(message_id[1].id),
|
'MESSAGE_ID': str(message_id[1].id),
|
||||||
"MEDIA_GROUP": True,
|
'MEDIA_GROUP': True,
|
||||||
"CHAT_ID": str(chat_id),
|
'CHAT_ID': str(chat_id),
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
@@ -181,44 +147,42 @@ async def filter_handler(client: Client, message: Message):
|
|||||||
except errors.ChatForwardsRestricted:
|
except errors.ChatForwardsRestricted:
|
||||||
message_id = await message.copy(chat_id)
|
message_id = await message.copy(chat_id)
|
||||||
filter_ = {
|
filter_ = {
|
||||||
"MEDIA_GROUP": False,
|
'MEDIA_GROUP': False,
|
||||||
"MESSAGE_ID": str(message_id.id),
|
'MESSAGE_ID': str(message_id.id),
|
||||||
"CHAT_ID": str(chat_id),
|
'CHAT_ID': str(chat_id),
|
||||||
}
|
}
|
||||||
|
|
||||||
chat_filters.update({name: filter_})
|
chat_filters.update({name: filter_})
|
||||||
|
|
||||||
set_filters_chat(message.chat.id, chat_filters)
|
set_filters_chat(message.chat.id, chat_filters)
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Filter</b> <code>{name}</code> has been added.",
|
f'<b>Filter</b> <code>{name}</code> has been added.',
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.edit(format_exc(e))
|
return await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["filters"], prefix) & filters.me)
|
@Client.on_message(filters.command(['filters'], prefix) & filters.me)
|
||||||
async def filters_handler(_, message: Message):
|
async def filters_handler(_, message: Message):
|
||||||
try:
|
try:
|
||||||
text = ""
|
text = ''
|
||||||
for index, a in enumerate(get_filters_chat(message.chat.id).items(), start=1):
|
for index, a in enumerate(get_filters_chat(message.chat.id).items(), start=1):
|
||||||
key, _ = a
|
key, _ = a
|
||||||
key = key.replace("<", "").replace(">", "")
|
key = key.replace('<', '').replace('>', '')
|
||||||
text += f"{index}. <code>{key}</code>\n"
|
text += f'{index}. <code>{key}</code>\n'
|
||||||
text = f"<b>Your filters in current chat</b>:\n\n" f"{text}"
|
text = f'<b>Your filters in current chat</b>:\n\n{text}'
|
||||||
text = text[:4096]
|
text = text[:4096]
|
||||||
return await message.edit(text)
|
return await message.edit(text)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.edit(format_exc(e))
|
return await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(filters.command(['delfilter', 'filterdel', 'fdel'], prefix) & filters.me)
|
||||||
filters.command(["delfilter", "filterdel", "fdel"], prefix) & filters.me
|
|
||||||
)
|
|
||||||
async def filter_del_handler(_, message: Message):
|
async def filter_del_handler(_, message: Message):
|
||||||
try:
|
try:
|
||||||
if len(message.text.split()) < 2:
|
if len(message.text.split()) < 2:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Usage</b>: <code>{prefix}fdel [name]</code>",
|
f'<b>Usage</b>: <code>{prefix}fdel [name]</code>',
|
||||||
)
|
)
|
||||||
name = message.text.split(maxsplit=1)[1].lower()
|
name = message.text.split(maxsplit=1)[1].lower()
|
||||||
chat_filters = get_filters_chat(message.chat.id)
|
chat_filters = get_filters_chat(message.chat.id)
|
||||||
@@ -229,18 +193,18 @@ async def filter_del_handler(_, message: Message):
|
|||||||
del chat_filters[name]
|
del chat_filters[name]
|
||||||
set_filters_chat(message.chat.id, chat_filters)
|
set_filters_chat(message.chat.id, chat_filters)
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Filter</b> <code>{name}</code> has been deleted.",
|
f'<b>Filter</b> <code>{name}</code> has been deleted.',
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.edit(format_exc(e))
|
return await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["fsearch"], prefix) & filters.me)
|
@Client.on_message(filters.command(['fsearch'], prefix) & filters.me)
|
||||||
async def filter_search_handler(_, message: Message):
|
async def filter_search_handler(_, message: Message):
|
||||||
try:
|
try:
|
||||||
if len(message.text.split()) < 2:
|
if len(message.text.split()) < 2:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Usage</b>: <code>{prefix}fsearch [name]</code>",
|
f'<b>Usage</b>: <code>{prefix}fsearch [name]</code>',
|
||||||
)
|
)
|
||||||
name = message.text.split(maxsplit=1)[1].lower()
|
name = message.text.split(maxsplit=1)[1].lower()
|
||||||
chat_filters = get_filters_chat(message.chat.id)
|
chat_filters = get_filters_chat(message.chat.id)
|
||||||
@@ -248,17 +212,14 @@ async def filter_search_handler(_, message: Message):
|
|||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Filter</b> <code>{name}</code> doesn't exists.",
|
f"<b>Filter</b> <code>{name}</code> doesn't exists.",
|
||||||
)
|
)
|
||||||
return await message.edit(
|
return await message.edit(f'<b>Trigger</b>:\n<code>{name}</code>\n<b>Answer</b>:\n{chat_filters[name]}')
|
||||||
f"<b>Trigger</b>:\n<code>{name}</code"
|
|
||||||
f">\n<b>Answer</b>:\n{chat_filters[name]}"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.edit(format_exc(e))
|
return await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["filters"] = {
|
modules_help['filters'] = {
|
||||||
"filter [name]": "Create filter (Reply required)",
|
'filter [name]': 'Create filter (Reply required)',
|
||||||
"filters": "List of all triggers",
|
'filters': 'List of all triggers',
|
||||||
"fdel [name]": "Delete filter by name",
|
'fdel [name]': 'Delete filter by name',
|
||||||
"fsearch [name]": "Info filter by name",
|
'fsearch [name]': 'Info filter by name',
|
||||||
}
|
}
|
||||||
|
|||||||
+83
-86
@@ -1,98 +1,95 @@
|
|||||||
import asyncio
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.raw import functions
|
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
|
||||||
|
|
||||||
REPLACEMENT_MAP = {
|
REPLACEMENT_MAP = {
|
||||||
"a": "ɐ",
|
'a': 'ɐ',
|
||||||
"b": "q",
|
'b': 'q',
|
||||||
"c": "ɔ",
|
'c': 'ɔ',
|
||||||
"d": "p",
|
'd': 'p',
|
||||||
"e": "ǝ",
|
'e': 'ǝ',
|
||||||
"f": "ɟ",
|
'f': 'ɟ',
|
||||||
"g": "ƃ",
|
'g': 'ƃ',
|
||||||
"h": "ɥ",
|
'h': 'ɥ',
|
||||||
"i": "ᴉ",
|
'i': 'ᴉ',
|
||||||
"j": "ɾ",
|
'j': 'ɾ',
|
||||||
"k": "ʞ",
|
'k': 'ʞ',
|
||||||
"l": "l",
|
'l': 'l',
|
||||||
"m": "ɯ",
|
'm': 'ɯ',
|
||||||
"n": "u",
|
'n': 'u',
|
||||||
"o": "o",
|
'o': 'o',
|
||||||
"p": "d",
|
'p': 'd',
|
||||||
"q": "b",
|
'q': 'b',
|
||||||
"r": "ɹ",
|
'r': 'ɹ',
|
||||||
"s": "s",
|
's': 's',
|
||||||
"t": "ʇ",
|
't': 'ʇ',
|
||||||
"u": "n",
|
'u': 'n',
|
||||||
"v": "ʌ",
|
'v': 'ʌ',
|
||||||
"w": "ʍ",
|
'w': 'ʍ',
|
||||||
"x": "x",
|
'x': 'x',
|
||||||
"y": "ʎ",
|
'y': 'ʎ',
|
||||||
"z": "z",
|
'z': 'z',
|
||||||
"A": "∀",
|
'A': '∀',
|
||||||
"B": "B",
|
'B': 'B',
|
||||||
"C": "Ɔ",
|
'C': 'Ɔ',
|
||||||
"D": "D",
|
'D': 'D',
|
||||||
"E": "Ǝ",
|
'E': 'Ǝ',
|
||||||
"F": "Ⅎ",
|
'F': 'Ⅎ',
|
||||||
"G": "פ",
|
'G': 'פ',
|
||||||
"H": "H",
|
'H': 'H',
|
||||||
"I": "I",
|
'I': 'I',
|
||||||
"J": "ſ",
|
'J': 'ſ',
|
||||||
"K": "K",
|
'K': 'K',
|
||||||
"L": "˥",
|
'L': '˥',
|
||||||
"M": "W",
|
'M': 'W',
|
||||||
"N": "N",
|
'N': 'N',
|
||||||
"O": "O",
|
'O': 'O',
|
||||||
"P": "Ԁ",
|
'P': 'Ԁ',
|
||||||
"Q": "Q",
|
'Q': 'Q',
|
||||||
"R": "R",
|
'R': 'R',
|
||||||
"S": "S",
|
'S': 'S',
|
||||||
"T": "┴",
|
'T': '┴',
|
||||||
"U": "∩",
|
'U': '∩',
|
||||||
"V": "Λ",
|
'V': 'Λ',
|
||||||
"W": "M",
|
'W': 'M',
|
||||||
"X": "X",
|
'X': 'X',
|
||||||
"Y": "⅄",
|
'Y': '⅄',
|
||||||
"Z": "Z",
|
'Z': 'Z',
|
||||||
"0": "0",
|
'0': '0',
|
||||||
"1": "Ɩ",
|
'1': 'Ɩ',
|
||||||
"2": "ᄅ",
|
'2': 'ᄅ',
|
||||||
"3": "Ɛ",
|
'3': 'Ɛ',
|
||||||
"4": "ㄣ",
|
'4': 'ㄣ',
|
||||||
"5": "ϛ",
|
'5': 'ϛ',
|
||||||
"6": "9",
|
'6': '9',
|
||||||
"7": "ㄥ",
|
'7': 'ㄥ',
|
||||||
"8": "8",
|
'8': '8',
|
||||||
"9": "6",
|
'9': '6',
|
||||||
",": "'",
|
',': "'",
|
||||||
".": "˙",
|
'.': '˙',
|
||||||
"?": "¿",
|
'?': '¿',
|
||||||
"!": "¡",
|
'!': '¡',
|
||||||
'"': ",,",
|
'"': ',,',
|
||||||
"'": ",",
|
"'": ',',
|
||||||
"(": ")",
|
'(': ')',
|
||||||
")": "(",
|
')': '(',
|
||||||
"[": "]",
|
'[': ']',
|
||||||
"]": "[",
|
']': '[',
|
||||||
"{": "}",
|
'{': '}',
|
||||||
"}": "{",
|
'}': '{',
|
||||||
"<": ">",
|
'<': '>',
|
||||||
">": "<",
|
'>': '<',
|
||||||
"&": "⅋",
|
'&': '⅋',
|
||||||
"_": "‾",
|
'_': '‾',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("flip", prefix) & filters.me)
|
@Client.on_message(filters.command('flip', prefix) & filters.me)
|
||||||
async def flip(client: Client, message: Message):
|
async def flip(client: Client, message: Message):
|
||||||
text = " ".join(message.command[1:])
|
text = ' '.join(message.command[1:])
|
||||||
final_str = ""
|
final_str = ''
|
||||||
for char in text:
|
for char in text:
|
||||||
if char in REPLACEMENT_MAP.keys():
|
if char in REPLACEMENT_MAP:
|
||||||
new_char = REPLACEMENT_MAP[char]
|
new_char = REPLACEMENT_MAP[char]
|
||||||
else:
|
else:
|
||||||
new_char = char
|
new_char = char
|
||||||
@@ -103,4 +100,4 @@ async def flip(client: Client, message: Message):
|
|||||||
await message.edit(text)
|
await message.edit(text)
|
||||||
|
|
||||||
|
|
||||||
modules_help["fliptext"] = {"flip [amount]*": "flip text upside down"}
|
modules_help['fliptext'] = {'flip [amount]*': 'flip text upside down'}
|
||||||
|
|||||||
+19
-20
@@ -1,52 +1,51 @@
|
|||||||
import os
|
import os
|
||||||
import io
|
|
||||||
import time
|
import time
|
||||||
import requests
|
|
||||||
from pyrogram import filters, Client
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from pyrogram import Client, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, progress
|
from utils.scripts import format_exc, progress
|
||||||
|
|
||||||
|
|
||||||
def schellwithflux(args):
|
def schellwithflux(args):
|
||||||
API_URL = "https://randydev-ryuzaki-api.hf.space/api/v1/akeno/fluxai"
|
API_URL = 'https://randydev-ryuzaki-api.hf.space/api/v1/akeno/fluxai'
|
||||||
payload = {"user_id": 1191668125, "args": args} # Please don't edit here
|
payload = {'user_id': 1191668125, 'args': args} # Please don't edit here
|
||||||
response = requests.post(API_URL, json=payload)
|
response = requests.post(API_URL, json=payload)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
print(f"Error status {response.status_code}")
|
print(f'Error status {response.status_code}')
|
||||||
return None
|
return None
|
||||||
return response.content
|
return response.content
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("fluxai", prefix) & filters.me)
|
@Client.on_message(filters.command('fluxai', prefix) & filters.me)
|
||||||
async def imgfluxai_(client: Client, message: Message):
|
async def imgfluxai_(client: Client, message: Message):
|
||||||
question = message.text.split(" ", 1)[1] if len(message.command) > 1 else None
|
question = message.text.split(' ', 1)[1] if len(message.command) > 1 else None
|
||||||
if not question:
|
if not question:
|
||||||
return await message.reply_text("Please provide a question for Flux.")
|
return await message.reply_text('Please provide a question for Flux.')
|
||||||
try:
|
try:
|
||||||
image_bytes = schellwithflux(question)
|
image_bytes = schellwithflux(question)
|
||||||
if image_bytes is None:
|
if image_bytes is None:
|
||||||
return await message.reply_text("Failed to generate an image.")
|
return await message.reply_text('Failed to generate an image.')
|
||||||
pro = await message.reply_text("Generating image, please wait...")
|
pro = await message.reply_text('Generating image, please wait...')
|
||||||
|
|
||||||
# Write the image bytes directly to a file
|
# Write the image bytes directly to a file
|
||||||
with open("flux_gen.jpg", "wb") as f:
|
with open('flux_gen.jpg', 'wb') as f:
|
||||||
f.write(image_bytes)
|
f.write(image_bytes)
|
||||||
|
|
||||||
ok = await pro.edit_text("Uploading image...")
|
ok = await pro.edit_text('Uploading image...')
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
"flux_gen.jpg",
|
'flux_gen.jpg',
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(ok, time.time(), "Uploading image..."),
|
progress_args=(ok, time.time(), 'Uploading image...'),
|
||||||
)
|
)
|
||||||
await ok.delete()
|
await ok.delete()
|
||||||
if os.path.exists("flux_gen.jpg"):
|
if os.path.exists('flux_gen.jpg'):
|
||||||
os.remove("flux_gen.jpg")
|
os.remove('flux_gen.jpg')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["fluxai"] = {
|
modules_help['fluxai'] = {
|
||||||
"fluxai [prompt]*": "text to image fluxai",
|
'fluxai [prompt]*': 'text to image fluxai',
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-28
@@ -1,72 +1,62 @@
|
|||||||
# This scripts contains use cases for userbots
|
# This scripts contains use cases for userbots
|
||||||
# This is used on my Moon-Userbot: https://github.com/The-MoonTg-project/Moon-Userbot
|
# This is used on my Moon-Userbot: https://github.com/The-MoonTg-project/Moon-Userbot
|
||||||
# YOu can check it out for uses example
|
# YOu can check it out for uses example
|
||||||
import os
|
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageTooLong
|
from pyrogram.errors import MessageTooLong
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
|
||||||
from utils.scripts import format_exc, import_library
|
|
||||||
from utils.config import gemini_key
|
from utils.config import gemini_key
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
from utils.rentry import paste as rentry_paste
|
from utils.rentry import paste as rentry_paste
|
||||||
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
genai = import_library("google.generativeai", "google-generativeai")
|
genai = import_library('google.generativeai', 'google-generativeai')
|
||||||
|
|
||||||
genai.configure(api_key=gemini_key)
|
genai.configure(api_key=gemini_key)
|
||||||
|
|
||||||
model = genai.GenerativeModel("gemini-2.0-flash")
|
model = genai.GenerativeModel('gemini-2.0-flash')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("gemini", prefix) & filters.me)
|
@Client.on_message(filters.command('gemini', prefix) & filters.me)
|
||||||
async def say(client: Client, message: Message):
|
async def say(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
await message.edit_text("<code>Please Wait...</code>")
|
await message.edit_text('<code>Please Wait...</code>')
|
||||||
|
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
prompt = message.text.split(maxsplit=1)[1]
|
prompt = message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
prompt = message.reply_to_message.text
|
prompt = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}gemini [prompt/reply to message]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}gemini [prompt/reply to message]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
chat = model.start_chat()
|
chat = model.start_chat()
|
||||||
response = chat.send_message(prompt)
|
response = chat.send_message(prompt)
|
||||||
|
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"**Question:**`{prompt}`\n**Answer:** {response.text}",
|
f'**Question:**`{prompt}`\n**Answer:** {response.text}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
await message.edit_text(
|
await message.edit_text('<code>Output is too long... Pasting to rentry...</code>')
|
||||||
"<code>Output is too long... Pasting to rentry...</code>"
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
rentry_url, edit_code = await rentry_paste(
|
rentry_url, edit_code = await rentry_paste(text=response.text, return_edit=True)
|
||||||
text=response.text, return_edit=True
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
await message.edit_text(
|
await message.edit_text('<b>Error:</b> <code>Failed to paste to rentry</code>')
|
||||||
"<b>Error:</b> <code>Failed to paste to rentry</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Output:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>",
|
f'<b>Output:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["gemini"] = {
|
modules_help['gemini'] = {
|
||||||
"gemini [prompt]*": "Ask questions with Gemini Ai",
|
'gemini [prompt]*': 'Ask questions with Gemini Ai',
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-15
@@ -16,32 +16,27 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["google", "g"], prefix) & filters.me)
|
@Client.on_message(filters.command(['google', 'g'], prefix) & filters.me)
|
||||||
async def webshot(_, message: Message):
|
async def webshot(_, message: Message):
|
||||||
user_request = " ".join(message.command[1:])
|
user_request = ' '.join(message.command[1:])
|
||||||
|
|
||||||
if user_request == "":
|
if user_request == '':
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
reply_user_request = message.reply_to_message.text
|
reply_user_request = message.reply_to_message.text
|
||||||
request = reply_user_request.replace(" ", "+")
|
request = reply_user_request.replace(' ', '+')
|
||||||
full_request = f"https://lmgtfy.app/?s=g&iie=1&q={request}"
|
full_request = f'https://lmgtfy.app/?s=g&iie=1&q={request}'
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<a href={full_request}>{reply_user_request}</a>",
|
f'<a href={full_request}>{reply_user_request}</a>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
request = user_request.replace(" ", "+")
|
request = user_request.replace(' ', '+')
|
||||||
full_request = f"https://lmgtfy.app/?s=g&iie=1&q={request}"
|
full_request = f'https://lmgtfy.app/?s=g&iie=1&q={request}'
|
||||||
await message.edit(
|
await message.edit(f'<a href={full_request}>{user_request}</a>', disable_web_page_preview=True)
|
||||||
f"<a href={full_request}>{user_request}</a>", disable_web_page_preview=True
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
modules_help["google"] = {
|
modules_help['google'] = {'google [request]': "To teach the interlocutor to use Google. Request isn't required."}
|
||||||
"google [request]": "To teach the interlocutor to use Google. Request isn't required."
|
|
||||||
}
|
|
||||||
|
|||||||
+13
-15
@@ -1,13 +1,13 @@
|
|||||||
import random
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import random
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors.exceptions.flood_420 import FloodWait
|
from pyrogram.errors.exceptions.flood_420 import FloodWait
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
R = "❤️"
|
R = '❤️'
|
||||||
W = "🤍"
|
W = '🤍'
|
||||||
|
|
||||||
heart_list = [
|
heart_list = [
|
||||||
W * 9,
|
W * 9,
|
||||||
@@ -20,7 +20,7 @@ heart_list = [
|
|||||||
W * 4 + R + W * 4,
|
W * 4 + R + W * 4,
|
||||||
W * 9,
|
W * 9,
|
||||||
]
|
]
|
||||||
joined_heart = "\n".join(heart_list)
|
joined_heart = '\n'.join(heart_list)
|
||||||
|
|
||||||
heartlet_len = joined_heart.count(R)
|
heartlet_len = joined_heart.count(R)
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ async def _wrap_edit(message: Message, text: str):
|
|||||||
|
|
||||||
async def phase1(message: Message):
|
async def phase1(message: Message):
|
||||||
"""Big scroll"""
|
"""Big scroll"""
|
||||||
BIG_SCROLL = "🧡💛💚💙💜🖤🤎"
|
BIG_SCROLL = '🧡💛💚💙💜🖤🤎'
|
||||||
await _wrap_edit(message, joined_heart)
|
await _wrap_edit(message, joined_heart)
|
||||||
for heart in BIG_SCROLL:
|
for heart in BIG_SCROLL:
|
||||||
await _wrap_edit(message, joined_heart.replace(R, heart))
|
await _wrap_edit(message, joined_heart.replace(R, heart))
|
||||||
@@ -46,9 +46,9 @@ async def phase1(message: Message):
|
|||||||
|
|
||||||
async def phase2(message: Message):
|
async def phase2(message: Message):
|
||||||
"""Per-heart randomiser"""
|
"""Per-heart randomiser"""
|
||||||
ALL = ["❤️"] + list("🧡💛💚💙💜🤎🖤") # don't include white heart
|
ALL = ['❤️'] + list('🧡💛💚💙💜🤎🖤') # don't include white heart
|
||||||
|
|
||||||
format_heart = joined_heart.replace(R, "{}")
|
format_heart = joined_heart.replace(R, '{}')
|
||||||
for _ in range(5):
|
for _ in range(5):
|
||||||
heart = format_heart.format(*random.choices(ALL, k=heartlet_len))
|
heart = format_heart.format(*random.choices(ALL, k=heartlet_len))
|
||||||
await _wrap_edit(message, heart)
|
await _wrap_edit(message, heart)
|
||||||
@@ -69,12 +69,12 @@ async def phase3(message: Message):
|
|||||||
async def phase4(message: Message):
|
async def phase4(message: Message):
|
||||||
"""Matrix shrinking"""
|
"""Matrix shrinking"""
|
||||||
for i in range(7, 0, -1):
|
for i in range(7, 0, -1):
|
||||||
heart_matrix = "\n".join([R * i] * i)
|
heart_matrix = '\n'.join([R * i] * i)
|
||||||
await _wrap_edit(message, heart_matrix)
|
await _wrap_edit(message, heart_matrix)
|
||||||
await asyncio.sleep(SLEEP)
|
await asyncio.sleep(SLEEP)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("hearts", prefix) & filters.me)
|
@Client.on_message(filters.command('hearts', prefix) & filters.me)
|
||||||
async def hearts(client: Client, message: Message):
|
async def hearts(client: Client, message: Message):
|
||||||
await phase1(message)
|
await phase1(message)
|
||||||
await phase2(message)
|
await phase2(message)
|
||||||
@@ -82,12 +82,10 @@ async def hearts(client: Client, message: Message):
|
|||||||
await phase4(message)
|
await phase4(message)
|
||||||
await asyncio.sleep(SLEEP * 3)
|
await asyncio.sleep(SLEEP * 3)
|
||||||
|
|
||||||
final_caption = " ".join(message.command[1:])
|
final_caption = ' '.join(message.command[1:])
|
||||||
if not final_caption:
|
if not final_caption:
|
||||||
final_caption = "💕 by @moonuserbot"
|
final_caption = '💕 by @moonuserbot'
|
||||||
await message.edit(final_caption)
|
await message.edit(final_caption)
|
||||||
|
|
||||||
|
|
||||||
modules_help["hearts"] = {
|
modules_help['hearts'] = {'hearts': 'Heart animation. May cause floodwaits, use at your own risk!'}
|
||||||
"hearts": "Heart animation. May cause floodwaits, use at your own risk!"
|
|
||||||
}
|
|
||||||
|
|||||||
+21
-23
@@ -13,18 +13,17 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_module_help, with_reply
|
|
||||||
from utils.module import ModuleManager
|
from utils.module import ModuleManager
|
||||||
|
from utils.scripts import format_module_help, with_reply
|
||||||
|
|
||||||
module_manager = ModuleManager.get_instance()
|
module_manager = ModuleManager.get_instance()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["help", "h"], prefix) & filters.me)
|
@Client.on_message(filters.command(['help', 'h'], prefix) & filters.me)
|
||||||
async def help_cmd(_, message: Message):
|
async def help_cmd(_, message: Message):
|
||||||
if not module_manager.help_navigator:
|
if not module_manager.help_navigator:
|
||||||
await message.edit("<b>Help system is not initialized yet. Please wait...</b>")
|
await message.edit('<b>Help system is not initialized yet. Please wait...</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
@@ -41,43 +40,42 @@ async def help_cmd(_, message: Message):
|
|||||||
cmd_desc = commands[command]
|
cmd_desc = commands[command]
|
||||||
module_found = True
|
module_found = True
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Help for command <code>{prefix}{command_name}</code></b>\n"
|
f'<b>Help for command <code>{prefix}{command_name}</code></b>\n'
|
||||||
f"Module: {module_name} (<code>{prefix}help {module_name}</code>)\n\n"
|
f'Module: {module_name} (<code>{prefix}help {module_name}</code>)\n\n'
|
||||||
f"<code>{prefix}{cmd[0]}</code>"
|
f'<code>{prefix}{cmd[0]}</code>'
|
||||||
f"{' <code>' + cmd[1] + '</code>' if len(cmd) > 1 else ''}"
|
f'{" <code>" + cmd[1] + "</code>" if len(cmd) > 1 else ""}'
|
||||||
f" — <i>{cmd_desc}</i>",
|
f' — <i>{cmd_desc}</i>',
|
||||||
)
|
)
|
||||||
if not module_found:
|
if not module_found:
|
||||||
await message.edit(f"<b>Module or command {command_name} not found</b>")
|
await message.edit(f'<b>Module or command {command_name} not found</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["pn", "pp", "pq"], prefix) & filters.me)
|
@Client.on_message(filters.command(['pn', 'pp', 'pq'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def handle_navigation(_, message: Message):
|
async def handle_navigation(_, message: Message):
|
||||||
if not module_manager.help_navigator:
|
if not module_manager.help_navigator:
|
||||||
await message.edit("<b>Help system is not initialized yet. Please wait...</b>")
|
await message.edit('<b>Help system is not initialized yet. Please wait...</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
reply_message = message.reply_to_message
|
reply_message = message.reply_to_message
|
||||||
if reply_message and "Help Page No:" in message.reply_to_message.text:
|
if reply_message and 'Help Page No:' in message.reply_to_message.text:
|
||||||
cmd = message.command[0].lower()
|
cmd = message.command[0].lower()
|
||||||
if cmd == "pn":
|
if cmd == 'pn':
|
||||||
if module_manager.help_navigator.next_page():
|
if module_manager.help_navigator.next_page():
|
||||||
await module_manager.help_navigator.send_page(reply_message)
|
await module_manager.help_navigator.send_page(reply_message)
|
||||||
return await message.delete()
|
return await message.delete()
|
||||||
await message.edit("No more pages available.")
|
await message.edit('No more pages available.')
|
||||||
elif cmd == "pp":
|
elif cmd == 'pp':
|
||||||
if module_manager.help_navigator.prev_page():
|
if module_manager.help_navigator.prev_page():
|
||||||
await module_manager.help_navigator.send_page(reply_message)
|
await module_manager.help_navigator.send_page(reply_message)
|
||||||
return await message.delete()
|
return await message.delete()
|
||||||
return await message.edit("This is the first page.")
|
return await message.edit('This is the first page.')
|
||||||
elif cmd == "pq":
|
elif cmd == 'pq':
|
||||||
await reply_message.delete()
|
await reply_message.delete()
|
||||||
return await message.edit("Help closed.")
|
return await message.edit('Help closed.')
|
||||||
|
|
||||||
|
|
||||||
modules_help["help"] = {
|
modules_help['help'] = {
|
||||||
"help [module/command name]": "Get common/module/command help",
|
'help [module/command name]': 'Get common/module/command help',
|
||||||
"pn/pp/pq": "Navigate through help pages"
|
'pn/pp/pq': 'Navigate through help pages' + ' (pn: next page, pp: previous page, pq: quit help)',
|
||||||
+ " (pn: next page, pp: previous page, pq: quit help)",
|
|
||||||
}
|
}
|
||||||
|
|||||||
+83
-119
@@ -1,16 +1,14 @@
|
|||||||
import os
|
|
||||||
import io
|
|
||||||
import time
|
|
||||||
import aiohttp
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import io
|
||||||
import logging
|
import logging
|
||||||
from PIL import Image
|
import os
|
||||||
|
import time
|
||||||
from pyrogram import filters, Client, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
from PIL import Image
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
@@ -20,47 +18,41 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
async def query_huggingface(payload):
|
async def query_huggingface(payload):
|
||||||
api_key = db.get("custom.hf", "api_key", None)
|
api_key = db.get('custom.hf', 'api_key', None)
|
||||||
model = db.get("custom.hf", "current_model", None)
|
model = db.get('custom.hf', 'current_model', None)
|
||||||
|
|
||||||
if not api_key:
|
if not api_key:
|
||||||
raise ValueError(
|
raise ValueError(f'API key not set. Use {prefix}set_hf api <api_key> to set it.')
|
||||||
f"API key not set. Use {prefix}set_hf api <api_key> to set it."
|
|
||||||
)
|
|
||||||
if not model:
|
if not model:
|
||||||
raise ValueError(
|
raise ValueError(f'Model not set. Use {prefix}set_hf model <model_name> to set it.')
|
||||||
f"Model not set. Use {prefix}set_hf model <model_name> to set it."
|
|
||||||
)
|
|
||||||
|
|
||||||
api_url = f"https://api-inference.huggingface.co/models/{model}"
|
api_url = f'https://api-inference.huggingface.co/models/{model}'
|
||||||
headers = {"Authorization": f"Bearer {api_key}"}
|
headers = {'Authorization': f'Bearer {api_key}'}
|
||||||
timeout = aiohttp.ClientTimeout(total=120)
|
timeout = aiohttp.ClientTimeout(total=120)
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
retries = 3
|
retries = 3
|
||||||
|
|
||||||
for attempt in range(1, retries + 1):
|
for attempt in range(1, retries + 1):
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
async with (
|
||||||
async with session.post(
|
aiohttp.ClientSession(timeout=timeout) as session,
|
||||||
api_url, headers=headers, json=payload
|
session.post(api_url, headers=headers, json=payload) as response,
|
||||||
) as response:
|
):
|
||||||
fetch_time = int((time.time() - start_time) * 1000)
|
fetch_time = int((time.time() - start_time) * 1000)
|
||||||
if response.status != 200:
|
if response.status != 200:
|
||||||
error_text = await response.text()
|
error_text = await response.text()
|
||||||
logger.error(f"API Error {response.status}: {error_text}")
|
logger.error(f'API Error {response.status}: {error_text}')
|
||||||
return None, fetch_time
|
return None, fetch_time
|
||||||
return await response.read(), fetch_time
|
return await response.read(), fetch_time
|
||||||
except asyncio.TimeoutError:
|
except TimeoutError:
|
||||||
logger.error(f"TimeoutError: Attempt {attempt}/{retries} timed out.")
|
logger.error(f'TimeoutError: Attempt {attempt}/{retries} timed out.')
|
||||||
if attempt == retries:
|
if attempt == retries:
|
||||||
raise
|
raise
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
logger.error(
|
logger.error('Request was cancelled. Ensure the task is not being forcefully terminated.')
|
||||||
"Request was cancelled. Ensure the task is not being forcefully terminated."
|
|
||||||
)
|
|
||||||
raise
|
raise
|
||||||
except aiohttp.ClientError as e:
|
except aiohttp.ClientError as e:
|
||||||
logger.error(f"Network Error: {e}")
|
logger.error(f'Network Error: {e}')
|
||||||
if attempt == retries:
|
if attempt == retries:
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
@@ -70,157 +62,129 @@ async def query_huggingface(payload):
|
|||||||
async def save_image(image_bytes, path):
|
async def save_image(image_bytes, path):
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
with ThreadPoolExecutor() as pool:
|
with ThreadPoolExecutor() as pool:
|
||||||
await loop.run_in_executor(
|
await loop.run_in_executor(pool, lambda: Image.open(io.BytesIO(image_bytes)).save(path))
|
||||||
pool, lambda: Image.open(io.BytesIO(image_bytes)).save(path)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["set_hf"], prefix) & filters.me)
|
@Client.on_message(filters.command(['set_hf'], prefix) & filters.me)
|
||||||
async def manage_huggingface(_, message: Message):
|
async def manage_huggingface(_, message: Message):
|
||||||
"""Manage Hugging Face API key and models."""
|
"""Manage Hugging Face API key and models."""
|
||||||
subcommand = message.command[1].lower() if len(message.command) > 1 else None
|
subcommand = message.command[1].lower() if len(message.command) > 1 else None
|
||||||
arg = message.command[2] if len(message.command) > 2 else None
|
arg = message.command[2] if len(message.command) > 2 else None
|
||||||
|
|
||||||
if subcommand == "api":
|
if subcommand == 'api':
|
||||||
if arg:
|
if arg:
|
||||||
db.set("custom.hf", "api_key", arg)
|
db.set('custom.hf', 'api_key', arg)
|
||||||
return await message.edit_text(
|
return await message.edit_text(f'Hugging Face API key set successfully.\nAPI Key: {arg}')
|
||||||
f"Hugging Face API key set successfully.\nAPI Key: {arg}"
|
return await message.edit_text(f'Usage: {prefix}hf api <api_key>')
|
||||||
)
|
|
||||||
return await message.edit_text(f"Usage: {prefix}hf api <api_key>")
|
|
||||||
|
|
||||||
if subcommand == "model":
|
if subcommand == 'model':
|
||||||
if arg:
|
if arg:
|
||||||
models = db.get("custom.hf", "models", [])
|
models = db.get('custom.hf', 'models', [])
|
||||||
if arg not in models:
|
if arg not in models:
|
||||||
models.append(arg)
|
models.append(arg)
|
||||||
db.set("custom.hf", "models", models)
|
db.set('custom.hf', 'models', models)
|
||||||
db.set("custom.hf", "current_model", arg)
|
db.set('custom.hf', 'current_model', arg)
|
||||||
return await message.edit_text(
|
return await message.edit_text(f"Model '{arg}' added and set as the current model.")
|
||||||
f"Model '{arg}' added and set as the current model."
|
return await message.edit_text(f'Usage: {prefix}hf model <model_name>')
|
||||||
)
|
|
||||||
return await message.edit_text(f"Usage: {prefix}hf model <model_name>")
|
|
||||||
|
|
||||||
if subcommand == "select":
|
if subcommand == 'select':
|
||||||
models = db.get("custom.hf", "models", [])
|
models = db.get('custom.hf', 'models', [])
|
||||||
if arg and arg.lower() == "all":
|
if arg and arg.lower() == 'all':
|
||||||
db.set("custom.hf", "current_model", "all")
|
db.set('custom.hf', 'current_model', 'all')
|
||||||
model_list = "\n".join([f"*{i + 1}. {m}" for i, m in enumerate(models)])
|
model_list = '\n'.join([f'*{i + 1}. {m}' for i, m in enumerate(models)])
|
||||||
return await message.edit_text(
|
return await message.edit_text(
|
||||||
f"All models selected:\n<code>{model_list}</code>\n\n"
|
f'All models selected:\n<code>{model_list}</code>\n\nImages will be generated from all models.'
|
||||||
f"Images will be generated from all models."
|
|
||||||
)
|
)
|
||||||
if arg:
|
if arg:
|
||||||
try:
|
try:
|
||||||
index = int(arg) - 1
|
index = int(arg) - 1
|
||||||
if 0 <= index < len(models):
|
if 0 <= index < len(models):
|
||||||
db.set("custom.hf", "current_model", models[index])
|
db.set('custom.hf', 'current_model', models[index])
|
||||||
return await message.edit_text(f"Model set to '{models[index]}'.")
|
return await message.edit_text(f"Model set to '{models[index]}'.")
|
||||||
return await message.edit_text("Invalid model number.")
|
return await message.edit_text('Invalid model number.')
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return await message.edit_text(
|
return await message.edit_text('Invalid model number. Use a valid integer.')
|
||||||
"Invalid model number. Use a valid integer."
|
return await message.edit_text(f'Usage: {prefix}hf select <model_number|all>')
|
||||||
)
|
|
||||||
return await message.edit_text(f"Usage: {prefix}hf select <model_number|all>")
|
|
||||||
|
|
||||||
if subcommand == "delete" and arg:
|
if subcommand == 'delete' and arg:
|
||||||
try:
|
try:
|
||||||
index = int(arg) - 1
|
index = int(arg) - 1
|
||||||
models = db.get("custom.hf", "models", [])
|
models = db.get('custom.hf', 'models', [])
|
||||||
if 0 <= index < len(models):
|
if 0 <= index < len(models):
|
||||||
removed_model = models.pop(index)
|
removed_model = models.pop(index)
|
||||||
db.set("custom.hf", "models", models)
|
db.set('custom.hf', 'models', models)
|
||||||
if db.get("custom.hf", "current_model") == removed_model:
|
if db.get('custom.hf', 'current_model') == removed_model:
|
||||||
db.set(
|
db.set('custom.hf', 'current_model', models[0] if models else 'None')
|
||||||
"custom.hf", "current_model", models[0] if models else "None"
|
|
||||||
)
|
|
||||||
return await message.edit_text(f"Model '{removed_model}' deleted.")
|
return await message.edit_text(f"Model '{removed_model}' deleted.")
|
||||||
return await message.edit_text("Invalid model number.")
|
return await message.edit_text('Invalid model number.')
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return await message.edit_text("Invalid model number. Use a valid integer.")
|
return await message.edit_text('Invalid model number. Use a valid integer.')
|
||||||
|
|
||||||
api_key = db.get("custom.hf", "api_key", None)
|
api_key = db.get('custom.hf', 'api_key', None)
|
||||||
models = db.get("custom.hf", "models", [])
|
models = db.get('custom.hf', 'models', [])
|
||||||
current_model = db.get("custom.hf", "current_model", "Not set")
|
current_model = db.get('custom.hf', 'current_model', 'Not set')
|
||||||
model_list = "\n".join(
|
model_list = '\n'.join(
|
||||||
[
|
[f'{"*" if m == current_model or current_model == "all" else ""}{i + 1}. {m}' for i, m in enumerate(models)]
|
||||||
f"{'*' if m == current_model or current_model == 'all' else ''}{i + 1}. {m}"
|
|
||||||
for i, m in enumerate(models)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
settings = (
|
settings = (
|
||||||
f"<b>Hugging Face settings:</b>\n"
|
f'<b>Hugging Face settings:</b>\n'
|
||||||
f"<b>API Key:</b>\n<code>{api_key if api_key else 'Not set'}</code>\n\n"
|
f'<b>API Key:</b>\n<code>{api_key if api_key else "Not set"}</code>\n\n'
|
||||||
f"<b>Available Models:</b>\n<code>{model_list}</code>"
|
f'<b>Available Models:</b>\n<code>{model_list}</code>'
|
||||||
)
|
)
|
||||||
usage_message = (
|
usage_message = (
|
||||||
f"{settings}\n\n<b>Usage:</b>\n"
|
f'{settings}\n\n<b>Usage:</b>\n'
|
||||||
f"<code>{prefix}set_hf</code> <code>api</code>, <code>model</code>, <code>select</code>, <code>delete</code>, <code>select all</code>"
|
f'<code>{prefix}set_hf</code> <code>api</code>, <code>model</code>, <code>select</code>, <code>delete</code>, <code>select all</code>'
|
||||||
)
|
)
|
||||||
await message.edit_text(usage_message)
|
await message.edit_text(usage_message)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["hf", "hface", "huggingface"], prefix))
|
@Client.on_message(filters.command(['hf', 'hface', 'huggingface'], prefix))
|
||||||
async def imgflux_(_, message: Message):
|
async def imgflux_(_, message: Message):
|
||||||
prompt = message.text.split(" ", 1)[1] if len(message.command) > 1 else None
|
prompt = message.text.split(' ', 1)[1] if len(message.command) > 1 else None
|
||||||
if not prompt:
|
if not prompt:
|
||||||
usage_message = (
|
usage_message = f'<b>Usage:</b> <code>{prefix}{message.command[0]} [custom prompt]</code>'
|
||||||
f"<b>Usage:</b> <code>{prefix}{message.command[0]} [custom prompt]</code>"
|
return await (message.edit_text if message.from_user.is_self else message.reply_text)(usage_message)
|
||||||
)
|
|
||||||
return await (
|
|
||||||
message.edit_text if message.from_user.is_self else message.reply_text
|
|
||||||
)(usage_message)
|
|
||||||
|
|
||||||
processing_message = await (
|
processing_message = await (message.edit_text if message.from_user.is_self else message.reply_text)('Processing...')
|
||||||
message.edit_text if message.from_user.is_self else message.reply_text
|
|
||||||
)("Processing...")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
current_model = db.get("custom.hf", "current_model", None)
|
current_model = db.get('custom.hf', 'current_model', None)
|
||||||
models = db.get("custom.hf", "models", [])
|
models = db.get('custom.hf', 'models', [])
|
||||||
models_to_use = models if current_model == "all" else [current_model]
|
models_to_use = models if current_model == 'all' else [current_model]
|
||||||
|
|
||||||
generated_images = []
|
generated_images = []
|
||||||
|
|
||||||
for model in models_to_use:
|
for model in models_to_use:
|
||||||
db.set("custom.hf", "current_model", model)
|
db.set('custom.hf', 'current_model', model)
|
||||||
payload = {"inputs": prompt}
|
payload = {'inputs': prompt}
|
||||||
image_bytes, fetch_time = await query_huggingface(payload)
|
image_bytes, fetch_time = await query_huggingface(payload)
|
||||||
if not image_bytes:
|
if not image_bytes:
|
||||||
logger.warning(f"Failed to fetch image for model: {model}")
|
logger.warning(f'Failed to fetch image for model: {model}')
|
||||||
continue
|
continue
|
||||||
|
|
||||||
image_path = f"hf_flux_gen_{model.replace('/', '_')}.jpg"
|
image_path = f'hf_flux_gen_{model.replace("/", "_")}.jpg'
|
||||||
await save_image(image_bytes, image_path)
|
await save_image(image_bytes, image_path)
|
||||||
generated_images.append((image_path, model, fetch_time))
|
generated_images.append((image_path, model, fetch_time))
|
||||||
|
|
||||||
if not generated_images:
|
if not generated_images:
|
||||||
return await processing_message.edit_text(
|
return await processing_message.edit_text('Failed to generate an image for all models.')
|
||||||
"Failed to generate an image for all models."
|
|
||||||
)
|
|
||||||
|
|
||||||
for image_path, model_name, fetch_time in generated_images:
|
for image_path, model_name, fetch_time in generated_images:
|
||||||
caption = (
|
caption = f'**Model:**\n> {model_name}\n**Prompt used:**\n> {prompt}\n\n**Fetching Time:** {fetch_time} ms'
|
||||||
f"**Model:**\n> {model_name}\n"
|
await message.reply_photo(image_path, caption=caption, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"**Prompt used:**\n> {prompt}\n\n"
|
|
||||||
f"**Fetching Time:** {fetch_time} ms"
|
|
||||||
)
|
|
||||||
await message.reply_photo(
|
|
||||||
image_path, caption=caption, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
os.remove(image_path)
|
os.remove(image_path)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Unexpected Error: {e}")
|
logger.error(f'Unexpected Error: {e}')
|
||||||
await processing_message.edit_text(format_exc(e))
|
await processing_message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
await processing_message.delete()
|
await processing_message.delete()
|
||||||
|
|
||||||
|
|
||||||
modules_help["huggingface"] = {
|
modules_help['huggingface'] = {
|
||||||
"hf [prompt]*": "Generate an AI image using Hugging Face model(s).",
|
'hf [prompt]*': 'Generate an AI image using Hugging Face model(s).',
|
||||||
"set_hf <api>*": "Set the Hugging Face API key.",
|
'set_hf <api>*': 'Set the Hugging Face API key.',
|
||||||
"set_hf model <model_name>*": "Add and set a Hugging Face model.",
|
'set_hf model <model_name>*': 'Add and set a Hugging Face model.',
|
||||||
"set_hf select <model_number|all>*": "Select a specific model or all models for use.",
|
'set_hf select <model_number|all>*': 'Select a specific model or all models for use.',
|
||||||
"set_hf delete <model_number>*": "Delete a model from the list.",
|
'set_hf delete <model_number>*': 'Delete a model from the list.',
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-26
@@ -16,73 +16,72 @@
|
|||||||
|
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message, MessageOriginHiddenUser
|
from pyrogram.types import Message, MessageOriginHiddenUser
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("id", prefix) & filters.me)
|
@Client.on_message(filters.command('id', prefix) & filters.me)
|
||||||
async def ids(_, message: Message):
|
async def ids(_, message: Message):
|
||||||
text = "\n".join(
|
text = '\n'.join(
|
||||||
[
|
[
|
||||||
f"Chat ID: `{message.chat.id}`",
|
f'Chat ID: `{message.chat.id}`',
|
||||||
f"Chat DC ID: `{message.chat.dc_id}`\n",
|
f'Chat DC ID: `{message.chat.dc_id}`\n',
|
||||||
f"Message ID: `{message.id}`",
|
f'Message ID: `{message.id}`',
|
||||||
(
|
(
|
||||||
f"Your ID: `{message.from_user.id}`"
|
f'Your ID: `{message.from_user.id}`'
|
||||||
if message.from_user
|
if message.from_user
|
||||||
else f"Channel/Group ID: `{message.sender_chat.id}`"
|
else f'Channel/Group ID: `{message.sender_chat.id}`'
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
f"Your DC ID: `{message.from_user.dc_id}`"
|
f'Your DC ID: `{message.from_user.dc_id}`'
|
||||||
if message.from_user
|
if message.from_user
|
||||||
else f"Channel/Group ID: `{message.sender_chat.id}`"
|
else f'Channel/Group ID: `{message.sender_chat.id}`'
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
if rtm := message.reply_to_message:
|
if rtm := message.reply_to_message:
|
||||||
# print(rtm)
|
# print(rtm)
|
||||||
text += f"\n\nReplied Message ID: `{rtm.id}`"
|
text += f'\n\nReplied Message ID: `{rtm.id}`'
|
||||||
|
|
||||||
if user := rtm.from_user:
|
if user := rtm.from_user:
|
||||||
text = "\n".join(
|
text = '\n'.join(
|
||||||
[
|
[
|
||||||
text,
|
text,
|
||||||
f"Replied User ID: `{user.id}`",
|
f'Replied User ID: `{user.id}`',
|
||||||
f"Replied User DC ID: `{user.dc_id}`",
|
f'Replied User DC ID: `{user.dc_id}`',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
text = "\n".join(
|
text = '\n'.join(
|
||||||
[
|
[
|
||||||
text,
|
text,
|
||||||
f"Replied Chat ID: `{rtm.sender_chat.id}`",
|
f'Replied Chat ID: `{rtm.sender_chat.id}`',
|
||||||
f"Replied Chat DC ID: `{rtm.sender_chat.dc_id}`",
|
f'Replied Chat DC ID: `{rtm.sender_chat.dc_id}`',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
if rtm.forward_origin and rtm.forward_origin.date:
|
if rtm.forward_origin and rtm.forward_origin.date:
|
||||||
if isinstance(rtm.forward_origin, MessageOriginHiddenUser):
|
if isinstance(rtm.forward_origin, MessageOriginHiddenUser):
|
||||||
text = "\n".join(
|
text = '\n'.join(
|
||||||
[
|
[
|
||||||
text,
|
text,
|
||||||
"\nForwarded from a hidden user.",
|
'\nForwarded from a hidden user.',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
elif ffc := rtm.forward_origin.sender_user:
|
elif ffc := rtm.forward_origin.sender_user:
|
||||||
text = "\n".join(
|
text = '\n'.join(
|
||||||
[
|
[
|
||||||
text,
|
text,
|
||||||
f"\nForwarded Message ID: `{getattr(rtm.forward_origin, 'message_id', None)}`",
|
f'\nForwarded Message ID: `{getattr(rtm.forward_origin, "message_id", None)}`',
|
||||||
f"Forwarded from Chat ID: `{ffc.id}`",
|
f'Forwarded from Chat ID: `{ffc.id}`',
|
||||||
f"Forwarded from Chat DC ID: `{ffc.dc_id}`",
|
f'Forwarded from Chat DC ID: `{ffc.dc_id}`',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
await message.edit("**__" + text + "__**", parse_mode=enums.ParseMode.MARKDOWN)
|
await message.edit('**__' + text + '__**', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
|
||||||
modules_help["id"] = {
|
modules_help['id'] = {
|
||||||
"id": "simply run or reply to message",
|
'id': 'simply run or reply to message',
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-18
@@ -1,16 +1,14 @@
|
|||||||
import asyncio
|
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.raw import functions
|
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("joindate", prefix) & filters.me)
|
@Client.on_message(filters.command('joindate', prefix) & filters.me)
|
||||||
async def joindate(client: Client, message: Message):
|
async def joindate(client: Client, message: Message):
|
||||||
await message.edit(f"<b>One moment...</b>")
|
await message.edit('<b>One moment...</b>')
|
||||||
members = []
|
members = []
|
||||||
cgetmsg = await client.get_messages(message.chat.id, 1)
|
cgetmsg = await client.get_messages(message.chat.id, 1)
|
||||||
async for m in client.iter_chat_members(message.chat.id):
|
async for m in client.iter_chat_members(message.chat.id):
|
||||||
@@ -23,22 +21,16 @@ async def joindate(client: Client, message: Message):
|
|||||||
|
|
||||||
members.sort(key=lambda member: member[1])
|
members.sort(key=lambda member: member[1])
|
||||||
|
|
||||||
with open("joined_date.txt", "w", encoding="utf8") as f:
|
with open('joined_date.txt', 'w', encoding='utf8') as f:
|
||||||
f.write("Join Date First Name\n")
|
f.write('Join Date First Name\n')
|
||||||
for member in members:
|
for member in members:
|
||||||
f.write(
|
f.write(str(datetime.fromtimestamp(member[1]).strftime('%y-%m-%d %H:%M')) + f' {member[0]}\n')
|
||||||
str(datetime.fromtimestamp(member[1]).strftime("%y-%m-%d %H:%M"))
|
|
||||||
+ f" {member[0]}\n"
|
|
||||||
)
|
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_document(message.chat.id, "joined_date.txt")
|
await client.send_document(message.chat.id, 'joined_date.txt')
|
||||||
os.remove("joined_date.txt")
|
os.remove('joined_date.txt')
|
||||||
|
|
||||||
|
|
||||||
|
modules_help['joindate'] = {
|
||||||
modules_help["joindate"] = {
|
'joindate': 'Get a list of all chat members and sort them by the date they joined the group'
|
||||||
"joindate": "Get a list of all chat members and sort them by the date they joined the group"
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
|
import asyncio
|
||||||
|
import random
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
import asyncio, random
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("kokodrilo", prefix) & filters.me)
|
@Client.on_message(filters.command('kokodrilo', prefix) & filters.me)
|
||||||
async def kokodrilo_explodando(_, message: Message):
|
async def kokodrilo_explodando(_, message: Message):
|
||||||
amount = 1
|
amount = 1
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
amount = int(message.command[1])
|
amount = int(message.command[1])
|
||||||
for _ in range(amount):
|
for _ in range(amount):
|
||||||
await message.edit("🐊")
|
await message.edit('🐊')
|
||||||
await asyncio.sleep(random.uniform(1, 2.5))
|
await asyncio.sleep(random.uniform(1, 2.5))
|
||||||
await message.edit("💥")
|
await message.edit('💥')
|
||||||
await asyncio.sleep(1.8)
|
await asyncio.sleep(1.8)
|
||||||
|
|
||||||
|
|
||||||
modules_help["kokodrilo_explodando"] = {
|
modules_help['kokodrilo_explodando'] = {
|
||||||
"kokodrilo [number of explosions]": "<b>kOkOdRiLo ExPlOrAdO</b>",
|
'kokodrilo [number of explosions]': '<b>kOkOdRiLo ExPlOrAdO</b>',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,20 +18,19 @@ import asyncio
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["leave_chat", "lc"], prefix) & filters.me)
|
@Client.on_message(filters.command(['leave_chat', 'lc'], prefix) & filters.me)
|
||||||
async def leave_chat(_, message: Message):
|
async def leave_chat(_, message: Message):
|
||||||
if message.chat.type != "private":
|
if message.chat.type != 'private':
|
||||||
await message.edit("<b>Goodbye...</b>")
|
await message.edit('<b>Goodbye...</b>')
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
await message.chat.leave()
|
await message.chat.leave()
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Not supported in private chats</b>")
|
await message.edit('<b>Not supported in private chats</b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["leave_chat"] = {
|
modules_help['leave_chat'] = {
|
||||||
"leave_chat": "Quit chat",
|
'leave_chat': 'Quit chat',
|
||||||
}
|
}
|
||||||
|
|||||||
+131
-153
@@ -23,318 +23,296 @@ import sys
|
|||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import restart
|
from utils.scripts import restart
|
||||||
from utils.db import db
|
|
||||||
|
|
||||||
|
|
||||||
BASE_PATH = os.path.abspath(os.getcwd())
|
BASE_PATH = os.path.abspath(os.getcwd())
|
||||||
CATEGORIES = [
|
CATEGORIES = [
|
||||||
"ai",
|
'ai',
|
||||||
"dl",
|
'dl',
|
||||||
"admin",
|
'admin',
|
||||||
"anime",
|
'anime',
|
||||||
"fun",
|
'fun',
|
||||||
"images",
|
'images',
|
||||||
"info",
|
'info',
|
||||||
"misc",
|
'misc',
|
||||||
"music",
|
'music',
|
||||||
"news",
|
'news',
|
||||||
"paste",
|
'paste',
|
||||||
"rev",
|
'rev',
|
||||||
"tts",
|
'tts',
|
||||||
"utils",
|
'utils',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["modhash", "mh"], prefix) & filters.me)
|
@Client.on_message(filters.command(['modhash', 'mh'], prefix) & filters.me)
|
||||||
async def get_mod_hash(_, message: Message):
|
async def get_mod_hash(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
return
|
return
|
||||||
url = message.command[1].lower()
|
url = message.command[1].lower()
|
||||||
resp = requests.get(url)
|
resp = requests.get(url)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
await message.edit(
|
await message.edit(f'<b>Troubleshooting with downloading module <code>{url}</code></b>')
|
||||||
f"<b>Troubleshooting with downloading module <code>{url}</code></b>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Module hash: <code>{hashlib.sha256(resp.content).hexdigest()}</code>\n"
|
f'<b>Module hash: <code>{hashlib.sha256(resp.content).hexdigest()}</code>\n'
|
||||||
f"Link: <code>{url}</code>\nFile: <code>{url.split('/')[-1]}</code></b>",
|
f'Link: <code>{url}</code>\nFile: <code>{url.split("/")[-1]}</code></b>',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["loadmod", "lm"], prefix) & filters.me)
|
@Client.on_message(filters.command(['loadmod', 'lm'], prefix) & filters.me)
|
||||||
async def loadmod(_, message: Message):
|
async def loadmod(_, message: Message):
|
||||||
if (
|
if (
|
||||||
not (
|
not (
|
||||||
message.reply_to_message
|
message.reply_to_message
|
||||||
and message.reply_to_message.document
|
and message.reply_to_message.document
|
||||||
and message.reply_to_message.document.file_name.endswith(".py")
|
and message.reply_to_message.document.file_name.endswith('.py')
|
||||||
)
|
)
|
||||||
and len(message.command) == 1
|
and len(message.command) == 1
|
||||||
):
|
):
|
||||||
await message.edit("<b>Specify module to download</b>")
|
await message.edit('<b>Specify module to download</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
await message.edit("<b>Fetching module...</b>")
|
await message.edit('<b>Fetching module...</b>')
|
||||||
url = message.command[1].lower()
|
url = message.command[1].lower()
|
||||||
|
|
||||||
if url.startswith(
|
if url.startswith('https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/'):
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/"
|
module_name = url.split('/')[-1].split('.')[0]
|
||||||
):
|
elif '.' not in url:
|
||||||
module_name = url.split("/")[-1].split(".")[0]
|
|
||||||
elif "." not in url:
|
|
||||||
module_name = url.lower()
|
module_name = url.lower()
|
||||||
try:
|
try:
|
||||||
f = requests.get(
|
f = requests.get(
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt"
|
'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt'
|
||||||
).text
|
).text
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit("Failed to fetch custom modules list")
|
return await message.edit('Failed to fetch custom modules list')
|
||||||
modules_dict = {line.split("/")[-1].split()[0]: line.strip() for line in f.splitlines()}
|
modules_dict = {line.split('/')[-1].split()[0]: line.strip() for line in f.splitlines()}
|
||||||
if module_name in modules_dict:
|
if module_name in modules_dict:
|
||||||
url = f"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py"
|
url = f'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py'
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Module <code>{module_name}</code> is not found</b>')
|
||||||
f"<b>Module <code>{module_name}</code> is not found</b>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
modules_hashes = requests.get(
|
modules_hashes = requests.get(
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/modules_hashes.txt"
|
'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/modules_hashes.txt'
|
||||||
).text
|
).text
|
||||||
resp = requests.get(url)
|
resp = requests.get(url)
|
||||||
|
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Troubleshooting with downloading module <code>{url}</code></b>",
|
f'<b>Troubleshooting with downloading module <code>{url}</code></b>',
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if hashlib.sha256(resp.content).hexdigest() not in modules_hashes:
|
if hashlib.sha256(resp.content).hexdigest() not in modules_hashes:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Only <a href=https://github.com/The-MoonTg-project/custom_modules/tree/main/modules_hashes.txt>"
|
'<b>Only <a href=https://github.com/The-MoonTg-project/custom_modules/tree/main/modules_hashes.txt>'
|
||||||
"verified</a> modules or from the official "
|
'verified</a> modules or from the official '
|
||||||
"<a href=https://github.com/The-MoonTg-project/custom_modules>"
|
'<a href=https://github.com/The-MoonTg-project/custom_modules>'
|
||||||
"custom_modules</a> repository are supported!</b>",
|
'custom_modules</a> repository are supported!</b>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
module_name = url.split("/")[-1].split(".")[0]
|
module_name = url.split('/')[-1].split('.')[0]
|
||||||
|
|
||||||
resp = requests.get(url)
|
resp = requests.get(url)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
await message.edit(f"<b>Module <code>{module_name}</code> is not found</b>")
|
await message.edit(f'<b>Module <code>{module_name}</code> is not found</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
|
if not os.path.exists(f'{BASE_PATH}/modules/custom_modules'):
|
||||||
os.mkdir(f"{BASE_PATH}/modules/custom_modules")
|
os.mkdir(f'{BASE_PATH}/modules/custom_modules')
|
||||||
|
|
||||||
with open(f"./modules/custom_modules/{module_name}.py", "wb") as f:
|
with open(f'./modules/custom_modules/{module_name}.py', 'wb') as f:
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
else:
|
else:
|
||||||
file_name = await message.reply_to_message.download()
|
file_name = await message.reply_to_message.download()
|
||||||
module_name = message.reply_to_message.document.file_name[:-3]
|
module_name = message.reply_to_message.document.file_name[:-3]
|
||||||
|
|
||||||
with open(file_name, "rb") as f:
|
with open(file_name, 'rb') as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
modules_hashes = requests.get(
|
modules_hashes = requests.get(
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/modules_hashes.txt"
|
'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/modules_hashes.txt'
|
||||||
).text
|
).text
|
||||||
|
|
||||||
if hashlib.sha256(content).hexdigest() not in modules_hashes:
|
if hashlib.sha256(content).hexdigest() not in modules_hashes:
|
||||||
os.remove(file_name)
|
os.remove(file_name)
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Only <a href=https://github.com/The-MoonTg-project/custom_modules/tree/main/modules_hashes.txt>"
|
'<b>Only <a href=https://github.com/The-MoonTg-project/custom_modules/tree/main/modules_hashes.txt>'
|
||||||
"verified</a> modules or from the official "
|
'verified</a> modules or from the official '
|
||||||
"<a href=https://github.com/The-MoonTg-project/custom_modules>"
|
'<a href=https://github.com/The-MoonTg-project/custom_modules>'
|
||||||
"custom_modules</a> repository are supported!</b>",
|
'custom_modules</a> repository are supported!</b>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
os.rename(file_name, f"./modules/custom_modules/{module_name}.py")
|
os.rename(file_name, f'./modules/custom_modules/{module_name}.py')
|
||||||
|
|
||||||
all_modules = db.get("custom.modules", "allModules", [])
|
all_modules = db.get('custom.modules', 'allModules', [])
|
||||||
if module_name not in all_modules:
|
if module_name not in all_modules:
|
||||||
all_modules.append(module_name)
|
all_modules.append(module_name)
|
||||||
db.set("custom.modules", "allModules", all_modules)
|
db.set('custom.modules', 'allModules', all_modules)
|
||||||
await message.edit(
|
await message.edit(f'<b>The module <code>{module_name}</code> is loaded!\nRestarting...</b>')
|
||||||
f"<b>The module <code>{module_name}</code> is loaded!\nRestarting...</b>"
|
|
||||||
)
|
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["unloadmod", "ulm"], prefix) & filters.me)
|
@Client.on_message(filters.command(['unloadmod', 'ulm'], prefix) & filters.me)
|
||||||
async def unload_mods(_, message: Message):
|
async def unload_mods(_, message: Message):
|
||||||
if len(message.command) <= 1:
|
if len(message.command) <= 1:
|
||||||
return
|
return
|
||||||
|
|
||||||
module_name = message.command[1].lower()
|
module_name = message.command[1].lower()
|
||||||
|
|
||||||
if module_name.startswith(
|
if module_name.startswith('https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/'):
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/"
|
module_name = module_name.split('/')[-1].split('.')[0]
|
||||||
):
|
|
||||||
module_name = module_name.split("/")[-1].split(".")[0]
|
|
||||||
|
|
||||||
if os.path.exists(f"{BASE_PATH}/modules/custom_modules/{module_name}.py"):
|
if os.path.exists(f'{BASE_PATH}/modules/custom_modules/{module_name}.py'):
|
||||||
os.remove(f"{BASE_PATH}/modules/custom_modules/{module_name}.py")
|
os.remove(f'{BASE_PATH}/modules/custom_modules/{module_name}.py')
|
||||||
if module_name == "musicbot":
|
if module_name == 'musicbot':
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[sys.executable, "-m", "pip", "uninstall", "-y", "requirements.txt"],
|
[sys.executable, '-m', 'pip', 'uninstall', '-y', 'requirements.txt'],
|
||||||
cwd=f"{BASE_PATH}/musicbot",
|
cwd=f'{BASE_PATH}/musicbot',
|
||||||
)
|
)
|
||||||
shutil.rmtree(f"{BASE_PATH}/musicbot")
|
shutil.rmtree(f'{BASE_PATH}/musicbot')
|
||||||
all_modules = db.get("custom.modules", "allModules", [])
|
all_modules = db.get('custom.modules', 'allModules', [])
|
||||||
if module_name in all_modules:
|
if module_name in all_modules:
|
||||||
all_modules.remove(module_name)
|
all_modules.remove(module_name)
|
||||||
db.set("custom.modules", "allModules", all_modules)
|
db.set('custom.modules', 'allModules', all_modules)
|
||||||
await message.edit(
|
await message.edit(f'<b>The module <code>{module_name}</code> removed!\nRestarting...</b>')
|
||||||
f"<b>The module <code>{module_name}</code> removed!\nRestarting...</b>"
|
|
||||||
)
|
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
elif os.path.exists(f"{BASE_PATH}/modules/{module_name}.py"):
|
elif os.path.exists(f'{BASE_PATH}/modules/{module_name}.py'):
|
||||||
await message.edit(
|
await message.edit('<b>It is forbidden to remove built-in modules, it will disrupt the updater</b>')
|
||||||
"<b>It is forbidden to remove built-in modules, it will disrupt the updater</b>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Module <code>{module_name}</code> is not found</b>")
|
await message.edit(f'<b>Module <code>{module_name}</code> is not found</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["loadallmods", "lmall"], prefix) & filters.me)
|
@Client.on_message(filters.command(['loadallmods', 'lmall'], prefix) & filters.me)
|
||||||
async def load_all_mods(_, message: Message):
|
async def load_all_mods(_, message: Message):
|
||||||
await message.edit("<b>Fetching info...</b>")
|
await message.edit('<b>Fetching info...</b>')
|
||||||
|
|
||||||
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
|
if not os.path.exists(f'{BASE_PATH}/modules/custom_modules'):
|
||||||
os.mkdir(f"{BASE_PATH}/modules/custom_modules")
|
os.mkdir(f'{BASE_PATH}/modules/custom_modules')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
f = requests.get(
|
f = requests.get('https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt').text
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt"
|
|
||||||
).text
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit("Failed to fetch custom modules list")
|
return await message.edit('Failed to fetch custom modules list')
|
||||||
modules_list = f.splitlines()
|
modules_list = f.splitlines()
|
||||||
|
|
||||||
await message.edit("<b>Loading modules...</b>")
|
await message.edit('<b>Loading modules...</b>')
|
||||||
for module_name in modules_list:
|
for module_name in modules_list:
|
||||||
url = f"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{module_name}.py"
|
url = f'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{module_name}.py'
|
||||||
resp = requests.get(url)
|
resp = requests.get(url)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
continue
|
continue
|
||||||
with open(
|
with open(f'./modules/custom_modules/{module_name.split("/")[1]}.py', 'wb') as f:
|
||||||
f"./modules/custom_modules/{module_name.split('/')[1]}.py", "wb"
|
|
||||||
) as f:
|
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Successfully loaded new modules: {len(modules_list)}\nRestarting...</b>",
|
f'<b>Successfully loaded new modules: {len(modules_list)}\nRestarting...</b>',
|
||||||
)
|
)
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["unloadallmods", "ulmall"], prefix) & filters.me)
|
@Client.on_message(filters.command(['unloadallmods', 'ulmall'], prefix) & filters.me)
|
||||||
async def unload_all_mods(_, message: Message):
|
async def unload_all_mods(_, message: Message):
|
||||||
await message.edit("<b>Fetching info...</b>")
|
await message.edit('<b>Fetching info...</b>')
|
||||||
|
|
||||||
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
|
if not os.path.exists(f'{BASE_PATH}/modules/custom_modules'):
|
||||||
return await message.edit("<b>You don't have any modules installed</b>")
|
return await message.edit("<b>You don't have any modules installed</b>")
|
||||||
shutil.rmtree(f"{BASE_PATH}/modules/custom_modules")
|
shutil.rmtree(f'{BASE_PATH}/modules/custom_modules')
|
||||||
db.set("custom.modules", "allModules", [])
|
db.set('custom.modules', 'allModules', [])
|
||||||
await message.edit("<b>Successfully unloaded all modules!\nRestarting...</b>")
|
await message.edit('<b>Successfully unloaded all modules!\nRestarting...</b>')
|
||||||
|
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["updateallmods"], prefix) & filters.me)
|
@Client.on_message(filters.command(['updateallmods'], prefix) & filters.me)
|
||||||
async def updateallmods(_, message: Message):
|
async def updateallmods(_, message: Message):
|
||||||
await message.edit("<b>Updating modules...</b>")
|
await message.edit('<b>Updating modules...</b>')
|
||||||
|
|
||||||
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
|
if not os.path.exists(f'{BASE_PATH}/modules/custom_modules'):
|
||||||
os.mkdir(f"{BASE_PATH}/modules/custom_modules")
|
os.mkdir(f'{BASE_PATH}/modules/custom_modules')
|
||||||
|
|
||||||
modules_installed = list(os.walk("modules/custom_modules"))[0][2]
|
modules_installed = list(os.walk('modules/custom_modules'))[0][2]
|
||||||
|
|
||||||
if not modules_installed:
|
if not modules_installed:
|
||||||
return await message.edit("<b>You don't have any modules installed</b>")
|
return await message.edit("<b>You don't have any modules installed</b>")
|
||||||
|
|
||||||
for module_name in modules_installed:
|
for module_name in modules_installed:
|
||||||
if not module_name.endswith(".py"):
|
if not module_name.endswith('.py'):
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
f = requests.get(
|
f = requests.get('https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt').text
|
||||||
"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/full.txt"
|
|
||||||
).text
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit("Failed to fetch custom modules list")
|
return await message.edit('Failed to fetch custom modules list')
|
||||||
modules_dict = {line.split("/")[-1].split()[0]: line.strip() for line in f.splitlines()}
|
modules_dict = {line.split('/')[-1].split()[0]: line.strip() for line in f.splitlines()}
|
||||||
if module_name in modules_dict:
|
if module_name in modules_dict:
|
||||||
resp = requests.get(
|
resp = requests.get(
|
||||||
f"https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py"
|
f'https://raw.githubusercontent.com/The-MoonTg-project/custom_modules/main/{modules_dict[module_name]}.py'
|
||||||
)
|
)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
modules_installed.remove(module_name)
|
modules_installed.remove(module_name)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
with open(f"./modules/custom_modules/{module_name}", "wb") as f:
|
with open(f'./modules/custom_modules/{module_name}', 'wb') as f:
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
|
|
||||||
await message.edit(f"<b>Successfully updated {len(modules_installed)} modules</b>")
|
await message.edit(f'<b>Successfully updated {len(modules_installed)} modules</b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["loader"] = {
|
modules_help['loader'] = {
|
||||||
"loadmod [module_name]*": "Download module.\n"
|
'loadmod [module_name]*': 'Download module.\n'
|
||||||
"Only modules from the official custom_modules repository and proven "
|
'Only modules from the official custom_modules repository and proven '
|
||||||
"modules whose hashes are in modules_hashes.txt are supported",
|
'modules whose hashes are in modules_hashes.txt are supported',
|
||||||
"unloadmod [module_name]*": "Delete module",
|
'unloadmod [module_name]*': 'Delete module',
|
||||||
"modhash [link]*": "Get module hash by link",
|
'modhash [link]*': 'Get module hash by link',
|
||||||
"loadallmods": "Load all custom modules (use it at your own risk)",
|
'loadallmods': 'Load all custom modules (use it at your own risk)',
|
||||||
"unloadallmods": "Unload all custom modules",
|
'unloadallmods': 'Unload all custom modules',
|
||||||
"updateallmods": "Update all custom modules"
|
'updateallmods': 'Update all custom modules'
|
||||||
"\n\n* - required argument"
|
'\n\n* - required argument'
|
||||||
"\n <b>short cmds:</b>"
|
'\n <b>short cmds:</b>'
|
||||||
"\n loadmod - lm"
|
'\n loadmod - lm'
|
||||||
"\n unloadmod - ulm"
|
'\n unloadmod - ulm'
|
||||||
"\n modhash - mh"
|
'\n modhash - mh'
|
||||||
"\n loadallmods - lmall"
|
'\n loadallmods - lmall'
|
||||||
"\n unloadallmods - ulmall",
|
'\n unloadallmods - ulmall',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,37 +15,35 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help
|
from utils.misc import modules_help
|
||||||
from utils.scripts import prefix, import_library, with_reply
|
from utils.scripts import import_library, prefix, with_reply
|
||||||
|
|
||||||
import_library("markitdown")
|
import_library('markitdown')
|
||||||
|
|
||||||
from markitdown import MarkItDown
|
from markitdown import MarkItDown
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["markitdown", "mkdn"], prefix) & filters.me)
|
@Client.on_message(filters.command(['markitdown', 'mkdn'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def markitdown(client: Client, message: Message):
|
async def markitdown(client: Client, message: Message):
|
||||||
if message.reply_to_message.document:
|
if message.reply_to_message.document:
|
||||||
await message.edit("Converting to Markdown...")
|
await message.edit('Converting to Markdown...')
|
||||||
file = await message.reply_to_message.download()
|
file = await message.reply_to_message.download()
|
||||||
file_name = (message.reply_to_message.document.file_name).split(".")[0] + ".md"
|
file_name = (message.reply_to_message.document.file_name).split('.')[0] + '.md'
|
||||||
markitdown = MarkItDown()
|
markitdown = MarkItDown()
|
||||||
result = markitdown.convert(file)
|
result = markitdown.convert(file)
|
||||||
with open(file_name, "w") as f:
|
with open(file_name, 'w') as f:
|
||||||
f.write(result.text_content)
|
f.write(result.text_content)
|
||||||
await message.edit("Uploading...")
|
await message.edit('Uploading...')
|
||||||
await client.send_document(
|
await client.send_document(message.chat.id, file_name, reply_to_message_id=message.reply_to_message.id)
|
||||||
message.chat.id, file_name, reply_to_message_id=message.reply_to_message.id
|
|
||||||
)
|
|
||||||
os.remove(file)
|
os.remove(file)
|
||||||
os.remove(file_name)
|
os.remove(file_name)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit("Reply to a document to convert it to Markdown.")
|
await message.edit('Reply to a document to convert it to Markdown.')
|
||||||
|
|
||||||
|
|
||||||
modules_help["markitdown"] = {"markitdown": "Convert a document to Markdown."}
|
modules_help['markitdown'] = {'markitdown': 'Convert a document to Markdown.'}
|
||||||
|
|||||||
+12
-19
@@ -17,26 +17,23 @@
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from pyrogram.types.user_and_chats.user import Link
|
from pyrogram.types.user_and_chats.user import Link
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
def custom_mention(user, custom_text):
|
def custom_mention(user, custom_text):
|
||||||
return Link(
|
return Link(
|
||||||
f"tg://user?id={user.id}",
|
f'tg://user?id={user.id}',
|
||||||
custom_text,
|
custom_text,
|
||||||
user._client.parse_mode,
|
user._client.parse_mode,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("mention", prefix) & filters.me)
|
@Client.on_message(filters.command('mention', prefix) & filters.me)
|
||||||
async def example_edit(client: Client, message: Message):
|
async def example_edit(client: Client, message: Message):
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
if message.reply_to_message and not len(message.text.split()) > 1:
|
if message.reply_to_message and not len(message.text.split()) > 1:
|
||||||
user = message.reply_to_message.from_user
|
user = message.reply_to_message.from_user
|
||||||
custom_text = (
|
custom_text = message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
||||||
message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
|
||||||
)
|
|
||||||
if custom_text:
|
if custom_text:
|
||||||
await message.edit(custom_mention(user, custom_text))
|
await message.edit(custom_mention(user, custom_text))
|
||||||
else:
|
else:
|
||||||
@@ -46,27 +43,23 @@ async def example_edit(client: Client, message: Message):
|
|||||||
if len(message.text.split()) > 1:
|
if len(message.text.split()) > 1:
|
||||||
user_id = message.text.split()[1]
|
user_id = message.text.split()[1]
|
||||||
if user_id.isdigit():
|
if user_id.isdigit():
|
||||||
text = (
|
text = message.text.split(maxsplit=2)[2] if len(message.text.split()) > 2 else None
|
||||||
message.text.split(maxsplit=2)[2]
|
|
||||||
if len(message.text.split()) > 2
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
if text:
|
if text:
|
||||||
men = Link(f"tg://user?id={user_id}", text, client.parse_mode)
|
men = Link(f'tg://user?id={user_id}', text, client.parse_mode)
|
||||||
else:
|
else:
|
||||||
men = (await client.get_users(user_id)).mention
|
men = (await client.get_users(user_id)).mention
|
||||||
await message.edit(men)
|
await message.edit(men)
|
||||||
else:
|
else:
|
||||||
await message.edit("Invalid user_id")
|
await message.edit('Invalid user_id')
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit("Reply to a message or provide a user_id")
|
await message.edit('Reply to a message or provide a user_id')
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
modules_help["mention"] = {
|
modules_help['mention'] = {
|
||||||
"mention": "Mention the user you replied to.",
|
'mention': 'Mention the user you replied to.',
|
||||||
"mention [custom_text]": "Mention the user you replied to with custom text.",
|
'mention [custom_text]': 'Mention the user you replied to with custom text.',
|
||||||
"mention [user_id] [custom_text]": "Mention a user by their user_id with custom text.",
|
'mention [user_id] [custom_text]': 'Mention a user by their user_id with custom text.',
|
||||||
"mention [user_id]": "Mention a user by their user_id.",
|
'mention [user_id]': 'Mention a user by their user_id.',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
# original module https://raw.githubusercontent.com/KeyZenD/modules/master/MirrorFlipV2.py | t.me/the_kzd
|
# original module https://raw.githubusercontent.com/KeyZenD/modules/master/MirrorFlipV2.py | t.me/the_kzd
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import import_library
|
from utils.scripts import import_library
|
||||||
|
|
||||||
PIL = import_library("PIL", "pillow")
|
PIL = import_library('PIL', 'pillow')
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
|
||||||
@@ -19,7 +17,7 @@ async def make(client, message, o):
|
|||||||
downloads = await client.download_media(reply.photo.file_id)
|
downloads = await client.download_media(reply.photo.file_id)
|
||||||
else:
|
else:
|
||||||
downloads = await client.download_media(reply.sticker.file_id)
|
downloads = await client.download_media(reply.sticker.file_id)
|
||||||
path = f"{downloads}"
|
path = f'{downloads}'
|
||||||
img = Image.open(path)
|
img = Image.open(path)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
@@ -41,21 +39,19 @@ async def make(client, message, o):
|
|||||||
return await reply.reply_sticker(sticker=path)
|
return await reply.reply_sticker(sticker=path)
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
return await message.edit(
|
return await message.edit('<b>Need to answer the photo/sticker</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Need to answer the photo/sticker</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["ll", "rr", "dd", "uu"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ll', 'rr', 'dd', 'uu'], prefix) & filters.me)
|
||||||
async def mirror_flip(client: Client, message: Message):
|
async def mirror_flip(client: Client, message: Message):
|
||||||
await message.edit("<b>Processing...</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Processing...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
param = {"ll": 1, "rr": 2, "dd": 3, "uu": 4}[message.command[0]]
|
param = {'ll': 1, 'rr': 2, 'dd': 3, 'uu': 4}[message.command[0]]
|
||||||
await make(client, message, param)
|
await make(client, message, param)
|
||||||
|
|
||||||
|
|
||||||
modules_help["mirror_flip"] = {
|
modules_help['mirror_flip'] = {
|
||||||
"ll [reply on photo or sticker]*": "reflects the left side",
|
'll [reply on photo or sticker]*': 'reflects the left side',
|
||||||
"rr [reply on photo or sticker]*": "reflects the right side",
|
'rr [reply on photo or sticker]*': 'reflects the right side',
|
||||||
"uu [reply on photo or sticker]*": "reflects the top",
|
'uu [reply on photo or sticker]*': 'reflects the top',
|
||||||
"dd [reply on photo or sticker]*": "reflects the bottom",
|
'dd [reply on photo or sticker]*': 'reflects the bottom',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
from os import listdir
|
from os import listdir
|
||||||
|
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ from utils.misc import modules_help, prefix
|
|||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["lback"], prefix) & filters.me)
|
@Client.on_message(filters.command(['lback'], prefix) & filters.me)
|
||||||
async def backup_database_cmd(_: Client, message: Message):
|
async def backup_database_cmd(_: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Backup the database.
|
Backup the database.
|
||||||
@@ -18,42 +18,40 @@ async def backup_database_cmd(_: Client, message: Message):
|
|||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
await message.edit("[😇] I think you didn't specify the name of the bot.")
|
await message.edit("[😇] I think you didn't specify the name of the bot.")
|
||||||
return
|
return
|
||||||
await message.edit_text(
|
await message.edit_text("<b>I'm copying the database...</b>", parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>I'm copying the database...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
name = message.command[1].lower()
|
name = message.command[1].lower()
|
||||||
folders = listdir("/root/")
|
folders = listdir('/root/')
|
||||||
if name not in folders:
|
if name not in folders:
|
||||||
await message.edit("[😇] There is no such bot in the root folder.")
|
await message.edit('[😇] There is no such bot in the root folder.')
|
||||||
return
|
return
|
||||||
folder = listdir("/root/" + name)
|
folder = listdir('/root/' + name)
|
||||||
for file in folder:
|
for file in folder:
|
||||||
if file.endswith((".db", ".sqlite", ".sqlite3")):
|
if file.endswith(('.db', '.sqlite', '.sqlite3')):
|
||||||
await message.reply_document(
|
await message.reply_document(
|
||||||
document="/root/" + name + "/" + file,
|
document='/root/' + name + '/' + file,
|
||||||
caption="<code>Bot Database <b>" + name + "</b></code>",
|
caption='<code>Bot Database <b>' + name + '</b></code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
return await message.delete()
|
return await message.delete()
|
||||||
folder = listdir("/root/" + name + "/assets")
|
folder = listdir('/root/' + name + '/assets')
|
||||||
for file in folder:
|
for file in folder:
|
||||||
if file.endswith((".db", ".sqlite", ".sqlite3")):
|
if file.endswith(('.db', '.sqlite', '.sqlite3')):
|
||||||
await message.reply_document(
|
await message.reply_document(
|
||||||
document="/root/" + name + "/assets/" + file,
|
document='/root/' + name + '/assets/' + file,
|
||||||
caption="<code>Bot Database <b>" + name + "</b></code>",
|
caption='<code>Bot Database <b>' + name + '</b></code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
return await message.delete()
|
return await message.delete()
|
||||||
await message.edit("[😇] Database not found.")
|
await message.edit('[😇] Database not found.')
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
"Failed to back up the database!\n\n" f"{format_exc(ex)}",
|
f'Failed to back up the database!\n\n{format_exc(ex)}',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["autobackup"] = {
|
modules_help['autobackup'] = {
|
||||||
"lback [name]*": "<b>Backup database from folder</b>",
|
'lback [name]*': '<b>Backup database from folder</b>',
|
||||||
"lbackall": "<b>Backup all databases</b>",
|
'lbackall': '<b>Backup all databases</b>',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,140 +15,129 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageTooLong
|
from pyrogram.errors import MessageTooLong
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
def addtrg(channel_id):
|
def addtrg(channel_id):
|
||||||
channel_ids = db.get("custom.autofwd", "chatto", default=[])
|
channel_ids = db.get('custom.autofwd', 'chatto', default=[])
|
||||||
if channel_id not in channel_ids:
|
if channel_id not in channel_ids:
|
||||||
channel_ids.append(channel_id)
|
channel_ids.append(channel_id)
|
||||||
db.set("custom.autofwd", "chatto", channel_ids)
|
db.set('custom.autofwd', 'chatto', channel_ids)
|
||||||
|
|
||||||
|
|
||||||
def rmtrg(channel_id):
|
def rmtrg(channel_id):
|
||||||
channel_ids = db.get("custom.autofwd", "chatto", default=[])
|
channel_ids = db.get('custom.autofwd', 'chatto', default=[])
|
||||||
if channel_id in channel_ids:
|
if channel_id in channel_ids:
|
||||||
channel_ids.remove(channel_id)
|
channel_ids.remove(channel_id)
|
||||||
db.set("custom.autofwd", "chatto", channel_ids)
|
db.set('custom.autofwd', 'chatto', channel_ids)
|
||||||
|
|
||||||
|
|
||||||
def addsrc(channel_id):
|
def addsrc(channel_id):
|
||||||
channel_ids = db.get("custom.autofwd", "chatsrc", default=[])
|
channel_ids = db.get('custom.autofwd', 'chatsrc', default=[])
|
||||||
if channel_id not in channel_ids:
|
if channel_id not in channel_ids:
|
||||||
channel_ids.append(channel_id)
|
channel_ids.append(channel_id)
|
||||||
db.set("custom.autofwd", "chatsrc", channel_ids)
|
db.set('custom.autofwd', 'chatsrc', channel_ids)
|
||||||
|
|
||||||
|
|
||||||
def rmsrc(channel_id):
|
def rmsrc(channel_id):
|
||||||
channel_ids = db.get("custom.autofwd", "chatsrc", default=[])
|
channel_ids = db.get('custom.autofwd', 'chatsrc', default=[])
|
||||||
if channel_id in channel_ids:
|
if channel_id in channel_ids:
|
||||||
channel_ids.remove(channel_id)
|
channel_ids.remove(channel_id)
|
||||||
db.set("custom.autofwd", "chatsrc", channel_ids)
|
db.set('custom.autofwd', 'chatsrc', channel_ids)
|
||||||
|
|
||||||
|
|
||||||
def getfwd_data():
|
def getfwd_data():
|
||||||
source_chats = db.get("custom.autofwd", "chatsrc")
|
source_chats = db.get('custom.autofwd', 'chatsrc')
|
||||||
target_chats = db.get("custom.autofwd", "chatto")
|
target_chats = db.get('custom.autofwd', 'chatto')
|
||||||
return source_chats, target_chats
|
return source_chats, target_chats
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["addfwd_src", "addfwd_to"], prefix) & filters.me)
|
@Client.on_message(filters.command(['addfwd_src', 'addfwd_to'], prefix) & filters.me)
|
||||||
async def addfwd(_, message: Message):
|
async def addfwd(_, message: Message):
|
||||||
if message.command[0] == "addfwd_src":
|
if message.command[0] == 'addfwd_src':
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
channel_id = message.text.split(maxsplit=1)[1]
|
channel_id = message.text.split(maxsplit=1)[1]
|
||||||
if not channel_id.startswith("-100"):
|
if not channel_id.startswith('-100'):
|
||||||
channel_id = "-100" + channel_id
|
channel_id = '-100' + channel_id
|
||||||
# chat id should be integer
|
# chat id should be integer
|
||||||
if not channel_id.isdigit():
|
if not channel_id.isdigit():
|
||||||
try:
|
try:
|
||||||
channel_id = int(channel_id)
|
channel_id = int(channel_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit_text("Chat id should be in integer")
|
return await message.edit_text('Chat id should be in integer')
|
||||||
addsrc(channel_id=channel_id)
|
addsrc(channel_id=channel_id)
|
||||||
await message.edit_text(
|
await message.edit_text(f'Auto Forwarding Enabled for Chat with id: <code>{channel_id}</code>')
|
||||||
f"Auto Forwarding Enabled for Chat with id: <code>{channel_id}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Chat id not provided!")
|
await message.edit_text('Chat id not provided!')
|
||||||
return
|
return
|
||||||
elif message.command[0] == "addfwd_to":
|
elif message.command[0] == 'addfwd_to':
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
channel_id = message.text.split(maxsplit=1)[1]
|
channel_id = message.text.split(maxsplit=1)[1]
|
||||||
if not channel_id.startswith("-100"):
|
if not channel_id.startswith('-100'):
|
||||||
channel_id = "-100" + channel_id
|
channel_id = '-100' + channel_id
|
||||||
# chat id should be integer
|
# chat id should be integer
|
||||||
if not channel_id.isdigit():
|
if not channel_id.isdigit():
|
||||||
try:
|
try:
|
||||||
channel_id = int(channel_id)
|
channel_id = int(channel_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit_text("Chat id should be in integer")
|
return await message.edit_text('Chat id should be in integer')
|
||||||
addtrg(channel_id=channel_id)
|
addtrg(channel_id=channel_id)
|
||||||
await message.edit_text(
|
await message.edit_text(f'Auto Forwarding Enabled to Chat with id: <code>{channel_id}</code>')
|
||||||
f"Auto Forwarding Enabled to Chat with id: <code>{channel_id}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Chat id not provided!")
|
await message.edit_text('Chat id not provided!')
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["delfwd_src", "delfwd_to"], prefix) & filters.me)
|
@Client.on_message(filters.command(['delfwd_src', 'delfwd_to'], prefix) & filters.me)
|
||||||
async def delfwd(_, message: Message):
|
async def delfwd(_, message: Message):
|
||||||
if message.command[0] == "delfwd_src":
|
if message.command[0] == 'delfwd_src':
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
channel_id = message.text.split(maxsplit=1)[1]
|
channel_id = message.text.split(maxsplit=1)[1]
|
||||||
if not channel_id.startswith("-100"):
|
if not channel_id.startswith('-100'):
|
||||||
channel_id = "-100" + channel_id
|
channel_id = '-100' + channel_id
|
||||||
# chat id should be integer
|
# chat id should be integer
|
||||||
if not channel_id.isdigit():
|
if not channel_id.isdigit():
|
||||||
try:
|
try:
|
||||||
channel_id = int(channel_id)
|
channel_id = int(channel_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit_text("Chat id should be in integer")
|
return await message.edit_text('Chat id should be in integer')
|
||||||
rmsrc(channel_id=channel_id)
|
rmsrc(channel_id=channel_id)
|
||||||
await message.edit_text(
|
await message.edit_text(f'Auto Forwarding Disabled for Chat with id: <code>{channel_id}</code>')
|
||||||
f"Auto Forwarding Disabled for Chat with id: <code>{channel_id}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Chat id not provided!")
|
await message.edit_text('Chat id not provided!')
|
||||||
return
|
return
|
||||||
elif message.command[0] == "delfwd_to":
|
elif message.command[0] == 'delfwd_to':
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
channel_id = message.text.split(maxsplit=1)[1]
|
channel_id = message.text.split(maxsplit=1)[1]
|
||||||
if not channel_id.startswith("-100"):
|
if not channel_id.startswith('-100'):
|
||||||
channel_id = "-100" + channel_id
|
channel_id = '-100' + channel_id
|
||||||
# chat id should be integer
|
# chat id should be integer
|
||||||
if not channel_id.isdigit():
|
if not channel_id.isdigit():
|
||||||
try:
|
try:
|
||||||
channel_id = int(channel_id)
|
channel_id = int(channel_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
return await message.edit_text("Chat id should be in integer")
|
return await message.edit_text('Chat id should be in integer')
|
||||||
rmtrg(channel_id=channel_id)
|
rmtrg(channel_id=channel_id)
|
||||||
await message.edit_text(
|
await message.edit_text(f'Auto Forwarding Disabled to Chat with id: <code>{channel_id}</code>')
|
||||||
f"Auto Forwarding Disabled to Chat with id: <code>{channel_id}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Chat id not provided!")
|
await message.edit_text('Chat id not provided!')
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("autofwd", prefix) & filters.me)
|
@Client.on_message(filters.command('autofwd', prefix) & filters.me)
|
||||||
async def autofwd(_, message: Message):
|
async def autofwd(_, message: Message):
|
||||||
source_chats, target_chats = getfwd_data()
|
source_chats, target_chats = getfwd_data()
|
||||||
return await message.edit_text(
|
return await message.edit_text(f'Source Chats: {source_chats}\nTarget Chats: {target_chats}')
|
||||||
f"Source Chats: {source_chats}\nTarget Chats: {target_chats}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.channel | filters.group)
|
@Client.on_message(filters.channel | filters.group)
|
||||||
async def autofwd_main(client: Client, message: Message):
|
async def autofwd_main(client: Client, message: Message):
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
source_chats = db.get("custom.autofwd", "chatsrc")
|
source_chats = db.get('custom.autofwd', 'chatsrc')
|
||||||
target_chats = db.get("custom.autofwd", "chatto")
|
target_chats = db.get('custom.autofwd', 'chatto')
|
||||||
|
|
||||||
if source_chats is not None and chat_id in source_chats:
|
if source_chats is not None and chat_id in source_chats:
|
||||||
if target_chats is not None:
|
if target_chats is not None:
|
||||||
@@ -158,20 +147,20 @@ async def autofwd_main(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
try:
|
try:
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Auto Forwarding Failed for Chat with id: <code>{chat_id}</code> to <code>{chat}</code>\n\n{e}",
|
f'Auto Forwarding Failed for Chat with id: <code>{chat_id}</code> to <code>{chat}</code>\n\n{e}',
|
||||||
)
|
)
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Auto Forwarding Failed for Chat with id: <code>{chat_id}</code> to <code>{chat}</code>, Please check logs!",
|
f'Auto Forwarding Failed for Chat with id: <code>{chat_id}</code> to <code>{chat}</code>, Please check logs!',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["autofwd"] = {
|
modules_help['autofwd'] = {
|
||||||
"autofwd": "Retrieve Data of auto fwd",
|
'autofwd': 'Retrieve Data of auto fwd',
|
||||||
"addfwd_src [channel_id]*": "Enable auto forwarding for a channel",
|
'addfwd_src [channel_id]*': 'Enable auto forwarding for a channel',
|
||||||
"addfwd_to [channel_id]*": "Enable auto forwarding to a channel",
|
'addfwd_to [channel_id]*': 'Enable auto forwarding to a channel',
|
||||||
"delfwd_src [channel_id]*": "Disable auto forwarding for a channel",
|
'delfwd_src [channel_id]*': 'Disable auto forwarding for a channel',
|
||||||
"delfwd_to [channel_id]*": "Disable auto forwarding to a channel",
|
'delfwd_to [channel_id]*': 'Disable auto forwarding to a channel',
|
||||||
}
|
}
|
||||||
|
|||||||
+80
-101
@@ -1,106 +1,95 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
from utils import config
|
||||||
|
from utils.db import db
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, restart
|
from utils.scripts import format_exc, restart
|
||||||
from utils.db import db
|
|
||||||
from utils import config
|
|
||||||
|
|
||||||
if config.db_type in ["mongodb", "mongo"]:
|
if config.db_type in ['mongodb', 'mongo']:
|
||||||
import bson
|
import bson
|
||||||
|
|
||||||
|
|
||||||
def dump_mongo(collections, path, db_):
|
def dump_mongo(collections, path, db_):
|
||||||
for coll in collections:
|
for coll in collections:
|
||||||
with open(os.path.join(path, f"{coll}.bson"), "wb+") as f:
|
with open(os.path.join(path, f'{coll}.bson'), 'wb+') as f:
|
||||||
for doc in db_[coll].find():
|
for doc in db_[coll].find():
|
||||||
f.write(bson.BSON.encode(doc))
|
f.write(bson.BSON.encode(doc))
|
||||||
|
|
||||||
|
|
||||||
def restore_mongo(path, db_):
|
def restore_mongo(path, db_):
|
||||||
for coll in os.listdir(path):
|
for coll in os.listdir(path):
|
||||||
if coll.endswith(".bson"):
|
if coll.endswith('.bson'):
|
||||||
with open(os.path.join(path, coll), "rb+") as f:
|
with open(os.path.join(path, coll), 'rb+') as f:
|
||||||
db_[coll.split(".")[0]].insert_many(bson.decode_all(f.read()))
|
db_[coll.split('.')[0]].insert_many(bson.decode_all(f.read()))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["backup", "back"], prefix) & filters.me)
|
@Client.on_message(filters.command(['backup', 'back'], prefix) & filters.me)
|
||||||
async def backup(client: Client, message: Message):
|
async def backup(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Backup the database
|
Backup the database
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not os.path.exists("backups/"):
|
if not os.path.exists('backups/'):
|
||||||
os.mkdir("backups/")
|
os.mkdir('backups/')
|
||||||
|
|
||||||
await message.edit(
|
await message.edit('<b>Backing up database...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Backing up database...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
if config.db_type in ["mongo", "mongodb"]:
|
if config.db_type in ['mongo', 'mongodb']:
|
||||||
dump_mongo(db._database.list_collection_names(), "backups/", db._database)
|
dump_mongo(db._database.list_collection_names(), 'backups/', db._database)
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Database backed up to:</b> <code>backups/</code> folder",
|
'<b>Database backed up to:</b> <code>backups/</code> folder',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
shutil.copy(config.db_name, f"backups/{config.db_name}")
|
shutil.copy(config.db_name, f'backups/{config.db_name}')
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
"me",
|
'me',
|
||||||
caption=f"<b>Database backup complete!\nType: </b>"
|
caption='<b>Database backup complete!\nType: </b>'
|
||||||
f"<code>.restore</code> in response to this message to restore the database.",
|
'<code>.restore</code> in response to this message to restore the database.',
|
||||||
document=f"backups/{config.db_name}",
|
document=f'backups/{config.db_name}',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Database backed up successfully! <code>(Check your favorites)</code></b>",
|
'<b>Database backed up successfully! <code>(Check your favorites)</code></b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["restore", "res"], prefix) & filters.me)
|
@Client.on_message(filters.command(['restore', 'res'], prefix) & filters.me)
|
||||||
async def restore(client: Client, message: Message):
|
async def restore(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Restore the database
|
Restore the database
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await message.edit(
|
await message.edit('<b>Restoring database...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Restoring database...</b>", parse_mode=enums.ParseMode.HTML
|
if config.db_type in ['mongo', 'mongodb']:
|
||||||
)
|
restore_mongo('backups/', db._database)
|
||||||
if config.db_type in ["mongo", "mongodb"]:
|
|
||||||
restore_mongo("backups/", db._database)
|
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Database restored from:</b> <code>backups/</code> folder",
|
'<b>Database restored from:</b> <code>backups/</code> folder',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
if not message.reply_to_message or not message.reply_to_message.document:
|
if not message.reply_to_message or not message.reply_to_message.document:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Reply to a document to restore the database.</b>",
|
'<b>Reply to a document to restore the database.</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
elif not message.reply_to_message.document.file_name.casefold().endswith(
|
elif not message.reply_to_message.document.file_name.casefold().endswith(('.db', '.sqlite', '.sqlite3')):
|
||||||
(".db", ".sqlite", ".sqlite3")
|
|
||||||
):
|
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Reply to a database file to restore the database.</b>",
|
'<b>Reply to a database file to restore the database.</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
await message.reply_to_message.download(
|
await message.reply_to_message.download(f'backups/{message.reply_to_message.document.file_name}')
|
||||||
f"backups/{message.reply_to_message.document.file_name}"
|
shutil.copy(f'backups/{message.reply_to_message.document.file_name}', config.db_name)
|
||||||
)
|
|
||||||
shutil.copy(
|
|
||||||
f"backups/{message.reply_to_message.document.file_name}", config.db_name
|
|
||||||
)
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Database restored successfully!</b>",
|
'<b>Database restored successfully!</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
@@ -108,104 +97,96 @@ async def restore(client: Client, message: Message):
|
|||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["backupmods", "bms"], prefix) & filters.me)
|
@Client.on_message(filters.command(['backupmods', 'bms'], prefix) & filters.me)
|
||||||
async def backupmods(client: Client, message: Message):
|
async def backupmods(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Backup the modules
|
Backup the modules
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not os.path.exists("backups/"):
|
if not os.path.exists('backups/'):
|
||||||
os.mkdir("backups/")
|
os.mkdir('backups/')
|
||||||
|
|
||||||
await message.edit(
|
await message.edit('<b>Backing up modules...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Backing up modules...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
from utils.misc import modules_help
|
from utils.misc import modules_help
|
||||||
|
|
||||||
for mod in modules_help:
|
for mod in modules_help:
|
||||||
if os.path.isfile(f"modules/custom_modules/{mod}.py"):
|
if os.path.isfile(f'modules/custom_modules/{mod}.py'):
|
||||||
f = open(f"backups/{mod}.py", "wb")
|
f = open(f'backups/{mod}.py', 'wb')
|
||||||
f.write(open(f"modules/custom_modules/{mod}.py", "rb").read())
|
f.write(open(f'modules/custom_modules/{mod}.py', 'rb').read())
|
||||||
await message.edit(
|
await message.edit(
|
||||||
text=f"<b>All modules backed up to:</b> <code>backups/</code> folder",
|
text='<b>All modules backed up to:</b> <code>backups/</code> folder',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["backupmod", "bm"], prefix) & filters.me)
|
@Client.on_message(filters.command(['backupmod', 'bm'], prefix) & filters.me)
|
||||||
async def backupmod(client: Client, message: Message):
|
async def backupmod(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Backup the module
|
Backup the module
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not os.path.exists("backups/"):
|
if not os.path.exists('backups/'):
|
||||||
os.mkdir("backups/")
|
os.mkdir('backups/')
|
||||||
from utils.misc import modules_help
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
mod = message.text.split(maxsplit=1)[1].split(".")[0]
|
mod = message.text.split(maxsplit=1)[1].split('.')[0]
|
||||||
except:
|
except:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Usage:</b> <code>{prefix}backupmod [module]</code>",
|
f'<b>Usage:</b> <code>{prefix}backupmod [module]</code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
await message.edit(
|
await message.edit('<b>Backing up module...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Backing up module...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
if os.path.isfile(f"modules/custom_modules/{mod}.py"):
|
if os.path.isfile(f'modules/custom_modules/{mod}.py'):
|
||||||
f = open(f"backups/{mod}.py", "wb")
|
f = open(f'backups/{mod}.py', 'wb')
|
||||||
f.write(open(f"modules/custom_modules/{mod}.py", "rb").read())
|
f.write(open(f'modules/custom_modules/{mod}.py', 'rb').read())
|
||||||
else:
|
else:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Module <code>{mod}</code> not found.</b>",
|
f'<b>Module <code>{mod}</code> not found.</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
await message.reply_document(
|
await message.reply_document(
|
||||||
document=f"backups/{mod}.py",
|
document=f'backups/{mod}.py',
|
||||||
caption=f"<b>Module <code>{mod}</code> backed up to:</b> <code>backups/</code> folder",
|
caption=f'<b>Module <code>{mod}</code> backed up to:</b> <code>backups/</code> folder',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["restoremod", "resmod"], prefix) & filters.me)
|
@Client.on_message(filters.command(['restoremod', 'resmod'], prefix) & filters.me)
|
||||||
async def restoremod(client: Client, message: Message):
|
async def restoremod(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Restore the module
|
Restore the module
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not os.path.exists("backups/"):
|
if not os.path.exists('backups/'):
|
||||||
os.mkdir("backups/")
|
os.mkdir('backups/')
|
||||||
from utils.misc import modules_help
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
mod = message.text.split(maxsplit=1)[1].split(".")[0]
|
mod = message.text.split(maxsplit=1)[1].split('.')[0]
|
||||||
except:
|
except:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Usage:</b> <code>{prefix}restoremod [module]</code>",
|
f'<b>Usage:</b> <code>{prefix}restoremod [module]</code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
await message.edit(
|
await message.edit('<b>Restoring module...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Restoring module...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
if os.path.isfile(f"backups/{mod}.py"):
|
if os.path.isfile(f'backups/{mod}.py'):
|
||||||
f = open(f"modules/custom_modules/{mod}.py", "wb")
|
f = open(f'modules/custom_modules/{mod}.py', 'wb')
|
||||||
f.write(open(f"backups/{mod}.py", "rb").read())
|
f.write(open(f'backups/{mod}.py', 'rb').read())
|
||||||
else:
|
else:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Module <code>{mod}</code> not found.</b>",
|
f'<b>Module <code>{mod}</code> not found.</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Module <code>{mod}</code> restored successfully!</b>",
|
f'<b>Module <code>{mod}</code> restored successfully!</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
@@ -213,27 +194,25 @@ async def restoremod(client: Client, message: Message):
|
|||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["restoremods", "resmods"], prefix) & filters.me)
|
@Client.on_message(filters.command(['restoremods', 'resmods'], prefix) & filters.me)
|
||||||
async def restoremods(client: Client, message: Message):
|
async def restoremods(client: Client, message: Message):
|
||||||
"""
|
"""
|
||||||
Restore the modules
|
Restore the modules
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not os.path.exists("backups/"):
|
if not os.path.exists('backups/'):
|
||||||
os.mkdir("backups/")
|
os.mkdir('backups/')
|
||||||
|
|
||||||
await message.edit(
|
await message.edit('<b>Restoring modules...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Restoring modules...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
|
|
||||||
for mod in os.listdir("backups/"):
|
for mod in os.listdir('backups/'):
|
||||||
if mod.endswith(".py"):
|
if mod.endswith('.py'):
|
||||||
if os.path.isfile(f"modules/{mod}"):
|
if os.path.isfile(f'modules/{mod}'):
|
||||||
continue
|
continue
|
||||||
f = open(f"modules/custom_modules/{mod}", "wb")
|
f = open(f'modules/custom_modules/{mod}', 'wb')
|
||||||
f.write(open(f"backups/{mod}", "rb").read())
|
f.write(open(f'backups/{mod}', 'rb').read())
|
||||||
await message.edit(
|
await message.edit(
|
||||||
text=f"<b>All modules restored from:</b> <code>backups/</code> folder",
|
text='<b>All modules restored from:</b> <code>backups/</code> folder',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
@@ -241,11 +220,11 @@ async def restoremods(client: Client, message: Message):
|
|||||||
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["backup"] = {
|
modules_help['backup'] = {
|
||||||
"backup": f"<b>Backup database</b>",
|
'backup': '<b>Backup database</b>',
|
||||||
"restore [reply]": f"<b>Restore database</b>",
|
'restore [reply]': '<b>Restore database</b>',
|
||||||
"backupmod [name]": f"<b>Backup mod</b>",
|
'backupmod [name]': '<b>Backup mod</b>',
|
||||||
"backupmods": f"<b>Backup all mods</b>",
|
'backupmods': '<b>Backup all mods</b>',
|
||||||
"resmod [name]": f"<b>Restore mod</b>",
|
'resmod [name]': '<b>Restore mod</b>',
|
||||||
"resmods": f"<b>Restore all mods</b>",
|
'resmods': '<b>Restore all mods</b>',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,109 +1,95 @@
|
|||||||
from pyrogram import Client, filters
|
|
||||||
import requests
|
import requests
|
||||||
|
from pyrogram import Client, filters
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, import_library
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
pcp = import_library('pubchempy')
|
||||||
|
|
||||||
pcp = import_library("pubchempy")
|
INATURALIST_API_URL = 'https://api.inaturalist.org/v1/observations'
|
||||||
|
|
||||||
INATURALIST_API_URL = "https://api.inaturalist.org/v1/observations"
|
|
||||||
|
|
||||||
|
|
||||||
def get_marine_life_details(species_name):
|
def get_marine_life_details(species_name):
|
||||||
params = {
|
params = {
|
||||||
"taxon_name": species_name,
|
'taxon_name': species_name,
|
||||||
"quality_grade": "research",
|
'quality_grade': 'research',
|
||||||
"iconic_taxa": "Mollusca,Fish,Crustacea",
|
'iconic_taxa': 'Mollusca,Fish,Crustacea',
|
||||||
"per_page": 1,
|
'per_page': 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.get(INATURALIST_API_URL, params=params)
|
response = requests.get(INATURALIST_API_URL, params=params)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if data["total_results"] > 0:
|
if data['total_results'] > 0:
|
||||||
observation = data["results"][0]
|
observation = data['results'][0]
|
||||||
species = observation["taxon"]["name"]
|
species = observation['taxon']['name']
|
||||||
common_name = observation["taxon"]["preferred_common_name"]
|
common_name = observation['taxon']['preferred_common_name']
|
||||||
photo_url = (
|
photo_url = observation['photos'][0]['url'] if observation['photos'] else 'No photo available'
|
||||||
observation["photos"][0]["url"]
|
description = observation['description'] if 'description' in observation else 'No description available.'
|
||||||
if observation["photos"]
|
|
||||||
else "No photo available"
|
|
||||||
)
|
|
||||||
description = (
|
|
||||||
observation["description"]
|
|
||||||
if "description" in observation
|
|
||||||
else "No description available."
|
|
||||||
)
|
|
||||||
return {
|
return {
|
||||||
"species": species,
|
'species': species,
|
||||||
"common_name": common_name,
|
'common_name': common_name,
|
||||||
"photo_url": photo_url,
|
'photo_url': photo_url,
|
||||||
"description": description,
|
'description': description,
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
return {"error": "No marine life found for this species."}
|
return {'error': 'No marine life found for this species.'}
|
||||||
else:
|
else:
|
||||||
return {
|
return {'error': f'Error {response.status_code}: Unable to connect to iNaturalist API.'}
|
||||||
"error": f"Error {response.status_code}: Unable to connect to iNaturalist API."
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("camistry", prefix) & filters.me)
|
@Client.on_message(filters.command('camistry', prefix) & filters.me)
|
||||||
async def fetch_chemical_data_with_visual(_, message):
|
async def fetch_chemical_data_with_visual(_, message):
|
||||||
query = " ".join(message.text.split()[1:]) # Combine query words properly
|
query = ' '.join(message.text.split()[1:]) # Combine query words properly
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Fetch chemical data by name
|
# Fetch chemical data by name
|
||||||
results = pcp.get_compounds(query, "name", record_type="3d")
|
results = pcp.get_compounds(query, 'name', record_type='3d')
|
||||||
|
|
||||||
if results:
|
if results:
|
||||||
compound = results[0]
|
compound = results[0]
|
||||||
|
|
||||||
# Send chemical information without SMILES structure
|
# Send chemical information without SMILES structure
|
||||||
info = (
|
info = (
|
||||||
f"<b>Chemical Data for {compound.iupac_name}</b>\n\n"
|
f'<b>Chemical Data for {compound.iupac_name}</b>\n\n'
|
||||||
f"<b>Molecular Formula:</b> <code>{compound.molecular_formula}</code>\n"
|
f'<b>Molecular Formula:</b> <code>{compound.molecular_formula}</code>\n'
|
||||||
f"<b>Molecular Weight:</b> <code>{compound.molecular_weight}</code>\n"
|
f'<b>Molecular Weight:</b> <code>{compound.molecular_weight}</code>\n'
|
||||||
f"<b>CID:</b> <code>{compound.cid}</code>\n"
|
f'<b>CID:</b> <code>{compound.cid}</code>\n'
|
||||||
f"<b>Synonyms:</b> <code>{', '.join(compound.synonyms[:5])}</code>\n"
|
f'<b>Synonyms:</b> <code>{", ".join(compound.synonyms[:5])}</code>\n'
|
||||||
)
|
)
|
||||||
await message.edit_text(info)
|
await message.edit_text(info)
|
||||||
else:
|
else:
|
||||||
await message.edit_text(f"No chemical data found for the query: '{query}'")
|
await message.edit_text(f"No chemical data found for the query: '{query}'")
|
||||||
|
|
||||||
except pcp.PubChemHTTPError as http_err:
|
except pcp.PubChemHTTPError as http_err:
|
||||||
await message.edit_text(f"HTTP error occurred: {format_exc(http_err)}")
|
await message.edit_text(f'HTTP error occurred: {format_exc(http_err)}')
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("marinelife", prefix) & filters.me)
|
@Client.on_message(filters.command('marinelife', prefix) & filters.me)
|
||||||
async def marine_life_command(_, message):
|
async def marine_life_command(_, message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit_text(
|
await message.edit_text(f'Please specify a species name. Example: {prefix}marinelife dolphin')
|
||||||
f"Please specify a species name. Example: {prefix}marinelife dolphin"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
species_name = " ".join(message.command[1:])
|
species_name = ' '.join(message.command[1:])
|
||||||
marine_life = get_marine_life_details(species_name)
|
marine_life = get_marine_life_details(species_name)
|
||||||
|
|
||||||
if "error" in marine_life:
|
if 'error' in marine_life:
|
||||||
await message.edit_text(marine_life["error"])
|
await message.edit_text(marine_life['error'])
|
||||||
else:
|
else:
|
||||||
reply_text = (
|
reply_text = (
|
||||||
f"<b>Species</b>: <code>{marine_life['species']}</code>\n"
|
f'<b>Species</b>: <code>{marine_life["species"]}</code>\n'
|
||||||
f"<b>Common Name</b>: <code>{marine_life['common_name']}</code>\n"
|
f'<b>Common Name</b>: <code>{marine_life["common_name"]}</code>\n'
|
||||||
f"<b>Description</b>: <code>{marine_life['description']}</code>\n"
|
f'<b>Description</b>: <code>{marine_life["description"]}</code>\n'
|
||||||
f"<a href='{marine_life['photo_url']}'>Photo</a>"
|
f"<a href='{marine_life['photo_url']}'>Photo</a>"
|
||||||
)
|
)
|
||||||
await message.edit_text(reply_text)
|
await message.edit_text(reply_text)
|
||||||
|
|
||||||
|
|
||||||
modules_help["cama"] = {
|
modules_help['cama'] = {
|
||||||
"camistry [text]": " getting camicale info",
|
'camistry [text]': ' getting camicale info',
|
||||||
"marinelife [text]": " getting marinelife info",
|
'marinelife [text]': ' getting marinelife info',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,65 +1,60 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.errors import (
|
from pyrogram.errors import (
|
||||||
FileReferenceExpired,
|
FileReferenceExpired,
|
||||||
FileReferenceInvalid,
|
FileReferenceInvalid,
|
||||||
TopicDeleted,
|
|
||||||
TopicClosed,
|
TopicClosed,
|
||||||
|
TopicDeleted,
|
||||||
)
|
)
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from collections import defaultdict
|
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
mlog_enabled = filters.create(lambda _, __, ___: db.get("custom.mlog", "status", False))
|
mlog_enabled = filters.create(lambda _, __, ___: db.get('custom.mlog', 'status', False))
|
||||||
|
|
||||||
# Media cache and processing tasks
|
# Media cache and processing tasks
|
||||||
user_media_cache = defaultdict(list)
|
user_media_cache = defaultdict(list)
|
||||||
media_processing_tasks = {}
|
media_processing_tasks = {}
|
||||||
|
|
||||||
|
|
||||||
# Helper to get group-specific data
|
# Helper to get group-specific data
|
||||||
def get_group_data(group_id):
|
def get_group_data(group_id):
|
||||||
return db.get(f"custom.mlog", str(group_id), {})
|
return db.get('custom.mlog', str(group_id), {})
|
||||||
|
|
||||||
|
|
||||||
# Helper to update group-specific data
|
# Helper to update group-specific data
|
||||||
def update_group_data(group_id, data):
|
def update_group_data(group_id, data):
|
||||||
db.set(f"custom.mlog", str(group_id), data)
|
db.set('custom.mlog', str(group_id), data)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["mlog"], prefix) & filters.me)
|
@Client.on_message(filters.command(['mlog'], prefix) & filters.me)
|
||||||
async def mlog(_, message: Message):
|
async def mlog(_, message: Message):
|
||||||
if len(message.command) < 2 or message.command[1].lower() not in ["on", "off"]:
|
if len(message.command) < 2 or message.command[1].lower() not in ['on', 'off']:
|
||||||
return await message.edit(f"<b>Usage:</b> <code>{prefix}mlog [on/off]</code>")
|
return await message.edit(f'<b>Usage:</b> <code>{prefix}mlog [on/off]</code>')
|
||||||
|
|
||||||
status = message.command[1].lower() == "on"
|
status = message.command[1].lower() == 'on'
|
||||||
db.set("custom.mlog", "status", status)
|
db.set('custom.mlog', 'status', status)
|
||||||
await message.edit(f"<b>Media logging is now {'enabled' if status else 'disabled'}</b>")
|
await message.edit(f'<b>Media logging is now {"enabled" if status else "disabled"}</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["msetchat"], prefix) & filters.me)
|
@Client.on_message(filters.command(['msetchat'], prefix) & filters.me)
|
||||||
async def set_chat(_, message: Message):
|
async def set_chat(_, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
return await message.edit(f"<b>Usage:</b> <code>{prefix}msetchat [chat_id]</code>")
|
return await message.edit(f'<b>Usage:</b> <code>{prefix}msetchat [chat_id]</code>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
chat_id = message.command[1]
|
chat_id = message.command[1]
|
||||||
chat_id = int("-100" + chat_id if not chat_id.startswith("-100") else chat_id)
|
chat_id = int('-100' + chat_id if not chat_id.startswith('-100') else chat_id)
|
||||||
db.set("custom.mlog", "chat", chat_id)
|
db.set('custom.mlog', 'chat', chat_id)
|
||||||
await message.edit(f"<b>Chat ID set to {chat_id}</b>")
|
await message.edit(f'<b>Chat ID set to {chat_id}</b>')
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await message.edit("<b>Invalid chat ID</b>")
|
await message.edit('<b>Invalid chat ID</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(mlog_enabled & filters.incoming & filters.private & filters.media & ~filters.me & ~filters.bot)
|
||||||
mlog_enabled
|
|
||||||
& filters.incoming
|
|
||||||
& filters.private
|
|
||||||
& filters.media
|
|
||||||
& ~filters.me
|
|
||||||
& ~filters.bot
|
|
||||||
)
|
|
||||||
async def media_log(client: Client, message: Message):
|
async def media_log(client: Client, message: Message):
|
||||||
user_id = message.from_user.id
|
user_id = message.from_user.id
|
||||||
user_media_cache[user_id].append(message)
|
user_media_cache[user_id].append(message)
|
||||||
@@ -76,26 +71,26 @@ async def process_media(client: Client, user):
|
|||||||
if user_id == me.id:
|
if user_id == me.id:
|
||||||
return
|
return
|
||||||
|
|
||||||
chat_id = db.get("custom.mlog", "chat")
|
chat_id = db.get('custom.mlog', 'chat')
|
||||||
if not chat_id:
|
if not chat_id:
|
||||||
return await client.send_message(
|
return await client.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Media Logger is on, but no Chat ID is set. Use {prefix}msetchat to set it.",
|
f'Media Logger is on, but no Chat ID is set. Use {prefix}msetchat to set it.',
|
||||||
)
|
)
|
||||||
|
|
||||||
group_data = get_group_data(chat_id)
|
group_data = get_group_data(chat_id)
|
||||||
user_topics = group_data.get("user_topics", {})
|
user_topics = group_data.get('user_topics', {})
|
||||||
topic_id = user_topics.get(str(user_id)) # Fetch user's topic ID if it exists
|
topic_id = user_topics.get(str(user_id)) # Fetch user's topic ID if it exists
|
||||||
|
|
||||||
if not topic_id:
|
if not topic_id:
|
||||||
topic = await client.create_forum_topic(chat_id, user.first_name)
|
topic = await client.create_forum_topic(chat_id, user.first_name)
|
||||||
topic_id = topic.id
|
topic_id = topic.id
|
||||||
user_topics[str(user_id)] = topic_id # Store topic ID for this user
|
user_topics[str(user_id)] = topic_id # Store topic ID for this user
|
||||||
update_group_data(chat_id, {"user_topics": user_topics})
|
update_group_data(chat_id, {'user_topics': user_topics})
|
||||||
m = await client.send_message(
|
m = await client.send_message(
|
||||||
chat_id=chat_id,
|
chat_id=chat_id,
|
||||||
message_thread_id=topic_id,
|
message_thread_id=topic_id,
|
||||||
text=f"<b>Chat Name:</b> {user.full_name}\n<b>User ID:</b> {user_id}\n<b>Username:</b> @{user.username or 'N/A'}\n<b>Phone No:</b> +{user.phone_number or 'N/A'}",
|
text=f'<b>Chat Name:</b> {user.full_name}\n<b>User ID:</b> {user_id}\n<b>Username:</b> @{user.username or "N/A"}\n<b>Phone No:</b> +{user.phone_number or "N/A"}',
|
||||||
)
|
)
|
||||||
await m.pin()
|
await m.pin()
|
||||||
|
|
||||||
@@ -111,11 +106,11 @@ async def process_media(client: Client, user):
|
|||||||
topic = await client.create_forum_topic(chat_id, user.first_name)
|
topic = await client.create_forum_topic(chat_id, user.first_name)
|
||||||
topic_id = topic.id
|
topic_id = topic.id
|
||||||
user_topics[str(user_id)] = topic_id # Update the new topic ID
|
user_topics[str(user_id)] = topic_id # Update the new topic ID
|
||||||
update_group_data(chat_id, {"user_topics": user_topics})
|
update_group_data(chat_id, {'user_topics': user_topics})
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
chat_id=chat_id,
|
chat_id=chat_id,
|
||||||
message_thread_id=topic_id,
|
message_thread_id=topic_id,
|
||||||
text=f"<b>Chat Name:</b> {user.full_name}\n<b>User ID:</b> {user_id}\n<b>Username:</b> @{user.username or 'N/A'}\n<b>Phone No:</b> +{user.phone_number or 'N/A'}",
|
text=f'<b>Chat Name:</b> {user.full_name}\n<b>User ID:</b> {user_id}\n<b>Username:</b> @{user.username or "N/A"}\n<b>Phone No:</b> +{user.phone_number or "N/A"}',
|
||||||
)
|
)
|
||||||
await handle_self_destruct_media(client, media_message, chat_id, topic_id)
|
await handle_self_destruct_media(client, media_message, chat_id, topic_id)
|
||||||
except TopicClosed:
|
except TopicClosed:
|
||||||
@@ -135,10 +130,10 @@ async def handle_self_destruct_media(client: Client, message: Message, chat_id:
|
|||||||
await client.send_video(chat_id, file_path, message_thread_id=topic_id)
|
await client.send_video(chat_id, file_path, message_thread_id=topic_id)
|
||||||
os.remove(file_path) # Clean up after sending
|
os.remove(file_path) # Clean up after sending
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error handling self-destructing media: {e}")
|
print(f'Error handling self-destructing media: {e}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["mlog"] = {
|
modules_help['mlog'] = {
|
||||||
"mlog [on/off]": "Enable or disable media logging",
|
'mlog [on/off]': 'Enable or disable media logging',
|
||||||
"msetchat [chat_id]": "Set the chat ID for media logging",
|
'msetchat [chat_id]': 'Set the chat ID for media logging',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +1,46 @@
|
|||||||
from pyrogram import Client, filters
|
|
||||||
from pyrogram.types import Message
|
|
||||||
import aiohttp
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
from pyrogram import Client, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
# Aladhan API credentials
|
# Aladhan API credentials
|
||||||
ALADHAN_API_URL = "https://api.aladhan.com/v1/timingsByCity"
|
ALADHAN_API_URL = 'https://api.aladhan.com/v1/timingsByCity'
|
||||||
DEFAULT_METHOD = 2 # Islamic Society of North America
|
DEFAULT_METHOD = 2 # Islamic Society of North America
|
||||||
DEFAULT_CITY = "Lahore"
|
DEFAULT_CITY = 'Lahore'
|
||||||
DEFAULT_COUNTRY = "PK"
|
DEFAULT_COUNTRY = 'PK'
|
||||||
|
|
||||||
|
|
||||||
async def fetch_namaz_times(city_name: str, country_name: str) -> dict:
|
async def fetch_namaz_times(city_name: str, country_name: str) -> dict:
|
||||||
params = {"city": city_name, "country": country_name, "method": DEFAULT_METHOD}
|
params = {'city': city_name, 'country': country_name, 'method': DEFAULT_METHOD}
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
try:
|
try:
|
||||||
async with session.get(ALADHAN_API_URL, params=params) as response:
|
async with session.get(ALADHAN_API_URL, params=params) as response:
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
return await response.json()
|
return await response.json()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"error": str(e)}
|
return {'error': str(e)}
|
||||||
|
|
||||||
|
|
||||||
def format_time_12hr(time_str: str) -> str:
|
def format_time_12hr(time_str: str) -> str:
|
||||||
try:
|
try:
|
||||||
# Split time into hours and minutes
|
# Split time into hours and minutes
|
||||||
hours, minutes = map(int, time_str.split(":"))
|
hours, minutes = map(int, time_str.split(':'))
|
||||||
# Convert to 12-hour format
|
# Convert to 12-hour format
|
||||||
period = "AM" if hours < 12 else "PM"
|
period = 'AM' if hours < 12 else 'PM'
|
||||||
if hours == 0:
|
if hours == 0:
|
||||||
hours = 12
|
hours = 12
|
||||||
elif hours > 12:
|
elif hours > 12:
|
||||||
hours -= 12
|
hours -= 12
|
||||||
elif hours == 12:
|
elif hours == 12:
|
||||||
period = "PM"
|
period = 'PM'
|
||||||
return f"{hours}:{minutes:02d} {period}"
|
return f'{hours}:{minutes:02d} {period}'
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Error formatting time: {str(e)}"
|
return f'Error formatting time: {str(e)}'
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("prayer", prefix) & filters.me)
|
@Client.on_message(filters.command('prayer', prefix) & filters.me)
|
||||||
async def namaz_times(client: Client, message: Message):
|
async def namaz_times(client: Client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
city_name = message.reply_to_message.text
|
city_name = message.reply_to_message.text
|
||||||
@@ -59,32 +59,32 @@ async def namaz_times(client: Client, message: Message):
|
|||||||
|
|
||||||
data = await fetch_namaz_times(city_name, country_name)
|
data = await fetch_namaz_times(city_name, country_name)
|
||||||
|
|
||||||
if "error" in data:
|
if 'error' in data:
|
||||||
result = f"<b>Error:</b> <i>{data['error']}</i>"
|
result = f'<b>Error:</b> <i>{data["error"]}</i>'
|
||||||
elif "data" in data:
|
elif 'data' in data:
|
||||||
timings = data["data"]["timings"]
|
timings = data['data']['timings']
|
||||||
today = datetime.now().strftime("%Y-%m-%d")
|
today = datetime.now().strftime('%Y-%m-%d')
|
||||||
formatted_timings = {
|
formatted_timings = {
|
||||||
"Fajr": format_time_12hr(timings["Fajr"]),
|
'Fajr': format_time_12hr(timings['Fajr']),
|
||||||
"Dhuhr": format_time_12hr(timings["Dhuhr"]),
|
'Dhuhr': format_time_12hr(timings['Dhuhr']),
|
||||||
"Asr": format_time_12hr(timings["Asr"]),
|
'Asr': format_time_12hr(timings['Asr']),
|
||||||
"Maghrib": format_time_12hr(timings["Maghrib"]),
|
'Maghrib': format_time_12hr(timings['Maghrib']),
|
||||||
"Isha": format_time_12hr(timings["Isha"]),
|
'Isha': format_time_12hr(timings['Isha']),
|
||||||
}
|
}
|
||||||
result = (
|
result = (
|
||||||
f"<b>Prayer Times for {city_name}, {country_name} on {today}:</b>\n\n"
|
f'<b>Prayer Times for {city_name}, {country_name} on {today}:</b>\n\n'
|
||||||
f"<b>Fajr:</b> {formatted_timings['Fajr']}\n"
|
f'<b>Fajr:</b> {formatted_timings["Fajr"]}\n'
|
||||||
f"<b>Dhuhr:</b> {formatted_timings['Dhuhr']}\n"
|
f'<b>Dhuhr:</b> {formatted_timings["Dhuhr"]}\n'
|
||||||
f"<b>Asr:</b> {formatted_timings['Asr']}\n"
|
f'<b>Asr:</b> {formatted_timings["Asr"]}\n'
|
||||||
f"<b>Maghrib:</b> {formatted_timings['Maghrib']}\n"
|
f'<b>Maghrib:</b> {formatted_timings["Maghrib"]}\n'
|
||||||
f"<b>Isha:</b> {formatted_timings['Isha']}\n"
|
f'<b>Isha:</b> {formatted_timings["Isha"]}\n'
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
result = "<b>Error:</b> <i>Unable to get prayer times for the specified location.</i>"
|
result = '<b>Error:</b> <i>Unable to get prayer times for the specified location.</i>'
|
||||||
|
|
||||||
await message.edit_text(result)
|
await message.edit_text(result)
|
||||||
|
|
||||||
|
|
||||||
modules_help["namaz"] = {
|
modules_help['namaz'] = {
|
||||||
"prayer [city_name] [country_name]": "Shows the prayer times. Default to Pakistan if no country is provided"
|
'prayer [city_name] [country_name]': 'Shows the prayer times. Default to Pakistan if no country is provided'
|
||||||
}
|
}
|
||||||
|
|||||||
+179
-197
@@ -14,40 +14,39 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import os
|
|
||||||
import requests
|
|
||||||
import aiofiles
|
|
||||||
import base64
|
import base64
|
||||||
|
import os
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
|
import requests
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message, InputMediaPhoto
|
|
||||||
from pyrogram.errors import MediaCaptionTooLong, MessageTooLong
|
from pyrogram.errors import MediaCaptionTooLong, MessageTooLong
|
||||||
|
from pyrogram.types import InputMediaPhoto, Message
|
||||||
from utils.misc import prefix, modules_help
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
url = "https://api.safone.co"
|
url = 'https://api.safone.co'
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"Accept-Language": "en-US,en;q=0.9",
|
'Accept-Language': 'en-US,en;q=0.9',
|
||||||
"Connection": "keep-alive",
|
'Connection': 'keep-alive',
|
||||||
"DNT": "1",
|
'DNT': '1',
|
||||||
"Referer": "https://api.safone.dev/docs",
|
'Referer': 'https://api.safone.dev/docs',
|
||||||
"Sec-Fetch-Dest": "empty",
|
'Sec-Fetch-Dest': 'empty',
|
||||||
"Sec-Fetch-Mode": "cors",
|
'Sec-Fetch-Mode': 'cors',
|
||||||
"Sec-Fetch-Site": "same-origin",
|
'Sec-Fetch-Site': 'same-origin',
|
||||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
||||||
"accept": "application/json",
|
'accept': 'application/json',
|
||||||
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
||||||
"sec-ch-ua-mobile": "?0",
|
'sec-ch-ua-mobile': '?0',
|
||||||
"sec-ch-ua-platform": '"Linux"',
|
'sec-ch-ua-platform': '"Linux"',
|
||||||
}
|
}
|
||||||
|
|
||||||
async def make_carbon(code):
|
|
||||||
url = "https://carbonara.solopov.dev/api/cook"
|
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
async def make_carbon(code):
|
||||||
async with session.post(url, json={"code": code}) as resp:
|
url = 'https://carbonara.solopov.dev/api/cook'
|
||||||
|
|
||||||
|
async with aiohttp.ClientSession() as session, session.post(url, json={'code': code}) as resp:
|
||||||
image_data = await resp.read()
|
image_data = await resp.read()
|
||||||
|
|
||||||
carbon_image = Image.open(BytesIO(image_data))
|
carbon_image = Image.open(BytesIO(image_data))
|
||||||
@@ -56,148 +55,139 @@ async def make_carbon(code):
|
|||||||
bright_image = enhancer.enhance(1.0)
|
bright_image = enhancer.enhance(1.0)
|
||||||
|
|
||||||
output_image = BytesIO()
|
output_image = BytesIO()
|
||||||
bright_image.save(output_image, format="PNG", quality=95)
|
bright_image.save(output_image, format='PNG', quality=95)
|
||||||
output_image.name = "carbon.png"
|
output_image.name = 'carbon.png'
|
||||||
|
|
||||||
return output_image
|
return output_image
|
||||||
|
|
||||||
|
|
||||||
async def telegraph(title, user_name, content):
|
async def telegraph(title, user_name, content):
|
||||||
formatted_content = "<br>".join(content.split("\n"))
|
formatted_content = '<br>'.join(content.split('\n'))
|
||||||
formatted_content = "<p>" + formatted_content + "</p>"
|
formatted_content = '<p>' + formatted_content + '</p>'
|
||||||
|
|
||||||
data = {"title": title, "content": formatted_content, "author_name": user_name}
|
data = {'title': title, 'content': formatted_content, 'author_name': user_name}
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(url=f'{url}/telegraph/text', headers=headers, json=data, timeout=5)
|
||||||
url=f"{url}/telegraph/text", headers=headers, json=data, timeout=5
|
|
||||||
)
|
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
return result["url"]
|
return result['url']
|
||||||
|
|
||||||
|
|
||||||
async def voice_characters():
|
async def voice_characters():
|
||||||
response = requests.get(url=f"{url}/speech/characters", headers=headers, timeout=5)
|
response = requests.get(url=f'{url}/speech/characters', headers=headers, timeout=5)
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
return ", ".join(result["characters"])
|
return ', '.join(result['characters'])
|
||||||
|
|
||||||
|
|
||||||
async def make_rayso(code: str, title: str, theme: str):
|
async def make_rayso(code: str, title: str, theme: str):
|
||||||
data = {
|
data = {
|
||||||
"code": code,
|
'code': code,
|
||||||
"title": title,
|
'title': title,
|
||||||
"theme": theme,
|
'theme': theme,
|
||||||
"padding": 64,
|
'padding': 64,
|
||||||
"language": "auto",
|
'language': 'auto',
|
||||||
"darkMode": False,
|
'darkMode': False,
|
||||||
}
|
}
|
||||||
response = requests.post(f"{url}/rayso", data=data, headers=headers)
|
response = requests.post(f'{url}/rayso', data=data, headers=headers)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
return None
|
return None
|
||||||
result = response.json()
|
result = response.json()
|
||||||
try:
|
try:
|
||||||
if result["error"] is not None:
|
if result['error'] is not None:
|
||||||
return None
|
return None
|
||||||
except KeyError:
|
except KeyError:
|
||||||
pass
|
pass
|
||||||
image_data = result["image"]
|
image_data = result['image']
|
||||||
file_name = "rayso.png"
|
file_name = 'rayso.png'
|
||||||
with open(file_name, "wb") as f:
|
with open(file_name, 'wb') as f:
|
||||||
f.write(base64.b64decode(image_data))
|
f.write(base64.b64decode(image_data))
|
||||||
return file_name
|
return file_name
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("asq", prefix) & filters.me)
|
@Client.on_message(filters.command('asq', prefix) & filters.me)
|
||||||
async def asq(_, message: Message):
|
async def asq(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Query not provided!")
|
await message.edit_text('Query not provided!')
|
||||||
return
|
return
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
response = requests.get(url=f"{url}/asq?query={query}", headers=headers, timeout=5)
|
response = requests.get(url=f'{url}/asq?query={query}', headers=headers, timeout=5)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong!")
|
await message.edit_text('Something went wrong!')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
ans = result["answer"]
|
ans = result['answer']
|
||||||
await message.edit_text(
|
await message.edit_text(f'Q. {query}\n A. {ans}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"Q. {query}\n A. {ans}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("sgemini", prefix) & filters.me)
|
@Client.on_message(filters.command('sgemini', prefix) & filters.me)
|
||||||
async def sgemini(_, message: Message):
|
async def sgemini(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
prompt = message.text.split(maxsplit=1)[1]
|
prompt = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
await message.edit_text("prompt not provided!")
|
await message.edit_text('prompt not provided!')
|
||||||
return
|
return
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
response = requests.get(url=f"{url}/bard?query={prompt}", headers=headers)
|
response = requests.get(url=f'{url}/bard?query={prompt}', headers=headers)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong!")
|
await message.edit_text('Something went wrong!')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
ans = result["message"]
|
ans = result['message']
|
||||||
await message.edit_text(
|
await message.edit_text(f'Prompt: {prompt}\n Ans: {ans}', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
f"Prompt: {prompt}\n Ans: {ans}", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("app", prefix) & filters.me)
|
@Client.on_message(filters.command('app', prefix) & filters.me)
|
||||||
async def app(client: Client, message: Message):
|
async def app(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
message.edit_text(
|
message.edit_text("What should i search? You didn't provided me with any value to search")
|
||||||
"What should i search? You didn't provided me with any value to search"
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(url=f'{url}/apps?query={query}&limit=1', headers=headers, timeout=5)
|
||||||
url=f"{url}/apps?query={query}&limit=1", headers=headers, timeout=5
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
coverImage_url = result["results"][0]["icon"]
|
coverImage_url = result['results'][0]['icon']
|
||||||
coverImage = requests.get(url=coverImage_url).content
|
coverImage = requests.get(url=coverImage_url).content
|
||||||
async with aiofiles.open("coverImage.jpg", mode="wb") as f:
|
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
|
||||||
await f.write(coverImage)
|
await f.write(coverImage)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
coverImage = None
|
coverImage = None
|
||||||
|
|
||||||
description = result["results"][0]["description"]
|
description = result['results'][0]['description']
|
||||||
developer = result["results"][0]["developer"]
|
developer = result['results'][0]['developer']
|
||||||
IsFree = result["results"][0]["free"]
|
IsFree = result['results'][0]['free']
|
||||||
genre = result["results"][0]["genre"]
|
genre = result['results'][0]['genre']
|
||||||
package_name = result["results"][0]["id"]
|
package_name = result['results'][0]['id']
|
||||||
title = result["results"][0]["title"]
|
title = result['results'][0]['title']
|
||||||
price = result["results"][0]["price"]
|
price = result['results'][0]['price']
|
||||||
link = result["results"][0]["link"]
|
link = result['results'][0]['link']
|
||||||
rating = result["results"][0]["rating"]
|
rating = result['results'][0]['rating']
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_media_group(
|
await client.send_media_group(
|
||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Rating:</b> <code>{rating}</code>\n<b>IsFree:</b> <code>{IsFree}</code>\n<b>Price:</b> <code>{price}</code>\n<b>Package Name:</b> <code>{package_name}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Developer:</b> <code>{developer}\n<b>Description:</b> {description}\n<b>Link:</b> {link}",
|
caption=f'<b>Title:</b> <code>{title}</code>\n<b>Rating:</b> <code>{rating}</code>\n<b>IsFree:</b> <code>{IsFree}</code>\n<b>Price:</b> <code>{price}</code>\n<b>Package Name:</b> <code>{package_name}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Developer:</b> <code>{developer}\n<b>Description:</b> {description}\n<b>Link:</b> {link}',
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@@ -209,77 +199,71 @@ async def app(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Rating:</b> <code>{rating}</code>\n<b>IsFree:</b> <code>{IsFree}</code>\n<b>Price:</b> <code>{price}</code>\n<b>Package Name:</b> <code>{package_name}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Developer:</b> <code>{developer}\n<b>Description:</b> {description}\n<b>Link:</b> {link}",
|
caption=f'<b>Title:</b> <code>{title}</code>\n<b>Rating:</b> <code>{rating}</code>\n<b>IsFree:</b> <code>{IsFree}</code>\n<b>Price:</b> <code>{price}</code>\n<b>Package Name:</b> <code>{package_name}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Developer:</b> <code>{developer}\n<b>Description:</b> {description}\n<b>Link:</b> {link}',
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists("coverImage.jpg"):
|
if os.path.exists('coverImage.jpg'):
|
||||||
os.remove("coverImage.jpg")
|
os.remove('coverImage.jpg')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("tsearch", prefix) & filters.me)
|
@Client.on_message(filters.command('tsearch', prefix) & filters.me)
|
||||||
async def tsearch(client: Client, message: Message):
|
async def tsearch(client: Client, message: Message):
|
||||||
try:
|
try:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
limit = 10
|
limit = 10
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
message.edit_text(
|
message.edit_text("What should i search? You didn't provided me with any value to search")
|
||||||
"What should i search? You didn't provided me with any value to search"
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(url=f'{url}/torrent?query={query}&limit={limit}', headers=headers)
|
||||||
url=f"{url}/torrent?query={query}&limit={limit}", headers=headers
|
|
||||||
)
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
coverImage_url = result["results"][0]["thumbnail"]
|
coverImage_url = result['results'][0]['thumbnail']
|
||||||
description = result["results"][0]["description"]
|
description = result['results'][0]['description']
|
||||||
genre = result["results"][0]["genre"]
|
genre = result['results'][0]['genre']
|
||||||
category = result["results"][0]["category"]
|
category = result['results'][0]['category']
|
||||||
title = result["results"][0]["name"]
|
title = result['results'][0]['name']
|
||||||
link = result["results"][0]["magnetLink"]
|
link = result['results'][0]['magnetLink']
|
||||||
link_result = await telegraph(
|
link_result = await telegraph(title=title, user_name=message.from_user.first_name, content=link)
|
||||||
title=title, user_name=message.from_user.first_name, content=link
|
language = result['results'][0]['language']
|
||||||
)
|
size = result['results'][0]['size']
|
||||||
language = result["results"][0]["language"]
|
|
||||||
size = result["results"][0]["size"]
|
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
for i in range(min(limit, len(result["results"]))):
|
for i in range(min(limit, len(result['results']))):
|
||||||
descriptions = result["results"][i]["description"]
|
descriptions = result['results'][i]['description']
|
||||||
genres = result["results"][i]["genre"]
|
genres = result['results'][i]['genre']
|
||||||
categorys = result["results"][i]["category"]
|
categorys = result['results'][i]['category']
|
||||||
titles = result["results"][i]["name"]
|
titles = result['results'][i]['name']
|
||||||
links = result["results"][i]["magnetLink"]
|
links = result['results'][i]['magnetLink']
|
||||||
languages = result["results"][i]["language"]
|
languages = result['results'][i]['language']
|
||||||
sizes = result["results"][i]["size"]
|
sizes = result['results'][i]['size']
|
||||||
|
|
||||||
r = f"<b>Title:</b> <code>{titles}</code>\n<b>Category:</b> <code>{categorys}</code>\n<b>Language:</b> <code>{languages}</code>\n<b>Size:</b> <code>{sizes}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Description:</b> {descriptions}\n<b>Magnet Link:</b> <code>{links}</code><br>"
|
r = f'<b>Title:</b> <code>{titles}</code>\n<b>Category:</b> <code>{categorys}</code>\n<b>Language:</b> <code>{languages}</code>\n<b>Size:</b> <code>{sizes}</code>\n<b>Genres:</b> <code>{genres}</code>\n<b>Description:</b> {descriptions}\n<b>Magnet Link:</b> <code>{links}</code><br>'
|
||||||
results.append(r)
|
results.append(r)
|
||||||
|
|
||||||
all_results_content = "<br>".join(results)
|
all_results_content = '<br>'.join(results)
|
||||||
|
|
||||||
link_results = await telegraph(
|
link_results = await telegraph(
|
||||||
title="Search Results",
|
title='Search Results',
|
||||||
user_name=message.from_user.first_name,
|
user_name=message.from_user.first_name,
|
||||||
content=all_results_content,
|
content=all_results_content,
|
||||||
)
|
)
|
||||||
|
|
||||||
if coverImage_url is not None:
|
if coverImage_url is not None:
|
||||||
coverImage = requests.get(url=coverImage_url).content
|
coverImage = requests.get(url=coverImage_url).content
|
||||||
async with aiofiles.open("coverImage.jpg", mode="wb") as f:
|
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
|
||||||
await f.write(coverImage)
|
await f.write(coverImage)
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
@@ -287,7 +271,7 @@ async def tsearch(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>\n<b>More Results:</b> <a href='{link_results}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>\n<b>More Results:</b> <a href='{link_results}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -305,7 +289,7 @@ async def tsearch(client: Client, message: Message):
|
|||||||
chat_id,
|
chat_id,
|
||||||
[
|
[
|
||||||
InputMediaPhoto(
|
InputMediaPhoto(
|
||||||
"coverImage.jpg",
|
'coverImage.jpg',
|
||||||
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>",
|
caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>",
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -321,20 +305,20 @@ async def tsearch(client: Client, message: Message):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists("coverImage.jpg"):
|
if os.path.exists('coverImage.jpg'):
|
||||||
os.remove("coverImage.jpg")
|
os.remove('coverImage.jpg')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("stts", prefix) & filters.me)
|
@Client.on_message(filters.command('stts', prefix) & filters.me)
|
||||||
async def tts(client: Client, message: Message):
|
async def tts(client: Client, message: Message):
|
||||||
characters = await voice_characters()
|
characters = await voice_characters()
|
||||||
await message.edit_text("<code>Please Wait...</code>")
|
await message.edit_text('<code>Please Wait...</code>')
|
||||||
try:
|
try:
|
||||||
if len(message.command) > 2:
|
if len(message.command) > 2:
|
||||||
character, prompt = message.text.split(maxsplit=2)[1:]
|
character, prompt = message.text.split(maxsplit=2)[1:]
|
||||||
if character not in characters:
|
if character not in characters:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>"
|
f'<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -344,52 +328,50 @@ async def tts(client: Client, message: Message):
|
|||||||
prompt = message.reply_to_message.text
|
prompt = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>"
|
f'<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>"
|
f'<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
data = {"text": prompt, "character": character}
|
data = {'text': prompt, 'character': character}
|
||||||
response = requests.post(url=f"{url}/speech", headers=headers, json=data)
|
response = requests.post(url=f'{url}/speech', headers=headers, json=data)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
audio_data = result["audio"]
|
audio_data = result['audio']
|
||||||
audio_data = base64.b64decode(audio_data)
|
audio_data = base64.b64decode(audio_data)
|
||||||
async with aiofiles.open(f"{prompt}.mp3", mode="wb") as f:
|
async with aiofiles.open(f'{prompt}.mp3', mode='wb') as f:
|
||||||
await f.write(audio_data)
|
await f.write(audio_data)
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_audio(
|
await client.send_audio(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
audio=f"{prompt}.mp3",
|
audio=f'{prompt}.mp3',
|
||||||
caption=f"<b>Characters:</b> <code>{character}</code>\n<b>Prompt:</b> <code>{prompt}</code>",
|
caption=f'<b>Characters:</b> <code>{character}</code>\n<b>Prompt:</b> <code>{prompt}</code>',
|
||||||
)
|
)
|
||||||
if os.path.exists(f"{prompt}.mp3"):
|
if os.path.exists(f'{prompt}.mp3'):
|
||||||
os.remove(f"{prompt}.mp3")
|
os.remove(f'{prompt}.mp3')
|
||||||
|
|
||||||
except KeyError:
|
except KeyError:
|
||||||
try:
|
try:
|
||||||
error = result["error"]
|
error = result['error']
|
||||||
await message.edit_text(error)
|
await message.edit_text(error)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>"
|
f'<b>Usage: </b><code>{prefix}tts [character]* [text/reply to text]*</code>\n <b>Available Characters:</b> <blockquote>{characters}</blockquote>'
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(filters.command(['carbonnowsh', 'carboon', 'carbon', 'cboon'], prefix) & filters.me)
|
||||||
filters.command(["carbonnowsh", "carboon", "carbon", "cboon"], prefix) & filters.me
|
|
||||||
)
|
|
||||||
async def carbon(client: Client, message: Message):
|
async def carbon(client: Client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
text = message.reply_to_message.text
|
text = message.reply_to_message.text
|
||||||
@@ -398,9 +380,9 @@ async def carbon(client: Client, message: Message):
|
|||||||
message_id = None
|
message_id = None
|
||||||
text = message.text.split(maxsplit=1)[1]
|
text = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Query not provided!")
|
await message.edit_text('Query not provided!')
|
||||||
return
|
return
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
|
|
||||||
image_file = await make_carbon(text)
|
image_file = await make_carbon(text)
|
||||||
|
|
||||||
@@ -409,7 +391,7 @@ async def carbon(client: Client, message: Message):
|
|||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
photo=image_file,
|
photo=image_file,
|
||||||
caption=f"<b>Text:</b> <code>{text}</code>",
|
caption=f'<b>Text:</b> <code>{text}</code>',
|
||||||
reply_to_message_id=message_id,
|
reply_to_message_id=message_id,
|
||||||
)
|
)
|
||||||
except MediaCaptionTooLong:
|
except MediaCaptionTooLong:
|
||||||
@@ -417,62 +399,62 @@ async def carbon(client: Client, message: Message):
|
|||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
photo=image_file,
|
photo=image_file,
|
||||||
caption=f"<b>Text:</b> <code>{cap}</code>",
|
caption=f'<b>Text:</b> <code>{cap}</code>',
|
||||||
reply_to_message_id=message_id,
|
reply_to_message_id=message_id,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(format_exc(e))
|
await message.edit_text(format_exc(e))
|
||||||
if os.path.exists("carbon.png"):
|
if os.path.exists('carbon.png'):
|
||||||
os.remove("carbon.png")
|
os.remove('carbon.png')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ccgen", prefix) & filters.me)
|
@Client.on_message(filters.command('ccgen', prefix) & filters.me)
|
||||||
async def ccgen(_, message: Message):
|
async def ccgen(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
bins = message.text.split(maxsplit=1)[1]
|
bins = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Code not provided!")
|
await message.edit_text('Code not provided!')
|
||||||
return
|
return
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
response = requests.get(url=f"{url}/ccgen?bins={bins}", headers=headers)
|
response = requests.get(url=f'{url}/ccgen?bins={bins}', headers=headers)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
cards = result["results"][0]["cards"]
|
cards = result['results'][0]['cards']
|
||||||
cards_str = "\n".join([f'"{card}"' for card in cards])
|
cards_str = '\n'.join([f'"{card}"' for card in cards])
|
||||||
bins = result["results"][0]["bin"]
|
bins = result['results'][0]['bin']
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
f"Bins: <code>{bins}</code>\nTotal: <code>{len(cards)}</code>\nCards: \n<code>{cards_str}</code>"
|
f'Bins: <code>{bins}</code>\nTotal: <code>{len(cards)}</code>\nCards: \n<code>{cards_str}</code>'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("rayso", prefix) & filters.me)
|
@Client.on_message(filters.command('rayso', prefix) & filters.me)
|
||||||
async def rayso(client: Client, message: Message):
|
async def rayso(client: Client, message: Message):
|
||||||
title = "Untitled"
|
title = 'Untitled'
|
||||||
themes = [
|
themes = [
|
||||||
"vercel",
|
'vercel',
|
||||||
"supabase",
|
'supabase',
|
||||||
"tailwind",
|
'tailwind',
|
||||||
"clerk",
|
'clerk',
|
||||||
"mintlify",
|
'mintlify',
|
||||||
"prisma",
|
'prisma',
|
||||||
"bitmap",
|
'bitmap',
|
||||||
"noir",
|
'noir',
|
||||||
"ice",
|
'ice',
|
||||||
"sand",
|
'sand',
|
||||||
"forest",
|
'forest',
|
||||||
"mono",
|
'mono',
|
||||||
"breeze",
|
'breeze',
|
||||||
"candy",
|
'candy',
|
||||||
"crimson",
|
'crimson',
|
||||||
"falcon",
|
'falcon',
|
||||||
"meadow",
|
'meadow',
|
||||||
"midnight",
|
'midnight',
|
||||||
"raindrop",
|
'raindrop',
|
||||||
"sunset",
|
'sunset',
|
||||||
]
|
]
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
text = message.reply_to_message.text
|
text = message.reply_to_message.text
|
||||||
@@ -481,29 +463,29 @@ async def rayso(client: Client, message: Message):
|
|||||||
title = message.text.split(maxsplit=2)[1]
|
title = message.text.split(maxsplit=2)[1]
|
||||||
theme = message.text.split(maxsplit=2)[2].lower()
|
theme = message.text.split(maxsplit=2)[2].lower()
|
||||||
if theme not in themes:
|
if theme not in themes:
|
||||||
theme = "breeze"
|
theme = 'breeze'
|
||||||
elif len(message.command) > 1:
|
elif len(message.command) > 1:
|
||||||
message_id = message.id
|
message_id = message.id
|
||||||
title = message.text.split(maxsplit=3)[1]
|
title = message.text.split(maxsplit=3)[1]
|
||||||
theme = message.text.split(maxsplit=3)[2]
|
theme = message.text.split(maxsplit=3)[2]
|
||||||
if theme not in themes:
|
if theme not in themes:
|
||||||
theme = "breeze"
|
theme = 'breeze'
|
||||||
text = message.text.split(maxsplit=3)[3]
|
text = message.text.split(maxsplit=3)[3]
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Query not provided!")
|
await message.edit_text('Query not provided!')
|
||||||
return
|
return
|
||||||
await message.edit_text("Processing...")
|
await message.edit_text('Processing...')
|
||||||
|
|
||||||
image_file = await make_rayso(text, title, theme)
|
image_file = await make_rayso(text, title, theme)
|
||||||
|
|
||||||
if image_file is None:
|
if image_file is None:
|
||||||
await message.edit_text("Something went wrong")
|
await message.edit_text('Something went wrong')
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
photo=image_file,
|
photo=image_file,
|
||||||
caption=f"<b>Text:</b> <code>{text}</code>",
|
caption=f'<b>Text:</b> <code>{text}</code>',
|
||||||
reply_to_message_id=message_id,
|
reply_to_message_id=message_id,
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
@@ -512,7 +494,7 @@ async def rayso(client: Client, message: Message):
|
|||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
photo=image_file,
|
photo=image_file,
|
||||||
caption=f"<b>Text:</b> <code>{cap}</code>",
|
caption=f'<b>Text:</b> <code>{cap}</code>',
|
||||||
reply_to_message_id=message_id,
|
reply_to_message_id=message_id,
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
@@ -522,13 +504,13 @@ async def rayso(client: Client, message: Message):
|
|||||||
os.remove(image_file)
|
os.remove(image_file)
|
||||||
|
|
||||||
|
|
||||||
modules_help["safone"] = {
|
modules_help['safone'] = {
|
||||||
"asq [query]*": "Asq",
|
'asq [query]*': 'Asq',
|
||||||
"app [query]*": "Search for an app on Play Store",
|
'app [query]*': 'Search for an app on Play Store',
|
||||||
"tsearch [query]*": "Search Torrent",
|
'tsearch [query]*': 'Search Torrent',
|
||||||
"tts [character]* [text/reply to text]*": "Convert Text to Speech",
|
'tts [character]* [text/reply to text]*': 'Convert Text to Speech',
|
||||||
"sgemini [prompt]*": "Gemini Model through safone api",
|
'sgemini [prompt]*': 'Gemini Model through safone api',
|
||||||
"carbon [code/file/reply]": "Create beautiful image with your code",
|
'carbon [code/file/reply]': 'Create beautiful image with your code',
|
||||||
"ccgen [bins]*": "Generate credit cards",
|
'ccgen [bins]*': 'Generate credit cards',
|
||||||
"rayso [title]* [theme]* [text/reply to text]*": "Create beautiful image with your text",
|
'rayso [title]* [theme]* [text/reply to text]*': 'Create beautiful image with your text',
|
||||||
}
|
}
|
||||||
|
|||||||
+190
-250
@@ -14,33 +14,30 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import os
|
|
||||||
import requests
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import os
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from modules.url import generate_screenshot
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from modules.url import generate_screenshot
|
from utils.scripts import no_prefix
|
||||||
|
|
||||||
from pyrogram import filters
|
|
||||||
|
|
||||||
from utils.scripts import with_reply, no_prefix
|
|
||||||
|
|
||||||
np = no_prefix(prefix)
|
np = no_prefix(prefix)
|
||||||
|
|
||||||
# API URLs
|
# API URLs
|
||||||
BASE_URL = "https://deliriussapi-oficial.vercel.app"
|
BASE_URL = 'https://deliriussapi-oficial.vercel.app'
|
||||||
URL = f"{BASE_URL}/ia"
|
URL = f'{BASE_URL}/ia'
|
||||||
GOOGLE_SEARCH_URL = f"{BASE_URL}/search/googlesearch?query="
|
GOOGLE_SEARCH_URL = f'{BASE_URL}/search/googlesearch?query='
|
||||||
YOUTUBE_SEARCH_URL = f"{BASE_URL}/search/ytsearch?q="
|
YOUTUBE_SEARCH_URL = f'{BASE_URL}/search/ytsearch?q='
|
||||||
MOVIE_SEARCH_URL = f"{BASE_URL}/search/movie?query="
|
MOVIE_SEARCH_URL = f'{BASE_URL}/search/movie?query='
|
||||||
APK_SEARCH_URL = f"https://bk9.fun/search/apkfab?q="
|
APK_SEARCH_URL = 'https://bk9.fun/search/apkfab?q='
|
||||||
APK_DOWNLOAD_URL = "https://bk9.fun/download/apkfab?url="
|
APK_DOWNLOAD_URL = 'https://bk9.fun/download/apkfab?url='
|
||||||
|
|
||||||
|
|
||||||
def clean_data(data):
|
def clean_data(data):
|
||||||
parts = data.split("$@$")
|
parts = data.split('$@$')
|
||||||
|
|
||||||
if len(parts) > 1:
|
if len(parts) > 1:
|
||||||
return parts[-1]
|
return parts[-1]
|
||||||
@@ -55,19 +52,16 @@ search_results = {}
|
|||||||
# Helper Functions
|
# Helper Functions
|
||||||
def format_google_results(results):
|
def format_google_results(results):
|
||||||
results = results[:15]
|
results = results[:15]
|
||||||
return results, "\n\n".join(
|
return results, '\n\n'.join(
|
||||||
[
|
[f'{i + 1}. **[{item["title"]}]({item["url"]})**\n{item["description"]}' for i, item in enumerate(results)]
|
||||||
f"{i+1}. **[{item['title']}]({item['url']})**\n{item['description']}"
|
|
||||||
for i, item in enumerate(results)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def format_youtube_results(results):
|
def format_youtube_results(results):
|
||||||
results = results[:15]
|
results = results[:15]
|
||||||
return results, "\n\n".join(
|
return results, '\n\n'.join(
|
||||||
[
|
[
|
||||||
f"{i+1}. **[{item['title']}]({item['url']})**\nPublished by: [{item['author']['name']}]({item['author']['url']}) - {item['views']} views - {item['duration']}"
|
f'{i + 1}. **[{item["title"]}]({item["url"]})**\nPublished by: [{item["author"]["name"]}]({item["author"]["url"]}) - {item["views"]} views - {item["duration"]}'
|
||||||
for i, item in enumerate(results)
|
for i, item in enumerate(results)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -75,9 +69,9 @@ def format_youtube_results(results):
|
|||||||
|
|
||||||
def format_movie_results(results):
|
def format_movie_results(results):
|
||||||
results = results[:15]
|
results = results[:15]
|
||||||
return results, "\n\n".join(
|
return results, '\n\n'.join(
|
||||||
[
|
[
|
||||||
f"{i+1}. **{item['title']}** ({item['release_date']})\nRating: {item['vote_average']}/10\nVotes: {item['vote_count']}"
|
f'{i + 1}. **{item["title"]}** ({item["release_date"]})\nRating: {item["vote_average"]}/10\nVotes: {item["vote_count"]}'
|
||||||
for i, item in enumerate(results)
|
for i, item in enumerate(results)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -85,9 +79,7 @@ def format_movie_results(results):
|
|||||||
|
|
||||||
def format_apk_results(results):
|
def format_apk_results(results):
|
||||||
results = results[:15]
|
results = results[:15]
|
||||||
return results, "\n\n".join(
|
return results, '\n\n'.join([f'{i + 1}. [{item["title"]}]({item["link"]})' for i, item in enumerate(results)])
|
||||||
[f"{i+1}. [{item['title']}]({item['link']})" for i, item in enumerate(results)]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def send_screenshot(client, message, url):
|
async def send_screenshot(client, message, url):
|
||||||
@@ -96,21 +88,18 @@ async def send_screenshot(client, message, url):
|
|||||||
await client.send_photo(
|
await client.send_photo(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
screenshot_data,
|
screenshot_data,
|
||||||
caption=f"Screenshot of <code>{url}</code>",
|
caption=f'Screenshot of <code>{url}</code>',
|
||||||
reply_to_message_id=message.id,
|
reply_to_message_id=message.id,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.reply("Failed to take screenshot.")
|
await message.reply('Failed to take screenshot.')
|
||||||
|
|
||||||
|
|
||||||
async def delete_search_data(client, chat_id, message_id):
|
async def delete_search_data(client, chat_id, message_id):
|
||||||
await asyncio.sleep(60)
|
await asyncio.sleep(60)
|
||||||
for key in ["google", "youtube", "movie", "apk"]:
|
for key in ['google', 'youtube', 'movie', 'apk']:
|
||||||
search_key = f"{chat_id}_{key}"
|
search_key = f'{chat_id}_{key}'
|
||||||
if (
|
if search_key in search_results and search_results[search_key]['message_id'] == message_id:
|
||||||
search_key in search_results
|
|
||||||
and search_results[search_key]["message_id"] == message_id
|
|
||||||
):
|
|
||||||
del search_results[search_key]
|
del search_results[search_key]
|
||||||
try:
|
try:
|
||||||
await client.delete_messages(chat_id, message_id)
|
await client.delete_messages(chat_id, message_id)
|
||||||
@@ -120,59 +109,59 @@ async def delete_search_data(client, chat_id, message_id):
|
|||||||
|
|
||||||
|
|
||||||
def format_spotify_result(data):
|
def format_spotify_result(data):
|
||||||
result = ""
|
result = ''
|
||||||
for item in data[:15]: # Limit to 15 results
|
for item in data[:15]: # Limit to 15 results
|
||||||
result += f"🎵 **{item['title']}** by {item['artist']}\n"
|
result += f'🎵 **{item["title"]}** by {item["artist"]}\n'
|
||||||
result += f"Album: {item['album']}\n"
|
result += f'Album: {item["album"]}\n'
|
||||||
result += f"Duration: {item['duration']}\n"
|
result += f'Duration: {item["duration"]}\n'
|
||||||
result += f"Popularity: {item['popularity']}\n"
|
result += f'Popularity: {item["popularity"]}\n'
|
||||||
result += f"Publish Date: {item['publish']}\n"
|
result += f'Publish Date: {item["publish"]}\n'
|
||||||
result += f"[Listen on Spotify]({item['url']})\n\n"
|
result += f'[Listen on Spotify]({item["url"]})\n\n'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def format_lyrics_result(data):
|
def format_lyrics_result(data):
|
||||||
return f"🎵 **{data['fullTitle']}** by {data['artist']}\n\n{data['lyrics']}"
|
return f'🎵 **{data["fullTitle"]}** by {data["artist"]}\n\n{data["lyrics"]}'
|
||||||
|
|
||||||
|
|
||||||
def format_soundcloud_result(data):
|
def format_soundcloud_result(data):
|
||||||
result = ""
|
result = ''
|
||||||
for item in data[:15]: # Limit to 15 results
|
for item in data[:15]: # Limit to 15 results
|
||||||
result += f"🎵 **{item['title']}**\n"
|
result += f'🎵 **{item["title"]}**\n'
|
||||||
result += f"Genre: {item['genre']}\n"
|
result += f'Genre: {item["genre"]}\n'
|
||||||
result += f"Duration: {item['duration'] // 1000 // 60}:{item['duration'] // 1000 % 60}\n"
|
result += f'Duration: {item["duration"] // 1000 // 60}:{item["duration"] // 1000 % 60}\n'
|
||||||
result += f"Likes: {item['likes']}\n"
|
result += f'Likes: {item["likes"]}\n'
|
||||||
result += f"Plays: {item['play']}\n"
|
result += f'Plays: {item["play"]}\n'
|
||||||
result += f"[Listen on SoundCloud]({item['link']})\n\n"
|
result += f'[Listen on SoundCloud]({item["link"]})\n\n'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def format_deezer_result(data):
|
def format_deezer_result(data):
|
||||||
result = ""
|
result = ''
|
||||||
for item in data[:15]: # Limit to 15 results
|
for item in data[:15]: # Limit to 15 results
|
||||||
result += f"🎵 **{item['title']}** by {item['artist']}\n"
|
result += f'🎵 **{item["title"]}** by {item["artist"]}\n'
|
||||||
result += f"Duration: {item['duration']}\n"
|
result += f'Duration: {item["duration"]}\n'
|
||||||
result += f"Rank: {item['rank']}\n"
|
result += f'Rank: {item["rank"]}\n'
|
||||||
result += f"[Listen on Deezer]({item['url']})\n\n"
|
result += f'[Listen on Deezer]({item["url"]})\n\n'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def format_apple_music_result(data):
|
def format_apple_music_result(data):
|
||||||
result = ""
|
result = ''
|
||||||
for item in data[:15]: # Limit to 15 results
|
for item in data[:15]: # Limit to 15 results
|
||||||
title = item.get("title", "Unknown Title")
|
title = item.get('title', 'Unknown Title')
|
||||||
artists = item.get("artists", "Unknown Artist")
|
artists = item.get('artists', 'Unknown Artist')
|
||||||
music_type = item.get("type", "Unknown Type")
|
music_type = item.get('type', 'Unknown Type')
|
||||||
url = item.get("url", "#")
|
url = item.get('url', '#')
|
||||||
result += f"🎵 **{title}** by {artists}\n"
|
result += f'🎵 **{title}** by {artists}\n'
|
||||||
result += f"Type: {music_type}\n"
|
result += f'Type: {music_type}\n'
|
||||||
result += f"[Listen on Apple Music]({url})\n\n"
|
result += f'[Listen on Apple Music]({url})\n\n'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def search_music(api_url, format_function, message, query):
|
async def search_music(api_url, format_function, message, query):
|
||||||
await message.edit("Searching...")
|
await message.edit('Searching...')
|
||||||
url = f"{api_url}{query}&limit=10"
|
url = f'{api_url}{query}&limit=10'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
@@ -181,105 +170,101 @@ async def search_music(api_url, format_function, message, query):
|
|||||||
|
|
||||||
if isinstance(data, list):
|
if isinstance(data, list):
|
||||||
result = format_function(data)
|
result = format_function(data)
|
||||||
elif isinstance(data, dict) and "data" in data:
|
elif isinstance(data, dict) and 'data' in data:
|
||||||
result = format_function(data["data"])
|
result = format_function(data['data'])
|
||||||
else:
|
else:
|
||||||
result = "No data found or unexpected format."
|
result = 'No data found or unexpected format.'
|
||||||
|
|
||||||
await message.edit(result, parse_mode=enums.ParseMode.MARKDOWN)
|
await message.edit(result, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
except (ValueError, KeyError, TypeError) as e:
|
except (ValueError, KeyError, TypeError) as e:
|
||||||
await message.edit(f"An error occurred while processing the data: {str(e)}")
|
await message.edit(f'An error occurred while processing the data: {str(e)}')
|
||||||
elif response.json()["msg"]:
|
elif response.json()['msg']:
|
||||||
await message.edit(response.json()["msg"])
|
await message.edit(response.json()['msg'])
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["gsearch"], prefix) & filters.me)
|
@Client.on_message(filters.command(['gsearch'], prefix) & filters.me)
|
||||||
async def google_search(client: Client, message: Message):
|
async def google_search(client: Client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
query = message.reply_to_message.text.strip()
|
query = message.reply_to_message.text.strip()
|
||||||
elif len(message.command) > 1:
|
elif len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
return await message.edit_text(f"{prefix}gsearch <query/reply to query>")
|
return await message.edit_text(f'{prefix}gsearch <query/reply to query>')
|
||||||
|
|
||||||
await message.edit("Searching...")
|
await message.edit('Searching...')
|
||||||
url = f"{GOOGLE_SEARCH_URL}{query}"
|
url = f'{GOOGLE_SEARCH_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
results, formatted_results = format_google_results(data["data"])
|
results, formatted_results = format_google_results(data['data'])
|
||||||
search_message = await message.edit(
|
search_message = await message.edit(
|
||||||
f"**Google Search Results for:** `{query}`\n\n{formatted_results}",
|
f'**Google Search Results for:** `{query}`\n\n{formatted_results}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
search_key = f"{message.chat.id}_google"
|
search_key = f'{message.chat.id}_google'
|
||||||
global search_results
|
global search_results
|
||||||
search_results[search_key] = {
|
search_results[search_key] = {
|
||||||
"results": results,
|
'results': results,
|
||||||
"message_id": search_message.id,
|
'message_id': search_message.id,
|
||||||
}
|
}
|
||||||
google_url = f"https://www.google.com/search?q={query}"
|
google_url = f'https://www.google.com/search?q={query}'
|
||||||
await send_screenshot(client, message, google_url)
|
await send_screenshot(client, message, google_url)
|
||||||
asyncio.create_task(
|
asyncio.create_task(delete_search_data(client, message.chat.id, search_message.id))
|
||||||
delete_search_data(client, message.chat.id, search_message.id)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["ytsearch"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ytsearch'], prefix) & filters.me)
|
||||||
async def youtube_search(client: Client, message: Message):
|
async def youtube_search(client: Client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
query = message.reply_to_message.text.strip()
|
query = message.reply_to_message.text.strip()
|
||||||
elif len(message.command) > 1:
|
elif len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
return await message.edit_text(f"{prefix}ytsearch <query/reply to query>")
|
return await message.edit_text(f'{prefix}ytsearch <query/reply to query>')
|
||||||
|
|
||||||
await message.edit("Searching...")
|
await message.edit('Searching...')
|
||||||
url = f"{YOUTUBE_SEARCH_URL}{query}"
|
url = f'{YOUTUBE_SEARCH_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
results, formatted_results = format_youtube_results(data["data"])
|
results, formatted_results = format_youtube_results(data['data'])
|
||||||
search_message = await message.edit(
|
search_message = await message.edit(
|
||||||
f"**YouTube Search Results for:** `{query}`\n\n{formatted_results}",
|
f'**YouTube Search Results for:** `{query}`\n\n{formatted_results}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
search_key = f"{message.chat.id}_youtube"
|
search_key = f'{message.chat.id}_youtube'
|
||||||
global search_results
|
global search_results
|
||||||
search_results[search_key] = {
|
search_results[search_key] = {
|
||||||
"results": results,
|
'results': results,
|
||||||
"message_id": search_message.id,
|
'message_id': search_message.id,
|
||||||
}
|
}
|
||||||
youtube_url = f"https://www.youtube.com/results?search_query={query}"
|
youtube_url = f'https://www.youtube.com/results?search_query={query}'
|
||||||
await send_screenshot(client, message, youtube_url)
|
await send_screenshot(client, message, youtube_url)
|
||||||
asyncio.create_task(
|
asyncio.create_task(delete_search_data(client, message.chat.id, search_message.id))
|
||||||
delete_search_data(client, message.chat.id, search_message.id)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["moviesearch"], prefix) & filters.me)
|
@Client.on_message(filters.command(['moviesearch'], prefix) & filters.me)
|
||||||
async def movie_search(client, message: Message):
|
async def movie_search(client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
query = message.reply_to_message.text.strip()
|
query = message.reply_to_message.text.strip()
|
||||||
elif len(message.command) > 1:
|
elif len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
return await message.edit_text(f"{prefix}moviesearch <query/reply to query>")
|
return await message.edit_text(f'{prefix}moviesearch <query/reply to query>')
|
||||||
|
|
||||||
await message.edit("Searching...")
|
await message.edit('Searching...')
|
||||||
url = f"{MOVIE_SEARCH_URL}{query}"
|
url = f'{MOVIE_SEARCH_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
results, formatted_results = format_movie_results(data["data"])
|
results, formatted_results = format_movie_results(data['data'])
|
||||||
|
|
||||||
# Split the message into multiple parts if it's too long
|
# Split the message into multiple parts if it's too long
|
||||||
parts = []
|
parts = []
|
||||||
@@ -289,179 +274,145 @@ async def movie_search(client, message: Message):
|
|||||||
|
|
||||||
for part in parts:
|
for part in parts:
|
||||||
search_message = await message.reply(
|
search_message = await message.reply(
|
||||||
f"**Movie Search Results for:** `{query}`\n\n{part}",
|
f'**Movie Search Results for:** `{query}`\n\n{part}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
search_key = f"{message.chat.id}_movie"
|
search_key = f'{message.chat.id}_movie'
|
||||||
global search_results
|
global search_results
|
||||||
search_results[search_key] = {
|
search_results[search_key] = {
|
||||||
"results": results,
|
'results': results,
|
||||||
"message_id": search_message.id,
|
'message_id': search_message.id,
|
||||||
}
|
}
|
||||||
asyncio.create_task(
|
asyncio.create_task(delete_search_data(client, message.chat.id, search_message.id))
|
||||||
delete_search_data(client, message.chat.id, search_message.id)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["apksearch"], prefix) & filters.me)
|
@Client.on_message(filters.command(['apksearch'], prefix) & filters.me)
|
||||||
async def apk_search(client, message: Message):
|
async def apk_search(client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
query = message.reply_to_message.text.strip()
|
query = message.reply_to_message.text.strip()
|
||||||
elif len(message.command) > 1:
|
elif len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
else:
|
else:
|
||||||
return await message.edit_text(f"{prefix}apksearch <query/reply to query>")
|
return await message.edit_text(f'{prefix}apksearch <query/reply to query>')
|
||||||
|
|
||||||
await message.edit("Searching...")
|
await message.edit('Searching...')
|
||||||
url = f"{APK_SEARCH_URL}{query}"
|
url = f'{APK_SEARCH_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
results, formatted_results = format_apk_results(data["BK9"])
|
results, formatted_results = format_apk_results(data['BK9'])
|
||||||
search_message = await message.edit(
|
search_message = await message.edit(
|
||||||
f"**APK Search Results for:** `{query}`\n\n{formatted_results}",
|
f'**APK Search Results for:** `{query}`\n\n{formatted_results}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
search_key = f"{message.chat.id}_apk"
|
search_key = f'{message.chat.id}_apk'
|
||||||
global search_results
|
global search_results
|
||||||
search_results[search_key] = {
|
search_results[search_key] = {
|
||||||
"results": results,
|
'results': results,
|
||||||
"message_id": search_message.id,
|
'message_id': search_message.id,
|
||||||
}
|
}
|
||||||
|
|
||||||
asyncio.create_task(
|
asyncio.create_task(delete_search_data(client, message.chat.id, search_message.id))
|
||||||
delete_search_data(client, message.chat.id, search_message.id)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["wgpt", "gptweb"], prefix) & filters.me)
|
@Client.on_message(filters.command(['wgpt', 'gptweb'], prefix) & filters.me)
|
||||||
async def gptweb(_, message: Message):
|
async def gptweb(_, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit("Usage: `wgpt <query>`")
|
await message.edit('Usage: `wgpt <query>`')
|
||||||
return
|
return
|
||||||
await message.edit("Thinking...")
|
await message.edit('Thinking...')
|
||||||
query = " ".join(message.command[1:])
|
query = ' '.join(message.command[1:])
|
||||||
url = f"{URL}/gptweb?text={query}"
|
url = f'{URL}/gptweb?text={query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"**Question:**\n{query}\n**Answer:**\n{data['data']}",
|
f'**Question:**\n{query}\n**Answer:**\n{data["data"]}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["wgemini"], prefix) & filters.me)
|
@Client.on_message(filters.command(['wgemini'], prefix) & filters.me)
|
||||||
async def gemini(_, message: Message):
|
async def gemini(_, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit("Usage: `wgemini <query>`")
|
await message.edit('Usage: `wgemini <query>`')
|
||||||
return
|
return
|
||||||
await message.edit("Thinking...")
|
await message.edit('Thinking...')
|
||||||
query = " ".join(message.command[1:])
|
query = ' '.join(message.command[1:])
|
||||||
url = f"{URL}/gemini?query={query}"
|
url = f'{URL}/gemini?query={query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"**Question:**\n{query}\n**Answer:**\n{data['message']}",
|
f'**Question:**\n{query}\n**Answer:**\n{data["message"]}',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["sputify"], prefix) & filters.me)
|
@Client.on_message(filters.command(['sputify'], prefix) & filters.me)
|
||||||
async def spotify_search(_, message: Message):
|
async def spotify_search(_, message: Message):
|
||||||
query = (
|
query = message.text.split(maxsplit=1)[1] if len(message.command) > 1 else message.reply_to_message.text
|
||||||
message.text.split(maxsplit=1)[1]
|
|
||||||
if len(message.command) > 1
|
|
||||||
else message.reply_to_message.text
|
|
||||||
)
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit("Usage: spotify <query>")
|
await message.edit('Usage: spotify <query>')
|
||||||
return
|
return
|
||||||
await search_music(
|
await search_music(f'{BASE_URL}/search/spotify?q=', format_spotify_result, message, query)
|
||||||
f"{BASE_URL}/search/spotify?q=", format_spotify_result, message, query
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["lyrics"], prefix) & filters.me)
|
@Client.on_message(filters.command(['lyrics'], prefix) & filters.me)
|
||||||
async def lyrics_search(_, message: Message):
|
async def lyrics_search(_, message: Message):
|
||||||
query = (
|
query = message.text.split(maxsplit=1)[1] if len(message.command) > 1 else message.reply_to_message.text
|
||||||
message.text.split(maxsplit=1)[1]
|
|
||||||
if len(message.command) > 1
|
|
||||||
else message.reply_to_message.text
|
|
||||||
)
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit("Usage: lyrics <song name>")
|
await message.edit('Usage: lyrics <song name>')
|
||||||
return
|
return
|
||||||
await search_music(
|
await search_music(f'{BASE_URL}/search/letra?query=', format_lyrics_result, message, query)
|
||||||
f"{BASE_URL}/search/letra?query=", format_lyrics_result, message, query
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["soundcloud"], prefix) & filters.me)
|
@Client.on_message(filters.command(['soundcloud'], prefix) & filters.me)
|
||||||
async def soundcloud_search(_, message: Message):
|
async def soundcloud_search(_, message: Message):
|
||||||
query = (
|
query = message.text.split(maxsplit=1)[1] if len(message.command) > 1 else message.reply_to_message.text
|
||||||
message.text.split(maxsplit=1)[1]
|
|
||||||
if len(message.command) > 1
|
|
||||||
else message.reply_to_message.text
|
|
||||||
)
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit("Usage: soundcloud <query>")
|
await message.edit('Usage: soundcloud <query>')
|
||||||
return
|
return
|
||||||
await search_music(
|
await search_music(f'{BASE_URL}/search/soundcloud?q=', format_soundcloud_result, message, query)
|
||||||
f"{BASE_URL}/search/soundcloud?q=", format_soundcloud_result, message, query
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["deezer"], prefix) & filters.me)
|
@Client.on_message(filters.command(['deezer'], prefix) & filters.me)
|
||||||
async def deezer_search(_, message: Message):
|
async def deezer_search(_, message: Message):
|
||||||
query = (
|
query = message.text.split(maxsplit=1)[1] if len(message.command) > 1 else message.reply_to_message.text
|
||||||
message.text.split(maxsplit=1)[1]
|
|
||||||
if len(message.command) > 1
|
|
||||||
else message.reply_to_message.text
|
|
||||||
)
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit("Usage: deezer <query>")
|
await message.edit('Usage: deezer <query>')
|
||||||
return
|
return
|
||||||
await search_music(
|
await search_music(f'{BASE_URL}/search/deezer?q=', format_deezer_result, message, query)
|
||||||
f"{BASE_URL}/search/deezer?q=", format_deezer_result, message, query
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["applemusic"], prefix) & filters.me)
|
@Client.on_message(filters.command(['applemusic'], prefix) & filters.me)
|
||||||
async def applemusic_search(_, message: Message):
|
async def applemusic_search(_, message: Message):
|
||||||
query = (
|
query = message.text.split(maxsplit=1)[1] if len(message.command) > 1 else message.reply_to_message.text
|
||||||
message.text.split(maxsplit=1)[1]
|
|
||||||
if len(message.command) > 1
|
|
||||||
else message.reply_to_message.text
|
|
||||||
)
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit("Usage: applemusic <query>")
|
await message.edit('Usage: applemusic <query>')
|
||||||
return
|
return
|
||||||
await search_music(
|
await search_music(f'{BASE_URL}/search/applemusic?text=', format_apple_music_result, message, query)
|
||||||
f"{BASE_URL}/search/applemusic?text=", format_apple_music_result, message, query
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.reply & filters.text & filters.me & np)
|
@Client.on_message(filters.reply & filters.text & filters.me & np)
|
||||||
async def handle_reply(client: Client, message: Message):
|
async def handle_reply(client: Client, message: Message):
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
search_keys = [
|
search_keys = [
|
||||||
f"{chat_id}_google",
|
f'{chat_id}_google',
|
||||||
f"{chat_id}_youtube",
|
f'{chat_id}_youtube',
|
||||||
f"{chat_id}_movie",
|
f'{chat_id}_movie',
|
||||||
f"{chat_id}_apk",
|
f'{chat_id}_apk',
|
||||||
]
|
]
|
||||||
|
|
||||||
for search_key in search_keys:
|
for search_key in search_keys:
|
||||||
@@ -472,76 +423,65 @@ async def handle_reply(client: Client, message: Message):
|
|||||||
return
|
return
|
||||||
|
|
||||||
index = int(message.text.strip()) - 1
|
index = int(message.text.strip()) - 1
|
||||||
results = search_results[search_key]["results"]
|
results = search_results[search_key]['results']
|
||||||
search_message_id = search_results[search_key]["message_id"]
|
search_message_id = search_results[search_key]['message_id']
|
||||||
if (
|
if message.reply_to_message.id == search_message_id and 0 <= index < len(results):
|
||||||
message.reply_to_message.id == search_message_id
|
await message.edit('Please wait...')
|
||||||
and 0 <= index < len(results)
|
|
||||||
):
|
|
||||||
await message.edit("Please wait...")
|
|
||||||
|
|
||||||
if search_key.endswith("_movie"):
|
if search_key.endswith('_movie'):
|
||||||
# Send movie details with image
|
# Send movie details with image
|
||||||
movie = results[index]
|
movie = results[index]
|
||||||
caption = (
|
caption = (
|
||||||
f"**{movie['title']}** ({movie['release_date']})\n"
|
f'**{movie["title"]}** ({movie["release_date"]})\n'
|
||||||
f"Original Title: {movie['original_title']}\n"
|
f'Original Title: {movie["original_title"]}\n'
|
||||||
f"Language: {movie['original_language']}\n"
|
f'Language: {movie["original_language"]}\n'
|
||||||
f"Overview: {movie['overview']}\n"
|
f'Overview: {movie["overview"]}\n'
|
||||||
f"Popularity: {movie['popularity']}\n"
|
f'Popularity: {movie["popularity"]}\n'
|
||||||
f"Rating: {movie['vote_average']}/10\n"
|
f'Rating: {movie["vote_average"]}/10\n'
|
||||||
f"Votes: {movie['vote_count']}"
|
f'Votes: {movie["vote_count"]}'
|
||||||
)
|
)
|
||||||
if "image" in movie:
|
if 'image' in movie:
|
||||||
response = requests.get(movie["image"])
|
response = requests.get(movie['image'])
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
with open("movie_image.jpg", "wb") as f:
|
with open('movie_image.jpg', 'wb') as f:
|
||||||
f.write(response.content)
|
f.write(response.content)
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
photo="movie_image.jpg",
|
photo='movie_image.jpg',
|
||||||
caption=caption,
|
caption=caption,
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
os.remove("movie_image.jpg")
|
os.remove('movie_image.jpg')
|
||||||
else:
|
else:
|
||||||
await message.reply(
|
await message.reply(caption, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
caption, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.reply(
|
await message.reply(caption, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
caption, parse_mode=enums.ParseMode.MARKDOWN
|
elif search_key.endswith('_apk'):
|
||||||
)
|
apk_url = f'{APK_DOWNLOAD_URL}{results[index]["link"]}'
|
||||||
elif search_key.endswith("_apk"):
|
|
||||||
apk_url = f"{APK_DOWNLOAD_URL}{results[index]['link']}"
|
|
||||||
fetch_apk_url = requests.get(apk_url)
|
fetch_apk_url = requests.get(apk_url)
|
||||||
if fetch_apk_url.status_code != 200:
|
if fetch_apk_url.status_code != 200:
|
||||||
await message.edit("Failed to fetch APK data.")
|
await message.edit('Failed to fetch APK data.')
|
||||||
else:
|
else:
|
||||||
data_apk = fetch_apk_url.json()
|
data_apk = fetch_apk_url.json()
|
||||||
download_url = data_apk["BK9"]["link"]
|
download_url = data_apk['BK9']['link']
|
||||||
size_apk = data_apk["BK9"]["size"]
|
size_apk = data_apk['BK9']['size']
|
||||||
apk_size = float(size_apk.split(" ")[0])
|
apk_size = float(size_apk.split(' ')[0])
|
||||||
|
|
||||||
if "GB" in size_apk or apk_size > 100:
|
if 'GB' in size_apk or apk_size > 100:
|
||||||
await message.edit(
|
await message.edit('File size is too large to download.')
|
||||||
"File size is too large to download."
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
apk_file_name = f"{data_apk['BK9']['title']}.apk"
|
apk_file_name = f'{data_apk["BK9"]["title"]}.apk'
|
||||||
response = requests.get(download_url)
|
response = requests.get(download_url)
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
await message.edit(
|
await message.edit('Failed to download the APK file.')
|
||||||
"Failed to download the APK file."
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
with open(apk_file_name, "wb") as f:
|
with open(apk_file_name, 'wb') as f:
|
||||||
f.write(response.content)
|
f.write(response.content)
|
||||||
|
|
||||||
await message.reply_document(apk_file_name)
|
await message.reply_document(apk_file_name)
|
||||||
os.remove(apk_file_name)
|
os.remove(apk_file_name)
|
||||||
else:
|
else:
|
||||||
url = results[index]["url"]
|
url = results[index]['url']
|
||||||
await send_screenshot(client, message, url)
|
await send_screenshot(client, message, url)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
return
|
return
|
||||||
@@ -549,17 +489,17 @@ async def handle_reply(client: Client, message: Message):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
modules_help["sarethai"] = {
|
modules_help['sarethai'] = {
|
||||||
"wgpt [query]*": "Ask anything to GPT-Web",
|
'wgpt [query]*': 'Ask anything to GPT-Web',
|
||||||
"gptweb [query]*": "Ask anything to GPT-Web",
|
'gptweb [query]*': 'Ask anything to GPT-Web',
|
||||||
"wgemini [query]*": "Ask anything to Gemini",
|
'wgemini [query]*': 'Ask anything to Gemini',
|
||||||
"sputify [query]*": "Search for songs on Spotify",
|
'sputify [query]*': 'Search for songs on Spotify',
|
||||||
"lyrics [song name]*": "Get the lyrics of a song",
|
'lyrics [song name]*': 'Get the lyrics of a song',
|
||||||
"soundcloud [query]*": "Search for songs on SoundCloud",
|
'soundcloud [query]*': 'Search for songs on SoundCloud',
|
||||||
"deezer [query]*": "Search for songs on Deezer",
|
'deezer [query]*': 'Search for songs on Deezer',
|
||||||
"applemusic [query]*": "Search for songs on Apple Music",
|
'applemusic [query]*': 'Search for songs on Apple Music',
|
||||||
"gsearch [query]*": "Searches Google for the query.",
|
'gsearch [query]*': 'Searches Google for the query.',
|
||||||
"ytsearch [query]*": "Searches YouTube for the query.",
|
'ytsearch [query]*': 'Searches YouTube for the query.',
|
||||||
"moviesearch [query]*": "Searches movies for the query and returns results.",
|
'moviesearch [query]*': 'Searches movies for the query and returns results.',
|
||||||
"apksearch [query]*": "Searches APKs for the query and returns results.",
|
'apksearch [query]*': 'Searches APKs for the query and returns results.',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,16 +12,15 @@ from utils.scripts import format_exc
|
|||||||
now = {}
|
now = {}
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["search"], prefix) & filters.me)
|
@Client.on_message(filters.command(['search'], prefix) & filters.me)
|
||||||
async def search_cmd(client: Client, message: Message):
|
async def search_cmd(client: Client, message: Message):
|
||||||
if now.get(message.chat.id):
|
if now.get(message.chat.id):
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>You already have a search in progress!\n"
|
f'<b>You already have a search in progress!\nType: <code>{prefix}scancel</code> to cancel it.</b>',
|
||||||
"Type: <code>{}scancel</code> to cancel it.</b>".format(prefix),
|
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
await message.edit("<b>Start searching...</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Start searching...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
finished = False
|
finished = False
|
||||||
local = False
|
local = False
|
||||||
try:
|
try:
|
||||||
@@ -30,9 +29,7 @@ async def search_cmd(client: Client, message: Message):
|
|||||||
timeout = float(message.command[3]) if len(message.command) > 3 else 2
|
timeout = float(message.command[3]) if len(message.command) > 3 else 2
|
||||||
except:
|
except:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
"<b>Usage:</b> <code>{}search [/cmd]* [search_word]* [timeout=2.0]</code>".format(
|
f'<b>Usage:</b> <code>{prefix}search [/cmd]* [search_word]* [timeout=2.0]</code>',
|
||||||
prefix
|
|
||||||
),
|
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -49,31 +46,25 @@ async def search_cmd(client: Client, message: Message):
|
|||||||
local = True
|
local = True
|
||||||
if not local:
|
if not local:
|
||||||
await sleep(timeout)
|
await sleep(timeout)
|
||||||
await message.reply_text(
|
await message.reply_text(quote=False, text=cmd, reply_to_message_id=None)
|
||||||
quote=False, text=cmd, reply_to_message_id=None
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
if now[message.chat.id]:
|
if now[message.chat.id]:
|
||||||
await message.reply_text(
|
await message.reply_text('<b>Search finished!</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Search finished!</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
await message.edit(format_exc(ex), parse_mode=enums.ParseMode.HTML)
|
await message.edit(format_exc(ex), parse_mode=enums.ParseMode.HTML)
|
||||||
now[message.chat.id] = False
|
now[message.chat.id] = False
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["scancel"], prefix) & filters.me)
|
@Client.on_message(filters.command(['scancel'], prefix) & filters.me)
|
||||||
async def scancel_cmd(_: Client, message: Message):
|
async def scancel_cmd(_: Client, message: Message):
|
||||||
if not now.get(message.chat.id):
|
if not now.get(message.chat.id):
|
||||||
return await message.edit(
|
return await message.edit('<b>There is no search in progress!</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>There is no search in progress!</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
now[message.chat.id] = False
|
now[message.chat.id] = False
|
||||||
await message.edit("<b>Search cancelled!</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Search cancelled!</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["search"] = {
|
modules_help['search'] = {
|
||||||
"search [/cmd]* [search_word]* [timeout=2.0]": "Search for a specific word in bot (while)",
|
'search [/cmd]* [search_word]* [timeout=2.0]': 'Search for a specific word in bot (while)',
|
||||||
"scancel": "Cancel current search",
|
'scancel': 'Cancel current search',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,21 +2,19 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.scripts import format_exc, import_library
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
from utils.scripts import format_exc, import_library
|
||||||
|
|
||||||
import_library("lxml_html_clean")
|
import_library('lxml_html_clean')
|
||||||
import_library("newspaper", "newspaper3k")
|
import_library('newspaper', 'newspaper3k')
|
||||||
nltk = import_library("nltk")
|
nltk = import_library('nltk')
|
||||||
from newspaper import Article
|
from newspaper import Article
|
||||||
from newspaper.article import ArticleException
|
from newspaper.article import ArticleException
|
||||||
|
|
||||||
|
nltk.download('all')
|
||||||
nltk.download("all")
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("summary", prefix) & filters.me)
|
@Client.on_message(filters.command('summary', prefix) & filters.me)
|
||||||
async def summarize_article(_, message: Message):
|
async def summarize_article(_, message: Message):
|
||||||
"""
|
"""
|
||||||
Summarize an article from a given URL.
|
Summarize an article from a given URL.
|
||||||
@@ -32,7 +30,7 @@ async def summarize_article(_, message: Message):
|
|||||||
url = message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
url = message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
||||||
|
|
||||||
if not url:
|
if not url:
|
||||||
await message.edit_text("Please provide a valid URL after the command.")
|
await message.edit_text('Please provide a valid URL after the command.')
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -51,14 +49,10 @@ async def summarize_article(_, message: Message):
|
|||||||
"""
|
"""
|
||||||
await message.edit_text(response)
|
await message.edit_text(response)
|
||||||
except ArticleException:
|
except ArticleException:
|
||||||
return await message.edit_text(
|
return await message.edit_text('Unable to extract information from the provided URL.')
|
||||||
"Unable to extract information from the provided URL."
|
|
||||||
)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await message.edit_text(f"An error occurred: {format_exc(e)}")
|
return await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["summary"] = {
|
modules_help['summary'] = {'summary [url]': 'Reply with article links, getting summary of articles'}
|
||||||
"summary [url]": "Reply with article links, getting summary of articles"
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,21 +14,16 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
from pyrogram import Client, filters, enums
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
ru_keys = (
|
ru_keys = """ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"""
|
||||||
"""ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"""
|
en_keys = """`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?"""
|
||||||
)
|
|
||||||
en_keys = (
|
|
||||||
"""`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?"""
|
|
||||||
)
|
|
||||||
table = str.maketrans(ru_keys + en_keys, en_keys + ru_keys)
|
table = str.maketrans(ru_keys + en_keys, en_keys + ru_keys)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["switch", "sw"], prefix) & filters.me)
|
@Client.on_message(filters.command(['switch', 'sw'], prefix) & filters.me)
|
||||||
async def switch(client: Client, message: Message):
|
async def switch(client: Client, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
@@ -38,9 +33,7 @@ async def switch(client: Client, message: Message):
|
|||||||
if history and history[1].from_user.is_self and history[1].text:
|
if history and history[1].from_user.is_self and history[1].text:
|
||||||
text = history[1].text
|
text = history[1].text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit('<b>Text to switch not found</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Text to switch not found</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
text = message.text.split(maxsplit=1)[1]
|
text = message.text.split(maxsplit=1)[1]
|
||||||
@@ -48,6 +41,6 @@ async def switch(client: Client, message: Message):
|
|||||||
await message.edit(str.translate(text, table), parse_mode=enums.ParseMode.HTML)
|
await message.edit(str.translate(text, table), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["switch"] = {
|
modules_help['switch'] = {
|
||||||
"sw [reply/text for switch]*": "Useful when you forgot to change the keyboard layout[RU]",
|
'sw [reply/text for switch]*': 'Useful when you forgot to change the keyboard layout[RU]',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,70 +1,62 @@
|
|||||||
import requests
|
|
||||||
import time
|
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageTooLong
|
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.errors import MessageTooLong
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
# Replace with your Gladia API key
|
# Replace with your Gladia API key
|
||||||
gladia_key = "your key "
|
gladia_key = 'your key '
|
||||||
gladia_url = "https://api.gladia.io/v2/transcription/"
|
gladia_url = 'https://api.gladia.io/v2/transcription/'
|
||||||
|
|
||||||
|
|
||||||
# Function to make fetch requests to the Gladia API
|
# Function to make fetch requests to the Gladia API
|
||||||
def make_fetch_request(url, headers, method="GET", data=None):
|
def make_fetch_request(url, headers, method='GET', data=None):
|
||||||
if method == "POST":
|
if method == 'POST':
|
||||||
response = requests.post(url, headers=headers, json=data)
|
response = requests.post(url, headers=headers, json=data)
|
||||||
else:
|
else:
|
||||||
response = requests.get(url, headers=headers)
|
response = requests.get(url, headers=headers)
|
||||||
return response.json()
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("transcribeyt", prefix) & filters.me)
|
@Client.on_message(filters.command('transcribeyt', prefix) & filters.me)
|
||||||
async def transcribe_audio(_, message: Message):
|
async def transcribe_audio(_, message: Message):
|
||||||
"""
|
"""
|
||||||
Transcribe an audio URL using the Gladia API.
|
Transcribe an audio URL using the Gladia API.
|
||||||
|
|
||||||
Usage: .transcribe <audio_url>
|
Usage: .transcribe <audio_url>
|
||||||
"""
|
"""
|
||||||
audio_url = (
|
audio_url = message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
||||||
message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else None
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check if a valid URL was provided
|
# Check if a valid URL was provided
|
||||||
if not audio_url:
|
if not audio_url:
|
||||||
await message.reply("Please provide a valid audio URL.")
|
await message.reply('Please provide a valid audio URL.')
|
||||||
return
|
return
|
||||||
|
|
||||||
headers = {"x-gladia-key": gladia_key, "Content-Type": "application/json"}
|
headers = {'x-gladia-key': gladia_key, 'Content-Type': 'application/json'}
|
||||||
|
|
||||||
request_data = {"audio_url": audio_url}
|
request_data = {'audio_url': audio_url}
|
||||||
|
|
||||||
# Send initial request to Gladia API
|
# Send initial request to Gladia API
|
||||||
status_message = await message.reply("- Sending initial request to Gladia API...")
|
status_message = await message.reply('- Sending initial request to Gladia API...')
|
||||||
initial_response = make_fetch_request(gladia_url, headers, "POST", request_data)
|
initial_response = make_fetch_request(gladia_url, headers, 'POST', request_data)
|
||||||
|
|
||||||
# Check if the response contains the result_url
|
# Check if the response contains the result_url
|
||||||
if "result_url" not in initial_response:
|
if 'result_url' not in initial_response:
|
||||||
await status_message.edit(f"Error in transcription request: {initial_response}")
|
await status_message.edit(f'Error in transcription request: {initial_response}')
|
||||||
return
|
return
|
||||||
|
|
||||||
result_url = initial_response["result_url"]
|
result_url = initial_response['result_url']
|
||||||
await status_message.edit(
|
await status_message.edit('Initial request sent. Polling for transcription results...')
|
||||||
f"Initial request sent. Polling for transcription results..."
|
|
||||||
)
|
|
||||||
|
|
||||||
# Polling for transcription result
|
# Polling for transcription result
|
||||||
while True:
|
while True:
|
||||||
poll_response = make_fetch_request(result_url, headers)
|
poll_response = make_fetch_request(result_url, headers)
|
||||||
|
|
||||||
if poll_response.get("status") == "done":
|
if poll_response.get('status') == 'done':
|
||||||
transcription = (
|
transcription = poll_response.get('result', {}).get('transcription', {}).get('full_transcript')
|
||||||
poll_response.get("result", {})
|
|
||||||
.get("transcription", {})
|
|
||||||
.get("full_transcript")
|
|
||||||
)
|
|
||||||
if transcription:
|
if transcription:
|
||||||
# Format the transcription result with HTML
|
# Format the transcription result with HTML
|
||||||
result_html = f"""
|
result_html = f"""
|
||||||
@@ -74,12 +66,10 @@ async def transcribe_audio(_, message: Message):
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Attempt to send transcription as a message
|
# Attempt to send transcription as a message
|
||||||
await message.reply_text(
|
await message.reply_text(result_html, parse_mode=enums.ParseMode.HTML)
|
||||||
result_html, parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
# Save the large response to a file
|
# Save the large response to a file
|
||||||
with open("transcription.txt", "w") as f:
|
with open('transcription.txt', 'w') as f:
|
||||||
f.write(result_html)
|
f.write(result_html)
|
||||||
|
|
||||||
# Read general details to include in the caption
|
# Read general details to include in the caption
|
||||||
@@ -87,24 +77,18 @@ async def transcribe_audio(_, message: Message):
|
|||||||
|
|
||||||
# Send the file with a caption
|
# Send the file with a caption
|
||||||
await message.reply_document(
|
await message.reply_document(
|
||||||
"transcription.txt",
|
'transcription.txt',
|
||||||
caption=f"<u><b>General Details</b></u>:\n{general_details}",
|
caption=f'<u><b>General Details</b></u>:\n{general_details}',
|
||||||
)
|
)
|
||||||
|
|
||||||
# Clean up by removing the file
|
# Clean up by removing the file
|
||||||
os.remove("transcription.html")
|
os.remove('transcription.html')
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit('Transcription completed, but no transcript was found.')
|
||||||
"Transcription completed, but no transcript was found."
|
|
||||||
)
|
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
await status_message.edit(
|
await status_message.edit(f'Transcription status: {poll_response.get("status")}')
|
||||||
f"Transcription status: {poll_response.get('status')}"
|
|
||||||
)
|
|
||||||
time.sleep(30) # Wait for a few seconds before polling again
|
time.sleep(30) # Wait for a few seconds before polling again
|
||||||
|
|
||||||
|
|
||||||
modules_help["transcribeyt"] = {
|
modules_help['transcribeyt'] = {'transcribeyt [yt video url]': 'Reply with a YT video link to get transcribed '}
|
||||||
"transcribeyt [yt video url]": "Reply with a YT video link to get transcribed "
|
|
||||||
}
|
|
||||||
|
|||||||
+49
-59
@@ -16,128 +16,118 @@
|
|||||||
|
|
||||||
from pyrogram import Client, errors, filters
|
from pyrogram import Client, errors, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.handlers import NoteSendHandler
|
from utils.handlers import NoteSendHandler
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["save"], prefix) & filters.me)
|
@Client.on_message(filters.command(['save'], prefix) & filters.me)
|
||||||
async def save_note(client: Client, message: Message):
|
async def save_note(client: Client, message: Message):
|
||||||
await message.edit("<b>Loading...</b>")
|
await message.edit('<b>Loading...</b>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
chat = await client.get_chat(db.get("core.notes", "chat_id", 0))
|
chat = await client.get_chat(db.get('core.notes', 'chat_id', 0))
|
||||||
except (errors.RPCError, ValueError, KeyError):
|
except (errors.RPCError, ValueError, KeyError):
|
||||||
# group is not accessible or isn't created
|
# group is not accessible or isn't created
|
||||||
chat = await client.create_supergroup(
|
chat = await client.create_supergroup('Userbot_Notes_Filters', "Don't touch this group, please")
|
||||||
"Userbot_Notes_Filters", "Don't touch this group, please"
|
db.set('core.notes', 'chat_id', chat.id)
|
||||||
)
|
|
||||||
db.set("core.notes", "chat_id", chat.id)
|
|
||||||
|
|
||||||
chat_id = chat.id
|
chat_id = chat.id
|
||||||
|
|
||||||
if message.reply_to_message and len(message.text.split()) >= 2:
|
if message.reply_to_message and len(message.text.split()) >= 2:
|
||||||
note_name = message.text.split(maxsplit=1)[1]
|
note_name = message.text.split(maxsplit=1)[1]
|
||||||
if message.reply_to_message.media_group_id:
|
if message.reply_to_message.media_group_id:
|
||||||
checking_note = db.get("core.notes", f"note{note_name}", False)
|
checking_note = db.get('core.notes', f'note{note_name}', False)
|
||||||
if not checking_note:
|
if not checking_note:
|
||||||
get_media_group = [
|
get_media_group = [
|
||||||
_.id
|
_.id for _ in await client.get_media_group(message.chat.id, message.reply_to_message.id)
|
||||||
for _ in await client.get_media_group(
|
|
||||||
message.chat.id, message.reply_to_message.id
|
|
||||||
)
|
|
||||||
]
|
]
|
||||||
try:
|
try:
|
||||||
message_id = await client.forward_messages(
|
message_id = await client.forward_messages(chat_id, message.chat.id, get_media_group)
|
||||||
chat_id, message.chat.id, get_media_group
|
|
||||||
)
|
|
||||||
except errors.ChatForwardsRestricted:
|
except errors.ChatForwardsRestricted:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Forwarding messages is restricted by chat admins</b>",
|
'<b>Forwarding messages is restricted by chat admins</b>',
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
note = {
|
note = {
|
||||||
"MESSAGE_ID": str(message_id[1].id),
|
'MESSAGE_ID': str(message_id[1].id),
|
||||||
"MEDIA_GROUP": True,
|
'MEDIA_GROUP': True,
|
||||||
"CHAT_ID": str(chat_id),
|
'CHAT_ID': str(chat_id),
|
||||||
}
|
}
|
||||||
db.set("core.notes", f"note{note_name}", note)
|
db.set('core.notes', f'note{note_name}', note)
|
||||||
await message.edit(f"<b>Note {note_name} saved</b>")
|
await message.edit(f'<b>Note {note_name} saved</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>This note already exists</b>")
|
await message.edit('<b>This note already exists</b>')
|
||||||
else:
|
else:
|
||||||
checking_note = db.get("core.notes", f"note{note_name}", False)
|
checking_note = db.get('core.notes', f'note{note_name}', False)
|
||||||
if not checking_note:
|
if not checking_note:
|
||||||
try:
|
try:
|
||||||
message_id = await message.reply_to_message.forward(chat_id)
|
message_id = await message.reply_to_message.forward(chat_id)
|
||||||
except errors.ChatForwardsRestricted:
|
except errors.ChatForwardsRestricted:
|
||||||
message_id = await message.copy(chat_id)
|
message_id = await message.copy(chat_id)
|
||||||
note = {
|
note = {
|
||||||
"MEDIA_GROUP": False,
|
'MEDIA_GROUP': False,
|
||||||
"MESSAGE_ID": str(message_id.id),
|
'MESSAGE_ID': str(message_id.id),
|
||||||
"CHAT_ID": str(chat_id),
|
'CHAT_ID': str(chat_id),
|
||||||
}
|
}
|
||||||
db.set("core.notes", f"note{note_name}", note)
|
db.set('core.notes', f'note{note_name}', note)
|
||||||
await message.edit(f"<b>Note {note_name} saved</b>")
|
await message.edit(f'<b>Note {note_name} saved</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>This note already exists</b>")
|
await message.edit('<b>This note already exists</b>')
|
||||||
elif len(message.text.split()) >= 3:
|
elif len(message.text.split()) >= 3:
|
||||||
note_name = message.text.split(maxsplit=1)[1].split()[0]
|
note_name = message.text.split(maxsplit=1)[1].split()[0]
|
||||||
checking_note = db.get("core.notes", f"note{note_name}", False)
|
checking_note = db.get('core.notes', f'note{note_name}', False)
|
||||||
if not checking_note:
|
if not checking_note:
|
||||||
message_id = await client.send_message(
|
message_id = await client.send_message(chat_id, message.text.split(note_name)[1].strip())
|
||||||
chat_id, message.text.split(note_name)[1].strip()
|
|
||||||
)
|
|
||||||
note = {
|
note = {
|
||||||
"MEDIA_GROUP": False,
|
'MEDIA_GROUP': False,
|
||||||
"MESSAGE_ID": str(message_id.id),
|
'MESSAGE_ID': str(message_id.id),
|
||||||
"CHAT_ID": str(chat_id),
|
'CHAT_ID': str(chat_id),
|
||||||
}
|
}
|
||||||
db.set("core.notes", f"note{note_name}", note)
|
db.set('core.notes', f'note{note_name}', note)
|
||||||
await message.edit(f"<b>Note {note_name} saved</b>")
|
await message.edit(f'<b>Note {note_name} saved</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>This note already exists</b>")
|
await message.edit('<b>This note already exists</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Example: <code>{prefix}save note_name</code></b>",
|
f'<b>Example: <code>{prefix}save note_name</code></b>',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("note", prefix) & filters.me)
|
@Client.on_message(filters.command('note', prefix) & filters.me)
|
||||||
async def note_send(client: Client, message: Message):
|
async def note_send(client: Client, message: Message):
|
||||||
handler = NoteSendHandler(client, message)
|
handler = NoteSendHandler(client, message)
|
||||||
await handler.handle_note_send()
|
await handler.handle_note_send()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["notes"], prefix) & filters.me)
|
@Client.on_message(filters.command(['notes'], prefix) & filters.me)
|
||||||
async def notes(_, message: Message):
|
async def notes(_, message: Message):
|
||||||
await message.edit("<b>Loading...</b>")
|
await message.edit('<b>Loading...</b>')
|
||||||
text = "Available notes:\n\n"
|
text = 'Available notes:\n\n'
|
||||||
collection = db.get_collection("core.notes")
|
collection = db.get_collection('core.notes')
|
||||||
for note in collection.keys():
|
for note in collection.keys():
|
||||||
if note[:4] == "note":
|
if note[:4] == 'note':
|
||||||
text += f"<code>{note[4:]}</code>\n"
|
text += f'<code>{note[4:]}</code>\n'
|
||||||
await message.edit(text)
|
await message.edit(text)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["clear"], prefix) & filters.me)
|
@Client.on_message(filters.command(['clear'], prefix) & filters.me)
|
||||||
async def clear_note(_, message: Message):
|
async def clear_note(_, message: Message):
|
||||||
if len(message.text.split()) >= 2:
|
if len(message.text.split()) >= 2:
|
||||||
note_name = message.text.split(maxsplit=1)[1]
|
note_name = message.text.split(maxsplit=1)[1]
|
||||||
find_note = db.get("core.notes", f"note{note_name}", False)
|
find_note = db.get('core.notes', f'note{note_name}', False)
|
||||||
if find_note:
|
if find_note:
|
||||||
db.remove("core.notes", f"note{note_name}")
|
db.remove('core.notes', f'note{note_name}')
|
||||||
await message.edit(f"<b>Note {note_name} deleted</b>")
|
await message.edit(f'<b>Note {note_name} deleted</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>There is no such note</b>")
|
await message.edit('<b>There is no such note</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Example: <code>{prefix}clear note_name</code></b>")
|
await message.edit(f'<b>Example: <code>{prefix}clear note_name</code></b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["notes"] = {
|
modules_help['notes'] = {
|
||||||
"save [name]*": "Save note",
|
'save [name]*': 'Save note',
|
||||||
"note [name]*": "Get saved note",
|
'note [name]*': 'Get saved note',
|
||||||
"notes": "Get note list",
|
'notes': 'Get note list',
|
||||||
"clear [name]*": "Delete note",
|
'clear [name]*': 'Delete note',
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-53
@@ -22,94 +22,85 @@ import aiofiles
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.errors import MessageTooLong
|
from pyrogram.errors import MessageTooLong
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import edit_or_reply, format_exc, progress
|
|
||||||
from utils.rentry import paste as rentry_paste
|
from utils.rentry import paste as rentry_paste
|
||||||
|
from utils.scripts import edit_or_reply, format_exc, progress
|
||||||
|
|
||||||
|
|
||||||
async def read_file(file_path):
|
async def read_file(file_path):
|
||||||
async with aiofiles.open(file_path, mode="r") as file:
|
async with aiofiles.open(file_path) as file:
|
||||||
content = await file.read()
|
content = await file.read()
|
||||||
return content
|
return content
|
||||||
|
|
||||||
|
|
||||||
def check_extension(file_path):
|
def check_extension(file_path):
|
||||||
extensions = {
|
extensions = {
|
||||||
".txt": "<pre lang='plaintext'>",
|
'.txt': "<pre lang='plaintext'>",
|
||||||
".py": "<pre lang='python'>",
|
'.py': "<pre lang='python'>",
|
||||||
".js": "<pre lang='javascript'>",
|
'.js': "<pre lang='javascript'>",
|
||||||
".json": "<pre lang='json'>",
|
'.json': "<pre lang='json'>",
|
||||||
".smali": "<pre lang='smali'>",
|
'.smali': "<pre lang='smali'>",
|
||||||
".sh": "<pre lang='shell'>",
|
'.sh': "<pre lang='shell'>",
|
||||||
".c": "<pre lang='c'>",
|
'.c': "<pre lang='c'>",
|
||||||
".java": "<pre lang='java'>",
|
'.java': "<pre lang='java'>",
|
||||||
".php": "<pre lang='php'>",
|
'.php': "<pre lang='php'>",
|
||||||
".doc": "<pre lang='doc'>",
|
'.doc': "<pre lang='doc'>",
|
||||||
".docx": "<pre lang='docx'>",
|
'.docx': "<pre lang='docx'>",
|
||||||
".rtf": "<pre lang='rtf'>",
|
'.rtf': "<pre lang='rtf'>",
|
||||||
".s": "<pre lang='asm'>",
|
'.s': "<pre lang='asm'>",
|
||||||
".dart": "<pre lang='dart'>",
|
'.dart': "<pre lang='dart'>",
|
||||||
".cfg": "<pre lang='cfg'>",
|
'.cfg': "<pre lang='cfg'>",
|
||||||
".swift": "<pre lang='swift'>",
|
'.swift': "<pre lang='swift'>",
|
||||||
".cs": "<pre lang='csharp'>",
|
'.cs': "<pre lang='csharp'>",
|
||||||
".vb": "<pre lang='vb'>",
|
'.vb': "<pre lang='vb'>",
|
||||||
".css": "<pre lang='css'>",
|
'.css': "<pre lang='css'>",
|
||||||
".htm": "<pre lang='html'>",
|
'.htm': "<pre lang='html'>",
|
||||||
".html": "<pre lang='html'>",
|
'.html': "<pre lang='html'>",
|
||||||
".rss": "<pre lang='xml'>",
|
'.rss': "<pre lang='xml'>",
|
||||||
".xhtml": "<pre lang='xtml'>",
|
'.xhtml': "<pre lang='xtml'>",
|
||||||
".cpp": "<pre lang='cpp'>",
|
'.cpp': "<pre lang='cpp'>",
|
||||||
}
|
}
|
||||||
|
|
||||||
ext = os.path.splitext(file_path)[1].lower()
|
ext = os.path.splitext(file_path)[1].lower()
|
||||||
|
|
||||||
return extensions.get(ext, "<pre>")
|
return extensions.get(ext, '<pre>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("open", prefix) & filters.me)
|
@Client.on_message(filters.command('open', prefix) & filters.me)
|
||||||
async def openfile(client: Client, message: Message):
|
async def openfile(client: Client, message: Message):
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
return await message.edit_text("Kindly Reply to a File")
|
return await message.edit_text('Kindly Reply to a File')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ms = await edit_or_reply(message, "<b>Downloading...</b>")
|
ms = await edit_or_reply(message, '<b>Downloading...</b>')
|
||||||
ct = time.time()
|
ct = time.time()
|
||||||
file_path = await message.reply_to_message.download(
|
file_path = await message.reply_to_message.download(progress=progress, progress_args=(ms, ct, 'Downloading...'))
|
||||||
progress=progress, progress_args=(ms, ct, "Downloading...")
|
await ms.edit_text('<code>Trying to open file...</code>')
|
||||||
)
|
|
||||||
await ms.edit_text("<code>Trying to open file...</code>")
|
|
||||||
file_info = os.stat(file_path)
|
file_info = os.stat(file_path)
|
||||||
file_name = file_path.split("/")[-1:]
|
file_name = file_path.split('/')[-1:]
|
||||||
file_size = file_info.st_size
|
file_size = file_info.st_size
|
||||||
last_modified = datetime.datetime.fromtimestamp(file_info.st_mtime).strftime(
|
last_modified = datetime.datetime.fromtimestamp(file_info.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
|
||||||
"%Y-%m-%d %H:%M:%S"
|
|
||||||
)
|
|
||||||
code_start = check_extension(file_path=file_path)
|
code_start = check_extension(file_path=file_path)
|
||||||
content = await read_file(file_path=file_path)
|
content = await read_file(file_path=file_path)
|
||||||
await ms.edit_text(
|
await ms.edit_text(
|
||||||
f"<b>File Name:</b> <code>{file_name[0]}</code>\n<b>Size:</b> <code>{file_size} bytes</code>\n<b>Last Modified:</b> <code>{last_modified}</code>\n<b>Content:</b> {code_start}{content}</pre>",
|
f'<b>File Name:</b> <code>{file_name[0]}</code>\n<b>Size:</b> <code>{file_size} bytes</code>\n<b>Last Modified:</b> <code>{last_modified}</code>\n<b>Content:</b> {code_start}{content}</pre>',
|
||||||
)
|
)
|
||||||
|
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
await ms.edit_text(
|
await ms.edit_text('<code>File Content is too long... Pasting to rentry...</code>')
|
||||||
"<code>File Content is too long... Pasting to rentry...</code>"
|
content_new = f'```{code_start[11:-2]}\n{content}```'
|
||||||
)
|
|
||||||
content_new = f"```{code_start[11:-2]}\n{content}```"
|
|
||||||
try:
|
try:
|
||||||
rentry_url, edit_code = await rentry_paste(
|
rentry_url, edit_code = await rentry_paste(text=content_new, return_edit=True)
|
||||||
text=content_new, return_edit=True
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
await ms.edit_text("<b>Error:</b> <code>Failed to paste to rentry</code>")
|
await ms.edit_text('<b>Error:</b> <code>Failed to paste to rentry</code>')
|
||||||
return
|
return
|
||||||
await client.send_message(
|
await client.send_message(
|
||||||
"me",
|
'me',
|
||||||
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
f"Here's your edit code for Url: {rentry_url}\nEdit code: <code>{edit_code}</code>",
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
await ms.edit_text(
|
await ms.edit_text(
|
||||||
f"<b>File Name:</b> <code>{file_name[0]}</code>\n<b>Size:</b> <code>{file_size} bytes</code>\n<b>Last Modified:</b> <code>{last_modified}</code>\n<b>Content:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>",
|
f'<b>File Name:</b> <code>{file_name[0]}</code>\n<b>Size:</b> <code>{file_size} bytes</code>\n<b>Last Modified:</b> <code>{last_modified}</code>\n<b>Content:</b> {rentry_url}\n<b>Note:</b> <code>Edit Code has been sent to your saved messages</code>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -121,6 +112,4 @@ async def openfile(client: Client, message: Message):
|
|||||||
os.remove(file_path)
|
os.remove(file_path)
|
||||||
|
|
||||||
|
|
||||||
modules_help["open"] = {
|
modules_help['open'] = {'open': "Open content of any text supported filetype and show it's raw data"}
|
||||||
"open": "Open content of any text supported filetype and show it's raw data"
|
|
||||||
}
|
|
||||||
|
|||||||
+29
-30
@@ -1,49 +1,48 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
from utils.config import gemini_key
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import import_library
|
from utils.scripts import import_library
|
||||||
from utils.config import gemini_key
|
|
||||||
|
|
||||||
|
import_library('pyzerox', 'py-zerox')
|
||||||
|
|
||||||
import_library("pyzerox", "py-zerox")
|
import litellm
|
||||||
|
|
||||||
from pyzerox import zerox
|
from pyzerox import zerox
|
||||||
from pyzerox.errors import ModelAccessError, NotAVisionModel
|
from pyzerox.errors import ModelAccessError, NotAVisionModel
|
||||||
import litellm
|
|
||||||
|
|
||||||
kwargs = {}
|
kwargs = {}
|
||||||
|
|
||||||
CUSTOM_SYSTEM_PROMPT = "For the below pdf page, convert it into as accurate markdown format as possible with it's structure intact i.e, tables, charts, layouts etc. Return only the markdown with no explanation text. Do not exclude any content from the page."
|
CUSTOM_SYSTEM_PROMPT = "For the below pdf page, convert it into as accurate markdown format as possible with it's structure intact i.e, tables, charts, layouts etc. Return only the markdown with no explanation text. Do not exclude any content from the page."
|
||||||
|
|
||||||
|
|
||||||
MODEL = "gemini/gemini-1.5-pro"
|
MODEL = 'gemini/gemini-1.5-pro'
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("pdf2md", prefix) & filters.me)
|
@Client.on_message(filters.command('pdf2md', prefix) & filters.me)
|
||||||
async def pdf2md(client: Client, message: Message):
|
async def pdf2md(client: Client, message: Message):
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
await message.edit("Reply to a pdf file")
|
await message.edit('Reply to a pdf file')
|
||||||
return
|
return
|
||||||
if not message.reply_to_message.document:
|
if not message.reply_to_message.document:
|
||||||
await message.edit("Reply to a pdf file")
|
await message.edit('Reply to a pdf file')
|
||||||
return
|
return
|
||||||
if not message.reply_to_message.document.mime_type == "application/pdf":
|
if not message.reply_to_message.document.mime_type == 'application/pdf':
|
||||||
await message.edit("Reply to a pdf file")
|
await message.edit('Reply to a pdf file')
|
||||||
return
|
return
|
||||||
if gemini_key == "":
|
if gemini_key == '':
|
||||||
await message.edit("Set GEMINI_KEY to use this command")
|
await message.edit('Set GEMINI_KEY to use this command')
|
||||||
return
|
return
|
||||||
file_name = message.reply_to_message.document.file_name
|
file_name = message.reply_to_message.document.file_name
|
||||||
file_name = file_name.split(".")[0]
|
file_name = file_name.split('.')[0]
|
||||||
if os.path.exists(f"{file_name}.md"):
|
if os.path.exists(f'{file_name}.md'):
|
||||||
os.remove(f"{file_name}.md")
|
os.remove(f'{file_name}.md')
|
||||||
md = f"{file_name}.md"
|
md = f'{file_name}.md'
|
||||||
os.environ["GEMINI_API_KEY"] = gemini_key
|
os.environ['GEMINI_API_KEY'] = gemini_key
|
||||||
await message.edit("Downloading pdf...")
|
await message.edit('Downloading pdf...')
|
||||||
pdf = await message.reply_to_message.download()
|
pdf = await message.reply_to_message.download()
|
||||||
await message.edit("Converting pdf to markdown...")
|
await message.edit('Converting pdf to markdown...')
|
||||||
try:
|
try:
|
||||||
result = await zerox(
|
result = await zerox(
|
||||||
file_path=pdf,
|
file_path=pdf,
|
||||||
@@ -55,29 +54,29 @@ async def pdf2md(client: Client, message: Message):
|
|||||||
if result:
|
if result:
|
||||||
pages = result.pages
|
pages = result.pages
|
||||||
for page in pages:
|
for page in pages:
|
||||||
with open(md, "a") as f:
|
with open(md, 'a') as f:
|
||||||
f.write(page.content)
|
f.write(page.content)
|
||||||
f.write("\n\n")
|
f.write('\n\n')
|
||||||
else:
|
else:
|
||||||
await message.edit("No result")
|
await message.edit('No result')
|
||||||
return
|
return
|
||||||
except ModelAccessError:
|
except ModelAccessError:
|
||||||
await message.edit("Model not accessible")
|
await message.edit('Model not accessible')
|
||||||
return
|
return
|
||||||
except NotAVisionModel:
|
except NotAVisionModel:
|
||||||
await message.edit("Model is not a vision model")
|
await message.edit('Model is not a vision model')
|
||||||
return
|
return
|
||||||
except litellm.InternalServerError:
|
except litellm.InternalServerError:
|
||||||
await message.edit("Internal Server Error")
|
await message.edit('Internal Server Error')
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(f"Error: {e}")
|
await message.edit(f'Error: {e}')
|
||||||
return
|
return
|
||||||
await message.edit("Uploading markdown...")
|
await message.edit('Uploading markdown...')
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
document=md,
|
document=md,
|
||||||
file_name=f"{message.reply_to_message.document.file_name.split('.')[0]}.md",
|
file_name=f'{message.reply_to_message.document.file_name.split(".")[0]}.md',
|
||||||
reply_to_message_id=message.reply_to_message.id,
|
reply_to_message_id=message.reply_to_message.id,
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
@@ -85,4 +84,4 @@ async def pdf2md(client: Client, message: Message):
|
|||||||
os.remove(md)
|
os.remove(md)
|
||||||
|
|
||||||
|
|
||||||
modules_help["pdf2md"] = {"pdf2md": "Convert a pdf to markdown"}
|
modules_help['pdf2md'] = {'pdf2md': 'Convert a pdf to markdown'}
|
||||||
|
|||||||
@@ -1,27 +1,26 @@
|
|||||||
from pyrogram import Client, filters, enums
|
import random
|
||||||
from pyrogram.types import Message
|
|
||||||
|
|
||||||
|
from pyrogram import Client, enums, filters
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import with_reply
|
from utils.scripts import with_reply
|
||||||
|
|
||||||
import random
|
|
||||||
|
|
||||||
|
@Client.on_message(filters.command('prus', prefix) & filters.me)
|
||||||
@Client.on_message(filters.command("prus", prefix) & filters.me)
|
|
||||||
@with_reply
|
@with_reply
|
||||||
async def prussian_cmd(_, message: Message):
|
async def prussian_cmd(_, message: Message):
|
||||||
words = [
|
words = [
|
||||||
"сука",
|
'сука',
|
||||||
"нахуй",
|
'нахуй',
|
||||||
"блять",
|
'блять',
|
||||||
"блядь",
|
'блядь',
|
||||||
"пиздец",
|
'пиздец',
|
||||||
"еблан",
|
'еблан',
|
||||||
"уебан",
|
'уебан',
|
||||||
"уебок",
|
'уебок',
|
||||||
"пизда",
|
'пизда',
|
||||||
"очко",
|
'очко',
|
||||||
"хуй",
|
'хуй',
|
||||||
]
|
]
|
||||||
splitted = message.reply_to_message.text.split()
|
splitted = message.reply_to_message.text.split()
|
||||||
|
|
||||||
@@ -29,9 +28,9 @@ async def prussian_cmd(_, message: Message):
|
|||||||
for j in range(1, 2):
|
for j in range(1, 2):
|
||||||
splitted.insert(i, random.choice(words))
|
splitted.insert(i, random.choice(words))
|
||||||
|
|
||||||
await message.edit(" ".join(splitted), parse_mode=enums.ParseMode.HTML)
|
await message.edit(' '.join(splitted), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["perfectrussian"] = {
|
modules_help['perfectrussian'] = {
|
||||||
"prus": "translate your message into perfect 🇷🇺Russian",
|
'prus': 'translate your message into perfect 🇷🇺Russian',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,16 +17,15 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["ping", "p"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ping', 'p'], prefix) & filters.me)
|
||||||
async def ping(client: Client, message: Message):
|
async def ping(client: Client, message: Message):
|
||||||
latency = await client.ping()
|
latency = await client.ping()
|
||||||
await message.edit(f"<b>Pong! {latency}ms</b>")
|
await message.edit(f'<b>Pong! {latency}ms</b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["ping"] = {
|
modules_help['ping'] = {
|
||||||
"ping": "Check ping to Telegram servers",
|
'ping': 'Check ping to Telegram servers',
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-17
@@ -16,37 +16,32 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import restart
|
from utils.scripts import restart
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(
|
@Client.on_message(filters.command(['sp', 'setprefix'], prefix) & filters.me)
|
||||||
filters.command(["sp", "setprefix"], prefix) & filters.me
|
|
||||||
)
|
|
||||||
async def setprefix(_, message: Message):
|
async def setprefix(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
pref = message.command[1]
|
pref = message.command[1]
|
||||||
db.set("core.main", "prefix", pref)
|
db.set('core.main', 'prefix', pref)
|
||||||
await message.edit(
|
await message.edit(f'<b>Prefix [ <code>{pref}</code> ] is set!\nRestarting...</b>')
|
||||||
f"<b>Prefix [ <code>{pref}</code> ] is set!\nRestarting...</b>"
|
|
||||||
)
|
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
restart()
|
restart()
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>The prefix must not be empty!</b>")
|
await message.edit('<b>The prefix must not be empty!</b>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["prefix"] = {
|
modules_help['prefix'] = {
|
||||||
"sp [prefix]": "Set custom prefix",
|
'sp [prefix]': 'Set custom prefix',
|
||||||
"setprefix [prefix]": "Set custom prefix",
|
'setprefix [prefix]': 'Set custom prefix',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,20 +15,20 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import with_reply
|
from utils.scripts import with_reply
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("del", prefix) & filters.me)
|
@Client.on_message(filters.command('del', prefix) & filters.me)
|
||||||
async def del_msg(_, message: Message):
|
async def del_msg(_, message: Message):
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await message.reply_to_message.delete()
|
await message.reply_to_message.delete()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("purge", prefix) & filters.me)
|
@Client.on_message(filters.command('purge', prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def purge(client: Client, message: Message):
|
async def purge(client: Client, message: Message):
|
||||||
chunk = []
|
chunk = []
|
||||||
@@ -48,7 +48,7 @@ async def purge(client: Client, message: Message):
|
|||||||
await client.delete_messages(message.chat.id, chunk)
|
await client.delete_messages(message.chat.id, chunk)
|
||||||
|
|
||||||
|
|
||||||
modules_help["purge"] = {
|
modules_help['purge'] = {
|
||||||
"purge [reply]": "Purge (delete all messages) chat from replied message to last",
|
'purge [reply]': 'Purge (delete all messages) chat from replied message to last',
|
||||||
"del [reply]": "Delete replied message",
|
'del [reply]': 'Delete replied message',
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-22
@@ -28,9 +28,7 @@ from utils.scripts import format_exc
|
|||||||
|
|
||||||
|
|
||||||
# noinspection PyUnusedLocal
|
# noinspection PyUnusedLocal
|
||||||
@Client.on_message(
|
@Client.on_message(filters.command(['ex', 'exec', 'py', 'exnoedit'], prefix) & filters.me)
|
||||||
filters.command(["ex", "exec", "py", "exnoedit"], prefix) & filters.me
|
|
||||||
)
|
|
||||||
async def user_exec(_: Client, message: Message):
|
async def user_exec(_: Client, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
await message.edit("<b>Code to execute isn't provided</b>")
|
await message.edit("<b>Code to execute isn't provided</b>")
|
||||||
@@ -39,18 +37,13 @@ async def user_exec(_: Client, message: Message):
|
|||||||
code = message.text.split(maxsplit=1)[1]
|
code = message.text.split(maxsplit=1)[1]
|
||||||
stdout = StringIO()
|
stdout = StringIO()
|
||||||
|
|
||||||
await message.edit("<b>Executing...</b>")
|
await message.edit('<b>Executing...</b>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with redirect_stdout(stdout):
|
with redirect_stdout(stdout):
|
||||||
exec(code) # skipcq
|
exec(code) # skipcq
|
||||||
text = (
|
text = f'<b>Code:</b>\n<code>{code}</code>\n\n<b>Result</b>:\n<code>{stdout.getvalue()}</code>'
|
||||||
"<b>Code:</b>\n"
|
if message.command[0] == 'exnoedit':
|
||||||
f"<code>{code}</code>\n\n"
|
|
||||||
"<b>Result</b>:\n"
|
|
||||||
f"<code>{stdout.getvalue()}</code>"
|
|
||||||
)
|
|
||||||
if message.command[0] == "exnoedit":
|
|
||||||
await message.reply(text)
|
await message.reply(text)
|
||||||
else:
|
else:
|
||||||
await message.edit(text)
|
await message.edit(text)
|
||||||
@@ -59,7 +52,7 @@ async def user_exec(_: Client, message: Message):
|
|||||||
|
|
||||||
|
|
||||||
# noinspection PyUnusedLocal
|
# noinspection PyUnusedLocal
|
||||||
@Client.on_message(filters.command(["ev", "eval"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ev', 'eval'], prefix) & filters.me)
|
||||||
async def user_eval(client: Client, message: Message):
|
async def user_eval(client: Client, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
await message.edit("<b>Code to eval isn't provided</b>")
|
await message.edit("<b>Code to eval isn't provided</b>")
|
||||||
@@ -69,18 +62,13 @@ async def user_eval(client: Client, message: Message):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
result = eval(code) # skipcq
|
result = eval(code) # skipcq
|
||||||
await message.edit(
|
await message.edit(f'<b>Expression:</b>\n<code>{code}</code>\n\n<b>Result</b>:\n<code>{result}</code>')
|
||||||
"<b>Expression:</b>\n"
|
|
||||||
f"<code>{code}</code>\n\n"
|
|
||||||
"<b>Result</b>:\n"
|
|
||||||
f"<code>{result}</code>"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["python"] = {
|
modules_help['python'] = {
|
||||||
"ex [python code]": "Execute Python code",
|
'ex [python code]': 'Execute Python code',
|
||||||
"exnoedit [python code]": "Execute Python code and return result with reply",
|
'exnoedit [python code]': 'Execute Python code and return result with reply',
|
||||||
"eval [python code]": "Eval Python code",
|
'eval [python code]': 'Eval Python code',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +1,33 @@
|
|||||||
import asyncio, random
|
import random
|
||||||
from pyrogram import Client, filters, enums
|
|
||||||
from pyrogram.raw import functions
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
emojis = [
|
emojis = [
|
||||||
"👍",
|
'👍',
|
||||||
"👎",
|
'👎',
|
||||||
"❤️",
|
'❤️',
|
||||||
"🔥",
|
'🔥',
|
||||||
"🥰",
|
'🥰',
|
||||||
"👏",
|
'👏',
|
||||||
"😁",
|
'😁',
|
||||||
"🤔",
|
'🤔',
|
||||||
"🤯",
|
'🤯',
|
||||||
"😱",
|
'😱',
|
||||||
"🤬",
|
'🤬',
|
||||||
"😢",
|
'😢',
|
||||||
"🎉",
|
'🎉',
|
||||||
"🤩",
|
'🤩',
|
||||||
"🤮",
|
'🤮',
|
||||||
"💩",
|
'💩',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("reactspam", prefix) & filters.me)
|
@Client.on_message(filters.command('reactspam', prefix) & filters.me)
|
||||||
async def reactspam(client: Client, message: Message):
|
async def reactspam(client: Client, message: Message):
|
||||||
await message.edit(f"<b>One moment...</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>One moment...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
try:
|
try:
|
||||||
selected_emojis = random.sample(emojis, 3)
|
selected_emojis = random.sample(emojis, 3)
|
||||||
print(selected_emojis)
|
print(selected_emojis)
|
||||||
@@ -41,4 +41,4 @@ async def reactspam(client: Client, message: Message):
|
|||||||
return await message.edit_text(format_exc(e))
|
return await message.edit_text(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["reactionspam"] = {"reactspam [amount]* [emoji]*": "spam reactions"}
|
modules_help['reactionspam'] = {'reactspam [amount]* [emoji]*': 'spam reactions'}
|
||||||
|
|||||||
+44
-57
@@ -17,7 +17,6 @@ import requests
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.config import rmbg_key
|
from utils.config import rmbg_key
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import edit_or_reply, format_exc
|
from utils.scripts import edit_or_reply, format_exc
|
||||||
@@ -43,54 +42,51 @@ async def convert_to_image(message, client) -> None | str:
|
|||||||
if message.reply_to_message.photo:
|
if message.reply_to_message.photo:
|
||||||
final_path = await message.reply_to_message.download()
|
final_path = await message.reply_to_message.download()
|
||||||
elif message.reply_to_message.sticker:
|
elif message.reply_to_message.sticker:
|
||||||
if message.reply_to_message.sticker.mime_type == "image/webp":
|
if message.reply_to_message.sticker.mime_type == 'image/webp':
|
||||||
final_path = "webp_to_png_s_proton.png"
|
final_path = 'webp_to_png_s_proton.png'
|
||||||
path_s = await message.reply_to_message.download()
|
path_s = await message.reply_to_message.download()
|
||||||
im = Image.open(path_s)
|
im = Image.open(path_s)
|
||||||
im.save(final_path, "PNG")
|
im.save(final_path, 'PNG')
|
||||||
else:
|
else:
|
||||||
path_s = await client.download_media(message.reply_to_message)
|
path_s = await client.download_media(message.reply_to_message)
|
||||||
final_path = "lottie_proton.png"
|
final_path = 'lottie_proton.png'
|
||||||
cmd = (
|
cmd = f'lottie_convert.py --frame 0 -if lottie -of png {path_s} {final_path}'
|
||||||
f"lottie_convert.py --frame 0 -if lottie -of png {path_s} {final_path}"
|
|
||||||
)
|
|
||||||
await exec(cmd) # skipcq
|
await exec(cmd) # skipcq
|
||||||
elif message.reply_to_message.audio:
|
elif message.reply_to_message.audio:
|
||||||
thumb = message.reply_to_message.audio.thumbs[0].file_id
|
thumb = message.reply_to_message.audio.thumbs[0].file_id
|
||||||
final_path = await client.download_media(thumb)
|
final_path = await client.download_media(thumb)
|
||||||
elif message.reply_to_message.video or message.reply_to_message.animation:
|
elif message.reply_to_message.video or message.reply_to_message.animation:
|
||||||
final_path = "fetched_thumb.png"
|
final_path = 'fetched_thumb.png'
|
||||||
vid_path = await client.download_media(message.reply_to_message)
|
vid_path = await client.download_media(message.reply_to_message)
|
||||||
await exec(
|
await exec(f'ffmpeg -i {vid_path} -filter:v scale=500:500 -an {final_path}') # skipcq
|
||||||
f"ffmpeg -i {vid_path} -filter:v scale=500:500 -an {final_path}"
|
|
||||||
) # skipcq
|
|
||||||
elif message.reply_to_message.document:
|
elif message.reply_to_message.document:
|
||||||
if message.reply_to_message.document.mime_type == "image/jpeg":
|
if (
|
||||||
|
message.reply_to_message.document.mime_type == 'image/jpeg'
|
||||||
|
or message.reply_to_message.document.mime_type == 'image/png'
|
||||||
|
):
|
||||||
final_path = await message.reply_to_message.download()
|
final_path = await message.reply_to_message.download()
|
||||||
elif message.reply_to_message.document.mime_type == "image/png":
|
elif message.reply_to_message.document.mime_type == 'image/webp':
|
||||||
final_path = await message.reply_to_message.download()
|
final_path = 'webp_to_png_s_proton.png'
|
||||||
elif message.reply_to_message.document.mime_type == "image/webp":
|
|
||||||
final_path = "webp_to_png_s_proton.png"
|
|
||||||
path_s = await message.reply_to_message.download()
|
path_s = await message.reply_to_message.download()
|
||||||
im = Image.open(path_s)
|
im = Image.open(path_s)
|
||||||
im.save(final_path, "PNG")
|
im.save(final_path, 'PNG')
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
return final_path
|
return final_path
|
||||||
|
|
||||||
|
|
||||||
def remove_background(photo_data):
|
def remove_background(photo_data):
|
||||||
with open(photo_data, "rb") as image_file:
|
with open(photo_data, 'rb') as image_file:
|
||||||
image_data = image_file.read()
|
image_data = image_file.read()
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
"https://api.remove.bg/v1.0/removebg",
|
'https://api.remove.bg/v1.0/removebg',
|
||||||
files={"image_file": image_data},
|
files={'image_file': image_data},
|
||||||
data={"size": "auto"},
|
data={'size': 'auto'},
|
||||||
headers={"X-Api-Key": rmbg_key},
|
headers={'X-Api-Key': rmbg_key},
|
||||||
)
|
)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
return BytesIO(response.content)
|
return BytesIO(response.content)
|
||||||
print("Error:", response.status_code, response.text)
|
print('Error:', response.status_code, response.text)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -108,26 +104,26 @@ def _check_rmbg(func):
|
|||||||
return check_rmbg
|
return check_rmbg
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("rmbg", prefix) & filters.me)
|
@Client.on_message(filters.command('rmbg', prefix) & filters.me)
|
||||||
@_check_rmbg
|
@_check_rmbg
|
||||||
async def rmbg(client: Client, message: Message):
|
async def rmbg(client: Client, message: Message):
|
||||||
pablo = await edit_or_reply(message, "<code>Processing...</code>")
|
pablo = await edit_or_reply(message, '<code>Processing...</code>')
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
await pablo.edit("<code>Reply To A Image Please!</code>")
|
await pablo.edit('<code>Reply To A Image Please!</code>')
|
||||||
return
|
return
|
||||||
cool = await convert_to_image(message, client)
|
cool = await convert_to_image(message, client)
|
||||||
if not cool:
|
if not cool:
|
||||||
await pablo.edit("<code>Reply to a valid media first.</code>")
|
await pablo.edit('<code>Reply to a valid media first.</code>')
|
||||||
return
|
return
|
||||||
start = datetime.now()
|
start = datetime.now()
|
||||||
await pablo.edit("sending to ReMove.BG")
|
await pablo.edit('sending to ReMove.BG')
|
||||||
input_file_name = cool
|
input_file_name = cool
|
||||||
files = {
|
files = {
|
||||||
"image_file": (input_file_name, open(input_file_name, "rb")),
|
'image_file': (input_file_name, open(input_file_name, 'rb')),
|
||||||
}
|
}
|
||||||
r = requests.post(
|
r = requests.post(
|
||||||
"https://api.remove.bg/v1.0/removebg",
|
'https://api.remove.bg/v1.0/removebg',
|
||||||
headers={"X-Api-Key": rmbg_key},
|
headers={'X-Api-Key': rmbg_key},
|
||||||
files=files,
|
files=files,
|
||||||
allow_redirects=True,
|
allow_redirects=True,
|
||||||
stream=True,
|
stream=True,
|
||||||
@@ -135,30 +131,23 @@ async def rmbg(client: Client, message: Message):
|
|||||||
if os.path.exists(cool):
|
if os.path.exists(cool):
|
||||||
os.remove(cool)
|
os.remove(cool)
|
||||||
output_file_name = r
|
output_file_name = r
|
||||||
contentType = output_file_name.headers.get("content-type")
|
contentType = output_file_name.headers.get('content-type')
|
||||||
if "image" in contentType:
|
if 'image' in contentType:
|
||||||
with io.BytesIO(output_file_name.content) as remove_bg_image:
|
with io.BytesIO(output_file_name.content) as remove_bg_image:
|
||||||
remove_bg_image.name = "BG_rem.png"
|
remove_bg_image.name = 'BG_rem.png'
|
||||||
await client.send_document(
|
await client.send_document(message.chat.id, remove_bg_image, reply_to_message_id=message.id)
|
||||||
message.chat.id, remove_bg_image, reply_to_message_id=message.id
|
|
||||||
)
|
|
||||||
end = datetime.now()
|
end = datetime.now()
|
||||||
ms = (end - start).seconds
|
ms = (end - start).seconds
|
||||||
await pablo.edit(
|
await pablo.edit(f"<code>Removed image's Background in {ms} seconds.")
|
||||||
f"<code>Removed image's Background in {ms} seconds."
|
if os.path.exists('BG_rem.png'):
|
||||||
)
|
os.remove('BG_rem.png')
|
||||||
if os.path.exists("BG_rem.png"):
|
|
||||||
os.remove("BG_rem.png")
|
|
||||||
else:
|
else:
|
||||||
await pablo.edit(
|
await pablo.edit('ReMove.BG API returned Errors.' + f'\n`{output_file_name.content.decode("UTF-8")}')
|
||||||
"ReMove.BG API returned Errors."
|
|
||||||
+ f"\n`{output_file_name.content.decode('UTF-8')}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("rebg", prefix) & filters.me)
|
@Client.on_message(filters.command('rebg', prefix) & filters.me)
|
||||||
async def rembg(client: Client, message: Message):
|
async def rembg(client: Client, message: Message):
|
||||||
await message.edit("<code>Processing...</code>")
|
await message.edit('<code>Processing...</code>')
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
@@ -167,28 +156,26 @@ async def rembg(client: Client, message: Message):
|
|||||||
try:
|
try:
|
||||||
photo_data = await message.reply_to_message.download()
|
photo_data = await message.reply_to_message.download()
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await message.edit("<b>File not found</b>")
|
await message.edit('<b>File not found</b>')
|
||||||
return
|
return
|
||||||
background_removed_data = remove_background(photo_data)
|
background_removed_data = remove_background(photo_data)
|
||||||
|
|
||||||
if background_removed_data:
|
if background_removed_data:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_photo(
|
await client.send_photo(chat_id, photo=background_removed_data, caption='Background removed!')
|
||||||
chat_id, photo=background_removed_data, caption="Background removed!"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(
|
||||||
"`Is Your RMBG Api 'rmbg_key' Valid Or You Didn't Add It??`\n **Check logs for details**",
|
"`Is Your RMBG Api 'rmbg_key' Valid Or You Didn't Add It??`\n **Check logs for details**",
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.reply_text(f"An error occurred: {format_exc(e)}")
|
await message.reply_text(f'An error occurred: {format_exc(e)}')
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists(photo_data):
|
if os.path.exists(photo_data):
|
||||||
os.remove(photo_data)
|
os.remove(photo_data)
|
||||||
|
|
||||||
|
|
||||||
modules_help["removebg"] = {
|
modules_help['removebg'] = {
|
||||||
"rebg [reply to image]*": "remove background from image without transparency",
|
'rebg [reply to image]*': 'remove background from image without transparency',
|
||||||
"rmbg [reply to image]*": "remove background from image with transparency",
|
'rmbg [reply to image]*': 'remove background from image with transparency',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,18 +20,17 @@
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["say", "s"], prefix) & filters.me)
|
@Client.on_message(filters.command(['say', 's'], prefix) & filters.me)
|
||||||
async def say(_, message: Message):
|
async def say(_, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
return
|
return
|
||||||
command = " ".join(message.command[1:])
|
command = ' '.join(message.command[1:])
|
||||||
await message.edit(f"<code>{command}</code>")
|
await message.edit(f'<code>{command}</code>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["say"] = {
|
modules_help['say'] = {
|
||||||
"say [command]*": "Send message that won't be interpreted by userbot",
|
'say [command]*': "Send message that won't be interpreted by userbot",
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-13
@@ -18,41 +18,38 @@ import os
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, format_module_help, format_small_module_help
|
from utils.scripts import format_exc, format_module_help, format_small_module_help
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["sendmod", "sm"], prefix) & filters.me)
|
@Client.on_message(filters.command(['sendmod', 'sm'], prefix) & filters.me)
|
||||||
async def sendmod(client: Client, message: Message):
|
async def sendmod(client: Client, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
await message.edit("<b>Module name to send is not provided</b>")
|
await message.edit('<b>Module name to send is not provided</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("<b>Dispatching...</b>")
|
await message.edit('<b>Dispatching...</b>')
|
||||||
try:
|
try:
|
||||||
module_name = message.command[1].lower()
|
module_name = message.command[1].lower()
|
||||||
if module_name in modules_help:
|
if module_name in modules_help:
|
||||||
text = format_module_help(module_name)
|
text = format_module_help(module_name)
|
||||||
if len(text) >= 1024:
|
if len(text) >= 1024:
|
||||||
text = format_small_module_help(module_name)
|
text = format_small_module_help(module_name)
|
||||||
if os.path.isfile(f"modules/{module_name}.py"):
|
if os.path.isfile(f'modules/{module_name}.py'):
|
||||||
await client.send_document(
|
await client.send_document(message.chat.id, f'modules/{module_name}.py', caption=text)
|
||||||
message.chat.id, f"modules/{module_name}.py", caption=text
|
elif os.path.isfile(f'modules/custom_modules/{module_name.lower()}.py'):
|
||||||
)
|
|
||||||
elif os.path.isfile(f"modules/custom_modules/{module_name.lower()}.py"):
|
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
f"modules/custom_modules/{module_name}.py",
|
f'modules/custom_modules/{module_name}.py',
|
||||||
caption=text,
|
caption=text,
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Module {module_name} not found!</b>")
|
await message.edit(f'<b>Module {module_name} not found!</b>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["sendmod"] = {
|
modules_help['sendmod'] = {
|
||||||
"sendmod [module_name]": "Send module to interlocutor",
|
'sendmod [module_name]': 'Send module to interlocutor',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,137 +20,128 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from html import escape
|
from html import escape
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, ContinuePropagation, filters
|
||||||
from pyrogram import ContinuePropagation
|
|
||||||
from pyrogram.errors import RPCError
|
from pyrogram.errors import RPCError
|
||||||
from pyrogram.raw.functions.account import GetAuthorizations, ResetAuthorization
|
from pyrogram.raw.functions.account import GetAuthorizations, ResetAuthorization
|
||||||
from pyrogram.raw.types import UpdateServiceNotification
|
from pyrogram.raw.types import UpdateServiceNotification
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
auth_hashes = db.get("core.sessionkiller", "auths_hashes", [])
|
auth_hashes = db.get('core.sessionkiller', 'auths_hashes', [])
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["sessions"], prefix) & filters.me)
|
@Client.on_message(filters.command(['sessions'], prefix) & filters.me)
|
||||||
async def sessions_list(client: Client, message: Message):
|
async def sessions_list(client: Client, message: Message):
|
||||||
formatted_sessions = []
|
formatted_sessions = []
|
||||||
sessions = (await client.invoke(GetAuthorizations())).authorizations
|
sessions = (await client.invoke(GetAuthorizations())).authorizations
|
||||||
for num, session in enumerate(sessions, 1):
|
for num, session in enumerate(sessions, 1):
|
||||||
formatted_sessions.append(
|
formatted_sessions.append(
|
||||||
f"<b>{num}</b>. <b>{escape(session.device_model)}</b> on <code>{escape(session.platform if session.platform != '' else 'unknown platform')}</code>\n"
|
f'<b>{num}</b>. <b>{escape(session.device_model)}</b> on <code>{escape(session.platform if session.platform != "" else "unknown platform")}</code>\n'
|
||||||
f"<b>Hash:</b> <code>{session.hash}</code>\n"
|
f'<b>Hash:</b> <code>{session.hash}</code>\n'
|
||||||
f"<b>App name:</b> <code>{escape(session.app_name)}</code> <code>v.{escape(session.app_version if session.app_version != '' else 'unknown')}</code>\n"
|
f'<b>App name:</b> <code>{escape(session.app_name)}</code> <code>v.{escape(session.app_version if session.app_version != "" else "unknown")}</code>\n'
|
||||||
f"<b>Created (last activity):</b> {datetime.fromtimestamp(session.date_created).isoformat()} ({datetime.fromtimestamp(session.date_active).isoformat()})\n"
|
f'<b>Created (last activity):</b> {datetime.fromtimestamp(session.date_created).isoformat()} ({datetime.fromtimestamp(session.date_active).isoformat()})\n'
|
||||||
f"<b>IP and location: </b>: <code>{session.ip}</code> (<i>{session.country}</i>)\n"
|
f'<b>IP and location: </b>: <code>{session.ip}</code> (<i>{session.country}</i>)\n'
|
||||||
f"<b>Official status:</b> <code>{'✅' if session.official_app else '❌️'}</code>\n"
|
f'<b>Official status:</b> <code>{"✅" if session.official_app else "❌️"}</code>\n'
|
||||||
f"<b>2FA accepted:</b> <code>{'❌️️' if session.password_pending else '✅'}</code>\n"
|
f'<b>2FA accepted:</b> <code>{"❌️️" if session.password_pending else "✅"}</code>\n'
|
||||||
f"<b>Can accept calls / secret chats:</b> {'❌️️' if session.call_requests_disabled else '✅'} / {'❌️️' if session.encrypted_requests_disabled else '✅'}"
|
f'<b>Can accept calls / secret chats:</b> {"❌️️" if session.call_requests_disabled else "✅"} / {"❌️️" if session.encrypted_requests_disabled else "✅"}'
|
||||||
)
|
)
|
||||||
answer = "<b>Active sessions at your account:</b>\n\n"
|
answer = '<b>Active sessions at your account:</b>\n\n'
|
||||||
chunk = []
|
chunk = []
|
||||||
for s in formatted_sessions:
|
for s in formatted_sessions:
|
||||||
chunk.append(s)
|
chunk.append(s)
|
||||||
if len(chunk) == 5:
|
if len(chunk) == 5:
|
||||||
answer += "\n\n".join(chunk)
|
answer += '\n\n'.join(chunk)
|
||||||
await message.reply(answer)
|
await message.reply(answer)
|
||||||
answer = ""
|
answer = ''
|
||||||
chunk.clear()
|
chunk.clear()
|
||||||
if chunk:
|
if chunk:
|
||||||
await message.reply("\n\n".join(chunk))
|
await message.reply('\n\n'.join(chunk))
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["sessionkiller", "sk"], prefix) & filters.me)
|
@Client.on_message(filters.command(['sessionkiller', 'sk'], prefix) & filters.me)
|
||||||
async def sessionkiller(client: Client, message: Message):
|
async def sessionkiller(client: Client, message: Message):
|
||||||
if len(message.command) == 1:
|
if len(message.command) == 1:
|
||||||
if db.get("core.sessionkiller", "enabled", False):
|
if db.get('core.sessionkiller', 'enabled', False):
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Sessionkiller status: enabled\n"
|
'<b>Sessionkiller status: enabled\n'
|
||||||
f"You can disable it with <code>{prefix}sessionkiller disable</code></b>"
|
f'You can disable it with <code>{prefix}sessionkiller disable</code></b>'
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Sessionkiller status: disabled\n"
|
'<b>Sessionkiller status: disabled\n'
|
||||||
f"You can enable it with <code>{prefix}sessionkiller enable</code></b>"
|
f'You can enable it with <code>{prefix}sessionkiller enable</code></b>'
|
||||||
)
|
)
|
||||||
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
|
elif message.command[1] in ['enable', 'on', '1', 'yes', 'true']:
|
||||||
db.set("core.sessionkiller", "enabled", True)
|
db.set('core.sessionkiller', 'enabled', True)
|
||||||
await message.edit("<b>Sessionkiller enabled!</b>")
|
await message.edit('<b>Sessionkiller enabled!</b>')
|
||||||
db.set(
|
db.set(
|
||||||
"core.sessionkiller",
|
'core.sessionkiller',
|
||||||
"auths_hashes",
|
'auths_hashes',
|
||||||
[
|
[auth.hash for auth in (await client.invoke(GetAuthorizations())).authorizations],
|
||||||
auth.hash
|
|
||||||
for auth in (await client.invoke(GetAuthorizations())).authorizations
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
|
elif message.command[1] in ['disable', 'off', '0', 'no', 'false']:
|
||||||
db.set("core.sessionkiller", "enabled", False)
|
db.set('core.sessionkiller', 'enabled', False)
|
||||||
await message.edit("<b>Sessionkiller disabled!</b>")
|
await message.edit('<b>Sessionkiller disabled!</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: {prefix}sessionkiller [enable|disable]</b>")
|
await message.edit(f'<b>Usage: {prefix}sessionkiller [enable|disable]</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_raw_update()
|
@Client.on_raw_update()
|
||||||
async def check_new_login(client: Client, update: UpdateServiceNotification, _, __):
|
async def check_new_login(client: Client, update: UpdateServiceNotification, _, __):
|
||||||
if not isinstance(update, UpdateServiceNotification) or not update.type.startswith(
|
if not isinstance(update, UpdateServiceNotification) or not update.type.startswith('auth'):
|
||||||
"auth"
|
|
||||||
):
|
|
||||||
raise ContinuePropagation
|
raise ContinuePropagation
|
||||||
if not db.get("core.sessionkiller", "enabled", False):
|
if not db.get('core.sessionkiller', 'enabled', False):
|
||||||
raise ContinuePropagation
|
raise ContinuePropagation
|
||||||
authorizations = (await client.invoke(GetAuthorizations()))["authorizations"]
|
authorizations = (await client.invoke(GetAuthorizations()))['authorizations']
|
||||||
for auth in authorizations:
|
for auth in authorizations:
|
||||||
if auth.current:
|
if auth.current:
|
||||||
continue
|
continue
|
||||||
if auth["hash"] not in auth_hashes:
|
if auth['hash'] not in auth_hashes:
|
||||||
# found new unexpected login
|
# found new unexpected login
|
||||||
try:
|
try:
|
||||||
await client.invoke(ResetAuthorization(hash=auth.hash))
|
await client.invoke(ResetAuthorization(hash=auth.hash))
|
||||||
except RPCError:
|
except RPCError:
|
||||||
info_text = (
|
info_text = (
|
||||||
"Someone tried to log in to your account. You can see this report because you"
|
'Someone tried to log in to your account. You can see this report because you'
|
||||||
"turned on this feature. But I couldn't terminate attacker's session and "
|
"turned on this feature. But I couldn't terminate attacker's session and "
|
||||||
"⚠ <b>you must reset it manually</b>. You should change your 2FA password "
|
'⚠ <b>you must reset it manually</b>. You should change your 2FA password '
|
||||||
"(if enabled), or set it.\n"
|
'(if enabled), or set it.\n'
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
info_text = (
|
info_text = (
|
||||||
"Someone tried to log in to your account. Since you have enabled "
|
'Someone tried to log in to your account. Since you have enabled '
|
||||||
"this feature, I deleted the attacker's session from your account. "
|
"this feature, I deleted the attacker's session from your account. "
|
||||||
"You should change your 2FA password (if enabled), or set it.\n"
|
'You should change your 2FA password (if enabled), or set it.\n'
|
||||||
)
|
|
||||||
logined_time = datetime.utcfromtimestamp(auth.date_created).strftime(
|
|
||||||
"%d-%m-%Y %H-%M-%S UTC"
|
|
||||||
)
|
)
|
||||||
|
logined_time = datetime.utcfromtimestamp(auth.date_created).strftime('%d-%m-%Y %H-%M-%S UTC')
|
||||||
full_report = (
|
full_report = (
|
||||||
"<b>!!! ACTION REQUIRED !!!</b>\n"
|
'<b>!!! ACTION REQUIRED !!!</b>\n'
|
||||||
+ info_text
|
+ info_text
|
||||||
+ "Below is the information about the attacker that I got.\n\n"
|
+ 'Below is the information about the attacker that I got.\n\n'
|
||||||
f"Unique authorization hash: <code>{auth.hash}</code> (not valid anymore)\n"
|
f'Unique authorization hash: <code>{auth.hash}</code> (not valid anymore)\n'
|
||||||
f"Device model: <code>{escape(auth.device_model)}</code>\n"
|
f'Device model: <code>{escape(auth.device_model)}</code>\n'
|
||||||
f"Platform: <code>{escape(auth.platform)}</code>\n"
|
f'Platform: <code>{escape(auth.platform)}</code>\n'
|
||||||
f"API ID: <code>{auth.api_id}</code>\n"
|
f'API ID: <code>{auth.api_id}</code>\n'
|
||||||
f"App name: <code>{escape(auth.app_name)}</code>\n"
|
f'App name: <code>{escape(auth.app_name)}</code>\n'
|
||||||
f"App version: <code>{auth.app_version}</code>\n"
|
f'App version: <code>{auth.app_version}</code>\n'
|
||||||
f"Logined at: <code>{logined_time}</code>\n"
|
f'Logined at: <code>{logined_time}</code>\n'
|
||||||
f"IP: <code>{auth.ip}</code>\n"
|
f'IP: <code>{auth.ip}</code>\n'
|
||||||
f"Country: <code>{auth.country}</code>\n"
|
f'Country: <code>{auth.country}</code>\n'
|
||||||
f"Official app: <b>{'yes' if auth.official_app else 'no'}</b>\n\n"
|
f'Official app: <b>{"yes" if auth.official_app else "no"}</b>\n\n'
|
||||||
f"<b>It is you? Type <code>{prefix}sk off</code> and try logging "
|
f'<b>It is you? Type <code>{prefix}sk off</code> and try logging '
|
||||||
f"in again.</b>"
|
f'in again.</b>'
|
||||||
)
|
)
|
||||||
# schedule sending report message so user will get notification
|
# schedule sending report message so user will get notification
|
||||||
schedule_date = int(time.time() + 15)
|
schedule_date = int(time.time() + 15)
|
||||||
await client.send_message("me", full_report, schedule_date=schedule_date)
|
await client.send_message('me', full_report, schedule_date=schedule_date)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
modules_help["sessions"] = {
|
modules_help['sessions'] = {
|
||||||
"sessionkiller [enable|disable]": "When enabled, every new session will be terminated.\n"
|
'sessionkiller [enable|disable]': 'When enabled, every new session will be terminated.\n'
|
||||||
"Useful for additional protection for your account",
|
'Useful for additional protection for your account',
|
||||||
"sessions": "List all sessions on your account",
|
'sessions': 'List all sessions on your account',
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-10
@@ -18,35 +18,34 @@
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.errors import YouBlockedUser
|
from pyrogram.errors import YouBlockedUser
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.conv import Conversation
|
from utils.conv import Conversation
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc
|
from utils.scripts import format_exc
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("sgb", prefix) & filters.me)
|
@Client.on_message(filters.command('sgb', prefix) & filters.me)
|
||||||
async def sg(client: Client, message: Message):
|
async def sg(client: Client, message: Message):
|
||||||
if message.reply_to_message and message.reply_to_message.from_user:
|
if message.reply_to_message and message.reply_to_message.from_user:
|
||||||
user_id = message.reply_to_message.from_user.id
|
user_id = message.reply_to_message.from_user.id
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: </b><code>{prefix}sgb [id]</code>")
|
await message.edit(f'<b>Usage: </b><code>{prefix}sgb [id]</code>')
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await message.edit("<code>Processing please wait</code>")
|
await message.edit('<code>Processing please wait</code>')
|
||||||
bot_username = "@SangMata_beta_bot"
|
bot_username = '@SangMata_beta_bot'
|
||||||
async with Conversation(client, bot_username, timeout=15) as conv:
|
async with Conversation(client, bot_username, timeout=15) as conv:
|
||||||
await conv.send_message(str(user_id))
|
await conv.send_message(str(user_id))
|
||||||
response = await conv.get_response(timeout=10)
|
response = await conv.get_response(timeout=10)
|
||||||
if "you have used up your quota" in response.text:
|
if 'you have used up your quota' in response.text:
|
||||||
await message.edit(response.text.splitlines()[0])
|
await message.edit(response.text.splitlines()[0])
|
||||||
return
|
return
|
||||||
return await message.edit(response.text)
|
return await message.edit(response.text)
|
||||||
except YouBlockedUser:
|
except YouBlockedUser:
|
||||||
await message.edit("<i>Please unblock @SangMata_beta_bot first.</i>")
|
await message.edit('<i>Please unblock @SangMata_beta_bot first.</i>')
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
await message.edit("<i>No response from bot within the timeout period.</i>")
|
await message.edit('<i>No response from bot within the timeout period.</i>')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(f"<i>Error: {format_exc(e)}</i>")
|
await message.edit(f'<i>Error: {format_exc(e)}</i>')
|
||||||
|
|
||||||
|
|
||||||
modules_help["sangmata"] = {"sgb": "reply to any user"}
|
modules_help['sangmata'] = {'sgb': 'reply to any user'}
|
||||||
|
|||||||
+12
-13
@@ -14,21 +14,20 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
from subprocess import Popen, PIPE, TimeoutExpired
|
|
||||||
import os
|
import os
|
||||||
|
from subprocess import PIPE, Popen, TimeoutExpired
|
||||||
from time import perf_counter
|
from time import perf_counter
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
|
||||||
from pyrogram.errors import MessageTooLong
|
from pyrogram.errors import MessageTooLong
|
||||||
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["shell", "sh"], prefix) & filters.me)
|
@Client.on_message(filters.command(['shell', 'sh'], prefix) & filters.me)
|
||||||
async def shell(_, message: Message):
|
async def shell(_, message: Message):
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
return await message.edit("<b>Specify the command in message text</b>")
|
return await message.edit('<b>Specify the command in message text</b>')
|
||||||
cmd_text = message.text.split(maxsplit=1)[1]
|
cmd_text = message.text.split(maxsplit=1)[1]
|
||||||
cmd_args = cmd_text.split()
|
cmd_args = cmd_text.split()
|
||||||
cmd_obj = Popen(
|
cmd_obj = Popen(
|
||||||
@@ -38,22 +37,22 @@ async def shell(_, message: Message):
|
|||||||
text=True,
|
text=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
char = "#" if os.getuid() == 0 else "$"
|
char = '#' if os.getuid() == 0 else '$'
|
||||||
text = f"<b>{char}</b> <code>{cmd_text}</code>\n\n"
|
text = f'<b>{char}</b> <code>{cmd_text}</code>\n\n'
|
||||||
|
|
||||||
await message.edit(text + "<b>Running...</b>")
|
await message.edit(text + '<b>Running...</b>')
|
||||||
try:
|
try:
|
||||||
start_time = perf_counter()
|
start_time = perf_counter()
|
||||||
stdout, stderr = cmd_obj.communicate(timeout=60)
|
stdout, stderr = cmd_obj.communicate(timeout=60)
|
||||||
except TimeoutExpired:
|
except TimeoutExpired:
|
||||||
text += "<b>Timeout expired (60 seconds)</b>"
|
text += '<b>Timeout expired (60 seconds)</b>'
|
||||||
else:
|
else:
|
||||||
stop_time = perf_counter()
|
stop_time = perf_counter()
|
||||||
if stdout:
|
if stdout:
|
||||||
text += f"<b>Output:</b>\n<code>{stdout}</code>\n\n"
|
text += f'<b>Output:</b>\n<code>{stdout}</code>\n\n'
|
||||||
if stderr:
|
if stderr:
|
||||||
text += f"<b>Error:</b>\n<code>{stderr}</code>\n\n"
|
text += f'<b>Error:</b>\n<code>{stderr}</code>\n\n'
|
||||||
text += f"<b>Completed in {round(stop_time - start_time, 5)} seconds with code {cmd_obj.returncode}</b>"
|
text += f'<b>Completed in {round(stop_time - start_time, 5)} seconds with code {cmd_obj.returncode}</b>'
|
||||||
try:
|
try:
|
||||||
await message.edit(text)
|
await message.edit(text)
|
||||||
except MessageTooLong:
|
except MessageTooLong:
|
||||||
@@ -61,4 +60,4 @@ async def shell(_, message: Message):
|
|||||||
cmd_obj.kill()
|
cmd_obj.kill()
|
||||||
|
|
||||||
|
|
||||||
modules_help["shell"] = {"sh [command]*": "Execute command in shell"}
|
modules_help['shell'] = {'sh [command]*': 'Execute command in shell'}
|
||||||
|
|||||||
@@ -1,75 +1,73 @@
|
|||||||
from datetime import datetime
|
import io
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
import io
|
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
TIKTOK_API_URL = "https://api.maher-zubair.tech/stalk/tiktok?q="
|
TIKTOK_API_URL = 'https://api.maher-zubair.tech/stalk/tiktok?q='
|
||||||
INSTAGRAM_API_URL = "https://tools.betabotz.eu.org/tools/stalk-ig?q="
|
INSTAGRAM_API_URL = 'https://tools.betabotz.eu.org/tools/stalk-ig?q='
|
||||||
GH_STALK = "https://api.github.com/users/"
|
GH_STALK = 'https://api.github.com/users/'
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["tiktokstalk"], prefix) & filters.me)
|
@Client.on_message(filters.command(['tiktokstalk'], prefix) & filters.me)
|
||||||
async def tiktok_stalk(_, message: Message):
|
async def tiktok_stalk(_, message: Message):
|
||||||
query = ""
|
query = ''
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.command[1]
|
query = message.command[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
query = message.reply_to_message.text.strip()
|
query = message.reply_to_message.text.strip()
|
||||||
|
|
||||||
if not query:
|
if not query:
|
||||||
await message.edit(
|
await message.edit('Usage: `tiktokstalk <username>` or reply to a message containing the username.')
|
||||||
"Usage: `tiktokstalk <username>` or reply to a message containing the username."
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("Fetching TikTok profile...")
|
await message.edit('Fetching TikTok profile...')
|
||||||
url = f"{TIKTOK_API_URL}{query}"
|
url = f'{TIKTOK_API_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json().get("result", {})
|
data = response.json().get('result', {})
|
||||||
if data:
|
if data:
|
||||||
profile_pic_url = data.get("profile", "")
|
profile_pic_url = data.get('profile', '')
|
||||||
profile_pic = requests.get(profile_pic_url).content
|
profile_pic = requests.get(profile_pic_url).content
|
||||||
profile_pic_stream = io.BytesIO(profile_pic)
|
profile_pic_stream = io.BytesIO(profile_pic)
|
||||||
profile_pic_stream.name = "profile.jpg"
|
profile_pic_stream.name = 'profile.jpg'
|
||||||
|
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
photo=profile_pic_stream,
|
photo=profile_pic_stream,
|
||||||
caption=(
|
caption=(
|
||||||
f"</b>TikTok Profile:</b>\n"
|
f'</b>TikTok Profile:</b>\n'
|
||||||
f"</b>Name:</b> {data.get('name', 'N/A')}\n"
|
f'</b>Name:</b> {data.get("name", "N/A")}\n'
|
||||||
f"</b>Username:</b> {data.get('username', 'N/A')}\n"
|
f'</b>Username:</b> {data.get("username", "N/A")}\n'
|
||||||
f"</b>Followers:</b> {data.get('followers', 'N/A')}\n"
|
f'</b>Followers:</b> {data.get("followers", "N/A")}\n'
|
||||||
f"</b>Following:</b> {data.get('following', 'N/A')}\n"
|
f'</b>Following:</b> {data.get("following", "N/A")}\n'
|
||||||
f"</b>Likes:</b> {data.get('likes', 'N/A')}\n"
|
f'</b>Likes:</b> {data.get("likes", "N/A")}\n'
|
||||||
f"</b>Description:</b> {data.get('desc', 'N/A')}\n"
|
f'</b>Description:</b> {data.get("desc", "N/A")}\n'
|
||||||
f"</b>Bio:</b> {data.get('bio', 'N/A')}"
|
f'</b>Bio:</b> {data.get("bio", "N/A")}'
|
||||||
),
|
),
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("No data found for this TikTok user.")
|
await message.edit('No data found for this TikTok user.')
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ipinfo", prefix) & filters.me)
|
@Client.on_message(filters.command('ipinfo', prefix) & filters.me)
|
||||||
async def ipinfo(_, message: Message):
|
async def ipinfo(_, message: Message):
|
||||||
searchip = message.text.split(" ", 1)
|
searchip = message.text.split(' ', 1)
|
||||||
if len(searchip) == 1:
|
if len(searchip) == 1:
|
||||||
await message.edit_text(f"Usage:{prefix}ipinfo [ip]")
|
await message.edit_text(f'Usage:{prefix}ipinfo [ip]')
|
||||||
return
|
return
|
||||||
searchip = searchip[1]
|
searchip = searchip[1]
|
||||||
m = await message.edit_text("Searching...")
|
m = await message.edit_text('Searching...')
|
||||||
await m.edit_text("🔎")
|
await m.edit_text('🔎')
|
||||||
try:
|
try:
|
||||||
url = requests.get(
|
url = requests.get(
|
||||||
f"http://ip-api.com/json/{searchip}?fields=status,message,continent,continentCode,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,offset,currency,isp,org,as,asname,reverse,mobile,proxy,hosting,query"
|
f'http://ip-api.com/json/{searchip}?fields=status,message,continent,continentCode,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,offset,currency,isp,org,as,asname,reverse,mobile,proxy,hosting,query'
|
||||||
)
|
)
|
||||||
response = json.loads(url.text)
|
response = json.loads(url.text)
|
||||||
text = f"""
|
text = f"""
|
||||||
@@ -98,10 +96,10 @@ async def ipinfo(_, message: Message):
|
|||||||
<b>Hosting:</b> <code>{response['hosting']}</code>"""
|
<b>Hosting:</b> <code>{response['hosting']}</code>"""
|
||||||
await m.edit_text(text)
|
await m.edit_text(text)
|
||||||
except:
|
except:
|
||||||
await m.edit_text("Unable To Find Info!")
|
await m.edit_text('Unable To Find Info!')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("instastalk", prefix) & filters.me)
|
@Client.on_message(filters.command('instastalk', prefix) & filters.me)
|
||||||
async def instagram_stalk(_, message: Message):
|
async def instagram_stalk(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
@@ -109,43 +107,43 @@ async def instagram_stalk(_, message: Message):
|
|||||||
query = message.reply_to_message.text
|
query = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"Usage: <code>{prefix}instastalk <username></code> or reply to a message containing the username."
|
f'Usage: <code>{prefix}instastalk <username></code> or reply to a message containing the username.'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("Fetching Instagram profile...")
|
await message.edit('Fetching Instagram profile...')
|
||||||
url = f"{INSTAGRAM_API_URL}{query}"
|
url = f'{INSTAGRAM_API_URL}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json().get("result", {}).get("user_info", {})
|
data = response.json().get('result', {}).get('user_info', {})
|
||||||
if data:
|
if data:
|
||||||
profile_pic_url = data.get("profile_pic_url", "")
|
profile_pic_url = data.get('profile_pic_url', '')
|
||||||
profile_pic = requests.get(profile_pic_url).content
|
profile_pic = requests.get(profile_pic_url).content
|
||||||
profile_pic_stream = io.BytesIO(profile_pic)
|
profile_pic_stream = io.BytesIO(profile_pic)
|
||||||
profile_pic_stream.name = "profile.jpg"
|
profile_pic_stream.name = 'profile.jpg'
|
||||||
|
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
photo=profile_pic_stream,
|
photo=profile_pic_stream,
|
||||||
caption=(
|
caption=(
|
||||||
f"</b>Instagram Profile:</b>\n"
|
f'</b>Instagram Profile:</b>\n'
|
||||||
f"</b>Full Name:</b> {data.get('full_name', 'N/A')}\n"
|
f'</b>Full Name:</b> {data.get("full_name", "N/A")}\n'
|
||||||
f"</b>Username:</b> {data.get('username', 'N/A')}\n"
|
f'</b>Username:</b> {data.get("username", "N/A")}\n'
|
||||||
f"</b>Biography:</b> {data.get('biography', 'N/A')}\n"
|
f'</b>Biography:</b> {data.get("biography", "N/A")}\n'
|
||||||
f"</b>External URL:</b> {data.get('external_url', 'N/A')}\n"
|
f'</b>External URL:</b> {data.get("external_url", "N/A")}\n'
|
||||||
f"</b>Posts:</b> {data.get('posts', 'N/A')}\n"
|
f'</b>Posts:</b> {data.get("posts", "N/A")}\n'
|
||||||
f"</b>Followers:</b> {data.get('followers', 'N/A')}\n"
|
f'</b>Followers:</b> {data.get("followers", "N/A")}\n'
|
||||||
f"</b>Following:</b> {data.get('following', 'N/A')}"
|
f'</b>Following:</b> {data.get("following", "N/A")}'
|
||||||
),
|
),
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("No data found for this Instagram user.")
|
await message.edit('No data found for this Instagram user.')
|
||||||
await message.delete()
|
await message.delete()
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("ghstalk", prefix) & filters.me)
|
@Client.on_message(filters.command('ghstalk', prefix) & filters.me)
|
||||||
async def github_stalk(_, message: Message):
|
async def github_stalk(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
query = message.text.split(maxsplit=1)[1]
|
query = message.text.split(maxsplit=1)[1]
|
||||||
@@ -153,48 +151,44 @@ async def github_stalk(_, message: Message):
|
|||||||
query = message.reply_to_message.text
|
query = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"Usage: <code>{prefix}ghstalk <username></code> or reply to a message containing the username."
|
f'Usage: <code>{prefix}ghstalk <username></code> or reply to a message containing the username.'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("Fetching GitHub profile...")
|
await message.edit('Fetching GitHub profile...')
|
||||||
url = f"{GH_STALK}{query}"
|
url = f'{GH_STALK}{query}'
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
created_at = data.get("created_at", "N/A")
|
created_at = data.get('created_at', 'N/A')
|
||||||
formatted_date = (
|
formatted_date = datetime.strptime(created_at, '%Y-%m-%dT%H:%M:%S%z') if created_at != 'N/A' else None
|
||||||
datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S%z")
|
|
||||||
if created_at != "N/A"
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
if data:
|
if data:
|
||||||
await message.reply_photo(
|
await message.reply_photo(
|
||||||
photo=data.get("avatar_url", "").replace("?v=4", ""),
|
photo=data.get('avatar_url', '').replace('?v=4', ''),
|
||||||
caption=f"</b>GitHub Profile:</b>\n"
|
caption=f'</b>GitHub Profile:</b>\n'
|
||||||
f"</b>Name:</b> {data.get('name', 'N/A')}\n"
|
f'</b>Name:</b> {data.get("name", "N/A")}\n'
|
||||||
f"</b>Username:</b> {data.get('login', 'N/A')}\n"
|
f'</b>Username:</b> {data.get("login", "N/A")}\n'
|
||||||
f"</b>Bio:</b> {data.get('bio', 'N/A')}\n"
|
f'</b>Bio:</b> {data.get("bio", "N/A")}\n'
|
||||||
f"</b>Public Repositories:</b> <a href='{data.get('repos_url', '')}'>{data.get('public_repos', 'N/A')}</a>\n"
|
f"</b>Public Repositories:</b> <a href='{data.get('repos_url', '')}'>{data.get('public_repos', 'N/A')}</a>\n"
|
||||||
f"</b>Public Gists:</b> <a href='{data.get('gists_url', '')}'>{data.get('public_gists', 'N/A')}</a>\n"
|
f"</b>Public Gists:</b> <a href='{data.get('gists_url', '')}'>{data.get('public_gists', 'N/A')}</a>\n"
|
||||||
f"</b>Company:</b> {data.get('company', 'N/A')}\n"
|
f'</b>Company:</b> {data.get("company", "N/A")}\n'
|
||||||
f"</b>Location:</b> {data.get('location', 'N/A')}\n"
|
f'</b>Location:</b> {data.get("location", "N/A")}\n'
|
||||||
f"</b>Email:</b> {data.get('email', 'N/A')}\n"
|
f'</b>Email:</b> {data.get("email", "N/A")}\n'
|
||||||
f"</b>Website:</b> {data.get('blog', 'N/A')}\n"
|
f'</b>Website:</b> {data.get("blog", "N/A")}\n'
|
||||||
f"</b>Created At:</b> {formatted_date.strftime('%Y-%m-%d %I:%M:%S %p') if formatted_date else 'N/A'}\n"
|
f'</b>Created At:</b> {formatted_date.strftime("%Y-%m-%d %I:%M:%S %p") if formatted_date else "N/A"}\n'
|
||||||
f"</b>Hireable:</b> {data.get('hireable', 'N/A')}\n"
|
f'</b>Hireable:</b> {data.get("hireable", "N/A")}\n'
|
||||||
f"</b>Followers:</b> {data.get('followers', 'N/A')}\n"
|
f'</b>Followers:</b> {data.get("followers", "N/A")}\n'
|
||||||
f"</b>Following:</b> {data.get('following', 'N/A')}",
|
f'</b>Following:</b> {data.get("following", "N/A")}',
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("No data found for this GitHub user.")
|
await message.edit('No data found for this GitHub user.')
|
||||||
else:
|
else:
|
||||||
await message.edit("An error occurred, please try again later.")
|
await message.edit('An error occurred, please try again later.')
|
||||||
|
|
||||||
|
|
||||||
modules_help["socialstalk"] = {
|
modules_help['socialstalk'] = {
|
||||||
"tiktokstalk [username]*": "Get TikTok profile information",
|
'tiktokstalk [username]*': 'Get TikTok profile information',
|
||||||
"ipinfo [IP address]*": "Get information about an IP address",
|
'ipinfo [IP address]*': 'Get information about an IP address',
|
||||||
"instastalk [username]*": "Get Instagram profile information",
|
'instastalk [username]*': 'Get Instagram profile information',
|
||||||
"ghstalk [username]*": "Get GitHub profile information",
|
'ghstalk [username]*': 'Get GitHub profile information',
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-10
@@ -18,18 +18,17 @@ import asyncio
|
|||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
commands = ["spam", "statspam", "slowspam", "fastspam"]
|
commands = ['spam', 'statspam', 'slowspam', 'fastspam']
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(commands, prefix) & filters.me)
|
@Client.on_message(filters.command(commands, prefix) & filters.me)
|
||||||
async def spam(client: Client, message: Message):
|
async def spam(client: Client, message: Message):
|
||||||
amount = int(message.command[1])
|
amount = int(message.command[1])
|
||||||
text = " ".join(message.command[2:])
|
text = ' '.join(message.command[2:])
|
||||||
|
|
||||||
cooldown = {"spam": 0.15, "statspam": 0.1, "slowspam": 0.9, "fastspam": 0}
|
cooldown = {'spam': 0.15, 'statspam': 0.1, 'slowspam': 0.9, 'fastspam': 0}
|
||||||
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
@@ -39,16 +38,16 @@ async def spam(client: Client, message: Message):
|
|||||||
else:
|
else:
|
||||||
sent = await client.send_message(message.chat.id, text)
|
sent = await client.send_message(message.chat.id, text)
|
||||||
|
|
||||||
if message.command[0] == "statspam":
|
if message.command[0] == 'statspam':
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
await sent.delete()
|
await sent.delete()
|
||||||
|
|
||||||
await asyncio.sleep(cooldown[message.command[0]])
|
await asyncio.sleep(cooldown[message.command[0]])
|
||||||
|
|
||||||
|
|
||||||
modules_help["spam"] = {
|
modules_help['spam'] = {
|
||||||
"spam [amount] [text]": "Start spam",
|
'spam [amount] [text]': 'Start spam',
|
||||||
"statspam [amount] [text]": "Send and delete",
|
'statspam [amount] [text]': 'Send and delete',
|
||||||
"fastspam [amount] [text]": "Start fast spam",
|
'fastspam [amount] [text]': 'Start fast spam',
|
||||||
"slowspam [amount] [text]": "Start slow spam",
|
'slowspam [amount] [text]': 'Start slow spam',
|
||||||
}
|
}
|
||||||
|
|||||||
+40
-60
@@ -13,19 +13,17 @@ from pyrogram.types import Message
|
|||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, import_library, resize_image
|
from utils.scripts import format_exc, import_library, resize_image
|
||||||
|
|
||||||
Image = import_library("PIL", "pillow").Image
|
Image = import_library('PIL', 'pillow').Image
|
||||||
np = import_library("numpy")
|
np = import_library('numpy')
|
||||||
imageio = import_library("imageio")
|
imageio = import_library('imageio')
|
||||||
|
|
||||||
|
|
||||||
def create_gif(filename: str, offset: int, fps: int = 2, typ: str = "spin"):
|
def create_gif(filename: str, offset: int, fps: int = 2, typ: str = 'spin'):
|
||||||
img = Image.open(f"downloads/{filename}")
|
img = Image.open(f'downloads/{filename}')
|
||||||
if typ.lower() != "spin":
|
if typ.lower() != 'spin':
|
||||||
img = img.resize(
|
img = img.resize((random.randint(200, 1280), random.randint(200, 1280)), Image.ANTIALIAS)
|
||||||
(random.randint(200, 1280), random.randint(200, 1280)), Image.ANTIALIAS
|
|
||||||
)
|
|
||||||
imageio.mimsave(
|
imageio.mimsave(
|
||||||
"downloads/video.gif",
|
'downloads/video.gif',
|
||||||
[img.rotate(-(i % 360)) for i in range(1, 361, offset)],
|
[img.rotate(-(i % 360)) for i in range(1, 361, offset)],
|
||||||
fps=fps,
|
fps=fps,
|
||||||
)
|
)
|
||||||
@@ -40,9 +38,7 @@ async def quote_cmd(client: Client, message: types.Message):
|
|||||||
|
|
||||||
messages = []
|
messages = []
|
||||||
|
|
||||||
async for msg in client.get_chat_history(
|
async for msg in client.get_chat_history(message.chat.id, offset_id=message.reply_to_message.id, reverse=True):
|
||||||
message.chat.id, offset_id=message.reply_to_message.id, reverse=True
|
|
||||||
):
|
|
||||||
if msg.empty:
|
if msg.empty:
|
||||||
continue
|
continue
|
||||||
if msg.message_id >= message.id:
|
if msg.message_id >= message.id:
|
||||||
@@ -57,102 +53,86 @@ async def quote_cmd(client: Client, message: types.Message):
|
|||||||
|
|
||||||
if send_for_me:
|
if send_for_me:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
message = await client.send_message(
|
message = await client.send_message('me', '<b>Generating...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"me", "<b>Generating...</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Generating...</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Generating...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
url = "https://quotes.fl1yd.su/generate"
|
url = 'https://quotes.fl1yd.su/generate'
|
||||||
params = {
|
params = {
|
||||||
"messages": [
|
'messages': [await render_message(client, msg) for msg in messages if not msg.empty],
|
||||||
await render_message(client, msg) for msg in messages if not msg.empty
|
'quote_color': '#162330',
|
||||||
],
|
'text_color': '#fff',
|
||||||
"quote_color": "#162330",
|
|
||||||
"text_color": "#fff",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
response = await aiohttp.ClientSession().post(url, json=params)
|
response = await aiohttp.ClientSession().post(url, json=params)
|
||||||
if response.status != 200:
|
if response.status != 200:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Quotes API error!</b>\n" f"<code>{response.text}</code>",
|
f'<b>Quotes API error!</b>\n<code>{response.text}</code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
resized = resize_image(
|
resized = resize_image(BytesIO(await response.read()), img_type='PNG' if is_png else 'WEBP')
|
||||||
BytesIO(await response.read()), img_type="PNG" if is_png else "WEBP"
|
|
||||||
)
|
|
||||||
return resized, is_png
|
return resized, is_png
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["spin", "dspin"], prefix) & filters.me)
|
@Client.on_message(filters.command(['spin', 'dspin'], prefix) & filters.me)
|
||||||
async def spin_handler(client: Client, message: Message):
|
async def spin_handler(client: Client, message: Message):
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Reply to a <i>message</i> to spin it!</b>",
|
'<b>Reply to a <i>message</i> to spin it!</b>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
await message.edit(
|
await message.edit('<b>Downloading sticker...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Downloading sticker...</b>", parse_mode=enums.ParseMode.HTML
|
return await message.edit('<b>Invalid file type!</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
)
|
|
||||||
return await message.edit(
|
|
||||||
"<b>Invalid file type!</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
coro = True
|
coro = True
|
||||||
if message.reply_to_message.document:
|
if message.reply_to_message.document:
|
||||||
filename = message.reply_to_message.document.file_name
|
filename = message.reply_to_message.document.file_name
|
||||||
if (
|
if (
|
||||||
not filename.endswith(".webp")
|
not filename.endswith('.webp')
|
||||||
and not filename.endswith(".png")
|
and not filename.endswith('.png')
|
||||||
and not filename.endswith(".jpg")
|
and not filename.endswith('.jpg')
|
||||||
and not filename.endswith(".jpeg")
|
and not filename.endswith('.jpeg')
|
||||||
):
|
):
|
||||||
return await message.edit(
|
return await message.edit('<b>Invalid file type!</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Invalid file type!</b>", parse_mode=enums.ParseMode.HTML
|
|
||||||
)
|
|
||||||
elif message.reply_to_message.sticker:
|
elif message.reply_to_message.sticker:
|
||||||
if message.reply_to_message.sticker.is_video:
|
if message.reply_to_message.sticker.is_video:
|
||||||
return await message.edit(
|
return await message.edit('<b>Video stickers not allowed</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
"<b>Video stickers not allowed</b>", parse_mode=enums.ParseMode.HTML
|
filename = 'sticker.webp'
|
||||||
)
|
|
||||||
filename = "sticker.webp"
|
|
||||||
elif message.reply_to_message.text:
|
elif message.reply_to_message.text:
|
||||||
result = await quote_cmd(client, message)
|
result = await quote_cmd(client, message)
|
||||||
if result[1]:
|
if result[1]:
|
||||||
filename = "sticker.png"
|
filename = 'sticker.png'
|
||||||
else:
|
else:
|
||||||
filename = "sticker.webp"
|
filename = 'sticker.webp'
|
||||||
open(f"downloads/" + filename, "wb").write(result[0].getbuffer())
|
open('downloads/' + filename, 'wb').write(result[0].getbuffer())
|
||||||
coro = False
|
coro = False
|
||||||
else:
|
else:
|
||||||
filename = "photo.jpg"
|
filename = 'photo.jpg'
|
||||||
if coro:
|
if coro:
|
||||||
await message.reply_to_message.download(f"downloads/{filename}")
|
await message.reply_to_message.download(f'downloads/{filename}')
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
return await message.edit(
|
return await message.edit(
|
||||||
f"<b>Message can not be loaded:</b>\n<code>{format_exc(ex)}</code>",
|
f'<b>Message can not be loaded:</b>\n<code>{format_exc(ex)}</code>',
|
||||||
parse_mode=enums.ParseMode.HTML,
|
parse_mode=enums.ParseMode.HTML,
|
||||||
)
|
)
|
||||||
await message.edit("<b>Spinning...</b>", parse_mode=enums.ParseMode.HTML)
|
await message.edit('<b>Spinning...</b>', parse_mode=enums.ParseMode.HTML)
|
||||||
offset = int(message.command[1]) if len(message.command) > 1 else 10
|
offset = int(message.command[1]) if len(message.command) > 1 else 10
|
||||||
fps = int(message.command[2]) if len(message.command) > 2 else 30
|
fps = int(message.command[2]) if len(message.command) > 2 else 30
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
await loop.run_in_executor(
|
await loop.run_in_executor(None, lambda: create_gif(filename, offset, fps, message.command[0]))
|
||||||
None, lambda: create_gif(filename, offset, fps, message.command[0])
|
|
||||||
)
|
|
||||||
await message.delete()
|
await message.delete()
|
||||||
return await client.send_animation(
|
return await client.send_animation(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
animation="downloads/video.gif",
|
animation='downloads/video.gif',
|
||||||
reply_to_message_id=message.reply_to_message.id,
|
reply_to_message_id=message.reply_to_message.id,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.reply(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
await message.reply(format_exc(e), parse_mode=enums.ParseMode.HTML)
|
||||||
|
|
||||||
|
|
||||||
modules_help["spin"] = {
|
modules_help['spin'] = {
|
||||||
"spin [offset] [fps]": "Spin message (Reply required)",
|
'spin [offset] [fps]': 'Spin message (Reply required)',
|
||||||
"dspin [offset] [fps]": "SHAKAL spin message (Reply required)",
|
'dspin [offset] [fps]': 'SHAKAL spin message (Reply required)',
|
||||||
}
|
}
|
||||||
|
|||||||
+120
-148
@@ -18,16 +18,15 @@ import base64
|
|||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, filters, errors, types
|
from pyrogram import Client, errors, filters, types
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import with_reply, format_exc, resize_image
|
from utils.scripts import format_exc, resize_image, with_reply
|
||||||
|
|
||||||
QUOTES_API = "https://quotes-o042.onrender.com/generate"
|
QUOTES_API = 'https://quotes-o042.onrender.com/generate'
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["q", "quote"], prefix) & filters.me)
|
@Client.on_message(filters.command(['q', 'quote'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def quote_cmd(client: Client, message: Message):
|
async def quote_cmd(client: Client, message: Message):
|
||||||
if len(message.command) > 1 and message.command[1].isdigit():
|
if len(message.command) > 1 and message.command[1].isdigit():
|
||||||
@@ -39,9 +38,9 @@ async def quote_cmd(client: Client, message: Message):
|
|||||||
else:
|
else:
|
||||||
count = 1
|
count = 1
|
||||||
|
|
||||||
is_png = "!png" in message.command or "!file" in message.command
|
is_png = '!png' in message.command or '!file' in message.command
|
||||||
send_for_me = "!me" in message.command or "!ls" in message.command
|
send_for_me = '!me' in message.command or '!ls' in message.command
|
||||||
no_reply = "!noreply" in message.command or "!nr" in message.command
|
no_reply = '!noreply' in message.command or '!nr' in message.command
|
||||||
|
|
||||||
messages = []
|
messages = []
|
||||||
|
|
||||||
@@ -66,32 +65,26 @@ async def quote_cmd(client: Client, message: Message):
|
|||||||
|
|
||||||
if send_for_me:
|
if send_for_me:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
message = await client.send_message("me", "<b>Generating...</b>")
|
message = await client.send_message('me', '<b>Generating...</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Generating...</b>")
|
await message.edit('<b>Generating...</b>')
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
"messages": [
|
'messages': [await render_message(client, msg) for msg in messages if not msg.empty],
|
||||||
await render_message(client, msg) for msg in messages if not msg.empty
|
'quote_color': '#162330',
|
||||||
],
|
'text_color': '#fff',
|
||||||
"quote_color": "#162330",
|
|
||||||
"text_color": "#fff",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.post(QUOTES_API, json=params)
|
response = requests.post(QUOTES_API, json=params)
|
||||||
if not response.ok:
|
if not response.ok:
|
||||||
return await message.edit(
|
return await message.edit(f'<b>Quotes API error!</b>\n<code>{response.text}</code>')
|
||||||
f"<b>Quotes API error!</b>\n<code>{response.text}</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
resized = resize_image(
|
resized = resize_image(BytesIO(response.content), img_type='PNG' if is_png else 'WEBP')
|
||||||
BytesIO(response.content), img_type="PNG" if is_png else "WEBP"
|
await message.edit('<b>Sending...</b>')
|
||||||
)
|
|
||||||
await message.edit("<b>Sending...</b>")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
func = client.send_document if is_png else client.send_sticker
|
func = client.send_document if is_png else client.send_sticker
|
||||||
chat_id = "me" if send_for_me else message.chat.id
|
chat_id = 'me' if send_for_me else message.chat.id
|
||||||
await func(chat_id, resized)
|
await func(chat_id, resized)
|
||||||
except errors.RPCError as e: # no rights to send stickers, etc
|
except errors.RPCError as e: # no rights to send stickers, etc
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
@@ -99,23 +92,21 @@ async def quote_cmd(client: Client, message: Message):
|
|||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["fq", "fakequote"], prefix) & filters.me)
|
@Client.on_message(filters.command(['fq', 'fakequote'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def fake_quote_cmd(client: Client, message: types.Message):
|
async def fake_quote_cmd(client: Client, message: types.Message):
|
||||||
is_png = "!png" in message.command or "!file" in message.command
|
is_png = '!png' in message.command or '!file' in message.command
|
||||||
send_for_me = "!me" in message.command or "!ls" in message.command
|
send_for_me = '!me' in message.command or '!ls' in message.command
|
||||||
no_reply = "!noreply" in message.command or "!nr" in message.command
|
no_reply = '!noreply' in message.command or '!nr' in message.command
|
||||||
|
|
||||||
fake_quote_text = " ".join(
|
fake_quote_text = ' '.join(
|
||||||
[
|
[
|
||||||
arg
|
arg for arg in message.command[1:] if arg not in ['!png', '!file', '!me', '!ls', '!noreply', '!nr']
|
||||||
for arg in message.command[1:]
|
|
||||||
if arg not in ["!png", "!file", "!me", "!ls", "!noreply", "!nr"]
|
|
||||||
] # remove some special arg words
|
] # remove some special arg words
|
||||||
)
|
)
|
||||||
|
|
||||||
if not fake_quote_text:
|
if not fake_quote_text:
|
||||||
return await message.edit("<b>Fake quote text is empty</b>")
|
return await message.edit('<b>Fake quote text is empty</b>')
|
||||||
|
|
||||||
q_message = await client.get_messages(message.chat.id, message.reply_to_message.id)
|
q_message = await client.get_messages(message.chat.id, message.reply_to_message.id)
|
||||||
q_message.text = fake_quote_text
|
q_message.text = fake_quote_text
|
||||||
@@ -125,30 +116,26 @@ async def fake_quote_cmd(client: Client, message: types.Message):
|
|||||||
|
|
||||||
if send_for_me:
|
if send_for_me:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
message = await client.send_message("me", "<b>Generating...</b>")
|
message = await client.send_message('me', '<b>Generating...</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Generating...</b>")
|
await message.edit('<b>Generating...</b>')
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
"messages": [await render_message(client, q_message)],
|
'messages': [await render_message(client, q_message)],
|
||||||
"quote_color": "#162330",
|
'quote_color': '#162330',
|
||||||
"text_color": "#fff",
|
'text_color': '#fff',
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.post(QUOTES_API, json=params)
|
response = requests.post(QUOTES_API, json=params)
|
||||||
if not response.ok:
|
if not response.ok:
|
||||||
return await message.edit(
|
return await message.edit(f'<b>Quotes API error!</b>\n<code>{response.text}</code>')
|
||||||
f"<b>Quotes API error!</b>\n<code>{response.text}</code>"
|
|
||||||
)
|
|
||||||
|
|
||||||
resized = resize_image(
|
resized = resize_image(BytesIO(response.content), img_type='PNG' if is_png else 'WEBP')
|
||||||
BytesIO(response.content), img_type="PNG" if is_png else "WEBP"
|
await message.edit('<b>Sending...</b>')
|
||||||
)
|
|
||||||
await message.edit("<b>Sending...</b>")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
func = client.send_document if is_png else client.send_sticker
|
func = client.send_document if is_png else client.send_sticker
|
||||||
chat_id = "me" if send_for_me else message.chat.id
|
chat_id = 'me' if send_for_me else message.chat.id
|
||||||
await func(chat_id, resized)
|
await func(chat_id, resized)
|
||||||
except errors.RPCError as e: # no rights to send stickers, etc
|
except errors.RPCError as e: # no rights to send stickers, etc
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
@@ -171,11 +158,11 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
|
|
||||||
# text
|
# text
|
||||||
if message.photo:
|
if message.photo:
|
||||||
text = message.caption if message.caption else ""
|
text = message.caption if message.caption else ''
|
||||||
elif message.poll:
|
elif message.poll:
|
||||||
text = get_poll_text(message.poll)
|
text = get_poll_text(message.poll)
|
||||||
elif message.sticker:
|
elif message.sticker:
|
||||||
text = ""
|
text = ''
|
||||||
else:
|
else:
|
||||||
text = get_reply_text(message)
|
text = get_reply_text(message)
|
||||||
|
|
||||||
@@ -185,7 +172,7 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
elif message.sticker:
|
elif message.sticker:
|
||||||
media = await get_file(message.sticker.file_id)
|
media = await get_file(message.sticker.file_id)
|
||||||
else:
|
else:
|
||||||
media = ""
|
media = ''
|
||||||
|
|
||||||
# entities
|
# entities
|
||||||
entities = []
|
entities = []
|
||||||
@@ -193,9 +180,9 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
for entity in message.entities:
|
for entity in message.entities:
|
||||||
entities.append(
|
entities.append(
|
||||||
{
|
{
|
||||||
"offset": entity.offset,
|
'offset': entity.offset,
|
||||||
"length": entity.length,
|
'length': entity.length,
|
||||||
"type": str(entity.type).split(".")[-1].lower(),
|
'type': str(entity.type).split('.')[-1].lower(),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -206,7 +193,7 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
elif isinstance(msg.forward_origin, types.MessageOriginHiddenUser):
|
elif isinstance(msg.forward_origin, types.MessageOriginHiddenUser):
|
||||||
msg.from_user.id = 0
|
msg.from_user.id = 0
|
||||||
msg.from_user.first_name = msg.forward_origin.sender_user_name
|
msg.from_user.first_name = msg.forward_origin.sender_user_name
|
||||||
msg.from_user.last_name = ""
|
msg.from_user.last_name = ''
|
||||||
elif isinstance(msg.forward_origin, types.MessageOriginChat):
|
elif isinstance(msg.forward_origin, types.MessageOriginChat):
|
||||||
msg.sender_chat = msg.forward_origin.sender_chat
|
msg.sender_chat = msg.forward_origin.sender_chat
|
||||||
msg.from_user.id = 0
|
msg.from_user.id = 0
|
||||||
@@ -220,63 +207,55 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
if message.from_user and message.from_user.id != 0:
|
if message.from_user and message.from_user.id != 0:
|
||||||
from_user = message.from_user
|
from_user = message.from_user
|
||||||
|
|
||||||
author["id"] = from_user.id
|
author['id'] = from_user.id
|
||||||
author["name"] = get_full_name(from_user)
|
author['name'] = get_full_name(from_user)
|
||||||
if message.author_signature:
|
if message.author_signature:
|
||||||
author["rank"] = message.author_signature
|
author['rank'] = message.author_signature
|
||||||
elif message.chat.type != "supergroup" or message.forward_date:
|
elif message.chat.type != 'supergroup' or message.forward_date:
|
||||||
author["rank"] = ""
|
author['rank'] = ''
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
member = await message.chat.get_member(from_user.id)
|
member = await message.chat.get_member(from_user.id)
|
||||||
except errors.UserNotParticipant:
|
except errors.UserNotParticipant:
|
||||||
author["rank"] = ""
|
author['rank'] = ''
|
||||||
else:
|
else:
|
||||||
author["rank"] = getattr(member, "title", "") or (
|
author['rank'] = getattr(member, 'title', '') or (
|
||||||
"owner"
|
'owner' if member.status == 'creator' else 'admin' if member.status == 'administrator' else ''
|
||||||
if member.status == "creator"
|
|
||||||
else "admin"
|
|
||||||
if member.status == "administrator"
|
|
||||||
else ""
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if from_user.photo:
|
if from_user.photo:
|
||||||
author["avatar"] = await get_file(from_user.photo.big_file_id)
|
author['avatar'] = await get_file(from_user.photo.big_file_id)
|
||||||
elif not from_user.photo and from_user.username:
|
elif not from_user.photo and from_user.username:
|
||||||
# may be user blocked us, we will try to get avatar via t.me
|
# may be user blocked us, we will try to get avatar via t.me
|
||||||
t_me_page = requests.get(f"https://t.me/{from_user.username}").text
|
t_me_page = requests.get(f'https://t.me/{from_user.username}').text
|
||||||
sub = '<meta property="og:image" content='
|
sub = '<meta property="og:image" content='
|
||||||
index = t_me_page.find(sub)
|
index = t_me_page.find(sub)
|
||||||
if index != -1:
|
if index != -1:
|
||||||
link = t_me_page[index + 35 :].split('"')
|
link = t_me_page[index + 35 :].split('"')
|
||||||
if (
|
if len(link) > 0 and link[0] and link[0] != 'https://telegram.org/img/t_logo.png':
|
||||||
len(link) > 0
|
|
||||||
and link[0]
|
|
||||||
and link[0] != "https://telegram.org/img/t_logo.png"
|
|
||||||
):
|
|
||||||
# found valid link
|
# found valid link
|
||||||
avatar = requests.get(link[0]).content
|
avatar = requests.get(link[0]).content
|
||||||
author["avatar"] = base64.b64encode(avatar).decode()
|
author['avatar'] = base64.b64encode(avatar).decode()
|
||||||
else:
|
else:
|
||||||
author["avatar"] = ""
|
author['avatar'] = ''
|
||||||
else:
|
else:
|
||||||
author["avatar"] = ""
|
author['avatar'] = ''
|
||||||
else:
|
else:
|
||||||
author["avatar"] = ""
|
author['avatar'] = ''
|
||||||
elif message.from_user and message.from_user.id == 0:
|
elif message.from_user and message.from_user.id == 0:
|
||||||
author["id"] = 0
|
author['id'] = 0
|
||||||
author["name"] = message.from_user.first_name
|
author['name'] = message.from_user.first_name
|
||||||
author["rank"] = ""
|
author['rank'] = ''
|
||||||
else:
|
else:
|
||||||
author["id"] = message.sender_chat.id
|
author['id'] = message.sender_chat.id
|
||||||
author["name"] = message.sender_chat.title
|
author['name'] = message.sender_chat.title
|
||||||
author["rank"] = "channel" if message.sender_chat.type == "channel" else ""
|
author['rank'] = 'channel' if message.sender_chat.type == 'channel' else ''
|
||||||
|
|
||||||
if message.sender_chat.photo:
|
if message.sender_chat.photo:
|
||||||
author["avatar"] = await get_file(message.sender_chat.photo.big_file_id)
|
author['avatar'] = await get_file(message.sender_chat.photo.big_file_id)
|
||||||
else:
|
else:
|
||||||
author["avatar"] = ""
|
author['avatar'] = ''
|
||||||
author["via_bot"] = message.via_bot.username if message.via_bot else ""
|
author['via_bot'] = message.via_bot.username if message.via_bot else ''
|
||||||
|
|
||||||
# reply
|
# reply
|
||||||
reply = {}
|
reply = {}
|
||||||
@@ -285,129 +264,122 @@ async def render_message(app: Client, message: types.Message) -> dict:
|
|||||||
move_forwards(reply_msg)
|
move_forwards(reply_msg)
|
||||||
|
|
||||||
if reply_msg.from_user:
|
if reply_msg.from_user:
|
||||||
reply["id"] = reply_msg.from_user.id
|
reply['id'] = reply_msg.from_user.id
|
||||||
reply["name"] = get_full_name(reply_msg.from_user)
|
reply['name'] = get_full_name(reply_msg.from_user)
|
||||||
else:
|
else:
|
||||||
reply["id"] = reply_msg.sender_chat.id
|
reply['id'] = reply_msg.sender_chat.id
|
||||||
reply["name"] = reply_msg.sender_chat.title
|
reply['name'] = reply_msg.sender_chat.title
|
||||||
|
|
||||||
reply["text"] = get_reply_text(reply_msg)
|
reply['text'] = get_reply_text(reply_msg)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"text": text,
|
'text': text,
|
||||||
"media": media,
|
'media': media,
|
||||||
"entities": entities,
|
'entities': entities,
|
||||||
"author": author,
|
'author': author,
|
||||||
"reply": reply,
|
'reply': reply,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def get_audio_text(audio: types.Audio) -> str:
|
def get_audio_text(audio: types.Audio) -> str:
|
||||||
if audio.title and audio.performer:
|
if audio.title and audio.performer:
|
||||||
return f" ({audio.title} — {audio.performer})"
|
return f' ({audio.title} — {audio.performer})'
|
||||||
if audio.title:
|
if audio.title:
|
||||||
return f" ({audio.title})"
|
return f' ({audio.title})'
|
||||||
if audio.performer:
|
if audio.performer:
|
||||||
return f" ({audio.performer})"
|
return f' ({audio.performer})'
|
||||||
return ""
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def get_reply_text(reply: types.Message) -> str:
|
def get_reply_text(reply: types.Message) -> str:
|
||||||
return (
|
return (
|
||||||
"📷 Photo" + ("\n" + reply.caption if reply.caption else "")
|
'📷 Photo' + ('\n' + reply.caption if reply.caption else '')
|
||||||
if reply.photo
|
if reply.photo
|
||||||
else (
|
else (
|
||||||
get_reply_poll_text(reply.poll)
|
get_reply_poll_text(reply.poll)
|
||||||
if reply.poll
|
if reply.poll
|
||||||
else (
|
else (
|
||||||
"📍 Location"
|
'📍 Location'
|
||||||
if reply.location or reply.venue
|
if reply.location or reply.venue
|
||||||
else (
|
else (
|
||||||
"👤 Contact"
|
'👤 Contact'
|
||||||
if reply.contact
|
if reply.contact
|
||||||
else (
|
else (
|
||||||
"🖼 GIF"
|
'🖼 GIF'
|
||||||
if reply.animation
|
if reply.animation
|
||||||
else (
|
else (
|
||||||
"🎧 Music" + get_audio_text(reply.audio)
|
'🎧 Music' + get_audio_text(reply.audio)
|
||||||
if reply.audio
|
if reply.audio
|
||||||
else (
|
else (
|
||||||
"📹 Video"
|
'📹 Video'
|
||||||
if reply.video
|
if reply.video
|
||||||
else (
|
else (
|
||||||
"📹 Videomessage"
|
'📹 Videomessage'
|
||||||
if reply.video_note
|
if reply.video_note
|
||||||
else (
|
else (
|
||||||
"🎵 Voice"
|
'🎵 Voice'
|
||||||
if reply.voice
|
if reply.voice
|
||||||
else (
|
else (
|
||||||
(
|
(reply.sticker.emoji + ' ' if reply.sticker.emoji else '') + 'Sticker'
|
||||||
reply.sticker.emoji + " "
|
|
||||||
if reply.sticker.emoji
|
|
||||||
else ""
|
|
||||||
)
|
|
||||||
+ "Sticker"
|
|
||||||
if reply.sticker
|
if reply.sticker
|
||||||
else (
|
else (
|
||||||
"💾 File " + reply.document.file_name
|
'💾 File ' + reply.document.file_name
|
||||||
if reply.document
|
if reply.document
|
||||||
else (
|
else (
|
||||||
"🎮 Game"
|
'🎮 Game'
|
||||||
if reply.game
|
if reply.game
|
||||||
else (
|
else (
|
||||||
"🎮 set new record"
|
'🎮 set new record'
|
||||||
if reply.game_high_score
|
if reply.game_high_score
|
||||||
else (
|
else (
|
||||||
f"{reply.dice.emoji} - {reply.dice.value}"
|
f'{reply.dice.emoji} - {reply.dice.value}'
|
||||||
if reply.dice
|
if reply.dice
|
||||||
else (
|
else (
|
||||||
(
|
(
|
||||||
"👤 joined the group"
|
'👤 joined the group'
|
||||||
if reply.new_chat_members[
|
if reply.new_chat_members[0].id
|
||||||
0
|
|
||||||
].id
|
|
||||||
== reply.from_user.id
|
== reply.from_user.id
|
||||||
else f"👤 invited {get_full_name(reply.new_chat_members[0])} to the group"
|
else f'👤 invited {get_full_name(reply.new_chat_members[0])} to the group'
|
||||||
)
|
)
|
||||||
if reply.new_chat_members
|
if reply.new_chat_members
|
||||||
else (
|
else (
|
||||||
(
|
(
|
||||||
"👤 left the group"
|
'👤 left the group'
|
||||||
if reply.left_chat_member.id
|
if reply.left_chat_member.id
|
||||||
== reply.from_user.id
|
== reply.from_user.id
|
||||||
else f"👤 removed {get_full_name(reply.left_chat_member)}"
|
else f'👤 removed {get_full_name(reply.left_chat_member)}'
|
||||||
)
|
)
|
||||||
if reply.left_chat_member
|
if reply.left_chat_member
|
||||||
else (
|
else (
|
||||||
f"✏ changed group name to {reply.new_chat_title}"
|
f'✏ changed group name to {reply.new_chat_title}'
|
||||||
if reply.new_chat_title
|
if reply.new_chat_title
|
||||||
else (
|
else (
|
||||||
"🖼 changed group photo"
|
'🖼 changed group photo'
|
||||||
if reply.new_chat_photo
|
if reply.new_chat_photo
|
||||||
else (
|
else (
|
||||||
"🖼 removed group photo"
|
'🖼 removed group photo'
|
||||||
if reply.delete_chat_photo
|
if reply.delete_chat_photo
|
||||||
else (
|
else (
|
||||||
"📍 pinned message"
|
'📍 pinned message'
|
||||||
if reply.pinned_message
|
if reply.pinned_message
|
||||||
else (
|
else (
|
||||||
"🎤 started a new video chat"
|
'🎤 started a new video chat'
|
||||||
if reply.video_chat_started
|
if reply.video_chat_started
|
||||||
else (
|
else (
|
||||||
"🎤 ended the video chat"
|
'🎤 ended the video chat'
|
||||||
if reply.video_chat_ended
|
if reply.video_chat_ended
|
||||||
else (
|
else (
|
||||||
"🎤 invited participants to the video chat"
|
'🎤 invited participants to the video chat'
|
||||||
if reply.video_chat_members_invited
|
if reply.video_chat_members_invited
|
||||||
else (
|
else (
|
||||||
"👥 created the group"
|
'👥 created the group'
|
||||||
if reply.group_chat_created
|
if reply.group_chat_created
|
||||||
or reply.supergroup_chat_created
|
or reply.supergroup_chat_created
|
||||||
else (
|
else (
|
||||||
"👥 created the channel"
|
'👥 created the channel'
|
||||||
if reply.channel_chat_created
|
if reply.channel_chat_created
|
||||||
else reply.text
|
else reply.text
|
||||||
or "unsupported message"
|
or 'unsupported message'
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -436,27 +408,27 @@ def get_reply_text(reply: types.Message) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def get_poll_text(poll: types.Poll) -> str:
|
def get_poll_text(poll: types.Poll) -> str:
|
||||||
text = get_reply_poll_text(poll) + "\n"
|
text = get_reply_poll_text(poll) + '\n'
|
||||||
|
|
||||||
text += poll.question + "\n"
|
text += poll.question + '\n'
|
||||||
for option in poll.options:
|
for option in poll.options:
|
||||||
text += f"- {option.text}"
|
text += f'- {option.text}'
|
||||||
if option.voter_count > 0:
|
if option.voter_count > 0:
|
||||||
text += f" ({option.voter_count} voted)"
|
text += f' ({option.voter_count} voted)'
|
||||||
text += "\n"
|
text += '\n'
|
||||||
|
|
||||||
text += f"Total: {poll.total_voter_count} voted"
|
text += f'Total: {poll.total_voter_count} voted'
|
||||||
|
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
def get_reply_poll_text(poll: types.Poll) -> str:
|
def get_reply_poll_text(poll: types.Poll) -> str:
|
||||||
if poll.is_anonymous:
|
if poll.is_anonymous:
|
||||||
text = "📊 Anonymous poll" if poll.type == "regular" else "📊 Anonymous quiz"
|
text = '📊 Anonymous poll' if poll.type == 'regular' else '📊 Anonymous quiz'
|
||||||
else:
|
else:
|
||||||
text = "📊 Poll" if poll.type == "regular" else "📊 Quiz"
|
text = '📊 Poll' if poll.type == 'regular' else '📊 Quiz'
|
||||||
if poll.is_closed:
|
if poll.is_closed:
|
||||||
text += " (closed)"
|
text += ' (closed)'
|
||||||
|
|
||||||
return text
|
return text
|
||||||
|
|
||||||
@@ -464,13 +436,13 @@ def get_reply_poll_text(poll: types.Poll) -> str:
|
|||||||
def get_full_name(user: types.User) -> str:
|
def get_full_name(user: types.User) -> str:
|
||||||
name = user.first_name
|
name = user.first_name
|
||||||
if user.last_name:
|
if user.last_name:
|
||||||
name += " " + user.last_name
|
name += ' ' + user.last_name
|
||||||
return name
|
return name
|
||||||
|
|
||||||
|
|
||||||
modules_help["squotes"] = {
|
modules_help['squotes'] = {
|
||||||
"q [reply]* [count 1-15] [!png] [!me] [!noreply]": "Generate a quote\n"
|
'q [reply]* [count 1-15] [!png] [!me] [!noreply]': 'Generate a quote\n'
|
||||||
"Available options: !png — send as PNG, !me — send quote to"
|
'Available options: !png — send as PNG, !me — send quote to'
|
||||||
"saved messages, !noreply — generate quote without reply",
|
'saved messages, !noreply — generate quote without reply',
|
||||||
"fq [reply]* [!png] [!me] [!noreply] [text]*": "Generate a fake quote",
|
'fq [reply]* [!png] [!me] [!noreply] [text]*': 'Generate a fake quote',
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-63
@@ -17,27 +17,25 @@
|
|||||||
import os
|
import os
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
from pyrogram import Client, filters, types, enums
|
from pyrogram import Client, enums, filters, types
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import (
|
from utils.scripts import (
|
||||||
with_reply,
|
format_exc,
|
||||||
interact_with,
|
interact_with,
|
||||||
interact_with_to_delete,
|
interact_with_to_delete,
|
||||||
format_exc,
|
|
||||||
resize_image,
|
resize_image,
|
||||||
|
with_reply,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("kang", prefix) & filters.me)
|
@Client.on_message(filters.command('kang', prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def kang(client: Client, message: types.Message):
|
async def kang(client: Client, message: types.Message):
|
||||||
await message.edit("<b>Please wait...</b>")
|
await message.edit('<b>Please wait...</b>')
|
||||||
|
|
||||||
if len(message.command) < 2:
|
if len(message.command) < 2:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>No arguments provided\n"
|
f'<b>No arguments provided\nUsage: <code>{prefix}kang [pack]* [emoji]</code></b>',
|
||||||
f"Usage: <code>{prefix}kang [pack]* [emoji]</code></b>",
|
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -45,29 +43,17 @@ async def kang(client: Client, message: types.Message):
|
|||||||
if len(message.command) >= 3:
|
if len(message.command) >= 3:
|
||||||
emoji = message.command[2]
|
emoji = message.command[2]
|
||||||
else:
|
else:
|
||||||
emoji = "✨"
|
emoji = '✨'
|
||||||
|
|
||||||
await client.unblock_user("@stickers")
|
await client.unblock_user('@stickers')
|
||||||
await interact_with(
|
await interact_with(await client.send_message('@stickers', '/cancel', parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
await client.send_message(
|
await interact_with(await client.send_message('@stickers', '/addsticker', parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
"@stickers", "/cancel", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
)
|
|
||||||
await interact_with(
|
|
||||||
await client.send_message(
|
|
||||||
"@stickers", "/addsticker", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
result = await interact_with(
|
result = await interact_with(await client.send_message('@stickers', pack, parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
await client.send_message(
|
if '.TGS' in result.text:
|
||||||
"@stickers", pack, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if ".TGS" in result.text:
|
|
||||||
await message.edit("<b>Animated packs aren't supported</b>")
|
await message.edit("<b>Animated packs aren't supported</b>")
|
||||||
return
|
return
|
||||||
if "StickerExample.psd" not in result.text:
|
if 'StickerExample.psd' not in result.text:
|
||||||
await message.edit(
|
await message.edit(
|
||||||
"<b>Stickerpack doesn't exitst. Create it using @Stickers bot (via /newpack command)</b>",
|
"<b>Stickerpack doesn't exitst. Create it using @Stickers bot (via /newpack command)</b>",
|
||||||
)
|
)
|
||||||
@@ -85,79 +71,63 @@ async def kang(client: Client, message: types.Message):
|
|||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
await interact_with(
|
await interact_with(await client.send_document('@stickers', resized, parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
await client.send_document(
|
response = await interact_with(await client.send_message('@stickers', emoji, parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
"@stickers", resized, parse_mode=enums.ParseMode.MARKDOWN
|
if '/done' in response.text:
|
||||||
)
|
|
||||||
)
|
|
||||||
response = await interact_with(
|
|
||||||
await client.send_message(
|
|
||||||
"@stickers", emoji, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if "/done" in response.text:
|
|
||||||
# ok
|
# ok
|
||||||
await interact_with(
|
await interact_with(await client.send_message('@stickers', '/done', parse_mode=enums.ParseMode.MARKDOWN))
|
||||||
await client.send_message(
|
await client.delete_messages('@stickers', interact_with_to_delete)
|
||||||
"@stickers", "/done", parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
)
|
|
||||||
await client.delete_messages("@stickers", interact_with_to_delete)
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Sticker added to <a href=https://t.me/addstickers/{pack}>pack</a></b>",
|
f'<b>Sticker added to <a href=https://t.me/addstickers/{pack}>pack</a></b>',
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Something went wrong. Check history with @stickers</b>")
|
await message.edit('<b>Something went wrong. Check history with @stickers</b>')
|
||||||
interact_with_to_delete.clear()
|
interact_with_to_delete.clear()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["stp", "s2p", "stick2png"], prefix) & filters.me)
|
@Client.on_message(filters.command(['stp', 's2p', 'stick2png'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def stick2png(client: Client, message: types.Message):
|
async def stick2png(client: Client, message: types.Message):
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Downloading...</b>")
|
await message.edit('<b>Downloading...</b>')
|
||||||
|
|
||||||
path = await message.reply_to_message.download()
|
path = await message.reply_to_message.download()
|
||||||
with open(path, "rb") as f:
|
with open(path, 'rb') as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
file_io = BytesIO(content)
|
file_io = BytesIO(content)
|
||||||
file_io.name = "sticker.png"
|
file_io.name = 'sticker.png'
|
||||||
|
|
||||||
await client.send_document(
|
await client.send_document(message.chat.id, file_io, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
message.chat.id, file_io, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
else:
|
else:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["resize"], prefix) & filters.me)
|
@Client.on_message(filters.command(['resize'], prefix) & filters.me)
|
||||||
@with_reply
|
@with_reply
|
||||||
async def resize_cmd(client: Client, message: types.Message):
|
async def resize_cmd(client: Client, message: types.Message):
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Downloading...</b>")
|
await message.edit('<b>Downloading...</b>')
|
||||||
|
|
||||||
path = await message.reply_to_message.download()
|
path = await message.reply_to_message.download()
|
||||||
resized = resize_image(path)
|
resized = resize_image(path)
|
||||||
resized.name = "image.png"
|
resized.name = 'image.png'
|
||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
await client.send_document(
|
await client.send_document(message.chat.id, resized, parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
message.chat.id, resized, parse_mode=enums.ParseMode.MARKDOWN
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
else:
|
else:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
|
|
||||||
|
|
||||||
modules_help["stickers"] = {
|
modules_help['stickers'] = {
|
||||||
"kang [reply]* [pack]* [emoji]": "Add sticker to defined pack",
|
'kang [reply]* [pack]* [emoji]': 'Add sticker to defined pack',
|
||||||
"stp [reply]*": "Convert replied sticker to PNG",
|
'stp [reply]*': 'Convert replied sticker to PNG',
|
||||||
"resize [reply]*": "Resize replied image to 512xN format",
|
'resize [reply]*': 'Resize replied image to 512xN format',
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-36
@@ -14,17 +14,17 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import random
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
import random
|
from utils.misc import gitrepo, modules_help, prefix, python_version, userbot_version
|
||||||
import datetime
|
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix, userbot_version, python_version, gitrepo
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["support", "repo"], prefix) & filters.me)
|
@Client.on_message(filters.command(['support', 'repo'], prefix) & filters.me)
|
||||||
async def support(_, message: Message):
|
async def support(_, message: Message):
|
||||||
devs = ["@Qbtaumai", "@H4T3H46K3R"]
|
devs = ['@Qbtaumai', '@H4T3H46K3R']
|
||||||
random.shuffle(devs)
|
random.shuffle(devs)
|
||||||
|
|
||||||
commands_count = 0.0
|
commands_count = 0.0
|
||||||
@@ -33,27 +33,27 @@ async def support(_, message: Message):
|
|||||||
commands_count += 1
|
commands_count += 1
|
||||||
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Moon-Userbot\n\n"
|
f'<b>Moon-Userbot\n\n'
|
||||||
"GitHub: <a href=https://github.com/The-MoonTg-project/Moon-Userbot>Moon-Userbot</a>\n"
|
'GitHub: <a href=https://github.com/The-MoonTg-project/Moon-Userbot>Moon-Userbot</a>\n'
|
||||||
"Custom modules repository: <a href=https://github.com/The-MoonTg-project/custom_modules>"
|
'Custom modules repository: <a href=https://github.com/The-MoonTg-project/custom_modules>'
|
||||||
"custom_modules</a>\n"
|
'custom_modules</a>\n'
|
||||||
"License: <a href=https://github.com/The-MoonTg-project/Moon-Userbot/blob/master/LICENSE>GNU GPL v3</a>\n\n"
|
'License: <a href=https://github.com/The-MoonTg-project/Moon-Userbot/blob/master/LICENSE>GNU GPL v3</a>\n\n'
|
||||||
"Channel: @moonuserbot\n"
|
'Channel: @moonuserbot\n'
|
||||||
"Custom modules: @moonub_modules\n"
|
'Custom modules: @moonub_modules\n'
|
||||||
"Chat [EN]: @moonub_chat\n"
|
'Chat [EN]: @moonub_chat\n'
|
||||||
f"Main developers: {', '.join(devs)}\n\n"
|
f'Main developers: {", ".join(devs)}\n\n'
|
||||||
f"Python version: {python_version}\n"
|
f'Python version: {python_version}\n'
|
||||||
f"Modules count: {len(modules_help) / 1}\n"
|
f'Modules count: {len(modules_help) / 1}\n'
|
||||||
f"Commands count: {commands_count}</b>",
|
f'Commands count: {commands_count}</b>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["version", "ver"], prefix) & filters.me)
|
@Client.on_message(filters.command(['version', 'ver'], prefix) & filters.me)
|
||||||
async def version(client: Client, message: Message):
|
async def version(client: Client, message: Message):
|
||||||
changelog = ""
|
changelog = ''
|
||||||
ub_version = ".".join(userbot_version.split(".")[:2])
|
ub_version = '.'.join(userbot_version.split('.')[:2])
|
||||||
async for m in client.search_messages("moonuserbot", query=f"{userbot_version}."):
|
async for m in client.search_messages('moonuserbot', query=f'{userbot_version}.'):
|
||||||
if ub_version in m.text:
|
if ub_version in m.text:
|
||||||
changelog = m.message_id
|
changelog = m.message_id
|
||||||
|
|
||||||
@@ -63,26 +63,32 @@ async def version(client: Client, message: Message):
|
|||||||
remote_url = list(gitrepo.remote().urls)[0]
|
remote_url = list(gitrepo.remote().urls)[0]
|
||||||
commit_time = (
|
commit_time = (
|
||||||
datetime.datetime.fromtimestamp(gitrepo.head.commit.committed_date)
|
datetime.datetime.fromtimestamp(gitrepo.head.commit.committed_date)
|
||||||
.astimezone(datetime.timezone.utc)
|
.astimezone(datetime.UTC)
|
||||||
.strftime("%Y-%m-%d %H:%M:%S %Z")
|
.strftime('%Y-%m-%d %H:%M:%S %Z')
|
||||||
)
|
)
|
||||||
git_info = (
|
git_info = (
|
||||||
f"\n<b>Branch: <a href={remote_url}/tree/{gitrepo.active_branch}>{gitrepo.active_branch}</a>\n"
|
(
|
||||||
if gitrepo.active_branch != "master" else "\n"
|
f'\n<b>Branch: <a href={remote_url}/tree/{gitrepo.active_branch}>{gitrepo.active_branch}</a>\n'
|
||||||
) + f"Commit: <a href={remote_url}/commit/{gitrepo.head.commit.hexsha}>" f"{gitrepo.head.commit.hexsha[:7]}</a> by {gitrepo.head.commit.author.name}\n" f"Commit time: {commit_time}</b>"
|
if gitrepo.active_branch != 'master'
|
||||||
|
else '\n'
|
||||||
|
)
|
||||||
|
+ f'Commit: <a href={remote_url}/commit/{gitrepo.head.commit.hexsha}>'
|
||||||
|
f'{gitrepo.head.commit.hexsha[:7]}</a> by {gitrepo.head.commit.author.name}\n'
|
||||||
|
f'Commit time: {commit_time}</b>'
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
git_info = ""
|
git_info = ''
|
||||||
|
|
||||||
await message.reply(
|
await message.reply(
|
||||||
f"<b>Moon Userbot version: {userbot_version}\n"
|
f'<b>Moon Userbot version: {userbot_version}\n'
|
||||||
f"Changelog </b><i><a href=https://t.me/moonuserbot/{changelog}>in channel</a></i>.<b>\n"
|
f'Changelog </b><i><a href=https://t.me/moonuserbot/{changelog}>in channel</a></i>.<b>\n'
|
||||||
f"Changelog written by </b><i>"
|
f'Changelog written by </b><i>'
|
||||||
f"<a href=https://t.me/Qbtaumai>Abhi</a></i>\n\n"
|
f'<a href=https://t.me/Qbtaumai>Abhi</a></i>\n\n'
|
||||||
f"{git_info}",
|
f'{git_info}',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
modules_help["support"] = {
|
modules_help['support'] = {
|
||||||
"support": "Information about userbot",
|
'support': 'Information about userbot',
|
||||||
"version": "Check userbot version",
|
'version': 'Check userbot version',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,29 +15,28 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from PIL import Image
|
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
from utils.misc import modules_help, prefix
|
||||||
from utils.misc import prefix, modules_help
|
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("setthumb", prefix) & filters.me)
|
@Client.on_message(filters.command('setthumb', prefix) & filters.me)
|
||||||
async def setthumb(_, message: Message):
|
async def setthumb(_, message: Message):
|
||||||
THUMB_PATH = "downloads/thumb"
|
THUMB_PATH = 'downloads/thumb'
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
if not os.path.exists(THUMB_PATH):
|
if not os.path.exists(THUMB_PATH):
|
||||||
os.makedirs(THUMB_PATH)
|
os.makedirs(THUMB_PATH)
|
||||||
new_thumb = await message.reply_to_message.download()
|
new_thumb = await message.reply_to_message.download()
|
||||||
with Image.open(new_thumb) as img:
|
with Image.open(new_thumb) as img:
|
||||||
if img.format in ["PNG", "JPG", "JPEG"]:
|
if img.format in ['PNG', 'JPG', 'JPEG']:
|
||||||
new_path = os.path.join(THUMB_PATH, "thumb.jpg")
|
new_path = os.path.join(THUMB_PATH, 'thumb.jpg')
|
||||||
os.rename(new_thumb, new_path)
|
os.rename(new_thumb, new_path)
|
||||||
await message.edit_text("Thumbnail set successfully!")
|
await message.edit_text('Thumbnail set successfully!')
|
||||||
else:
|
else:
|
||||||
await message.edit_text("Kindly reply to a PHOTO Entity!")
|
await message.edit_text('Kindly reply to a PHOTO Entity!')
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
modules_help["thumb"] = {"setthumb [reply_to_photo]*": "set your own custom thumbnail"}
|
modules_help['thumb'] = {'setthumb [reply_to_photo]*': 'set your own custom thumbnail'}
|
||||||
|
|||||||
@@ -15,20 +15,17 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import time
|
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.errors import FloodWait
|
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["type", "typewriter"], prefix) & filters.me)
|
@Client.on_message(filters.command(['type', 'typewriter'], prefix) & filters.me)
|
||||||
async def type_cmd(_, message: Message):
|
async def type_cmd(_, message: Message):
|
||||||
text = message.text.split(maxsplit=1)[1]
|
text = message.text.split(maxsplit=1)[1]
|
||||||
typed = ""
|
typed = ''
|
||||||
typing_symbol = "▒"
|
typing_symbol = '▒'
|
||||||
|
|
||||||
for char in text:
|
for char in text:
|
||||||
await message.edit(typed + typing_symbol)
|
await message.edit(typed + typing_symbol)
|
||||||
@@ -38,6 +35,6 @@ async def type_cmd(_, message: Message):
|
|||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
|
|
||||||
modules_help["type"] = {
|
modules_help['type'] = {
|
||||||
"type</code> <code>| </code><code>typewriter [text]*": "Typing emulation. Don't use a lot of characters, you can receive a lot of floodwaits!"
|
'type</code> <code>| </code><code>typewriter [text]*': "Typing emulation. Don't use a lot of characters, you can receive a lot of floodwaits!"
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-48
@@ -15,15 +15,14 @@
|
|||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix, requirements_list
|
|
||||||
from utils.db import db
|
from utils.db import db
|
||||||
|
from utils.misc import modules_help, prefix, requirements_list
|
||||||
from utils.scripts import format_exc, restart
|
from utils.scripts import format_exc, restart
|
||||||
|
|
||||||
|
|
||||||
@@ -31,87 +30,82 @@ def check_command(command):
|
|||||||
return shutil.which(command) is not None
|
return shutil.which(command) is not None
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("restart", prefix) & filters.me)
|
@Client.on_message(filters.command('restart', prefix) & filters.me)
|
||||||
async def restart_cmd(_, message: Message):
|
async def restart_cmd(_, message: Message):
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "restart",
|
'type': 'restart',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
if "LAVHOST" in os.environ:
|
if 'LAVHOST' in os.environ:
|
||||||
await message.edit("<b>Your lavHost is restarting...</b>")
|
await message.edit('<b>Your lavHost is restarting...</b>')
|
||||||
os.system("lavhost restart")
|
os.system('lavhost restart')
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("<b>Restarting...</b>")
|
await message.edit('<b>Restarting...</b>')
|
||||||
if os.path.exists("moonlogs.txt"):
|
if os.path.exists('moonlogs.txt'):
|
||||||
os.remove("moonlogs.txt")
|
os.remove('moonlogs.txt')
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("update", prefix) & filters.me)
|
@Client.on_message(filters.command('update', prefix) & filters.me)
|
||||||
async def update(_, message: Message):
|
async def update(_, message: Message):
|
||||||
db.set(
|
db.set(
|
||||||
"core.updater",
|
'core.updater',
|
||||||
"restart_info",
|
'restart_info',
|
||||||
{
|
{
|
||||||
"type": "update",
|
'type': 'update',
|
||||||
"chat_id": message.chat.id,
|
'chat_id': message.chat.id,
|
||||||
"message_id": message.id,
|
'message_id': message.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
if "LAVHOST" in os.environ:
|
if 'LAVHOST' in os.environ:
|
||||||
await message.edit("<b>Your lavHost is updating...</b>")
|
await message.edit('<b>Your lavHost is updating...</b>')
|
||||||
os.system("lavhost update")
|
os.system('lavhost update')
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("<b>Updating...</b>")
|
await message.edit('<b>Updating...</b>')
|
||||||
try:
|
try:
|
||||||
if not check_command("termux-setup-storage"):
|
if not check_command('termux-setup-storage'):
|
||||||
subprocess.run(
|
subprocess.run([sys.executable, '-m', 'pip', 'install', '-U', 'pip'], check=True)
|
||||||
[sys.executable, "-m", "pip", "install", "-U", "pip"], check=True
|
subprocess.run(['git', 'pull'], check=True)
|
||||||
)
|
|
||||||
subprocess.run(["git", "pull"], check=True)
|
|
||||||
|
|
||||||
if (
|
if os.path.exists('requirements.txt') and os.path.getsize('requirements.txt') > 0:
|
||||||
os.path.exists("requirements.txt")
|
|
||||||
and os.path.getsize("requirements.txt") > 0
|
|
||||||
):
|
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[
|
[
|
||||||
sys.executable,
|
sys.executable,
|
||||||
"-m",
|
'-m',
|
||||||
"pip",
|
'pip',
|
||||||
"install",
|
'install',
|
||||||
"-U",
|
'-U',
|
||||||
"-r",
|
'-r',
|
||||||
"requirements.txt",
|
'requirements.txt',
|
||||||
],
|
],
|
||||||
check=True,
|
check=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
if requirements_list:
|
if requirements_list:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
[sys.executable, "-m", "pip", "install", "-U", *requirements_list],
|
[sys.executable, '-m', 'pip', 'install', '-U', *requirements_list],
|
||||||
check=True,
|
check=True,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
db.remove("core.updater", "restart_info")
|
db.remove('core.updater', 'restart_info')
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Updating: done! Restarting...</b>")
|
await message.edit('<b>Updating: done! Restarting...</b>')
|
||||||
if os.path.exists("moonlogs.txt"):
|
if os.path.exists('moonlogs.txt'):
|
||||||
os.remove("moonlogs.txt")
|
os.remove('moonlogs.txt')
|
||||||
restart()
|
restart()
|
||||||
|
|
||||||
|
|
||||||
modules_help["updater"] = {
|
modules_help['updater'] = {
|
||||||
"update": "Update the userbot. If new core modules are avaliable, they will be installed",
|
'update': 'Update the userbot. If new core modules are avaliable, they will be installed',
|
||||||
"restart": "Restart userbot",
|
'restart': 'Restart userbot',
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-36
@@ -17,71 +17,65 @@
|
|||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, progress
|
from utils.scripts import format_exc, progress
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("upl", prefix) & filters.me)
|
@Client.on_message(filters.command('upl', prefix) & filters.me)
|
||||||
async def upl(client: Client, message: Message):
|
async def upl(client: Client, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
link = message.text.split(maxsplit=1)[1]
|
link = message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
link = message.reply_to_message.text
|
link = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if not os.path.isfile(link):
|
if not os.path.isfile(link):
|
||||||
await message.edit(
|
await message.edit(f'<b>Error: </b><code>{link}</code> is not a valid file path.')
|
||||||
f"<b>Error: </b><code>{link}</code> is not a valid file path."
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Uploading Now...</b>")
|
await message.edit('<b>Uploading Now...</b>')
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
link,
|
link,
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(message, time.time(), "<b>Uploading Now...</b>", link),
|
progress_args=(message, time.time(), '<b>Uploading Now...</b>', link),
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("dlf", prefix) & filters.me)
|
@Client.on_message(filters.command('dlf', prefix) & filters.me)
|
||||||
async def dlf(client: Client, message: Message):
|
async def dlf(client: Client, message: Message):
|
||||||
if message.reply_to_message:
|
if message.reply_to_message:
|
||||||
await client.download_media(
|
await client.download_media(
|
||||||
message.reply_to_message,
|
message.reply_to_message,
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(message, time.time(), "<b>Uploading Now...</b>"),
|
progress_args=(message, time.time(), '<b>Uploading Now...</b>'),
|
||||||
)
|
)
|
||||||
await message.edit("<b>Downloaded Successfully!</b>")
|
await message.edit('<b>Downloaded Successfully!</b>')
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: </b><code>{prefix}dlf [reply to a file]</code>")
|
await message.edit(f'<b>Usage: </b><code>{prefix}dlf [reply to a file]</code>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("moonlogs", prefix) & filters.me)
|
@Client.on_message(filters.command('moonlogs', prefix) & filters.me)
|
||||||
async def mupl(client: Client, message: Message):
|
async def mupl(client: Client, message: Message):
|
||||||
link = "moonlogs.txt"
|
link = 'moonlogs.txt'
|
||||||
if os.path.exists(link):
|
if os.path.exists(link):
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Uploading Now...</b>")
|
await message.edit('<b>Uploading Now...</b>')
|
||||||
with open(link, "rb") as f:
|
with open(link, 'rb') as f:
|
||||||
data = f.read()
|
data = f.read()
|
||||||
bio = io.BytesIO(data)
|
bio = io.BytesIO(data)
|
||||||
bio.name = "moonlogs.txt"
|
bio.name = 'moonlogs.txt'
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id, bio, progress=progress, progress_args=(message, time.time(), '<b>Uploading Now...</b>')
|
||||||
bio,
|
|
||||||
progress=progress,
|
|
||||||
progress_args=(message, time.time(), "<b>Uploading Now...</b>")
|
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -90,31 +84,27 @@ async def mupl(client: Client, message: Message):
|
|||||||
await message.edit("<b>Error: </b><code>LOGS</code> file doesn't exist.")
|
await message.edit("<b>Error: </b><code>LOGS</code> file doesn't exist.")
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("uplr", prefix) & filters.me)
|
@Client.on_message(filters.command('uplr', prefix) & filters.me)
|
||||||
async def uplr(client: Client, message: Message):
|
async def uplr(client: Client, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
link = message.text.split(maxsplit=1)[1]
|
link = message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
link = message.reply_to_message.text
|
link = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if not os.path.isfile(link):
|
if not os.path.isfile(link):
|
||||||
await message.edit(
|
await message.edit(f'<b>Error: </b><code>{link}</code> is not a valid file path.')
|
||||||
f"<b>Error: </b><code>{link}</code> is not a valid file path."
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await message.edit("<b>Uploading Now...</b>")
|
await message.edit('<b>Uploading Now...</b>')
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
link,
|
link,
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(message, time.time(), "<b>Uploading Now...</b>", link),
|
progress_args=(message, time.time(), '<b>Uploading Now...</b>', link),
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -124,9 +114,9 @@ async def uplr(client: Client, message: Message):
|
|||||||
os.remove(link)
|
os.remove(link)
|
||||||
|
|
||||||
|
|
||||||
modules_help["uplud"] = {
|
modules_help['uplud'] = {
|
||||||
"upl [filepath]/[reply to path]*": "Upload a file from your local machine to Telegram",
|
'upl [filepath]/[reply to path]*': 'Upload a file from your local machine to Telegram',
|
||||||
"dlf": "Download a file from Telegram to your local machine",
|
'dlf': 'Download a file from Telegram to your local machine',
|
||||||
"uplr [filepath]/[reply to path]*": "Upload a file from your local machine to Telegram, delete the file after uploading",
|
'uplr [filepath]/[reply to path]*': 'Upload a file from your local machine to Telegram, delete the file after uploading',
|
||||||
"moonlogs": "Upload the moonlogs.txt file to Telegram",
|
'moonlogs': 'Upload the moonlogs.txt file to Telegram',
|
||||||
}
|
}
|
||||||
|
|||||||
+66
-85
@@ -17,7 +17,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
import mimetypes
|
import mimetypes
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -29,14 +28,13 @@ import urllib3
|
|||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
from pySmartDL import SmartDL
|
from pySmartDL import SmartDL
|
||||||
|
|
||||||
from utils.config import apiflash_key
|
from utils.config import apiflash_key
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, humanbytes, progress
|
from utils.scripts import format_exc, humanbytes, progress
|
||||||
|
|
||||||
|
|
||||||
def generate_screenshot(url):
|
def generate_screenshot(url):
|
||||||
api_url = f"https://api.apiflash.com/v1/urltoimage?access_key={apiflash_key}&url={url}&format=png"
|
api_url = f'https://api.apiflash.com/v1/urltoimage?access_key={apiflash_key}&url={url}&format=png'
|
||||||
response = requests.get(api_url)
|
response = requests.get(api_url)
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
return BytesIO(response.content)
|
return BytesIO(response.content)
|
||||||
@@ -46,23 +44,23 @@ def generate_screenshot(url):
|
|||||||
http = urllib3.PoolManager()
|
http = urllib3.PoolManager()
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("short", prefix) & filters.me)
|
@Client.on_message(filters.command('short', prefix) & filters.me)
|
||||||
async def short(_, message: Message):
|
async def short(_, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
link = message.text.split(maxsplit=1)[1]
|
link = message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
link = message.reply_to_message.text
|
link = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(f"<b>Usage: </b><code>{prefix}short [url to short]</code>")
|
await message.edit(f'<b>Usage: </b><code>{prefix}short [url to short]</code>')
|
||||||
return
|
return
|
||||||
r = http.request("GET", "https://clck.ru/--?url=" + link)
|
r = http.request('GET', 'https://clck.ru/--?url=' + link)
|
||||||
await message.edit(
|
await message.edit(
|
||||||
r.data.decode().replace("https://", "<b>Shortened Url:</b>"),
|
r.data.decode().replace('https://', '<b>Shortened Url:</b>'),
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("urldl", prefix) & filters.me)
|
@Client.on_message(filters.command('urldl', prefix) & filters.me)
|
||||||
async def urldl(client: Client, message: Message):
|
async def urldl(client: Client, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
message_id = None
|
message_id = None
|
||||||
@@ -71,65 +69,63 @@ async def urldl(client: Client, message: Message):
|
|||||||
message_id = message.reply_to_message.id
|
message_id = message.reply_to_message.id
|
||||||
link = message.reply_to_message.text
|
link = message.reply_to_message.text
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>Usage: </b><code>{prefix}urldl [url to download]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}urldl [url to download]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("<b>Trying to download...</b>")
|
await message.edit('<b>Trying to download...</b>')
|
||||||
|
|
||||||
c_time = time.time()
|
c_time = time.time()
|
||||||
|
|
||||||
resp = requests.head(link, allow_redirects=True, timeout=5)
|
resp = requests.head(link, allow_redirects=True, timeout=5)
|
||||||
if resp.status_code != 200:
|
if resp.status_code != 200:
|
||||||
return await message.edit("<b>Failed to fetch request header information</b>")
|
return await message.edit('<b>Failed to fetch request header information</b>')
|
||||||
|
|
||||||
content_type = resp.headers.get("Content-Type").split(";")[0]
|
content_type = resp.headers.get('Content-Type').split(';')[0]
|
||||||
extension = mimetypes.guess_extension(content_type)
|
extension = mimetypes.guess_extension(content_type)
|
||||||
|
|
||||||
# Check if the file is an executable binary
|
# Check if the file is an executable binary
|
||||||
is_executable = content_type in [
|
is_executable = content_type in [
|
||||||
"application/octet-stream",
|
'application/octet-stream',
|
||||||
"application/x-msdownload",
|
'application/x-msdownload',
|
||||||
]
|
]
|
||||||
|
|
||||||
# Get the file extension from the URL
|
# Get the file extension from the URL
|
||||||
url_extension = os.path.splitext(link)[1].lower()
|
url_extension = os.path.splitext(link)[1].lower()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
os.makedirs("downloads")
|
os.makedirs('downloads')
|
||||||
if is_executable:
|
if is_executable:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(url_extension):
|
if not file_name.endswith(url_extension):
|
||||||
file_name += url_extension
|
file_name += url_extension
|
||||||
elif extension:
|
elif extension:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(extension):
|
if not file_name.endswith(extension):
|
||||||
file_name += extension
|
file_name += extension
|
||||||
else:
|
else:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
if is_executable:
|
if is_executable:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(url_extension):
|
if not file_name.endswith(url_extension):
|
||||||
file_name += url_extension
|
file_name += url_extension
|
||||||
elif extension:
|
elif extension:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(extension):
|
if not file_name.endswith(extension):
|
||||||
file_name += extension
|
file_name += extension
|
||||||
else:
|
else:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
except FileExistsError:
|
except FileExistsError:
|
||||||
if is_executable:
|
if is_executable:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(url_extension):
|
if not file_name.endswith(url_extension):
|
||||||
file_name += url_extension
|
file_name += url_extension
|
||||||
elif extension:
|
elif extension:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
if not file_name.endswith(extension):
|
if not file_name.endswith(extension):
|
||||||
file_name += extension
|
file_name += extension
|
||||||
else:
|
else:
|
||||||
file_name = "downloads/" + link.split("/")[-1]
|
file_name = 'downloads/' + link.split('/')[-1]
|
||||||
|
|
||||||
downloader = SmartDL(link, file_name, progress_bar=False, timeout=10)
|
downloader = SmartDL(link, file_name, progress_bar=False, timeout=10)
|
||||||
start_t = datetime.now()
|
start_t = datetime.now()
|
||||||
@@ -140,24 +136,24 @@ async def urldl(client: Client, message: Message):
|
|||||||
while not downloader.isFinished():
|
while not downloader.isFinished():
|
||||||
total_length = downloader.filesize or None
|
total_length = downloader.filesize or None
|
||||||
downloaded = downloader.get_dl_size(human=True)
|
downloaded = downloader.get_dl_size(human=True)
|
||||||
u_m = ""
|
u_m = ''
|
||||||
now = time.time()
|
now = time.time()
|
||||||
diff = now - c_time
|
diff = now - c_time
|
||||||
percentage = downloader.get_progress() * 100
|
percentage = downloader.get_progress() * 100
|
||||||
speed = downloader.get_speed(human=True)
|
speed = downloader.get_speed(human=True)
|
||||||
progress_str = (
|
progress_str = (
|
||||||
"".join(["▰" for _ in range(math.floor(percentage / 5))])
|
''.join(['▰' for _ in range(math.floor(percentage / 5))])
|
||||||
+ "".join(["▱" for _ in range(20 - math.floor(percentage / 5))])
|
+ ''.join(['▱' for _ in range(20 - math.floor(percentage / 5))])
|
||||||
+ f"\n<b>Progress:</b> {round(percentage, 2)}%"
|
+ f'\n<b>Progress:</b> {round(percentage, 2)}%'
|
||||||
)
|
)
|
||||||
eta = downloader.get_eta(human=True)
|
eta = downloader.get_eta(human=True)
|
||||||
try:
|
try:
|
||||||
m = "<b>Trying to download...</b>\n"
|
m = '<b>Trying to download...</b>\n'
|
||||||
m += f"<b>File Name:</b> <code>{unquote(link.split('/')[-1])}</code>\n"
|
m += f'<b>File Name:</b> <code>{unquote(link.split("/")[-1])}</code>\n'
|
||||||
m += f"<b>Speed:</b> {speed}\n"
|
m += f'<b>Speed:</b> {speed}\n'
|
||||||
m += f"{progress_str}\n"
|
m += f'{progress_str}\n'
|
||||||
m += f"{downloaded} of {humanbytes(total_length)}\n"
|
m += f'{downloaded} of {humanbytes(total_length)}\n'
|
||||||
m += f"<b>ETA:</b> {eta}"
|
m += f'<b>ETA:</b> {eta}'
|
||||||
if round(diff % 10.00) == 0 and m != u_m:
|
if round(diff % 10.00) == 0 and m != u_m:
|
||||||
await message.edit_text(disable_web_page_preview=True, text=m)
|
await message.edit_text(disable_web_page_preview=True, text=m)
|
||||||
u_m = m
|
u_m = m
|
||||||
@@ -167,25 +163,23 @@ async def urldl(client: Client, message: Message):
|
|||||||
if os.path.exists(file_name):
|
if os.path.exists(file_name):
|
||||||
end_t = datetime.now()
|
end_t = datetime.now()
|
||||||
sec = (end_t - start_t).seconds
|
sec = (end_t - start_t).seconds
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Downloaded to <code>{file_name}</code> in {sec} seconds</b>')
|
||||||
f"<b>Downloaded to <code>{file_name}</code> in {sec} seconds</b>"
|
ms_ = await message.edit('<b>Starting Upload...</b>')
|
||||||
)
|
|
||||||
ms_ = await message.edit("<b>Starting Upload...</b>")
|
|
||||||
await client.send_document(
|
await client.send_document(
|
||||||
message.chat.id,
|
message.chat.id,
|
||||||
file_name,
|
file_name,
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(ms_, c_time, "`Uploading...`"),
|
progress_args=(ms_, c_time, '`Uploading...`'),
|
||||||
caption=f"<b>File Name:</b> <code>{unquote(link.split('/')[-1])}</code>\n",
|
caption=f'<b>File Name:</b> <code>{unquote(link.split("/")[-1])}</code>\n',
|
||||||
reply_to_message_id=message_id,
|
reply_to_message_id=message_id,
|
||||||
)
|
)
|
||||||
await message.delete()
|
await message.delete()
|
||||||
os.remove(file_name)
|
os.remove(file_name)
|
||||||
else:
|
else:
|
||||||
await message.edit("<b>Failed to download</b>")
|
await message.edit('<b>Failed to download</b>')
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("upload", prefix) & filters.me)
|
@Client.on_message(filters.command('upload', prefix) & filters.me)
|
||||||
async def upload_cmd(_, message: Message):
|
async def upload_cmd(_, message: Message):
|
||||||
max_size = 512 * 1024 * 1024
|
max_size = 512 * 1024 * 1024
|
||||||
max_size_mb = 100
|
max_size_mb = 100
|
||||||
@@ -193,20 +187,18 @@ async def upload_cmd(_, message: Message):
|
|||||||
min_file_age = 31
|
min_file_age = 31
|
||||||
max_file_age = 180
|
max_file_age = 180
|
||||||
|
|
||||||
ms_ = await message.edit("`Downloading...`", parse_mode=enums.ParseMode.MARKDOWN)
|
ms_ = await message.edit('`Downloading...`', parse_mode=enums.ParseMode.MARKDOWN)
|
||||||
c_time = time.time()
|
c_time = time.time()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
file_name = await message.download(
|
file_name = await message.download(progress=progress, progress_args=(ms_, c_time, '`Downloading...`'))
|
||||||
progress=progress, progress_args=(ms_, c_time, "`Downloading...`")
|
|
||||||
)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
try:
|
try:
|
||||||
file_name = await message.reply_to_message.download(
|
file_name = await message.reply_to_message.download(
|
||||||
progress=progress, progress_args=(ms_, c_time, "`Downloading...`")
|
progress=progress, progress_args=(ms_, c_time, '`Downloading...`')
|
||||||
)
|
)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
await message.edit("<b>File to upload not found</b>")
|
await message.edit('<b>File to upload not found</b>')
|
||||||
return
|
return
|
||||||
|
|
||||||
if os.path.getsize(file_name) > max_size:
|
if os.path.getsize(file_name) > max_size:
|
||||||
@@ -215,71 +207,60 @@ async def upload_cmd(_, message: Message):
|
|||||||
os.remove(file_name)
|
os.remove(file_name)
|
||||||
return
|
return
|
||||||
|
|
||||||
await message.edit("<b>Uploading...</b>")
|
await message.edit('<b>Uploading...</b>')
|
||||||
with open(file_name, "rb") as f:
|
with open(file_name, 'rb') as f:
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
"https://x0.at",
|
'https://x0.at',
|
||||||
files={"file": f},
|
files={'file': f},
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.ok:
|
if response.ok:
|
||||||
file_size_mb = os.path.getsize(file_name) / 1024 / 1024
|
file_size_mb = os.path.getsize(file_name) / 1024 / 1024
|
||||||
file_age = int(
|
file_age = int(min_file_age + (max_file_age - min_file_age) * ((1 - (file_size_mb / max_size_mb)) ** 2))
|
||||||
min_file_age
|
url = response.text.replace('https://', '')
|
||||||
+ (max_file_age - min_file_age) * ((1 - (file_size_mb / max_size_mb)) ** 2)
|
|
||||||
)
|
|
||||||
url = response.text.replace("https://", "")
|
|
||||||
await message.edit(
|
await message.edit(
|
||||||
f"<b>Your URL: {url}\nYour file will remain live for {file_age} days</b>",
|
f'<b>Your URL: {url}\nYour file will remain live for {file_age} days</b>',
|
||||||
disable_web_page_preview=True,
|
disable_web_page_preview=True,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
await message.edit(
|
await message.edit(f'<b>API returned an error!\n{response.text}\n Not allowed</b>')
|
||||||
f"<b>API returned an error!\n{response.text}\n Not allowed</b>"
|
|
||||||
)
|
|
||||||
print(response.text)
|
print(response.text)
|
||||||
if os.path.exists(file_name):
|
if os.path.exists(file_name):
|
||||||
os.remove(file_name)
|
os.remove(file_name)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command(["ws", "webshot"], prefix) & filters.me)
|
@Client.on_message(filters.command(['ws', 'webshot'], prefix) & filters.me)
|
||||||
async def webshot(client: Client, message: Message):
|
async def webshot(client: Client, message: Message):
|
||||||
if len(message.command) > 1:
|
if len(message.command) > 1:
|
||||||
url = message.text.split(maxsplit=1)[1]
|
url = message.text.split(maxsplit=1)[1]
|
||||||
if not url.startswith("https://"):
|
if not url.startswith('https://'):
|
||||||
url = "https://" + message.text.split(maxsplit=1)[1]
|
url = 'https://' + message.text.split(maxsplit=1)[1]
|
||||||
elif message.reply_to_message:
|
elif message.reply_to_message:
|
||||||
url = message.reply_to_message.text
|
url = message.reply_to_message.text
|
||||||
if not url.startswith("https://"):
|
if not url.startswith('https://'):
|
||||||
url = "https://" + url
|
url = 'https://' + url
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text(f'<b>Usage: </b><code>{prefix}webshot/{prefix}ws [url/reply to url]</code>')
|
||||||
f"<b>Usage: </b><code>{prefix}webshot/{prefix}ws [url/reply to url]</code>"
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
await message.edit("<b>Generating screenshot...</b>")
|
await message.edit('<b>Generating screenshot...</b>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
screenshot_data = generate_screenshot(url)
|
screenshot_data = generate_screenshot(url)
|
||||||
if screenshot_data:
|
if screenshot_data:
|
||||||
await message.delete()
|
await message.delete()
|
||||||
await client.send_photo(
|
await client.send_photo(chat_id, screenshot_data, caption=f'Screenshot of <code>{url}</code>')
|
||||||
chat_id, screenshot_data, caption=f"Screenshot of <code>{url}</code>"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
await message.edit_text(
|
await message.edit_text('<code>Failed to generate screenshot...\nMake sure url is correct</code>')
|
||||||
"<code>Failed to generate screenshot...\nMake sure url is correct</code>"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await message.edit_text(f"An error occurred: {format_exc(e)}")
|
await message.edit_text(f'An error occurred: {format_exc(e)}')
|
||||||
|
|
||||||
|
|
||||||
modules_help["url"] = {
|
modules_help['url'] = {
|
||||||
"short [url]*": "short url",
|
'short [url]*': 'short url',
|
||||||
"urldl [url]*": "download url content",
|
'urldl [url]*': 'download url content',
|
||||||
"upload [file|reply]*": "upload file to internet",
|
'upload [file|reply]*': 'upload file to internet',
|
||||||
"webshot [link]*": "Screenshot of web page",
|
'webshot [link]*': 'Screenshot of web page',
|
||||||
"ws [reply to link]*": "Screenshot of web page",
|
'ws [reply to link]*': 'Screenshot of web page',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,19 +17,18 @@
|
|||||||
from pyrogram import Client, filters
|
from pyrogram import Client, filters
|
||||||
from pyrogram.raw import functions
|
from pyrogram.raw import functions
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import format_exc, interact_with, interact_with_to_delete
|
from utils.scripts import format_exc, interact_with, interact_with_to_delete
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("inf", prefix) & filters.me)
|
@Client.on_message(filters.command('inf', prefix) & filters.me)
|
||||||
async def get_user_inf(client: Client, message: Message):
|
async def get_user_inf(client: Client, message: Message):
|
||||||
if len(message.command) >= 2:
|
if len(message.command) >= 2:
|
||||||
peer = await client.resolve_peer(message.command[1])
|
peer = await client.resolve_peer(message.command[1])
|
||||||
elif message.reply_to_message and message.reply_to_message.from_user:
|
elif message.reply_to_message and message.reply_to_message.from_user:
|
||||||
peer = await client.resolve_peer(message.reply_to_message.from_user.id)
|
peer = await client.resolve_peer(message.reply_to_message.from_user.id)
|
||||||
else:
|
else:
|
||||||
peer = await client.resolve_peer("me")
|
peer = await client.resolve_peer('me')
|
||||||
|
|
||||||
response = await client.invoke(functions.users.GetFullUser(id=peer))
|
response = await client.invoke(functions.users.GetFullUser(id=peer))
|
||||||
|
|
||||||
@@ -37,10 +36,10 @@ async def get_user_inf(client: Client, message: Message):
|
|||||||
full_user = response.full_user
|
full_user = response.full_user
|
||||||
|
|
||||||
if user.username is None:
|
if user.username is None:
|
||||||
username = "None"
|
username = 'None'
|
||||||
else:
|
else:
|
||||||
username = f"@{user.username}"
|
username = f'@{user.username}'
|
||||||
about = "None" if full_user.about is None else full_user.about
|
about = 'None' if full_user.about is None else full_user.about
|
||||||
|
|
||||||
user_info = f"""|=<b>Username: {username}
|
user_info = f"""|=<b>Username: {username}
|
||||||
|-Id: <code>{user.id}</code>
|
|-Id: <code>{user.id}</code>
|
||||||
@@ -53,9 +52,9 @@ async def get_user_inf(client: Client, message: Message):
|
|||||||
await message.edit(user_info)
|
await message.edit(user_info)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("inffull", prefix) & filters.me)
|
@Client.on_message(filters.command('inffull', prefix) & filters.me)
|
||||||
async def get_full_user_inf(client: Client, message: Message):
|
async def get_full_user_inf(client: Client, message: Message):
|
||||||
await message.edit("<b>Receiving the information...</b>")
|
await message.edit('<b>Receiving the information...</b>')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if len(message.command) >= 2:
|
if len(message.command) >= 2:
|
||||||
@@ -63,30 +62,28 @@ async def get_full_user_inf(client: Client, message: Message):
|
|||||||
elif message.reply_to_message and message.reply_to_message.from_user:
|
elif message.reply_to_message and message.reply_to_message.from_user:
|
||||||
peer = await client.resolve_peer(message.reply_to_message.from_user.id)
|
peer = await client.resolve_peer(message.reply_to_message.from_user.id)
|
||||||
else:
|
else:
|
||||||
peer = await client.resolve_peer("me")
|
peer = await client.resolve_peer('me')
|
||||||
|
|
||||||
response = await client.invoke(functions.users.GetFullUser(id=peer))
|
response = await client.invoke(functions.users.GetFullUser(id=peer))
|
||||||
|
|
||||||
user = response.users[0]
|
user = response.users[0]
|
||||||
full_user = response.full_user
|
full_user = response.full_user
|
||||||
|
|
||||||
await client.unblock_user("@creationdatebot")
|
await client.unblock_user('@creationdatebot')
|
||||||
try:
|
try:
|
||||||
response = await interact_with(
|
response = await interact_with(await client.send_message('creationdatebot', f'/id {user.id}'))
|
||||||
await client.send_message("creationdatebot", f"/id {user.id}")
|
|
||||||
)
|
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
creation_date = "None"
|
creation_date = 'None'
|
||||||
else:
|
else:
|
||||||
creation_date = response.text
|
creation_date = response.text
|
||||||
# await client.delete_messages("@creationdatebot", interact_with_to_delete)
|
# await client.delete_messages("@creationdatebot", interact_with_to_delete)
|
||||||
interact_with_to_delete.clear()
|
interact_with_to_delete.clear()
|
||||||
|
|
||||||
if user.username is None:
|
if user.username is None:
|
||||||
username = "None"
|
username = 'None'
|
||||||
else:
|
else:
|
||||||
username = f"@{user.username}"
|
username = f'@{user.username}'
|
||||||
about = "None" if full_user.about is None else full_user.about
|
about = 'None' if full_user.about is None else full_user.about
|
||||||
user_info = f"""|=<b>Username: {username}
|
user_info = f"""|=<b>Username: {username}
|
||||||
|-Id: <code>{user.id}</code>
|
|-Id: <code>{user.id}</code>
|
||||||
|-Account creation date: <code>{creation_date}</code>
|
|-Account creation date: <code>{creation_date}</code>
|
||||||
@@ -109,7 +106,7 @@ async def get_full_user_inf(client: Client, message: Message):
|
|||||||
await message.edit(format_exc(e))
|
await message.edit(format_exc(e))
|
||||||
|
|
||||||
|
|
||||||
modules_help["user_info"] = {
|
modules_help['user_info'] = {
|
||||||
"inf [reply|id|username]": "Get brief information about user",
|
'inf [reply|id|username]': 'Get brief information about user',
|
||||||
"inffull [reply|id|username": "Get full information about user",
|
'inffull [reply|id|username': 'Get full information about user',
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-30
@@ -12,48 +12,47 @@ import time
|
|||||||
import requests
|
import requests
|
||||||
from pyrogram import Client, enums, filters
|
from pyrogram import Client, enums, filters
|
||||||
from pyrogram.types import Message
|
from pyrogram.types import Message
|
||||||
|
|
||||||
from utils.config import vt_key as vak
|
from utils.config import vt_key as vak
|
||||||
from utils.misc import modules_help, prefix
|
from utils.misc import modules_help, prefix
|
||||||
from utils.scripts import edit_or_reply, format_exc, progress
|
from utils.scripts import edit_or_reply, format_exc, progress
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("vt", prefix) & filters.me)
|
@Client.on_message(filters.command('vt', prefix) & filters.me)
|
||||||
async def scan_my_file(_, message: Message):
|
async def scan_my_file(_, message: Message):
|
||||||
ms_ = await edit_or_reply(message, "`Please Wait! Scanning This File`")
|
ms_ = await edit_or_reply(message, '`Please Wait! Scanning This File`')
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`Please Reply To File To Scan For Viruses`",
|
'`Please Reply To File To Scan For Viruses`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if not message.reply_to_message.document:
|
if not message.reply_to_message.document:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`Please Reply To File To Scan For Viruses`",
|
'`Please Reply To File To Scan For Viruses`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if vak is None:
|
if vak is None:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`You Need To Set VIRUSTOTAL_API_KEY For Functing Of This Plugin.`",
|
'`You Need To Set VIRUSTOTAL_API_KEY For Functing Of This Plugin.`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if int(message.reply_to_message.document.file_size) > 32000000:
|
if int(message.reply_to_message.document.file_size) > 32000000:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
f"**File Too Large, Use `{prefix}vtl` instead**",
|
f'**File Too Large, Use `{prefix}vtl` instead**',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
c_time = time.time()
|
c_time = time.time()
|
||||||
downloaded_file_name = await message.reply_to_message.download(
|
downloaded_file_name = await message.reply_to_message.download(
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(ms_, c_time, "`Downloading This File!`"),
|
progress_args=(ms_, c_time, '`Downloading This File!`'),
|
||||||
)
|
)
|
||||||
|
|
||||||
url = "https://www.virustotal.com/vtapi/v2/file/scan"
|
url = 'https://www.virustotal.com/vtapi/v2/file/scan'
|
||||||
params = {"apikey": vak}
|
params = {'apikey': vak}
|
||||||
files = {"file": (downloaded_file_name, open(downloaded_file_name, "rb"))}
|
files = {'file': (downloaded_file_name, open(downloaded_file_name, 'rb'))}
|
||||||
response = requests.post(url, files=files, params=params, timeout=10)
|
response = requests.post(url, files=files, params=params, timeout=10)
|
||||||
try:
|
try:
|
||||||
r_json = response.json()
|
r_json = response.json()
|
||||||
md5 = r_json["md5"]
|
md5 = r_json['md5']
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await ms_.edit(format_exc(e))
|
return await ms_.edit(format_exc(e))
|
||||||
await ms_.edit(
|
await ms_.edit(
|
||||||
@@ -63,64 +62,64 @@ async def scan_my_file(_, message: Message):
|
|||||||
os.remove(downloaded_file_name)
|
os.remove(downloaded_file_name)
|
||||||
|
|
||||||
|
|
||||||
@Client.on_message(filters.command("vtl", prefix) & filters.me)
|
@Client.on_message(filters.command('vtl', prefix) & filters.me)
|
||||||
async def scan_my_large_file(_, message: Message):
|
async def scan_my_large_file(_, message: Message):
|
||||||
ms_ = await edit_or_reply(message, "`Please Wait! Scanning This File`")
|
ms_ = await edit_or_reply(message, '`Please Wait! Scanning This File`')
|
||||||
if not message.reply_to_message:
|
if not message.reply_to_message:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`Please Reply To File To Scan For Viruses`",
|
'`Please Reply To File To Scan For Viruses`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if not message.reply_to_message.document:
|
if not message.reply_to_message.document:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`Please Reply To File To Scan For Viruses`",
|
'`Please Reply To File To Scan For Viruses`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if vak is None:
|
if vak is None:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"`You Need To Set VIRUSTOTAL_API_KEY For Functing Of This Plugin.`",
|
'`You Need To Set VIRUSTOTAL_API_KEY For Functing Of This Plugin.`',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
if int(message.reply_to_message.document.file_size) > 650000000:
|
if int(message.reply_to_message.document.file_size) > 650000000:
|
||||||
return await ms_.edit(
|
return await ms_.edit(
|
||||||
"**File Too Large, exceeded Max capacity of 650MB**",
|
'**File Too Large, exceeded Max capacity of 650MB**',
|
||||||
parse_mode=enums.ParseMode.MARKDOWN,
|
parse_mode=enums.ParseMode.MARKDOWN,
|
||||||
)
|
)
|
||||||
c_time = time.time()
|
c_time = time.time()
|
||||||
downloaded_file_name = await message.reply_to_message.download(
|
downloaded_file_name = await message.reply_to_message.download(
|
||||||
progress=progress,
|
progress=progress,
|
||||||
progress_args=(ms_, c_time, "`Downloading This File!`"),
|
progress_args=(ms_, c_time, '`Downloading This File!`'),
|
||||||
)
|
)
|
||||||
|
|
||||||
url1 = "https://www.virustotal.com/api/v3/files/upload_url"
|
url1 = 'https://www.virustotal.com/api/v3/files/upload_url'
|
||||||
|
|
||||||
headers = {"accept": "application/json", "x-apikey": vak}
|
headers = {'accept': 'application/json', 'x-apikey': vak}
|
||||||
|
|
||||||
rponse = requests.get(url1, headers=headers, timeout=10)
|
rponse = requests.get(url1, headers=headers, timeout=10)
|
||||||
try:
|
try:
|
||||||
r_json = rponse.json()
|
r_json = rponse.json()
|
||||||
upl_data = r_json["data"]
|
upl_data = r_json['data']
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await ms_.edit(format_exc(e))
|
return await ms_.edit(format_exc(e))
|
||||||
|
|
||||||
url = upl_data
|
url = upl_data
|
||||||
|
|
||||||
files = {"file": (downloaded_file_name, open(downloaded_file_name, "rb"))}
|
files = {'file': (downloaded_file_name, open(downloaded_file_name, 'rb'))}
|
||||||
headers = {"accept": "application/json", "x-apikey": vak}
|
headers = {'accept': 'application/json', 'x-apikey': vak}
|
||||||
response = requests.post(url, files=files, headers=headers, timeout=10)
|
response = requests.post(url, files=files, headers=headers, timeout=10)
|
||||||
|
|
||||||
r_json = response.json()
|
r_json = response.json()
|
||||||
analysis_url = r_json["data"]["links"]["self"]
|
analysis_url = r_json['data']['links']['self']
|
||||||
|
|
||||||
url = analysis_url
|
url = analysis_url
|
||||||
|
|
||||||
headers = {"accept": "application/json", "x-apikey": vak}
|
headers = {'accept': 'application/json', 'x-apikey': vak}
|
||||||
|
|
||||||
response_result = requests.get(url, headers=headers, timeout=10)
|
response_result = requests.get(url, headers=headers, timeout=10)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r_json = response_result.json()
|
r_json = response_result.json()
|
||||||
md5 = r_json["meta"]["file_info"]["md5"]
|
md5 = r_json['meta']['file_info']['md5']
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return await ms_.edit(format_exc(e))
|
return await ms_.edit(format_exc(e))
|
||||||
await ms_.edit(
|
await ms_.edit(
|
||||||
@@ -130,7 +129,7 @@ async def scan_my_large_file(_, message: Message):
|
|||||||
os.remove(downloaded_file_name)
|
os.remove(downloaded_file_name)
|
||||||
|
|
||||||
|
|
||||||
modules_help["virustotal"] = {
|
modules_help['virustotal'] = {
|
||||||
"vt [reply to file]*": "Scan for viruses on Virus Total (for lower file size <32MB)",
|
'vt [reply to file]*': 'Scan for viruses on Virus Total (for lower file size <32MB)',
|
||||||
"vtl [reply to file]*": "Scan for viruses on Virus Total (for lower file size >=32MB)",
|
'vtl [reply to file]*': 'Scan for viruses on Virus Total (for lower file size >=32MB)',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
from pyrogram import Client, enums
|
from pyrogram import Client, enums
|
||||||
|
|
||||||
api_id = input("Enter Your API ID: \n")
|
api_id = input('Enter Your API ID: \n')
|
||||||
api_hash = input("Enter Your API HASH : \n")
|
api_hash = input('Enter Your API HASH : \n')
|
||||||
|
|
||||||
with Client("my_account", api_id=api_id, api_hash=api_hash, hide_password=True) as bot_:
|
with Client('my_account', api_id=api_id, api_hash=api_hash, hide_password=True) as bot_:
|
||||||
first_name = (bot_.get_me()).first_name
|
first_name = (bot_.get_me()).first_name
|
||||||
string_session_ = f"<b><u>String Session For {first_name}</b></u> \n<code>{bot_.export_session_string()}</code>"
|
string_session_ = f'<b><u>String Session For {first_name}</b></u> \n<code>{bot_.export_session_string()}</code>'
|
||||||
bot_.send_message("me", string_session_, parse_mode=enums.ParseMode.HTML, disable_web_page_preview=True)
|
bot_.send_message('me', string_session_, parse_mode=enums.ParseMode.HTML, disable_web_page_preview=True)
|
||||||
print(f"String Has Been Sent To Your Saved Message : {first_name}")
|
print(f'String Has Been Sent To Your Saved Message : {first_name}')
|
||||||
|
|||||||
+18
-19
@@ -1,32 +1,31 @@
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
import environs
|
import environs
|
||||||
|
|
||||||
env = environs.Env()
|
env = environs.Env()
|
||||||
try:
|
try:
|
||||||
env.read_env("./.env")
|
env.read_env('./.env')
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
print("No .env file found, using os.environ.")
|
print('No .env file found, using os.environ.')
|
||||||
|
|
||||||
api_id = int(os.getenv("API_ID", env.int("API_ID")))
|
api_id = int(os.getenv('API_ID', env.int('API_ID')))
|
||||||
api_hash = os.getenv("API_HASH", env.str("API_HASH"))
|
api_hash = os.getenv('API_HASH', env.str('API_HASH'))
|
||||||
|
|
||||||
STRINGSESSION = os.getenv("STRINGSESSION", env.str("STRINGSESSION"))
|
STRINGSESSION = os.getenv('STRINGSESSION', env.str('STRINGSESSION'))
|
||||||
|
|
||||||
second_session = os.getenv("SECOND_SESSION", env.str("SECOND_SESSION", ""))
|
second_session = os.getenv('SECOND_SESSION', env.str('SECOND_SESSION', ''))
|
||||||
|
|
||||||
db_type = os.getenv("DATABASE_TYPE", env.str("DATABASE_TYPE"))
|
db_type = os.getenv('DATABASE_TYPE', env.str('DATABASE_TYPE'))
|
||||||
db_url = os.getenv("DATABASE_URL", env.str("DATABASE_URL", ""))
|
db_url = os.getenv('DATABASE_URL', env.str('DATABASE_URL', ''))
|
||||||
db_name = os.getenv("DATABASE_NAME", env.str("DATABASE_NAME"))
|
db_name = os.getenv('DATABASE_NAME', env.str('DATABASE_NAME'))
|
||||||
|
|
||||||
apiflash_key = os.getenv("APIFLASH_KEY", env.str("APIFLASH_KEY"))
|
apiflash_key = os.getenv('APIFLASH_KEY', env.str('APIFLASH_KEY'))
|
||||||
rmbg_key = os.getenv("RMBG_KEY", env.str("RMBG_KEY", ""))
|
rmbg_key = os.getenv('RMBG_KEY', env.str('RMBG_KEY', ''))
|
||||||
vt_key = os.getenv("VT_KEY", env.str("VT_KEY", ""))
|
vt_key = os.getenv('VT_KEY', env.str('VT_KEY', ''))
|
||||||
gemini_key = os.getenv("GEMINI_KEY", env.str("GEMINI_KEY", ""))
|
gemini_key = os.getenv('GEMINI_KEY', env.str('GEMINI_KEY', ''))
|
||||||
cohere_key = os.getenv("COHERE_KEY", env.str("COHERE_KEY", ""))
|
cohere_key = os.getenv('COHERE_KEY', env.str('COHERE_KEY', ''))
|
||||||
|
|
||||||
pm_limit = int(os.getenv("PM_LIMIT", env.int("PM_LIMIT", 4)))
|
pm_limit = int(os.getenv('PM_LIMIT', env.int('PM_LIMIT', 4)))
|
||||||
|
|
||||||
test_server = bool(os.getenv("TEST_SERVER", env.bool("TEST_SERVER", False)))
|
test_server = bool(os.getenv('TEST_SERVER', env.bool('TEST_SERVER', False)))
|
||||||
modules_repo_branch = os.getenv(
|
modules_repo_branch = os.getenv('MODULES_REPO_BRANCH', env.str('MODULES_REPO_BRANCH', 'master'))
|
||||||
"MODULES_REPO_BRANCH", env.str("MODULES_REPO_BRANCH", "master")
|
|
||||||
)
|
|
||||||
|
|||||||
+14
-20
@@ -14,14 +14,12 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import asyncio
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
from pyrogram import Client, filters, types
|
from pyrogram import Client, filters, types
|
||||||
from pyrogram.handlers import MessageHandler
|
|
||||||
from pyrogram.enums.parse_mode import ParseMode
|
from pyrogram.enums.parse_mode import ParseMode
|
||||||
|
from pyrogram.handlers import MessageHandler
|
||||||
import asyncio
|
|
||||||
from typing import Union, List, Dict, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class _TrueFilter(filters.Filter):
|
class _TrueFilter(filters.Filter):
|
||||||
@@ -30,12 +28,12 @@ class _TrueFilter(filters.Filter):
|
|||||||
|
|
||||||
|
|
||||||
class Conversation:
|
class Conversation:
|
||||||
_locks: Dict[int, asyncio.Lock] = {}
|
_locks: dict[int, asyncio.Lock] = {}
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
client: Client,
|
client: Client,
|
||||||
chat: Union[str, int],
|
chat: str | int,
|
||||||
timeout: float = 5,
|
timeout: float = 5,
|
||||||
delete_at_end=True,
|
delete_at_end=True,
|
||||||
exclusive=True,
|
exclusive=True,
|
||||||
@@ -49,10 +47,10 @@ class Conversation:
|
|||||||
self._chat_id = 0
|
self._chat_id = 0
|
||||||
self._message_ids = []
|
self._message_ids = []
|
||||||
self._handler_object = None
|
self._handler_object = None
|
||||||
self._chat_unique_lock: Optional[asyncio.Lock] = None
|
self._chat_unique_lock: asyncio.Lock | None = None
|
||||||
self._waiters: Dict[asyncio.Event, filters.Filter] = {}
|
self._waiters: dict[asyncio.Event, filters.Filter] = {}
|
||||||
self._responses: Dict[asyncio.Event, types.Message] = {}
|
self._responses: dict[asyncio.Event, types.Message] = {}
|
||||||
self._pending_updates: List[types.Message] = []
|
self._pending_updates: list[types.Message] = []
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
self._chat_id = (await self.client.get_chat(self.chat)).id
|
self._chat_id = (await self.client.get_chat(self.chat)).id
|
||||||
@@ -65,9 +63,7 @@ class Conversation:
|
|||||||
if self.exclusive:
|
if self.exclusive:
|
||||||
await self._chat_unique_lock.acquire()
|
await self._chat_unique_lock.acquire()
|
||||||
|
|
||||||
self._handler_object = MessageHandler(
|
self._handler_object = MessageHandler(self._handler, filters.chat(self._chat_id))
|
||||||
self._handler, filters.chat(self._chat_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
if -999 not in self.client.dispatcher.groups:
|
if -999 not in self.client.dispatcher.groups:
|
||||||
new_groups = OrderedDict(self.client.dispatcher.groups)
|
new_groups = OrderedDict(self.client.dispatcher.groups)
|
||||||
@@ -101,7 +97,7 @@ class Conversation:
|
|||||||
|
|
||||||
async def get_response(
|
async def get_response(
|
||||||
self,
|
self,
|
||||||
message_filter: Optional[filters.Filter] = None,
|
message_filter: filters.Filter | None = None,
|
||||||
timeout: float = None,
|
timeout: float = None,
|
||||||
) -> types.Message:
|
) -> types.Message:
|
||||||
if timeout is None:
|
if timeout is None:
|
||||||
@@ -119,15 +115,13 @@ class Conversation:
|
|||||||
self._message_ids.append(message.id)
|
self._message_ids.append(message.id)
|
||||||
return message
|
return message
|
||||||
|
|
||||||
async def _wait_message(
|
async def _wait_message(self, message_filter: filters.Filter | None, timeout: float) -> types.Message:
|
||||||
self, message_filter: Optional[filters.Filter], timeout: float
|
|
||||||
) -> types.Message:
|
|
||||||
event = asyncio.Event()
|
event = asyncio.Event()
|
||||||
self._waiters[event] = message_filter
|
self._waiters[event] = message_filter
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(event.wait(), timeout=timeout)
|
await asyncio.wait_for(event.wait(), timeout=timeout)
|
||||||
except asyncio.TimeoutError as e:
|
except TimeoutError as e:
|
||||||
raise TimeoutError from e
|
raise TimeoutError from e
|
||||||
finally:
|
finally:
|
||||||
self._waiters.pop(event)
|
self._waiters.pop(event)
|
||||||
@@ -137,8 +131,8 @@ class Conversation:
|
|||||||
async def send_message(
|
async def send_message(
|
||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
parse_mode: Optional[str] = ParseMode.HTML,
|
parse_mode: str | None = ParseMode.HTML,
|
||||||
entities: List[types.MessageEntity] = None,
|
entities: list[types.MessageEntity] = None,
|
||||||
disable_web_page_preview: bool = None,
|
disable_web_page_preview: bool = None,
|
||||||
disable_notification: bool = None,
|
disable_notification: bool = None,
|
||||||
reply_to_message_id: int = None,
|
reply_to_message_id: int = None,
|
||||||
|
|||||||
+48
-48
@@ -14,16 +14,18 @@
|
|||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import re
|
|
||||||
import json
|
import json
|
||||||
import threading
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from dns import resolver
|
import threading
|
||||||
|
|
||||||
import pymongo
|
import pymongo
|
||||||
|
from dns import resolver
|
||||||
|
|
||||||
from utils import config
|
from utils import config
|
||||||
|
|
||||||
resolver.default_resolver = resolver.Resolver(configure=False)
|
resolver.default_resolver = resolver.Resolver(configure=False)
|
||||||
resolver.default_resolver.nameservers = ["1.1.1.1"]
|
resolver.default_resolver.nameservers = ['1.1.1.1']
|
||||||
|
|
||||||
|
|
||||||
class Database:
|
class Database:
|
||||||
@@ -55,26 +57,24 @@ class MongoDatabase(Database):
|
|||||||
|
|
||||||
def set(self, module: str, variable: str, value):
|
def set(self, module: str, variable: str, value):
|
||||||
if not isinstance(module, str) or not isinstance(variable, str):
|
if not isinstance(module, str) or not isinstance(variable, str):
|
||||||
raise ValueError("Module and variable must be strings")
|
raise ValueError('Module and variable must be strings')
|
||||||
self._database[module].replace_one(
|
self._database[module].replace_one({'var': variable}, {'var': variable, 'val': value}, upsert=True)
|
||||||
{"var": variable}, {"var": variable, "val": value}, upsert=True
|
|
||||||
)
|
|
||||||
|
|
||||||
def get(self, module: str, variable: str, default=None):
|
def get(self, module: str, variable: str, default=None):
|
||||||
if not isinstance(module, str) or not isinstance(variable, str):
|
if not isinstance(module, str) or not isinstance(variable, str):
|
||||||
raise ValueError("Module and variable must be strings")
|
raise ValueError('Module and variable must be strings')
|
||||||
doc = self._database[module].find_one({"var": variable})
|
doc = self._database[module].find_one({'var': variable})
|
||||||
return default if doc is None else doc["val"]
|
return default if doc is None else doc['val']
|
||||||
|
|
||||||
def get_collection(self, module: str):
|
def get_collection(self, module: str):
|
||||||
if not isinstance(module, str):
|
if not isinstance(module, str):
|
||||||
raise ValueError("Module must be a string")
|
raise ValueError('Module must be a string')
|
||||||
return {item["var"]: item["val"] for item in self._database[module].find()}
|
return {item['var']: item['val'] for item in self._database[module].find()}
|
||||||
|
|
||||||
def remove(self, module: str, variable: str):
|
def remove(self, module: str, variable: str):
|
||||||
if not isinstance(module, str) or not isinstance(variable, str):
|
if not isinstance(module, str) or not isinstance(variable, str):
|
||||||
raise ValueError("Module and variable must be strings")
|
raise ValueError('Module and variable must be strings')
|
||||||
self._database[module].delete_one({"var": variable})
|
self._database[module].delete_one({'var': variable})
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self._client.close()
|
self._client.close()
|
||||||
@@ -82,27 +82,27 @@ class MongoDatabase(Database):
|
|||||||
def add_chat_history(self, user_id, message):
|
def add_chat_history(self, user_id, message):
|
||||||
chat_history = self.get_chat_history(user_id, default=[])
|
chat_history = self.get_chat_history(user_id, default=[])
|
||||||
chat_history.append(message)
|
chat_history.append(message)
|
||||||
self.set(f"core.cohere.user_{user_id}", "chat_history", chat_history)
|
self.set(f'core.cohere.user_{user_id}', 'chat_history', chat_history)
|
||||||
|
|
||||||
def get_chat_history(self, user_id, default=None):
|
def get_chat_history(self, user_id, default=None):
|
||||||
if default is None:
|
if default is None:
|
||||||
default = []
|
default = []
|
||||||
return self.get(f"core.cohere.user_{user_id}", "chat_history", default=[])
|
return self.get(f'core.cohere.user_{user_id}', 'chat_history', default=[])
|
||||||
|
|
||||||
def addaiuser(self, user_id):
|
def addaiuser(self, user_id):
|
||||||
chatai_users = self.get("core.chatbot", "chatai_users", default=[])
|
chatai_users = self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
if user_id not in chatai_users:
|
if user_id not in chatai_users:
|
||||||
chatai_users.append(user_id)
|
chatai_users.append(user_id)
|
||||||
self.set("core.chatbot", "chatai_users", chatai_users)
|
self.set('core.chatbot', 'chatai_users', chatai_users)
|
||||||
|
|
||||||
def remaiuser(self, user_id):
|
def remaiuser(self, user_id):
|
||||||
chatai_users = self.get("core.chatbot", "chatai_users", default=[])
|
chatai_users = self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
if user_id in chatai_users:
|
if user_id in chatai_users:
|
||||||
chatai_users.remove(user_id)
|
chatai_users.remove(user_id)
|
||||||
self.set("core.chatbot", "chatai_users", chatai_users)
|
self.set('core.chatbot', 'chatai_users', chatai_users)
|
||||||
|
|
||||||
def getaiusers(self):
|
def getaiusers(self):
|
||||||
return self.get("core.chatbot", "chatai_users", default=[])
|
return self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
|
|
||||||
|
|
||||||
class SqliteDatabase(Database):
|
class SqliteDatabase(Database):
|
||||||
@@ -114,25 +114,25 @@ class SqliteDatabase(Database):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_row(row: sqlite3.Row):
|
def _parse_row(row: sqlite3.Row):
|
||||||
if row["type"] == "bool":
|
if row['type'] == 'bool':
|
||||||
return row["val"] == "1"
|
return row['val'] == '1'
|
||||||
if row["type"] == "int":
|
if row['type'] == 'int':
|
||||||
return int(row["val"])
|
return int(row['val'])
|
||||||
if row["type"] == "str":
|
if row['type'] == 'str':
|
||||||
return row["val"]
|
return row['val']
|
||||||
return json.loads(row["val"])
|
return json.loads(row['val'])
|
||||||
|
|
||||||
def _execute(self, module: str, *args, **kwargs) -> sqlite3.Cursor:
|
def _execute(self, module: str, *args, **kwargs) -> sqlite3.Cursor:
|
||||||
pattern = r"^(core|custom)"
|
pattern = r'^(core|custom)'
|
||||||
if not re.match(pattern, module):
|
if not re.match(pattern, module):
|
||||||
raise ValueError(f"Invalid module name format: {module}")
|
raise ValueError(f'Invalid module name format: {module}')
|
||||||
|
|
||||||
self._lock.acquire()
|
self._lock.acquire()
|
||||||
try:
|
try:
|
||||||
cursor = self._conn.cursor()
|
cursor = self._conn.cursor()
|
||||||
return cursor.execute(*args, **kwargs)
|
return cursor.execute(*args, **kwargs)
|
||||||
except sqlite3.OperationalError as e:
|
except sqlite3.OperationalError as e:
|
||||||
if str(e).startswith("no such table"):
|
if str(e).startswith('no such table'):
|
||||||
sql = f"""
|
sql = f"""
|
||||||
CREATE TABLE IF NOT EXISTS '{module}' (
|
CREATE TABLE IF NOT EXISTS '{module}' (
|
||||||
var TEXT UNIQUE NOT NULL,
|
var TEXT UNIQUE NOT NULL,
|
||||||
@@ -165,17 +165,17 @@ class SqliteDatabase(Database):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
val = "1" if value else "0"
|
val = '1' if value else '0'
|
||||||
typ = "bool"
|
typ = 'bool'
|
||||||
elif isinstance(value, str):
|
elif isinstance(value, str):
|
||||||
val = value
|
val = value
|
||||||
typ = "str"
|
typ = 'str'
|
||||||
elif isinstance(value, int):
|
elif isinstance(value, int):
|
||||||
val = str(value)
|
val = str(value)
|
||||||
typ = "int"
|
typ = 'int'
|
||||||
else:
|
else:
|
||||||
val = json.dumps(value)
|
val = json.dumps(value)
|
||||||
typ = "json"
|
typ = 'json'
|
||||||
|
|
||||||
self._execute(module, sql, (variable, val, typ, val, typ, variable))
|
self._execute(module, sql, (variable, val, typ, val, typ, variable))
|
||||||
self._conn.commit()
|
self._conn.commit()
|
||||||
@@ -188,16 +188,16 @@ class SqliteDatabase(Database):
|
|||||||
self._conn.commit()
|
self._conn.commit()
|
||||||
|
|
||||||
def get_collection(self, module: str) -> dict:
|
def get_collection(self, module: str) -> dict:
|
||||||
pattern = r"^(core|custom)"
|
pattern = r'^(core|custom)'
|
||||||
if not re.match(pattern, module):
|
if not re.match(pattern, module):
|
||||||
raise ValueError(f"Invalid module name format: {module}")
|
raise ValueError(f'Invalid module name format: {module}')
|
||||||
|
|
||||||
sql = f"SELECT * FROM '{module}'"
|
sql = f"SELECT * FROM '{module}'"
|
||||||
cur = self._execute(module, sql)
|
cur = self._execute(module, sql)
|
||||||
|
|
||||||
collection = {}
|
collection = {}
|
||||||
for row in cur:
|
for row in cur:
|
||||||
collection[row["var"]] = self._parse_row(row)
|
collection[row['var']] = self._parse_row(row)
|
||||||
|
|
||||||
return collection
|
return collection
|
||||||
|
|
||||||
@@ -208,30 +208,30 @@ class SqliteDatabase(Database):
|
|||||||
def add_chat_history(self, user_id, message):
|
def add_chat_history(self, user_id, message):
|
||||||
chat_history = self.get_chat_history(user_id, default=[])
|
chat_history = self.get_chat_history(user_id, default=[])
|
||||||
chat_history.append(message)
|
chat_history.append(message)
|
||||||
self.set(f"core.cohere.user_{user_id}", "chat_history", chat_history)
|
self.set(f'core.cohere.user_{user_id}', 'chat_history', chat_history)
|
||||||
|
|
||||||
def get_chat_history(self, user_id, default=None):
|
def get_chat_history(self, user_id, default=None):
|
||||||
if default is None:
|
if default is None:
|
||||||
default = []
|
default = []
|
||||||
return self.get(f"core.cohere.user_{user_id}", "chat_history", default=[])
|
return self.get(f'core.cohere.user_{user_id}', 'chat_history', default=[])
|
||||||
|
|
||||||
def addaiuser(self, user_id):
|
def addaiuser(self, user_id):
|
||||||
chatai_users = self.get("core.chatbot", "chatai_users", default=[])
|
chatai_users = self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
if user_id not in chatai_users:
|
if user_id not in chatai_users:
|
||||||
chatai_users.append(user_id)
|
chatai_users.append(user_id)
|
||||||
self.set("core.chatbot", "chatai_users", chatai_users)
|
self.set('core.chatbot', 'chatai_users', chatai_users)
|
||||||
|
|
||||||
def remaiuser(self, user_id):
|
def remaiuser(self, user_id):
|
||||||
chatai_users = self.get("core.chatbot", "chatai_users", default=[])
|
chatai_users = self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
if user_id in chatai_users:
|
if user_id in chatai_users:
|
||||||
chatai_users.remove(user_id)
|
chatai_users.remove(user_id)
|
||||||
self.set("core.chatbot", "chatai_users", chatai_users)
|
self.set('core.chatbot', 'chatai_users', chatai_users)
|
||||||
|
|
||||||
def getaiusers(self):
|
def getaiusers(self):
|
||||||
return self.get("core.chatbot", "chatai_users", default=[])
|
return self.get('core.chatbot', 'chatai_users', default=[])
|
||||||
|
|
||||||
|
|
||||||
if config.db_type in ["mongo", "mongodb"]:
|
if config.db_type in ['mongo', 'mongodb']:
|
||||||
db = MongoDatabase(config.db_url, config.db_name)
|
db = MongoDatabase(config.db_url, config.db_name)
|
||||||
else:
|
else:
|
||||||
db = SqliteDatabase(config.db_name)
|
db = SqliteDatabase(config.db_name)
|
||||||
|
|||||||
+274
-353
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user