Skip to content

Commit

Permalink
update to Pyrogram v2.x.x (UsergeTeam#516)
Browse files Browse the repository at this point in the history
* fix conditions

* update to pyrogram v2

* fixes

* fix conditions

* pep8

* pep8

* Update raw_client.py

* some minor things

Co-authored-by: None <[email protected]>
Co-authored-by: rking32 <[email protected]>
  • Loading branch information
3 people authored Jun 24, 2022
1 parent dd460fc commit 412a274
Show file tree
Hide file tree
Showing 18 changed files with 271 additions and 182 deletions.
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.4.16
pyrogram>=2.0.30
tgcrypto
18 changes: 12 additions & 6 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,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 @@ -237,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", **kwargs)

@property
def ubot(self) -> 'Userge':
Expand All @@ -265,11 +266,12 @@ 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.name = config.SESSION_STRING
self.storage.session_string = config.SESSION_STRING

@property
def dual_mode(self) -> bool:
Expand Down Expand Up @@ -343,7 +345,8 @@ def begin(self, coro: Optional[Awaitable[Any]] = None) -> None:
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()

Expand Down Expand Up @@ -375,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: 18 additions & 18 deletions userge/core/ext/raw_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +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):
if isinstance(data, funcs.account.DeleteAccount) or data.ID == 1099779595:
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 @@ -67,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 @@ -104,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
6 changes: 3 additions & 3 deletions userge/core/methods/chats/send_read_acknowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ 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:
Expand Down
82 changes: 48 additions & 34 deletions userge/core/methods/decorators/raw_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from functools import partial
from typing import List, Dict, Union, Any, Callable, Optional, Awaitable

from pyrogram import StopPropagation, ContinuePropagation
from pyrogram import StopPropagation, ContinuePropagation, enums
from pyrogram.filters import Filter as RawFilter
from pyrogram.types import Message as RawMessage, ChatMember
from pyrogram.errors.exceptions.bad_request_400 import PeerIdInvalid, UserNotParticipant
Expand Down Expand Up @@ -50,10 +50,13 @@ async def _update_u_cht(r_m: RawMessage) -> Optional[ChatMember]:
user = await r_m.chat.get_member(RawClient.USER_ID)
except UserNotParticipant:
return None
user.can_all = None
if user.status == "creator":
user.can_all = True
if user.status in ("creator", "administrator"):
# is this required?
# user.privileges.can_all = None
# if user.status == enums.ChatMemberStatus.OWNER:
# user.privileges.can_all = True
if user.status in (
enums.ChatMemberStatus.OWNER,
enums.ChatMemberStatus.ADMINISTRATOR):
_U_AD_CHT[r_m.chat.id] = user
else:
_U_NM_CHT[r_m.chat.id] = user
Expand All @@ -70,7 +73,7 @@ async def _update_b_cht(r_m: RawMessage) -> Optional[ChatMember]:
bot = await r_m.chat.get_member(RawClient.BOT_ID)
except UserNotParticipant:
return None
if bot.status == "administrator":
if bot.status == enums.ChatMemberStatus.ADMINISTRATOR:
_B_AD_CHT[r_m.chat.id] = bot
else:
_B_NM_CHT[r_m.chat.id] = bot
Expand Down Expand Up @@ -101,14 +104,14 @@ async def _init(r_m: RawMessage) -> None:
async def _raise_func(r_c: Union['_client.Userge', '_client.UsergeBot'],
r_m: RawMessage, text: str) -> None:
# pylint: disable=protected-access
if r_m.chat.type in ("private", "bot"):
if r_m.chat.type in (enums.ChatType.PRIVATE, enums.ChatType.BOT):
await r_m.reply(f"< **ERROR**: {text} ! >")
else:
await r_c._channel.log(f"{text}\nCaused By: [link]({r_m.link})", "ERROR")


async def _is_admin(r_m: RawMessage, is_bot: bool) -> bool:
if r_m.chat.type in ("private", "bot"):
if r_m.chat.type in (enums.ChatType.PRIVATE, enums.ChatType.BOT):
return False
if round(time.time() - _TASK_1_START_TO) > 10:
_clear_cht()
Expand All @@ -120,7 +123,7 @@ async def _is_admin(r_m: RawMessage, is_bot: bool) -> bool:


def _get_chat_member(r_m: RawMessage, is_bot: bool) -> Optional[ChatMember]:
if r_m.chat.type in ("private", "bot"):
if r_m.chat.type in (enums.ChatType.PRIVATE, enums.ChatType.BOT):
return None
if is_bot:
if r_m.chat.id in _B_AD_CHT:
Expand Down Expand Up @@ -179,26 +182,28 @@ async def _both_have_perm(flt: Union['types.raw.Command', 'types.raw.Filter'],
return False
if user is None or bot is None:
return False

if flt.check_change_info_perm and not (
(user.can_all or user.can_change_info) and bot.can_change_info):
(user.privileges and bot.privileges) and (
user.privileges.can_change_info and bot.privileges.can_change_info)):
return False
if flt.check_edit_perm and not (
(user.can_all or user.can_edit_messages) and bot.can_edit_messages):
if flt.check_edit_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_edit_messages and bot.privileges.can_edit_messages)):
return False
if flt.check_delete_perm and not (
(user.can_all or user.can_delete_messages) and bot.can_delete_messages):
if flt.check_delete_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_delete_messages and bot.privileges.can_delete_messages)):
return False
if flt.check_restrict_perm and not (
(user.can_all or user.can_restrict_members) and bot.can_restrict_members):
if flt.check_restrict_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_restrict_members and bot.privileges.can_restrict_members)):
return False
if flt.check_promote_perm and not (
(user.can_all or user.can_promote_members) and bot.can_promote_members):
if flt.check_promote_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_promote_members and bot.privileges.can_promote_members)):
return False
if flt.check_invite_perm and not (
(user.can_all or user.can_invite_users) and bot.can_invite_users):
if flt.check_invite_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_invite_users and bot.privileges.can_invite_users)):
return False
if flt.check_pin_perm and not (
(user.can_all or user.can_pin_messages) and bot.can_pin_messages):
if flt.check_pin_perm and not ((user.privileges and bot.privileges) and (
user.privileges.can_pin_messages and bot.privileges.can_pin_messages)):
return False
return True

