Skip to content

Commit

Permalink
bugs fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
Adarsh Goel committed Apr 15, 2022
0 parents commit 5453f26
Show file tree
Hide file tree
Showing 38 changed files with 2,775 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
custom: ['https://t.me/adarsh_bot', 'https://t.me/agprojects']
121 changes: 121 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
config.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

#session files
*.session
WebStreamer/template/new.html
WebStreamer/template/beta.html
WebStreamer/template/style.css
6 changes: 6 additions & 0 deletions Adarsh/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# (c) adarsh-goel


import time
StartTime = time.time()
__version__ = 1.1
87 changes: 87 additions & 0 deletions Adarsh/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# (c) adarsh-goel
import os
import sys
import glob
import asyncio
import logging
import importlib
from pathlib import Path
from pyrogram import idle
from .bot import StreamBot
from .vars import Var
from aiohttp import web
from .server import web_server
from .utils.keepalive import ping_server
from Adarsh.bot.clients import initialize_clients

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logging.getLogger("aiohttp").setLevel(logging.ERROR)
logging.getLogger("pyrogram").setLevel(logging.ERROR)
logging.getLogger("aiohttp.web").setLevel(logging.ERROR)

ppath = "Adarsh/bot/plugins/*.py"
files = glob.glob(ppath)
StreamBot.start()
loop = asyncio.get_event_loop()


async def start_services():
print('\n')
print('------------------- Initalizing Telegram Bot -------------------')
bot_info = await StreamBot.get_me()
StreamBot.username = bot_info.username
print("------------------------------ DONE ------------------------------")
print()
print(
"---------------------- Initializing Clients ----------------------"
)
await initialize_clients()
print("------------------------------ DONE ------------------------------")
print('\n')
print('--------------------------- Importing ---------------------------')
for name in files:
with open(name) as a:
patt = Path(a.name)
plugin_name = patt.stem.replace(".py", "")
plugins_dir = Path(f"Adarsh/bot/plugins/{plugin_name}.py")
import_path = ".plugins.{}".format(plugin_name)
spec = importlib.util.spec_from_file_location(import_path, plugins_dir)
load = importlib.util.module_from_spec(spec)
spec.loader.exec_module(load)
sys.modules["Adarsh.bot.plugins." + plugin_name] = load
print("Imported => " + plugin_name)
if Var.ON_HEROKU:
print("------------------ Starting Keep Alive Service ------------------")
print()
asyncio.create_task(ping_server())
print('-------------------- Initalizing Web Server -------------------------')
app = web.AppRunner(await web_server())
await app.setup()
bind_address = "0.0.0.0" if Var.ON_HEROKU else Var.BIND_ADRESS
await web.TCPSite(app, bind_address, Var.PORT).start()
print('----------------------------- DONE ---------------------------------------------------------------------')
print('\n')
print('---------------------------------------------------------------------------------------------------------')
print('---------------------------------------------------------------------------------------------------------')
print('Join https://t.me/agprojects to follow me for new bots')
print('---------------------------------------------------------------------------------------------------------')
print('\n')
print('----------------------- Service Started -----------------------------------------------------------------')
print(' bot =>> {}'.format((await StreamBot.get_me()).first_name))
print(' server ip =>> {}:{}'.format(bind_address, Var.PORT))
print(' Owner =>> {}'.format((Var.OWNER_USERNAME)))
if Var.ON_HEROKU:
print(' app runnng on =>> {}'.format(Var.FQDN))
print('---------------------------------------------------------------------------------------------------------')
print('Give a star to my repo https://github.com/adarsh-goel/filestreambot also follow me for new bots')
print('---------------------------------------------------------------------------------------------------------')
await idle()

if __name__ == '__main__':
try:
loop.run_until_complete(start_services())
except KeyboardInterrupt:
logging.info('----------------------- Service Stopped -----------------------')
17 changes: 17 additions & 0 deletions Adarsh/bot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# (c) adarsh-goel
from pyrogram import Client
import pyromod.listen
from ..vars import Var
from os import getcwd

StreamBot = Client(
session_name='Web Streamer',
api_id=Var.API_ID,
api_hash=Var.API_HASH,
bot_token=Var.BOT_TOKEN,
sleep_threshold=Var.SLEEP_THRESHOLD,
workers=Var.WORKERS
)

multi_clients = {}
work_loads = {}
44 changes: 44 additions & 0 deletions Adarsh/bot/clients.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# (c) adarsh-goel

