本文整理汇总了Python中telethon.utils.get_peer_id方法的典型用法代码示例。如果您正苦于以下问题:Python utils.get_peer_id方法的具体用法?Python utils.get_peer_id怎么用?Python utils.get_peer_id使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telethon.utils
的用法示例。
在下文中一共展示了utils.get_peer_id方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_entity_rows_by_id
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
t = self.Entity.__table__
if exact:
rows = self.engine.execute(select([t.c.id, t.c.hash]).where(
and_(t.c.session_id == self.session_id, t.c.id == key)))
else:
ids = (
utils.get_peer_id(PeerUser(key)),
utils.get_peer_id(PeerChat(key)),
utils.get_peer_id(PeerChannel(key))
)
rows = self.engine.execute(select([t.c.id, t.c.hash])
.where(
and_(t.c.session_id == self.session_id, t.c.id.in_(ids))))
try:
return next(rows)
except StopIteration:
return None
示例2: dump_channel
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def dump_channel(self, channel_full, channel, photo_id, timestamp=None):
"""Dump a Channel into the Channel table.
Params: ChannelFull, Channel to dump, MediaID
of the profile photo in the DB
Returns -"""
# Need to get the full object too for 'about' info
values = (get_peer_id(channel),
timestamp or round(time.time()),
channel_full.about,
channel.title,
channel.username,
photo_id,
channel_full.pinned_msg_id)
for callback in self._dump_callbacks['channel']:
callback(values)
return self._insert_if_valid_date('Channel', values, date_column=1,
where=('ID', get_peer_id(channel)))
示例3: dump_supergroup
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def dump_supergroup(self, supergroup_full, supergroup, photo_id,
timestamp=None):
"""Dump a Supergroup into the Supergroup table
Params: ChannelFull, Channel to dump, MediaID
of the profile photo in the DB.
Returns -"""
# Need to get the full object too for 'about' info
values = (get_peer_id(supergroup),
timestamp or round(time.time()),
getattr(supergroup_full, 'about', None) or '',
supergroup.title,
supergroup.username,
photo_id,
supergroup_full.pinned_msg_id)
for callback in self._dump_callbacks['supergroup']:
callback(values)
return self._insert_if_valid_date('Supergroup', values, date_column=1,
where=('ID', get_peer_id(supergroup)))
示例4: _dump_admin_log
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def _dump_admin_log(self, events, target):
"""
Helper method to iterate the events from a GetAdminLogRequest
and dump them into the Dumper, mostly to avoid excessive nesting.
Also enqueues any media to be downloaded later by a different coroutine.
"""
for event in events:
assert isinstance(event, types.ChannelAdminLogEvent)
if isinstance(event.action,
types.ChannelAdminLogEventActionChangePhoto):
media_id1 = self.dumper.dump_media(event.action.new_photo)
media_id2 = self.dumper.dump_media(event.action.prev_photo)
self.enqueue_photo(event.action.new_photo, media_id1, target,
peer_id=event.user_id, date=event.date)
self.enqueue_photo(event.action.prev_photo, media_id2, target,
peer_id=event.user_id, date=event.date)
else:
media_id1 = None
media_id2 = None
self.dumper.dump_admin_log_event(
event, utils.get_peer_id(target), media_id1, media_id2
)
return min(e.id for e in events)
示例5: on_regex
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def on_regex(event):
if event.fwd_from:
return
if not event.is_private and\
await group_has_sedbot(await event.get_input_chat()):
# await event.edit("This group has a sed bot. Ignoring this message!")
return
chat_id = utils.get_peer_id(await event.get_input_chat())
m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())
if m is not None:
s = f"{HEADER}{s}"
out = await borg.send_message(
await event.get_input_chat(), s, reply_to=m.id
)
last_msgs[chat_id].appendleft(out)
elif s is not None:
await event.edit(s)
raise events.StopPropagation
示例6: on_regex
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def on_regex(event):
if event.fwd_from:
return
if not event.is_private and\
await group_has_sedbot(await event.get_input_chat()):
# await event.edit("This group has a sed bot. Ignoring this message!")
return
chat_id = utils.get_peer_id(await event.get_input_chat())
m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())
if m is not None:
s = f"{HEADER}{s}"
out = await bot.send_message(
await event.get_input_chat(), s, reply_to=m.id
)
last_msgs[chat_id].appendleft(out)
elif s is not None:
await event.edit(s)
raise events.StopPropagation
示例7: get_entity_rows_by_id
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
if exact:
query = self._db_query(self.Entity, self.Entity.id == key)
else:
ids = (
utils.get_peer_id(PeerUser(key)),
utils.get_peer_id(PeerChat(key)),
utils.get_peer_id(PeerChannel(key))
)
query = self._db_query(self.Entity, self.Entity.id.in_(ids))
row = query.one_or_none()
return (row.id, row.hash) if row else None
示例8: get_peer_id
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def get_peer_id(
self: 'TelegramClient',
peer: 'hints.EntityLike',
add_mark: bool = True) -> int:
"""
Gets the ID for the given entity.
This method needs to be ``async`` because `peer` supports usernames,
invite-links, phone numbers (from people in your contact list), etc.
If ``add_mark is False``, then a positive ID will be returned
instead. By default, bot-API style IDs (signed) are returned.
Example
.. code-block:: python
print(await client.get_peer_id('me'))
"""
if isinstance(peer, int):
return utils.get_peer_id(peer, add_mark=add_mark)
try:
if peer.SUBCLASS_OF_ID not in (0x2d45687, 0xc91c90b6):
# 0x2d45687, 0xc91c90b6 == crc32(b'Peer') and b'InputPeer'
peer = await self.get_input_entity(peer)
except AttributeError:
peer = await self.get_input_entity(peer)
if isinstance(peer, types.InputPeerSelf):
peer = await self.get_me(input_peer=True)
return utils.get_peer_id(peer, add_mark=add_mark)
# endregion
# region Private methods
示例9: test_formatter_get_chat
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def test_formatter_get_chat(self):
"""
Ensures that the BaseFormatter is able to fetch the expected
entities when using a date parameter.
"""
chat = types.Chat(
id=123,
title='Some title',
photo=types.ChatPhotoEmpty(),
participants_count=7,
date=datetime.now(),
version=1
)
dumper = Dumper(self.dumper_config)
fmt = BaseFormatter(dumper.conn)
for month in range(1, 13):
dumper.dump_chat(chat, None, timestamp=int(datetime(
year=2010, month=month, day=1
).timestamp()))
dumper.commit()
cid = tl_utils.get_peer_id(chat)
# Default should get the most recent version
date = fmt.get_chat(cid).date_updated
assert date == datetime(year=2010, month=12, day=1)
# Expected behaviour is to get the previous available date
target = datetime(year=2010, month=6, day=29)
date = fmt.get_chat(cid, target).date_updated
assert date == datetime(year=2010, month=6, day=1)
# Expected behaviour is to get the next date if previous unavailable
target = datetime(year=2009, month=12, day=1)
date = fmt.get_chat(cid, target).date_updated
assert date == datetime(year=2010, month=1, day=1)
示例10: fmt_dialog
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def fmt_dialog(dialog, id_pad=0, username_pad=0):
"""
Space-fill a row with given padding values
to ensure alignment when printing dialogs.
"""
username = getattr(dialog.entity, 'username', None)
username = '@' + username if username else NO_USERNAME
return '{:<{id_pad}} | {:<{username_pad}} | {}'.format(
utils.get_peer_id(dialog.entity), username, dialog.name,
id_pad=id_pad, username_pad=username_pad
)
示例11: find_fmt_dialog_padding
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def find_fmt_dialog_padding(dialogs):
"""
Find the correct amount of space padding
to give dialogs when printing them.
"""
no_username = NO_USERNAME[:-1] # Account for the added '@' if username
return (
max(len(str(utils.get_peer_id(dialog.entity))) for dialog in dialogs),
max(len(getattr(dialog.entity, 'username', no_username) or no_username)
for dialog in dialogs) + 1
)
示例12: _dump_messages
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def _dump_messages(self, messages, target):
"""
Helper method to iterate the messages from a GetMessageHistoryRequest
and dump them into the Dumper, mostly to avoid excessive nesting.
Also enqueues any media to be downloaded later by a different coroutine.
"""
for m in messages:
if isinstance(m, types.Message):
media_id = self.dumper.dump_media(m.media)
if media_id and self._check_media(m.media):
self.enqueue_media(
media_id, utils.get_peer_id(target), m.from_id, m.date
)
self.dumper.dump_message(
message=m,
context_id=utils.get_peer_id(target),
forward_id=self.dumper.dump_forward(m.fwd_from),
media_id=media_id
)
elif isinstance(m, types.MessageService):
if isinstance(m.action, types.MessageActionChatEditPhoto):
media_id = self.dumper.dump_media(m.action.photo)
self.enqueue_photo(m.action.photo, media_id, target,
peer_id=m.from_id, date=m.date)
else:
media_id = None
self.dumper.dump_message_service(
message=m,
context_id=utils.get_peer_id(target),
media_id=media_id
)
示例13: enqueue_entities
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
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)
if isinstance(entity, (types.User, types.InputPeerUser)):
self._user_queue.put_nowait(entity)
else:
self._chat_queue.put_nowait(entity)
示例14: enqueue_photo
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
def enqueue_photo(self, photo, photo_id, context,
peer_id=None, date=None):
if not photo_id:
return
if not isinstance(context, int):
context = utils.get_peer_id(context)
if peer_id is None:
peer_id = context
if date is None:
date = getattr(photo, 'date', None) or datetime.datetime.now()
self.enqueue_media(photo_id, context, peer_id, date)
示例15: download_past_media
# 需要导入模块: from telethon import utils [as 别名]
# 或者: from telethon.utils import get_peer_id [as 别名]
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()