Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
#haste: Replaces the message you reply to with a hastebin link.
"""
await event.delete()
if not event.reply_to_msg_id:
return
msg = await event.get_reply_message()
if len(msg.raw_text or '') < 200:
return
sent = await event.respond(
'Uploading paste…', reply_to=msg.reply_to_msg_id)
name = html.escape(
utils.get_display_name(await msg.get_sender()) or 'A user')
text = msg.raw_text
code = ''
for _, string in msg.get_entities_text((
types.MessageEntityCode, types.MessageEntityPre)):
code += f'{string}\n'
text = text.replace(string, '')
code = code.rstrip()
if code:
text = re.sub(r'\s+', ' ', text)
else:
code = msg.raw_text
text = ''
async with aiohttp.ClientSession() as session:
def mention_user(user: tg.types.User) -> str:
"""Returns a string that mentions the given user, regardless of whether they have a username."""
if user.username:
# Use username mention if possible
name = f"@{user.username}"
else:
# Use the first and last name otherwise
name = tg.utils.get_display_name(user)
if not name:
# Deleted accounts have no name; behave like the official clients
name = "Deleted Account"
return f"[{name}](tg://user?id={user.id})"
async def download_past_media(self, dumper, target_id):
"""
Downloads the past media that has already been dumped into the
database but has not been downloaded for the given target ID yet.
Media which formatted filename results in an already-existing file
will be *ignored* and not re-downloaded again.
"""
# TODO Should this respect and download only allowed media? Or all?
target_in = await self.client.get_input_entity(target_id)
target = await self.client.get_entity(target_in)
target_id = utils.get_peer_id(target)
bar = tqdm.tqdm(unit='B', desc='media', unit_divisor=1000,
unit_scale=True, bar_format=BAR_FORMAT, total=0,
postfix={'chat': utils.get_display_name(target)})
msg_cursor = dumper.conn.cursor()
msg_cursor.execute('SELECT ID, Date, FromID, MediaID FROM Message '
'WHERE ContextID = ? AND MediaID IS NOT NULL',
(target_id,))
msg_row = msg_cursor.fetchone()
while msg_row:
await self._download_media(
media_id=msg_row[3],
context_id=target_id,
sender_id=msg_row[2],
date=datetime.datetime.utcfromtimestamp(msg_row[1]),
bar=bar
)
msg_row = msg_cursor.fetchone()
self.entity = kwargs.pop('entity')
# Initialize the frame
kwargs['borderwidth'] = 2
kwargs['relief'] = 'ridge'
super().__init__(master, **kwargs)
# Set up our custom widget
self.profile_picture = Label(self)
self.profile_picture.grid(row=0, column=0, sticky=NSEW)
self.right_column = Frame(self, padding=(16, 0))
self.right_column.grid(row=0, column=1)
self.name_label = Label(self.right_column,
text=sanitize_string(get_display_name(self.entity)),
font='-weight bold -size 14')
self.name_label.grid(row=0, sticky=NW)
if hasattr(self.entity, 'username'):
self.username_label = Label(self.right_column,
text='@{}'.format(self.entity.username),
font='-size 12')
self.username_label.grid(row=1, sticky=NW)
if hasattr(self.entity, 'phone'):
self.phone_label = Label(self.right_column,
text='+{}'.format(self.entity.phone))
self.phone_label.grid(row=2, sticky=NW)
elif hasattr(self.entity, 'participants_count'):
self.participants_label = Label(self.right_column,
def profile_check_invite(user: tg.types.User) -> bool:
# Some spammers have Telegram invite links in their first or last names
return "t.me/" in tg.utils.get_display_name(user)
# is not `min`, because its `access_hash` cannot be used
# anywhere (since layer 102, there are two access hashes).
return
if isinstance(p, (InputPeerUser, InputPeerChannel)):
p_hash = p.access_hash
elif isinstance(p, InputPeerChat):
p_hash = 0
else:
return
username = getattr(e, 'username', None) or None
if username is not None:
username = username.lower()
phone = getattr(e, 'phone', None)
name = utils.get_display_name(e) or None
return self._entity_values_to_row(
marked_id, p_hash, username, phone, name
)
def set_signed_in(self, me):
"""
Configures the application as "signed in" (displays user's
name and disables the entry to input phone/bot token/code).
"""
self.me = me
self.sign_in_label.configure(text='Signed in')
self.sign_in_entry.configure(state=tkinter.NORMAL)
self.sign_in_entry.delete(0, tkinter.END)
self.sign_in_entry.insert(tkinter.INSERT, utils.get_display_name(me))
self.sign_in_entry.configure(state=tkinter.DISABLED)
self.sign_in_button.configure(text='Log out')
self.chat.focus()
def display_message(message: str, sender_id=None, date=None):
"""Appends new message to message logs"""
if ignore_handler.check(message):
return
if sender_id:
if not date:
date = datetime.datetime.now()
if not message:
message = '{multimedia ¯\_(ツ)_/¯}'
date = date.strftime(config.TIMESTAMP_FORMAT)
sender_name = get_display_name(sender_id) + ': '
message = " {} | {}{}".format(date, sender_name, message)
message_log.body.insert(-1, urwid.Text(message))
message_log.set_focus(len(message_log.body)-1)
mainloop.draw_screen()