Skip to content

Commit

Permalink
feat: custom thumb, caption & dump id
Browse files Browse the repository at this point in the history
This commit for feature request to add custom caption that closes #9 and also for feature request to add dump channel/group that closes #11
  • Loading branch information
X-Gorn committed Jun 7, 2024
1 parent 20a400f commit 3ea89b1
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 28 deletions.
3 changes: 3 additions & 0 deletions Bot/clients.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
from .config import Config
from pyrogram import Client
from typing import Union


class BotClient(Client):
Expand All @@ -9,6 +10,8 @@ def __init__(self):
self.bot: Client = Client(name='BulkLoader', api_id=Config.APP_ID, api_hash=Config.API_HASH,
bot_token=Config.BOT_TOKEN, plugins=Config.PLUGINS)
self.logger: logging.Logger = logging.getLogger('bot')
self.custom_caption: str = ""
self.custom_thumbnail = Union[str, None] = None

async def startup(self):
await self.bot.start()
Expand Down
4 changes: 4 additions & 0 deletions Bot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class Config(object):
# Upload method (default to False)
AS_ZIP = bool(strtobool(os.environ.get('AS_ZIP', 'False')))

# Channel/Group ID where you dump all the downloaded files.
DUMP_ID = int(os.environ.get('DUMP_ID')
) if os.environ.get('DUMP_ID') else None

PLUGINS = {'root': 'Bot.plugins'}

DOWNLOAD_DIR = "./downloads/"
48 changes: 33 additions & 15 deletions Bot/functions/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
import random
import traceback
from typing import Tuple
from pyrogram.errors import FloodWait
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from pyrogram.types import Message
from ..config import Config
from .. import client


