Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pull] beta from UsergeTeam:beta #38

Open
wants to merge 67 commits into
base: beta
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
a114018
add heroku restart method if hard restart + update loader version (#485)
Krishna-Singhal Feb 28, 2022
5f0be4d
separate cmd for heroku restart + bug fixes
rking32 Mar 1, 2022
d4fd6ed
better branches
rking32 Mar 1, 2022
b21281c
Add optional flag `-i` in help (#486)
AsmSafone Mar 2, 2022
f148620
improve humanbytes
SpEcHiDe Mar 3, 2022
950fe26
improve help
rking32 Mar 3, 2022
347c4a2
better loader responses
rking32 Mar 3, 2022
c7840a3
remove logging from `get_custom_import_re` (#489)
Krishna-Singhal Mar 3, 2022
e4e2eba
Added more units in `humanbytes` 😜 (#488)
jigarvarma2k20 Mar 4, 2022
19c0027
add arg to get_custom_import_re
SpEcHiDe Mar 4, 2022
93dcc5f
improve loading and reloading plugins
rking32 Mar 4, 2022
62dfb80
return None explicitly (deepsource)
rking32 Mar 4, 2022
fe7a3bd
log successful and exiting msgs
rking32 Mar 4, 2022
f26ebfe
minor things
rking32 Mar 4, 2022
cbe17a2
don't allow edited msgs anymore
rking32 Mar 5, 2022
e6ea24d
minimum pyrogram V1.4.8 (#490)
jigarvarma2k20 Mar 5, 2022
931c242
min loader to 2.9
rking32 Mar 5, 2022
118b324
Update Userge to v1.0.0
rking32 Mar 5, 2022
f78417b
next lvl security for secured envs + introducing secured strings
rking32 Mar 9, 2022
5cabba1
ignore these things
rking32 Mar 10, 2022
a37014c
improved secured string
rking32 Mar 10, 2022
3b2a64c
better help + search plugins by adding -p flag in .s
rking32 Mar 10, 2022
a3cb1ce
further improved secured strings
rking32 Mar 10, 2022
adca6e2
fix not working with user session
rking32 Mar 11, 2022
fccb79b
better crash handling + improved start, stop, reload time
rking32 Mar 11, 2022
ec567c4
minor improvements
rking32 Mar 11, 2022
18bb3b9
fix unpack requires a buffer of 267 bytes (video_chat)
rking32 Mar 11, 2022
0671003
less spam help + option to get loader logs (help logs)
rking32 Mar 15, 2022
603deb4
min loader to 3.7
rking32 Mar 15, 2022
7478843
min loader to 3.8 (#494)
Krishna-Singhal Mar 15, 2022
579b0e2
moved secret msg to plugins
rking32 Mar 17, 2022
25dc432
disable link preview while logging to channel
rking32 Mar 19, 2022
71480fd
option to only fetch one plugins repo (help repos)
rking32 Mar 19, 2022
122e4b8
some minor things
rking32 Mar 19, 2022
e8ed65e
update pyro to 1.4.9
rking32 Mar 20, 2022
8a09360
Bump Pyrogram from 1.4.9 to 1.4.15 (#499)
Krishna-Singhal Apr 23, 2022
d640afa
Removed hide_via parameter (#501)
AlbertEinsteinTG Apr 23, 2022
1965fc2
yft (#502)
SpEcHiDe Apr 23, 2022
36ee728
Freeze pyrogram at least stable version (#507)
Harsh-br0 Apr 28, 2022
e1a6b21
Patch DeleteAccount (#497)
Krishna-Singhal Apr 28, 2022
71c17c6
Userge New Logo (#503)
Apr 30, 2022
dd8b938
Update README.md (#508)
SpEcHiDe Apr 30, 2022
f1244fa
Add support to eval from .py and .txt file (#498)
jigarvarma2k20 Apr 30, 2022
bc8dc83
disable link preview (eval)
rking32 Apr 30, 2022
5ed8140
cached secured env and closes #500
rking32 Apr 30, 2022
bb2c77c
Update __main__.py (#509)
jigarvarma2k20 May 8, 2022
73c12a0
New Logo (#510)
May 11, 2022
748e9cb
fix typo in delvar (#511)
Krishna-Singhal May 13, 2022
dd460fc
fix eval text file conditions (#515)
subinps Jun 16, 2022
412a274
update to Pyrogram v2.x.x (#516)
subinps Jun 24, 2022
380c5a5
min loader to v4.5
rking32 Jun 24, 2022
88aeea0
min loader to v4.6
rking32 Jun 24, 2022
0544ab0
some minor fixes (conversation things)
rking32 Jun 26, 2022
d25e8fb
fixed 'Message' object has no attribute '_client' while deleting msgs…
rking32 Jul 1, 2022
394afc3
fixed maximum recursion depth while parsing msg
rking32 Jul 3, 2022
91ad610
Remove duplicate line😅 (#519)
jigarvarma2k20 Jul 7, 2022
5e561df
Fix deepsource (#520)
jigarvarma2k20 Jul 12, 2022
32acbee
Fix typo (#523)
cclauss Jul 22, 2022
624ecf4
Delete multiple sudo cmds from sudo at once (#527)
jigarvarma2k20 Aug 7, 2022
b888849
fix deleting sudo cmds (#530)
adi-code22 Aug 9, 2022
4e77aae
add syntax highlighting (#532)
subinps Oct 17, 2022
ae2ea9c
Fix deepsource [`consider-using-f-string`] (#531)
jigarvarma2k20 Oct 17, 2022
2d8e037
min loader to 5.0
rking32 Oct 28, 2022
c485f69
Fix deepsource (#533)
Krishna-Singhal Oct 30, 2022
4404c84
Avoid caching on edit timeout (#534)
Harsh-br0 Nov 27, 2022
dd651fd
freeze pyro version
rking32 Dec 5, 2022
3d883ec
Make bash as default shell on Linux (#537)
Harsh-br0 Apr 3, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,4 @@ logs/
./loader/
userge/plugins/dev/
.rcache
test.py
test.py
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<p align="center">
<a href="https://github.com/UsergeTeam/Userge">
<img src="resources/userge.png" alt="Userge">
<img src="https://telegra.ph/file/f3aed2f6f2d4a1ad7831d.png" alt="Userge">
</a>
<br>
<b>Pluggable Telegram UserBot</b>
Expand Down Expand Up @@ -49,9 +49,9 @@

> Special Thanks to all of you !!!.

## [Documentation](http://theuserge.tech) 📘
## [Documentation](https://theuserge.github.io) 📘

## [Deployment](http://theuserge.tech/deployment) 👷
## [Deployment](https://theuserge.github.io/deployment) 👷

## [Plugins](https://github.com/UsergeTeam/Userge-Plugins) 🔌

Expand Down
2 changes: 1 addition & 1 deletion min_loader.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5
5.0
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
dnspython
heroku3
motor
pyrogram>=1.3.6
pyrogram==2.0.58
tgcrypto
Binary file modified resources/userge.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions userge/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# All rights reserved.

from userge.logger import logging # noqa
from userge import config # noqa
from userge.core import ( # noqa
Userge, filters, Message, get_collection, pool)

Expand Down
16 changes: 10 additions & 6 deletions userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@
import heroku3

from userge import logging
from .sys_tools import secured_env, secured_str

_LOG = logging.getLogger(__name__)

API_ID = int(environ.get("API_ID"))
API_HASH = environ.get("API_HASH")
BOT_TOKEN = environ.get("BOT_TOKEN")
SESSION_STRING = environ.get("SESSION_STRING")
DB_URI = environ.get("DATABASE_URL")
# try to get this value using eval :)
TEST = secured_str("nice! report @UsergeSpam")

API_ID = environ.get("API_ID")
API_HASH = secured_env("API_HASH")
BOT_TOKEN = secured_env("BOT_TOKEN")
SESSION_STRING = secured_env("SESSION_STRING")
DB_URI = secured_env("DATABASE_URL")

OWNER_ID = tuple(filter(lambda x: x, map(int, environ.get("OWNER_ID", "0").split())))
LOG_CHANNEL_ID = int(environ.get("LOG_CHANNEL_ID"))
Expand All @@ -36,7 +40,7 @@
FINISHED_PROGRESS_STR = environ.get("FINISHED_PROGRESS_STR")
UNFINISHED_PROGRESS_STR = environ.get("UNFINISHED_PROGRESS_STR")

HEROKU_API_KEY = environ.get("HEROKU_API_KEY")
HEROKU_API_KEY = secured_env("HEROKU_API_KEY")
HEROKU_APP_NAME = environ.get("HEROKU_APP_NAME")
HEROKU_APP = heroku3.from_key(HEROKU_API_KEY).apps()[HEROKU_APP_NAME] \
if HEROKU_API_KEY and HEROKU_APP_NAME else None
Expand Down
68 changes: 56 additions & 12 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,21 @@ def init(self) -> Optional[ModuleType]:

return self._init

def main(self) -> None:
def main(self) -> Optional[ModuleType]:
self._main = _import_module(self._path + ".__main__")

return self._main

def reload_init(self) -> Optional[ModuleType]:
self._init = _reload_module(self._init)

return self._init

def reload_main(self) -> None:
def reload_main(self) -> Optional[ModuleType]:
self._main = _reload_module(self._main)

return self._main


_MODULES: List[_Module] = []
_START_TIME = time.time()
Expand Down Expand Up @@ -122,7 +126,7 @@ async def _wait_for_instance() -> None:
break


class _AbstractUserge(Methods, RawClient):
class _AbstractUserge(Methods):
def __init__(self, **kwargs) -> None:
self._me: Optional[types.User] = None
super().__init__(**kwargs)
Expand Down Expand Up @@ -170,8 +174,10 @@ async def _load_plugins(self) -> None:
_MODULES.append(mdl)
self.manager.update_plugin(mt.__name__, mt.__doc__)

for mdl in _MODULES:
mdl.main()
for mdl in tuple(_MODULES):
if not mdl.main():
self.manager.remove(mdl.name)
_MODULES.remove(mdl)

await self.manager.init()
_LOG.info(f"Imported ({len(_MODULES)}) Plugins => "
Expand All @@ -192,8 +198,10 @@ async def reload_plugins(self) -> int:
reloaded.append(mdl)
self.manager.update_plugin(mt.__name__, mt.__doc__)

for mdl in reloaded:
mdl.reload_main()
for mdl in tuple(reloaded):
if not mdl.reload_main():
self.manager.remove(mdl.name)
reloaded.remove(mdl)

await self.manager.init()
await self.manager.start()
Expand Down Expand Up @@ -229,8 +237,9 @@ def __hash__(self) -> int: # pylint: disable=W0235

class UsergeBot(_AbstractUserge):
""" UsergeBot, the bot """

def __init__(self, **kwargs) -> None:
super().__init__(session_name=":memory:", **kwargs)
super().__init__(name="usergeBot", in_memory=True, **kwargs)

@property
def ubot(self) -> 'Userge':
Expand All @@ -243,7 +252,7 @@ class Userge(_AbstractUserge):

has_bot = bool(config.BOT_TOKEN)

def __init__(self, **kwargs) -> None:
def __init__(self) -> None:
kwargs = {
'api_id': config.API_ID,
'api_hash': config.API_HASH,
Expand All @@ -257,9 +266,13 @@ def __init__(self, **kwargs) -> None:
RawClient.DUAL_MODE = True
kwargs['bot'] = UsergeBot(bot=self, **kwargs)

kwargs['session_name'] = config.SESSION_STRING or ":memory:"
kwargs['name'] = 'userge'
kwargs['session_string'] = config.SESSION_STRING or None
super().__init__(**kwargs)

if config.SESSION_STRING:
self.storage.session_string = config.SESSION_STRING

@property
def dual_mode(self) -> bool:
return RawClient.DUAL_MODE
Expand Down Expand Up @@ -302,6 +315,17 @@ async def stop(self, **_) -> None:

await _set_running(False)

def _get_log_client(self) -> _AbstractUserge:
return self.bot if self.has_bot else self

async def _log_success(self) -> None:
# pylint: disable=protected-access
await self._get_log_client()._channel.log("<pre>Userge started successfully</pre>")

async def _log_exit(self) -> None:
# pylint: disable=protected-access
await self._get_log_client()._channel.log("<pre>\nExiting Userge ...</pre>")

def begin(self, coro: Optional[Awaitable[Any]] = None) -> None:
""" start userge """
try:
Expand All @@ -310,9 +334,20 @@ def begin(self, coro: Optional[Awaitable[Any]] = None) -> None:
return

idle_event = asyncio.Event()
log_errored = False

try:
self.loop.run_until_complete(self._log_success())
except Exception as i_e:
_LOG.exception(i_e)

idle_event.set()
log_errored = True

def _handle(num, _) -> None:
_LOG.info(f"Received Stop Signal [{signal.Signals(num).name}], Exiting Userge ...")
_LOG.info(
f"Received Stop Signal [{signal.Signals(num).name}], Exiting Userge ...")

idle_event.set()

for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGINT):
Expand All @@ -328,6 +363,12 @@ def _handle(num, _) -> None:
_LOG.info(f"Idling Userge - {mode}")
self.loop.run_until_complete(idle_event.wait())

if not log_errored:
try:
self.loop.run_until_complete(self._log_exit())
except Exception as i_e:
_LOG.exception(i_e)

with suppress(RuntimeError):
self.loop.run_until_complete(self.stop())
self.loop.run_until_complete(self.manager.exit())
Expand All @@ -337,7 +378,10 @@ def _handle(num, _) -> None:
t.cancel()

with suppress(RuntimeError):
self.loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))
self.loop.run_until_complete(
asyncio.gather(
*to_cancel,
return_exceptions=True))
self.loop.run_until_complete(self.loop.shutdown_asyncgens())

self.loop.stop()
Expand Down
36 changes: 19 additions & 17 deletions userge/core/ext/raw_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,23 @@ def __init__(self, bot: Optional['userge.core.client.UsergeBot'] = None, **kwarg
self._channel = userge.core.types.new.ChannelLogger(self, "CORE")
userge.core.types.new.Conversation.init(self)

async def send(self, data: TLObject, retries: int = Session.MAX_RETRIES,
timeout: float = Session.WAIT_TIMEOUT, sleep_threshold: float = None):
async def invoke(self, query: TLObject, retries: int = Session.MAX_RETRIES,
timeout: float = Session.WAIT_TIMEOUT, sleep_threshold: float = None):
if isinstance(query, funcs.account.DeleteAccount) or query.ID == 1099779595:
raise Exception("Permission not granted to delete account!")
key = 0
if isinstance(data, (funcs.messages.SendMessage,
funcs.messages.SendMedia,
funcs.messages.SendMultiMedia,
funcs.messages.EditMessage,
funcs.messages.ForwardMessages)):
if isinstance(data, funcs.messages.ForwardMessages):
tmp = data.to_peer
if isinstance(query, (funcs.messages.SendMessage,
funcs.messages.SendMedia,
funcs.messages.SendMultiMedia,
funcs.messages.EditMessage,
funcs.messages.ForwardMessages)):
if isinstance(query, funcs.messages.ForwardMessages):
tmp = query.to_peer
else:
tmp = data.peer
if isinstance(data, funcs.messages.SendMedia) and isinstance(
data.media, (types.InputMediaUploadedDocument,
types.InputMediaUploadedPhoto)):
tmp = query.peer
if isinstance(query, funcs.messages.SendMedia) and isinstance(
query.media, (types.InputMediaUploadedDocument,
types.InputMediaUploadedPhoto)):
tmp = None
if tmp:
if isinstance(tmp, (types.InputPeerChannel, types.InputPeerChannelFromMessage)):
Expand All @@ -65,9 +67,9 @@ async def send(self, data: TLObject, retries: int = Session.MAX_RETRIES,
key = int(tmp.chat_id)
elif isinstance(tmp, (types.InputPeerUser, types.InputPeerUserFromMessage)):
key = int(tmp.user_id)
elif isinstance(data, funcs.channels.DeleteMessages) and isinstance(
data.channel, (types.InputChannel, types.InputChannelFromMessage)):
key = int(data.channel.channel_id)
elif isinstance(query, funcs.channels.DeleteMessages) and isinstance(
query.channel, (types.InputChannel, types.InputChannelFromMessage)):
key = int(query.channel.channel_id)
if key:
async with self.REQ_LOCK:
try:
Expand Down Expand Up @@ -102,7 +104,7 @@ async def send(self, data: TLObject, retries: int = Session.MAX_RETRIES,
sleep(1)
now += 1
req.add(now)
return await super().send(data, retries, timeout, sleep_threshold)
return await super().invoke(query, retries, timeout, sleep_threshold)


class ChatReq:
Expand Down
8 changes: 4 additions & 4 deletions userge/core/methods/chats/send_read_acknowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,17 @@ async def send_read_acknowledge(self,
if max_id is None:
if message:
if isinstance(message, list):
max_id = max(msg.message_id for msg in message)
max_id = max(msg.id for msg in message)
else:
max_id = message.message_id
max_id = message.id
else:
max_id = 0
if clear_mentions:
await self.send(
await self.invoke(
functions.messages.ReadMentions(
peer=await self.resolve_peer(chat_id)))
if max_id is None:
return True
if max_id is not None:
return bool(await self.read_history(chat_id=chat_id, max_id=max_id))
return bool(await self.read_chat_history(chat_id=chat_id, max_id=max_id))
return False
Loading