Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def add_object(self, tlobject, replace=False):
"""Adds a Telegram object (TLObject) to its corresponding table"""
if isinstance(tlobject, Message): # Adding a message
self.add_message(tlobject, replace=replace)
elif isinstance(tlobject, MessageService): # Adding a message service
self.add_message_service(tlobject, replace=replace)
elif isinstance(tlobject, User): # Adding an user
self.add_user(tlobject, replace=replace)
elif isinstance(tlobject, UserEmpty): # Adding an empty user
self.add_user(tlobject, replace=replace)
elif isinstance(tlobject, Chat): # Adding a chat
self.add_chat(tlobject, replace=replace)
elif isinstance(tlobject, ChatEmpty): # Adding an empty chat
self.add_chat(tlobject, replace=replace)
elif isinstance(tlobject, ChatForbidden): # Adding a forbidden chat
self.add_chat(tlobject, replace=replace)
elif isinstance(tlobject, Channel): # Adding a channel
self.add_channel(tlobject, replace=replace)
elif isinstance(tlobject, ChannelForbidden): # Adding a forbidden channel
self.add_channel(tlobject, replace=replace)
else:
def convert_user(sql_tuple):
"""Converts an sql tuple back to an user TLObject"""
return User(id=sql_tuple[0],
access_hash=sql_tuple[1],
is_self=sql_tuple[2],
contact=sql_tuple[3],
mutual_contact=sql_tuple[4],
deleted=sql_tuple[5],
bot=sql_tuple[6],
first_name=sql_tuple[7],
last_name=sql_tuple[8],
username=sql_tuple[9],
phone=sql_tuple[10],
photo=TLDatabase.convert_object(sql_tuple[11]))
def enqueue_entities(self, entities):
"""
Enqueues the given iterable of entities to be dumped later by a
different coroutine. These in turn might enqueue profile photos.
"""
for entity in entities:
eid = utils.get_peer_id(entity)
self._displays[eid] = utils.get_display_name(entity)
if isinstance(entity, types.User):
if entity.deleted or entity.min:
continue # Empty name would cause IntegrityError
elif isinstance(entity, types.Channel):
if entity.left:
continue # Getting full info triggers ChannelPrivateError
elif not isinstance(entity, (types.Chat,
types.InputPeerUser,
types.InputPeerChat,
types.InputPeerChannel)):
# Drop UserEmpty, ChatEmpty, ChatForbidden and ChannelForbidden
continue
if eid in self._checked_entity_ids:
continue
else:
self._checked_entity_ids.add(eid)
text += await misc.resolve_channel(event.client, result)
elif isinstance(chat, types.Chat):
result = await client(
functions.messages.GetFullChatRequest(
chat_id=chat
)
)
text += await misc.resolve_chat(event.client, result)
break
else:
try:
chat = await client.get_entity(valid)
except (TypeError, ValueError):
continue
if isinstance(chat, types.User):
text = f"**ID:** `{chat.id}`"
if chat.username:
text += f"\n**Username:** @{chat.username}"
text += f"\n{await get_chat_link(chat)}"
if isinstance(chat, types.ChatForbidden):
text += f"\n`Not allowed to view {chat.title}.`"
elif isinstance(chat, types.ChatEmpty):
text += "\n`The chat is empty.`"
elif isinstance(chat, types.Chat):
text = f"**Chat:** @{valid}"
result = await client(
functions.messages.GetFullChatRequest(
chat_id=chat
)
)
async def get_entity_from_msg(event: NewMessage.Event) -> Tuple[
Union[None, types.User], Union[None, bool, str], Union[None, bool, str]
]:
"""Get a User entity and/or a reason from the event's regex pattern"""
exception = False
entity = None
match = event.matches[0].group(1)
# TODO: Find better logic to differentiate user and reason
pattern = re.compile(r"(@?\w+|\d+)(?: |$)(.*)")
user = pattern.match(match).group(1) if match else None
extra = pattern.match(match).group(2) if match else None
reply = await event.get_reply_message()
if reply and not (user and extra):
user = reply.from_id
extra = match.strip()
def add_user(self, user, replace=False):
"""Adds an user TLObject to its table"""
c = self.con.cursor()
if replace:
query = 'insert or replace into users values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
else:
query = 'insert into users values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
if isinstance(user, User):
c.execute(query,
(user.id,
user.access_hash,
user.is_self,
user.contact,
user.mutual_contact,
user.deleted,
user.bot,
user.first_name,
user.last_name,
user.username,
user.phone,
self.adapt_object(user.photo)))
elif isinstance(user, UserEmpty):
c.execute(query, (user.id,
None, None, None, None, None, None, None, None, None, None, None))
def verifyLoggerGroup(client: UserBotClient) -> None:
client.logger = True
def disable_logger(error: str):
if LOGGER_CHAT_ID != 0:
LOGGER.error(error)
client.logger = False
try:
entity = client.loop.run_until_complete(
client.get_entity(LOGGER_CHAT_ID)
)
if not isinstance(entity, types.User):
if not entity.creator:
if entity.default_banned_rights.send_messages:
disable_logger(
"Permissions missing to send messages "
"for the specified Logger group."
)
client.logger = entity
except ValueError:
disable_logger(
"Logger group ID cannot be found. "
"Make sure it's correct."
)
except TypeError:
disable_logger(
"Logger group ID is unsupported. "
"Make sure it's correct."
async def get_users(event: NewMessage.Event) -> types.User or None:
match = event.matches[0].group(1)
users = []
if match:
matches, _ = await client.parse_arguments(match)
for match in matches:
try:
entity = await client.get_entity(match)
if isinstance(entity, types.User):
users.append(entity)
except (TypeError, ValueError):
pass
elif event.is_private and event.out:
users = [await event.get_chat()]
elif event.reply_to_msg_id:
reply = await event.get_reply_message()
users = [await reply.get_sender()]
return users
async def get_chat_link(
arg: Union[types.User, types.Chat, types.Channel, NewMessage.Event],
reply=None
) -> str:
if isinstance(arg, (types.User, types.Chat, types.Channel)):
entity = arg
else:
entity = await arg.get_chat()
if isinstance(entity, types.User):
if entity.is_self:
name = "yourself"
else:
name = get_display_name(entity) or "Deleted Account?"
extra = f"[{name}](tg://user?id={entity.id})"
else:
if hasattr(entity, 'username') and entity.username is not None:
username = '@' + entity.username
else:
username = entity.id
if reply is not None:
skipped = []
text = ''
log = ''
if match:
args, _ = await client.parse_arguments(match)
for user in args:
if user in whitelistedUsers:
users.append(user)
continue
elif user in whitelistedChats:
chats.append(user)
continue
try:
entity = await client.get_entity(user)
if isinstance(entity, types.User):
if not entity.is_self:
users.append(entity.id)
else:
chats.append(entity.id)
except Exception:
skipped.append(f"`{user}`")
else:
if event.reply_to_msg_id:
entity = (await event.get_reply_message()).from_id
users.append(entity)
else:
entity = await event.get_chat()
if event.is_private:
users.append(entity.id)
else:
chats.append(entity.id)