Expand Down Expand Up @@ -109,35 +111,51 @@ async def send_media(file_name: str, update: Message) -> bool:
if os.path.isfile(file_name):
files = file_name
pablo = update
if not '/' in files:
caption = files
else:
caption = files.split('/')[-1]
caption = client.custom_caption
if not caption:
if not '/' in files:
caption = files
else:
caption = files.split('/')[-1]
progress_args = ('Uploading...', pablo, time.time())
thumbnail = client.custom_thumbnail
if files.lower().endswith(('.mkv', '.mp4')):
metadata = extractMetadata(createParser(files))
duration = 0
if metadata is not None:
if metadata.has("duration"):
duration = metadata.get('duration').seconds
rndmtime = str(random.randint(0, duration))
await run_cmd(f'ffmpeg -ss {rndmtime} -i "{files}" -vframes 1 thumbnail.jpg')
await update.reply_video(files, caption=caption, duration=duration, thumb='thumbnail.jpg', progress=progress_for_pyrogram, progress_args=progress_args)
os.remove('thumbnail.jpg')
if not thumbnail:
thumbnail = files+'.jpg'
await run_cmd(f'ffmpeg -ss {rndmtime} -i "{files}" -vframes 1 "{thumbnail}"')
sended_media = await update.reply_video(files, caption=caption, duration=duration, thumb=thumbnail, progress=progress_for_pyrogram, progress_args=progress_args)
elif files.lower().endswith(('.jpg', '.jpeg', '.png')):
try:
await update.reply_photo(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
except Exception as e:
print(e)
await update.reply_document(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
sended_media = await update.reply_photo(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
except Exception:
client.logger.warning(traceback.format_exc())
sended_media = await update.reply_document(files, caption=caption, thumb=thumbnail, progress=progress_for_pyrogram, progress_args=progress_args)
elif files.lower().endswith(('.mp3')):
duration = 0
if metadata is not None:
if metadata.has("duration"):
duration = metadata.get('duration').seconds
try:
await update.reply_audio(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
sended_media = await update.reply_audio(files, caption=caption, duration=duration, thumb=thumbnail, progress=progress_for_pyrogram, progress_args=progress_args)
except Exception as e:
print(e)
await update.reply_document(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
client.logger.warning(traceback.format_exc())
sended_media = await update.reply_document(files, caption=caption, thumb=thumbnail, progress=progress_for_pyrogram, progress_args=progress_args)
else:
await update.reply_document(files, caption=caption, progress=progress_for_pyrogram, progress_args=progress_args)
sended_media = await update.reply_document(files, caption=caption, thumb=thumbnail, progress=progress_for_pyrogram, progress_args=progress_args)
if Config.DUMP_ID:
try:
await sended_media.forward(Config.DUMP_ID)
except FloodWait as e:
await asyncio.sleep(e.value)
await sended_media.forward(Config.DUMP_ID)
except Exception:
client.logger.warning(traceback.format_exc())
return True
else:
return False
Expand Down
64 changes: 51 additions & 13 deletions Bot/plugins/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,41 @@ async def linkloader(bot: Client, update: Message):
if Config.AS_ZIP:
shutil.make_archive(dirs, 'zip', dirs)
start_time = time.time()
await update.reply_document(
filename,
progress=progress_for_pyrogram,
progress_args=(
'Uploading...',
pablo,
start_time
try:
sended_media = await update.reply_document(
document=filename,
thumb=client.custom_thumbnail,
caption=client.custom_caption,
progress=progress_for_pyrogram,
progress_args=(
'Uploading...',
pablo,
start_time
)
)
except FloodWait as e:
await asyncio.sleep(e.value)
sended_media = await update.reply_document(
document=filename,
thumb=client.custom_thumbnail,
caption=client.custom_caption,
progress=progress_for_pyrogram,
progress_args=(
'Uploading...',
pablo,
start_time
)
)
)
except Exception:
client.logger.warning(traceback.format_exc())
if Config.DUMP_ID:
try:
await sended_media.forward(Config.DUMP_ID)
except FloodWait as e:
await asyncio.sleep(e.value)
await sended_media.forward(Config.DUMP_ID)
except Exception:
client.logger.warning(traceback.format_exc())
await pablo.delete()
os.remove(filename)
shutil.rmtree(dirs)
Expand All @@ -80,7 +106,7 @@ async def linkloader(bot: Client, update: Message):


@Client.on_message(filters.document & OWNER_FILTER & filters.private)
async def loader(bot: Client, update: Message):
async def documentloader(bot: Client, update: Message):
dirs = f'{Config.DOWNLOAD_DIR}{update.from_user.id}'
if not os.path.isdir(dirs):
os.makedirs(dirs)
Expand Down Expand Up @@ -112,8 +138,10 @@ async def loader(bot: Client, update: Message):
shutil.make_archive(dirs, 'zip', dirs)
start_time = time.time()
try:
await update.reply_document(
filename,
sended_media = await update.reply_document(
document=filename,
thumb=client.custom_thumbnail,
caption=client.custom_caption,
progress=progress_for_pyrogram,
progress_args=(
'Uploading...',
Expand All @@ -123,8 +151,10 @@ async def loader(bot: Client, update: Message):
)
except FloodWait as e:
await asyncio.sleep(e.value)
await update.reply_document(
filename,
sended_media = await update.reply_document(
document=filename,
thumb=client.custom_thumbnail,
caption=client.custom_caption,
progress=progress_for_pyrogram,
progress_args=(
'Uploading...',
Expand All @@ -134,6 +164,14 @@ async def loader(bot: Client, update: Message):
)
except Exception:
client.logger.warning(traceback.format_exc())
if Config.DUMP_ID:
try:
await sended_media.forward(Config.DUMP_ID)
except FloodWait as e:
await asyncio.sleep(e.value)
await sended_media.forward(Config.DUMP_ID)
except Exception:
client.logger.warning(traceback.format_exc())
await pablo.delete()
os.remove(filename)
shutil.rmtree(dirs)
Expand Down
45 changes: 45 additions & 0 deletions Bot/plugins/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from .. import client
from pyrogram import Client, filters
from pyrogram.types import Message
from ..functions.filters import OWNER_FILTER
from ..functions.helper import URL_REGEX, run_cmd
from ..config import Config


async def reply_to_photo_filter(_, __, m: Message):
return bool(m.reply_to_message.photo)


@Client.on_message(filters.private & OWNER_FILTER & filters.command('caption'))
async def custom_caption(bot: Client, update: Message):
try:
caption = update.text.split(' ', 1)[1]
await update.reply(text='Custom caption updated.')
except IndexError:
caption = ""
await update.reply(text='Custom caption cleared.')
client.custom_caption = caption


@Client.on_message(filters.private & OWNER_FILTER & filters.command('thumbnail') & ~filters.reply & filters.regex(pattern=URL_REGEX))
async def custom_thumbnail(bot: Client, update: Message):
try:
thumbnail = f'{Config.DOWNLOAD_DIR}{update.from_user.id}.jpg'
command = 'wget -O "{}" "{}"'.format(
thumbnail, URL_REGEX.findall(update.text)[0])
await run_cmd(command)
await update.reply(text='Custom thumbnail updated.')
except IndexError:
if not client.custom_thumbnail:
return await update.reply(
text='Reply to a photo or `/thumbnail https.....jpg`'
)
thumbnail = None
await update.reply(text='Custom thumbnail cleared.')
client.custom_thumbnail = thumbnail


@Client.on_message(filters.private & OWNER_FILTER & filters.command('thumbnail') & filters.reply & filters.create(reply_to_photo_filter))
async def custom_thumbnail_reply(bot: Client, update: Message):
client.custom_thumbnail = await update.reply_to_message.download(file_name=f'{Config.DOWNLOAD_DIR}{update.from_user.id}.jpg')
await update.reply(text='Custom thumbnail updated.')
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ Telegram Bot to Bulk Downloading list of yt-dlp supported urls and Upload to Tel

### Features:

#### Settings

- `/thumbnail`: custom thumbnail. ex: reply to a photo or do `/thumbnail https...jpg`
- `/caption`: custom thumbnail. ex: `/caption abc`

Note: To clear thumbnail or the caption. do the command without args. ex: `/thumbnail` or `/caption`

#### Upload list of urls (2 methods):

- send links.
Expand All @@ -31,6 +38,8 @@ Note: Make sure that each link is separated.

`OWNER_ID`: Your Telegram ID.

`DUMP_ID`: Your Telegram Channel/Group ID to Dump the Uploaded Files. let it empty if you don't need it.

`AS_ZIP`: Set this to `True` if you want the bot to zip downloaded files before uploading. Default to `False`

</details>
Expand All @@ -55,6 +64,10 @@ Run Docker Container

`docker run --name=bulkloader -d -e API_HASH=abc -e APP_ID=123 -e BOT_TOKEN="123:abc" -e OWNER_ID=12345678 -e AS_ZIP=False xgorn/bulkloader:latest`

Restart Docker Container

`docker restart bulkloader`

Stop and Remove Docker Container (useful when you want to update the image to the latest and run it again)

```
Expand All @@ -66,6 +79,10 @@ Update Image to Latest

`docker pull xgorn/bulkloader:latest`

Redeploy Docker Container with Latest Image(one command)

`docker stop bulkloader && docker rm bulkloader && docker pull xgorn/bulkloader:latest && docker run --name=bulkloader -d -e API_HASH=abc -e APP_ID=123 -e BOT_TOKEN="123:abc" -e OWNER_ID=12345678 -e AS_ZIP=False xgorn/bulkloader:latest`

</details>

<details>
Expand Down
5 changes: 5 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
"AS_ZIP": {
"description": "Upload method.",
"value": "False"
},
"DUMP_ID": {
"description": "Dump Channel/Group. (optional)",
"value": "",
"required": false
}
},
"stack": "container",
Expand Down

0 comments on commit 3ea89b1

Please sign in to comment.