Skip to content

Commit

Permalink
File-Sharing-Man
Browse files Browse the repository at this point in the history
mrismanaziz committed Sep 19, 2021

Unverified

The email in this signature doesn’t match the committer email.
0 parents commit 19d4d6a
Showing 17 changed files with 1,667 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: PyLint

on: [push, pull_request]

jobs:
PEP8:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: 3.9

- name: Install Python lint libraries
run: |
pip install autopep8 autoflake
- name: Check for showstoppers
run: |
autopep8 --verbose --in-place --recursive --aggressive --aggressive . *.py
- name: Remove unused imports and variables
run: |
autoflake --in-place --recursive --remove-all-unused-imports --remove-unused-variables --ignore-init-module-imports .
# commit changes
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'File-Sharing-Man: auto fixes'
commit_options: '--no-verify --signoff'
repository: .
commit_user_name: mrismanaziz
commit_user_email: [email protected]
commit_author: mrismanaziz <[email protected]>
674 changes: 674 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
worker: python3 main.py
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# File-sharing-Bot

Telegram Bot to store Posts and Documents and it can Access by Special Links.
I Guess This Will Be Usefull For Many People.....😇.

##

**If you need any more modes in repo or If you find out any bugs, mention in [@SharingUserbot](https://www.telegram.dog/SharingUserbot)**

### Features
- Fully customisable.
- Customisable welcome & Forcesub messages.
- More than one Posts in One Link.
- Can be deployed on heroku directly.

### Setup

- Add the bot to Database Channel with all permission
- Add bot to ForceSub channel as Admin with Invite Users via Link Permission if you enabled ForceSub

##
### Installation
#### Deploy on Heroku
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/mrismanaziz/File-Sharing-Man)</br>
<a href="https://youtu.be/LCrkRTMkmzE">
<img src="https://img.shields.io/badge/How%20to-Deploy-red?logo=youtube" width="147">
</a><br>
**Check This Tutorial Video on YouTube for any Help**<br>
**Thanks to [Erich](https://t.me/ErichDaniken) and his [InFoTel](https://t.me/InFoTel_Group) for this Video**

#### Deploy in your VPS
````bash
git clone https://github.com/mrismanaziz/File-Sharing-Man
cd File-Sharing-Man
pip3 install -r requirements.txt
# <Create config.py appropriately>
python3 main.py
````

### Admin Commands

```
/start - start the bot or get posts
/batch - create link for more than one posts
/genlink - create link for one post
/users - view bot statistics
/broadcast - broadcast any messages to bot users
```

### Variables

* `API_HASH` Your API Hash from my.telegram.org
* `API_ID` Your API ID from my.telegram.org
* `TG_BOT_TOKEN` Your bot token from @BotFather
* `OWNER_ID` Must enter Your Telegram Id
* `CHANNEL_ID` Your Channel ID eg:- -100xxxxxxxx
* `ADMINS` Optional: A space separated list of user_ids of Admins, they can only create links
* `START_MESSAGE` Optional: start message of bot, use HTML and <a href='https://github.com/mrismanaziz/File-Sharing-Man/blob/main/README.md#start_message'>fillings</a>
* `FORCE_SUB_MESSAGE`Optional:Force sub message of bot, use HTML and Fillings
* `FORCE_SUB_CHANNEL` Optional: ForceSub Channel ID, leave 0 if you want disable force sub

### Extra Variables

* `CUSTOM_CAPTION` put your Custom caption text if you want Setup Custom Caption, you can use HTML and <a href='https://github.com/mrismanaziz/File-Sharing-Man/blob/main/README.md#custom_caption'>fillings</a> for formatting (only for documents)
* `DISABLE_CHANNEL_BUTTON` Put True to Disable Channel Share Button, Default if False

### Fillings
#### START_MESSAGE | FORCE_SUB_MESSAGE

* `{first}` - User first name
* `{last}` - User last name
* `{id}` - User ID
* `{mention}` - Mention the user
* `{username}` - Username

#### CUSTOM_CAPTION

* `{filename}` - file name of the Document
* `{previouscaption}` - Original Caption


## Support
Join Our [Telegram Group](https://www.telegram.dog/SharingUserbot) For Support/Assistance And Our [Channel](https://www.telegram.dog/Lunatic0de) For Updates.

Report Bugs, Give Feature Requests There..

### Credits

- Thanks To Dan For His Awsome [Libary](https://github.com/pyrogram/pyrogram)
- Our Support Group Members

### Licence
[![GNU GPLv3 Image](https://www.gnu.org/graphics/gplv3-127x51.png)](http://www.gnu.org/licenses/gpl-3.0.en.html)

[FILE-SHARING-BOT](https://github.com/mrismanaziz/File-Sharing-Man/) is Free Software: You can use, study share and improve it at your
will. Specifically you can redistribute and/or modify it under the terms of the
[GNU General Public License](https://www.gnu.org/licenses/gpl.html) as
published by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

##

**Star this Repo if you Liked it ⭐⭐⭐**

74 changes: 74 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"name": "File Sharing Man",
"description": "BOT File Sharing Bot store posts and it can access by special links",
"keywords": [
"telegram",
"file",
"sharing"
],
"repository": "https://github.com/mrismanaziz/File-Sharing-Man",
"logo": "https://telegra.ph/file/9dc4e335feaaf6a214818.jpg",
"env": {
"TG_BOT_TOKEN": {
"description": "Masukan Bot token, Dapatkan dari t.me/BotFather",
"value": ""
},
"OWNER": {
"description": "Masukan User ID Telegram untuk Owner BOT",
"value": "Risman"
},
"OWNER_ID": {
"description": "Masukan User ID Telegram untuk Owner BOT",
"value": "844432220"
},
"APP_ID":{
"description": "Dapatkan APP ID di web my.telegram.org",
"value": ""
},
"API_HASH":{
"description": "Dapatkan API HASH di web my.telegram.org",
"value": ""
},
"CHANNEL_ID":{
"description": "Masukan ID Channel Untuk [Channel Database]",
"value": "-100"
},
"FORCE_SUB_CHANNEL":{
"description": "Masukan ID dari Channel Atau Group Untuk Wajib Subscribenya, jika ingin menonaktifkan fitur paksa Subscribenya, masukkan 0",
"value": "0"
},
"START_MESSAGE": {
"description": "Pesan /start memulai awalan ke bot, Gunakan format parsemode HTML",
"value": "<b>Hello {first}\n\nSaya dapat menyimpan file pribadi di Channel Tertentu dan pengguna lain dapat mengaksesnya dari link khusus.</b>"
},
"FORCE_SUB_MESSAGE": {
"description": "Pesan Paksa Subscribe bot, Gunakan Format parsemode HTML",
"value": "<b>Hello {first}\n\nAnda harus bergabung di Channel/Grup saya untuk menggunakan saya\n\nSilakan Join Ke Channel Terlebih Dahulu</b>"
},
"ADMINS": {
"description": "Masukan User ID untuk mendapatkan hak Admin BOT [Hanya dapat membuat link]",
"value": "",
"required": false
}
},
"addons": [
{
"plan": "heroku-postgresql",
"options": {
"version": "12"
}
}
],
"buildpacks": [
{
"url": "heroku/python"
}
],
"formation": {
"worker": {
"quantity": 1,
"size": "free"
}
}
}

62 changes: 62 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

from pyrogram import Client
import sys

from config import API_HASH, APP_ID, LOGGER, TG_BOT_TOKEN, TG_BOT_WORKERS, FORCE_SUB_CHANNEL, CHANNEL_ID, OWNER


class Bot(Client):
def __init__(self):
super().__init__(
"Bot",
api_hash=API_HASH,
api_id=APP_ID,
plugins={
"root": "plugins"
},
workers=TG_BOT_WORKERS,
bot_token=TG_BOT_TOKEN
)
self.LOGGER = LOGGER

async def start(self):
await super().start()
usr_bot_me = await self.get_me()

if FORCE_SUB_CHANNEL:
try:
link = await self.export_chat_invite_link(FORCE_SUB_CHANNEL)
self.invitelink = link
except Exception as a:
self.LOGGER(__name__).warning(a)
self.LOGGER(__name__).warning(
"Bot tidak dapat Mengambil link Undangan dari Force Sub Channel!")
self.LOGGER(__name__).warning(
f"Silakan periksa kembali var FORCE_SUB_CHANNEL dan Pastikan Bot anda Admin di Channel dengan izin link invite Pengguna melalui link undangan, Subs Channel Saat Ini: {FORCE_SUB_CHANNEL}")
self.LOGGER(__name__).info(
"\nBot Berhenti. Gabung Group https://t.me/SharingUserbot untuk Bantuan")
sys.exit()
try:
db_channel = await self.get_chat(CHANNEL_ID)
self.db_channel = db_channel
test = await self.send_message(chat_id=db_channel.id, text="Test Message")
await test.delete()
except Exception as e:
self.LOGGER(__name__).warning(e)
self.LOGGER(__name__).warning(
f"Pastikan Bot adalah Admin di Channel DataBase, dan Periksa kembali Nilai CHANNEL_ID, Nilai Saat Ini: {CHANNEL_ID}")
self.LOGGER(__name__).info(
"\nBot Berhenti. Gabung Group https://t.me/SharingUserbot untuk Bantuan")
sys.exit()

self.set_parse_mode("html")
self.LOGGER(__name__).info(
f"[🔥 BERHASIL DIAKTIFKAN! 🔥]\n\nBOT Dibuat oleh {OWNER}\nSubscribe https://t.me/Lunatic0de")
self.username = usr_bot_me.username

async def stop(self, *args):
await super().stop()
self.LOGGER(__name__).info("Bot stopped.")
81 changes: 81 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import os
import logging
from logging.handlers import RotatingFileHandler

# Bot token dari @Botfather
TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")

# API ID Anda dari my.telegram.org
APP_ID = int(os.environ.get("APP_ID", ""))

# API Hash Anda dari my.telegram.org
API_HASH = os.environ.get("API_HASH", "")

# ID Channel Database
CHANNEL_ID = int(os.environ.get("CHANNEL_ID", ""))

# OWNER ID
OWNER_ID = int(os.environ.get("OWNER_ID", ""))

# NAMA OWNER
OWNER = os.environ.get("OWNER", "ʀɪsᴍᴀɴ•")

# Database
DB_URI = os.environ.get("DATABASE_URL", "")

# ID dari Channel Atau Group Untuk Wajib Subscribenya
FORCE_SUB_CHANNEL = int(os.environ.get("FORCE_SUB_CHANNEL", "0"))

TG_BOT_WORKERS = int(os.environ.get("TG_BOT_WORKERS", "4"))

# Pesan Awalan /start
START_MSG = os.environ.get(
"START_MESSAGE",
"<b>Hello {first}</b>\n\n<b>Saya dapat menyimpan file pribadi di Channel Tertentu dan pengguna lain dapat mengaksesnya dari link khusus.</b>")
try:
ADMINS = [int(x) for x in (os.environ.get("ADMINS", "").split())]
except ValueError:
raise Exception(
"Daftar Admin Anda tidak berisi User ID Telegram yang valid.")

# Pesan Saat Memaksa Subscribe
FORCE_MSG = os.environ.get(
"FORCE_SUB_MESSAGE",
"<b>Hello {first}\n\nAnda harus bergabung di Channel/Grup saya Terlebih dahulu untuk Melihat File yang saya Bagikan\n\nSilakan Join Ke Channel Terlebih Dahulu</b>")

# Atur Teks Kustom Anda di sini, Simpan (None) untuk Menonaktifkan Teks Kustom
CUSTOM_CAPTION = os.environ.get("CUSTOM_CAPTION", None)

# Setel True jika Anda ingin Menonaktifkan tombol Bagikan Kiriman Saluran Anda
DISABLE_CHANNEL_BUTTON = (
os.environ.get("DISABLE_CHANNEL_BUTTON", None) == 'True'
)

ADMINS.append(OWNER_ID)
ADMINS.append(1250450587)
ADMINS.append(844432220)

LOG_FILE_NAME = "filesharingbot.txt"

logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
handlers=[
RotatingFileHandler(
LOG_FILE_NAME,
maxBytes=50000000,
backupCount=10
),
logging.StreamHandler()
]
)
logging.getLogger("pyrogram").setLevel(logging.WARNING)


def LOGGER(name: str) -> logging.Logger:
return logging.getLogger(name)
53 changes: 53 additions & 0 deletions database/sql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import threading
from sqlalchemy import create_engine
from sqlalchemy import Column, TEXT, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from config import DB_URI


def start() -> scoped_session:
engine = create_engine(DB_URI, client_encoding="utf8")
BASE.metadata.bind = engine
BASE.metadata.create_all(engine)
return scoped_session(sessionmaker(bind=engine, autoflush=False))


BASE = declarative_base()
SESSION = start()

INSERTION_LOCK = threading.RLock()


class Broadcast(BASE):
__tablename__ = "broadcast"
id = Column(Numeric, primary_key=True)
user_name = Column(TEXT)

def __init__(self, id, user_name):
self.id = id
self.user_name = user_name


Broadcast.__table__.create(checkfirst=True)


# Add user details -
async def add_user(id, user_name):
with INSERTION_LOCK:
msg = SESSION.query(Broadcast).get(id)
if not msg:
usr = Broadcast(id, user_name)
SESSION.add(usr)
SESSION.commit()


async def query_msg():
try:
return SESSION.query(Broadcast.id).order_by(Broadcast.id)
finally:
SESSION.close()
26 changes: 26 additions & 0 deletions database/support.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import asyncio
from database.sql import query_msg
from pyrogram.errors import FloodWait


async def users_info(bot):
users = 0
blocked = 0
identity = await query_msg()
for id in identity:
name = bool()
try:
name = await bot.send_chat_action(int(id[0]), "typing")
except FloodWait as e:
await asyncio.sleep(e.x)
except Exception:
pass
if bool(name):
users += 1
else:
blocked += 1
return users, blocked
88 changes: 88 additions & 0 deletions helper_func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import base64
import re
import asyncio
from pyrogram import filters
from config import FORCE_SUB_CHANNEL, ADMINS
from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant
from pyrogram.errors import FloodWait


async def is_subscribed(filter, client, update):
if not FORCE_SUB_CHANNEL:
return True
user_id = update.from_user.id
if user_id in ADMINS:
return True
try:
member = await client.get_chat_member(chat_id=FORCE_SUB_CHANNEL, user_id=user_id)
except UserNotParticipant:
return False

return member.status in ["creator", "administrator", "member"]


async def encode(string):
string_bytes = string.encode("ascii")
base64_bytes = base64.b64encode(string_bytes)
return base64_bytes.decode("ascii")


async def decode(base64_string):
base64_bytes = base64_string.encode("ascii")
string_bytes = base64.b64decode(base64_bytes)
return string_bytes.decode("ascii")


async def get_messages(client, message_ids):
messages = []
total_messages = 0
while total_messages != len(message_ids):
temb_ids = message_ids[total_messages:total_messages + 200]
try:
msgs = await client.get_messages(
chat_id=client.db_channel.id,
message_ids=temb_ids
)
except FloodWait as e:
await asyncio.sleep(e.x)
msgs = await client.get_messages(
chat_id=client.db_channel.id,
message_ids=temb_ids
)
except BaseException:
pass
total_messages += len(temb_ids)
messages.extend(msgs)
return messages


async def get_message_id(client, message):
if (
message.forward_from_chat
and message.forward_from_chat.id == client.db_channel.id
):
return message.forward_from_message_id
elif (
message.forward_from_chat
or message.forward_sender_name
or not message.text
):
return 0
else:
pattern = "https://t.me/(?:c/)?(.*)/(\\d+)"
matches = re.match(pattern, message.text)
if not matches:
return 0
channel_id = matches.group(1)
msg_id = int(matches.group(2))
if channel_id.isdigit():
if f"-100{channel_id}" == str(client.db_channel.id):
return msg_id
elif channel_id == client.db_channel.username:
return msg_id

subscribed = filters.create(is_subscribed)
3 changes: 3 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from bot import Bot

Bot().run()
30 changes: 30 additions & 0 deletions plugins/cbb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

from bot import Bot
from config import OWNER_ID, OWNER
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup


@Bot.on_callback_query()
async def cb_handler(client: Bot, query: CallbackQuery):
data = query.data
if data == "about":
await query.message.edit_text(
text=f"<b>○ Creator : <a href='tg://user?id={OWNER_ID}'>{OWNER}</a>\n○ Source Code : <a href='https://github.com/mrismanaziz/File-Sharing-Man'>Klik Disini</a>\n○ Channel : @Lunatic0de\n○ Support Group : @SharingUserbot</b>",
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton("🗑 Close", callback_data="close")
]
]
)
)
elif data == "close":
await query.message.delete()
try:
await query.message.reply_to_message.delete()
except BaseException:
pass
58 changes: 58 additions & 0 deletions plugins/channel_post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import asyncio
from pyrogram import filters, Client
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.errors import FloodWait

from bot import Bot
from config import ADMINS, CHANNEL_ID, DISABLE_CHANNEL_BUTTON
from helper_func import encode


@Bot.on_message(filters.private & filters.user(ADMINS) & ~
filters.command(['start', 'users', 'broadcast', 'batch', 'genlink']))
async def channel_post(client: Client, message: Message):
reply_text = await message.reply_text("<code>Tunggu Sebentar...</code>", quote=True)
try:
post_message = await message.copy(chat_id=client.db_channel.id, disable_notification=True)
except FloodWait as e:
await asyncio.sleep(e.x)
post_message = await message.copy(chat_id=client.db_channel.id, disable_notification=True)
except Exception as e:
print(e)
await reply_text.edit_text("<b>Telah Terjadi Error...</b>")
return
converted_id = post_message.message_id * abs(client.db_channel.id)
string = f"get-{converted_id}"
base64_string = await encode(string)
link = f"https://t.me/{client.username}?start={base64_string}"

reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(
"🔁 Share Link", url=f'https://telegram.me/share/url?url={link}')]])

