Skip to content
This repository has been archived by the owner on Sep 6, 2024. It is now read-only.

Commit

Permalink
Release tgEasy New Update: v1.1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
jayantkageri committed Aug 24, 2021
1 parent 52f4dd2 commit b6db4a0
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 112 deletions.
32 changes: 26 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,16 @@ along with tgEasy. If not, see <http://www.gnu.org/licenses/>.

# tgEasy
```python
from tgEasy import command, run
from tgEasy import tgClient, command
from pyrogram import Client

app = tgClient(Client("my_account"))

@command("start", group_only=True)
async def start(client, message):
await message.reply_text(f"Hello {message.from_user.mention}")

run()
app.run()
```

## Featurs
Expand All @@ -56,10 +59,24 @@ run()
- `BOT_TOKEN` - Bot Token provided by Bot Father
- `LOGS` - Log Group ID
- `PLUGINS` - Plugins Directory Path where your Plugins are located, By Default it is `plugins` Directory
- `HANDLERS` - The Command Handlers, By Default it is `/` and `!`

## Documatation
- Add `from tgEasy import run` and `run()` for running
- Never name `tgEasy` for your any files/directory

### `tgEasy.tgClient`
- A Class for Initialising the tgEasy and it's Methods, Types and Functions
- Parameters:
- client (`pyrogram.Client`):
- The Pyrogram Client

#### Example
```python
from tgEasy import tgClient
from pyrogram import Client

app = tgClient(Client("my_account"))
```
### `tgEasy.command`
- A decorater to Register Commands in simple way and manage errors in that Function itself, alternative for `@pyrogram.Client.on_message(pyrogram.filters.command('command'))`
- Parameters:
Expand All @@ -74,6 +91,9 @@ run()

- self_admin (bool) **optional**:
- If True, the command will only executeed if the Bot is Admin in the Chat, By Default False

- self_only (bool) **optional**:
- If True, the command will only executeed if the Bot is Admin in the Chat, By Default False

- filter (`~pyrogram.filters`) **optional**:
- Pyrogram Filters, hope you know about this, for Advaced usage. By Default `~pyrogram.filters.edited` and this can't be changed. Use `and` for seaperating filters.
Expand All @@ -83,7 +103,7 @@ run()
import pyrogram
from tgEasy import command

@command("start", group_only=False, pm_only=False, self_admin=False, pyrogram.filters.chat("777000") and pyrogram.filters.text)
@command("start", group_only=False, pm_only=False, self_admin=False, self_only=False, pyrogram.filters.chat("777000") and pyrogram.filters.text)
async def start(client, message):
await message.reply_text(f"Hello {message.from_user.mention}")
```
Expand Down Expand Up @@ -143,8 +163,8 @@ async def start(client, message):
await message.reply_text(f"Hello Admin {message.from_user.mention}")
```

### `tgEasy.run()`
- Runs the `pyrogram.Client` by adding `tgEasy.run()` in your main file and run [Not Recommended to use this], instead of running `python3 -m tgEasy`.
### `tgEasy.tgClient.run()`
- Runs the `pyrogram.Client` by adding `tgEasy.tgClient.run()` in your main file and run [Not Recommended to use this], instead of running `python3 -m tgEasy`.

- This calls `pyrogram.Client.start()`, `pyrogram.idle()` and `pyrogram.Client.stop()`
#### Example
Expand Down
110 changes: 62 additions & 48 deletions tgEasy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# along with tgEasy. If not, see <http://www.gnu.org/licenses/>.

import os
import typing

import pyrogram
from .config import Config
Expand All @@ -27,60 +28,73 @@
from .decorater import *
from .helpers import *
import logging
logging.basicConfig(level=logging.INFO)
__version__ = "0.1.3"
__version__ = "1.1.3"
__copyright__ = "Copyright 2021 Jayant Hegde Kageri <github.com/jayantkageri>"
__license__ = "GNU Lesser General Public License v3 or later (LGPLv3+)"