import asyncio
import logging
from ..vars import Var
from pyrogram import Client
from Adarsh.utils.config_parser import TokenParser
from . import multi_clients, work_loads, StreamBot


async def initialize_clients():
multi_clients[0] = StreamBot
work_loads[0] = 0
all_tokens = TokenParser().parse_from_env()
if not all_tokens:
print("No additional clients found, using default client")
return

async def start_client(client_id, token):
try:
print(f"Starting - Client {client_id}")
if client_id == len(all_tokens):
await asyncio.sleep(2)
print("This will take some time, please wait...")
client = await Client(
session_name=":memory:",
api_id=Var.API_ID,
api_hash=Var.API_HASH,
bot_token=token,
sleep_threshold=Var.SLEEP_THRESHOLD,
no_updates=True,
).start()
work_loads[client_id] = 0
return client_id, client
except Exception:
logging.error(f"Failed starting Client - {client_id} Error:", exc_info=True)

clients = await asyncio.gather(*[start_client(i, token) for i, token in all_tokens.items()])
multi_clients.update(dict(clients))
if len(multi_clients) != 1:
Var.MULTI_CLIENT = True
print("Multi-Client Mode Enabled")
else:
print("No additional clients were initialized, using default client")
90 changes: 90 additions & 0 deletions Adarsh/bot/plugins/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# (c) @adarsh-goel
import os
import time
import string
import random
import asyncio
import aiofiles
import datetime
from Adarsh.utils.broadcast_helper import send_msg
from Adarsh.utils.database import Database
from Adarsh.bot import StreamBot
from Adarsh.vars import Var
from pyrogram import filters, Client
from pyrogram.types import Message
db = Database(Var.DATABASE_URL, Var.SESSION_NAME)
broadcast_ids = {}

@StreamBot.on_message(filters.command("users") & filters.private & ~filters.edited)
async def sts(c: Client, m: Message):
user_id=m.from_user.id
if user_id in Var.OWNER_ID:
total_users = await db.total_users_count()
await m.reply_text(text=f"Total Users in DB: {total_users}", parse_mode="Markdown", quote=True)


@StreamBot.on_message(filters.command("broadcast") & filters.private & ~filters.edited & filters.user(list(Var.OWNER_ID)))
async def broadcast_(c, m):
user_id=m.from_user.id
out = await m.reply_text(
text=f"Broadcast initiated! You will be notified with log file when all the users are notified."
)
all_users = await db.get_all_users()
broadcast_msg = m.reply_to_message
while True:
broadcast_id = ''.join([random.choice(string.ascii_letters) for i in range(3)])
if not broadcast_ids.get(broadcast_id):
break
start_time = time.time()
total_users = await db.total_users_count()
done = 0
failed = 0
success = 0
broadcast_ids[broadcast_id] = dict(
total=total_users,
current=done,
failed=failed,
success=success
)
async with aiofiles.open('broadcast.txt', 'w') as broadcast_log_file:
async for user in all_users:
sts, msg = await send_msg(
user_id=int(user['id']),
message=broadcast_msg
)
if msg is not None:
await broadcast_log_file.write(msg)
if sts == 200:
success += 1
else:
failed += 1
if sts == 400:
await db.delete_user(user['id'])
done += 1
if broadcast_ids.get(broadcast_id) is None:
break
else:
broadcast_ids[broadcast_id].update(
dict(
current=done,
failed=failed,
success=success
)
)
if broadcast_ids.get(broadcast_id):
broadcast_ids.pop(broadcast_id)
completed_in = datetime.timedelta(seconds=int(time.time() - start_time))
await asyncio.sleep(3)
await out.delete()
if failed == 0:
await m.reply_text(
text=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.",
quote=True
)
else:
await m.reply_document(
document='broadcast.txt',
caption=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.",
quote=True
)
os.remove('broadcast.txt')
14 changes: 14 additions & 0 deletions Adarsh/bot/plugins/dc_checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from Adarsh.bot import StreamBot
from pyrogram import filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton

START_TEXT = """ Your Telegram DC Is : `{}` """

@StreamBot.on_message(filters.regex("DC"))
async def start(bot, update):
text = START_TEXT.format(update.from_user.dc_id)
await update.reply_text(
text=text,
disable_web_page_preview=True,
quote=True
)
Loading

0 comments on commit 5453f26

Please sign in to comment.