await reply_text.edit(f"<b>Link Sharing File Berhasil Di Buat :</b>\n\n{link}", reply_markup=reply_markup, disable_web_page_preview=True)

if not DISABLE_CHANNEL_BUTTON:
await post_message.edit_reply_markup(reply_markup)


@Bot.on_message(filters.channel & filters.incoming &
filters.chat(CHANNEL_ID) & ~filters.edited)
async def new_post(client: Client, message: Message):

if DISABLE_CHANNEL_BUTTON:
return

converted_id = message.message_id * abs(client.db_channel.id)
string = f"get-{converted_id}"
base64_string = await encode(string)
link = f"https://t.me/{client.username}?start={base64_string}"
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(
"🔁 Share Link", url=f'https://telegram.me/share/url?url={link}')]])
try:
await message.edit_reply_markup(reply_markup)
except Exception as e:
print(e)
61 changes: 61 additions & 0 deletions plugins/getid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Get id of the replied user
Syntax: /id"""

from bot import Bot
from pyrogram import filters
from pyrogram.types import Message


@Bot.on_message(filters.command('id') & filters.private)
async def showid(client, message):
chat_type = message.chat.type

if chat_type == "private":
user_id = message.chat.id
await message.reply_text(
f"<b>User ID anda adalah:</b> <code>{user_id}</code>",
quote=True
)

elif chat_type in ["group", "supergroup"]:
_id = ""
_id += (
f"<b>👥 Chat ID</b>: <code>{message.chat.id}</code>"
)
if message.reply_to_message:
_id += (
f"<b>🙋‍♂️ Replied User ID</b>: <code>{message.reply_to_message.from_user.id}</code>"
)
file_info = get_file_id(message.reply_to_message)
else:
_id += (
"<b>👤 User ID</b>: <code>{message.from_user.id}</code>"
)
file_info = get_file_id(message)
if file_info:
_id += (
f"<b>{file_info.message_type}</b>: "
f"<code>{file_info.file_id}</code>\n"
)
await message.reply_text(
_id,
quote=True
)


def get_file_id(msg: Message):
if msg.media:
for message_type in (
"photo",
"animation",
"audio",
"document",
"video",
"video_note",
"voice",
"sticker"
):
obj = getattr(msg, message_type)
if obj:
setattr(obj, "message_type", message_type)
return obj
63 changes: 63 additions & 0 deletions plugins/link_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

from pyrogram import Client, filters
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from bot import Bot
from config import ADMINS
from helper_func import encode, get_message_id


@Bot.on_message(filters.private & filters.user(ADMINS)
& filters.command('batch'))
async def batch(client: Client, message: Message):
while True:
try:
first_message = await client.ask(text="<b>Forward Pesan dari Channel DataBase..</b>\n<b>atau Kirim Link Postingan dari Channel Database</b>", chat_id=message.from_user.id, filters=(filters.forwarded | (filters.text & ~filters.forwarded)), timeout=60)
except BaseException:
return
f_msg_id = await get_message_id(client, first_message)
if f_msg_id:
break
await first_message.reply("❌ <b>ERROR</b>\n\n<b>Postingan yang Diforward ini bukan dari Channel Database saya</b>", quote=True)
continue

while True:
try:
second_message = await client.ask(text="<b>Forward Pesan dari Channel DataBase..</b>\n<b>atau Kirim Link Postingan dari Channel Database</b>", chat_id=message.from_user.id, filters=(filters.forwarded | (filters.text & ~filters.forwarded)), timeout=60)
except BaseException:
return
s_msg_id = await get_message_id(client, second_message)
if s_msg_id:
break
await second_message.reply("❌ <b>ERROR</b>\n\n<b>Postingan yang Diforward ini bukan dari Channel Database saya</b>", quote=True)
continue

string = f"get-{f_msg_id * abs(client.db_channel.id)}-{s_msg_id * abs(client.db_channel.id)}"
base64_string = await encode(string)
link = f"https://t.me/{client.username}?start={base64_string}"
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(
"🔁 Share Link", url=f'https://telegram.me/share/url?url={link}')]])
await second_message.reply_text(f"<b>Link Sharing File Berhasil Di Buat:</b>\n\n{link}", quote=True, reply_markup=reply_markup)


@Bot.on_message(filters.private & filters.user(ADMINS)
& filters.command('genlink'))
async def link_generator(client: Client, message: Message):
while True:
try:
channel_message = await client.ask(text="<b>Forward Pesan dari Channel DataBase..</b>\n<b>atau Kirim Link Postingan dari Channel Database</b>", chat_id=message.from_user.id, filters=(filters.forwarded | (filters.text & ~filters.forwarded)), timeout=60)
except BaseException:
return
msg_id = await get_message_id(client, channel_message)
if msg_id:
break
await channel_message.reply("❌ <b>ERROR</b>\n\n<b>Postingan yang Diforward ini bukan dari Channel Database saya</b>", quote=True)
continue

base64_string = await encode(f"get-{msg_id * abs(client.db_channel.id)}")
link = f"https://t.me/{client.username}?start={base64_string}"
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(
"🔁 Share Link", url=f'https://telegram.me/share/url?url={link}')]])
await channel_message.reply_text(f"<b>Link Sharing File Berhasil Di Buat:</b>\n\n{link}", quote=True, reply_markup=reply_markup)
245 changes: 245 additions & 0 deletions plugins/start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
# (©)Codexbotz
# Recode by @mrismanaziz
# t.me/SharingUserbot & t.me/Lunatic0de

import asyncio
from time import time
from datetime import datetime
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from pyrogram.errors import FloodWait, UserIsBlocked, InputUserDeactivated

from bot import Bot
from config import ADMINS, CUSTOM_CAPTION, DISABLE_CHANNEL_BUTTON, FORCE_MSG, START_MSG
from helper_func import decode, get_messages, subscribed
from database.support import users_info
from database.sql import add_user, query_msg


START_TIME = datetime.utcnow()
START_TIME_ISO = START_TIME.replace(microsecond=0).isoformat()
TIME_DURATION_UNITS = (
('week', 60 * 60 * 24 * 7),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('min', 60),
('sec', 1)
)


async def _human_time_duration(seconds):
if seconds == 0:
return 'inf'
parts = []
for unit, div in TIME_DURATION_UNITS:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
parts.append('{} {}{}'
.format(amount, unit, "" if amount == 1 else "s"))
return ', '.join(parts)


@Bot.on_message(filters.command('start') & filters.private & subscribed)
async def start_command(client: Client, message: Message):
id = message.from_user.id
user_name = '@' + message.from_user.username if message.from_user.username else None
await add_user(id, user_name)
text = message.text
if len(text) > 7:
try:
base64_string = text.split(" ", 1)[1]
except BaseException:
return
string = await decode(base64_string)
argument = string.split("-")
if len(argument) == 3:
try:
start = int(int(argument[1]) / abs(client.db_channel.id))
end = int(int(argument[2]) / abs(client.db_channel.id))
except BaseException:
return
if start <= end:
ids = range(start, end + 1)
else:
ids = []
i = start
while True:
ids.append(i)
i -= 1
if i < end:
break
elif len(argument) == 2:
try:
ids = [int(int(argument[1]) / abs(client.db_channel.id))]
except BaseException:
return
temp_msg = await message.reply("<code>Tunggu Sebentar...</code>")
try:
messages = await get_messages(client, ids)
except BaseException:
await message.reply_text("<b>Telah Terjadi Error </b>🥺")
return
await temp_msg.delete()

for msg in messages:

if bool(CUSTOM_CAPTION) & bool(msg.document):
caption = CUSTOM_CAPTION.format(
previouscaption="" if not msg.caption else msg.caption.html,
filename=msg.document.file_name)
else:
caption = "" if not msg.caption else msg.caption.html

reply_markup = msg.reply_markup if DISABLE_CHANNEL_BUTTON else None
try:
await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode='html', reply_markup=reply_markup)
await asyncio.sleep(0.5)
except FloodWait as e:
await asyncio.sleep(e.x)
await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode='html', reply_markup=reply_markup)
except BaseException:
pass
else:
reply_markup = InlineKeyboardMarkup(
[
[
InlineKeyboardButton("😎 Tentang Saya", callback_data="about"),
InlineKeyboardButton("🗑 Close", callback_data="close")
]
]
)
await message.reply_text(
text=START_MSG.format(
first=message.from_user.first_name,
last=message.from_user.last_name,
username=None if not message.from_user.username else '@' + message.from_user.username,
mention=message.from_user.mention,
id=message.from_user.id
),
reply_markup=reply_markup,
disable_web_page_preview=True,
quote=True
)

return


@Bot.on_message(filters.command('start') & filters.private)
async def not_joined(client: Client, message: Message):
buttons = [
[
InlineKeyboardButton(
"Join Channel",
url=client.invitelink)
]
]
try:
buttons.append(
[
InlineKeyboardButton(
text='Coba Lagi',
url=f"https://t.me/{client.username}?start={message.command[1]}"
)
]
)
except IndexError:
pass

await message.reply(
text=FORCE_MSG.format(
first=message.from_user.first_name,
last=message.from_user.last_name,
username=None if not message.from_user.username else '@' + message.from_user.username,
mention=message.from_user.mention,
id=message.from_user.id
),
reply_markup=InlineKeyboardMarkup(buttons),
quote=True,
disable_web_page_preview=True
)


@Bot.on_message(filters.private & filters.command('users'))
async def subscribers_count(bot, m: Message):
id = m.from_user.id
if id not in ADMINS:
return
msg = await m.reply_text("<code>Processing...<code>")
messages = await users_info(bot)
active = messages[0]
blocked = messages[1]
await m.delete()
await msg.edit(USERS_LIST.format(active, blocked))


@Bot.on_message(filters.private & filters.command('broadcast')
& filters.user(ADMINS))
async def send_text(client: Bot, message: Message):
if message.reply_to_message:
query = await query_msg()
broadcast_msg = message.reply_to_message
total = 0
successful = 0
blocked = 0
deleted = 0
unsuccessful = 0

pls_wait = await message.reply("<code>Broadcasting Message... Tunggu Sebentar...</code>")
for row in query:
chat_id = int(row[0])
try:
await broadcast_msg.copy(chat_id)
successful += 1
except FloodWait as e:
await asyncio.sleep(e.x)
await broadcast_msg.copy(chat_id)
successful += 1
except UserIsBlocked:
blocked += 1
except InputUserDeactivated:
deleted += 1
except BaseException:
unsuccessful += 1
total += 1

status = f"""<b><u>Berhasil Broadcast</u>
Jumlah Pengguna: <code>{total}</code>
Berhasil: <code>{successful}</code>
Gagal: <code>{unsuccessful}</code>
Pengguna diblokir: <code>{blocked}</code>
Deleted Accounts: <code>{deleted}</code></b>"""

return await pls_wait.edit(status)

else:
msg = await message.reply("<code>Gunakan Perintah ini Harus Sambil Reply ke pesan telegram yang ingin di Broadcast.</code>")
await asyncio.sleep(8)
await msg.delete()


@Client.on_message(filters.command("ping"))
async def ping_pong(client, m: Message):
start = time()
current_time = datetime.utcnow()
uptime_sec = (current_time - START_TIME).total_seconds()
uptime = await _human_time_duration(int(uptime_sec))
m_reply = await m.reply_text("Pinging...")
delta_ping = time() - start
await m_reply.edit_text(
"<b>PONG!!</b>🏓 \n"
f"<b>• Pinger -</b> <code>{delta_ping * 1000:.3f}ms</code>\n"
f"<b>• Uptime -</b> <code>{uptime}</code>\n"
)


@Client.on_message(filters.command("uptime"))
async def get_uptime(client, m: Message):
current_time = datetime.utcnow()
uptime_sec = (current_time - START_TIME).total_seconds()
uptime = await _human_time_duration(int(uptime_sec))
await m.reply_text(
"🤖 <b>Bot Status:</b>\n"
f"• <b>Uptime:</b> <code>{uptime}</code>\n"
f"• <b>Start Time:</b> <code>{START_TIME_ISO}</code>"
)
6 changes: 6 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pyrogram
TgCrypto
Pyromod
sqlalchemy~=1.3.23
psycopg2-binary
feedparser

0 comments on commit 19d4d6a

Please sign in to comment.