app = pyrogram.Client(
session_name="pyrogram",
api_id=Config.API_ID,
api_hash=Config.API_HASH,
bot_token=Config.BOT_TOKEN,
plugins={"root": Config.PLUGINS} if Config.PLUGINS else None
)
app.__doc__ = "`~pyrogram.Client`"
client, client.__doc__ = app, app.__doc__

def run():
class tgClient:
"""
### `tgEasy.run()`
- Runs the `pyrogram.Client` by adding `tgEasy.run()` in your main file and run.
### `tgEasy.tgClient`
- A Class for Initialising the tgEasy and it's Methods, Types and Functions
- Parameters:
- client (`pyrogram.Client`):
- The Pyrogram Client
- This calls `pyrogram.Client.start()`, `pyrogram.idle()` and `pyrogram.Client.stop()`
#### Example
.. code-block:: python
from tgEasy import run
from tgEasy import tgClient
from pyrogram import Client
run()
app = tgClient(Client("my_account"))
"""
import logging
print(f"tgEasy v{__version__}, {__copyright__}")
print(f"Licenced under the terms of {__license__}", end='\n\n')
if not Config.LOGS:
logging.warning("Log Group ID is't Set, Please set it else Bot will not able to Send Crash Logs")
logging.info("Starting the pyrogram.Client")
try:
app.start()
app.send_message(Config.LOGS, "pyrogram.Client Started")
except pyrogram.errors.exceptions.bad_request_400.AccessTokenExpired:
raise AccessTokenExpired("[400 ACCESS_TOKEN_EXPIRED]: The bot token has expired, Use Diffrent one or change it to the Correct one")
except pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid:
logging.warning("Interact the Bot to your Log Group Now")
pass
if Config.PLUGINS and not os.path.exists(Config.PLUGINS):
logging.warn(f"There is no directory named {Config.PLUGINS}, tgEasy Quitting")
quit()
logging.info("Started the pyrogram.Client")
logging.info("Idling the pyrogram.Client")
pyrogram.idle()
logging.info("Sending Message before Stopping the pyrogram.Client")
try:
app.send_message(
Config.LOGS, "pyrogram.Client Stopped, If this is UnExpected check Logs")
except pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid:
logging.warning("Unable to Send Message to Log Group, Please Interact Bot with the Log Group while Running")
pass
logging.info("Stopping the pyrogram.Client")
app.stop()
logging.info("Stopped the pyrogram.Client")
__client__ = None
def __init__(
self,
client = pyrogram.Client
):
super().__init__()
self.__client__ = client
tgClient.__client__ = self.__client__
print(f"tgEasy v{__version__}, {__copyright__}")
print(f"Licenced under the terms of {__license__}", end='\n\n')

def run(self):
"""
### `tgEasy.tgClient.run()`
- Runs the `pyrogram.Client` by adding `tgEasy.tgClient.run()` in your main file and run.
- This calls `pyrogram.Client.start()`, `pyrogram.idle()` and `pyrogram.Client.stop()`
#### Example
.. code-block:: python
from tgEasy import tgClient
from pyrogram import Client
app = tgClient(Client)
app.run()
"""
import logging
if not Config.LOGS:
logging.warning("Log Group ID is't Set, Please set it else Bot will not able to Send Crash Logs")
logging.info("Starting the pyrogram.Client")
try:
self.__client__.start()
self.__client__.send_message(Config.LOGS, "pyrogram.Client Started")
except pyrogram.errors.exceptions.bad_request_400.AccessTokenExpired:
raise AccessTokenExpired("[400 ACCESS_TOKEN_EXPIRED]: The bot token has expired, Use Diffrent one or change it to the Correct one")
except pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid:
logging.warning("Interact the Bot to your Log Group Now")
pass
logging.info("Started the pyrogram.Client")
logging.info("Idling the pyrogram.Client")
pyrogram.idle()
logging.info("Sending Message before Stopping the pyrogram.Client")
try:
self.__client__.send_message(
Config.LOGS, "pyrogram.Client Stopped, If this is UnExpected check Logs")
except pyrogram.errors.exceptions.bad_request_400.PeerIdInvalid:
logging.warning("Unable to Send Message to Log Group, Please Interact Bot with the Log Group while Running")
pass
logging.info("Stopping the pyrogram.Client")
self.__client__.stop()
logging.info("Stopped the pyrogram.Client")
5 changes: 3 additions & 2 deletions tgEasy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@
config = Configuration(loaders=[Environment(), EnvFile(filename=env_file)])