Expand Down Expand Up @@ -233,7 +238,8 @@ def on_filters(self, filters: RawFilter, group: int = 0,
""" abstract on filter method """

def _build_decorator(self,
flt: Union['types.raw.Command', 'types.raw.Filter'],
flt: Union['types.raw.Command',
'types.raw.Filter'],
**kwargs: Union[str, bool]) -> 'RawDecorator._PYRORETTYPE':
def decorator(func: _PYROFUNC) -> _PYROFUNC:
async def template(r_c: Union['_client.Userge', '_client.UsergeBot'],
Expand All @@ -251,7 +257,7 @@ async def template(r_c: Union['_client.Userge', '_client.UsergeBot'],
_raise = partial(_raise_func, r_c, r_m)
if r_m.chat and r_m.chat.type not in flt.scope:
if isinstance(flt, types.raw.Command):
await _raise(f"`invalid chat type [{r_m.chat.type}]`")
await _raise(f"`invalid chat type [{r_m.chat.type.name}]`")
return
is_bot = r_c.is_bot
if r_m.chat and flt.only_admins and not await _is_admin(r_m, is_bot):
Expand All @@ -263,40 +269,47 @@ async def template(r_c: Union['_client.Userge', '_client.UsergeBot'],
c_m = _get_chat_member(r_m, is_bot)
if not c_m:
if isinstance(flt, types.raw.Command):
await _raise(f"`invalid chat type [{r_m.chat.type}]`")
await _raise(f"`invalid chat type [{r_m.chat.type.name}]`")
return
if c_m.status != "creator":
if flt.check_change_info_perm and not c_m.can_change_info:
if c_m.status != enums.ChatMemberStatus.OWNER:
if flt.check_change_info_perm and not (
c_m.privileges and c_m.privileges.can_change_info):
if isinstance(flt, types.raw.Command):
await _raise("`required permission [change_info]`")
return
if flt.check_edit_perm and not c_m.can_edit_messages:
if flt.check_edit_perm and not (
c_m.privileges and c_m.privileges.can_edit_messages):
if isinstance(flt, types.raw.Command):
await _raise("`required permission [edit_messages]`")
return
if flt.check_delete_perm and not c_m.can_delete_messages:
if flt.check_delete_perm and not (
c_m.privileges and c_m.privileges.can_delete_messages):
if isinstance(flt, types.raw.Command):
await _raise("`required permission [delete_messages]`")
return
if flt.check_restrict_perm and not c_m.can_restrict_members:
if flt.check_restrict_perm and not (
c_m.privileges and c_m.privileges.can_restrict_members):
if isinstance(flt, types.raw.Command):
if is_admin:
await _raise("`required permission [restrict_members]`")
else:
await _raise("`chat admin required`")
return
if flt.check_promote_perm and not c_m.can_promote_members:
if flt.check_promote_perm and not (
c_m.privileges and c_m.privileges.can_promote_members):
if isinstance(flt, types.raw.Command):
if is_admin:
await _raise("`required permission [promote_members]`")
else:
await _raise("`chat admin required`")
return
if flt.check_invite_perm and not c_m.can_invite_users:
if flt.check_invite_perm and not (
c_m.privileges and c_m.privileges.can_invite_users):
if isinstance(flt, types.raw.Command):
await _raise("`required permission [invite_users]`")
return
if flt.check_pin_perm and not c_m.can_pin_messages:
if flt.check_pin_perm and not (
c_m.privileges and c_m.privileges.can_pin_messages):
if isinstance(flt, types.raw.Command):
await _raise("`required permission [pin_messages]`")
return
Expand All @@ -320,7 +333,8 @@ async def template(r_c: Union['_client.Userge', '_client.UsergeBot'],
r_c, _client.Userge):
return

if flt.check_downpath and not os.path.isdir(config.Dynamic.DOWN_PATH):
if flt.check_downpath and not os.path.isdir(
config.Dynamic.DOWN_PATH):
os.makedirs(config.Dynamic.DOWN_PATH)

try:
Expand Down
5 changes: 3 additions & 2 deletions userge/core/methods/messages/edit_message_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import asyncio
from typing import Optional, Union, List

from pyrogram import enums
from pyrogram.types import InlineKeyboardMarkup, MessageEntity

from userge import config
Expand All @@ -28,7 +29,7 @@ async def edit_message_text(self, # pylint: disable=arguments-differ
text: str,
del_in: int = -1,
log: Union[bool, str] = False,
parse_mode: Union[str, object] = object,
parse_mode: Optional[enums.ParseMode] = None,
entities: List[MessageEntity] = None,
disable_web_page_preview: Optional[bool] = None,
reply_markup: InlineKeyboardMarkup = None
Expand Down Expand Up @@ -58,7 +59,7 @@ async def edit_message_text(self, # pylint: disable=arguments-differ
to the log channel.
If ``str``, the logger name will be updated.
parse_mode (``str``, *optional*):
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using
both Markdown and HTML styles.
You can combine both syntaxes together.
Expand Down
Loading

0 comments on commit 412a274

Please sign in to comment.