class Config(object):
class Config:
"""
Configuratoins of `tgEasy`.
"""
API_ID = config("API_ID")
API_HASH = config("API_HASH")
BOT_TOKEN = config("BOT_TOKEN")
LOGS = config("LOGS")
PLUGINS = config("PLUGINS", None)
PLUGINS = config("PLUGINS", default=None)
HANDLERS = list(config("HANDLER", default="/!"))
73 changes: 19 additions & 54 deletions tgEasy/decorater.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from .config import Config
from .helpers import *

def command(command: typing.Union[str, list], pm_only: typing.Union[bool, bool] = False, group_only: typing.Union[bool, bool] = False, self_admin: typing.Union[bool, bool] = False, filter: typing.Union[pyrogram.filters.Filter, pyrogram.filters.Filter] = None, *args, **kwargs):
def command(command: typing.Union[str, list], pm_only: typing.Union[bool, bool] = False, group_only: typing.Union[bool, bool] = False, self_admin: typing.Union[bool, bool] = False, self_only: typing.Union[bool] = False, filter: typing.Union[pyrogram.filters.Filter, pyrogram.filters.Filter] = None, *args, **kwargs):
"""
### `tgEasy.command`
- A decorater to Register Commands in simple way and manage errors in that Function itself, alternative for `@pyrogram.Client.on_message(pyrogram.filters.command('command'))`
Expand All @@ -37,6 +37,9 @@ def command(command: typing.Union[str, list], pm_only: typing.Union[bool, bool]
- pm_only (bool) **optional**:
- If True, the command will only executed in Private Messages only, By Default False.
- self_only (bool) **optional**:
- If True, the command will only excute if used by Self only, By Default False.
- self_admin (bool) **optional**:
- If True, the command will only executeed if the Bot is Admin in the Chat, By Default False
Expand All @@ -48,16 +51,20 @@ def command(command: typing.Union[str, list], pm_only: typing.Union[bool, bool]
import pyrogram
from tgEasy import command
@command("start", group_only=False, pm_only=False, self_admin=False, pyrogram.filters.chat("777000") and pyrogram.filters.text)
@command("start", group_only=False, pm_only=False, self_admin=False, self_only=False, pyrogram.filters.chat("777000") and pyrogram.filters.text)
async def start(client, message):
await message.reply_text(f"Hello {message.from_user.mention}")
"""
if filter:
filter = pyrogram.filters.command(command, prefixes=list(
"/!")) & ~pyrogram.filters.edited & filter
if self_only:
filter = pyrogram.filters.command(command, prefixes=Config.HANDLERS) & ~pyrogram.filters.edited & filter &filters.me if self_only else pyrogram.filters.command(command, prefixes=Config.HANDLER) & ~pyrogram.filters.edited & filter & pyrogram.filters.me
else:
filter = pyrogram.filters.command(command, prefixes=Config.HANDLERS) & ~pyrogram.filters.edited & filter &filters.me if self_only else pyrogram.filters.command(command, prefixes=Config.HANDLER) & ~pyrogram.filters.edited & filter
else:
filter = pyrogram.filters.command(
command, prefixes=list("/!")) & ~pyrogram.filters.edited
if self_only:
filter = pyrogram.filters.command(command, prefixes=Config.HANDLERS) & ~pyrogram.filters.edited & pyrogram.filters.me
else:
filter = pyrogram.filters.command(command, prefixes=Config.HANDLERS) & ~pyrogram.filters.edited

def wrapper(func):
async def decorator(client, message: pyrogram.types.Message):
Expand All @@ -79,8 +86,7 @@ async def decorator(client, message: pyrogram.types.Message):
await client.leave_chat(message.chat.id)
except BaseException as exception:
return await handle_error(exception, message)
tgEasy.app.add_handler(
pyrogram.handlers.MessageHandler(decorator, filter))
tgEasy.tgClient.__client__.add_handler(pyrogram.handlers.MessageHandler(callback=decorator, filters=filter))
return decorator
return wrapper

Expand Down Expand Up @@ -138,56 +144,11 @@ async def decorator(client, CallbackQuery: pyrogram.types.CallbackQuery):
pass
except BaseException as e:
return await handle_error(e, CallbackQuery)
tgEasy.app.add_handler(
tgEasy.tgClient.__client__.add_handler(
pyrogram.handlers.CallbackQueryHandler(decorator, filter))
return decorator
return wrapper


async def callback_func(func, subFunc2, client, message, permission, *args, **kwargs):
"""
Helper Function for Verifying Anonymous Admin Rights
"""
def callable():
@client.on_callback_query(pyrogram.filters.regex("^confirm.*"))
async def calllback(client, CallbackQuery):
if not await check_rights(CallbackQuery.message.chat.id, CallbackQuery.from_user.id, permission):
try:
await send.edit_text(f"You are Missing the following Rights to use this Command:\n{permission}")

return subFunc2
except pyrogram.exception.forbidden_403.ChatWriteForbidden:
await client.leave_chat(message.chat.id)

return subFunc2
except BaseException as exception:
await handle_error(exception, message)

return subFunc2
try:
await message.delete()
await func(client, message)
return subFunc2
except pyrogram.errors.exception.forbidden_403.ChatWriteForbidden:
await client.leave_chat(message.chat.id)
return subFunc2
except BaseException as exception:
await handle_error(exception, client, message)
return subFunc2
return callable()


async def anonymous(func, subFunc2, client, message, permission, *args, **kwargs):
"""
Helper for Checking the Rights of an Anonymous Admin
"""
send = await message.reply_text(
"It Looks like you are Anonymous Admin, Click the below Button to Confirm your Identity",
reply_markup=tgEasy.ikb([[["Confirm your Identity", "confirm"]]])
)
await callback_func(func, subFunc2, client, message, permission, *args, **kwargs)


def adminsOnly(permission: typing.Union[str, list], TRUST_ANON_ADMINS: typing.Union[bool, bool] = False):
"""
### `tgEasy.adminsOnly`
Expand All @@ -211,6 +172,8 @@ async def start(client, message):
"""
def wrapper(func):
async def decorator(client, message):
if not message.chat.type == "supergroup":
return await message.reply_text("This command can be used in supergroups only.")
if message.sender_chat:
if not TRUST_ANON_ADMINS:
return await message.reply_text(
Expand All @@ -222,6 +185,8 @@ async def decorator(client, message):
return await client.leave_chat(message.chat.id)
except BaseException as exception:
return await handle_error(exception, message)
if not await is_admin(message.chat.id, message.from_user.id):
return await message.reply_text("Only admins can execute this Command!")
if not await check_rights(message.chat.id, message.from_user.id, permission):
return await message.reply_text(f"You are Missing the following Rights to use this Command:\n{permission}")
try:
Expand Down
7 changes: 5 additions & 2 deletions tgEasy/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with tgEasy. If not, see <http://www.gnu.org/licenses/>.

import os
import typing
import pyrogram
import tgEasy


async def get_user(m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery]):
Expand Down Expand Up @@ -240,7 +242,7 @@ async def ban(client, message):
await message.chat.kick_member(user.id)
"""
try:
user = await tgEasy.app.get_chat_member(chat_id, user_id)
user = await tgEasy.tgClient.__client__.get_chat_member(chat_id, user_id)
except:
return False
if user.status == "user":
Expand All @@ -266,6 +268,7 @@ async def ban(client, message):
if rights in permission:
return True
return False
return False

async def is_admin(chat_id: typing.Union[int, str], user_id: typing.Union[int, str]) -> bool:
"""
Expand Down Expand Up @@ -295,7 +298,7 @@ async def ban(client, message):
await message.reply_text("User has been Banned.")
"""
try:
user = await tgEasy.app.get_chat_member(chat_id, user_id)
user = await tgEasy.tgClient.__client__.get_chat_member(chat_id, user_id)
except:
return False
if user.status == "administrator" or user.status == "creator":
Expand Down

0 comments on commit b6db4a0

Please sign in to comment.