id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
146,748 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/session.py
|
telethon._updates.session.SessionState
|
class SessionState:
"""
Stores the information needed to fetch updates and about the current user.
* user_id: 64-bit number representing the user identifier.
* dc_id: 32-bit number relating to the datacenter identifier where the user is.
* bot: is the logged-in user a bot?
* pts: 64-bit number holding the state needed to fetch updates.
* qts: alternative 64-bit number holding the state needed to fetch updates.
* date: 64-bit number holding the date needed to fetch updates.
* seq: 64-bit-number holding the sequence number needed to fetch updates.
* takeout_id: 64-bit-number holding the identifier of the current takeout session.
Note that some of the numbers will only use 32 out of the 64 available bits.
However, for future-proofing reasons, we recommend you pretend they are 64-bit long.
"""
__slots__ = ('user_id', 'dc_id', 'bot', 'pts', 'qts', 'date', 'seq', 'takeout_id')
def __init__(
self,
user_id: int,
dc_id: int,
bot: bool,
pts: int,
qts: int,
date: int,
seq: int,
takeout_id: Optional[int]
):
self.user_id = user_id
self.dc_id = dc_id
self.bot = bot
self.pts = pts
self.qts = qts
self.date = date
self.seq = seq
self.takeout_id = takeout_id
def __repr__(self):
return repr({k: getattr(self, k) for k in self.__slots__})
|
class SessionState:
'''
Stores the information needed to fetch updates and about the current user.
* user_id: 64-bit number representing the user identifier.
* dc_id: 32-bit number relating to the datacenter identifier where the user is.
* bot: is the logged-in user a bot?
* pts: 64-bit number holding the state needed to fetch updates.
* qts: alternative 64-bit number holding the state needed to fetch updates.
* date: 64-bit number holding the date needed to fetch updates.
* seq: 64-bit-number holding the sequence number needed to fetch updates.
* takeout_id: 64-bit-number holding the identifier of the current takeout session.
Note that some of the numbers will only use 32 out of the 64 available bits.
However, for future-proofing reasons, we recommend you pretend they are 64-bit long.
'''
def __init__(
self,
user_id: int,
dc_id: int,
bot: bool,
pts: int,
qts: int,
date: int,
seq: int,
takeout_id: Optional[int]
):
pass
def __repr__(self):
pass
| 3 | 1 | 11 | 0 | 11 | 0 | 1 | 0.57 | 0 | 2 | 0 | 0 | 2 | 8 | 2 | 2 | 40 | 4 | 23 | 22 | 10 | 13 | 13 | 12 | 10 | 1 | 0 | 0 | 2 |
146,749 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/session.py
|
telethon._updates.session.EntityType
|
class EntityType(IntEnum):
"""
You can rely on the type value to be equal to the ASCII character one of:
* 'U' (85): this entity belongs to a :tl:`User` who is not a ``bot``.
* 'B' (66): this entity belongs to a :tl:`User` who is a ``bot``.
* 'G' (71): this entity belongs to a small group :tl:`Chat`.
* 'C' (67): this entity belongs to a standard broadcast :tl:`Channel`.
* 'M' (77): this entity belongs to a megagroup :tl:`Channel`.
* 'E' (69): this entity belongs to an "enormous" "gigagroup" :tl:`Channel`.
"""
USER = ord('U')
BOT = ord('B')
GROUP = ord('G')
CHANNEL = ord('C')
MEGAGROUP = ord('M')
GIGAGROUP = ord('E')
def canonical(self):
"""
Return the canonical version of this type.
"""
return _canon_entity_types[self]
|
class EntityType(IntEnum):
'''
You can rely on the type value to be equal to the ASCII character one of:
* 'U' (85): this entity belongs to a :tl:`User` who is not a ``bot``.
* 'B' (66): this entity belongs to a :tl:`User` who is a ``bot``.
* 'G' (71): this entity belongs to a small group :tl:`Chat`.
* 'C' (67): this entity belongs to a standard broadcast :tl:`Channel`.
* 'M' (77): this entity belongs to a megagroup :tl:`Channel`.
* 'E' (69): this entity belongs to an "enormous" "gigagroup" :tl:`Channel`.
'''
def canonical(self):
'''
Return the canonical version of this type.
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 1.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 56 | 23 | 2 | 9 | 8 | 7 | 12 | 9 | 8 | 7 | 1 | 3 | 0 | 1 |
146,750 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/chats.py
|
telethon.client.chats._ParticipantsIter
|
class _ParticipantsIter(RequestIter):
async def _init(self, entity, filter, search):
if isinstance(filter, type):
if filter in (types.ChannelParticipantsBanned,
types.ChannelParticipantsKicked,
types.ChannelParticipantsSearch,
types.ChannelParticipantsContacts):
# These require a `q` parameter (support types for convenience)
filter = filter('')
else:
filter = filter()
entity = await self.client.get_input_entity(entity)
ty = helpers._entity_type(entity)
if search and (filter or ty != helpers._EntityType.CHANNEL):
# We need to 'search' ourselves unless we have a PeerChannel
search = search.casefold()
self.filter_entity = lambda ent: (
search in utils.get_display_name(ent).casefold() or
search in (getattr(ent, 'username', None) or '').casefold()
)
else:
self.filter_entity = lambda ent: True
# Only used for channels, but we should always set the attribute
# Called `requests` even though it's just one for legacy purposes.
self.requests = None
if ty == helpers._EntityType.CHANNEL:
if self.limit <= 0:
# May not have access to the channel, but getFull can get the .total.
self.total = (await self.client(
functions.channels.GetFullChannelRequest(entity)
)).full_chat.participants_count
raise StopAsyncIteration
self.seen = set()
self.requests = functions.channels.GetParticipantsRequest(
channel=entity,
filter=filter or types.ChannelParticipantsSearch(search),
offset=0,
limit=_MAX_PARTICIPANTS_CHUNK_SIZE,
hash=0
)
elif ty == helpers._EntityType.CHAT:
full = await self.client(
functions.messages.GetFullChatRequest(entity.chat_id))
if not isinstance(
full.full_chat.participants, types.ChatParticipants):
# ChatParticipantsForbidden won't have ``.participants``
self.total = 0
raise StopAsyncIteration
self.total = len(full.full_chat.participants.participants)
users = {user.id: user for user in full.users}
for participant in full.full_chat.participants.participants:
if isinstance(participant, types.ChannelParticipantLeft):
# See issue #3231 to learn why this is ignored.
continue
elif isinstance(participant, types.ChannelParticipantBanned):
user_id = participant.peer.user_id
else:
user_id = participant.user_id
user = users[user_id]
if not self.filter_entity(user):
continue
user = users[user_id]
user.participant = participant
self.buffer.append(user)
return True
else:
self.total = 1
if self.limit != 0:
user = await self.client.get_entity(entity)
if self.filter_entity(user):
user.participant = None
self.buffer.append(user)
return True
async def _load_next_chunk(self):
if not self.requests:
return True
self.requests.limit = min(self.limit - self.requests.offset, _MAX_PARTICIPANTS_CHUNK_SIZE)
if self.requests.offset > self.limit:
return True
if self.total is None:
f = self.requests.filter
if (
not isinstance(f, types.ChannelParticipantsRecent)
and (not isinstance(f, types.ChannelParticipantsSearch) or f.q)
):
# Only do an additional getParticipants here to get the total
# if there's a filter which would reduce the real total number.
# getParticipants is cheaper than getFull.
self.total = (await self.client(functions.channels.GetParticipantsRequest(
channel=self.requests.channel,
filter=types.ChannelParticipantsRecent(),
offset=0,
limit=1,
hash=0
))).count
participants = await self.client(self.requests)
if self.total is None:
# Will only get here if there was one request with a filter that matched all users.
self.total = participants.count
if not participants.users:
self.requests = None
return
self.requests.offset += len(participants.participants)
users = {user.id: user for user in participants.users}
for participant in participants.participants:
if isinstance(participant, types.ChannelParticipantBanned):
if not isinstance(participant.peer, types.PeerUser):
# May have the entire channel banned. See #3105.
continue
user_id = participant.peer.user_id
else:
user_id = participant.user_id
user = users[user_id]
if not self.filter_entity(user) or user.id in self.seen:
continue
self.seen.add(user_id)
user = users[user_id]
user.participant = participant
self.buffer.append(user)
|
class _ParticipantsIter(RequestIter):
async def _init(self, entity, filter, search):
pass
async def _load_next_chunk(self):
pass
| 3 | 0 | 68 | 9 | 53 | 6 | 13 | 0.11 | 1 | 2 | 1 | 0 | 2 | 4 | 2 | 31 | 138 | 19 | 107 | 17 | 104 | 12 | 75 | 17 | 72 | 14 | 5 | 3 | 25 |
146,751 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/session.py
|
telethon._updates.session.Entity
|
class Entity:
"""
Stores the information needed to use a certain user, chat or channel with the API.
* ty: 8-bit number indicating the type of the entity (of type `EntityType`).
* id: 64-bit number uniquely identifying the entity among those of the same type.
* hash: 64-bit signed number needed to use this entity with the API.
The string representation of this class is considered to be stable, for as long as
Telegram doesn't need to add more fields to the entities. It can also be converted
to bytes with ``bytes(entity)``, for a more compact representation.
"""
__slots__ = ('ty', 'id', 'hash')
def __init__(
self,
ty: EntityType,
id: int,
hash: int
):
self.ty = ty
self.id = id
self.hash = hash
@property
def is_user(self):
"""
``True`` if the entity is either a user or a bot.
"""
return self.ty in (EntityType.USER, EntityType.BOT)
@property
def is_group(self):
"""
``True`` if the entity is a small group chat or `megagroup`_.
.. _megagroup: https://telegram.org/blog/supergroups5k
"""
return self.ty in (EntityType.GROUP, EntityType.MEGAGROUP)
@property
def is_broadcast(self):
"""
``True`` if the entity is a broadcast channel or `broadcast group`_.
.. _broadcast group: https://telegram.org/blog/autodelete-inv2#groups-with-unlimited-members
"""
return self.ty in (EntityType.CHANNEL, EntityType.GIGAGROUP)
@classmethod
def from_str(cls, string: str):
"""
Convert the string into an `Entity`.
"""
try:
ty, id, hash = string.split('.')
ty, id, hash = ord(ty), int(id), int(hash)
except AttributeError:
raise TypeError(f'expected str, got {string!r}') from None
except (TypeError, ValueError):
raise ValueError(f'malformed entity str (must be T.id.hash), got {string!r}') from None
return cls(EntityType(ty), id, hash)
@classmethod
def from_bytes(cls, blob):
"""
Convert the bytes into an `Entity`.
"""
try:
ty, id, hash = struct.unpack('<Bqq', blob)
except struct.error:
raise ValueError(f'malformed entity data, got {string!r}') from None
return cls(EntityType(ty), id, hash)
def __str__(self):
return f'{chr(self.ty)}.{self.id}.{self.hash}'
def __bytes__(self):
return struct.pack('<Bqq', self.ty, self.id, self.hash)
def _as_input_peer(self):
if self.is_user:
return InputPeerUser(self.id, self.hash)
elif self.ty == EntityType.GROUP:
return InputPeerChat(self.id)
else:
return InputPeerChannel(self.id, self.hash)
def __repr__(self):
return repr({k: getattr(self, k) for k in self.__slots__})
|
class Entity:
'''
Stores the information needed to use a certain user, chat or channel with the API.
* ty: 8-bit number indicating the type of the entity (of type `EntityType`).
* id: 64-bit number uniquely identifying the entity among those of the same type.
* hash: 64-bit signed number needed to use this entity with the API.
The string representation of this class is considered to be stable, for as long as
Telegram doesn't need to add more fields to the entities. It can also be converted
to bytes with ``bytes(entity)``, for a more compact representation.
'''
def __init__(
self,
ty: EntityType,
id: int,
hash: int
):
pass
@property
def is_user(self):
'''
``True`` if the entity is either a user or a bot.
'''
pass
@property
def is_group(self):
'''
``True`` if the entity is a small group chat or `megagroup`_.
.. _megagroup: https://telegram.org/blog/supergroups5k
'''
pass
@property
def is_broadcast(self):
'''
``True`` if the entity is a broadcast channel or `broadcast group`_.
.. _broadcast group: https://telegram.org/blog/autodelete-inv2#groups-with-unlimited-members
'''
pass
@classmethod
def from_str(cls, string: str):
'''
Convert the string into an `Entity`.
'''
pass
@classmethod
def from_bytes(cls, blob):
'''
Convert the bytes into an `Entity`.
'''
pass
def __str__(self):
pass
def __bytes__(self):
pass
def _as_input_peer(self):
pass
def __repr__(self):
pass
| 16 | 6 | 6 | 0 | 4 | 2 | 2 | 0.52 | 0 | 6 | 1 | 0 | 8 | 3 | 10 | 10 | 92 | 16 | 50 | 27 | 29 | 26 | 38 | 17 | 27 | 3 | 0 | 1 | 15 |
146,752 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.State
|
class State:
__slots__ = ('pts', 'deadline')
def __init__(
self,
# Current local persistent timestamp.
pts: int,
# Next instant when we would get the update difference if no updates arrived before then.
deadline: float
):
self.pts = pts
self.deadline = deadline
def __repr__(self):
return f'State(pts={self.pts}, deadline={self.deadline})'
|
class State:
def __init__(
self,
# Current local persistent timestamp.
pts: int,
# Next instant when we would get the update difference if no updates arrived before then.
deadline: float
):
pass
def __repr__(self):
pass
| 3 | 0 | 6 | 0 | 5 | 1 | 1 | 0.18 | 0 | 2 | 0 | 0 | 2 | 2 | 2 | 2 | 15 | 2 | 11 | 10 | 4 | 2 | 7 | 6 | 4 | 1 | 0 | 0 | 2 |
146,753 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.Sentinel
|
class Sentinel:
__slots__ = ('tag',)
def __init__(self, tag=None):
self.tag = tag or '_'
def __repr__(self):
return self.tag
|
class Sentinel:
def __init__(self, tag=None):
pass
def __repr__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 8 | 2 | 6 | 5 | 3 | 0 | 6 | 5 | 3 | 1 | 0 | 0 | 2 |
146,754 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.PtsInfo
|
class PtsInfo:
__slots__ = ('pts', 'pts_count', 'entry')
def __init__(
self,
pts: int,
pts_count: int,
entry: object
):
self.pts = pts
self.pts_count = pts_count
self.entry = entry
@classmethod
def from_update(cls, update):
pts = getattr(update, 'pts', None)
if pts:
pts_count = getattr(update, 'pts_count', None) or 0
try:
entry = update.message.peer_id.channel_id
except AttributeError:
entry = getattr(update, 'channel_id', None) or ENTRY_ACCOUNT
return cls(pts=pts, pts_count=pts_count, entry=entry)
qts = getattr(update, 'qts', None)
if qts:
return cls(pts=qts, pts_count=1, entry=ENTRY_SECRET)
return None
def __repr__(self):
return f'PtsInfo(pts={self.pts}, pts_count={self.pts_count}, entry={self.entry})'
|
class PtsInfo:
def __init__(
self,
pts: int,
pts_count: int,
entry: object
):
pass
@classmethod
def from_update(cls, update):
pass
def __repr__(self):
pass
| 5 | 0 | 9 | 1 | 8 | 0 | 2 | 0 | 0 | 3 | 0 | 0 | 2 | 3 | 3 | 3 | 32 | 5 | 27 | 18 | 17 | 0 | 21 | 12 | 17 | 4 | 0 | 2 | 6 |
146,755 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_examples/gui.py
|
gui.App
|
class App(tkinter.Tk):
"""
Our main GUI application; we subclass `tkinter.Tk`
so the `self` instance can be the root widget.
One must be careful when assigning members or
defining methods since those may interfer with
the root widget.
You may prefer to have ``App.root = tkinter.Tk()``
and create widgets with ``self.root`` as parent.
"""
def __init__(self, client, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cl = client
self.me = None
self.title(TITLE)
self.geometry(SIZE)
# Signing in row; the entry supports phone and bot token
self.sign_in_label = tkinter.Label(self, text='Loading...')
self.sign_in_label.grid(row=0, column=0)
self.sign_in_entry = tkinter.Entry(self)
self.sign_in_entry.grid(row=0, column=1, sticky=tkinter.EW)
self.sign_in_entry.bind('<Return>', self.sign_in)
self.sign_in_button = tkinter.Button(self, text='...',
command=self.sign_in)
self.sign_in_button.grid(row=0, column=2)
self.code = None
# The chat where to send and show messages from
tkinter.Label(self, text='Target chat:').grid(row=1, column=0)
self.chat = tkinter.Entry(self)
self.chat.grid(row=1, column=1, columnspan=2, sticky=tkinter.EW)
self.columnconfigure(1, weight=1)
self.chat.bind('<Return>', self.check_chat)
self.chat.bind('<FocusOut>', self.check_chat)
self.chat.focus()
self.chat_id = None
# Message log (incoming and outgoing); we configure it as readonly
self.log = tkinter.scrolledtext.ScrolledText(self)
allow_copy(self.log)
self.log.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
self.rowconfigure(2, weight=1)
self.cl.add_event_handler(self.on_message, events.NewMessage)
# Save shown message IDs to support replying with ".rN reply"
# For instance to reply to the last message ".r1 this is a reply"
# Deletion also works with ".dN".
self.message_ids = []
# Save the sent texts to allow editing with ".s text/replacement"
# For instance to edit the last "hello" with "bye" ".s hello/bye"
self.sent_text = collections.deque(maxlen=10)
# Sending messages
tkinter.Label(self, text='Message:').grid(row=3, column=0)
self.message = tkinter.Entry(self)
self.message.grid(row=3, column=1, sticky=tkinter.EW)
self.message.bind('<Return>', self.send_message)
tkinter.Button(self, text='Send',
command=self.send_message).grid(row=3, column=2)
# Post-init (async, connect client)
self.cl.loop.create_task(self.post_init())
async def post_init(self):
"""
Completes the initialization of our application.
Since `__init__` cannot be `async` we use this.
"""
if await self.cl.is_user_authorized():
self.set_signed_in(await self.cl.get_me())
else:
# User is not logged in, configure the button to ask them to login
self.sign_in_button.configure(text='Sign in')
self.sign_in_label.configure(
text='Sign in (phone/token):')
async def on_message(self, event):
"""
Event handler that will add new messages to the message log.
"""
# We want to show only messages sent to this chat
if event.chat_id != self.chat_id:
return
# Save the message ID so we know which to reply to
self.message_ids.append(event.id)
# Decide a prefix (">> " for our messages, "<user>" otherwise)
if event.out:
text = '>> '
else:
sender = await event.get_sender()
text = '<{}> '.format(sanitize_str(
utils.get_display_name(sender)))
# If the message has media show "(MediaType) "
if event.media:
text += '({}) '.format(event.media.__class__.__name__)
text += sanitize_str(event.text)
text += '\n'
# Append the text to the end with a newline, and scroll to the end
self.log.insert(tkinter.END, text)
self.log.yview(tkinter.END)
# noinspection PyUnusedLocal
@callback
async def sign_in(self, event=None):
"""
Note the `event` argument. This is required since this callback
may be called from a ``widget.bind`` (such as ``'<Return>'``),
which sends information about the event we don't care about.
This callback logs out if authorized, signs in if a code was
sent or a bot token is input, or sends the code otherwise.
"""
self.sign_in_label.configure(text='Working...')
self.sign_in_entry.configure(state=tkinter.DISABLED)
if await self.cl.is_user_authorized():
await self.cl.log_out()
self.destroy()
return
value = self.sign_in_entry.get().strip()
if self.code:
self.set_signed_in(await self.cl.sign_in(code=value))
elif ':' in value:
self.set_signed_in(await self.cl.sign_in(bot_token=value))
else:
self.code = await self.cl.send_code_request(value)
self.sign_in_label.configure(text='Code:')
self.sign_in_entry.configure(state=tkinter.NORMAL)
self.sign_in_entry.delete(0, tkinter.END)
self.sign_in_entry.focus()
return
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()
# noinspection PyUnusedLocal
@callback
async def send_message(self, event=None):
"""
Sends a message. Does nothing if the client is not connected.
"""
if not self.cl.is_connected():
return
# The user needs to configure a chat where the message should be sent.
#
# If the chat ID does not exist, it was not valid and the user must
# configure one; hint them by changing the background to red.
if not self.chat_id:
self.chat.configure(bg='red')
self.chat.focus()
return
# Get the message, clear the text field and focus it again
text = self.message.get().strip()
self.message.delete(0, tkinter.END)
self.message.focus()
if not text:
return
# NOTE: This part is optional but supports editing messages
# You can remove it if you find it too complicated.
#
# Check if the edit matches any text
m = EDIT.match(text)
if m:
find = re.compile(m.group(1).lstrip())
# Cannot reversed(enumerate(...)), use index
for i in reversed(range(len(self.sent_text))):
msg_id, msg_text = self.sent_text[i]
if find.search(msg_text):
# Found text to replace, so replace it and edit
new = find.sub(m.group(2), msg_text)
self.sent_text[i] = (msg_id, new)
await self.cl.edit_message(self.chat_id, msg_id, new)
# Notify that a replacement was made
self.log.insert(tkinter.END, '(message edited: {} -> {})\n'
.format(msg_text, new))
self.log.yview(tkinter.END)
return
# Check if we want to delete the message
m = DELETE.match(text)
if m:
try:
delete = self.message_ids.pop(-int(m.group(1)))
except IndexError:
pass
else:
await self.cl.delete_messages(self.chat_id, delete)
# Notify that a message was deleted
self.log.insert(tkinter.END, '(message deleted)\n')
self.log.yview(tkinter.END)
return
# Check if we want to reply to some message
reply_to = None
m = REPLY.match(text)
if m:
text = m.group(2)
try:
reply_to = self.message_ids[-int(m.group(1))]
except IndexError:
pass
# NOTE: This part is no longer optional. It sends the message.
# Send the message text and get back the sent message object
message = await self.cl.send_message(self.chat_id, text,
reply_to=reply_to)
# Save the sent message ID and text to allow edits
self.sent_text.append((message.id, text))
# Process the sent message as if it were an event
await self.on_message(message)
# noinspection PyUnusedLocal
@callback
async def check_chat(self, event=None):
"""
Checks the input chat where to send and listen messages from.
"""
if self.me is None:
return # Not logged in yet
chat = self.chat.get().strip()
try:
chat = int(chat)
except ValueError:
pass
try:
old = self.chat_id
# Valid chat ID, set it and configure the colour back to white
self.chat_id = await self.cl.get_peer_id(chat)
self.chat.configure(bg='white')
# If the chat ID changed, clear the
# messages that we could edit or reply
if self.chat_id != old:
self.message_ids.clear()
self.sent_text.clear()
self.log.delete('1.0', tkinter.END)
if not self.me.bot:
for msg in reversed(
await self.cl.get_messages(self.chat_id, 100)):
await self.on_message(msg)
except ValueError:
# Invalid chat ID, let the user know with a yellow background
self.chat_id = None
self.chat.configure(bg='yellow')
|
class App(tkinter.Tk):
'''
Our main GUI application; we subclass `tkinter.Tk`
so the `self` instance can be the root widget.
One must be careful when assigning members or
defining methods since those may interfer with
the root widget.
You may prefer to have ``App.root = tkinter.Tk()``
and create widgets with ``self.root`` as parent.
'''
def __init__(self, client, *args, **kwargs):
pass
async def post_init(self):
'''
Completes the initialization of our application.
Since `__init__` cannot be `async` we use this.
'''
pass
async def on_message(self, event):
'''
Event handler that will add new messages to the message log.
'''
pass
@callback
async def sign_in(self, event=None):
'''
Note the `event` argument. This is required since this callback
may be called from a ``widget.bind`` (such as ``'<Return>'``),
which sends information about the event we don't care about.
This callback logs out if authorized, signs in if a code was
sent or a bot token is input, or sends the code otherwise.
'''
pass
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).
'''
pass
@callback
async def send_message(self, event=None):
'''
Sends a message. Does nothing if the client is not connected.
'''
pass
@callback
async def check_chat(self, event=None):
'''
Checks the input chat where to send and listen messages from.
'''
pass
| 11 | 7 | 36 | 4 | 23 | 9 | 4 | 0.47 | 1 | 11 | 1 | 0 | 7 | 12 | 7 | 194 | 273 | 35 | 163 | 38 | 152 | 76 | 149 | 35 | 141 | 11 | 2 | 4 | 30 |
146,756 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_examples/interactive_telegram_client.py
|
interactive_telegram_client.InteractiveTelegramClient
|
class InteractiveTelegramClient(TelegramClient):
"""Full featured Telegram client, meant to be used on an interactive
session to see what Telethon is capable off -
This client allows the user to perform some basic interaction with
Telegram through Telethon, such as listing dialogs (open chats),
talking to people, downloading media, and receiving updates.
"""
def __init__(self, session_user_id, api_id, api_hash,
proxy=None):
"""
Initializes the InteractiveTelegramClient.
:param session_user_id: Name of the *.session file.
:param api_id: Telegram's api_id acquired through my.telegram.org.
:param api_hash: Telegram's api_hash.
:param proxy: Optional proxy tuple/dictionary.
"""
print_title('Initialization')
print('Initializing interactive example...')
# The first step is to initialize the TelegramClient, as we are
# subclassing it, we need to call super().__init__(). On a more
# normal case you would want 'client = TelegramClient(...)'
super().__init__(
# These parameters should be passed always, session name and API
session_user_id, api_id, api_hash,
# You can optionally change the connection mode by passing a
# type or an instance of it. This changes how the sent packets
# look (low-level concept you normally shouldn't worry about).
# Default is ConnectionTcpFull, smallest is ConnectionTcpAbridged.
connection=ConnectionTcpAbridged,
# If you're using a proxy, set it here.
proxy=proxy
)
# Store {message.id: message} map here so that we can download
# media known the message ID, for every message having media.
self.found_media = {}
async def init(self):
# Calling .connect() may raise a connection error False, so you need
# to except those before continuing. Otherwise you may want to retry
# as done here.
print('Connecting to Telegram servers...')
try:
await self.connect()
except IOError:
# We handle IOError and not ConnectionError because
# PySocks' errors do not subclass ConnectionError
# (so this will work with and without proxies).
print('Initial connection failed. Retrying...')
await self.connect()
# If the user hasn't called .sign_in() yet, they won't
# be authorized. The first thing you must do is authorize. Calling
# .sign_in() should only be done once as the information is saved on
# the *.session file so you don't need to enter the code every time.
if not await self.is_user_authorized():
print('First run. Sending code request...')
user_phone = input('Enter your phone: ')
await self.sign_in(user_phone)
self_user = None
while self_user is None:
code = input('Enter the code you just received: ')
try:
self_user = await self.sign_in(code=code)
# Two-step verification may be enabled, and .sign_in will
# raise this error. If that's the case ask for the password.
# Note that getpass() may not work on PyCharm due to a bug,
# if that's the case simply change it for input().
except SessionPasswordNeededError:
pw = getpass('Two step verification is enabled. '
'Please enter your password: ')
self_user = await self.sign_in(password=pw)
async def run(self):
"""Main loop of the TelegramClient, will wait for user action"""
# Once everything is ready, we can add an event handler.
#
# Events are an abstraction over Telegram's "Updates" and
# are much easier to use.
self.add_event_handler(self.message_handler, events.NewMessage)
# Enter a while loop to chat as long as the user wants
while True:
# Retrieve the top dialogs. You can set the limit to None to
# retrieve all of them if you wish, but beware that may take
# a long time if you have hundreds of them.
dialog_count = 15
# Entities represent the user, chat or channel
# corresponding to the dialog on the same index.
dialogs = await self.get_dialogs(limit=dialog_count)
i = None
while i is None:
print_title('Dialogs window')
# Display them so the user can choose
for i, dialog in enumerate(dialogs, start=1):
sprint('{}. {}'.format(i, get_display_name(dialog.entity)))
# Let the user decide who they want to talk to
print()
print('> Who do you want to send messages to?')
print('> Available commands:')
print(' !q: Quits the dialogs window and exits.')
print(' !l: Logs out, terminating this session.')
print()
i = await async_input('Enter dialog ID or a command: ')
if i == '!q':
return
if i == '!l':
# Logging out will cause the user to need to reenter the
# code next time they want to use the library, and will
# also delete the *.session file off the filesystem.
#
# This is not the same as simply calling .disconnect(),
# which simply shuts down everything gracefully.
await self.log_out()
return
try:
i = int(i if i else 0) - 1
# Ensure it is inside the bounds, otherwise retry
if not 0 <= i < dialog_count:
i = None
except ValueError:
i = None
# Retrieve the selected user (or chat, or channel)
entity = dialogs[i].entity
# Show some information
print_title('Chat with "{}"'.format(get_display_name(entity)))
print('Available commands:')
print(' !q: Quits the current chat.')
print(' !Q: Quits the current chat and exits.')
print(' !h: prints the latest messages (message History).')
print(' !up <path>: Uploads and sends the Photo from path.')
print(' !uf <path>: Uploads and sends the File from path.')
print(' !d <msg-id>: Deletes a message by its id')
print(' !dm <msg-id>: Downloads the given message Media (if any).')
print(' !dp: Downloads the current dialog Profile picture.')
print(' !i: Prints information about this chat..')
print()
# And start a while loop to chat
while True:
msg = await async_input('Enter a message: ')
# Quit
if msg == '!q':
break
elif msg == '!Q':
return
# History
elif msg == '!h':
# First retrieve the messages and some information
messages = await self.get_messages(entity, limit=10)
# Iterate over all (in reverse order so the latest appear
# the last in the console) and print them with format:
# "[hh:mm] Sender: Message"
for msg in reversed(messages):
# Note how we access .sender here. Since we made an
# API call using the self client, it will always have
# information about the sender. This is different to
# events, where Telegram may not always send the user.
name = get_display_name(msg.sender)
# Format the message content
if getattr(msg, 'media', None):
self.found_media[msg.id] = msg
content = '<{}> {}'.format(
type(msg.media).__name__, msg.message)
elif hasattr(msg, 'message'):
content = msg.message
elif hasattr(msg, 'action'):
content = str(msg.action)
else:
# Unknown message, simply print its class name
content = type(msg).__name__
# And print it to the user
sprint('[{}:{}] (ID={}) {}: {}'.format(
msg.date.hour, msg.date.minute, msg.id, name, content))
# Send photo
elif msg.startswith('!up '):
# Slice the message to get the path
path = msg[len('!up '):]
await self.send_photo(path=path, entity=entity)
# Send file (document)
elif msg.startswith('!uf '):
# Slice the message to get the path
path = msg[len('!uf '):]
await self.send_document(path=path, entity=entity)
# Delete messages
elif msg.startswith('!d '):
# Slice the message to get message ID
msg = msg[len('!d '):]
deleted_msg = await self.delete_messages(entity, msg)
print('Deleted {}'.format(deleted_msg))
# Download media
elif msg.startswith('!dm '):
# Slice the message to get message ID
await self.download_media_by_id(msg[len('!dm '):])
# Download profile photo
elif msg == '!dp':
print('Downloading profile picture to usermedia/...')
os.makedirs('usermedia', exist_ok=True)
output = await self.download_profile_photo(entity,
'usermedia')
if output:
print('Profile picture downloaded to', output)
else:
print('No profile picture found for this user!')
elif msg == '!i':
attributes = list(entity.to_dict().items())
pad = max(len(x) for x, _ in attributes)
for name, val in attributes:
print("{:<{width}} : {}".format(name, val, width=pad))
# Send chat message (if any)
elif msg:
await self.send_message(entity, msg, link_preview=False)
async def send_photo(self, path, entity):
"""Sends the file located at path to the desired entity as a photo"""
await self.send_file(
entity, path,
progress_callback=self.upload_progress_callback
)
print('Photo sent!')
async def send_document(self, path, entity):
"""Sends the file located at path to the desired entity as a document"""
await self.send_file(
entity, path,
force_document=True,
progress_callback=self.upload_progress_callback
)
print('Document sent!')
async def download_media_by_id(self, media_id):
"""Given a message ID, finds the media this message contained and
downloads it.
"""
try:
msg = self.found_media[int(media_id)]
except (ValueError, KeyError):
# ValueError when parsing, KeyError when accessing dictionary
print('Invalid media ID given or message not found!')
return
print('Downloading media to usermedia/...')
os.makedirs('usermedia', exist_ok=True)
output = await self.download_media(
msg.media,
file='usermedia/',
progress_callback=self.download_progress_callback
)
print('Media downloaded to {}!'.format(output))
@staticmethod
def download_progress_callback(downloaded_bytes, total_bytes):
InteractiveTelegramClient.print_progress(
'Downloaded', downloaded_bytes, total_bytes
)
@staticmethod
def upload_progress_callback(uploaded_bytes, total_bytes):
InteractiveTelegramClient.print_progress(
'Uploaded', uploaded_bytes, total_bytes
)
@staticmethod
def print_progress(progress_type, downloaded_bytes, total_bytes):
print('{} {} out of {} ({:.2%})'.format(
progress_type, bytes_to_string(downloaded_bytes),
bytes_to_string(total_bytes), downloaded_bytes / total_bytes)
)
async def message_handler(self, event):
"""Callback method for received events.NewMessage"""
# Note that message_handler is called when a Telegram update occurs
# and an event is created. Telegram may not always send information
# about the ``.sender`` or the ``.chat``, so if you *really* want it
# you should use ``get_chat()`` and ``get_sender()`` while working
# with events. Since they are methods, you know they may make an API
# call, which can be expensive.
chat = await event.get_chat()
if event.is_group:
if event.out:
sprint('>> sent "{}" to chat {}'.format(
event.text, get_display_name(chat)
))
else:
sprint('<< {} @ {} sent "{}"'.format(
get_display_name(await event.get_sender()),
get_display_name(chat),
event.text
))
else:
if event.out:
sprint('>> "{}" to user {}'.format(
event.text, get_display_name(chat)
))
else:
sprint('<< {} sent "{}"'.format(
get_display_name(chat), event.text
))
|
class InteractiveTelegramClient(TelegramClient):
'''Full featured Telegram client, meant to be used on an interactive
session to see what Telethon is capable off -
This client allows the user to perform some basic interaction with
Telegram through Telethon, such as listing dialogs (open chats),
talking to people, downloading media, and receiving updates.
'''
def __init__(self, session_user_id, api_id, api_hash,
proxy=None):
'''
Initializes the InteractiveTelegramClient.
:param session_user_id: Name of the *.session file.
:param api_id: Telegram's api_id acquired through my.telegram.org.
:param api_hash: Telegram's api_hash.
:param proxy: Optional proxy tuple/dictionary.
'''
pass
async def init(self):
pass
async def run(self):
'''Main loop of the TelegramClient, will wait for user action'''
pass
async def send_photo(self, path, entity):
'''Sends the file located at path to the desired entity as a photo'''
pass
async def send_document(self, path, entity):
'''Sends the file located at path to the desired entity as a document'''
pass
async def download_media_by_id(self, media_id):
'''Given a message ID, finds the media this message contained and
downloads it.
'''
pass
@staticmethod
def download_progress_callback(downloaded_bytes, total_bytes):
pass
@staticmethod
def upload_progress_callback(uploaded_bytes, total_bytes):
pass
@staticmethod
def print_progress(progress_type, downloaded_bytes, total_bytes):
pass
async def message_handler(self, event):
'''Callback method for received events.NewMessage'''
pass
| 14 | 7 | 31 | 3 | 18 | 9 | 4 | 0.52 | 1 | 11 | 2 | 0 | 7 | 1 | 10 | 10 | 328 | 44 | 187 | 38 | 172 | 97 | 131 | 34 | 120 | 26 | 2 | 5 | 43 |
146,757 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/setup.py
|
setup.TempWorkDir
|
class TempWorkDir:
"""Switches the working directory to be the one on which this file lives,
while within the 'with' block.
"""
def __init__(self, new=None):
self.original = None
self.new = new or str(Path(__file__).parent.resolve())
def __enter__(self):
# os.chdir does not work with Path in Python 3.5.x
self.original = str(Path('.').resolve())
os.makedirs(self.new, exist_ok=True)
os.chdir(self.new)
return self
def __exit__(self, *args):
os.chdir(self.original)
|
class TempWorkDir:
'''Switches the working directory to be the one on which this file lives,
while within the 'with' block.
'''
def __init__(self, new=None):
pass
def __enter__(self):
pass
def __exit__(self, *args):
pass
| 4 | 1 | 4 | 0 | 3 | 0 | 1 | 0.36 | 0 | 2 | 0 | 0 | 3 | 2 | 3 | 3 | 17 | 2 | 11 | 6 | 7 | 4 | 11 | 6 | 7 | 1 | 0 | 0 | 3 |
146,758 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/entitycache.py
|
telethon._updates.entitycache.EntityCache
|
class EntityCache:
def __init__(
self,
hash_map: dict = _sentinel,
self_id: int = None,
self_bot: bool = None
):
self.hash_map = {} if hash_map is _sentinel else hash_map
self.self_id = self_id
self.self_bot = self_bot
def set_self_user(self, id, bot, hash):
self.self_id = id
self.self_bot = bot
if hash:
self.hash_map[id] = (hash, EntityType.BOT if bot else EntityType.USER)
def get(self, id):
try:
hash, ty = self.hash_map[id]
return Entity(ty, id, hash)
except KeyError:
return None
def extend(self, users, chats):
# See https://core.telegram.org/api/min for "issues" with "min constructors".
self.hash_map.update(
(u.id, (
u.access_hash,
EntityType.BOT if u.bot else EntityType.USER,
))
for u in users
if getattr(u, 'access_hash', None) and not u.min
)
self.hash_map.update(
(c.id, (
c.access_hash,
EntityType.MEGAGROUP if c.megagroup else (
EntityType.GIGAGROUP if getattr(c, 'gigagroup', None) else EntityType.CHANNEL
),
))
for c in chats
if getattr(c, 'access_hash', None) and not getattr(c, 'min', None)
)
def get_all_entities(self):
return [Entity(ty, id, hash) for id, (hash, ty) in self.hash_map.items()]
def put(self, entity):
self.hash_map[entity.id] = (entity.hash, entity.ty)
def retain(self, filter):
self.hash_map = {k: v for k, v in self.hash_map.items() if filter(k)}
def __len__(self):
return len(self.hash_map)
|
class EntityCache:
def __init__(
self,
hash_map: dict = _sentinel,
self_id: int = None,
self_bot: bool = None
):
pass
def set_self_user(self, id, bot, hash):
pass
def get(self, id):
pass
def extend(self, users, chats):
pass
def get_all_entities(self):
pass
def put(self, entity):
pass
def retain(self, filter):
pass
def __len__(self):
pass
| 9 | 0 | 6 | 0 | 6 | 0 | 2 | 0.02 | 0 | 6 | 2 | 0 | 8 | 3 | 8 | 8 | 56 | 7 | 48 | 19 | 34 | 1 | 27 | 13 | 18 | 4 | 0 | 1 | 15 |
146,759 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.GapError
|
class GapError(ValueError):
def __repr__(self):
return 'GapError()'
|
class GapError(ValueError):
def __repr__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 12 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
146,760 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.MessageBox
|
class MessageBox:
__slots__ = ('_log', 'map', 'date', 'seq', 'next_deadline', 'possible_gaps', 'getting_diff_for')
def __init__(
self,
log,
# Map each entry to their current state.
map: dict = _sentinel, # entry -> state
# Additional fields beyond PTS needed by `ENTRY_ACCOUNT`.
date: datetime.datetime = epoch() + datetime.timedelta(seconds=1),
seq: int = NO_SEQ,
# Holds the entry with the closest deadline (optimization to avoid recalculating the minimum deadline).
next_deadline: object = None, # entry
# Which entries have a gap and may soon trigger a need to get difference.
#
# If a gap is found, stores the required information to resolve it (when should it timeout and what updates
# should be held in case the gap is resolved on its own).
#
# Not stored directly in `map` as an optimization (else we would need another way of knowing which entries have
# a gap in them).
possible_gaps: dict = _sentinel, # entry -> possiblegap
# For which entries are we currently getting difference.
getting_diff_for: set = _sentinel, # entry
):
self._log = log
self.map = {} if map is _sentinel else map
self.date = date
self.seq = seq
self.next_deadline = next_deadline
self.possible_gaps = {} if possible_gaps is _sentinel else possible_gaps
self.getting_diff_for = set() if getting_diff_for is _sentinel else getting_diff_for
if __debug__:
self._trace('MessageBox initialized')
def _trace(self, msg, *args, **kwargs):
# Calls to trace can't really be removed beforehand without some dark magic.
# So every call to trace is prefixed with `if __debug__`` instead, to remove
# it when using `python -O`. Probably unnecessary, but it's nice to avoid
# paying the cost for something that is not used.
self._log.log(LOG_LEVEL_TRACE, 'Current MessageBox state: seq = %r, date = %s, map = %r',
self.seq, self.date.isoformat(), self.map)
self._log.log(LOG_LEVEL_TRACE, msg, *args, **kwargs)
# region Creation, querying, and setting base state.
def load(self, session_state, channel_states):
"""
Create a [`MessageBox`] from a previously known update state.
"""
if __debug__:
self._trace('Loading MessageBox with session_state = %r, channel_states = %r', session_state, channel_states)
deadline = next_updates_deadline()
self.map.clear()
if session_state.pts != NO_SEQ:
self.map[ENTRY_ACCOUNT] = State(pts=session_state.pts, deadline=deadline)
if session_state.qts != NO_SEQ:
self.map[ENTRY_SECRET] = State(pts=session_state.qts, deadline=deadline)
self.map.update((s.channel_id, State(pts=s.pts, deadline=deadline)) for s in channel_states)
self.date = datetime.datetime.fromtimestamp(session_state.date, tz=datetime.timezone.utc)
self.seq = session_state.seq
self.next_deadline = ENTRY_ACCOUNT
def session_state(self):
"""
Return the current state.
This should be used for persisting the state.
"""
return dict(
pts=self.map[ENTRY_ACCOUNT].pts if ENTRY_ACCOUNT in self.map else NO_SEQ,
qts=self.map[ENTRY_SECRET].pts if ENTRY_SECRET in self.map else NO_SEQ,
date=self.date,
seq=self.seq,
), {id: state.pts for id, state in self.map.items() if isinstance(id, int)}
def is_empty(self) -> bool:
"""
Return true if the message box is empty and has no state yet.
"""
return ENTRY_ACCOUNT not in self.map
def check_deadlines(self):
"""
Return the next deadline when receiving updates should timeout.
If a deadline expired, the corresponding entries will be marked as needing to get its difference.
While there are entries pending of getting their difference, this method returns the current instant.
"""
now = get_running_loop().time()
if self.getting_diff_for:
return now
deadline = next_updates_deadline()
# Most of the time there will be zero or one gap in flight so finding the minimum is cheap.
if self.possible_gaps:
deadline = min(deadline, *(gap.deadline for gap in self.possible_gaps.values()))
elif self.next_deadline in self.map:
deadline = min(deadline, self.map[self.next_deadline].deadline)
# asyncio's loop time precision only seems to be about 3 decimal places, so it's possible that
# we find the same number again on repeated calls. Without the "or equal" part we would log the
# timeout for updates several times (it also makes sense to get difference if now is the deadline).
if now >= deadline:
# Check all expired entries and add them to the list that needs getting difference.
self.getting_diff_for.update(entry for entry, gap in self.possible_gaps.items() if now >= gap.deadline)
self.getting_diff_for.update(entry for entry, state in self.map.items() if now >= state.deadline)
if __debug__:
self._trace('Deadlines met, now getting diff for %r', self.getting_diff_for)
# When extending `getting_diff_for`, it's important to have the moral equivalent of
# `begin_get_diff` (that is, clear possible gaps if we're now getting difference).
for entry in self.getting_diff_for:
self.possible_gaps.pop(entry, None)
return deadline
# Reset the deadline for the periods without updates for the given entries.
#
# It also updates the next deadline time to reflect the new closest deadline.
def reset_deadlines(self, entries, deadline):
if not entries:
return
for entry in entries:
if entry not in self.map:
raise RuntimeError('Called reset_deadline on an entry for which we do not have state')
self.map[entry].deadline = deadline
if self.next_deadline in entries:
# If the updated deadline was the closest one, recalculate the new minimum.
self.next_deadline = min(self.map.items(), key=lambda entry_state: entry_state[1].deadline)[0]
elif self.next_deadline in self.map and deadline < self.map[self.next_deadline].deadline:
# If the updated deadline is smaller than the next deadline, change the next deadline to be the new one.
# Any entry will do, so the one from the last iteration is fine.
self.next_deadline = entry
# else an unrelated deadline was updated, so the closest one remains unchanged.
# Convenience to reset a channel's deadline, with optional timeout.
def reset_channel_deadline(self, channel_id, timeout):
self.reset_deadlines({channel_id}, get_running_loop().time() + (timeout or NO_UPDATES_TIMEOUT))
# Sets the update state.
#
# Should be called right after login if [`MessageBox::new`] was used, otherwise undesirable
# updates will be fetched.
def set_state(self, state, reset=True):
if __debug__:
self._trace('Setting state %s', state)
deadline = next_updates_deadline()
if state.pts != NO_SEQ or not reset:
self.map[ENTRY_ACCOUNT] = State(pts=state.pts, deadline=deadline)
else:
self.map.pop(ENTRY_ACCOUNT, None)
# Telegram seems to use the `qts` for bot accounts, but while applying difference,
# it might be reset back to 0. See issue #3873 for more details.
#
# During login, a value of zero would mean the `pts` is unknown,
# so the map shouldn't contain that entry.
# But while applying difference, if the value is zero, it (probably)
# truly means that's what should be used (hence the `reset` flag).
if state.qts != NO_SEQ or not reset:
self.map[ENTRY_SECRET] = State(pts=state.qts, deadline=deadline)
else:
self.map.pop(ENTRY_SECRET, None)
self.date = state.date
self.seq = state.seq
# Like [`MessageBox::set_state`], but for channels. Useful when getting dialogs.
#
# The update state will only be updated if no entry was known previously.
def try_set_channel_state(self, id, pts):
if __debug__:
self._trace('Trying to set channel state for %r: %r', id, pts)
if id not in self.map:
self.map[id] = State(pts=pts, deadline=next_updates_deadline())
# Try to begin getting difference for the given entry.
# Fails if the entry does not have a previously-known state that can be used to get its difference.
#
# Clears any previous gaps.
def try_begin_get_diff(self, entry, reason):
if entry not in self.map:
# Won't actually be able to get difference for this entry if we don't have a pts to start off from.
if entry in self.possible_gaps:
raise RuntimeError('Should not have a possible_gap for an entry not in the state map')
if __debug__:
self._trace('Should get difference for %r because %s but cannot due to missing hash', entry, reason)
return
if __debug__:
self._trace('Marking %r as needing difference because %s', entry, reason)
self.getting_diff_for.add(entry)
self.possible_gaps.pop(entry, None)
# Finish getting difference for the given entry.
#
# It also resets the deadline.
def end_get_diff(self, entry):
try:
self.getting_diff_for.remove(entry)
except KeyError:
raise RuntimeError('Called end_get_diff on an entry which was not getting diff for')
self.reset_deadlines({entry}, next_updates_deadline())
assert entry not in self.possible_gaps, "gaps shouldn't be created while getting difference"
# endregion Creation, querying, and setting base state.
# region "Normal" updates flow (processing and detection of gaps).
# Process an update and return what should be done with it.
#
# Updates corresponding to entries for which their difference is currently being fetched
# will be ignored. While according to the [updates' documentation]:
#
# > Implementations [have] to postpone updates received via the socket while
# > filling gaps in the event and `Update` sequences, as well as avoid filling
# > gaps in the same sequence.
#
# In practice, these updates should have also been retrieved through getting difference.
#
# [updates documentation] https://core.telegram.org/api/updates
def process_updates(
self,
updates,
chat_hashes,
result, # out list of updates; returns list of user, chat, or raise if gap
):
# v1 has never sent updates produced by the client itself to the handlers.
# However proper update handling requires those to be processed.
# This is an ugly workaround for that.
self_outgoing = getattr(updates, '_self_outgoing', False)
real_result = result
result = []
date = getattr(updates, 'date', None)
seq = getattr(updates, 'seq', None)
seq_start = getattr(updates, 'seq_start', None)
users = getattr(updates, 'users', None) or []
chats = getattr(updates, 'chats', None) or []
if __debug__:
self._trace('Processing updates with seq = %r, seq_start = %r, date = %s: %s',
seq, seq_start, date.isoformat() if date else None, updates)
if date is None:
# updatesTooLong is the only one with no date (we treat it as a gap)
self.try_begin_get_diff(ENTRY_ACCOUNT, 'received updatesTooLong')
raise GapError
if seq is None:
seq = NO_SEQ
if seq_start is None:
seq_start = seq
# updateShort is the only update which cannot be dispatched directly but doesn't have 'updates' field
updates = getattr(updates, 'updates', None) or [updates.update if isinstance(updates, tl.UpdateShort) else updates]
for u in updates:
u._self_outgoing = self_outgoing
# > For all the other [not `updates` or `updatesCombined`] `Updates` type constructors
# > there is no need to check `seq` or change a local state.
if seq_start != NO_SEQ:
if self.seq + 1 > seq_start:
# Skipping updates that were already handled
if __debug__:
self._trace('Skipping updates as they should have already been handled')
return (users, chats)
elif self.seq + 1 < seq_start:
# Gap detected
self.try_begin_get_diff(ENTRY_ACCOUNT, 'detected gap')
raise GapError
# else apply
def _sort_gaps(update):
pts = PtsInfo.from_update(update)
return pts.pts - pts.pts_count if pts else 0
reset_deadlines = set() # temporary buffer
any_pts_applied = [False] # using a list to pass "by reference"
result.extend(filter(None, (
self.apply_pts_info(u, reset_deadlines=reset_deadlines, any_pts_applied=any_pts_applied)
# Telegram can send updates out of order (e.g. ReadChannelInbox first
# and then NewChannelMessage, both with the same pts, but the count is
# 0 and 1 respectively), so we sort them first.
for u in sorted(updates, key=_sort_gaps))))
# > If the updates were applied, local *Updates* state must be updated
# > with `seq` (unless it's 0) and `date` from the constructor.
#
# By "were applied", we assume it means "some other pts was applied".
# Updates which can be applied in any order, such as `UpdateChat`,
# should not cause `seq` to be updated (or upcoming updates such as
# `UpdateChatParticipant` could be missed).
if any_pts_applied[0]:
if __debug__:
self._trace('Updating seq as local pts was updated too')
if date != epoch():
self.date = date
if seq != NO_SEQ:
self.seq = seq
self.reset_deadlines(reset_deadlines, next_updates_deadline())
if self.possible_gaps:
if __debug__:
self._trace('Trying to re-apply %r possible gaps', len(self.possible_gaps))
# For each update in possible gaps, see if the gap has been resolved already.
for key in list(self.possible_gaps.keys()):
self.possible_gaps[key].updates.sort(key=_sort_gaps)
for _ in range(len(self.possible_gaps[key].updates)):
update = self.possible_gaps[key].updates.pop(0)
# If this fails to apply, it will get re-inserted at the end.
# All should fail, so the order will be preserved (it would've cycled once).
update = self.apply_pts_info(update, reset_deadlines=None)
if update:
result.append(update)
if __debug__:
self._trace('Resolved gap with %r: %s', PtsInfo.from_update(update), update)
# Clear now-empty gaps.
self.possible_gaps = {entry: gap for entry, gap in self.possible_gaps.items() if gap.updates}
real_result.extend(u for u in result if not u._self_outgoing)
return (users, chats)
# Tries to apply the input update if its `PtsInfo` follows the correct order.
#
# If the update can be applied, it is returned; otherwise, the update is stored in a
# possible gap (unless it was already handled or would be handled through getting
# difference) and `None` is returned.
def apply_pts_info(
self,
update,
*,
reset_deadlines,
any_pts_applied=[True], # mutable default is fine as it's write-only
):
# This update means we need to call getChannelDifference to get the updates from the channel
if isinstance(update, tl.UpdateChannelTooLong):
self.try_begin_get_diff(update.channel_id, 'received updateChannelTooLong')
return None
pts = PtsInfo.from_update(update)
if not pts:
# No pts means that the update can be applied in any order.
if __debug__:
self._trace('No pts in update, so it can be applied in any order: %s', update)
return update
# As soon as we receive an update of any form related to messages (has `PtsInfo`),
# the "no updates" period for that entry is reset.
#
# Build the `HashSet` to avoid calling `reset_deadline` more than once for the same entry.
#
# By the time this method returns, self.map will have an entry for which we can reset its deadline.
if reset_deadlines:
reset_deadlines.add(pts.entry)
if pts.entry in self.getting_diff_for:
# Note: early returning here also prevents gap from being inserted (which they should
# not be while getting difference).
if __debug__:
self._trace('Skipping update with %r as its difference is being fetched', pts)
return None
if pts.entry in self.map:
local_pts = self.map[pts.entry].pts
if local_pts + pts.pts_count > pts.pts:
# Ignore
if __debug__:
self._trace('Skipping update since local pts %r > %r: %s', local_pts, pts, update)
return None
elif local_pts + pts.pts_count < pts.pts:
# Possible gap
# TODO store chats too?
if __debug__:
self._trace('Possible gap since local pts %r < %r: %s', local_pts, pts, update)
if pts.entry not in self.possible_gaps:
self.possible_gaps[pts.entry] = PossibleGap(
deadline=get_running_loop().time() + POSSIBLE_GAP_TIMEOUT,
updates=[]
)
self.possible_gaps[pts.entry].updates.append(update)
return None
else:
# Apply
any_pts_applied[0] = True
if __debug__:
self._trace('Applying update pts since local pts %r = %r: %s', local_pts, pts, update)
# In a channel, we may immediately receive:
# * ReadChannelInbox (pts = X, pts_count = 0)
# * NewChannelMessage (pts = X, pts_count = 1)
#
# Notice how both `pts` are the same. If they were to be applied out of order, the first
# one however would've triggered a gap because `local_pts` + `pts_count` of 0 would be
# less than `remote_pts`. So there is no risk by setting the `local_pts` to match the
# `remote_pts` here of missing the new message.
#
# The message would however be lost if we initialized the pts with the first one, since
# the second one would appear "already handled". To prevent this we set the pts to be
# one less when the count is 0 (which might be wrong and trigger a gap later on, but is
# unlikely). This will prevent us from losing updates in the unlikely scenario where these
# two updates arrive in different packets (and therefore couldn't be sorted beforehand).
if pts.entry in self.map:
self.map[pts.entry].pts = pts.pts
else:
# When a chat is migrated to a megagroup, the first update can be a `ReadChannelInbox`
# with `pts = 1, pts_count = 0` followed by a `NewChannelMessage` with `pts = 2, pts_count=1`.
# Note how the `pts` for the message is 2 and not 1 unlike the case described before!
# This is likely because the `pts` cannot be 0 (or it would fail with PERSISTENT_TIMESTAMP_EMPTY),
# which forces the first update to be 1. But if we got difference with 1 and the second update
# also used 1, we would miss it, so Telegram probably uses 2 to work around that.
self.map[pts.entry] = State(
pts=(pts.pts - (0 if pts.pts_count else 1)) or 1,
deadline=next_updates_deadline()
)
return update
# endregion "Normal" updates flow (processing and detection of gaps).
# region Getting and applying account difference.
# Return the request that needs to be made to get the difference, if any.
def get_difference(self):
for entry in (ENTRY_ACCOUNT, ENTRY_SECRET):
if entry in self.getting_diff_for:
if entry not in self.map:
raise RuntimeError('Should not try to get difference for an entry without known state')
gd = fn.updates.GetDifferenceRequest(
pts=self.map[ENTRY_ACCOUNT].pts,
pts_total_limit=None,
date=self.date,
qts=self.map[ENTRY_SECRET].pts if ENTRY_SECRET in self.map else NO_SEQ,
)
if __debug__:
self._trace('Requesting account difference %s', gd)
return gd
return None
# Similar to [`MessageBox::process_updates`], but using the result from getting difference.
def apply_difference(
self,
diff,
chat_hashes,
):
if __debug__:
self._trace('Applying account difference %s', diff)
finish = None
result = None
if isinstance(diff, tl.updates.DifferenceEmpty):
finish = True
self.date = diff.date
self.seq = diff.seq
result = [], [], []
elif isinstance(diff, tl.updates.Difference):
finish = True
chat_hashes.extend(diff.users, diff.chats)
result = self.apply_difference_type(diff, chat_hashes)
elif isinstance(diff, tl.updates.DifferenceSlice):
finish = False
chat_hashes.extend(diff.users, diff.chats)
result = self.apply_difference_type(diff, chat_hashes)
elif isinstance(diff, tl.updates.DifferenceTooLong):
finish = True
self.map[ENTRY_ACCOUNT].pts = diff.pts # the deadline will be reset once the diff ends
result = [], [], []
if finish:
account = ENTRY_ACCOUNT in self.getting_diff_for
secret = ENTRY_SECRET in self.getting_diff_for
if not account and not secret:
raise RuntimeError('Should not be applying the difference when neither account or secret was diff was active')
# Both may be active if both expired at the same time.
if account:
self.end_get_diff(ENTRY_ACCOUNT)
if secret:
self.end_get_diff(ENTRY_SECRET)
return result
def apply_difference_type(
self,
diff,
chat_hashes,
):
state = getattr(diff, 'intermediate_state', None) or diff.state
self.set_state(state, reset=False)
# diff.other_updates can contain things like UpdateChannelTooLong and UpdateNewChannelMessage.
# We need to process those as if they were socket updates to discard any we have already handled.
updates = []
self.process_updates(tl.Updates(
updates=diff.other_updates,
users=diff.users,
chats=diff.chats,
date=epoch(),
seq=NO_SEQ, # this way date is not used
), chat_hashes, updates)
updates.extend(tl.UpdateNewMessage(
message=m,
pts=NO_SEQ,
pts_count=NO_SEQ,
) for m in diff.new_messages)
updates.extend(tl.UpdateNewEncryptedMessage(
message=m,
qts=NO_SEQ,
) for m in diff.new_encrypted_messages)
return updates, diff.users, diff.chats
def end_difference(self):
if __debug__:
self._trace('Ending account difference')
account = ENTRY_ACCOUNT in self.getting_diff_for
secret = ENTRY_SECRET in self.getting_diff_for
if not account and not secret:
raise RuntimeError('Should not be ending get difference when neither account or secret was diff was active')
# Both may be active if both expired at the same time.
if account:
self.end_get_diff(ENTRY_ACCOUNT)
if secret:
self.end_get_diff(ENTRY_SECRET)
# endregion Getting and applying account difference.
# region Getting and applying channel difference.
# Return the request that needs to be made to get a channel's difference, if any.
def get_channel_difference(
self,
chat_hashes,
):
entry = next((id for id in self.getting_diff_for if isinstance(id, int)), None)
if not entry:
return None
packed = chat_hashes.get(entry)
if not packed:
# Cannot get channel difference as we're missing its hash
# TODO we should probably log this
self.end_get_diff(entry)
# Remove the outdated `pts` entry from the map so that the next update can correct
# it. Otherwise, it will spam that the access hash is missing.
self.map.pop(entry, None)
return None
state = self.map.get(entry)
if not state:
raise RuntimeError('Should not try to get difference for an entry without known state')
gd = fn.updates.GetChannelDifferenceRequest(
force=False,
channel=tl.InputChannel(packed.id, packed.hash),
filter=tl.ChannelMessagesFilterEmpty(),
pts=state.pts,
limit=BOT_CHANNEL_DIFF_LIMIT if chat_hashes.self_bot else USER_CHANNEL_DIFF_LIMIT
)
if __debug__:
self._trace('Requesting channel difference %s', gd)
return gd
# Similar to [`MessageBox::process_updates`], but using the result from getting difference.
def apply_channel_difference(
self,
request,
diff,
chat_hashes,
):
entry = request.channel.channel_id
if __debug__:
self._trace('Applying channel difference for %r: %s', entry, diff)
self.possible_gaps.pop(entry, None)
if isinstance(diff, tl.updates.ChannelDifferenceEmpty):
assert diff.final
self.end_get_diff(entry)
self.map[entry].pts = diff.pts
return [], [], []
elif isinstance(diff, tl.updates.ChannelDifferenceTooLong):
assert diff.final
self.map[entry].pts = diff.dialog.pts
chat_hashes.extend(diff.users, diff.chats)
self.reset_channel_deadline(entry, diff.timeout)
# This `diff` has the "latest messages and corresponding chats", but it would
# be strange to give the user only partial changes of these when they would
# expect all updates to be fetched. Instead, nothing is returned.
return [], [], []
elif isinstance(diff, tl.updates.ChannelDifference):
if diff.final:
self.end_get_diff(entry)
self.map[entry].pts = diff.pts
chat_hashes.extend(diff.users, diff.chats)
updates = []
self.process_updates(tl.Updates(
updates=diff.other_updates,
users=diff.users,
chats=diff.chats,
date=epoch(),
seq=NO_SEQ, # this way date is not used
), chat_hashes, updates)
updates.extend(tl.UpdateNewChannelMessage(
message=m,
pts=NO_SEQ,
pts_count=NO_SEQ,
) for m in diff.new_messages)
self.reset_channel_deadline(entry, None)
return updates, diff.users, diff.chats
def end_channel_difference(self, request, reason: PrematureEndReason, chat_hashes):
entry = request.channel.channel_id
if __debug__:
self._trace('Ending channel difference for %r because %s', entry, reason)
if reason == PrematureEndReason.TEMPORARY_SERVER_ISSUES:
# Temporary issues. End getting difference without updating the pts so we can retry later.
self.possible_gaps.pop(entry, None)
self.end_get_diff(entry)
elif reason == PrematureEndReason.BANNED:
# Banned in the channel. Forget its state since we can no longer fetch updates from it.
self.possible_gaps.pop(entry, None)
self.end_get_diff(entry)
del self.map[entry]
else:
raise RuntimeError('Unknown reason to end channel difference')
|
class MessageBox:
def __init__(
self,
log,
# Map each entry to their current state.
map: dict = _sentinel, # entry -> state
# Additional fields beyond PTS needed by `ENTRY_ACCOUNT`.
date: datetime.datetime = epoch() + datetime.timedelta(seconds=1),
seq:
pass
def _trace(self, msg, *args, **kwargs):
pass
def load(self, session_state, channel_states):
'''
Create a [`MessageBox`] from a previously known update state.
'''
pass
def session_state(self):
'''
Return the current state.
This should be used for persisting the state.
'''
pass
def is_empty(self) -> bool:
'''
Return true if the message box is empty and has no state yet.
'''
pass
def check_deadlines(self):
'''
Return the next deadline when receiving updates should timeout.
If a deadline expired, the corresponding entries will be marked as needing to get its difference.
While there are entries pending of getting their difference, this method returns the current instant.
'''
pass
def reset_deadlines(self, entries, deadline):
pass
def reset_channel_deadline(self, channel_id, timeout):
pass
def set_state(self, state, reset=True):
pass
def try_set_channel_state(self, id, pts):
pass
def try_begin_get_diff(self, entry, reason):
pass
def end_get_diff(self, entry):
pass
def process_updates(
self,
updates,
chat_hashes,
result, # out list of updates; returns list of user, chat, or raise if gap
):
pass
def _sort_gaps(update):
pass
def apply_pts_info(
self,
update,
*,
reset_deadlines,
any_pts_applied=[True], # mutable default is fine as it's write-only
):
pass
def get_difference(self):
pass
def apply_difference(
self,
diff,
chat_hashes,
):
pass
def apply_difference_type(
self,
diff,
chat_hashes,
):
pass
def end_difference(self):
pass
def get_channel_difference(
self,
chat_hashes,
):
pass
def apply_channel_difference(
self,
request,
diff,
chat_hashes,
):
pass
def end_channel_difference(self, request, reason: PrematureEndReason, chat_hashes):
pass
| 23 | 4 | 27 | 3 | 18 | 6 | 5 | 0.45 | 0 | 18 | 5 | 0 | 21 | 7 | 21 | 21 | 665 | 104 | 395 | 107 | 336 | 177 | 295 | 69 | 272 | 22 | 0 | 5 | 120 |
146,761 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.PossibleGap
|
class PossibleGap:
__slots__ = ('deadline', 'updates')
def __init__(
self,
deadline: float,
# Pending updates (those with a larger PTS, producing the gap which may later be filled).
updates: list # of updates
):
self.deadline = deadline
self.updates = updates
def __repr__(self):
return f'PossibleGap(deadline={self.deadline}, update_count={len(self.updates)})'
|
class PossibleGap:
def __init__(
self,
deadline: float,
# Pending updates (those with a larger PTS, producing the gap which may later be filled).
updates:
pass
def __repr__(self):
pass
| 3 | 0 | 5 | 0 | 5 | 1 | 1 | 0.18 | 0 | 2 | 0 | 0 | 2 | 2 | 2 | 2 | 14 | 2 | 11 | 10 | 4 | 2 | 7 | 6 | 4 | 1 | 0 | 0 | 2 |
146,762 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/messagebox.py
|
telethon._updates.messagebox.PrematureEndReason
|
class PrematureEndReason(Enum):
TEMPORARY_SERVER_ISSUES = 'tmp'
BANNED = 'ban'
|
class PrematureEndReason(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
146,763 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/_updates/session.py
|
telethon._updates.session.ChannelState
|
class ChannelState:
"""
Stores the information needed to fetch updates from a channel.
* channel_id: 64-bit number representing the channel identifier.
* pts: 64-bit number holding the state needed to fetch updates.
"""
__slots__ = ('channel_id', 'pts')
def __init__(
self,
channel_id: int,
pts: int,
):
self.channel_id = channel_id
self.pts = pts
def __repr__(self):
return repr({k: getattr(self, k) for k in self.__slots__})
|
class ChannelState:
'''
Stores the information needed to fetch updates from a channel.
* channel_id: 64-bit number representing the channel identifier.
* pts: 64-bit number holding the state needed to fetch updates.
'''
def __init__(
self,
channel_id: int,
pts: int,
):
pass
def __repr__(self):
pass
| 3 | 1 | 5 | 0 | 5 | 0 | 1 | 0.45 | 0 | 1 | 0 | 0 | 2 | 2 | 2 | 2 | 19 | 3 | 11 | 10 | 4 | 5 | 7 | 6 | 4 | 1 | 0 | 0 | 2 |
146,764 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/errors/common.py
|
telethon.errors.common.InvalidChecksumError
|
class InvalidChecksumError(Exception):
"""
Occurs when using the TCP full mode and the checksum of a received
packet doesn't match the expected checksum.
"""
def __init__(self, checksum, valid_checksum):
super().__init__(
'Invalid checksum ({} when {} was expected). '
'This packet should be skipped.'
.format(checksum, valid_checksum))
self.checksum = checksum
self.valid_checksum = valid_checksum
|
class InvalidChecksumError(Exception):
'''
Occurs when using the TCP full mode and the checksum of a received
packet doesn't match the expected checksum.
'''
def __init__(self, checksum, valid_checksum):
pass
| 2 | 1 | 8 | 1 | 7 | 0 | 1 | 0.5 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 11 | 13 | 1 | 8 | 4 | 6 | 4 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
146,765 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/chats.py
|
telethon.client.chats._ProfilePhotoIter
|
class _ProfilePhotoIter(RequestIter):
async def _init(
self, entity, offset, max_id
):
entity = await self.client.get_input_entity(entity)
ty = helpers._entity_type(entity)
if ty == helpers._EntityType.USER:
self.request = functions.photos.GetUserPhotosRequest(
entity,
offset=offset,
max_id=max_id,
limit=1
)
else:
self.request = functions.messages.SearchRequest(
peer=entity,
q='',
filter=types.InputMessagesFilterChatPhotos(),
min_date=None,
max_date=None,
offset_id=0,
add_offset=offset,
limit=1,
max_id=max_id,
min_id=0,
hash=0
)
if self.limit == 0:
self.request.limit = 1
result = await self.client(self.request)
if isinstance(result, types.photos.Photos):
self.total = len(result.photos)
elif isinstance(result, types.messages.Messages):
self.total = len(result.messages)
else:
# Luckily both photosSlice and messages have a count for total
self.total = getattr(result, 'count', None)
async def _load_next_chunk(self):
self.request.limit = min(self.left, _MAX_PROFILE_PHOTO_CHUNK_SIZE)
result = await self.client(self.request)
if isinstance(result, types.photos.Photos):
self.buffer = result.photos
self.left = len(self.buffer)
self.total = len(self.buffer)
elif isinstance(result, types.messages.Messages):
self.buffer = [x.action.photo for x in result.messages
if isinstance(x.action, types.MessageActionChatEditPhoto)]
self.left = len(self.buffer)
self.total = len(self.buffer)
elif isinstance(result, types.photos.PhotosSlice):
self.buffer = result.photos
self.total = result.count
if len(self.buffer) < self.request.limit:
self.left = len(self.buffer)
else:
self.request.offset += len(result.photos)
else:
# Some broadcast channels have a photo that this request doesn't
# retrieve for whatever random reason the Telegram server feels.
#
# This means the `total` count may be wrong but there's not much
# that can be done around it (perhaps there are too many photos
# and this is only a partial result so it's not possible to just
# use the len of the result).
self.total = getattr(result, 'count', None)
# Unconditionally fetch the full channel to obtain this photo and
# yield it with the rest (unless it's a duplicate).
seen_id = None
if isinstance(result, types.messages.ChannelMessages):
channel = await self.client(functions.channels.GetFullChannelRequest(self.request.peer))
photo = channel.full_chat.chat_photo
if isinstance(photo, types.Photo):
self.buffer.append(photo)
seen_id = photo.id
self.buffer.extend(
x.action.photo for x in result.messages
if isinstance(x.action, types.MessageActionChatEditPhoto)
and x.action.photo.id != seen_id
)
if len(result.messages) < self.request.limit:
self.left = len(self.buffer)
elif result.messages:
self.request.add_offset = 0
self.request.offset_id = result.messages[-1].id
|
class _ProfilePhotoIter(RequestIter):
async def _init(
self, entity, offset, max_id
):
pass
async def _load_next_chunk(self):
pass
| 3 | 0 | 45 | 3 | 37 | 5 | 7 | 0.14 | 1 | 1 | 1 | 0 | 2 | 4 | 2 | 31 | 91 | 7 | 74 | 15 | 69 | 10 | 42 | 13 | 39 | 9 | 5 | 3 | 14 |
146,766 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/dialogs.py
|
telethon.client.dialogs._DialogsIter
|
class _DialogsIter(RequestIter):
async def _init(
self, offset_date, offset_id, offset_peer, ignore_pinned, ignore_migrated, folder
):
self.request = functions.messages.GetDialogsRequest(
offset_date=offset_date,
offset_id=offset_id,
offset_peer=offset_peer,
limit=1,
hash=0,
exclude_pinned=ignore_pinned,
folder_id=folder
)
if self.limit <= 0:
# Special case, get a single dialog and determine count
dialogs = await self.client(self.request)
self.total = getattr(dialogs, 'count', len(dialogs.dialogs))
raise StopAsyncIteration
self.seen = set()
self.offset_date = offset_date
self.ignore_migrated = ignore_migrated
async def _load_next_chunk(self):
self.request.limit = min(self.left, _MAX_CHUNK_SIZE)
r = await self.client(self.request)
self.total = getattr(r, 'count', len(r.dialogs))
entities = {utils.get_peer_id(x): x
for x in itertools.chain(r.users, r.chats)
if not isinstance(x, (types.UserEmpty, types.ChatEmpty))}
self.client._mb_entity_cache.extend(r.users, r.chats)
messages = {}
for m in r.messages:
m._finish_init(self.client, entities, None)
messages[_dialog_message_key(m.peer_id, m.id)] = m
for d in r.dialogs:
# We check the offset date here because Telegram may ignore it
message = messages.get(_dialog_message_key(d.peer, d.top_message))
if self.offset_date:
date = getattr(message, 'date', None)
if not date or date.timestamp() > self.offset_date.timestamp():
continue
peer_id = utils.get_peer_id(d.peer)
if peer_id not in self.seen:
self.seen.add(peer_id)
if peer_id not in entities:
# > In which case can a UserEmpty appear in the list of banned members?
# > In a very rare cases. This is possible but isn't an expected behavior.
# Real world example: https://t.me/TelethonChat/271471
continue
cd = custom.Dialog(self.client, d, entities, message)
if cd.dialog.pts:
self.client._message_box.try_set_channel_state(
utils.get_peer_id(d.peer, add_mark=False), cd.dialog.pts)
if not self.ignore_migrated or getattr(
cd.entity, 'migrated_to', None) is None:
self.buffer.append(cd)
if not self.buffer or len(r.dialogs) < self.request.limit\
or not isinstance(r, types.messages.DialogsSlice):
# Buffer being empty means all returned dialogs were skipped (due to offsets).
# Less than we requested means we reached the end, or
# we didn't get a DialogsSlice which means we got all.
return True
# We can't use `messages[-1]` as the offset ID / date.
# Why? Because pinned dialogs will mess with the order
# in this list. Instead, we find the last dialog which
# has a message, and use it as an offset.
last_message = next(filter(None, (
messages.get(_dialog_message_key(d.peer, d.top_message))
for d in reversed(r.dialogs)
)), None)
self.request.exclude_pinned = True
self.request.offset_id = last_message.id if last_message else 0
self.request.offset_date = last_message.date if last_message else None
self.request.offset_peer = self.buffer[-1].input_entity
|
class _DialogsIter(RequestIter):
async def _init(
self, offset_date, offset_id, offset_peer, ignore_pinned, ignore_migrated, folder
):
pass
async def _load_next_chunk(self):
pass
| 3 | 0 | 43 | 7 | 30 | 6 | 7 | 0.2 | 1 | 4 | 0 | 0 | 2 | 5 | 2 | 31 | 87 | 14 | 61 | 21 | 56 | 12 | 43 | 19 | 40 | 12 | 5 | 3 | 14 |
146,767 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/errors/common.py
|
telethon.errors.common.CdnFileTamperedError
|
class CdnFileTamperedError(SecurityError):
"""
Occurs when there's a hash mismatch between the decrypted CDN file
and its expected hash.
"""
def __init__(self):
super().__init__(
'The CDN file has been altered and its download cancelled.'
)
|
class CdnFileTamperedError(SecurityError):
'''
Occurs when there's a hash mismatch between the decrypted CDN file
and its expected hash.
'''
def __init__(self):
pass
| 2 | 1 | 4 | 0 | 4 | 0 | 1 | 0.8 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 12 | 9 | 0 | 5 | 2 | 3 | 4 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
146,768 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/errors/common.py
|
telethon.errors.common.BadMessageError
|
class BadMessageError(Exception):
"""Occurs when handling a bad_message_notification."""
ErrorMessages = {
16:
'msg_id too low (most likely, client time is wrong it would be '
'worthwhile to synchronize it using msg_id notifications and re-send '
'the original message with the "correct" msg_id or wrap it in a '
'container with a new msg_id if the original message had waited too '
'long on the client to be transmitted).',
17:
'msg_id too high (similar to the previous case, the client time has '
'to be synchronized, and the message re-sent with the correct msg_id).',
18:
'Incorrect two lower order msg_id bits (the server expects client '
'message msg_id to be divisible by 4).',
19:
'Container msg_id is the same as msg_id of a previously received '
'message (this must never happen).',
20:
'Message too old, and it cannot be verified whether the server has '
'received a message with this msg_id or not.',
32:
'msg_seqno too low (the server has already received a message with a '
'lower msg_id but with either a higher or an equal and odd seqno).',
33:
'msg_seqno too high (similarly, there is a message with a higher '
'msg_id but with either a lower or an equal and odd seqno).',
34:
'An even msg_seqno expected (irrelevant message), but odd received.',
35:
'Odd msg_seqno expected (relevant message), but even received.',
48:
'Incorrect server salt (in this case, the bad_server_salt response '
'is received with the correct salt, and the message is to be re-sent '
'with it).',
64:
'Invalid container.'
}
def __init__(self, request, code):
super().__init__(request, self.ErrorMessages.get(
code,
'Unknown error code (this should not happen): {}.'.format(code)))
self.code = code
|
class BadMessageError(Exception):
'''Occurs when handling a bad_message_notification.'''
def __init__(self, request, code):
pass
| 2 | 1 | 6 | 1 | 5 | 0 | 1 | 0.02 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 11 | 45 | 2 | 42 | 4 | 40 | 1 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
146,769 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/errors/common.py
|
telethon.errors.common.AuthKeyNotFound
|
class AuthKeyNotFound(Exception):
"""
The server claims it doesn't know about the authorization key (session
file) currently being used. This might be because it either has never
seen this authorization key, or it used to know about the authorization
key but has forgotten it, either temporarily or permanently (possibly
due to server errors).
If the issue persists, you may need to recreate the session file and login
again. This is not done automatically because it is not possible to know
if the issue is temporary or permanent.
"""
def __init__(self):
super().__init__(textwrap.dedent(self.__class__.__doc__))
|
class AuthKeyNotFound(Exception):
'''
The server claims it doesn't know about the authorization key (session
file) currently being used. This might be because it either has never
seen this authorization key, or it used to know about the authorization
key but has forgotten it, either temporarily or permanently (possibly
due to server errors).
If the issue persists, you may need to recreate the session file and login
again. This is not done automatically because it is not possible to know
if the issue is temporary or permanent.
'''
def __init__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 3.33 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 11 | 14 | 1 | 3 | 2 | 1 | 10 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
146,770 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/errors/common.py
|
telethon.errors.common.AlreadyInConversationError
|
class AlreadyInConversationError(Exception):
"""
Occurs when another exclusive conversation is opened in the same chat.
"""
def __init__(self):
super().__init__(
'Cannot open exclusive conversation in a '
'chat that already has one open conversation'
)
|
class AlreadyInConversationError(Exception):
'''
Occurs when another exclusive conversation is opened in the same chat.
'''
def __init__(self):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 1 | 0.5 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 11 | 9 | 0 | 6 | 2 | 4 | 3 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
146,771 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/crypto/factorization.py
|
telethon.crypto.factorization.Factorization
|
class Factorization:
"""
Simple module to factorize large numbers really quickly.
"""
@classmethod
def factorize(cls, pq):
"""
Factorizes the given large integer.
Implementation from https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/.
:param pq: the prime pair pq.
:return: a tuple containing the two factors p and q.
"""
if pq % 2 == 0:
return 2, pq // 2
y, c, m = randint(1, pq - 1), randint(1, pq - 1), randint(1, pq - 1)
g = r = q = 1
x = ys = 0
while g == 1:
x = y
for i in range(r):
y = (pow(y, 2, pq) + c) % pq
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = (pow(y, 2, pq) + c) % pq
q = q * (abs(x - y)) % pq
g = cls.gcd(q, pq)
k += m
r *= 2
if g == pq:
while True:
ys = (pow(ys, 2, pq) + c) % pq
g = cls.gcd(abs(x - ys), pq)
if g > 1:
break
p, q = g, pq // g
return (p, q) if p < q else (q, p)
@staticmethod
def gcd(a, b):
"""
Calculates the Greatest Common Divisor.
:param a: the first number.
:param b: the second number.
:return: GCD(a, b)
"""
while b:
a, b = b, a % b
return a
|
class Factorization:
'''
Simple module to factorize large numbers really quickly.
'''
@classmethod
def factorize(cls, pq):
'''
Factorizes the given large integer.
Implementation from https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/.
:param pq: the prime pair pq.
:return: a tuple containing the two factors p and q.
'''
pass
@staticmethod
def gcd(a, b):
'''
Calculates the Greatest Common Divisor.
:param a: the first number.
:param b: the second number.
:return: GCD(a, b)
'''
pass
| 5 | 3 | 27 | 6 | 16 | 6 | 6 | 0.44 | 0 | 1 | 0 | 0 | 0 | 0 | 2 | 2 | 61 | 12 | 34 | 11 | 29 | 15 | 32 | 9 | 29 | 10 | 0 | 3 | 12 |
146,772 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/crypto/cdndecrypter.py
|
telethon.crypto.cdndecrypter.CdnDecrypter
|
class CdnDecrypter:
"""
Used when downloading a file results in a 'FileCdnRedirect' to
both prepare the redirect, decrypt the file as it downloads, and
ensure the file hasn't been tampered. https://core.telegram.org/cdn
"""
def __init__(self, cdn_client, file_token, cdn_aes, cdn_file_hashes):
"""
Initializes the CDN decrypter.
:param cdn_client: a client connected to a CDN.
:param file_token: the token of the file to be used.
:param cdn_aes: the AES CTR used to decrypt the file.
:param cdn_file_hashes: the hashes the decrypted file must match.
"""
self.client = cdn_client
self.file_token = file_token
self.cdn_aes = cdn_aes
self.cdn_file_hashes = cdn_file_hashes
@staticmethod
async def prepare_decrypter(client, cdn_client, cdn_redirect):
"""
Prepares a new CDN decrypter.
:param client: a TelegramClient connected to the main servers.
:param cdn_client: a new client connected to the CDN.
:param cdn_redirect: the redirect file object that caused this call.
:return: (CdnDecrypter, first chunk file data)
"""
cdn_aes = AESModeCTR(
key=cdn_redirect.encryption_key,
# 12 first bytes of the IV..4 bytes of the offset (0, big endian)
iv=cdn_redirect.encryption_iv[:12] + bytes(4)
)
# We assume that cdn_redirect.cdn_file_hashes are ordered by offset,
# and that there will be enough of these to retrieve the whole file.
decrypter = CdnDecrypter(
cdn_client, cdn_redirect.file_token,
cdn_aes, cdn_redirect.cdn_file_hashes
)
cdn_file = await cdn_client(GetCdnFileRequest(
file_token=cdn_redirect.file_token,
offset=cdn_redirect.cdn_file_hashes[0].offset,
limit=cdn_redirect.cdn_file_hashes[0].limit
))
if isinstance(cdn_file, CdnFileReuploadNeeded):
# We need to use the original client here
await client(ReuploadCdnFileRequest(
file_token=cdn_redirect.file_token,
request_token=cdn_file.request_token
))
# We want to always return a valid upload.CdnFile
cdn_file = decrypter.get_file()
else:
cdn_file.bytes = decrypter.cdn_aes.encrypt(cdn_file.bytes)
cdn_hash = decrypter.cdn_file_hashes.pop(0)
decrypter.check(cdn_file.bytes, cdn_hash)
return decrypter, cdn_file
def get_file(self):
"""
Calls GetCdnFileRequest and decrypts its bytes.
Also ensures that the file hasn't been tampered.
:return: the CdnFile result.
"""
if self.cdn_file_hashes:
cdn_hash = self.cdn_file_hashes.pop(0)
cdn_file = self.client(GetCdnFileRequest(
self.file_token, cdn_hash.offset, cdn_hash.limit
))
cdn_file.bytes = self.cdn_aes.encrypt(cdn_file.bytes)
self.check(cdn_file.bytes, cdn_hash)
else:
cdn_file = CdnFile(bytes(0))
return cdn_file
@staticmethod
def check(data, cdn_hash):
"""
Checks the integrity of the given data.
Raises CdnFileTamperedError if the integrity check fails.
:param data: the data to be hashed.
:param cdn_hash: the expected hash.
"""
if sha256(data).digest() != cdn_hash.hash:
raise CdnFileTamperedError()
|
class CdnDecrypter:
'''
Used when downloading a file results in a 'FileCdnRedirect' to
both prepare the redirect, decrypt the file as it downloads, and
ensure the file hasn't been tampered. https://core.telegram.org/cdn
'''
def __init__(self, cdn_client, file_token, cdn_aes, cdn_file_hashes):
'''
Initializes the CDN decrypter.
:param cdn_client: a client connected to a CDN.
:param file_token: the token of the file to be used.
:param cdn_aes: the AES CTR used to decrypt the file.
:param cdn_file_hashes: the hashes the decrypted file must match.
'''
pass
@staticmethod
async def prepare_decrypter(client, cdn_client, cdn_redirect):
'''
Prepares a new CDN decrypter.
:param client: a TelegramClient connected to the main servers.
:param cdn_client: a new client connected to the CDN.
:param cdn_redirect: the redirect file object that caused this call.
:return: (CdnDecrypter, first chunk file data)
'''
pass
def get_file(self):
'''
Calls GetCdnFileRequest and decrypts its bytes.
Also ensures that the file hasn't been tampered.
:return: the CdnFile result.
'''
pass
@staticmethod
def check(data, cdn_hash):
'''
Checks the integrity of the given data.
Raises CdnFileTamperedError if the integrity check fails.
:param data: the data to be hashed.
:param cdn_hash: the expected hash.
'''
pass
| 7 | 5 | 21 | 2 | 11 | 8 | 2 | 0.74 | 0 | 3 | 2 | 0 | 2 | 4 | 4 | 4 | 94 | 12 | 47 | 17 | 40 | 35 | 28 | 15 | 23 | 2 | 0 | 1 | 7 |
146,773 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/crypto/authkey.py
|
telethon.crypto.authkey.AuthKey
|
class AuthKey:
"""
Represents an authorization key, used to encrypt and decrypt
messages sent to Telegram's data centers.
"""
def __init__(self, data):
"""
Initializes a new authorization key.
:param data: the data in bytes that represent this auth key.
"""
self.key = data
@property
def key(self):
return self._key
@key.setter
def key(self, value):
if not value:
self._key = self.aux_hash = self.key_id = None
return
if isinstance(value, type(self)):
self._key, self.aux_hash, self.key_id = \
value._key, value.aux_hash, value.key_id
return
self._key = value
with BinaryReader(sha1(self._key).digest()) as reader:
self.aux_hash = reader.read_long(signed=False)
reader.read(4)
self.key_id = reader.read_long(signed=False)
# TODO This doesn't really fit here, it's only used in authentication
def calc_new_nonce_hash(self, new_nonce, number):
"""
Calculates the new nonce hash based on the current attributes.
:param new_nonce: the new nonce to be hashed.
:param number: number to prepend before the hash.
:return: the hash for the given new nonce.
"""
new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
data = new_nonce + struct.pack('<BQ', number, self.aux_hash)
# Calculates the message key from the given data
return int.from_bytes(sha1(data).digest()[4:20], 'little', signed=True)
def __bool__(self):
return bool(self._key)
def __eq__(self, other):
return isinstance(other, type(self)) and other.key == self._key
|
class AuthKey:
'''
Represents an authorization key, used to encrypt and decrypt
messages sent to Telegram's data centers.
'''
def __init__(self, data):
'''
Initializes a new authorization key.
:param data: the data in bytes that represent this auth key.
'''
pass
@property
def key(self):
pass
@key.setter
def key(self):
pass
def calc_new_nonce_hash(self, new_nonce, number):
'''
Calculates the new nonce hash based on the current attributes.
:param new_nonce: the new nonce to be hashed.
:param number: number to prepend before the hash.
:return: the hash for the given new nonce.
'''
pass
def __bool__(self):
pass
def __eq__(self, other):
pass
| 9 | 3 | 7 | 1 | 4 | 2 | 1 | 0.57 | 0 | 3 | 0 | 0 | 6 | 3 | 6 | 6 | 54 | 10 | 28 | 12 | 19 | 16 | 25 | 9 | 18 | 3 | 0 | 1 | 8 |
146,774 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/crypto/aesctr.py
|
telethon.crypto.aesctr.AESModeCTR
|
class AESModeCTR:
"""Wrapper around pyaes.AESModeOfOperationCTR mode with custom IV"""
# TODO Maybe make a pull request to pyaes to support iv on CTR
def __init__(self, key, iv):
"""
Initializes the AES CTR mode with the given key/iv pair.
:param key: the key to be used as bytes.
:param iv: the bytes initialization vector. Must have a length of 16.
"""
# TODO Use libssl if available
assert isinstance(key, bytes)
self._aes = pyaes.AESModeOfOperationCTR(key)
assert isinstance(iv, bytes)
assert len(iv) == 16
self._aes._counter._counter = list(iv)
def encrypt(self, data):
"""
Encrypts the given plain text through AES CTR.
:param data: the plain text to be encrypted.
:return: the encrypted cipher text.
"""
return self._aes.encrypt(data)
def decrypt(self, data):
"""
Decrypts the given cipher text through AES CTR
:param data: the cipher text to be decrypted.
:return: the decrypted plain text.
"""
return self._aes.decrypt(data)
|
class AESModeCTR:
'''Wrapper around pyaes.AESModeOfOperationCTR mode with custom IV'''
def __init__(self, key, iv):
'''
Initializes the AES CTR mode with the given key/iv pair.
:param key: the key to be used as bytes.
:param iv: the bytes initialization vector. Must have a length of 16.
'''
pass
def encrypt(self, data):
'''
Encrypts the given plain text through AES CTR.
:param data: the plain text to be encrypted.
:return: the encrypted cipher text.
'''
pass
def decrypt(self, data):
'''
Decrypts the given cipher text through AES CTR
:param data: the cipher text to be decrypted.
:return: the decrypted plain text.
'''
pass
| 4 | 4 | 10 | 1 | 3 | 5 | 1 | 1.64 | 0 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 36 | 7 | 11 | 5 | 7 | 18 | 11 | 5 | 7 | 1 | 0 | 0 | 3 |
146,775 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/crypto/aes.py
|
telethon.crypto.aes.AES
|
class AES:
"""
Class that servers as an interface to encrypt and decrypt
text through the AES IGE mode.
"""
@staticmethod
def decrypt_ige(cipher_text, key, iv):
"""
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
if cryptg:
return cryptg.decrypt_ige(cipher_text, key, iv)
if libssl.decrypt_ige:
return libssl.decrypt_ige(cipher_text, key, iv)
iv1 = iv[:len(iv) // 2]
iv2 = iv[len(iv) // 2:]
aes = pyaes.AES(key)
plain_text = []
blocks_count = len(cipher_text) // 16
cipher_text_block = [0] * 16
for block_index in range(blocks_count):
for i in range(16):
cipher_text_block[i] = \
cipher_text[block_index * 16 + i] ^ iv2[i]
plain_text_block = aes.decrypt(cipher_text_block)
for i in range(16):
plain_text_block[i] ^= iv1[i]
iv1 = cipher_text[block_index * 16:block_index * 16 + 16]
iv2 = plain_text_block
plain_text.extend(plain_text_block)
return bytes(plain_text)
@staticmethod
def encrypt_ige(plain_text, key, iv):
"""
Encrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
padding = len(plain_text) % 16
if padding:
plain_text += os.urandom(16 - padding)
if cryptg:
return cryptg.encrypt_ige(plain_text, key, iv)
if libssl.encrypt_ige:
return libssl.encrypt_ige(plain_text, key, iv)
iv1 = iv[:len(iv) // 2]
iv2 = iv[len(iv) // 2:]
aes = pyaes.AES(key)
cipher_text = []
blocks_count = len(plain_text) // 16
for block_index in range(blocks_count):
plain_text_block = list(
plain_text[block_index * 16:block_index * 16 + 16]
)
for i in range(16):
plain_text_block[i] ^= iv1[i]
cipher_text_block = aes.encrypt(plain_text_block)
for i in range(16):
cipher_text_block[i] ^= iv2[i]
iv1 = cipher_text_block
iv2 = plain_text[block_index * 16:block_index * 16 + 16]
cipher_text.extend(cipher_text_block)
return bytes(cipher_text)
|
class AES:
'''
Class that servers as an interface to encrypt and decrypt
text through the AES IGE mode.
'''
@staticmethod
def decrypt_ige(cipher_text, key, iv):
'''
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
'''
pass
@staticmethod
def encrypt_ige(plain_text, key, iv):
'''
Encrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
'''
pass
| 5 | 3 | 38 | 10 | 24 | 4 | 7 | 0.24 | 0 | 3 | 0 | 0 | 0 | 0 | 2 | 2 | 83 | 20 | 51 | 24 | 46 | 12 | 46 | 22 | 43 | 7 | 0 | 2 | 13 |
146,776 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/users.py
|
telethon.client.users.UserMethods
|
class UserMethods:
async def __call__(self: 'TelegramClient', request, ordered=False, flood_sleep_threshold=None):
return await self._call(self._sender, request, ordered=ordered)
async def _call(self: 'TelegramClient', sender, request, ordered=False, flood_sleep_threshold=None):
if self._loop is not None and self._loop != helpers.get_running_loop():
raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)')
# if the loop is None it will fail with a connection error later on
if flood_sleep_threshold is None:
flood_sleep_threshold = self.flood_sleep_threshold
requests = list(request) if utils.is_list_like(request) else [request]
request = list(request) if utils.is_list_like(request) else request
for i, r in enumerate(requests):
if not isinstance(r, TLRequest):
raise _NOT_A_REQUEST()
await r.resolve(self, utils)
# Avoid making the request if it's already in a flood wait
if r.CONSTRUCTOR_ID in self._flood_waited_requests:
due = self._flood_waited_requests[r.CONSTRUCTOR_ID]
diff = round(due - time.time())
if diff <= 3: # Flood waits below 3 seconds are "ignored"
self._flood_waited_requests.pop(r.CONSTRUCTOR_ID, None)
elif diff <= flood_sleep_threshold:
self._log[__name__].info(*_fmt_flood(diff, r, early=True))
await asyncio.sleep(diff)
self._flood_waited_requests.pop(r.CONSTRUCTOR_ID, None)
else:
raise errors.FloodWaitError(request=r, capture=diff)
if self._no_updates:
if utils.is_list_like(request):
request[i] = functions.InvokeWithoutUpdatesRequest(r)
else:
# This should only run once as requests should be a list of 1 item
request = functions.InvokeWithoutUpdatesRequest(r)
request_index = 0
last_error = None
self._last_request = time.time()
for attempt in retry_range(self._request_retries):
try:
future = sender.send(request, ordered=ordered)
if isinstance(future, list):
results = []
exceptions = []
for f in future:
try:
result = await f
except RPCError as e:
exceptions.append(e)
results.append(None)
continue
self.session.process_entities(result)
exceptions.append(None)
results.append(result)
request_index += 1
if any(x is not None for x in exceptions):
raise MultiError(exceptions, results, requests)
else:
return results
else:
result = await future
self.session.process_entities(result)
return result
except (errors.ServerError, errors.RpcCallFailError,
errors.RpcMcgetFailError, errors.InterdcCallErrorError,
errors.TimedOutError,
errors.InterdcCallRichErrorError) as e:
last_error = e
self._log[__name__].warning(
'Telegram is having internal issues %s: %s',
e.__class__.__name__, e)
await asyncio.sleep(2)
except (errors.FloodWaitError, errors.FloodPremiumWaitError,
errors.SlowModeWaitError, errors.FloodTestPhoneWaitError) as e:
last_error = e
if utils.is_list_like(request):
request = request[request_index]
# SLOW_MODE_WAIT is chat-specific, not request-specific
if not isinstance(e, errors.SlowModeWaitError):
self._flood_waited_requests\
[request.CONSTRUCTOR_ID] = time.time() + e.seconds
# In test servers, FLOOD_WAIT_0 has been observed, and sleeping for
# such a short amount will cause retries very fast leading to issues.
if e.seconds == 0:
e.seconds = 1
if e.seconds <= self.flood_sleep_threshold:
self._log[__name__].info(*_fmt_flood(e.seconds, request))
await asyncio.sleep(e.seconds)
else:
raise
except (errors.PhoneMigrateError, errors.NetworkMigrateError,
errors.UserMigrateError) as e:
last_error = e
self._log[__name__].info('Phone migrated to %d', e.new_dc)
should_raise = isinstance(e, (
errors.PhoneMigrateError, errors.NetworkMigrateError
))
if should_raise and await self.is_user_authorized():
raise
await self._switch_dc(e.new_dc)
if self._raise_last_call_error and last_error is not None:
raise last_error
raise ValueError('Request was unsuccessful {} time(s)'
.format(attempt))
# region Public methods
async def get_me(self: 'TelegramClient', input_peer: bool = False) \
-> 'typing.Union[types.User, types.InputPeerUser]':
"""
Gets "me", the current :tl:`User` who is logged in.
If the user has not logged in yet, this method returns `None`.
Arguments
input_peer (`bool`, optional):
Whether to return the :tl:`InputPeerUser` version or the normal
:tl:`User`. This can be useful if you just need to know the ID
of yourself.
Returns
Your own :tl:`User`.
Example
.. code-block:: python
me = await client.get_me()
print(me.username)
"""
if input_peer and self._mb_entity_cache.self_id:
return self._mb_entity_cache.get(self._mb_entity_cache.self_id)._as_input_peer()
try:
me = (await self(
functions.users.GetUsersRequest([types.InputUserSelf()])))[0]
if not self._mb_entity_cache.self_id:
self._mb_entity_cache.set_self_user(me.id, me.bot, me.access_hash)
return utils.get_input_peer(me, allow_self=False) if input_peer else me
except errors.UnauthorizedError:
return None
@property
def _self_id(self: 'TelegramClient') -> typing.Optional[int]:
"""
Returns the ID of the logged-in user, if known.
This property is used in every update, and some like `updateLoginToken`
occur prior to login, so it gracefully handles when no ID is known yet.
"""
return self._mb_entity_cache.self_id
async def is_bot(self: 'TelegramClient') -> bool:
"""
Return `True` if the signed-in user is a bot, `False` otherwise.
Example
.. code-block:: python
if await client.is_bot():
print('Beep')
else:
print('Hello')
"""
if self._mb_entity_cache.self_bot is None:
await self.get_me(input_peer=True)
return self._mb_entity_cache.self_bot
async def is_user_authorized(self: 'TelegramClient') -> bool:
"""
Returns `True` if the user is authorized (logged in).
Example
.. code-block:: python
if not await client.is_user_authorized():
await client.send_code_request(phone)
code = input('enter code: ')
await client.sign_in(phone, code)
"""
if self._authorized is None:
try:
# Any request that requires authorization will work
await self(functions.updates.GetStateRequest())
self._authorized = True
except errors.RPCError:
self._authorized = False
return self._authorized
async def get_entity(
self: 'TelegramClient',
entity: 'hints.EntitiesLike') -> typing.Union['hints.Entity', typing.List['hints.Entity']]:
"""
Turns the given entity into a valid Telegram :tl:`User`, :tl:`Chat`
or :tl:`Channel`. You can also pass a list or iterable of entities,
and they will be efficiently fetched from the network.
Arguments
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
If a username is given, **the username will be resolved** making
an API call every time. Resolving usernames is an expensive
operation and will start hitting flood waits around 50 usernames
in a short period of time.
If you want to get the entity for a *cached* username, you should
first `get_input_entity(username) <get_input_entity>` which will
use the cache), and then use `get_entity` with the result of the
previous call.
Similar limits apply to invite links, and you should use their
ID instead.
Using phone numbers (from people in your contact list), exact
names, integer IDs or :tl:`Peer` rely on a `get_input_entity`
first, which in turn needs the entity to be in cache, unless
a :tl:`InputPeer` was passed.
Unsupported types will raise ``TypeError``.
If the entity can't be found, ``ValueError`` will be raised.
Returns
:tl:`User`, :tl:`Chat` or :tl:`Channel` corresponding to the
input entity. A list will be returned if more than one was given.
Example
.. code-block:: python
from telethon import utils
me = await client.get_entity('me')
print(utils.get_display_name(me))
chat = await client.get_input_entity('username')
async for message in client.iter_messages(chat):
...
# Note that you could have used the username directly, but it's
# good to use get_input_entity if you will reuse it a lot.
async for message in client.iter_messages('username'):
...
# Note that for this to work the phone number must be in your contacts
some_id = await client.get_peer_id('+34123456789')
"""
single = not utils.is_list_like(entity)
if single:
entity = (entity,)
# Group input entities by string (resolve username),
# input users (get users), input chat (get chats) and
# input channels (get channels) to get the most entities
# in the less amount of calls possible.
inputs = []
for x in entity:
if isinstance(x, str):
inputs.append(x)
else:
inputs.append(await self.get_input_entity(x))
lists = {
helpers._EntityType.USER: [],
helpers._EntityType.CHAT: [],
helpers._EntityType.CHANNEL: [],
}
for x in inputs:
try:
lists[helpers._entity_type(x)].append(x)
except TypeError:
pass
users = lists[helpers._EntityType.USER]
chats = lists[helpers._EntityType.CHAT]
channels = lists[helpers._EntityType.CHANNEL]
if users:
# GetUsersRequest has a limit of 200 per call
tmp = []
while users:
curr, users = users[:200], users[200:]
tmp.extend(await self(functions.users.GetUsersRequest(curr)))
users = tmp
if chats: # TODO Handle chats slice?
chats = (await self(
functions.messages.GetChatsRequest([x.chat_id for x in chats]))).chats
if channels:
channels = (await self(
functions.channels.GetChannelsRequest(channels))).chats
# Merge users, chats and channels into a single dictionary
id_entity = {
# `get_input_entity` might've guessed the type from a non-marked ID,
# so the only way to match that with the input is by not using marks here.
utils.get_peer_id(x, add_mark=False): x
for x in itertools.chain(users, chats, channels)
}
# We could check saved usernames and put them into the users,
# chats and channels list from before. While this would reduce
# the amount of ResolveUsername calls, it would fail to catch
# username changes.
result = []
for x in inputs:
if isinstance(x, str):
result.append(await self._get_entity_from_string(x))
elif not isinstance(x, types.InputPeerSelf):
result.append(id_entity[utils.get_peer_id(x, add_mark=False)])
else:
result.append(next(
u for u in id_entity.values()
if isinstance(u, types.User) and u.is_self
))
return result[0] if single else result
async def get_input_entity(
self: 'TelegramClient',
peer: 'hints.EntityLike') -> 'types.TypeInputPeer':
"""
Turns the given entity into its input entity version.
Most requests use this kind of :tl:`InputPeer`, so this is the most
suitable call to make for those cases. **Generally you should let the
library do its job** and don't worry about getting the input entity
first, but if you're going to use an entity often, consider making the
call:
Arguments
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
If a username or invite link is given, **the library will
use the cache**. This means that it's possible to be using
a username that *changed* or an old invite link (this only
happens if an invite link for a small group chat is used
after it was upgraded to a mega-group).
If the username or ID from the invite link is not found in
the cache, it will be fetched. The same rules apply to phone
numbers (``'+34 123456789'``) from people in your contact list.
If an exact name is given, it must be in the cache too. This
is not reliable as different people can share the same name
and which entity is returned is arbitrary, and should be used
only for quick tests.
If a positive integer ID is given, the entity will be searched
in cached users, chats or channels, without making any call.
If a negative integer ID is given, the entity will be searched
exactly as either a chat (prefixed with ``-``) or as a channel
(prefixed with ``-100``).
If a :tl:`Peer` is given, it will be searched exactly in the
cache as either a user, chat or channel.
If the given object can be turned into an input entity directly,
said operation will be done.
Unsupported types will raise ``TypeError``.
If the entity can't be found, ``ValueError`` will be raised.
Returns
:tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`
or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.
If you need to get the ID of yourself, you should use
`get_me` with ``input_peer=True``) instead.
Example
.. code-block:: python
# If you're going to use "username" often in your code
# (make a lot of calls), consider getting its input entity
# once, and then using the "user" everywhere instead.
user = await client.get_input_entity('username')
# The same applies to IDs, chats or channels.
chat = await client.get_input_entity(-123456789)
"""
# Short-circuit if the input parameter directly maps to an InputPeer
try:
return utils.get_input_peer(peer)
except TypeError:
pass
# Next in priority is having a peer (or its ID) cached in-memory
try:
# 0x2d45687 == crc32(b'Peer')
if isinstance(peer, int) or peer.SUBCLASS_OF_ID == 0x2d45687:
return self._mb_entity_cache.get(utils.get_peer_id(peer, add_mark=False))._as_input_peer()
except AttributeError:
pass
# Then come known strings that take precedence
if peer in ('me', 'self'):
return types.InputPeerSelf()
# No InputPeer, cached peer, or known string. Fetch from disk cache
try:
return self.session.get_input_entity(peer)
except ValueError:
pass
# Only network left to try
if isinstance(peer, str):
return utils.get_input_peer(
await self._get_entity_from_string(peer))
# If we're a bot and the user has messaged us privately users.getUsers
# will work with access_hash = 0. Similar for channels.getChannels.
# If we're not a bot but the user is in our contacts, it seems to work
# regardless. These are the only two special-cased requests.
peer = utils.get_peer(peer)
if isinstance(peer, types.PeerUser):
users = await self(functions.users.GetUsersRequest([
types.InputUser(peer.user_id, access_hash=0)]))
if users and not isinstance(users[0], types.UserEmpty):
# If the user passed a valid ID they expect to work for
# channels but would be valid for users, we get UserEmpty.
# Avoid returning the invalid empty input peer for that.
#
# We *could* try to guess if it's a channel first, and if
# it's not, work as a chat and try to validate it through
# another request, but that becomes too much work.
return utils.get_input_peer(users[0])
elif isinstance(peer, types.PeerChat):
return types.InputPeerChat(peer.chat_id)
elif isinstance(peer, types.PeerChannel):
try:
channels = await self(functions.channels.GetChannelsRequest([
types.InputChannel(peer.channel_id, access_hash=0)]))
return utils.get_input_peer(channels.chats[0])
except errors.ChannelInvalidError:
pass
raise ValueError(
'Could not find the input entity for {} ({}). Please read https://'
'docs.telethon.dev/en/stable/concepts/entities.html to'
' find out more details.'
.format(peer, type(peer).__name__)
)
async def _get_peer(self: 'TelegramClient', peer: 'hints.EntityLike'):
i, cls = utils.resolve_id(await self.get_peer_id(peer))
return cls(i)
async 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
async def _get_entity_from_string(self: 'TelegramClient', string):
"""
Gets a full entity from the given string, which may be a phone or
a username, and processes all the found entities on the session.
The string may also be a user link, or a channel/chat invite link.
This method has the side effect of adding the found users to the
session database, so it can be queried later without API calls,
if this option is enabled on the session.
Returns the found entity, or raises TypeError if not found.
"""
phone = utils.parse_phone(string)
if phone:
try:
for user in (await self(
functions.contacts.GetContactsRequest(0))).users:
if user.phone == phone:
return user
except errors.BotMethodInvalidError:
raise ValueError('Cannot get entity by phone number as a '
'bot (try using integer IDs, not strings)')
elif string.lower() in ('me', 'self'):
return await self.get_me()
else:
username, is_join_chat = utils.parse_username(string)
if is_join_chat:
invite = await self(
functions.messages.CheckChatInviteRequest(username))
if isinstance(invite, types.ChatInvite):
raise ValueError(
'Cannot get entity from a channel (or group) '
'that you are not part of. Join the group and retry'
)
elif isinstance(invite, types.ChatInviteAlready):
return invite.chat
elif username:
try:
result = await self(
functions.contacts.ResolveUsernameRequest(username))
except errors.UsernameNotOccupiedError as e:
raise ValueError('No user has "{}" as username'
.format(username)) from e
try:
pid = utils.get_peer_id(result.peer, add_mark=False)
if isinstance(result.peer, types.PeerUser):
return next(x for x in result.users if x.id == pid)
else:
return next(x for x in result.chats if x.id == pid)
except StopIteration:
pass
try:
# Nobody with this username, maybe it's an exact name/title
return await self.get_entity(
self.session.get_input_entity(string))
except ValueError:
pass
raise ValueError(
'Cannot find any entity corresponding to "{}"'.format(string)
)
async def _get_input_dialog(self: 'TelegramClient', dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer')
dialog.peer = await self.get_input_entity(dialog.peer)
return dialog
elif dialog.SUBCLASS_OF_ID == 0xc91c90b6: # crc32(b'InputPeer')
return types.InputDialogPeer(dialog)
except AttributeError:
pass
return types.InputDialogPeer(await self.get_input_entity(dialog))
async def _get_input_notify(self: 'TelegramClient', notify):
"""
Returns a :tl:`InputNotifyPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if notify.SUBCLASS_OF_ID == 0x58981615:
if isinstance(notify, types.InputNotifyPeer):
notify.peer = await self.get_input_entity(notify.peer)
return notify
except AttributeError:
pass
return types.InputNotifyPeer(await self.get_input_entity(notify))
|
class UserMethods:
async def __call__(self: 'TelegramClient', request, ordered=False, flood_sleep_threshold=None):
pass
async def _call(self: 'TelegramClient', sender, request, ordered=False, flood_sleep_threshold=None):
pass
async def get_me(self: 'TelegramClient', input_peer: bool = False) \
-> 'typing.Union[types.User, types.InputPeerUser]':
'''
Gets "me", the current :tl:`User` who is logged in.
If the user has not logged in yet, this method returns `None`.
Arguments
input_peer (`bool`, optional):
Whether to return the :tl:`InputPeerUser` version or the normal
:tl:`User`. This can be useful if you just need to know the ID
of yourself.
Returns
Your own :tl:`User`.
Example
.. code-block:: python
me = await client.get_me()
print(me.username)
'''
pass
@property
def _self_id(self: 'TelegramClient') -> typing.Optional[int]:
'''
Returns the ID of the logged-in user, if known.
This property is used in every update, and some like `updateLoginToken`
occur prior to login, so it gracefully handles when no ID is known yet.
'''
pass
async def is_bot(self: 'TelegramClient') -> bool:
'''
Return `True` if the signed-in user is a bot, `False` otherwise.
Example
.. code-block:: python
if await client.is_bot():
print('Beep')
else:
print('Hello')
'''
pass
async def is_user_authorized(self: 'TelegramClient') -> bool:
'''
Returns `True` if the user is authorized (logged in).
Example
.. code-block:: python
if not await client.is_user_authorized():
await client.send_code_request(phone)
code = input('enter code: ')
await client.sign_in(phone, code)
'''
pass
async def get_entity(
self: 'TelegramClient',
entity: 'hints.EntitiesLike') -> typing.Union['hints.Entity', typing.List['hints.Entity']]:
'''
Turns the given entity into a valid Telegram :tl:`User`, :tl:`Chat`
or :tl:`Channel`. You can also pass a list or iterable of entities,
and they will be efficiently fetched from the network.
Arguments
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
If a username is given, **the username will be resolved** making
an API call every time. Resolving usernames is an expensive
operation and will start hitting flood waits around 50 usernames
in a short period of time.
If you want to get the entity for a *cached* username, you should
first `get_input_entity(username) <get_input_entity>` which will
use the cache), and then use `get_entity` with the result of the
previous call.
Similar limits apply to invite links, and you should use their
ID instead.
Using phone numbers (from people in your contact list), exact
names, integer IDs or :tl:`Peer` rely on a `get_input_entity`
first, which in turn needs the entity to be in cache, unless
a :tl:`InputPeer` was passed.
Unsupported types will raise ``TypeError``.
If the entity can't be found, ``ValueError`` will be raised.
Returns
:tl:`User`, :tl:`Chat` or :tl:`Channel` corresponding to the
input entity. A list will be returned if more than one was given.
Example
.. code-block:: python
from telethon import utils
me = await client.get_entity('me')
print(utils.get_display_name(me))
chat = await client.get_input_entity('username')
async for message in client.iter_messages(chat):
...
# Note that you could have used the username directly, but it's
# good to use get_input_entity if you will reuse it a lot.
async for message in client.iter_messages('username'):
...
# Note that for this to work the phone number must be in your contacts
some_id = await client.get_peer_id('+34123456789')
'''
pass
async def get_input_entity(
self: 'TelegramClient',
peer: 'hints.EntityLike') -> 'types.TypeInputPeer':
'''
Turns the given entity into its input entity version.
Most requests use this kind of :tl:`InputPeer`, so this is the most
suitable call to make for those cases. **Generally you should let the
library do its job** and don't worry about getting the input entity
first, but if you're going to use an entity often, consider making the
call:
Arguments
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
If a username or invite link is given, **the library will
use the cache**. This means that it's possible to be using
a username that *changed* or an old invite link (this only
happens if an invite link for a small group chat is used
after it was upgraded to a mega-group).
If the username or ID from the invite link is not found in
the cache, it will be fetched. The same rules apply to phone
numbers (``'+34 123456789'``) from people in your contact list.
If an exact name is given, it must be in the cache too. This
is not reliable as different people can share the same name
and which entity is returned is arbitrary, and should be used
only for quick tests.
If a positive integer ID is given, the entity will be searched
in cached users, chats or channels, without making any call.
If a negative integer ID is given, the entity will be searched
exactly as either a chat (prefixed with ``-``) or as a channel
(prefixed with ``-100``).
If a :tl:`Peer` is given, it will be searched exactly in the
cache as either a user, chat or channel.
If the given object can be turned into an input entity directly,
said operation will be done.
Unsupported types will raise ``TypeError``.
If the entity can't be found, ``ValueError`` will be raised.
Returns
:tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`
or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.
If you need to get the ID of yourself, you should use
`get_me` with ``input_peer=True``) instead.
Example
.. code-block:: python
# If you're going to use "username" often in your code
# (make a lot of calls), consider getting its input entity
# once, and then using the "user" everywhere instead.
user = await client.get_input_entity('username')
# The same applies to IDs, chats or channels.
chat = await client.get_input_entity(-123456789)
'''
pass
async def _get_peer(self: 'TelegramClient', peer: 'hints.EntityLike'):
pass
async 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'))
'''
pass
async def _get_entity_from_string(self: 'TelegramClient', string):
'''
Gets a full entity from the given string, which may be a phone or
a username, and processes all the found entities on the session.
The string may also be a user link, or a channel/chat invite link.
This method has the side effect of adding the found users to the
session database, so it can be queried later without API calls,
if this option is enabled on the session.
Returns the found entity, or raises TypeError if not found.
'''
pass
async def _get_input_dialog(self: 'TelegramClient', dialog):
'''
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
'''
pass
async def _get_input_notify(self: 'TelegramClient', notify):
'''
Returns a :tl:`InputNotifyPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
'''
pass
| 15 | 10 | 44 | 6 | 23 | 15 | 7 | 0.66 | 0 | 16 | 4 | 0 | 13 | 3 | 13 | 13 | 590 | 94 | 302 | 62 | 279 | 198 | 233 | 50 | 219 | 26 | 0 | 5 | 92 |
146,777 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/uploads.py
|
telethon.client.uploads._CacheType
|
class _CacheType:
"""Like functools.partial but pretends to be the wrapped class."""
def __init__(self, cls):
self._cls = cls
def __call__(self, *args, **kwargs):
return self._cls(*args, file_reference=b'', **kwargs)
def __eq__(self, other):
return self._cls == other
|
class _CacheType:
'''Like functools.partial but pretends to be the wrapped class.'''
def __init__(self, cls):
pass
def __call__(self, *args, **kwargs):
pass
def __eq__(self, other):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.14 | 0 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 10 | 2 | 7 | 5 | 3 | 1 | 7 | 5 | 3 | 1 | 0 | 0 | 3 |
146,778 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/dialogs.py
|
telethon.client.dialogs.DialogMethods
|
class DialogMethods:
# region Public methods
def iter_dialogs(
self: 'TelegramClient',
limit: float = None,
*,
offset_date: 'hints.DateLike' = None,
offset_id: int = 0,
offset_peer: 'hints.EntityLike' = types.InputPeerEmpty(),
ignore_pinned: bool = False,
ignore_migrated: bool = False,
folder: int = None,
archived: bool = None
) -> _DialogsIter:
"""
Iterator over the dialogs (open conversations/subscribed channels).
The order is the same as the one seen in official applications
(first pinned, them from those with the most recent message to
those with the oldest message).
Arguments
limit (`int` | `None`):
How many dialogs to be retrieved as maximum. Can be set to
`None` to retrieve all dialogs. Note that this may take
whole minutes if you have hundreds of dialogs, as Telegram
will tell the library to slow down through a
``FloodWaitError``.
offset_date (`datetime`, optional):
The offset date to be used.
offset_id (`int`, optional):
The message ID to be used as an offset.
offset_peer (:tl:`InputPeer`, optional):
The peer to be used as an offset.
ignore_pinned (`bool`, optional):
Whether pinned dialogs should be ignored or not.
When set to `True`, these won't be yielded at all.
ignore_migrated (`bool`, optional):
Whether :tl:`Chat` that have ``migrated_to`` a :tl:`Channel`
should be included or not. By default all the chats in your
dialogs are returned, but setting this to `True` will ignore
(i.e. skip) them in the same way official applications do.
folder (`int`, optional):
The folder from which the dialogs should be retrieved.
If left unspecified, all dialogs (including those from
folders) will be returned.
If set to ``0``, all dialogs that don't belong to any
folder will be returned.
If set to a folder number like ``1``, only those from
said folder will be returned.
By default Telegram assigns the folder ID ``1`` to
archived chats, so you should use that if you need
to fetch the archived dialogs.
archived (`bool`, optional):
Alias for `folder`. If unspecified, all will be returned,
`False` implies ``folder=0`` and `True` implies ``folder=1``.
Yields
Instances of `Dialog <telethon.tl.custom.dialog.Dialog>`.
Example
.. code-block:: python
# Print all dialog IDs and the title, nicely formatted
async for dialog in client.iter_dialogs():
print('{:>14}: {}'.format(dialog.id, dialog.title))
"""
if archived is not None:
folder = 1 if archived else 0
return _DialogsIter(
self,
limit,
offset_date=offset_date,
offset_id=offset_id,
offset_peer=offset_peer,
ignore_pinned=ignore_pinned,
ignore_migrated=ignore_migrated,
folder=folder
)
async def get_dialogs(self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList':
"""
Same as `iter_dialogs()`, but returns a
`TotalList <telethon.helpers.TotalList>` instead.
Example
.. code-block:: python
# Get all open conversation, print the title of the first
dialogs = await client.get_dialogs()
first = dialogs[0]
print(first.title)
# Use the dialog somewhere else
await client.send_message(first, 'hi')
# Getting only non-archived dialogs (both equivalent)
non_archived = await client.get_dialogs(folder=0)
non_archived = await client.get_dialogs(archived=False)
# Getting only archived dialogs (both equivalent)
archived = await client.get_dialogs(folder=1)
archived = await client.get_dialogs(archived=True)
"""
return await self.iter_dialogs(*args, **kwargs).collect()
get_dialogs.__signature__ = inspect.signature(iter_dialogs)
def iter_drafts(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None
) -> _DraftsIter:
"""
Iterator over draft messages.
The order is unspecified.
Arguments
entity (`hints.EntitiesLike`, optional):
The entity or entities for which to fetch the draft messages.
If left unspecified, all draft messages will be returned.
Yields
Instances of `Draft <telethon.tl.custom.draft.Draft>`.
Example
.. code-block:: python
# Clear all drafts
async for draft in client.get_drafts():
await draft.delete()
# Getting the drafts with 'bot1' and 'bot2'
async for draft in client.iter_drafts(['bot1', 'bot2']):
print(draft.text)
"""
if entity and not utils.is_list_like(entity):
entity = (entity,)
# TODO Passing a limit here makes no sense
return _DraftsIter(self, None, entities=entity)
async def get_drafts(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None
) -> 'hints.TotalList':
"""
Same as `iter_drafts()`, but returns a list instead.
Example
.. code-block:: python
# Get drafts, print the text of the first
drafts = await client.get_drafts()
print(drafts[0].text)
# Get the draft in your chat
draft = await client.get_drafts('me')
print(drafts.text)
"""
items = await self.iter_drafts(entity).collect()
if not entity or utils.is_list_like(entity):
return items
else:
return items[0]
async def edit_folder(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None,
folder: typing.Union[int, typing.Sequence[int]] = None,
*,
unpack=None
) -> types.Updates:
"""
Edits the folder used by one or more dialogs to archive them.
Arguments
entity (entities):
The entity or list of entities to move to the desired
archive folder.
folder (`int`):
The folder to which the dialog should be archived to.
If you want to "archive" a dialog, use ``folder=1``.
If you want to "un-archive" it, use ``folder=0``.
You may also pass a list with the same length as
`entities` if you want to control where each entity
will go.
unpack (`int`, optional):
If you want to unpack an archived folder, set this
parameter to the folder number that you want to
delete.
When you unpack a folder, all the dialogs inside are
moved to the folder number 0.
You can only use this parameter if the other two
are not set.
Returns
The :tl:`Updates` object that the request produces.
Example
.. code-block:: python
# Archiving the first 5 dialogs
dialogs = await client.get_dialogs(5)
await client.edit_folder(dialogs, 1)
# Un-archiving the third dialog (archiving to folder 0)
await client.edit_folder(dialog[2], 0)
# Moving the first dialog to folder 0 and the second to 1
dialogs = await client.get_dialogs(2)
await client.edit_folder(dialogs, [0, 1])
# Un-archiving all dialogs
await client.edit_folder(unpack=1)
"""
if (entity is None) == (unpack is None):
raise ValueError('You can only set either entities or unpack, not both')
if unpack is not None:
return await self(functions.folders.DeleteFolderRequest(
folder_id=unpack
))
if not utils.is_list_like(entity):
entities = [await self.get_input_entity(entity)]
else:
entities = await asyncio.gather(
*(self.get_input_entity(x) for x in entity))
if folder is None:
raise ValueError('You must specify a folder')
elif not utils.is_list_like(folder):
folder = [folder] * len(entities)
elif len(entities) != len(folder):
raise ValueError('Number of folders does not match number of entities')
return await self(functions.folders.EditPeerFoldersRequest([
types.InputFolderPeer(x, folder_id=y)
for x, y in zip(entities, folder)
]))
async def delete_dialog(
self: 'TelegramClient',
entity: 'hints.EntityLike',
*,
revoke: bool = False
):
"""
Deletes a dialog (leaves a chat or channel).
This method can be used as a user and as a bot. However,
bots will only be able to use it to leave groups and channels
(trying to delete a private conversation will do nothing).
See also `Dialog.delete() <telethon.tl.custom.dialog.Dialog.delete>`.
Arguments
entity (entities):
The entity of the dialog to delete. If it's a chat or
channel, you will leave it. Note that the chat itself
is not deleted, only the dialog, because you left it.
revoke (`bool`, optional):
On private chats, you may revoke the messages from
the other peer too. By default, it's `False`. Set
it to `True` to delete the history for both.
This makes no difference for bot accounts, who can
only leave groups and channels.
Returns
The :tl:`Updates` object that the request produces,
or nothing for private conversations.
Example
.. code-block:: python
# Deleting the first dialog
dialogs = await client.get_dialogs(5)
await client.delete_dialog(dialogs[0])
# Leaving a channel by username
await client.delete_dialog('username')
"""
# If we have enough information (`Dialog.delete` gives it to us),
# then we know we don't have to kick ourselves in deactivated chats.
if isinstance(entity, types.Chat):
deactivated = entity.deactivated
else:
deactivated = False
entity = await self.get_input_entity(entity)
ty = helpers._entity_type(entity)
if ty == helpers._EntityType.CHANNEL:
return await self(functions.channels.LeaveChannelRequest(entity))
if ty == helpers._EntityType.CHAT and not deactivated:
try:
result = await self(functions.messages.DeleteChatUserRequest(
entity.chat_id, types.InputUserSelf(), revoke_history=revoke
))
except errors.PeerIdInvalidError:
# Happens if we didn't have the deactivated information
result = None
else:
result = None
if not await self.is_bot():
await self(functions.messages.DeleteHistoryRequest(entity, 0, revoke=revoke))
return result
def conversation(
self: 'TelegramClient',
entity: 'hints.EntityLike',
*,
timeout: float = 60,
total_timeout: float = None,
max_messages: int = 100,
exclusive: bool = True,
replies_are_responses: bool = True) -> custom.Conversation:
"""
Creates a `Conversation <telethon.tl.custom.conversation.Conversation>`
with the given entity.
.. note::
This Conversation API has certain shortcomings, such as lacking
persistence, poor interaction with other event handlers, and
overcomplicated usage for anything beyond the simplest case.
If you plan to interact with a bot without handlers, this works
fine, but when running a bot yourself, you may instead prefer
to follow the advice from https://stackoverflow.com/a/62246569/.
This is not the same as just sending a message to create a "dialog"
with them, but rather a way to easily send messages and await for
responses or other reactions. Refer to its documentation for more.
Arguments
entity (`entity`):
The entity with which a new conversation should be opened.
timeout (`int` | `float`, optional):
The default timeout (in seconds) *per action* to be used. You
may also override this timeout on a per-method basis. By
default each action can take up to 60 seconds (the value of
this timeout).
total_timeout (`int` | `float`, optional):
The total timeout (in seconds) to use for the whole
conversation. This takes priority over per-action
timeouts. After these many seconds pass, subsequent
actions will result in ``asyncio.TimeoutError``.
max_messages (`int`, optional):
The maximum amount of messages this conversation will
remember. After these many messages arrive in the
specified chat, subsequent actions will result in
``ValueError``.
exclusive (`bool`, optional):
By default, conversations are exclusive within a single
chat. That means that while a conversation is open in a
chat, you can't open another one in the same chat, unless
you disable this flag.
If you try opening an exclusive conversation for
a chat where it's already open, it will raise
``AlreadyInConversationError``.
replies_are_responses (`bool`, optional):
Whether replies should be treated as responses or not.
If the setting is enabled, calls to `conv.get_response
<telethon.tl.custom.conversation.Conversation.get_response>`
and a subsequent call to `conv.get_reply
<telethon.tl.custom.conversation.Conversation.get_reply>`
will return different messages, otherwise they may return
the same message.
Consider the following scenario with one outgoing message,
1, and two incoming messages, the second one replying::
Hello! <1
2> (reply to 1) Hi!
3> (reply to 1) How are you?
And the following code:
.. code-block:: python
async with client.conversation(chat) as conv:
msg1 = await conv.send_message('Hello!')
msg2 = await conv.get_response()
msg3 = await conv.get_reply()
With the setting enabled, ``msg2`` will be ``'Hi!'`` and
``msg3`` be ``'How are you?'`` since replies are also
responses, and a response was already returned.
With the setting disabled, both ``msg2`` and ``msg3`` will
be ``'Hi!'`` since one is a response and also a reply.
Returns
A `Conversation <telethon.tl.custom.conversation.Conversation>`.
Example
.. code-block:: python
# <you> denotes outgoing messages you sent
# <usr> denotes incoming response messages
with bot.conversation(chat) as conv:
# <you> Hi!
conv.send_message('Hi!')
# <usr> Hello!
hello = conv.get_response()
# <you> Please tell me your name
conv.send_message('Please tell me your name')
# <usr> ?
name = conv.get_response().raw_text
while not any(x.isalpha() for x in name):
# <you> Your name didn't have any letters! Try again
conv.send_message("Your name didn't have any letters! Try again")
# <usr> Human
name = conv.get_response().raw_text
# <you> Thanks Human!
conv.send_message('Thanks {}!'.format(name))
"""
return custom.Conversation(
self,
entity,
timeout=timeout,
total_timeout=total_timeout,
max_messages=max_messages,
exclusive=exclusive,
replies_are_responses=replies_are_responses
)
|
class DialogMethods:
def iter_dialogs(
self: 'TelegramClient',
limit: float = None,
*,
offset_date: 'hints.DateLike' = None,
offset_id: int = 0,
offset_peer: 'hints.EntityLike' = types.InputPeerEmpty(),
ignore_pinned:
'''
Iterator over the dialogs (open conversations/subscribed channels).
The order is the same as the one seen in official applications
(first pinned, them from those with the most recent message to
those with the oldest message).
Arguments
limit (`int` | `None`):
How many dialogs to be retrieved as maximum. Can be set to
`None` to retrieve all dialogs. Note that this may take
whole minutes if you have hundreds of dialogs, as Telegram
will tell the library to slow down through a
``FloodWaitError``.
offset_date (`datetime`, optional):
The offset date to be used.
offset_id (`int`, optional):
The message ID to be used as an offset.
offset_peer (:tl:`InputPeer`, optional):
The peer to be used as an offset.
ignore_pinned (`bool`, optional):
Whether pinned dialogs should be ignored or not.
When set to `True`, these won't be yielded at all.
ignore_migrated (`bool`, optional):
Whether :tl:`Chat` that have ``migrated_to`` a :tl:`Channel`
should be included or not. By default all the chats in your
dialogs are returned, but setting this to `True` will ignore
(i.e. skip) them in the same way official applications do.
folder (`int`, optional):
The folder from which the dialogs should be retrieved.
If left unspecified, all dialogs (including those from
folders) will be returned.
If set to ``0``, all dialogs that don't belong to any
folder will be returned.
If set to a folder number like ``1``, only those from
said folder will be returned.
By default Telegram assigns the folder ID ``1`` to
archived chats, so you should use that if you need
to fetch the archived dialogs.
archived (`bool`, optional):
Alias for `folder`. If unspecified, all will be returned,
`False` implies ``folder=0`` and `True` implies ``folder=1``.
Yields
Instances of `Dialog <telethon.tl.custom.dialog.Dialog>`.
Example
.. code-block:: python
# Print all dialog IDs and the title, nicely formatted
async for dialog in client.iter_dialogs():
print('{:>14}: {}'.format(dialog.id, dialog.title))
'''
pass
async def get_dialogs(self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList':
'''
Same as `iter_dialogs()`, but returns a
`TotalList <telethon.helpers.TotalList>` instead.
Example
.. code-block:: python
# Get all open conversation, print the title of the first
dialogs = await client.get_dialogs()
first = dialogs[0]
print(first.title)
# Use the dialog somewhere else
await client.send_message(first, 'hi')
# Getting only non-archived dialogs (both equivalent)
non_archived = await client.get_dialogs(folder=0)
non_archived = await client.get_dialogs(archived=False)
# Getting only archived dialogs (both equivalent)
archived = await client.get_dialogs(folder=1)
archived = await client.get_dialogs(archived=True)
'''
pass
def iter_drafts(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None
) -> _DraftsIter:
'''
Iterator over draft messages.
The order is unspecified.
Arguments
entity (`hints.EntitiesLike`, optional):
The entity or entities for which to fetch the draft messages.
If left unspecified, all draft messages will be returned.
Yields
Instances of `Draft <telethon.tl.custom.draft.Draft>`.
Example
.. code-block:: python
# Clear all drafts
async for draft in client.get_drafts():
await draft.delete()
# Getting the drafts with 'bot1' and 'bot2'
async for draft in client.iter_drafts(['bot1', 'bot2']):
print(draft.text)
'''
pass
async def get_drafts(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None
) -> 'hints.TotalList':
'''
Same as `iter_drafts()`, but returns a list instead.
Example
.. code-block:: python
# Get drafts, print the text of the first
drafts = await client.get_drafts()
print(drafts[0].text)
# Get the draft in your chat
draft = await client.get_drafts('me')
print(drafts.text)
'''
pass
async def edit_folder(
self: 'TelegramClient',
entity: 'hints.EntitiesLike' = None,
folder: typing.Union[int, typing.Sequence[int]] = None,
*,
unpack=None
) -> types.Updates:
'''
Edits the folder used by one or more dialogs to archive them.
Arguments
entity (entities):
The entity or list of entities to move to the desired
archive folder.
folder (`int`):
The folder to which the dialog should be archived to.
If you want to "archive" a dialog, use ``folder=1``.
If you want to "un-archive" it, use ``folder=0``.
You may also pass a list with the same length as
`entities` if you want to control where each entity
will go.
unpack (`int`, optional):
If you want to unpack an archived folder, set this
parameter to the folder number that you want to
delete.
When you unpack a folder, all the dialogs inside are
moved to the folder number 0.
You can only use this parameter if the other two
are not set.
Returns
The :tl:`Updates` object that the request produces.
Example
.. code-block:: python
# Archiving the first 5 dialogs
dialogs = await client.get_dialogs(5)
await client.edit_folder(dialogs, 1)
# Un-archiving the third dialog (archiving to folder 0)
await client.edit_folder(dialog[2], 0)
# Moving the first dialog to folder 0 and the second to 1
dialogs = await client.get_dialogs(2)
await client.edit_folder(dialogs, [0, 1])
# Un-archiving all dialogs
await client.edit_folder(unpack=1)
'''
pass
async def delete_dialog(
self: 'TelegramClient',
entity: 'hints.EntityLike',
*,
revoke: bool = False
):
'''
Deletes a dialog (leaves a chat or channel).
This method can be used as a user and as a bot. However,
bots will only be able to use it to leave groups and channels
(trying to delete a private conversation will do nothing).
See also `Dialog.delete() <telethon.tl.custom.dialog.Dialog.delete>`.
Arguments
entity (entities):
The entity of the dialog to delete. If it's a chat or
channel, you will leave it. Note that the chat itself
is not deleted, only the dialog, because you left it.
revoke (`bool`, optional):
On private chats, you may revoke the messages from
the other peer too. By default, it's `False`. Set
it to `True` to delete the history for both.
This makes no difference for bot accounts, who can
only leave groups and channels.
Returns
The :tl:`Updates` object that the request produces,
or nothing for private conversations.
Example
.. code-block:: python
# Deleting the first dialog
dialogs = await client.get_dialogs(5)
await client.delete_dialog(dialogs[0])
# Leaving a channel by username
await client.delete_dialog('username')
'''
pass
def conversation(
self: 'TelegramClient',
entity: 'hints.EntityLike',
*,
timeout: float = 60,
total_timeout: float = None,
max_messages: int = 100,
exclusive: bool = True,
replies_are_responses: bool = True) -> custom.Conversation:
'''
Creates a `Conversation <telethon.tl.custom.conversation.Conversation>`
with the given entity.
.. note::
This Conversation API has certain shortcomings, such as lacking
persistence, poor interaction with other event handlers, and
overcomplicated usage for anything beyond the simplest case.
If you plan to interact with a bot without handlers, this works
fine, but when running a bot yourself, you may instead prefer
to follow the advice from https://stackoverflow.com/a/62246569/.
This is not the same as just sending a message to create a "dialog"
with them, but rather a way to easily send messages and await for
responses or other reactions. Refer to its documentation for more.
Arguments
entity (`entity`):
The entity with which a new conversation should be opened.
timeout (`int` | `float`, optional):
The default timeout (in seconds) *per action* to be used. You
may also override this timeout on a per-method basis. By
default each action can take up to 60 seconds (the value of
this timeout).
total_timeout (`int` | `float`, optional):
The total timeout (in seconds) to use for the whole
conversation. This takes priority over per-action
timeouts. After these many seconds pass, subsequent
actions will result in ``asyncio.TimeoutError``.
max_messages (`int`, optional):
The maximum amount of messages this conversation will
remember. After these many messages arrive in the
specified chat, subsequent actions will result in
``ValueError``.
exclusive (`bool`, optional):
By default, conversations are exclusive within a single
chat. That means that while a conversation is open in a
chat, you can't open another one in the same chat, unless
you disable this flag.
If you try opening an exclusive conversation for
a chat where it's already open, it will raise
``AlreadyInConversationError``.
replies_are_responses (`bool`, optional):
Whether replies should be treated as responses or not.
If the setting is enabled, calls to `conv.get_response
<telethon.tl.custom.conversation.Conversation.get_response>`
and a subsequent call to `conv.get_reply
<telethon.tl.custom.conversation.Conversation.get_reply>`
will return different messages, otherwise they may return
the same message.
Consider the following scenario with one outgoing message,
1, and two incoming messages, the second one replying::
Hello! <1
2> (reply to 1) Hi!
3> (reply to 1) How are you?
And the following code:
.. code-block:: python
async with client.conversation(chat) as conv:
msg1 = await conv.send_message('Hello!')
msg2 = await conv.get_response()
msg3 = await conv.get_reply()
With the setting enabled, ``msg2`` will be ``'Hi!'`` and
``msg3`` be ``'How are you?'`` since replies are also
responses, and a response was already returned.
With the setting disabled, both ``msg2`` and ``msg3`` will
be ``'Hi!'`` since one is a response and also a reply.
Returns
A `Conversation <telethon.tl.custom.conversation.Conversation>`.
Example
.. code-block:: python
# <you> denotes outgoing messages you sent
# <usr> denotes incoming response messages
with bot.conversation(chat) as conv:
# <you> Hi!
conv.send_message('Hi!')
# <usr> Hello!
hello = conv.get_response()
# <you> Please tell me your name
conv.send_message('Please tell me your name')
# <usr> ?
name = conv.get_response().raw_text
while not any(x.isalpha() for x in name):
# <you> Your name didn't have any letters! Try again
conv.send_message("Your name didn't have any letters! Try again")
# <usr> Human
name = conv.get_response().raw_text
# <you> Thanks Human!
conv.send_message('Thanks {}!'.format(name))
'''
pass
| 8 | 7 | 65 | 13 | 16 | 36 | 3 | 2.16 | 0 | 8 | 3 | 0 | 7 | 0 | 7 | 7 | 466 | 100 | 116 | 49 | 72 | 250 | 49 | 13 | 41 | 7 | 0 | 2 | 22 |
146,779 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/uploads.py
|
telethon.client.uploads.UploadMethods
|
class UploadMethods:
# region Public methods
async def send_file(
self: 'TelegramClient',
entity: 'hints.EntityLike',
file: 'typing.Union[hints.FileLike, typing.Sequence[hints.FileLike]]',
*,
caption: typing.Union[str, typing.Sequence[str]] = None,
force_document: bool = False,
file_size: int = None,
clear_draft: bool = False,
progress_callback: 'hints.ProgressCallback' = None,
reply_to: 'hints.MessageIDLike' = None,
attributes: 'typing.Sequence[types.TypeDocumentAttribute]' = None,
thumb: 'hints.FileLike' = None,
allow_cache: bool = True,
parse_mode: str = (),
formatting_entities: typing.Optional[
typing.Union[
typing.List[types.TypeMessageEntity], typing.List[typing.List[types.TypeMessageEntity]]
]
] = None,
voice_note: bool = False,
video_note: bool = False,
buttons: typing.Optional['hints.MarkupLike'] = None,
silent: bool = None,
background: bool = None,
supports_streaming: bool = False,
schedule: 'hints.DateLike' = None,
comment_to: 'typing.Union[int, types.Message]' = None,
ttl: int = None,
nosound_video: bool = None,
**kwargs) -> typing.Union[typing.List[typing.Any], typing.Any]:
"""
Sends message with the given file to the specified entity.
.. note::
If the ``hachoir3`` package (``hachoir`` module) is installed,
it will be used to determine metadata from audio and video files.
If the ``pillow`` package is installed and you are sending a photo,
it will be resized to fit within the maximum dimensions allowed
by Telegram to avoid ``errors.PhotoInvalidDimensionsError``. This
cannot be done if you are sending :tl:`InputFile`, however.
Arguments
entity (`entity`):
Who will receive the file.
file (`str` | `bytes` | `file` | `media`):
The file to send, which can be one of:
* A local file path to an in-disk file. The file name
will be the path's base name.
* A `bytes` byte array with the file's data to send
(for example, by using ``text.encode('utf-8')``).
A default file name will be used.
* A bytes `io.IOBase` stream over the file to send
(for example, by using ``open(file, 'rb')``).
Its ``.name`` property will be used for the file name,
or a default if it doesn't have one.
* An external URL to a file over the internet. This will
send the file as "external" media, and Telegram is the
one that will fetch the media and send it.
* A Bot API-like ``file_id``. You can convert previously
sent media to file IDs for later reusing with
`telethon.utils.pack_bot_file_id`.
* A handle to an existing file (for example, if you sent a
message with media before, you can use its ``message.media``
as a file here).
* A handle to an uploaded file (from `upload_file`).
* A :tl:`InputMedia` instance. For example, if you want to
send a dice use :tl:`InputMediaDice`, or if you want to
send a contact use :tl:`InputMediaContact`.
To send an album, you should provide a list in this parameter.
If a list or similar is provided, the files in it will be
sent as an album in the order in which they appear, sliced
in chunks of 10 if more than 10 are given.
caption (`str`, optional):
Optional caption for the sent media message. When sending an
album, the caption may be a list of strings, which will be
assigned to the files pairwise.
force_document (`bool`, optional):
If left to `False` and the file is a path that ends with
the extension of an image file or a video file, it will be
sent as such. Otherwise always as a document.
file_size (`int`, optional):
The size of the file to be uploaded if it needs to be uploaded,
which will be determined automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
clear_draft (`bool`, optional):
Whether the existing draft should be cleared or not.
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`):
Same as `reply_to` from `send_message`.
attributes (`list`, optional):
Optional attributes that override the inferred ones, like
:tl:`DocumentAttributeFilename` and so on.
thumb (`str` | `bytes` | `file`, optional):
Optional JPEG thumbnail (for documents). **Telegram will
ignore this parameter** unless you pass a ``.jpg`` file!
The file must also be small in dimensions and in disk size.
Successful thumbnails were files below 20kB and 320x320px.
Width/height and dimensions/size ratios may be important.
For Telegram to accept a thumbnail, you must provide the
dimensions of the underlying media through ``attributes=``
with :tl:`DocumentAttributesVideo` or by installing the
optional ``hachoir`` dependency.
allow_cache (`bool`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
parse_mode (`object`, optional):
See the `TelegramClient.parse_mode
<telethon.client.messageparse.MessageParseMethods.parse_mode>`
property for allowed values. Markdown parsing will be used by
default.
formatting_entities (`list`, optional):
Optional formatting entities for the sent media message. When sending an album,
`formatting_entities` can be a list of lists, where each inner list contains
`types.TypeMessageEntity`. Each inner list will be assigned to the corresponding
file in a pairwise manner with the caption. If provided, the ``parse_mode``
parameter will be ignored.
voice_note (`bool`, optional):
If `True` the audio will be sent as a voice note.
video_note (`bool`, optional):
If `True` the video will be sent as a video note,
also known as a round video message.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`):
The matrix (list of lists), row list or button to be shown
after sending the message. This parameter will only work if
you have signed in as a bot. You can also pass your own
:tl:`ReplyMarkup` here.
silent (`bool`, optional):
Whether the message should notify people with sound or not.
Defaults to `False` (send with a notification sound unless
the person has the chat muted). Set it to `True` to alter
this behaviour.
background (`bool`, optional):
Whether the message should be send in background.
supports_streaming (`bool`, optional):
Whether the sent video supports streaming or not. Note that
Telegram only recognizes as streamable some formats like MP4,
and others like AVI or MKV will not work. You should convert
these to MP4 before sending if you want them to be streamable.
Unsupported formats will result in ``VideoContentTypeError``.
schedule (`hints.DateLike`, optional):
If set, the file won't send immediately, and instead
it will be scheduled to be automatically sent at a later
time.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to"
the specified message).
This parameter takes precedence over ``reply_to``. If there is
no linked chat, `telethon.errors.sgIdInvalidError` is raised.
ttl (`int`. optional):
The Time-To-Live of the file (also known as "self-destruct timer"
or "self-destructing media"). If set, files can only be viewed for
a short period of time before they disappear from the message
history automatically.
The value must be at least 1 second, and at most 60 seconds,
otherwise Telegram will ignore this parameter.
Not all types of media can be used with this parameter, such
as text documents, which will fail with ``TtlMediaInvalidError``.
nosound_video (`bool`, optional):
Only applicable when sending a video file without an audio
track. If set to ``True``, the video will be displayed in
Telegram as a video. If set to ``False``, Telegram will attempt
to display the video as an animated gif. (It may still display
as a video due to other factors.) The value is ignored if set
on non-video files. This is set to ``True`` for albums, as gifs
cannot be sent in albums.
Returns
The `Message <telethon.tl.custom.message.Message>` (or messages)
containing the sent file, or messages if a list of them was passed.
Example
.. code-block:: python
# Normal files like photos
await client.send_file(chat, '/my/photos/me.jpg', caption="It's me!")
# or
await client.send_message(chat, "It's me!", file='/my/photos/me.jpg')
# Voice notes or round videos
await client.send_file(chat, '/my/songs/song.mp3', voice_note=True)
await client.send_file(chat, '/my/videos/video.mp4', video_note=True)
# Custom thumbnails
await client.send_file(chat, '/my/documents/doc.txt', thumb='photo.jpg')
# Only documents
await client.send_file(chat, '/my/photos/photo.png', force_document=True)
# Albums
await client.send_file(chat, [
'/my/photos/holiday1.jpg',
'/my/photos/holiday2.jpg',
'/my/drawings/portrait.png'
])
# Printing upload progress
def callback(current, total):
print('Uploaded', current, 'out of', total,
'bytes: {:.2%}'.format(current / total))
await client.send_file(chat, file, progress_callback=callback)
# Dices, including dart and other future emoji
from telethon.tl import types
await client.send_file(chat, types.InputMediaDice(''))
await client.send_file(chat, types.InputMediaDice('🎯'))
# Contacts
await client.send_file(chat, types.InputMediaContact(
phone_number='+34 123 456 789',
first_name='Example',
last_name='',
vcard=''
))
"""
# TODO Properly implement allow_cache to reuse the sha256 of the file
# i.e. `None` was used
if not file:
raise TypeError('Cannot use {!r} as file'.format(file))
if not caption:
caption = ''
if not formatting_entities:
formatting_entities = []
entity = await self.get_input_entity(entity)
if comment_to is not None:
entity, reply_to = await self._get_comment_data(entity, comment_to)
else:
reply_to = utils.get_message_id(reply_to)
# First check if the user passed an iterable, in which case
# we may want to send grouped.
if utils.is_list_like(file):
sent_count = 0
used_callback = None if not progress_callback else (
lambda s, t: progress_callback(sent_count + s, len(file))
)
if utils.is_list_like(caption):
captions = caption
else:
captions = [caption]
# Check that formatting_entities list is valid
if all(utils.is_list_like(obj) for obj in formatting_entities):
formatting_entities = formatting_entities
elif utils.is_list_like(formatting_entities):
formatting_entities = [formatting_entities]
else:
raise TypeError('The formatting_entities argument must be a list or a sequence of lists')
# Check that all entities in all lists are of the correct type
if not all(isinstance(ent, types.TypeMessageEntity) for sublist in formatting_entities for ent in sublist):
raise TypeError('All entities must be instances of <types.TypeMessageEntity>')
result = []
while file:
result += await self._send_album(
entity, file[:10], caption=captions[:10], formatting_entities=formatting_entities[:10],
progress_callback=used_callback, reply_to=reply_to,
parse_mode=parse_mode, silent=silent, schedule=schedule,
supports_streaming=supports_streaming, clear_draft=clear_draft,
force_document=force_document, background=background,
)
file = file[10:]
captions = captions[10:]
formatting_entities = formatting_entities[10:]
sent_count += 10
return result
if formatting_entities:
msg_entities = formatting_entities
else:
caption, msg_entities =\
await self._parse_message_text(caption, parse_mode)
file_handle, media, image = await self._file_to_media(
file, force_document=force_document,
file_size=file_size,
progress_callback=progress_callback,
attributes=attributes, allow_cache=allow_cache, thumb=thumb,
voice_note=voice_note, video_note=video_note,
supports_streaming=supports_streaming, ttl=ttl,
nosound_video=nosound_video,
)
# e.g. invalid cast from :tl:`MessageMediaWebPage`
if not media:
raise TypeError('Cannot use {!r} as file'.format(file))
markup = self.build_reply_markup(buttons)
reply_to = None if reply_to is None else types.InputReplyToMessage(reply_to)
request = functions.messages.SendMediaRequest(
entity, media, reply_to=reply_to, message=caption,
entities=msg_entities, reply_markup=markup, silent=silent,
schedule_date=schedule, clear_draft=clear_draft,
background=background
)
return self._get_response_message(request, await self(request), entity)
async def _send_album(self: 'TelegramClient', entity, files, caption='',
formatting_entities=None,
progress_callback=None, reply_to=None,
parse_mode=(), silent=None, schedule=None,
supports_streaming=None, clear_draft=None,
force_document=False, background=None, ttl=None):
"""Specialized version of .send_file for albums"""
# We don't care if the user wants to avoid cache, we will use it
# anyway. Why? The cached version will be exactly the same thing
# we need to produce right now to send albums (uploadMedia), and
# cache only makes a difference for documents where the user may
# want the attributes used on them to change.
#
# In theory documents can be sent inside the albums, but they appear
# as different messages (not inside the album), and the logic to set
# the attributes/avoid cache is already written in .send_file().
entity = await self.get_input_entity(entity)
if not utils.is_list_like(caption):
caption = (caption,)
if not all(isinstance(obj, list) for obj in formatting_entities):
formatting_entities = (formatting_entities,)
captions = []
# If the formatting_entities argument is provided, we don't use parse_mode
if formatting_entities:
# Pop from the end (so reverse)
capt_with_ent = itertools.zip_longest(reversed(caption), reversed(formatting_entities), fillvalue=None)
for msg_caption, msg_entities in capt_with_ent:
captions.append((msg_caption, msg_entities))
else:
for c in reversed(caption): # Pop from the end (so reverse)
captions.append(await self._parse_message_text(c or '', parse_mode))
reply_to = utils.get_message_id(reply_to)
used_callback = None if not progress_callback else (
# use an integer when sent matches total, to easily determine a file has been fully sent
lambda s, t: progress_callback(sent_count + 1 if s == t else sent_count + s / t, len(files))
)
# Need to upload the media first, but only if they're not cached yet
media = []
for sent_count, file in enumerate(files):
# Albums want :tl:`InputMedia` which, in theory, includes
# :tl:`InputMediaUploadedPhoto`. However, using that will
# make it `raise MediaInvalidError`, so we need to upload
# it as media and then convert that to :tl:`InputMediaPhoto`.
fh, fm, _ = await self._file_to_media(
file, supports_streaming=supports_streaming,
force_document=force_document, ttl=ttl,
progress_callback=used_callback, nosound_video=True)
if isinstance(fm, (types.InputMediaUploadedPhoto, types.InputMediaPhotoExternal)):
r = await self(functions.messages.UploadMediaRequest(
entity, media=fm
))
fm = utils.get_input_media(r.photo)
elif isinstance(fm, (types.InputMediaUploadedDocument, types.InputMediaDocumentExternal)):
r = await self(functions.messages.UploadMediaRequest(
entity, media=fm
))
fm = utils.get_input_media(
r.document, supports_streaming=supports_streaming)
if captions:
caption, msg_entities = captions.pop()
else:
caption, msg_entities = '', None
media.append(types.InputSingleMedia(
fm,
message=caption,
entities=msg_entities
# random_id is autogenerated
))
# Now we can construct the multi-media request
request = functions.messages.SendMultiMediaRequest(
entity, reply_to=None if reply_to is None else types.InputReplyToMessage(reply_to), multi_media=media,
silent=silent, schedule_date=schedule, clear_draft=clear_draft,
background=background
)
result = await self(request)
random_ids = [m.random_id for m in media]
return self._get_response_message(random_ids, result, entity)
async def upload_file(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
part_size_kb: float = None,
file_size: int = None,
file_name: str = None,
use_cache: type = None,
key: bytes = None,
iv: bytes = None,
progress_callback: 'hints.ProgressCallback' = None) -> 'types.TypeInputFile':
"""
Uploads a file to Telegram's servers, without sending it.
.. note::
Generally, you want to use `send_file` instead.
This method returns a handle (an instance of :tl:`InputFile` or
:tl:`InputFileBig`, as required) which can be later used before
it expires (they are usable during less than a day).
Uploading a file will simply return a "handle" to the file stored
remotely in the Telegram servers, which can be later used on. This
will **not** upload the file to your own chat or any chat at all.
Arguments
file (`str` | `bytes` | `file`):
The path of the file, byte array, or stream that will be sent.
Note that if a byte array or a stream is given, a filename
or its type won't be inferred, and it will be sent as an
"unnamed application/octet-stream".
part_size_kb (`int`, optional):
Chunk size when uploading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The size of the file to be uploaded, which will be determined
automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
file_name (`str`, optional):
The file name which will be used on the resulting InputFile.
If not specified, the name will be taken from the ``file``
and if this is not a `str`, it will be ``"unnamed"``.
use_cache (`type`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
When sending an album, the callback will receive a number
between 0 and the amount of files as the "sent" parameter,
and the amount of files as the "total". Note that the first
parameter will be a floating point number to indicate progress
within a file (e.g. ``2.5`` means it has sent 50% of the third
file, because it's between 2 and 3).
Returns
:tl:`InputFileBig` if the file size is larger than 10MB,
`InputSizedFile <telethon.tl.custom.inputsizedfile.InputSizedFile>`
(subclass of :tl:`InputFile`) otherwise.
Example
.. code-block:: python
# Photos as photo and document
file = await client.upload_file('photo.jpg')
await client.send_file(chat, file) # sends as photo
await client.send_file(chat, file, force_document=True) # sends as document
file.name = 'not a photo.jpg'
await client.send_file(chat, file, force_document=True) # document, new name
# As song or as voice note
file = await client.upload_file('song.ogg')
await client.send_file(chat, file) # sends as song
await client.send_file(chat, file, voice_note=True) # sends as voice note
"""
if isinstance(file, (types.InputFile, types.InputFileBig)):
return file # Already uploaded
pos = 0
async with helpers._FileStream(file, file_size=file_size) as stream:
# Opening the stream will determine the correct file size
file_size = stream.file_size
if not part_size_kb:
part_size_kb = utils.get_appropriated_part_size(file_size)
if part_size_kb > 512:
raise ValueError('The part size must be less or equal to 512KB')
part_size = int(part_size_kb * 1024)
if part_size % 1024 != 0:
raise ValueError(
'The part size must be evenly divisible by 1024')
# Set a default file name if None was specified
file_id = helpers.generate_random_long()
if not file_name:
file_name = stream.name or str(file_id)
# If the file name lacks extension, add it if possible.
# Else Telegram complains with `PHOTO_EXT_INVALID_ERROR`
# even if the uploaded image is indeed a photo.
if not os.path.splitext(file_name)[-1]:
file_name += utils._get_extension(stream)
# Determine whether the file is too big (over 10MB) or not
# Telegram does make a distinction between smaller or larger files
is_big = file_size > 10 * 1024 * 1024
hash_md5 = hashlib.md5()
part_count = (file_size + part_size - 1) // part_size
self._log[__name__].info('Uploading file of %d bytes in %d chunks of %d',
file_size, part_count, part_size)
pos = 0
for part_index in range(part_count):
# Read the file by in chunks of size part_size
part = await helpers._maybe_await(stream.read(part_size))
if not isinstance(part, bytes):
raise TypeError(
'file descriptor returned {}, not bytes (you must '
'open the file in bytes mode)'.format(type(part)))
# `file_size` could be wrong in which case `part` may not be
# `part_size` before reaching the end.
if len(part) != part_size and part_index < part_count - 1:
raise ValueError(
'read less than {} before reaching the end; either '
'`file_size` or `read` are wrong'.format(part_size))
pos += len(part)
# Encryption part if needed
if key and iv:
part = AES.encrypt_ige(part, key, iv)
if not is_big:
# Bit odd that MD5 is only needed for small files and not
# big ones with more chance for corruption, but that's
# what Telegram wants.
hash_md5.update(part)
# The SavePartRequest is different depending on whether
# the file is too large or not (over or less than 10MB)
if is_big:
request = functions.upload.SaveBigFilePartRequest(
file_id, part_index, part_count, part)
else:
request = functions.upload.SaveFilePartRequest(
file_id, part_index, part)
result = await self(request)
if result:
self._log[__name__].debug('Uploaded %d/%d',
part_index + 1, part_count)
if progress_callback:
await helpers._maybe_await(progress_callback(pos, file_size))
else:
raise RuntimeError(
'Failed to upload file part {}.'.format(part_index))
if is_big:
return types.InputFileBig(file_id, part_count, file_name)
else:
return custom.InputSizedFile(
file_id, part_count, file_name, md5=hash_md5, size=file_size
)
# endregion
async def _file_to_media(
self, file, force_document=False, file_size=None,
progress_callback=None, attributes=None, thumb=None,
allow_cache=True, voice_note=False, video_note=False,
supports_streaming=False, mime_type=None, as_image=None,
ttl=None, nosound_video=None):
if not file:
return None, None, None
if isinstance(file, pathlib.Path):
file = str(file.absolute())
is_image = utils.is_image(file)
if as_image is None:
as_image = is_image and not force_document
# `aiofiles` do not base `io.IOBase` but do have `read`, so we
# just check for the read attribute to see if it's file-like.
if not isinstance(file, (str, bytes, types.InputFile, types.InputFileBig)) \
and not hasattr(file, 'read'):
# The user may pass a Message containing media (or the media,
# or anything similar) that should be treated as a file. Try
# getting the input media for whatever they passed and send it.
#
# We pass all attributes since these will be used if the user
# passed :tl:`InputFile`, and all information may be relevant.
try:
return (None, utils.get_input_media(
file,
is_photo=as_image,
attributes=attributes,
force_document=force_document,
voice_note=voice_note,
video_note=video_note,
supports_streaming=supports_streaming,
ttl=ttl
), as_image)
except TypeError:
# Can't turn whatever was given into media
return None, None, as_image
media = None
file_handle = None
if isinstance(file, (types.InputFile, types.InputFileBig)):
file_handle = file
elif not isinstance(file, str) or os.path.isfile(file):
file_handle = await self.upload_file(
_resize_photo_if_needed(file, as_image),
file_size=file_size,
progress_callback=progress_callback
)
elif re.match('https?://', file):
if as_image:
media = types.InputMediaPhotoExternal(file, ttl_seconds=ttl)
else:
media = types.InputMediaDocumentExternal(file, ttl_seconds=ttl)
else:
bot_file = utils.resolve_bot_file_id(file)
if bot_file:
media = utils.get_input_media(bot_file, ttl=ttl)
if media:
pass # Already have media, don't check the rest
elif not file_handle:
raise ValueError(
'Failed to convert {} to media. Not an existing file, '
'an HTTP URL or a valid bot-API-like file ID'.format(file)
)
elif as_image:
media = types.InputMediaUploadedPhoto(file_handle, ttl_seconds=ttl)
else:
attributes, mime_type = utils.get_attributes(
file,
mime_type=mime_type,
attributes=attributes,
force_document=force_document and not is_image,
voice_note=voice_note,
video_note=video_note,
supports_streaming=supports_streaming,
thumb=thumb
)
if not thumb:
thumb = None
else:
if isinstance(thumb, pathlib.Path):
thumb = str(thumb.absolute())
thumb = await self.upload_file(thumb, file_size=file_size)
# setting `nosound_video` to `True` doesn't affect videos with sound
# instead it prevents sending silent videos as GIFs
nosound_video = nosound_video if mime_type.split("/")[0] == 'video' else None
media = types.InputMediaUploadedDocument(
file=file_handle,
mime_type=mime_type,
attributes=attributes,
thumb=thumb,
force_file=force_document and not is_image,
ttl_seconds=ttl,
nosound_video=nosound_video
)
return file_handle, media, as_image
|
class UploadMethods:
async def send_file(
self: 'TelegramClient',
entity: 'hints.EntityLike',
file: 'typing.Union[hints.FileLike, typing.Sequence[hints.FileLike]]',
*,
caption: typing.Union[str, typing.Sequence[str]] = None,
force_document: bool = False,
file_size: int = None,
clear_draft: bool = False,
progress_callback: 'hints.ProgressCallback' = None,
reply_to: 'hints.MessageIDLike' = None,
attributes: 'typing.Sequence[types.TypeDocumentAttribute]' = None,
thumb: 'hints.FileLike' = None,
allow_cache: bool = True,
parse_mode: str = (),
formatting_entities:
'''
Sends message with the given file to the specified entity.
.. note::
If the ``hachoir3`` package (``hachoir`` module) is installed,
it will be used to determine metadata from audio and video files.
If the ``pillow`` package is installed and you are sending a photo,
it will be resized to fit within the maximum dimensions allowed
by Telegram to avoid ``errors.PhotoInvalidDimensionsError``. This
cannot be done if you are sending :tl:`InputFile`, however.
Arguments
entity (`entity`):
Who will receive the file.
file (`str` | `bytes` | `file` | `media`):
The file to send, which can be one of:
* A local file path to an in-disk file. The file name
will be the path's base name.
* A `bytes` byte array with the file's data to send
(for example, by using ``text.encode('utf-8')``).
A default file name will be used.
* A bytes `io.IOBase` stream over the file to send
(for example, by using ``open(file, 'rb')``).
Its ``.name`` property will be used for the file name,
or a default if it doesn't have one.
* An external URL to a file over the internet. This will
send the file as "external" media, and Telegram is the
one that will fetch the media and send it.
* A Bot API-like ``file_id``. You can convert previously
sent media to file IDs for later reusing with
`telethon.utils.pack_bot_file_id`.
* A handle to an existing file (for example, if you sent a
message with media before, you can use its ``message.media``
as a file here).
* A handle to an uploaded file (from `upload_file`).
* A :tl:`InputMedia` instance. For example, if you want to
send a dice use :tl:`InputMediaDice`, or if you want to
send a contact use :tl:`InputMediaContact`.
To send an album, you should provide a list in this parameter.
If a list or similar is provided, the files in it will be
sent as an album in the order in which they appear, sliced
in chunks of 10 if more than 10 are given.
caption (`str`, optional):
Optional caption for the sent media message. When sending an
album, the caption may be a list of strings, which will be
assigned to the files pairwise.
force_document (`bool`, optional):
If left to `False` and the file is a path that ends with
the extension of an image file or a video file, it will be
sent as such. Otherwise always as a document.
file_size (`int`, optional):
The size of the file to be uploaded if it needs to be uploaded,
which will be determined automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
clear_draft (`bool`, optional):
Whether the existing draft should be cleared or not.
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`):
Same as `reply_to` from `send_message`.
attributes (`list`, optional):
Optional attributes that override the inferred ones, like
:tl:`DocumentAttributeFilename` and so on.
thumb (`str` | `bytes` | `file`, optional):
Optional JPEG thumbnail (for documents). **Telegram will
ignore this parameter** unless you pass a ``.jpg`` file!
The file must also be small in dimensions and in disk size.
Successful thumbnails were files below 20kB and 320x320px.
Width/height and dimensions/size ratios may be important.
For Telegram to accept a thumbnail, you must provide the
dimensions of the underlying media through ``attributes=``
with :tl:`DocumentAttributesVideo` or by installing the
optional ``hachoir`` dependency.
allow_cache (`bool`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
parse_mode (`object`, optional):
See the `TelegramClient.parse_mode
<telethon.client.messageparse.MessageParseMethods.parse_mode>`
property for allowed values. Markdown parsing will be used by
default.
formatting_entities (`list`, optional):
Optional formatting entities for the sent media message. When sending an album,
`formatting_entities` can be a list of lists, where each inner list contains
`types.TypeMessageEntity`. Each inner list will be assigned to the corresponding
file in a pairwise manner with the caption. If provided, the ``parse_mode``
parameter will be ignored.
voice_note (`bool`, optional):
If `True` the audio will be sent as a voice note.
video_note (`bool`, optional):
If `True` the video will be sent as a video note,
also known as a round video message.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`):
The matrix (list of lists), row list or button to be shown
after sending the message. This parameter will only work if
you have signed in as a bot. You can also pass your own
:tl:`ReplyMarkup` here.
silent (`bool`, optional):
Whether the message should notify people with sound or not.
Defaults to `False` (send with a notification sound unless
the person has the chat muted). Set it to `True` to alter
this behaviour.
background (`bool`, optional):
Whether the message should be send in background.
supports_streaming (`bool`, optional):
Whether the sent video supports streaming or not. Note that
Telegram only recognizes as streamable some formats like MP4,
and others like AVI or MKV will not work. You should convert
these to MP4 before sending if you want them to be streamable.
Unsupported formats will result in ``VideoContentTypeError``.
schedule (`hints.DateLike`, optional):
If set, the file won't send immediately, and instead
it will be scheduled to be automatically sent at a later
time.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to"
the specified message).
This parameter takes precedence over ``reply_to``. If there is
no linked chat, `telethon.errors.sgIdInvalidError` is raised.
ttl (`int`. optional):
The Time-To-Live of the file (also known as "self-destruct timer"
or "self-destructing media"). If set, files can only be viewed for
a short period of time before they disappear from the message
history automatically.
The value must be at least 1 second, and at most 60 seconds,
otherwise Telegram will ignore this parameter.
Not all types of media can be used with this parameter, such
as text documents, which will fail with ``TtlMediaInvalidError``.
nosound_video (`bool`, optional):
Only applicable when sending a video file without an audio
track. If set to ``True``, the video will be displayed in
Telegram as a video. If set to ``False``, Telegram will attempt
to display the video as an animated gif. (It may still display
as a video due to other factors.) The value is ignored if set
on non-video files. This is set to ``True`` for albums, as gifs
cannot be sent in albums.
Returns
The `Message <telethon.tl.custom.message.Message>` (or messages)
containing the sent file, or messages if a list of them was passed.
Example
.. code-block:: python
# Normal files like photos
await client.send_file(chat, '/my/photos/me.jpg', caption="It's me!")
# or
await client.send_message(chat, "It's me!", file='/my/photos/me.jpg')
# Voice notes or round videos
await client.send_file(chat, '/my/songs/song.mp3', voice_note=True)
await client.send_file(chat, '/my/videos/video.mp4', video_note=True)
# Custom thumbnails
await client.send_file(chat, '/my/documents/doc.txt', thumb='photo.jpg')
# Only documents
await client.send_file(chat, '/my/photos/photo.png', force_document=True)
# Albums
await client.send_file(chat, [
'/my/photos/holiday1.jpg',
'/my/photos/holiday2.jpg',
'/my/drawings/portrait.png'
])
# Printing upload progress
def callback(current, total):
print('Uploaded', current, 'out of', total,
'bytes: {:.2%}'.format(current / total))
await client.send_file(chat, file, progress_callback=callback)
# Dices, including dart and other future emoji
from telethon.tl import types
await client.send_file(chat, types.InputMediaDice(''))
await client.send_file(chat, types.InputMediaDice('🎯'))
# Contacts
await client.send_file(chat, types.InputMediaContact(
phone_number='+34 123 456 789',
first_name='Example',
last_name='',
vcard=''
))
'''
pass
async def _send_album(self: 'TelegramClient', entity, files, caption='',
formatting_entities=None,
progress_callback=None, reply_to=None,
parse_mode=(), silent=None, schedule=None,
supports_streaming=None, clear_draft=None,
force_document=False, background=None, ttl=None):
'''Specialized version of .send_file for albums'''
pass
async def upload_file(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
part_size_kb: float = None,
file_size: int = None,
file_name: str = None,
use_cache: type = None,
key: bytes = None,
iv: bytes = None,
progress_callback: 'hints.ProgressCallback' = None) -> 'types.TypeInputFile':
'''
Uploads a file to Telegram's servers, without sending it.
.. note::
Generally, you want to use `send_file` instead.
This method returns a handle (an instance of :tl:`InputFile` or
:tl:`InputFileBig`, as required) which can be later used before
it expires (they are usable during less than a day).
Uploading a file will simply return a "handle" to the file stored
remotely in the Telegram servers, which can be later used on. This
will **not** upload the file to your own chat or any chat at all.
Arguments
file (`str` | `bytes` | `file`):
The path of the file, byte array, or stream that will be sent.
Note that if a byte array or a stream is given, a filename
or its type won't be inferred, and it will be sent as an
"unnamed application/octet-stream".
part_size_kb (`int`, optional):
Chunk size when uploading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The size of the file to be uploaded, which will be determined
automatically if not specified.
If the file size can't be determined beforehand, the entire
file will be read in-memory to find out how large it is.
file_name (`str`, optional):
The file name which will be used on the resulting InputFile.
If not specified, the name will be taken from the ``file``
and if this is not a `str`, it will be ``"unnamed"``.
use_cache (`type`, optional):
This parameter currently does nothing, but is kept for
backward-compatibility (and it may get its use back in
the future).
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(sent bytes, total)``.
When sending an album, the callback will receive a number
between 0 and the amount of files as the "sent" parameter,
and the amount of files as the "total". Note that the first
parameter will be a floating point number to indicate progress
within a file (e.g. ``2.5`` means it has sent 50% of the third
file, because it's between 2 and 3).
Returns
:tl:`InputFileBig` if the file size is larger than 10MB,
`InputSizedFile <telethon.tl.custom.inputsizedfile.InputSizedFile>`
(subclass of :tl:`InputFile`) otherwise.
Example
.. code-block:: python
# Photos as photo and document
file = await client.upload_file('photo.jpg')
await client.send_file(chat, file) # sends as photo
await client.send_file(chat, file, force_document=True) # sends as document
file.name = 'not a photo.jpg'
await client.send_file(chat, file, force_document=True) # document, new name
# As song or as voice note
file = await client.upload_file('song.ogg')
await client.send_file(chat, file) # sends as song
await client.send_file(chat, file, voice_note=True) # sends as voice note
'''
pass
async def _file_to_media(
self, file, force_document=False, file_size=None,
progress_callback=None, attributes=None, thumb=None,
allow_cache=True, voice_note=False, video_note=False,
supports_streaming=False, mime_type=None, as_image=None,
ttl=None, nosound_video=None):
pass
| 5 | 3 | 186 | 31 | 80 | 76 | 16 | 0.96 | 0 | 16 | 1 | 0 | 4 | 0 | 4 | 4 | 751 | 128 | 320 | 95 | 261 | 306 | 156 | 39 | 151 | 17 | 0 | 4 | 62 |
146,780 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/updates.py
|
telethon.client.updates.EventBuilderDict
|
class EventBuilderDict:
"""
Helper "dictionary" to return events from types and cache them.
"""
def __init__(self, client: 'TelegramClient', update, others):
self.client = client
self.update = update
self.others = others
def __getitem__(self, builder):
try:
return self.__dict__[builder]
except KeyError:
event = self.__dict__[builder] = builder.build(
self.update, self.others, self.client._self_id)
if isinstance(event, EventCommon):
event.original_update = self.update
event._entities = self.update._entities
event._set_client(self.client)
elif event:
event._client = self.client
return event
|
class EventBuilderDict:
'''
Helper "dictionary" to return events from types and cache them.
'''
def __init__(self, client: 'TelegramClient', update, others):
pass
def __getitem__(self, builder):
pass
| 3 | 1 | 10 | 1 | 9 | 0 | 3 | 0.17 | 0 | 2 | 1 | 0 | 2 | 3 | 2 | 2 | 24 | 3 | 18 | 7 | 15 | 3 | 16 | 7 | 13 | 4 | 0 | 2 | 5 |
146,781 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/telegramclient.py
|
telethon.client.telegramclient.TelegramClient
|
class TelegramClient(
AccountMethods, AuthMethods, DownloadMethods, DialogMethods, ChatMethods,
BotMethods, MessageMethods, UploadMethods, ButtonMethods, UpdateMethods,
MessageParseMethods, UserMethods, TelegramBaseClient
):
pass
|
class TelegramClient(
AccountMethods, AuthMethods, DownloadMethods, DialogMethods, ChatMethods,
BotMethods, MessageMethods, UploadMethods, ButtonMethods, UpdateMethods,
MessageParseMethods, UserMethods, TelegramBaseClient
):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 6 | 0 | 6 | 5 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
146,782 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/messages.py
|
telethon.client.messages._MessagesIter
|
class _MessagesIter(RequestIter):
"""
Common factor for all requests that need to iterate over messages.
"""
async def _init(
self, entity, offset_id, min_id, max_id,
from_user, offset_date, add_offset, filter, search, reply_to,
scheduled
):
# Note that entity being `None` will perform a global search.
if entity:
self.entity = await self.client.get_input_entity(entity)
else:
self.entity = None
if self.reverse:
raise ValueError('Cannot reverse global search')
# Telegram doesn't like min_id/max_id. If these IDs are low enough
# (starting from last_id - 100), the request will return nothing.
#
# We can emulate their behaviour locally by setting offset = max_id
# and simply stopping once we hit a message with ID <= min_id.
if self.reverse:
offset_id = max(offset_id, min_id)
if offset_id and max_id:
if max_id - offset_id <= 1:
raise StopAsyncIteration
if not max_id:
max_id = float('inf')
else:
offset_id = max(offset_id, max_id)
if offset_id and min_id:
if offset_id - min_id <= 1:
raise StopAsyncIteration
if self.reverse:
if offset_id:
offset_id += 1
elif not offset_date:
# offset_id has priority over offset_date, so don't
# set offset_id to 1 if we want to offset by date.
offset_id = 1
if from_user:
from_user = await self.client.get_input_entity(from_user)
self.from_id = await self.client.get_peer_id(from_user)
else:
self.from_id = None
# `messages.searchGlobal` only works with text `search` or `filter` queries.
# If we want to perform global a search with `from_user` we have to perform
# a normal `messages.search`, *but* we can make the entity be `inputPeerEmpty`.
if not self.entity and from_user:
self.entity = types.InputPeerEmpty()
if filter is None:
filter = types.InputMessagesFilterEmpty()
else:
filter = filter() if isinstance(filter, type) else filter
if not self.entity:
self.request = functions.messages.SearchGlobalRequest(
q=search or '',
filter=filter,
min_date=None,
max_date=offset_date,
offset_rate=0,
offset_peer=types.InputPeerEmpty(),
offset_id=offset_id,
limit=1
)
elif scheduled:
self.request = functions.messages.GetScheduledHistoryRequest(
peer=entity,
hash=0
)
elif reply_to is not None:
self.request = functions.messages.GetRepliesRequest(
peer=self.entity,
msg_id=reply_to,
offset_id=offset_id,
offset_date=offset_date,
add_offset=add_offset,
limit=1,
max_id=0,
min_id=0,
hash=0
)
elif search is not None or not isinstance(filter, types.InputMessagesFilterEmpty) or from_user:
# Telegram completely ignores `from_id` in private chats
ty = helpers._entity_type(self.entity)
if ty == helpers._EntityType.USER:
# Don't bother sending `from_user` (it's ignored anyway),
# but keep `from_id` defined above to check it locally.
from_user = None
else:
# Do send `from_user` to do the filtering server-side,
# and set `from_id` to None to avoid checking it locally.
self.from_id = None
self.request = functions.messages.SearchRequest(
peer=self.entity,
q=search or '',
filter=filter,
min_date=None,
max_date=offset_date,
offset_id=offset_id,
add_offset=add_offset,
limit=0, # Search actually returns 0 items if we ask it to
max_id=0,
min_id=0,
hash=0,
from_id=from_user
)
# Workaround issue #1124 until a better solution is found.
# Telegram seemingly ignores `max_date` if `filter` (and
# nothing else) is specified, so we have to rely on doing
# a first request to offset from the ID instead.
#
# Even better, using `filter` and `from_id` seems to always
# trigger `RPC_CALL_FAIL` which is "internal issues"...
if not isinstance(filter, types.InputMessagesFilterEmpty) \
and offset_date and not search and not offset_id:
async for m in self.client.iter_messages(
self.entity, 1, offset_date=offset_date):
self.request.offset_id = m.id + 1
else:
self.request = functions.messages.GetHistoryRequest(
peer=self.entity,
limit=1,
offset_date=offset_date,
offset_id=offset_id,
min_id=0,
max_id=0,
add_offset=add_offset,
hash=0
)
if self.limit <= 0:
# No messages, but we still need to know the total message count
result = await self.client(self.request)
if isinstance(result, types.messages.MessagesNotModified):
self.total = result.count
else:
self.total = getattr(result, 'count', len(result.messages))
raise StopAsyncIteration
if self.wait_time is None:
self.wait_time = 1 if self.limit > 3000 else 0
# When going in reverse we need an offset of `-limit`, but we
# also want to respect what the user passed, so add them together.
if self.reverse:
self.request.add_offset -= _MAX_CHUNK_SIZE
self.add_offset = add_offset
self.max_id = max_id
self.min_id = min_id
self.last_id = 0 if self.reverse else float('inf')
async def _load_next_chunk(self):
self.request.limit = min(self.left, _MAX_CHUNK_SIZE)
if self.reverse and self.request.limit != _MAX_CHUNK_SIZE:
# Remember that we need -limit when going in reverse
self.request.add_offset = self.add_offset - self.request.limit
r = await self.client(self.request)
self.total = getattr(r, 'count', len(r.messages))
entities = {utils.get_peer_id(x): x
for x in itertools.chain(r.users, r.chats)}
messages = reversed(r.messages) if self.reverse else r.messages
for message in messages:
if (isinstance(message, types.MessageEmpty)
or self.from_id and message.sender_id != self.from_id):
continue
if not self._message_in_range(message):
return True
# There has been reports that on bad connections this method
# was returning duplicated IDs sometimes. Using ``last_id``
# is an attempt to avoid these duplicates, since the message
# IDs are returned in descending order (or asc if reverse).
self.last_id = message.id
message._finish_init(self.client, entities, self.entity)
self.buffer.append(message)
# Not a slice (using offset would return the same, with e.g. SearchGlobal).
if isinstance(r, types.messages.Messages):
return True
# Some channels are "buggy" and may return less messages than
# requested (apparently, the messages excluded are, for example,
# "not displayable due to local laws").
#
# This means it's not safe to rely on `len(r.messages) < req.limit` as
# the stop condition. Unfortunately more requests must be made.
#
# However we can still check if the highest ID is equal to or lower
# than the limit, in which case there won't be any more messages
# because the lowest message ID is 1.
#
# We also assume the API will always return, at least, one message if
# there is more to fetch.
if not r.messages or (not self.reverse and r.messages[0].id <= self.request.limit):
return True
# Get the last message that's not empty (in some rare cases
# it can happen that the last message is :tl:`MessageEmpty`)
if self.buffer:
self._update_offset(self.buffer[-1], r)
else:
# There are some cases where all the messages we get start
# being empty. This can happen on migrated mega-groups if
# the history was cleared, and we're using search. Telegram
# acts incredibly weird sometimes. Messages are returned but
# only "empty", not their contents. If this is the case we
# should just give up since there won't be any new Message.
return True
def _message_in_range(self, message):
"""
Determine whether the given message is in the range or
it should be ignored (and avoid loading more chunks).
"""
# No entity means message IDs between chats may vary
if self.entity:
if self.reverse:
if message.id <= self.last_id or message.id >= self.max_id:
return False
else:
if message.id >= self.last_id or message.id <= self.min_id:
return False
return True
def _update_offset(self, last_message, response):
"""
After making the request, update its offset with the last message.
"""
self.request.offset_id = last_message.id
if self.reverse:
# We want to skip the one we already have
self.request.offset_id += 1
if isinstance(self.request, functions.messages.SearchRequest):
# Unlike getHistory and searchGlobal that use *offset* date,
# this is *max* date. This means that doing a search in reverse
# will break it. Since it's not really needed once we're going
# (only for the first request), it's safe to just clear it off.
self.request.max_date = None
else:
# getHistory, searchGlobal and getReplies call it offset_date
self.request.offset_date = last_message.date
if isinstance(self.request, functions.messages.SearchGlobalRequest):
if last_message.input_chat:
self.request.offset_peer = last_message.input_chat
else:
self.request.offset_peer = types.InputPeerEmpty()
self.request.offset_rate = getattr(response, 'next_rate', 0)
|
class _MessagesIter(RequestIter):
'''
Common factor for all requests that need to iterate over messages.
'''
async def _init(
self, entity, offset_id, min_id, max_id,
from_user, offset_date, add_offset, filter, search, reply_to,
scheduled
):
pass
async def _load_next_chunk(self):
pass
def _message_in_range(self, message):
'''
Determine whether the given message is in the range or
it should be ignored (and avoid loading more chunks).
'''
pass
def _update_offset(self, last_message, response):
'''
After making the request, update its offset with the last message.
'''
pass
| 5 | 3 | 65 | 6 | 42 | 17 | 12 | 0.42 | 1 | 5 | 1 | 0 | 4 | 9 | 4 | 33 | 266 | 28 | 168 | 25 | 159 | 71 | 101 | 21 | 96 | 29 | 5 | 3 | 48 |
146,783 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/messages.py
|
telethon.client.messages._IDsIter
|
class _IDsIter(RequestIter):
async def _init(self, entity, ids):
self.total = len(ids)
self._ids = list(reversed(ids)) if self.reverse else ids
self._offset = 0
self._entity = (await self.client.get_input_entity(entity)) if entity else None
self._ty = helpers._entity_type(self._entity) if self._entity else None
# 30s flood wait every 300 messages (3 requests of 100 each, 30 of 10, etc.)
if self.wait_time is None:
self.wait_time = 10 if self.limit > 300 else 0
async def _load_next_chunk(self):
ids = self._ids[self._offset:self._offset + _MAX_CHUNK_SIZE]
if not ids:
raise StopAsyncIteration
self._offset += _MAX_CHUNK_SIZE
from_id = None # By default, no need to validate from_id
if self._ty == helpers._EntityType.CHANNEL:
try:
r = await self.client(
functions.channels.GetMessagesRequest(self._entity, ids))
except errors.MessageIdsEmptyError:
# All IDs were invalid, use a dummy result
r = types.messages.MessagesNotModified(len(ids))
else:
r = await self.client(functions.messages.GetMessagesRequest(ids))
if self._entity:
from_id = await self.client._get_peer(self._entity)
if isinstance(r, types.messages.MessagesNotModified):
self.buffer.extend(None for _ in ids)
return
entities = {utils.get_peer_id(x): x
for x in itertools.chain(r.users, r.chats)}
# Telegram seems to return the messages in the order in which
# we asked them for, so we don't need to check it ourselves,
# unless some messages were invalid in which case Telegram
# may decide to not send them at all.
#
# The passed message IDs may not belong to the desired entity
# since the user can enter arbitrary numbers which can belong to
# arbitrary chats. Validate these unless ``from_id is None``.
for message in r.messages:
if isinstance(message, types.MessageEmpty) or (
from_id and message.peer_id != from_id):
self.buffer.append(None)
else:
message._finish_init(self.client, entities, self._entity)
self.buffer.append(message)
|
class _IDsIter(RequestIter):
async def _init(self, entity, ids):
pass
async def _load_next_chunk(self):
pass
| 3 | 0 | 26 | 3 | 18 | 6 | 7 | 0.3 | 1 | 4 | 1 | 0 | 2 | 6 | 2 | 31 | 54 | 7 | 37 | 15 | 34 | 11 | 32 | 14 | 29 | 8 | 5 | 2 | 14 |
146,784 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/messageparse.py
|
telethon.client.messageparse.MessageParseMethods
|
class MessageParseMethods:
# region Public properties
@property
def parse_mode(self: 'TelegramClient'):
"""
This property is the default parse mode used when sending messages.
Defaults to `telethon.extensions.markdown`. It will always
be either `None` or an object with ``parse`` and ``unparse``
methods.
When setting a different value it should be one of:
* Object with ``parse`` and ``unparse`` methods.
* A ``callable`` to act as the parse method.
* A `str` indicating the ``parse_mode``. For Markdown ``'md'``
or ``'markdown'`` may be used. For HTML, ``'htm'`` or ``'html'``
may be used.
The ``parse`` method should be a function accepting a single
parameter, the text to parse, and returning a tuple consisting
of ``(parsed message str, [MessageEntity instances])``.
The ``unparse`` method should be the inverse of ``parse`` such
that ``assert text == unparse(*parse(text))``.
See :tl:`MessageEntity` for allowed message entities.
Example
.. code-block:: python
# Disabling default formatting
client.parse_mode = None
# Enabling HTML as the default format
client.parse_mode = 'html'
"""
return self._parse_mode
@parse_mode.setter
def parse_mode(self: 'TelegramClient', mode: str):
self._parse_mode = utils.sanitize_parse_mode(mode)
# endregion
# region Private methods
async def _replace_with_mention(self: 'TelegramClient', entities, i, user):
"""
Helper method to replace ``entities[i]`` to mention ``user``,
or do nothing if it can't be found.
"""
try:
entities[i] = types.InputMessageEntityMentionName(
entities[i].offset, entities[i].length,
await self.get_input_entity(user)
)
return True
except (ValueError, TypeError):
return False
async def _parse_message_text(self: 'TelegramClient', message, parse_mode):
"""
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
"""
if parse_mode == ():
parse_mode = self._parse_mode
else:
parse_mode = utils.sanitize_parse_mode(parse_mode)
if not parse_mode:
return message, []
original_message = message
message, msg_entities = parse_mode.parse(message)
if original_message and not message and not msg_entities:
raise ValueError("Failed to parse message")
for i in reversed(range(len(msg_entities))):
e = msg_entities[i]
if not e.length:
# 0-length MessageEntity is no longer valid #3884.
# Because the user can provide their own parser (with reasonable 0-length
# entities), strip them here rather than fixing the built-in parsers.
del msg_entities[i]
elif isinstance(e, types.MessageEntityTextUrl):
m = re.match(r'^@|\+|tg://user\?id=(\d+)', e.url)
if m:
user = int(m.group(1)) if m.group(1) else e.url
is_mention = await self._replace_with_mention(msg_entities, i, user)
if not is_mention:
del msg_entities[i]
elif isinstance(e, (types.MessageEntityMentionName,
types.InputMessageEntityMentionName)):
is_mention = await self._replace_with_mention(msg_entities, i, e.user_id)
if not is_mention:
del msg_entities[i]
return message, msg_entities
def _get_response_message(self: 'TelegramClient', request, result, input_chat):
"""
Extracts the response message known a request and Update result.
The request may also be the ID of the message to match.
If ``request is None`` this method returns ``{id: message}``.
If ``request.random_id`` is a list, this method returns a list too.
"""
if isinstance(result, types.UpdateShort):
updates = [result.update]
entities = {}
elif isinstance(result, (types.Updates, types.UpdatesCombined)):
updates = result.updates
entities = {utils.get_peer_id(x): x
for x in
itertools.chain(result.users, result.chats)}
else:
return None
random_to_id = {}
id_to_message = {}
for update in updates:
if isinstance(update, types.UpdateMessageID):
random_to_id[update.random_id] = update.id
elif isinstance(update, (
types.UpdateNewChannelMessage, types.UpdateNewMessage)):
update.message._finish_init(self, entities, input_chat)
# Pinning a message with `updatePinnedMessage` seems to
# always produce a service message we can't map so return
# it directly. The same happens for kicking users.
#
# It could also be a list (e.g. when sending albums).
#
# TODO this method is getting messier and messier as time goes on
if hasattr(request, 'random_id') or utils.is_list_like(request):
id_to_message[update.message.id] = update.message
else:
return update.message
elif (isinstance(update, types.UpdateEditMessage)
and helpers._entity_type(request.peer) != helpers._EntityType.CHANNEL):
update.message._finish_init(self, entities, input_chat)
# Live locations use `sendMedia` but Telegram responds with
# `updateEditMessage`, which means we won't have `id` field.
if hasattr(request, 'random_id'):
id_to_message[update.message.id] = update.message
elif request.id == update.message.id:
return update.message
elif (isinstance(update, types.UpdateEditChannelMessage)
and utils.get_peer_id(request.peer) ==
utils.get_peer_id(update.message.peer_id)):
if request.id == update.message.id:
update.message._finish_init(self, entities, input_chat)
return update.message
elif isinstance(update, types.UpdateNewScheduledMessage):
update.message._finish_init(self, entities, input_chat)
# Scheduled IDs may collide with normal IDs. However, for a
# single request there *shouldn't* be a mix between "some
# scheduled and some not".
id_to_message[update.message.id] = update.message
elif isinstance(update, types.UpdateMessagePoll):
if request.media.poll.id == update.poll_id:
m = types.Message(
id=request.id,
peer_id=utils.get_peer(request.peer),
media=types.MessageMediaPoll(
poll=update.poll,
results=update.results
)
)
m._finish_init(self, entities, input_chat)
return m
if request is None:
return id_to_message
random_id = request if isinstance(request, (int, list)) else getattr(request, 'random_id', None)
if random_id is None:
# Can happen when pinning a message does not actually produce a service message.
self._log[__name__].warning(
'No random_id in %s to map to, returning None message for %s', request, result)
return None
if not utils.is_list_like(random_id):
msg = id_to_message.get(random_to_id.get(random_id))
if not msg:
self._log[__name__].warning(
'Request %s had missing message mapping %s', request, result)
return msg
try:
return [id_to_message[random_to_id[rnd]] for rnd in random_id]
except KeyError:
# Sometimes forwards fail (`MESSAGE_ID_INVALID` if a message gets
# deleted or `WORKER_BUSY_TOO_LONG_RETRY` if there are issues at
# Telegram), in which case we get some "missing" message mappings.
# Log them with the hope that we can better work around them.
#
# This also happens when trying to forward messages that can't
# be forwarded because they don't exist (0, service, deleted)
# among others which could be (like deleted or existing).
self._log[__name__].warning(
'Request %s had missing message mappings %s', request, result)
return [
id_to_message.get(random_to_id[rnd])
if rnd in random_to_id
else None
for rnd in random_id
]
|
class MessageParseMethods:
@property
def parse_mode(self: 'TelegramClient'):
'''
This property is the default parse mode used when sending messages.
Defaults to `telethon.extensions.markdown`. It will always
be either `None` or an object with ``parse`` and ``unparse``
methods.
When setting a different value it should be one of:
* Object with ``parse`` and ``unparse`` methods.
* A ``callable`` to act as the parse method.
* A `str` indicating the ``parse_mode``. For Markdown ``'md'``
or ``'markdown'`` may be used. For HTML, ``'htm'`` or ``'html'``
may be used.
The ``parse`` method should be a function accepting a single
parameter, the text to parse, and returning a tuple consisting
of ``(parsed message str, [MessageEntity instances])``.
The ``unparse`` method should be the inverse of ``parse`` such
that ``assert text == unparse(*parse(text))``.
See :tl:`MessageEntity` for allowed message entities.
Example
.. code-block:: python
# Disabling default formatting
client.parse_mode = None
# Enabling HTML as the default format
client.parse_mode = 'html'
'''
pass
@parse_mode.setter
def parse_mode(self: 'TelegramClient'):
pass
async def _replace_with_mention(self: 'TelegramClient', entities, i, user):
'''
Helper method to replace ``entities[i]`` to mention ``user``,
or do nothing if it can't be found.
'''
pass
async def _parse_message_text(self: 'TelegramClient', message, parse_mode):
'''
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
'''
pass
def _get_response_message(self: 'TelegramClient', request, result, input_chat):
'''
Extracts the response message known a request and Update result.
The request may also be the ID of the message to match.
If ``request is None`` this method returns ``{id: message}``.
If ``request.random_id`` is a list, this method returns a list too.
'''
pass
| 8 | 4 | 41 | 6 | 23 | 12 | 8 | 0.54 | 0 | 10 | 1 | 0 | 5 | 1 | 5 | 5 | 220 | 37 | 119 | 24 | 111 | 64 | 80 | 22 | 74 | 22 | 0 | 4 | 38 |
146,785 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/downloads.py
|
telethon.client.downloads._GenericDownloadIter
|
class _GenericDownloadIter(_DirectDownloadIter):
async def _load_next_chunk(self):
# 1. Fetch enough for one chunk
data = b''
# 1.1. ``bad`` is how much into the data we have we need to offset
bad = self.request.offset % self.request.limit
before = self.request.offset
# 1.2. We have to fetch from a valid offset, so remove that bad part
self.request.offset -= bad
done = False
while not done and len(data) - bad < self._chunk_size:
cur = await self._request()
self.request.offset += self.request.limit
data += cur
done = len(cur) < self.request.limit
# 1.3 Restore our last desired offset
self.request.offset = before
# 2. Fill the buffer with the data we have
# 2.1. Slicing `bytes` is expensive, yield `memoryview` instead
mem = memoryview(data)
# 2.2. The current chunk starts at ``bad`` offset into the data,
# and each new chunk is ``stride`` bytes apart of the other
for i in range(bad, len(data), self._stride):
self.buffer.append(mem[i:i + self._chunk_size])
# 2.3. We will yield this offset, so move to the next one
self.request.offset += self._stride
# 2.4. If we are in the last chunk, we will return the last partial data
if done:
self.left = len(self.buffer)
await self.close()
return
# 2.5. If we are not done, we can't return incomplete chunks.
if len(self.buffer[-1]) != self._chunk_size:
self._last_part = self.buffer.pop().tobytes()
# 3. Be careful with the offsets. Re-fetching a bit of data
# is fine, since it greatly simplifies things.
# TODO Try to not re-fetch data
self.request.offset -= self._stride
|
class _GenericDownloadIter(_DirectDownloadIter):
async def _load_next_chunk(self):
pass
| 2 | 0 | 48 | 11 | 23 | 14 | 5 | 0.58 | 1 | 2 | 0 | 0 | 1 | 2 | 1 | 36 | 49 | 11 | 24 | 11 | 22 | 14 | 24 | 11 | 22 | 5 | 6 | 1 | 5 |
146,786 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/downloads.py
|
telethon.client.downloads._DirectDownloadIter
|
class _DirectDownloadIter(RequestIter):
async def _init(
self, file, dc_id, offset, stride, chunk_size, request_size, file_size, msg_data, cdn_redirect=None):
self.request = functions.upload.GetFileRequest(
file, offset=offset, limit=request_size)
self._client = self.client
self._cdn_redirect = cdn_redirect
if cdn_redirect is not None:
self.request = functions.upload.GetCdnFileRequest(cdn_redirect.file_token, offset=offset, limit=request_size)
self._client = await self.client._get_cdn_client(cdn_redirect)
self.total = file_size
self._stride = stride
self._chunk_size = chunk_size
self._last_part = None
self._msg_data = msg_data
self._timed_out = False
self._exported = dc_id and self._client.session.dc_id != dc_id
if not self._exported:
# The used sender will also change if ``FileMigrateError`` occurs
self._sender = self.client._sender
else:
try:
self._sender = await self.client._borrow_exported_sender(dc_id)
except errors.DcIdInvalidError:
# Can't export a sender for the ID we are currently in
config = await self.client(functions.help.GetConfigRequest())
for option in config.dc_options:
if option.ip_address == self.client.session.server_address:
self.client.session.set_dc(
option.id, option.ip_address, option.port)
self.client.session.save()
break
# TODO Figure out why the session may have the wrong DC ID
self._sender = self.client._sender
self._exported = False
async def _load_next_chunk(self):
cur = await self._request()
self.buffer.append(cur)
if len(cur) < self.request.limit:
self.left = len(self.buffer)
await self.close()
else:
self.request.offset += self._stride
async def _request(self):
try:
result = await self._client._call(self._sender, self.request)
self._timed_out = False
if isinstance(result, types.upload.FileCdnRedirect):
if self.client._mb_entity_cache.self_bot:
raise ValueError('FileCdnRedirect but the GetCdnFileRequest API access for bot users is restricted. Try to change api_id to avoid FileCdnRedirect')
raise _CdnRedirect(result)
if isinstance(result, types.upload.CdnFileReuploadNeeded):
await self.client._call(self.client._sender, functions.upload.ReuploadCdnFileRequest(file_token=self._cdn_redirect.file_token, request_token=result.request_token))
result = await self._client._call(self._sender, self.request)
return result.bytes
else:
return result.bytes
except errors.TimedOutError as e:
if self._timed_out:
self.client._log[__name__].warning('Got two timeouts in a row while downloading file')
raise
self._timed_out = True
self.client._log[__name__].info('Got timeout while downloading file, retrying once')
await asyncio.sleep(TIMED_OUT_SLEEP)
return await self._request()
except errors.FileMigrateError as e:
self.client._log[__name__].info('File lives in another DC')
self._sender = await self.client._borrow_exported_sender(e.new_dc)
self._exported = True
return await self._request()
except (errors.FilerefUpgradeNeededError, errors.FileReferenceExpiredError) as e:
# Only implemented for documents which are the ones that may take that long to download
if not self._msg_data \
or not isinstance(self.request.location, types.InputDocumentFileLocation) \
or self.request.location.thumb_size != '':
raise
self.client._log[__name__].info('File ref expired during download; refetching message')
chat, msg_id = self._msg_data
msg = await self.client.get_messages(chat, ids=msg_id)
if not isinstance(msg.media, types.MessageMediaDocument):
raise
document = msg.media.document
# Message media may have been edited for something else
if document.id != self.request.location.id:
raise
self.request.location.file_reference = document.file_reference
return await self._request()
async def close(self):
if not self._sender:
return
try:
if self._exported:
await self.client._return_exported_sender(self._sender)
elif self._sender != self.client._sender:
await self._sender.disconnect()
finally:
self._sender = None
async def __aenter__(self):
return self
async def __aexit__(self, *args):
await self.close()
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit
|
class _DirectDownloadIter(RequestIter):
async def _init(
self, file, dc_id, offset, stride, chunk_size, request_size, file_size, msg_data, cdn_redirect=None):
pass
async def _load_next_chunk(self):
pass
async def _request(self):
pass
async def close(self):
pass
async def __aenter__(self):
pass
async def __aexit__(self, *args):
pass
| 7 | 0 | 19 | 2 | 16 | 1 | 4 | 0.05 | 1 | 2 | 1 | 1 | 6 | 12 | 6 | 35 | 122 | 19 | 98 | 30 | 90 | 5 | 88 | 28 | 81 | 11 | 5 | 4 | 25 |
146,787 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/downloads.py
|
telethon.client.downloads._CdnRedirect
|
class _CdnRedirect(Exception):
def __init__(self, cdn_redirect=None):
self.cdn_redirect = cdn_redirect
|
class _CdnRedirect(Exception):
def __init__(self, cdn_redirect=None):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 11 | 3 | 0 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 3 | 0 | 1 |
146,788 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/downloads.py
|
telethon.client.downloads.DownloadMethods
|
class DownloadMethods:
# region Public methods
async def download_profile_photo(
self: 'TelegramClient',
entity: 'hints.EntityLike',
file: 'hints.FileLike' = None,
*,
download_big: bool = True) -> typing.Optional[str]:
"""
Downloads the profile photo from the given user, chat or channel.
Arguments
entity (`entity`):
From who the photo will be downloaded.
.. note::
This method expects the full entity (which has the data
to download the photo), not an input variant.
It's possible that sometimes you can't fetch the entity
from its input (since you can get errors like
``ChannelPrivateError``) but you already have it through
another call, like getting a forwarded message from it.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If file is the type `bytes`, it will be downloaded in-memory
and returned as a bytestring (i.e. ``file=bytes``, without
parentheses or quotes).
download_big (`bool`, optional):
Whether to use the big version of the available photos.
Returns
`None` if no photo was provided, or if it was Empty. On success
the file path is returned since it may differ from the one given.
Example
.. code-block:: python
# Download your own profile photo
path = await client.download_profile_photo('me')
print(path)
"""
# hex(crc32(x.encode('ascii'))) for x in
# ('User', 'Chat', 'UserFull', 'ChatFull')
ENTITIES = (0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697)
# ('InputPeer', 'InputUser', 'InputChannel')
INPUTS = (0xc91c90b6, 0xe669bf46, 0x40f202fd)
if not isinstance(entity, TLObject) or entity.SUBCLASS_OF_ID in INPUTS:
entity = await self.get_entity(entity)
thumb = -1 if download_big else 0
possible_names = []
if entity.SUBCLASS_OF_ID not in ENTITIES:
photo = entity
else:
if not hasattr(entity, 'photo'):
# Special case: may be a ChatFull with photo:Photo
# This is different from a normal UserProfilePhoto and Chat
if not hasattr(entity, 'chat_photo'):
return None
return await self._download_photo(
entity.chat_photo, file, date=None,
thumb=thumb, progress_callback=None
)
for attr in ('username', 'first_name', 'title'):
possible_names.append(getattr(entity, attr, None))
photo = entity.photo
if isinstance(photo, (types.UserProfilePhoto, types.ChatPhoto)):
dc_id = photo.dc_id
loc = types.InputPeerPhotoFileLocation(
# min users can be used to download profile photos
# self.get_input_entity would otherwise not accept those
peer=utils.get_input_peer(entity, check_hash=False),
photo_id=photo.photo_id,
big=download_big
)
else:
# It doesn't make any sense to check if `photo` can be used
# as input location, because then this method would be able
# to "download the profile photo of a message", i.e. its
# media which should be done with `download_media` instead.
return None
file = self._get_proper_filename(
file, 'profile_photo', '.jpg',
possible_names=possible_names
)
try:
result = await self.download_file(loc, file, dc_id=dc_id)
return result if file is bytes else file
except errors.LocationInvalidError:
# See issue #500, Android app fails as of v4.6.0 (1155).
# The fix seems to be using the full channel chat photo.
ie = await self.get_input_entity(entity)
ty = helpers._entity_type(ie)
if ty == helpers._EntityType.CHANNEL:
full = await self(functions.channels.GetFullChannelRequest(ie))
return await self._download_photo(
full.full_chat.chat_photo, file,
date=None, progress_callback=None,
thumb=thumb
)
else:
# Until there's a report for chats, no need to.
return None
async def download_media(
self: 'TelegramClient',
message: 'hints.MessageLike',
file: 'hints.FileLike' = None,
*,
thumb: 'typing.Union[int, types.TypePhotoSize]' = None,
progress_callback: 'hints.ProgressCallback' = None) -> typing.Optional[typing.Union[str, bytes]]:
"""
Downloads the given media from a message object.
Note that if the download is too slow, you should consider installing
``cryptg`` (through ``pip install cryptg``) so that decrypting the
received data is done in C instead of Python (much faster).
See also `Message.download_media() <telethon.tl.custom.message.Message.download_media>`.
Arguments
message (`Message <telethon.tl.custom.message.Message>` | :tl:`Media`):
The media or message containing the media that will be downloaded.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If file is the type `bytes`, it will be downloaded in-memory
and returned as a bytestring (i.e. ``file=bytes``, without
parentheses or quotes).
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(received bytes, total)``.
thumb (`int` | :tl:`PhotoSize`, optional):
Which thumbnail size from the document or photo to download,
instead of downloading the document or photo itself.
If it's specified but the file does not have a thumbnail,
this method will return `None`.
The parameter should be an integer index between ``0`` and
``len(sizes)``. ``0`` will download the smallest thumbnail,
and ``len(sizes) - 1`` will download the largest thumbnail.
You can also use negative indices, which work the same as
they do in Python's `list`.
You can also pass the :tl:`PhotoSize` instance to use.
Alternatively, the thumb size type `str` may be used.
In short, use ``thumb=0`` if you want the smallest thumbnail
and ``thumb=-1`` if you want the largest thumbnail.
.. note::
The largest thumbnail may be a video instead of a photo,
as they are available since layer 116 and are bigger than
any of the photos.
Returns
`None` if no media was provided, or if it was Empty. On success
the file path is returned since it may differ from the one given.
Example
.. code-block:: python
path = await client.download_media(message)
await client.download_media(message, filename)
# or
path = await message.download_media()
await message.download_media(filename)
# Downloading to memory
blob = await client.download_media(message, bytes)
# Printing download progress
def callback(current, total):
print('Downloaded', current, 'out of', total,
'bytes: {:.2%}'.format(current / total))
await client.download_media(message, progress_callback=callback)
"""
# Downloading large documents may be slow enough to require a new file reference
# to be obtained mid-download. Store (input chat, message id) so that the message
# can be re-fetched.
msg_data = None
# TODO This won't work for messageService
if isinstance(message, types.Message):
date = message.date
media = message.media
msg_data = (message.input_chat, message.id) if message.input_chat else None
else:
date = datetime.datetime.now()
media = message
if isinstance(media, str):
media = utils.resolve_bot_file_id(media)
if isinstance(media, types.MessageService):
if isinstance(message.action,
types.MessageActionChatEditPhoto):
media = media.photo
if isinstance(media, types.MessageMediaWebPage):
if isinstance(media.webpage, types.WebPage):
media = media.webpage.document or media.webpage.photo
if isinstance(media, (types.MessageMediaPhoto, types.Photo)):
return await self._download_photo(
media, file, date, thumb, progress_callback
)
elif isinstance(media, (types.MessageMediaDocument, types.Document)):
return await self._download_document(
media, file, date, thumb, progress_callback, msg_data
)
elif isinstance(media, types.MessageMediaContact) and thumb is None:
return self._download_contact(
media, file
)
elif isinstance(media, (types.WebDocument, types.WebDocumentNoProxy)) and thumb is None:
return await self._download_web_document(
media, file, progress_callback
)
async def download_file(
self: 'TelegramClient',
input_location: 'hints.FileLike',
file: 'hints.OutFileLike' = None,
*,
part_size_kb: float = None,
file_size: int = None,
progress_callback: 'hints.ProgressCallback' = None,
dc_id: int = None,
key: bytes = None,
iv: bytes = None) -> typing.Optional[bytes]:
"""
Low-level method to download files from their input location.
.. note::
Generally, you should instead use `download_media`.
This method is intended to be a bit more low-level.
Arguments
input_location (:tl:`InputFileLocation`):
The file location from which the file will be downloaded.
See `telethon.utils.get_input_location` source for a complete
list of supported types.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If the file path is `None` or `bytes`, then the result
will be saved in memory and returned as `bytes`.
part_size_kb (`int`, optional):
Chunk size when downloading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The file size that is about to be downloaded, if known.
Only used if ``progress_callback`` is specified.
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(downloaded bytes, total)``. Note that the
``total`` is the provided ``file_size``.
dc_id (`int`, optional):
The data center the library should connect to in order
to download the file. You shouldn't worry about this.
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
Example
.. code-block:: python
# Download a file and print its header
data = await client.download_file(input_file, bytes)
print(data[:16])
"""
return await self._download_file(
input_location,
file,
part_size_kb=part_size_kb,
file_size=file_size,
progress_callback=progress_callback,
dc_id=dc_id,
key=key,
iv=iv,
)
async def _download_file(
self: 'TelegramClient',
input_location: 'hints.FileLike',
file: 'hints.OutFileLike' = None,
*,
part_size_kb: float = None,
file_size: int = None,
progress_callback: 'hints.ProgressCallback' = None,
dc_id: int = None,
key: bytes = None,
iv: bytes = None,
msg_data: tuple = None,
cdn_redirect: types.upload.FileCdnRedirect = None
) -> typing.Optional[bytes]:
if not part_size_kb:
if not file_size:
part_size_kb = 64 # Reasonable default
else:
part_size_kb = utils.get_appropriated_part_size(file_size)
part_size = int(part_size_kb * 1024)
if part_size % MIN_CHUNK_SIZE != 0:
raise ValueError(
'The part size must be evenly divisible by 4096.')
if isinstance(file, pathlib.Path):
file = str(file.absolute())
in_memory = file is None or file is bytes
if in_memory:
f = io.BytesIO()
elif isinstance(file, str):
# Ensure that we'll be able to download the media
helpers.ensure_parent_dir_exists(file)
f = open(file, 'wb')
else:
f = file
try:
async for chunk in self._iter_download(
input_location, request_size=part_size, dc_id=dc_id, msg_data=msg_data, cdn_redirect=cdn_redirect):
if iv and key:
chunk = AES.decrypt_ige(chunk, key, iv)
r = f.write(chunk)
if inspect.isawaitable(r):
await r
if progress_callback:
r = progress_callback(f.tell(), file_size)
if inspect.isawaitable(r):
await r
# Not all IO objects have flush (see #1227)
if callable(getattr(f, 'flush', None)):
f.flush()
if in_memory:
return f.getvalue()
except _CdnRedirect as e:
self._log[__name__].info('FileCdnRedirect to CDN data center %s', e.cdn_redirect.dc_id)
return await self._download_file(
input_location=input_location,
file=file,
part_size_kb=part_size_kb,
file_size=file_size,
progress_callback=progress_callback,
dc_id=e.cdn_redirect.dc_id,
key=e.cdn_redirect.encryption_key,
iv=e.cdn_redirect.encryption_iv,
msg_data=msg_data,
cdn_redirect=e.cdn_redirect
)
finally:
if isinstance(file, str) or in_memory:
f.close()
def iter_download(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
offset: int = 0,
stride: int = None,
limit: int = None,
chunk_size: int = None,
request_size: int = MAX_CHUNK_SIZE,
file_size: int = None,
dc_id: int = None
):
"""
Iterates over a file download, yielding chunks of the file.
This method can be used to stream files in a more convenient
way, since it offers more control (pausing, resuming, etc.)
.. note::
Using a value for `offset` or `stride` which is not a multiple
of the minimum allowed `request_size`, or if `chunk_size` is
different from `request_size`, the library will need to do a
bit more work to fetch the data in the way you intend it to.
You normally shouldn't worry about this.
Arguments
file (`hints.FileLike`):
The file of which contents you want to iterate over.
offset (`int`, optional):
The offset in bytes into the file from where the
download should start. For example, if a file is
1024KB long and you just want the last 512KB, you
would use ``offset=512 * 1024``.
stride (`int`, optional):
The stride of each chunk (how much the offset should
advance between reading each chunk). This parameter
should only be used for more advanced use cases.
It must be bigger than or equal to the `chunk_size`.
limit (`int`, optional):
The limit for how many *chunks* will be yielded at most.
chunk_size (`int`, optional):
The maximum size of the chunks that will be yielded.
Note that the last chunk may be less than this value.
By default, it equals to `request_size`.
request_size (`int`, optional):
How many bytes will be requested to Telegram when more
data is required. By default, as many bytes as possible
are requested. If you would like to request data in
smaller sizes, adjust this parameter.
Note that values outside the valid range will be clamped,
and the final value will also be a multiple of the minimum
allowed size.
file_size (`int`, optional):
If the file size is known beforehand, you should set
this parameter to said value. Depending on the type of
the input file passed, this may be set automatically.
dc_id (`int`, optional):
The data center the library should connect to in order
to download the file. You shouldn't worry about this.
Yields
`bytes` objects representing the chunks of the file if the
right conditions are met, or `memoryview` objects instead.
Example
.. code-block:: python
# Streaming `media` to an output file
# After the iteration ends, the sender is cleaned up
with open('photo.jpg', 'wb') as fd:
async for chunk in client.iter_download(media):
fd.write(chunk)
# Fetching only the header of a file (32 bytes)
# You should manually close the iterator in this case.
#
# "stream" is a common name for asynchronous generators,
# and iter_download will yield `bytes` (chunks of the file).
stream = client.iter_download(media, request_size=32)
header = await stream.__anext__() # "manual" version of `async for`
await stream.close()
assert len(header) == 32
"""
return self._iter_download(
file,
offset=offset,
stride=stride,
limit=limit,
chunk_size=chunk_size,
request_size=request_size,
file_size=file_size,
dc_id=dc_id,
)
def _iter_download(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
offset: int = 0,
stride: int = None,
limit: int = None,
chunk_size: int = None,
request_size: int = MAX_CHUNK_SIZE,
file_size: int = None,
dc_id: int = None,
msg_data: tuple = None,
cdn_redirect: types.upload.FileCdnRedirect = None
):
info = utils._get_file_info(file)
if info.dc_id is not None:
dc_id = info.dc_id
if file_size is None:
file_size = info.size
file = info.location
if chunk_size is None:
chunk_size = request_size
if limit is None and file_size is not None:
limit = (file_size + chunk_size - 1) // chunk_size
if stride is None:
stride = chunk_size
elif stride < chunk_size:
raise ValueError('stride must be >= chunk_size')
request_size -= request_size % MIN_CHUNK_SIZE
if request_size < MIN_CHUNK_SIZE:
request_size = MIN_CHUNK_SIZE
elif request_size > MAX_CHUNK_SIZE:
request_size = MAX_CHUNK_SIZE
if chunk_size == request_size \
and offset % MIN_CHUNK_SIZE == 0 \
and stride % MIN_CHUNK_SIZE == 0 \
and (limit is None or offset % limit == 0):
cls = _DirectDownloadIter
self._log[__name__].info('Starting direct file download in chunks of '
'%d at %d, stride %d', request_size, offset, stride)
else:
cls = _GenericDownloadIter
self._log[__name__].info('Starting indirect file download in chunks of '
'%d at %d, stride %d', request_size, offset, stride)
return cls(
self,
limit,
file=file,
dc_id=dc_id,
offset=offset,
stride=stride,
chunk_size=chunk_size,
request_size=request_size,
file_size=file_size,
msg_data=msg_data,
cdn_redirect=cdn_redirect
)
# endregion
# region Private methods
@staticmethod
def _get_thumb(thumbs, thumb):
if not thumbs:
return None
# Seems Telegram has changed the order and put `PhotoStrippedSize`
# last while this is the smallest (layer 116). Ensure we have the
# sizes sorted correctly with a custom function.
def sort_thumbs(thumb):
if isinstance(thumb, types.PhotoStrippedSize):
return 1, len(thumb.bytes)
if isinstance(thumb, types.PhotoCachedSize):
return 1, len(thumb.bytes)
if isinstance(thumb, types.PhotoSize):
return 1, thumb.size
if isinstance(thumb, types.PhotoSizeProgressive):
return 1, max(thumb.sizes)
if isinstance(thumb, types.VideoSize):
return 2, thumb.size
# Empty size or invalid should go last
return 0, 0
thumbs = list(sorted(thumbs, key=sort_thumbs))
for i in reversed(range(len(thumbs))):
# :tl:`PhotoPathSize` is used for animated stickers preview, and the thumb is actually
# a SVG path of the outline. Users expect thumbnails to be JPEG files, so pretend this
# thumb size doesn't actually exist (#1655).
if isinstance(thumbs[i], types.PhotoPathSize):
thumbs.pop(i)
if thumb is None:
return thumbs[-1]
elif isinstance(thumb, int):
return thumbs[thumb]
elif isinstance(thumb, str):
return next((t for t in thumbs if t.type == thumb), None)
elif isinstance(thumb, (types.PhotoSize, types.PhotoCachedSize,
types.PhotoStrippedSize, types.VideoSize)):
return thumb
else:
return None
def _download_cached_photo_size(self: 'TelegramClient', size, file):
# No need to download anything, simply write the bytes
if isinstance(size, types.PhotoStrippedSize):
data = utils.stripped_photo_to_jpg(size.bytes)
else:
data = size.bytes
if file is bytes:
return data
elif isinstance(file, str):
helpers.ensure_parent_dir_exists(file)
f = open(file, 'wb')
else:
f = file
try:
f.write(data)
finally:
if isinstance(file, str):
f.close()
return file
async def _download_photo(self: 'TelegramClient', photo, file, date, thumb, progress_callback):
"""Specialized version of .download_media() for photos"""
# Determine the photo and its largest size
if isinstance(photo, types.MessageMediaPhoto):
photo = photo.photo
if not isinstance(photo, types.Photo):
return
# Include video sizes here (but they may be None so provide an empty list)
size = self._get_thumb(photo.sizes + (photo.video_sizes or []), thumb)
if not size or isinstance(size, types.PhotoSizeEmpty):
return
if isinstance(size, types.VideoSize):
file = self._get_proper_filename(file, 'video', '.mp4', date=date)
else:
file = self._get_proper_filename(file, 'photo', '.jpg', date=date)
if isinstance(size, (types.PhotoCachedSize, types.PhotoStrippedSize)):
return self._download_cached_photo_size(size, file)
if isinstance(size, types.PhotoSizeProgressive):
file_size = max(size.sizes)
else:
file_size = size.size
result = await self.download_file(
types.InputPhotoFileLocation(
id=photo.id,
access_hash=photo.access_hash,
file_reference=photo.file_reference,
thumb_size=size.type
),
file,
file_size=file_size,
progress_callback=progress_callback
)
return result if file is bytes else file
@staticmethod
def _get_kind_and_names(attributes):
"""Gets kind and possible names for :tl:`DocumentAttribute`."""
kind = 'document'
possible_names = []
for attr in attributes:
if isinstance(attr, types.DocumentAttributeFilename):
possible_names.insert(0, attr.file_name)
elif isinstance(attr, types.DocumentAttributeAudio):
kind = 'audio'
if attr.performer and attr.title:
possible_names.append('{} - {}'.format(
attr.performer, attr.title
))
elif attr.performer:
possible_names.append(attr.performer)
elif attr.title:
possible_names.append(attr.title)
elif attr.voice:
kind = 'voice'
return kind, possible_names
async def _download_document(
self, document, file, date, thumb, progress_callback, msg_data):
"""Specialized version of .download_media() for documents."""
if isinstance(document, types.MessageMediaDocument):
document = document.document
if not isinstance(document, types.Document):
return
if thumb is None:
kind, possible_names = self._get_kind_and_names(document.attributes)
file = self._get_proper_filename(
file, kind, utils.get_extension(document),
date=date, possible_names=possible_names
)
size = None
else:
file = self._get_proper_filename(file, 'photo', '.jpg', date=date)
size = self._get_thumb(document.thumbs, thumb)
if not size or isinstance(size, types.PhotoSizeEmpty):
return
if isinstance(size, (types.PhotoCachedSize, types.PhotoStrippedSize)):
return self._download_cached_photo_size(size, file)
result = await self._download_file(
types.InputDocumentFileLocation(
id=document.id,
access_hash=document.access_hash,
file_reference=document.file_reference,
thumb_size=size.type if size else ''
),
file,
file_size=size.size if size else document.size,
progress_callback=progress_callback,
msg_data=msg_data,
)
return result if file is bytes else file
@classmethod
def _download_contact(cls, mm_contact, file):
"""
Specialized version of .download_media() for contacts.
Will make use of the vCard 4.0 format.
"""
first_name = mm_contact.first_name
last_name = mm_contact.last_name
phone_number = mm_contact.phone_number
# Remove these pesky characters
first_name = first_name.replace(';', '')
last_name = (last_name or '').replace(';', '')
result = (
'BEGIN:VCARD\n'
'VERSION:4.0\n'
'N:{f};{l};;;\n'
'FN:{f} {l}\n'
'TEL;TYPE=cell;VALUE=uri:tel:+{p}\n'
'END:VCARD\n'
).format(f=first_name, l=last_name, p=phone_number).encode('utf-8')
file = cls._get_proper_filename(
file, 'contact', '.vcard',
possible_names=[first_name, phone_number, last_name]
)
if file is bytes:
return result
f = file if hasattr(file, 'write') else open(file, 'wb')
try:
f.write(result)
finally:
# Only close the stream if we opened it
if f != file:
f.close()
return file
@classmethod
async def _download_web_document(cls, web, file, progress_callback):
"""
Specialized version of .download_media() for web documents.
"""
if not aiohttp:
raise ValueError(
'Cannot download web documents without the aiohttp '
'dependency install it (pip install aiohttp)'
)
# TODO Better way to get opened handles of files and auto-close
kind, possible_names = self._get_kind_and_names(web.attributes)
file = self._get_proper_filename(
file, kind, utils.get_extension(web),
possible_names=possible_names
)
if file is bytes:
f = io.BytesIO()
elif hasattr(file, 'write'):
f = file
else:
f = open(file, 'wb')
try:
async with aiohttp.ClientSession() as session:
# TODO Use progress_callback; get content length from response
# https://github.com/telegramdesktop/tdesktop/blob/c7e773dd9aeba94e2be48c032edc9a78bb50234e/Telegram/SourceFiles/ui/images.cpp#L1318-L1319
async with session.get(web.url) as response:
while True:
chunk = await response.content.read(128 * 1024)
if not chunk:
break
f.write(chunk)
finally:
if f != file:
f.close()
return f.getvalue() if file is bytes else file
@staticmethod
def _get_proper_filename(file, kind, extension,
date=None, possible_names=None):
"""Gets a proper filename for 'file', if this is a path.
'kind' should be the kind of the output file (photo, document...)
'extension' should be the extension to be added to the file if
the filename doesn't have any yet
'date' should be when this file was originally sent, if known
'possible_names' should be an ordered list of possible names
If no modification is made to the path, any existing file
will be overwritten.
If any modification is made to the path, this method will
ensure that no existing file will be overwritten.
"""
if isinstance(file, pathlib.Path):
file = str(file.absolute())
if file is not None and not isinstance(file, str):
# Probably a stream-like object, we cannot set a filename here
return file
if file is None:
file = ''
elif os.path.isfile(file):
# Make no modifications to valid existing paths
return file
if os.path.isdir(file) or not file:
try:
name = None if possible_names is None else next(
x for x in possible_names if x
)
except StopIteration:
name = None
if not name:
if not date:
date = datetime.datetime.now()
name = '{}_{}-{:02}-{:02}_{:02}-{:02}-{:02}'.format(
kind,
date.year, date.month, date.day,
date.hour, date.minute, date.second,
)
file = os.path.join(file, name)
directory, name = os.path.split(file)
name, ext = os.path.splitext(name)
if not ext:
ext = extension
result = os.path.join(directory, name + ext)
if not os.path.isfile(result):
return result
i = 1
while True:
result = os.path.join(directory, '{} ({}){}'.format(name, i, ext))
if not os.path.isfile(result):
return result
i += 1
|
class DownloadMethods:
async def download_profile_photo(
self: 'TelegramClient',
entity: 'hints.EntityLike',
file: 'hints.FileLike' = None,
*,
download_big: bool = True) -> typing.Optional[str]:
'''
Downloads the profile photo from the given user, chat or channel.
Arguments
entity (`entity`):
From who the photo will be downloaded.
.. note::
This method expects the full entity (which has the data
to download the photo), not an input variant.
It's possible that sometimes you can't fetch the entity
from its input (since you can get errors like
``ChannelPrivateError``) but you already have it through
another call, like getting a forwarded message from it.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If file is the type `bytes`, it will be downloaded in-memory
and returned as a bytestring (i.e. ``file=bytes``, without
parentheses or quotes).
download_big (`bool`, optional):
Whether to use the big version of the available photos.
Returns
`None` if no photo was provided, or if it was Empty. On success
the file path is returned since it may differ from the one given.
Example
.. code-block:: python
# Download your own profile photo
path = await client.download_profile_photo('me')
print(path)
'''
pass
async def download_media(
self: 'TelegramClient',
message: 'hints.MessageLike',
file: 'hints.FileLike' = None,
*,
thumb: 'typing.Union[int, types.TypePhotoSize]' = None,
progress_callback: 'hints.ProgressCallback' = None) -> typing.Optional[typing.Union[str, bytes]]:
'''
Downloads the given media from a message object.
Note that if the download is too slow, you should consider installing
``cryptg`` (through ``pip install cryptg``) so that decrypting the
received data is done in C instead of Python (much faster).
See also `Message.download_media() <telethon.tl.custom.message.Message.download_media>`.
Arguments
message (`Message <telethon.tl.custom.message.Message>` | :tl:`Media`):
The media or message containing the media that will be downloaded.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If file is the type `bytes`, it will be downloaded in-memory
and returned as a bytestring (i.e. ``file=bytes``, without
parentheses or quotes).
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(received bytes, total)``.
thumb (`int` | :tl:`PhotoSize`, optional):
Which thumbnail size from the document or photo to download,
instead of downloading the document or photo itself.
If it's specified but the file does not have a thumbnail,
this method will return `None`.
The parameter should be an integer index between ``0`` and
``len(sizes)``. ``0`` will download the smallest thumbnail,
and ``len(sizes) - 1`` will download the largest thumbnail.
You can also use negative indices, which work the same as
they do in Python's `list`.
You can also pass the :tl:`PhotoSize` instance to use.
Alternatively, the thumb size type `str` may be used.
In short, use ``thumb=0`` if you want the smallest thumbnail
and ``thumb=-1`` if you want the largest thumbnail.
.. note::
The largest thumbnail may be a video instead of a photo,
as they are available since layer 116 and are bigger than
any of the photos.
Returns
`None` if no media was provided, or if it was Empty. On success
the file path is returned since it may differ from the one given.
Example
.. code-block:: python
path = await client.download_media(message)
await client.download_media(message, filename)
# or
path = await message.download_media()
await message.download_media(filename)
# Downloading to memory
blob = await client.download_media(message, bytes)
# Printing download progress
def callback(current, total):
print('Downloaded', current, 'out of', total,
'bytes: {:.2%}'.format(current / total))
await client.download_media(message, progress_callback=callback)
'''
pass
async def download_file(
self: 'TelegramClient',
input_location: 'hints.FileLike',
file: 'hints.OutFileLike' = None,
*,
part_size_kb: float = None,
file_size: int = None,
progress_callback: 'hints.ProgressCallback' = None,
dc_id: int = None,
key: bytes = None,
iv: bytes = None) -> typing.Optional[bytes]:
'''
Low-level method to download files from their input location.
.. note::
Generally, you should instead use `download_media`.
This method is intended to be a bit more low-level.
Arguments
input_location (:tl:`InputFileLocation`):
The file location from which the file will be downloaded.
See `telethon.utils.get_input_location` source for a complete
list of supported types.
file (`str` | `file`, optional):
The output file path, directory, or stream-like object.
If the path exists and is a file, it will be overwritten.
If the file path is `None` or `bytes`, then the result
will be saved in memory and returned as `bytes`.
part_size_kb (`int`, optional):
Chunk size when downloading files. The larger, the less
requests will be made (up to 512KB maximum).
file_size (`int`, optional):
The file size that is about to be downloaded, if known.
Only used if ``progress_callback`` is specified.
progress_callback (`callable`, optional):
A callback function accepting two parameters:
``(downloaded bytes, total)``. Note that the
``total`` is the provided ``file_size``.
dc_id (`int`, optional):
The data center the library should connect to in order
to download the file. You shouldn't worry about this.
key ('bytes', optional):
In case of an encrypted upload (secret chats) a key is supplied
iv ('bytes', optional):
In case of an encrypted upload (secret chats) an iv is supplied
Example
.. code-block:: python
# Download a file and print its header
data = await client.download_file(input_file, bytes)
print(data[:16])
'''
pass
async def _download_file(
self: 'TelegramClient',
input_location: 'hints.FileLike',
file: 'hints.OutFileLike' = None,
*,
part_size_kb: float = None,
file_size: int = None,
progress_callback: 'hints.ProgressCallback' = None,
dc_id: int = None,
key: bytes = None,
iv: bytes = None,
msg_data: tuple = None,
cdn_redirect: types.upload.FileCdnRedirect = None
) -> typing.Optional[bytes]:
pass
def iter_download(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
offset: int = 0,
stride: int = None,
limit: int = None,
chunk_size: int = None,
request_size: int = MAX_CHUNK_SIZE,
file_size: int = None,
dc_id: int = None
):
'''
Iterates over a file download, yielding chunks of the file.
This method can be used to stream files in a more convenient
way, since it offers more control (pausing, resuming, etc.)
.. note::
Using a value for `offset` or `stride` which is not a multiple
of the minimum allowed `request_size`, or if `chunk_size` is
different from `request_size`, the library will need to do a
bit more work to fetch the data in the way you intend it to.
You normally shouldn't worry about this.
Arguments
file (`hints.FileLike`):
The file of which contents you want to iterate over.
offset (`int`, optional):
The offset in bytes into the file from where the
download should start. For example, if a file is
1024KB long and you just want the last 512KB, you
would use ``offset=512 * 1024``.
stride (`int`, optional):
The stride of each chunk (how much the offset should
advance between reading each chunk). This parameter
should only be used for more advanced use cases.
It must be bigger than or equal to the `chunk_size`.
limit (`int`, optional):
The limit for how many *chunks* will be yielded at most.
chunk_size (`int`, optional):
The maximum size of the chunks that will be yielded.
Note that the last chunk may be less than this value.
By default, it equals to `request_size`.
request_size (`int`, optional):
How many bytes will be requested to Telegram when more
data is required. By default, as many bytes as possible
are requested. If you would like to request data in
smaller sizes, adjust this parameter.
Note that values outside the valid range will be clamped,
and the final value will also be a multiple of the minimum
allowed size.
file_size (`int`, optional):
If the file size is known beforehand, you should set
this parameter to said value. Depending on the type of
the input file passed, this may be set automatically.
dc_id (`int`, optional):
The data center the library should connect to in order
to download the file. You shouldn't worry about this.
Yields
`bytes` objects representing the chunks of the file if the
right conditions are met, or `memoryview` objects instead.
Example
.. code-block:: python
# Streaming `media` to an output file
# After the iteration ends, the sender is cleaned up
with open('photo.jpg', 'wb') as fd:
async for chunk in client.iter_download(media):
fd.write(chunk)
# Fetching only the header of a file (32 bytes)
# You should manually close the iterator in this case.
#
# "stream" is a common name for asynchronous generators,
# and iter_download will yield `bytes` (chunks of the file).
stream = client.iter_download(media, request_size=32)
header = await stream.__anext__() # "manual" version of `async for`
await stream.close()
assert len(header) == 32
'''
pass
def _iter_download(
self: 'TelegramClient',
file: 'hints.FileLike',
*,
offset: int = 0,
stride: int = None,
limit: int = None,
chunk_size: int = None,
request_size: int = MAX_CHUNK_SIZE,
file_size: int = None,
dc_id: int = None,
msg_data: tuple = None,
cdn_redirect: types.upload.FileCdnRedirect = None
):
pass
@staticmethod
def _get_thumb(thumbs, thumb):
pass
def sort_thumbs(thumb):
pass
def _download_cached_photo_size(self: 'TelegramClient', size, file):
pass
async def _download_photo(self: 'TelegramClient', photo, file, date, thumb, progress_callback):
'''Specialized version of .download_media() for photos'''
pass
@staticmethod
def _get_kind_and_names(attributes):
'''Gets kind and possible names for :tl:`DocumentAttribute`.'''
pass
async def _download_document(
self, document, file, date, thumb, progress_callback, msg_data):
'''Specialized version of .download_media() for documents.'''
pass
@classmethod
def _download_contact(cls, mm_contact, file):
'''
Specialized version of .download_media() for contacts.
Will make use of the vCard 4.0 format.
'''
pass
@classmethod
async def _download_web_document(cls, web, file, progress_callback):
'''
Specialized version of .download_media() for web documents.
'''
pass
@staticmethod
def _get_proper_filename(file, kind, extension,
date=None, possible_names=None):
'''Gets a proper filename for 'file', if this is a path.
'kind' should be the kind of the output file (photo, document...)
'extension' should be the extension to be added to the file if
the filename doesn't have any yet
'date' should be when this file was originally sent, if known
'possible_names' should be an ordered list of possible names
If no modification is made to the path, any existing file
will be overwritten.
If any modification is made to the path, this method will
ensure that no existing file will be overwritten.
'''
pass
| 21 | 10 | 57 | 8 | 33 | 16 | 8 | 0.5 | 0 | 18 | 4 | 0 | 9 | 0 | 14 | 14 | 874 | 138 | 490 | 131 | 409 | 247 | 271 | 63 | 255 | 16 | 0 | 5 | 121 |
146,789 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/dialogs.py
|
telethon.client.dialogs._DraftsIter
|
class _DraftsIter(RequestIter):
async def _init(self, entities, **kwargs):
if not entities:
r = await self.client(functions.messages.GetAllDraftsRequest())
items = r.updates
else:
peers = []
for entity in entities:
peers.append(types.InputDialogPeer(
await self.client.get_input_entity(entity)))
r = await self.client(functions.messages.GetPeerDialogsRequest(peers))
items = r.dialogs
# TODO Maybe there should be a helper method for this?
entities = {utils.get_peer_id(x): x
for x in itertools.chain(r.users, r.chats)}
self.buffer.extend(
custom.Draft(self.client, entities[utils.get_peer_id(d.peer)], d.draft)
for d in items
)
async def _load_next_chunk(self):
return []
|
class _DraftsIter(RequestIter):
async def _init(self, entities, **kwargs):
pass
async def _load_next_chunk(self):
pass
| 3 | 0 | 12 | 2 | 10 | 1 | 2 | 0.05 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 31 | 25 | 4 | 20 | 7 | 17 | 1 | 14 | 7 | 11 | 3 | 5 | 2 | 4 |
146,790 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/client/updates.py
|
telethon.client.updates.UpdateMethods
|
class UpdateMethods:
# region Public methods
async def _run_until_disconnected(self: 'TelegramClient'):
try:
# Make a high-level request to notify that we want updates
await self(functions.updates.GetStateRequest())
result = await self.disconnected
if self._updates_error is not None:
raise self._updates_error
return result
except KeyboardInterrupt:
pass
finally:
await self.disconnect()
async def set_receive_updates(self: 'TelegramClient', receive_updates):
"""
Change the value of `receive_updates`.
This is an `async` method, because in order for Telegram to start
sending updates again, a request must be made.
"""
self._no_updates = not receive_updates
if receive_updates:
await self(functions.updates.GetStateRequest())
def run_until_disconnected(self: 'TelegramClient'):
"""
Runs the event loop until the library is disconnected.
It also notifies Telegram that we want to receive updates
as described in https://core.telegram.org/api/updates.
If an unexpected error occurs during update handling,
the client will disconnect and said error will be raised.
Manual disconnections can be made by calling `disconnect()
<telethon.client.telegrambaseclient.TelegramBaseClient.disconnect>`
or sending a ``KeyboardInterrupt`` (e.g. by pressing ``Ctrl+C`` on
the console window running the script).
If a disconnection error occurs (i.e. the library fails to reconnect
automatically), said error will be raised through here, so you have a
chance to ``except`` it on your own code.
If the loop is already running, this method returns a coroutine
that you should await on your own code.
.. note::
If you want to handle ``KeyboardInterrupt`` in your code,
simply run the event loop in your code too in any way, such as
``loop.run_forever()`` or ``await client.disconnected`` (e.g.
``loop.run_until_complete(client.disconnected)``).
Example
.. code-block:: python
# Blocks the current task here until a disconnection occurs.
#
# You will still receive updates, since this prevents the
# script from exiting.
await client.run_until_disconnected()
"""
if self.loop.is_running():
return self._run_until_disconnected()
try:
return self.loop.run_until_complete(self._run_until_disconnected())
except KeyboardInterrupt:
pass
finally:
# No loop.run_until_complete; it's already syncified
self.disconnect()
def on(self: 'TelegramClient', event: EventBuilder):
"""
Decorator used to `add_event_handler` more conveniently.
Arguments
event (`_EventBuilder` | `type`):
The event builder class or instance to be used,
for instance ``events.NewMessage``.
Example
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
# Here we use client.on
@client.on(events.NewMessage)
async def handler(event):
...
"""
def decorator(f):
self.add_event_handler(f, event)
return f
return decorator
def add_event_handler(
self: 'TelegramClient',
callback: Callback,
event: EventBuilder = None):
"""
Registers a new event handler callback.
The callback will be called when the specified event occurs.
Arguments
callback (`callable`):
The callable function accepting one parameter to be used.
Note that if you have used `telethon.events.register` in
the callback, ``event`` will be ignored, and instead the
events you previously registered will be used.
event (`_EventBuilder` | `type`, optional):
The event builder class or instance to be used,
for instance ``events.NewMessage``.
If left unspecified, `telethon.events.raw.Raw` (the
:tl:`Update` objects with no further processing) will
be passed instead.
Example
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
async def handler(event):
...
client.add_event_handler(handler, events.NewMessage)
"""
builders = events._get_handlers(callback)
if builders is not None:
for event in builders:
self._event_builders.append((event, callback))
return
if isinstance(event, type):
event = event()
elif not event:
event = events.Raw()
self._event_builders.append((event, callback))
def remove_event_handler(
self: 'TelegramClient',
callback: Callback,
event: EventBuilder = None) -> int:
"""
Inverse operation of `add_event_handler()`.
If no event is given, all events for this callback are removed.
Returns how many callbacks were removed.
Example
.. code-block:: python
@client.on(events.Raw)
@client.on(events.NewMessage)
async def handler(event):
...
# Removes only the "Raw" handling
# "handler" will still receive "events.NewMessage"
client.remove_event_handler(handler, events.Raw)
# "handler" will stop receiving anything
client.remove_event_handler(handler)
"""
found = 0
if event and not isinstance(event, type):
event = type(event)
i = len(self._event_builders)
while i:
i -= 1
ev, cb = self._event_builders[i]
if cb == callback and (not event or isinstance(ev, event)):
del self._event_builders[i]
found += 1
return found
def list_event_handlers(self: 'TelegramClient')\
-> 'typing.Sequence[typing.Tuple[Callback, EventBuilder]]':
"""
Lists all registered event handlers.
Returns
A list of pairs consisting of ``(callback, event)``.
Example
.. code-block:: python
@client.on(events.NewMessage(pattern='hello'))
async def on_greeting(event):
'''Greets someone'''
await event.reply('Hi')
for callback, event in client.list_event_handlers():
print(id(callback), type(event))
"""
return [(callback, event) for event, callback in self._event_builders]
async def catch_up(self: 'TelegramClient'):
"""
"Catches up" on the missed updates while the client was offline.
You should call this method after registering the event handlers
so that the updates it loads can by processed by your script.
This can also be used to forcibly fetch new updates if there are any.
Example
.. code-block:: python
await client.catch_up()
"""
await self._updates_queue.put(types.UpdatesTooLong())
# endregion
# region Private methods
async def _update_loop(self: 'TelegramClient'):
# If the MessageBox is not empty, the account had to be logged-in to fill in its state.
# This flag is used to propagate the "you got logged-out" error up (but getting logged-out
# can only happen if it was once logged-in).
was_once_logged_in = self._authorized is True or not self._message_box.is_empty()
self._updates_error = None
try:
if self._catch_up:
# User wants to catch up as soon as the client is up and running,
# so this is the best place to do it.
await self.catch_up()
updates_to_dispatch = deque()
while self.is_connected():
if updates_to_dispatch:
if self._sequential_updates:
await self._dispatch_update(updates_to_dispatch.popleft())
else:
while updates_to_dispatch:
# TODO if _dispatch_update fails for whatever reason, it's not logged! this should be fixed
task = self.loop.create_task(self._dispatch_update(updates_to_dispatch.popleft()))
self._event_handler_tasks.add(task)
task.add_done_callback(self._event_handler_tasks.discard)
continue
if len(self._mb_entity_cache) >= self._entity_cache_limit:
self._log[__name__].info(
'In-memory entity cache limit reached (%s/%s), flushing to session',
len(self._mb_entity_cache),
self._entity_cache_limit
)
self._save_states_and_entities()
self._mb_entity_cache.retain(lambda id: id == self._mb_entity_cache.self_id or id in self._message_box.map)
if len(self._mb_entity_cache) >= self._entity_cache_limit:
warnings.warn('in-memory entities exceed entity_cache_limit after flushing; consider setting a larger limit')
self._log[__name__].info(
'In-memory entity cache at %s/%s after flushing to session',
len(self._mb_entity_cache),
self._entity_cache_limit
)
get_diff = self._message_box.get_difference()
if get_diff:
self._log[__name__].debug('Getting difference for account updates')
try:
diff = await self(get_diff)
except (
errors.ServerError,
errors.TimedOutError,
errors.FloodWaitError,
ValueError
) as e:
# Telegram is having issues
self._log[__name__].info('Cannot get difference since Telegram is having issues: %s', type(e).__name__)
self._message_box.end_difference()
continue
except (errors.UnauthorizedError, errors.AuthKeyError) as e:
# Not logged in or broken authorization key, can't get difference
self._log[__name__].info('Cannot get difference since the account is not logged in: %s', type(e).__name__)
self._message_box.end_difference()
if was_once_logged_in:
self._updates_error = e
await self.disconnect()
break
continue
except (errors.TypeNotFoundError, sqlite3.OperationalError) as e:
# User is likely doing weird things with their account or session and Telegram gets confused as to what layer they use
self._log[__name__].warning('Cannot get difference since the account is likely misusing the session: %s', e)
self._message_box.end_difference()
self._updates_error = e
await self.disconnect()
break
except OSError as e:
# Network is likely down, but it's unclear for how long.
# If disconnect is called this task will be cancelled along with the sleep.
# If disconnect is not called, getting difference should be retried after a few seconds.
self._log[__name__].info('Cannot get difference since the network is down: %s: %s', type(e).__name__, e)
await asyncio.sleep(5)
continue
updates, users, chats = self._message_box.apply_difference(diff, self._mb_entity_cache)
if updates:
self._log[__name__].info('Got difference for account updates')
updates_to_dispatch.extend(self._preprocess_updates(updates, users, chats))
continue
get_diff = self._message_box.get_channel_difference(self._mb_entity_cache)
if get_diff:
self._log[__name__].debug('Getting difference for channel %s updates', get_diff.channel.channel_id)
try:
diff = await self(get_diff)
except (errors.UnauthorizedError, errors.AuthKeyError) as e:
# Not logged in or broken authorization key, can't get difference
self._log[__name__].warning(
'Cannot get difference for channel %s since the account is not logged in: %s',
get_diff.channel.channel_id, type(e).__name__
)
self._message_box.end_channel_difference(
get_diff,
PrematureEndReason.TEMPORARY_SERVER_ISSUES,
self._mb_entity_cache
)
if was_once_logged_in:
self._updates_error = e
await self.disconnect()
break
continue
except (errors.TypeNotFoundError, sqlite3.OperationalError) as e:
self._log[__name__].warning(
'Cannot get difference for channel %s since the account is likely misusing the session: %s',
get_diff.channel.channel_id, e
)
self._message_box.end_channel_difference(
get_diff,
PrematureEndReason.TEMPORARY_SERVER_ISSUES,
self._mb_entity_cache
)
self._updates_error = e
await self.disconnect()
break
except (
errors.PersistentTimestampOutdatedError,
errors.PersistentTimestampInvalidError,
errors.ServerError,
errors.TimedOutError,
errors.FloodWaitError,
ValueError
) as e:
# According to Telegram's docs:
# "Channel internal replication issues, try again later (treat this like an RPC_CALL_FAIL)."
# We can treat this as "empty difference" and not update the local pts.
# Then this same call will be retried when another gap is detected or timeout expires.
#
# Another option would be to literally treat this like an RPC_CALL_FAIL and retry after a few
# seconds, but if Telegram is having issues it's probably best to wait for it to send another
# update (hinting it may be okay now) and retry then.
#
# This is a bit hacky because MessageBox doesn't really have a way to "not update" the pts.
# Instead we manually extract the previously-known pts and use that.
#
# For PersistentTimestampInvalidError:
# Somehow our pts is either too new or the server does not know about this.
# We treat this as PersistentTimestampOutdatedError for now.
# TODO investigate why/when this happens and if this is the proper solution
self._log[__name__].warning(
'Getting difference for channel updates %s caused %s;'
' ending getting difference prematurely until server issues are resolved',
get_diff.channel.channel_id, type(e).__name__
)
self._message_box.end_channel_difference(
get_diff,
PrematureEndReason.TEMPORARY_SERVER_ISSUES,
self._mb_entity_cache
)
continue
except (errors.ChannelPrivateError, errors.ChannelInvalidError):
# Timeout triggered a get difference, but we have been banned in the channel since then.
# Because we can no longer fetch updates from this channel, we should stop keeping track
# of it entirely.
self._log[__name__].info(
'Account is now banned in %d so we can no longer fetch updates from it',
get_diff.channel.channel_id
)
self._message_box.end_channel_difference(
get_diff,
PrematureEndReason.BANNED,
self._mb_entity_cache
)
continue
except OSError as e:
self._log[__name__].info(
'Cannot get difference for channel %d since the network is down: %s: %s',
get_diff.channel.channel_id, type(e).__name__, e
)
await asyncio.sleep(5)
continue
updates, users, chats = self._message_box.apply_channel_difference(get_diff, diff, self._mb_entity_cache)
if updates:
self._log[__name__].info('Got difference for channel %d updates', get_diff.channel.channel_id)
updates_to_dispatch.extend(self._preprocess_updates(updates, users, chats))
continue
deadline = self._message_box.check_deadlines()
deadline_delay = deadline - get_running_loop().time()
if deadline_delay > 0:
# Don't bother sleeping and timing out if the delay is already 0 (pollutes the logs).
try:
updates = await asyncio.wait_for(self._updates_queue.get(), deadline_delay)
except asyncio.TimeoutError:
self._log[__name__].debug('Timeout waiting for updates expired')
continue
else:
continue
processed = []
try:
users, chats = self._message_box.process_updates(updates, self._mb_entity_cache, processed)
except GapError:
continue # get(_channel)_difference will start returning requests
updates_to_dispatch.extend(self._preprocess_updates(processed, users, chats))
except asyncio.CancelledError:
pass
except Exception as e:
self._log[__name__].exception(f'Fatal error handling updates (this is a bug in Telethon v{__version__}, please report it)')
self._updates_error = e
await self.disconnect()
def _preprocess_updates(self, updates, users, chats):
self._mb_entity_cache.extend(users, chats)
entities = {utils.get_peer_id(x): x
for x in itertools.chain(users, chats)}
for u in updates:
u._entities = entities
return updates
async def _keepalive_loop(self: 'TelegramClient'):
# Pings' ID don't really need to be secure, just "random"
rnd = lambda: random.randrange(-2**63, 2**63)
while self.is_connected():
try:
await asyncio.wait_for(
self.disconnected, timeout=60
)
continue # We actually just want to act upon timeout
except asyncio.TimeoutError:
pass
except asyncio.CancelledError:
return
except Exception:
continue # Any disconnected exception should be ignored
# Check if we have any exported senders to clean-up periodically
await self._clean_exported_senders()
# Don't bother sending pings until the low-level connection is
# ready, otherwise a lot of pings will be batched to be sent upon
# reconnect, when we really don't care about that.
if not self._sender._transport_connected():
continue
# We also don't really care about their result.
# Just send them periodically.
try:
self._sender._keepalive_ping(rnd())
except (ConnectionError, asyncio.CancelledError):
return
# Entities and cached files are not saved when they are
# inserted because this is a rather expensive operation
# (default's sqlite3 takes ~0.1s to commit changes). Do
# it every minute instead. No-op if there's nothing new.
self._save_states_and_entities()
self.session.save()
async def _dispatch_update(self: 'TelegramClient', update):
# TODO only used for AlbumHack, and MessageBox is not really designed for this
others = None
if not self._mb_entity_cache.self_id:
# Some updates require our own ID, so we must make sure
# that the event builder has offline access to it. Calling
# `get_me()` will cache it under `self._mb_entity_cache`.
#
# It will return `None` if we haven't logged in yet which is
# fine, we will just retry next time anyway.
try:
await self.get_me(input_peer=True)
except OSError:
pass # might not have connection
built = EventBuilderDict(self, update, others)
for conv_set in self._conversations.values():
for conv in conv_set:
ev = built[events.NewMessage]
if ev:
conv._on_new_message(ev)
ev = built[events.MessageEdited]
if ev:
conv._on_edit(ev)
ev = built[events.MessageRead]
if ev:
conv._on_read(ev)
if conv._custom:
await conv._check_custom(built)
for builder, callback in self._event_builders:
event = built[type(builder)]
if not event:
continue
if not builder.resolved:
await builder.resolve(self)
filter = builder.filter(event)
if inspect.isawaitable(filter):
filter = await filter
if not filter:
continue
try:
await callback(event)
except errors.AlreadyInConversationError:
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].debug(
'Event handler "%s" already has an open conversation, '
'ignoring new one', name)
except events.StopPropagation:
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].debug(
'Event handler "%s" stopped chain of propagation '
'for event %s.', name, type(event).__name__
)
break
except Exception as e:
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].exception('Unhandled exception on %s', name)
async def _dispatch_event(self: 'TelegramClient', event):
"""
Dispatches a single, out-of-order event. Used by `AlbumHack`.
"""
# We're duplicating a most logic from `_dispatch_update`, but all in
# the name of speed; we don't want to make it worse for all updates
# just because albums may need it.
for builder, callback in self._event_builders:
if isinstance(builder, events.Raw):
continue
if not isinstance(event, builder.Event):
continue
if not builder.resolved:
await builder.resolve(self)
filter = builder.filter(event)
if inspect.isawaitable(filter):
filter = await filter
if not filter:
continue
try:
await callback(event)
except errors.AlreadyInConversationError:
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].debug(
'Event handler "%s" already has an open conversation, '
'ignoring new one', name)
except events.StopPropagation:
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].debug(
'Event handler "%s" stopped chain of propagation '
'for event %s.', name, type(event).__name__
)
break
except Exception as e:
if not isinstance(e, asyncio.CancelledError) or self.is_connected():
name = getattr(callback, '__name__', repr(callback))
self._log[__name__].exception('Unhandled exception on %s', name)
async def _handle_auto_reconnect(self: 'TelegramClient'):
# TODO Catch-up
# For now we make a high-level request to let Telegram
# know we are still interested in receiving more updates.
try:
await self.get_me()
except Exception as e:
self._log[__name__].warning('Error executing high-level request '
'after reconnect: %s: %s', type(e), e)
return
try:
self._log[__name__].info(
'Asking for the current state after reconnect...')
# TODO consider:
# If there aren't many updates while the client is disconnected
# (I tried with up to 20), Telegram seems to send them without
# asking for them (via updates.getDifference).
#
# On disconnection, the library should probably set a "need
# difference" or "catching up" flag so that any new updates are
# ignored, and then the library should call updates.getDifference
# itself to fetch them.
#
# In any case (either there are too many updates and Telegram
# didn't send them, or there isn't a lot and Telegram sent them
# but we dropped them), we fetch the new difference to get all
# missed updates. I feel like this would be the best solution.
# If a disconnection occurs, the old known state will be
# the latest one we were aware of, so we can catch up since
# the most recent state we were aware of.
await self.catch_up()
self._log[__name__].info('Successfully fetched missed updates')
except errors.RPCError as e:
self._log[__name__].warning('Failed to get missed updates after '
'reconnect: %r', e)
except Exception:
self._log[__name__].exception(
'Unhandled exception while getting update difference after reconnect')
|
class UpdateMethods:
async def _run_until_disconnected(self: 'TelegramClient'):
pass
async def set_receive_updates(self: 'TelegramClient', receive_updates):
'''
Change the value of `receive_updates`.
This is an `async` method, because in order for Telegram to start
sending updates again, a request must be made.
'''
pass
def run_until_disconnected(self: 'TelegramClient'):
'''
Runs the event loop until the library is disconnected.
It also notifies Telegram that we want to receive updates
as described in https://core.telegram.org/api/updates.
If an unexpected error occurs during update handling,
the client will disconnect and said error will be raised.
Manual disconnections can be made by calling `disconnect()
<telethon.client.telegrambaseclient.TelegramBaseClient.disconnect>`
or sending a ``KeyboardInterrupt`` (e.g. by pressing ``Ctrl+C`` on
the console window running the script).
If a disconnection error occurs (i.e. the library fails to reconnect
automatically), said error will be raised through here, so you have a
chance to ``except`` it on your own code.
If the loop is already running, this method returns a coroutine
that you should await on your own code.
.. note::
If you want to handle ``KeyboardInterrupt`` in your code,
simply run the event loop in your code too in any way, such as
``loop.run_forever()`` or ``await client.disconnected`` (e.g.
``loop.run_until_complete(client.disconnected)``).
Example
.. code-block:: python
# Blocks the current task here until a disconnection occurs.
#
# You will still receive updates, since this prevents the
# script from exiting.
await client.run_until_disconnected()
'''
pass
def on(self: 'TelegramClient', event: EventBuilder):
'''
Decorator used to `add_event_handler` more conveniently.
Arguments
event (`_EventBuilder` | `type`):
The event builder class or instance to be used,
for instance ``events.NewMessage``.
Example
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
# Here we use client.on
@client.on(events.NewMessage)
async def handler(event):
...
'''
pass
def decorator(f):
pass
def add_event_handler(
self: 'TelegramClient',
callback: Callback,
event: EventBuilder = None):
'''
Registers a new event handler callback.
The callback will be called when the specified event occurs.
Arguments
callback (`callable`):
The callable function accepting one parameter to be used.
Note that if you have used `telethon.events.register` in
the callback, ``event`` will be ignored, and instead the
events you previously registered will be used.
event (`_EventBuilder` | `type`, optional):
The event builder class or instance to be used,
for instance ``events.NewMessage``.
If left unspecified, `telethon.events.raw.Raw` (the
:tl:`Update` objects with no further processing) will
be passed instead.
Example
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
async def handler(event):
...
client.add_event_handler(handler, events.NewMessage)
'''
pass
def remove_event_handler(
self: 'TelegramClient',
callback: Callback,
event: EventBuilder = None) -> int:
'''
Inverse operation of `add_event_handler()`.
If no event is given, all events for this callback are removed.
Returns how many callbacks were removed.
Example
.. code-block:: python
@client.on(events.Raw)
@client.on(events.NewMessage)
async def handler(event):
...
# Removes only the "Raw" handling
# "handler" will still receive "events.NewMessage"
client.remove_event_handler(handler, events.Raw)
# "handler" will stop receiving anything
client.remove_event_handler(handler)
'''
pass
def list_event_handlers(self: 'TelegramClient')\
-> 'typing.Sequence[typing.Tuple[Callback, EventBuilder]]':
'''
Lists all registered event handlers.
Returns
A list of pairs consisting of ``(callback, event)``.
Example
.. code-block:: python
@client.on(events.NewMessage(pattern='hello'))
async def on_greeting(event):
'''Greets someone'''
await event.reply('Hi')
for callback, event in client.list_event_handlers():
print(id(callback), type(event))
'''
pass
async def catch_up(self: 'TelegramClient'):
'''
"Catches up" on the missed updates while the client was offline.
You should call this method after registering the event handlers
so that the updates it loads can by processed by your script.
This can also be used to forcibly fetch new updates if there are any.
Example
.. code-block:: python
await client.catch_up()
'''
pass
async def _update_loop(self: 'TelegramClient'):
pass
def _preprocess_updates(self, updates, users, chats):
pass
async def _keepalive_loop(self: 'TelegramClient'):
pass
async def _dispatch_update(self: 'TelegramClient', update):
pass
async def _dispatch_event(self: 'TelegramClient', event):
'''
Dispatches a single, out-of-order event. Used by `AlbumHack`.
'''
pass
async def _handle_auto_reconnect(self: 'TelegramClient'):
pass
| 16 | 8 | 42 | 5 | 24 | 13 | 6 | 0.54 | 0 | 20 | 11 | 0 | 14 | 3 | 14 | 14 | 643 | 93 | 359 | 59 | 336 | 195 | 278 | 47 | 262 | 28 | 0 | 5 | 91 |
146,791 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/sessions/memory.py
|
telethon.sessions.memory._SentFileType
|
class _SentFileType(Enum):
DOCUMENT = 0
PHOTO = 1
@staticmethod
def from_type(cls):
if cls == InputDocument:
return _SentFileType.DOCUMENT
elif cls == InputPhoto:
return _SentFileType.PHOTO
else:
raise ValueError('The cls must be either InputDocument/InputPhoto')
|
class _SentFileType(Enum):
@staticmethod
def from_type(cls):
pass
| 3 | 0 | 7 | 0 | 7 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 50 | 12 | 1 | 11 | 5 | 8 | 0 | 8 | 4 | 6 | 3 | 4 | 1 | 3 |
146,792 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/helpers.py
|
telethon.helpers._EntityType
|
class _EntityType(enum.Enum):
USER = 0
CHAT = 1
CHANNEL = 2
|
class _EntityType(enum.Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
146,793 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/core/gzippacked.py
|
telethon.tl.core.gzippacked.GzipPacked
|
class GzipPacked(TLObject):
CONSTRUCTOR_ID = 0x3072cfa1
def __init__(self, data):
self.data = data
@staticmethod
def gzip_if_smaller(content_related, data):
"""Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requests.
"""
if content_related and len(data) > 512:
gzipped = bytes(GzipPacked(data))
return gzipped if len(gzipped) < len(data) else data
else:
return data
def __bytes__(self):
return struct.pack('<I', GzipPacked.CONSTRUCTOR_ID) + \
TLObject.serialize_bytes(gzip.compress(self.data))
@staticmethod
def read(reader):
constructor = reader.read_int(signed=False)
assert constructor == GzipPacked.CONSTRUCTOR_ID
return gzip.decompress(reader.tgread_bytes())
@classmethod
def from_reader(cls, reader):
return GzipPacked(gzip.decompress(reader.tgread_bytes()))
def to_dict(self):
return {
'_': 'GzipPacked',
'data': self.data
}
|
class GzipPacked(TLObject):
def __init__(self, data):
pass
@staticmethod
def gzip_if_smaller(content_related, data):
'''Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requests.
'''
pass
def __bytes__(self):
pass
@staticmethod
def read(reader):
pass
@classmethod
def from_reader(cls, reader):
pass
def to_dict(self):
pass
| 10 | 1 | 5 | 0 | 4 | 1 | 1 | 0.19 | 1 | 1 | 0 | 0 | 3 | 1 | 6 | 6 | 39 | 7 | 27 | 14 | 17 | 5 | 19 | 11 | 12 | 3 | 1 | 1 | 8 |
146,794 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/parsers/tlobject/tlarg.py
|
telethon_generator.parsers.tlobject.tlarg.TLArg
|
class TLArg:
def __init__(self, name, arg_type, generic_definition):
"""
Initializes a new .tl argument
:param name: The name of the .tl argument
:param arg_type: The type of the .tl argument
:param generic_definition: Is the argument a generic definition?
(i.e. {X:Type})
"""
if name == 'self':
self.name = 'is_self'
elif name == 'from':
self.name = 'from_'
else:
self.name = name
# Default values
self.is_vector = False
self.flag = None # name of the flag to check if self is present
self.skip_constructor_id = False
self.flag_index = -1 # bit index of the flag to check if self is present
self.cls = None
# Special case: some types can be inferred, which makes it
# less annoying to type. Currently the only type that can
# be inferred is if the name is 'random_id', to which a
# random ID will be assigned if left as None (the default)
self.can_be_inferred = name == 'random_id'
# The type can be an indicator that other arguments will be flags
if arg_type == '#':
self.flag_indicator = True
self.type = None
self.is_generic = False
else:
self.flag_indicator = False
self.is_generic = arg_type.startswith('!')
# Strip the exclamation mark always to have only the name
self.type = arg_type.lstrip('!')
# The type may be a flag (FLAGS.IDX?REAL_TYPE)
# FLAGS can be any name, but it should have appeared previously.
flag_match = re.match(r'(\w+).(\d+)\?([\w<>.]+)', self.type)
if flag_match:
self.flag = flag_match.group(1)
self.flag_index = int(flag_match.group(2))
# Update the type to match the exact type, not the "flagged" one
self.type = flag_match.group(3)
# Then check if the type is a Vector<REAL_TYPE>
vector_match = re.match(r'[Vv]ector<([\w\d.]+)>', self.type)
if vector_match:
self.is_vector = True
# If the type's first letter is not uppercase, then
# it is a constructor and we use (read/write) its ID
# as pinpointed on issue #81.
self.use_vector_id = self.type[0] == 'V'
# Update the type to match the one inside the vector
self.type = vector_match.group(1)
# See use_vector_id. An example of such case is ipPort in
# help.configSpecial
if self.type.split('.')[-1][0].islower():
self.skip_constructor_id = True
# The name may contain "date" in it, if this is the case and
# the type is "int", we can safely assume that this should be
# treated as a "date" object. Note that this is not a valid
# Telegram object, but it's easier to work with
if self.type == 'int' and (
re.search(r'(\b|_)(date|until|since)(\b|_)', name) or
name in ('expires', 'expires_at', 'was_online')):
self.type = 'date'
self.generic_definition = generic_definition
def type_hint(self):
cls = self.type
if '.' in cls:
cls = cls.split('.')[1]
result = {
'int': 'int',
'long': 'int',
'int128': 'int',
'int256': 'int',
'double': 'float',
'string': 'str',
'date': 'Optional[datetime]', # None date = 0 timestamp
'bytes': 'bytes',
'Bool': 'bool',
'true': 'bool',
}.get(cls, "'Type{}'".format(cls))
if self.is_vector:
result = 'List[{}]'.format(result)
if self.flag and cls != 'date':
result = 'Optional[{}]'.format(result)
return result
def real_type(self):
# Find the real type representation by updating it as required
real_type = self.type
if self.flag_indicator:
real_type = '#'
if self.is_vector:
if self.use_vector_id:
real_type = 'Vector<{}>'.format(real_type)
else:
real_type = 'vector<{}>'.format(real_type)
if self.is_generic:
real_type = '!{}'.format(real_type)
if self.flag:
real_type = '{}.{}?{}'.format(self.flag, self.flag_index, real_type)
return real_type
def __str__(self):
name = self.orig_name()
if self.generic_definition:
return '{{{}:{}}}'.format(name, self.real_type())
else:
return '{}:{}'.format(name, self.real_type())
def __repr__(self):
return str(self).replace(':date', ':int').replace('?date', '?int')
def orig_name(self):
return self.name.replace('is_self', 'self').strip('_')
def to_dict(self):
return {
'name': self.orig_name(),
'type': re.sub(r'\bdate$', 'int', self.real_type())
}
def as_example(self, f, indent=0):
if self.is_generic:
f.write('other_request')
return
known = (KNOWN_NAMED_EXAMPLES.get((self.name, self.type))
or KNOWN_TYPED_EXAMPLES.get(self.type)
or KNOWN_TYPED_EXAMPLES.get(SYNONYMS.get(self.type)))
if known:
f.write(known)
return
assert self.omit_example() or self.cls, 'TODO handle ' + str(self)
# Pick an interesting example if any
for cls in self.cls:
if cls.is_good_example():
cls.as_example(f, indent)
break
else:
# If no example is good, just pick the first
self.cls[0].as_example(f, indent)
def omit_example(self):
return (self.flag or self.can_be_inferred) \
and self.name in OMITTED_EXAMPLES
|
class TLArg:
def __init__(self, name, arg_type, generic_definition):
'''
Initializes a new .tl argument
:param name: The name of the .tl argument
:param arg_type: The type of the .tl argument
:param generic_definition: Is the argument a generic definition?
(i.e. {X:Type})
'''
pass
def type_hint(self):
pass
def real_type(self):
pass
def __str__(self):
pass
def __repr__(self):
pass
def orig_name(self):
pass
def to_dict(self):
pass
def as_example(self, f, indent=0):
pass
def omit_example(self):
pass
| 10 | 1 | 17 | 2 | 12 | 4 | 3 | 0.33 | 0 | 2 | 0 | 0 | 9 | 12 | 9 | 9 | 166 | 26 | 109 | 30 | 99 | 36 | 85 | 30 | 75 | 8 | 0 | 2 | 29 |
146,795 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/parsers/methods.py
|
telethon_generator.parsers.methods.Usability
|
class Usability(enum.Enum):
UNKNOWN = 0
USER = 1
BOT = 2
BOTH = 4
@property
def key(self):
return {
Usability.UNKNOWN: 'unknown',
Usability.USER: 'user',
Usability.BOT: 'bot',
Usability.BOTH: 'both',
}[self]
|
class Usability(enum.Enum):
@property
def key(self):
pass
| 3 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 50 | 14 | 1 | 13 | 7 | 10 | 0 | 7 | 6 | 5 | 1 | 4 | 0 | 1 |
146,796 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/parsers/methods.py
|
telethon_generator.parsers.methods.MethodInfo
|
class MethodInfo:
def __init__(self, name, usability, errors, friendly):
self.name = name
self.errors = errors
self.friendly = friendly
try:
self.usability = {
'unknown': Usability.UNKNOWN,
'user': Usability.USER,
'bot': Usability.BOT,
'both': Usability.BOTH,
}[usability.lower()]
except KeyError:
raise ValueError('Usability must be either user, bot, both or '
'unknown, not {}'.format(usability)) from None
|
class MethodInfo:
def __init__(self, name, usability, errors, friendly):
pass
| 2 | 0 | 14 | 0 | 14 | 0 | 2 | 0 | 0 | 3 | 1 | 0 | 1 | 4 | 1 | 1 | 15 | 0 | 15 | 6 | 13 | 0 | 9 | 6 | 7 | 2 | 0 | 1 | 2 |
146,797 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/parsers/errors.py
|
telethon_generator.parsers.errors.Error
|
class Error:
def __init__(self, codes, name, description):
# TODO Some errors have the same name but different integer codes
# Should these be split into different files or doesn't really matter?
# Telegram isn't exactly consistent with returned errors anyway.
self.int_code = codes[0]
self.int_codes = codes
self.str_code = name
self.subclass = _get_class_name(codes[0])
self.subclass_exists = abs(codes[0]) in KNOWN_BASE_CLASSES
self.description = description
self.has_captures = '_X' in name
if self.has_captures:
self.name = _get_class_name(name.replace('_X', '_'))
self.pattern = name.replace('_X', r'_(\d+)')
self.capture_name = re.search(r'{(\w+)}', description).group(1)
else:
self.name = _get_class_name(name)
self.pattern = name
self.capture_name = None
|
class Error:
def __init__(self, codes, name, description):
pass
| 2 | 0 | 20 | 1 | 16 | 3 | 2 | 0.18 | 0 | 0 | 0 | 0 | 1 | 10 | 1 | 1 | 21 | 1 | 17 | 12 | 15 | 3 | 16 | 12 | 14 | 2 | 0 | 1 | 2 |
146,798 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/inlinequery.py
|
telethon.events.inlinequery.InlineQuery.Event
|
class Event(EventCommon, SenderGetter):
"""
Represents the event of a new callback query.
Members:
query (:tl:`UpdateBotInlineQuery`):
The original :tl:`UpdateBotInlineQuery`.
Make sure to access the `text` property of the query if
you want the text rather than the actual query object.
pattern_match (`obj`, optional):
The resulting object from calling the passed ``pattern``
function, which is ``re.compile(...).match`` by default.
"""
def __init__(self, query):
super().__init__(chat_peer=types.PeerUser(query.user_id))
SenderGetter.__init__(self, query.user_id)
self.query = query
self.pattern_match = None
self._answered = False
def _set_client(self, client):
super()._set_client(client)
self._sender, self._input_sender = utils._get_entity_pair(
self.sender_id, self._entities, client._mb_entity_cache)
@property
def id(self):
"""
Returns the unique identifier for the query ID.
"""
return self.query.query_id
@property
def text(self):
"""
Returns the text the user used to make the inline query.
"""
return self.query.query
@property
def offset(self):
"""
The string the user's client used as an offset for the query.
This will either be empty or equal to offsets passed to `answer`.
"""
return self.query.offset
@property
def geo(self):
"""
If the user location is requested when using inline mode
and the user's device is able to send it, this will return
the :tl:`GeoPoint` with the position of the user.
"""
return self.query.geo
@property
def builder(self):
"""
Returns a new `InlineBuilder
<telethon.tl.custom.inlinebuilder.InlineBuilder>` instance.
"""
return custom.InlineBuilder(self._client)
async def answer(
self, results=None, cache_time=0, *,
gallery=False, next_offset=None, private=False,
switch_pm=None, switch_pm_param=''):
"""
Answers the inline query with the given results.
See the documentation for `builder` to know what kind of answers
can be given.
Args:
results (`list`, optional):
A list of :tl:`InputBotInlineResult` to use.
You should use `builder` to create these:
.. code-block:: python
builder = inline.builder
r1 = builder.article('Be nice', text='Have a nice day')
r2 = builder.article('Be bad', text="I don't like you")
await inline.answer([r1, r2])
You can send up to 50 results as documented in
https://core.telegram.org/bots/api#answerinlinequery.
Sending more will raise ``ResultsTooMuchError``,
and you should consider using `next_offset` to
paginate them.
cache_time (`int`, optional):
For how long this result should be cached on
the user's client. Defaults to 0 for no cache.
gallery (`bool`, optional):
Whether the results should show as a gallery (grid) or not.
next_offset (`str`, optional):
The offset the client will send when the user scrolls the
results and it repeats the request.
private (`bool`, optional):
Whether the results should be cached by Telegram
(not private) or by the user's client (private).
switch_pm (`str`, optional):
If set, this text will be shown in the results
to allow the user to switch to private messages.
switch_pm_param (`str`, optional):
Optional parameter to start the bot with if
`switch_pm` was used.
Example:
.. code-block:: python
@bot.on(events.InlineQuery)
async def handler(event):
builder = event.builder
rev_text = event.text[::-1]
await event.answer([
builder.article('Reverse text', text=rev_text),
builder.photo('/path/to/photo.jpg')
])
"""
if self._answered:
return
if results:
futures = [self._as_future(x) for x in results]
await asyncio.wait(futures)
# All futures will be in the `done` *set* that `wait` returns.
#
# Precisely because it's a `set` and not a `list`, it
# will not preserve the order, but since all futures
# completed we can use our original, ordered `list`.
results = [x.result() for x in futures]
else:
results = []
if switch_pm:
switch_pm = types.InlineBotSwitchPM(switch_pm, switch_pm_param)
return await self._client(
functions.messages.SetInlineBotResultsRequest(
query_id=self.query.query_id,
results=results,
cache_time=cache_time,
gallery=gallery,
next_offset=next_offset,
private=private,
switch_pm=switch_pm
)
)
@staticmethod
def _as_future(obj):
if inspect.isawaitable(obj):
return asyncio.ensure_future(obj)
f = helpers.get_running_loop().create_future()
f.set_result(obj)
return f
|
class Event(EventCommon, SenderGetter):
'''
Represents the event of a new callback query.
Members:
query (:tl:`UpdateBotInlineQuery`):
The original :tl:`UpdateBotInlineQuery`.
Make sure to access the `text` property of the query if
you want the text rather than the actual query object.
pattern_match (`obj`, optional):
The resulting object from calling the passed ``pattern``
function, which is ``re.compile(...).match`` by default.
'''
def __init__(self, query):
pass
def _set_client(self, client):
pass
@property
def id(self):
'''
Returns the unique identifier for the query ID.
'''
pass
@property
def text(self):
'''
Returns the text the user used to make the inline query.
'''
pass
@property
def offset(self):
'''
The string the user's client used as an offset for the query.
This will either be empty or equal to offsets passed to `answer`.
'''
pass
@property
def geo(self):
'''
If the user location is requested when using inline mode
and the user's device is able to send it, this will return
the :tl:`GeoPoint` with the position of the user.
'''
pass
@property
def builder(self):
'''
Returns a new `InlineBuilder
<telethon.tl.custom.inlinebuilder.InlineBuilder>` instance.
'''
pass
async def answer(
self, results=None, cache_time=0, *,
gallery=False, next_offset=None, private=False,
switch_pm=None, switch_pm_param=''):
'''
Answers the inline query with the given results.
See the documentation for `builder` to know what kind of answers
can be given.
Args:
results (`list`, optional):
A list of :tl:`InputBotInlineResult` to use.
You should use `builder` to create these:
.. code-block:: python
builder = inline.builder
r1 = builder.article('Be nice', text='Have a nice day')
r2 = builder.article('Be bad', text="I don't like you")
await inline.answer([r1, r2])
You can send up to 50 results as documented in
https://core.telegram.org/bots/api#answerinlinequery.
Sending more will raise ``ResultsTooMuchError``,
and you should consider using `next_offset` to
paginate them.
cache_time (`int`, optional):
For how long this result should be cached on
the user's client. Defaults to 0 for no cache.
gallery (`bool`, optional):
Whether the results should show as a gallery (grid) or not.
next_offset (`str`, optional):
The offset the client will send when the user scrolls the
results and it repeats the request.
private (`bool`, optional):
Whether the results should be cached by Telegram
(not private) or by the user's client (private).
switch_pm (`str`, optional):
If set, this text will be shown in the results
to allow the user to switch to private messages.
switch_pm_param (`str`, optional):
Optional parameter to start the bot with if
`switch_pm` was used.
Example:
.. code-block:: python
@bot.on(events.InlineQuery)
async def handler(event):
builder = event.builder
rev_text = event.text[::-1]
await event.answer([
builder.article('Reverse text', text=rev_text),
builder.photo('/path/to/photo.jpg')
])
'''
pass
@staticmethod
def _as_future(obj):
pass
| 16 | 7 | 16 | 2 | 6 | 8 | 1 | 1.4 | 2 | 1 | 0 | 0 | 8 | 5 | 9 | 52 | 171 | 32 | 58 | 25 | 39 | 81 | 37 | 16 | 27 | 4 | 6 | 1 | 13 |
146,799 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/chataction.py
|
telethon.events.chataction.ChatAction.Event
|
class Event(EventCommon):
"""
Represents the event of a new chat action.
Members:
action_message (`MessageAction <https://tl.telethon.dev/types/message_action.html>`_):
The message invoked by this Chat Action.
new_pin (`bool`):
`True` if there is a new pin.
new_photo (`bool`):
`True` if there's a new chat photo (or it was removed).
photo (:tl:`Photo`, optional):
The new photo (or `None` if it was removed).
user_added (`bool`):
`True` if the user was added by some other.
user_joined (`bool`):
`True` if the user joined on their own.
user_left (`bool`):
`True` if the user left on their own.
user_kicked (`bool`):
`True` if the user was kicked by some other.
created (`bool`, optional):
`True` if this chat was just created.
new_title (`str`, optional):
The new title string for the chat, if applicable.
new_score (`str`, optional):
The new score string for the game, if applicable.
unpin (`bool`):
`True` if the existing pin gets unpinned.
"""
def __init__(self, where, new_photo=None,
added_by=None, kicked_by=None, created=None,
users=None, new_title=None, pin_ids=None, pin=None, new_score=None):
if isinstance(where, types.MessageService):
self.action_message = where
where = where.peer_id
else:
self.action_message = None
# TODO needs some testing (can there be more than one id, and do they follow pin order?)
# same in get_pinned_message
super().__init__(chat_peer=where,
msg_id=pin_ids[0] if pin_ids else None)
self.new_pin = pin_ids is not None
self._pin_ids = pin_ids
self._pinned_messages = None
self.new_photo = new_photo is not None
self.photo = \
new_photo if isinstance(new_photo, types.Photo) else None
self._added_by = None
self._kicked_by = None
self.user_added = self.user_joined = self.user_left = \
self.user_kicked = self.unpin = False
if added_by is True:
self.user_joined = True
elif added_by:
self.user_added = True
self._added_by = added_by
# If `from_id` was not present (it's `True`) or the affected
# user was "kicked by itself", then it left. Else it was kicked.
if kicked_by is True or (users is not None and kicked_by == users):
self.user_left = True
elif kicked_by:
self.user_kicked = True
self._kicked_by = kicked_by
self.created = bool(created)
if isinstance(users, list):
self._user_ids = [utils.get_peer_id(u) for u in users]
elif users:
self._user_ids = [utils.get_peer_id(users)]
else:
self._user_ids = []
self._users = None
self._input_users = None
self.new_title = new_title
self.new_score = new_score
self.unpin = not pin
def _set_client(self, client):
super()._set_client(client)
if self.action_message:
self.action_message._finish_init(client, self._entities, None)
async def respond(self, *args, **kwargs):
"""
Responds to the chat action message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
"""
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def reply(self, *args, **kwargs):
"""
Replies to the chat action message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
both ``entity`` and ``reply_to`` already set.
Has the same effect as `respond` if there is no message.
"""
if not self.action_message:
return await self.respond(*args, **kwargs)
kwargs['reply_to'] = self.action_message.id
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def delete(self, *args, **kwargs):
"""
Deletes the chat action message. You're responsible for checking
whether you have the permission to do so, or to except the error
otherwise. Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
Does nothing if no message action triggered this event.
"""
if not self.action_message:
return
return await self._client.delete_messages(
await self.get_input_chat(), [self.action_message],
*args, **kwargs
)
async def get_pinned_message(self):
"""
If ``new_pin`` is `True`, this returns the `Message
<telethon.tl.custom.message.Message>` object that was pinned.
"""
if self._pinned_messages is None:
await self.get_pinned_messages()
if self._pinned_messages:
return self._pinned_messages[0]
async def get_pinned_messages(self):
"""
If ``new_pin`` is `True`, this returns a `list` of `Message
<telethon.tl.custom.message.Message>` objects that were pinned.
"""
if not self._pin_ids:
return self._pin_ids # either None or empty list
chat = await self.get_input_chat()
if chat:
self._pinned_messages = await self._client.get_messages(
self._input_chat, ids=self._pin_ids)
return self._pinned_messages
@property
def added_by(self):
"""
The user who added ``users``, if applicable (`None` otherwise).
"""
if self._added_by and not isinstance(self._added_by, types.User):
aby = self._entities.get(utils.get_peer_id(self._added_by))
if aby:
self._added_by = aby
return self._added_by
async def get_added_by(self):
"""
Returns `added_by` but will make an API call if necessary.
"""
if not self.added_by and self._added_by:
self._added_by = await self._client.get_entity(self._added_by)
return self._added_by
@property
def kicked_by(self):
"""
The user who kicked ``users``, if applicable (`None` otherwise).
"""
if self._kicked_by and not isinstance(self._kicked_by, types.User):
kby = self._entities.get(utils.get_peer_id(self._kicked_by))
if kby:
self._kicked_by = kby
return self._kicked_by
async def get_kicked_by(self):
"""
Returns `kicked_by` but will make an API call if necessary.
"""
if not self.kicked_by and self._kicked_by:
self._kicked_by = await self._client.get_entity(self._kicked_by)
return self._kicked_by
@property
def user(self):
"""
The first user that takes part in this action. For example, who joined.
Might be `None` if the information can't be retrieved or
there is no user taking part.
"""
if self.users:
return self._users[0]
async def get_user(self):
"""
Returns `user` but will make an API call if necessary.
"""
if self.users or await self.get_users():
return self._users[0]
@property
def input_user(self):
"""
Input version of the ``self.user`` property.
"""
if self.input_users:
return self._input_users[0]
async def get_input_user(self):
"""
Returns `input_user` but will make an API call if necessary.
"""
if self.input_users or await self.get_input_users():
return self._input_users[0]
@property
def user_id(self):
"""
Returns the marked signed ID of the first user, if any.
"""
if self._user_ids:
return self._user_ids[0]
@property
def users(self):
"""
A list of users that take part in this action. For example, who joined.
Might be empty if the information can't be retrieved or there
are no users taking part.
"""
if not self._user_ids:
return []
if self._users is None:
self._users = [
self._entities[user_id]
for user_id in self._user_ids
if user_id in self._entities
]
return self._users
async def get_users(self):
"""
Returns `users` but will make an API call if necessary.
"""
if not self._user_ids:
return []
# Note: we access the property first so that it fills if needed
if (self.users is None or len(self._users) != len(self._user_ids)) and self.action_message:
await self.action_message._reload_message()
self._users = [
u for u in self.action_message.action_entities
if isinstance(u, (types.User, types.UserEmpty))]
return self._users
@property
def input_users(self):
"""
Input version of the ``self.users`` property.
"""
if self._input_users is None and self._user_ids:
self._input_users = []
for user_id in self._user_ids:
# First try to get it from our entities
try:
self._input_users.append(
utils.get_input_peer(self._entities[user_id]))
continue
except (KeyError, TypeError):
pass
# If missing, try from the entity cache
try:
self._input_users.append(self._client._mb_entity_cache.get(
utils.resolve_id(user_id)[0])._as_input_peer())
continue
except AttributeError:
pass
return self._input_users or []
async def get_input_users(self):
"""
Returns `input_users` but will make an API call if necessary.
"""
if not self._user_ids:
return []
# Note: we access the property first so that it fills if needed
if (self.input_users is None or len(self._input_users) != len(self._user_ids)) and self.action_message:
self._input_users = [
utils.get_input_peer(u)
for u in self.action_message.action_entities
if isinstance(u, (types.User, types.UserEmpty))]
return self._input_users or []
@property
def user_ids(self):
"""
Returns the marked signed ID of the users, if any.
"""
if self._user_ids:
return self._user_ids[:]
|
class Event(EventCommon):
'''
Represents the event of a new chat action.
Members:
action_message (`MessageAction <https://tl.telethon.dev/types/message_action.html>`_):
The message invoked by this Chat Action.
new_pin (`bool`):
`True` if there is a new pin.
new_photo (`bool`):
`True` if there's a new chat photo (or it was removed).
photo (:tl:`Photo`, optional):
The new photo (or `None` if it was removed).
user_added (`bool`):
`True` if the user was added by some other.
user_joined (`bool`):
`True` if the user joined on their own.
user_left (`bool`):
`True` if the user left on their own.
user_kicked (`bool`):
`True` if the user was kicked by some other.
created (`bool`, optional):
`True` if this chat was just created.
new_title (`str`, optional):
The new title string for the chat, if applicable.
new_score (`str`, optional):
The new score string for the game, if applicable.
unpin (`bool`):
`True` if the existing pin gets unpinned.
'''
def __init__(self, where, new_photo=None,
added_by=None, kicked_by=None, created=None,
users=None, new_title=None, pin_ids=None, pin=None, new_score=None):
pass
def _set_client(self, client):
pass
async def respond(self, *args, **kwargs):
'''
Responds to the chat action message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
'''
pass
async def reply(self, *args, **kwargs):
'''
Replies to the chat action message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
both ``entity`` and ``reply_to`` already set.
Has the same effect as `respond` if there is no message.
'''
pass
async def delete(self, *args, **kwargs):
'''
Deletes the chat action message. You're responsible for checking
whether you have the permission to do so, or to except the error
otherwise. Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
Does nothing if no message action triggered this event.
'''
pass
async def get_pinned_message(self):
'''
If ``new_pin`` is `True`, this returns the `Message
<telethon.tl.custom.message.Message>` object that was pinned.
'''
pass
async def get_pinned_messages(self):
'''
If ``new_pin`` is `True`, this returns a `list` of `Message
<telethon.tl.custom.message.Message>` objects that were pinned.
'''
pass
@property
def added_by(self):
'''
The user who added ``users``, if applicable (`None` otherwise).
'''
pass
async def get_added_by(self):
'''
Returns `added_by` but will make an API call if necessary.
'''
pass
@property
def kicked_by(self):
'''
The user who kicked ``users``, if applicable (`None` otherwise).
'''
pass
async def get_kicked_by(self):
'''
Returns `kicked_by` but will make an API call if necessary.
'''
pass
@property
def user(self):
'''
The first user that takes part in this action. For example, who joined.
Might be `None` if the information can't be retrieved or
there is no user taking part.
'''
pass
async def get_user(self):
'''
Returns `user` but will make an API call if necessary.
'''
pass
@property
def input_user(self):
'''
Input version of the ``self.user`` property.
'''
pass
async def get_input_user(self):
'''
Returns `input_user` but will make an API call if necessary.
'''
pass
@property
def user_id(self):
'''
Returns the marked signed ID of the first user, if any.
'''
pass
@property
def users(self):
'''
A list of users that take part in this action. For example, who joined.
Might be empty if the information can't be retrieved or there
are no users taking part.
'''
pass
async def get_users(self):
'''
Returns `users` but will make an API call if necessary.
'''
pass
@property
def input_users(self):
'''
Input version of the ``self.users`` property.
'''
pass
async def get_input_users(self):
'''
Returns `input_users` but will make an API call if necessary.
'''
pass
@property
def user_ids(self):
'''
Returns the marked signed ID of the users, if any.
'''
pass
| 30 | 20 | 13 | 1 | 7 | 4 | 3 | 0.67 | 1 | 6 | 0 | 0 | 21 | 20 | 21 | 57 | 337 | 63 | 165 | 54 | 133 | 110 | 132 | 41 | 110 | 10 | 6 | 3 | 59 |
146,800 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/callbackquery.py
|
telethon.events.callbackquery.CallbackQuery.Event
|
class Event(EventCommon, SenderGetter):
"""
Represents the event of a new callback query.
Members:
query (:tl:`UpdateBotCallbackQuery`):
The original :tl:`UpdateBotCallbackQuery`.
data_match (`obj`, optional):
The object returned by the ``data=`` parameter
when creating the event builder, if any. Similar
to ``pattern_match`` for the new message event.
pattern_match (`obj`, optional):
Alias for ``data_match``.
"""
def __init__(self, query, peer, msg_id):
super().__init__(peer, msg_id=msg_id)
SenderGetter.__init__(self, query.user_id)
self.query = query
self.data_match = None
self.pattern_match = None
self._message = None
self._answered = False
def _set_client(self, client):
super()._set_client(client)
self._sender, self._input_sender = utils._get_entity_pair(
self.sender_id, self._entities, client._mb_entity_cache)
@property
def id(self):
"""
Returns the query ID. The user clicking the inline
button is the one who generated this random ID.
"""
return self.query.query_id
@property
def message_id(self):
"""
Returns the message ID to which the clicked inline button belongs.
"""
return self._message_id
@property
def data(self):
"""
Returns the data payload from the original inline button.
"""
return self.query.data
@property
def chat_instance(self):
"""
Unique identifier for the chat where the callback occurred.
Useful for high scores in games.
"""
return self.query.chat_instance
async def get_message(self):
"""
Returns the message to which the clicked inline button belongs.
"""
if self._message is not None:
return self._message
try:
chat = await self.get_input_chat() if self.is_channel else None
self._message = await self._client.get_messages(
chat, ids=self._message_id)
except ValueError:
return
return self._message
async def _refetch_sender(self):
self._sender = self._entities.get(self.sender_id)
if not self._sender:
return
self._input_sender = utils.get_input_peer(self._chat)
if not getattr(self._input_sender, 'access_hash', True):
# getattr with True to handle the InputPeerSelf() case
try:
self._input_sender = self._client._mb_entity_cache.get(
utils.resolve_id(self._sender_id)[0])._as_input_peer()
except AttributeError:
m = await self.get_message()
if m:
self._sender = m._sender
self._input_sender = m._input_sender
async def answer(
self, message=None, cache_time=0, *, url=None, alert=False):
"""
Answers the callback query (and stops the loading circle).
Args:
message (`str`, optional):
The toast message to show feedback to the user.
cache_time (`int`, optional):
For how long this result should be cached on
the user's client. Defaults to 0 for no cache.
url (`str`, optional):
The URL to be opened in the user's client. Note that
the only valid URLs are those of games your bot has,
or alternatively a 't.me/your_bot?start=xyz' parameter.
alert (`bool`, optional):
Whether an alert (a pop-up dialog) should be used
instead of showing a toast. Defaults to `False`.
"""
if self._answered:
return
self._answered = True
return await self._client(
functions.messages.SetBotCallbackAnswerRequest(
query_id=self.query.query_id,
cache_time=cache_time,
alert=alert,
message=message,
url=url
)
)
@property
def via_inline(self):
"""
Whether this callback was generated from an inline button sent
via an inline query or not. If the bot sent the message itself
with buttons, and one of those is clicked, this will be `False`.
If a user sent the message coming from an inline query to the
bot, and one of those is clicked, this will be `True`.
If it's `True`, it's likely that the bot is **not** in the
chat, so methods like `respond` or `delete` won't work (but
`edit` will always work).
"""
return isinstance(self.query, types.UpdateInlineBotCallbackQuery)
async def respond(self, *args, **kwargs):
"""
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
"""
self._client.loop.create_task(self.answer())
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def reply(self, *args, **kwargs):
"""
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
both ``entity`` and ``reply_to`` already set.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
"""
self._client.loop.create_task(self.answer())
kwargs['reply_to'] = self.query.msg_id
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def edit(self, *args, **kwargs):
"""
Edits the message. Shorthand for
`telethon.client.messages.MessageMethods.edit_message` with
the ``entity`` set to the correct :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64`.
Returns `True` if the edit was successful.
This method also creates a task to `answer` the callback.
.. note::
This method won't respect the previous message unlike
`Message.edit <telethon.tl.custom.message.Message.edit>`,
since the message object is normally not present.
"""
self._client.loop.create_task(self.answer())
if isinstance(self.query.msg_id, (types.InputBotInlineMessageID, types.InputBotInlineMessageID64)):
return await self._client.edit_message(
self.query.msg_id, *args, **kwargs
)
else:
return await self._client.edit_message(
await self.get_input_chat(), self.query.msg_id,
*args, **kwargs
)
async def delete(self, *args, **kwargs):
"""
Deletes the message. Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
If you need to delete more than one message at once, don't use
this `delete` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
"""
self._client.loop.create_task(self.answer())
if isinstance(self.query.msg_id, (types.InputBotInlineMessageID, types.InputBotInlineMessageID64)):
raise TypeError(
'Inline messages cannot be deleted as there is no API request available to do so')
return await self._client.delete_messages(
await self.get_input_chat(), [self.query.msg_id],
*args, **kwargs
)
|
class Event(EventCommon, SenderGetter):
'''
Represents the event of a new callback query.
Members:
query (:tl:`UpdateBotCallbackQuery`):
The original :tl:`UpdateBotCallbackQuery`.
data_match (`obj`, optional):
The object returned by the ``data=`` parameter
when creating the event builder, if any. Similar
to ``pattern_match`` for the new message event.
pattern_match (`obj`, optional):
Alias for ``data_match``.
'''
def __init__(self, query, peer, msg_id):
pass
def _set_client(self, client):
pass
@property
def id(self):
'''
Returns the query ID. The user clicking the inline
button is the one who generated this random ID.
'''
pass
@property
def message_id(self):
'''
Returns the message ID to which the clicked inline button belongs.
'''
pass
@property
def data(self):
'''
Returns the data payload from the original inline button.
'''
pass
@property
def chat_instance(self):
'''
Unique identifier for the chat where the callback occurred.
Useful for high scores in games.
'''
pass
async def get_message(self):
'''
Returns the message to which the clicked inline button belongs.
'''
pass
async def _refetch_sender(self):
pass
async def answer(
self, message=None, cache_time=0, *, url=None, alert=False):
'''
Answers the callback query (and stops the loading circle).
Args:
message (`str`, optional):
The toast message to show feedback to the user.
cache_time (`int`, optional):
For how long this result should be cached on
the user's client. Defaults to 0 for no cache.
url (`str`, optional):
The URL to be opened in the user's client. Note that
the only valid URLs are those of games your bot has,
or alternatively a 't.me/your_bot?start=xyz' parameter.
alert (`bool`, optional):
Whether an alert (a pop-up dialog) should be used
instead of showing a toast. Defaults to `False`.
'''
pass
@property
def via_inline(self):
'''
Whether this callback was generated from an inline button sent
via an inline query or not. If the bot sent the message itself
with buttons, and one of those is clicked, this will be `False`.
If a user sent the message coming from an inline query to the
bot, and one of those is clicked, this will be `True`.
If it's `True`, it's likely that the bot is **not** in the
chat, so methods like `respond` or `delete` won't work (but
`edit` will always work).
'''
pass
async def respond(self, *args, **kwargs):
'''
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
'''
pass
async def reply(self, *args, **kwargs):
'''
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message` with
both ``entity`` and ``reply_to`` already set.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
'''
pass
async def edit(self, *args, **kwargs):
'''
Edits the message. Shorthand for
`telethon.client.messages.MessageMethods.edit_message` with
the ``entity`` set to the correct :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64`.
Returns `True` if the edit was successful.
This method also creates a task to `answer` the callback.
.. note::
This method won't respect the previous message unlike
`Message.edit <telethon.tl.custom.message.Message.edit>`,
since the message object is normally not present.
'''
pass
async def delete(self, *args, **kwargs):
'''
Deletes the message. Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
If you need to delete more than one message at once, don't use
this `delete` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
This method also creates a task to `answer` the callback.
This method will likely fail if `via_inline` is `True`.
'''
pass
| 20 | 12 | 13 | 1 | 6 | 6 | 2 | 0.97 | 2 | 4 | 0 | 0 | 14 | 7 | 14 | 57 | 221 | 36 | 94 | 29 | 73 | 91 | 66 | 23 | 51 | 5 | 6 | 3 | 24 |
146,801 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/crypto/libssl.py
|
telethon.crypto.libssl.AES_KEY
|
class AES_KEY(ctypes.Structure):
"""Helper class representing an AES key"""
_fields_ = [
('rd_key', ctypes.c_uint32 * (4 * (AES_MAXNR + 1))),
('rounds', ctypes.c_uint),
]
|
class AES_KEY(ctypes.Structure):
'''Helper class representing an AES key'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0 | 5 | 2 | 4 | 1 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
146,802 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/client/telegrambaseclient.py
|
telethon.client.telegrambaseclient.TelegramBaseClient.__init__._Loggers
|
class _Loggers(dict):
def __missing__(self, key):
if key.startswith("telethon."):
key = key.split('.', maxsplit=1)[1]
return base_logger.getChild(key)
|
class _Loggers(dict):
def __missing__(self, key):
pass
| 2 | 0 | 5 | 1 | 4 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 28 | 6 | 1 | 5 | 2 | 3 | 0 | 5 | 2 | 3 | 2 | 2 | 1 | 2 |
146,803 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/sessions/string.py
|
telethon.sessions.string.StringSession
|
class StringSession(MemorySession):
"""
This session file can be easily saved and loaded as a string. According
to the initial design, it contains only the data that is necessary for
successful connection and authentication, so takeout ID is not stored.
It is thought to be used where you don't want to create any on-disk
files but would still like to be able to save and load existing sessions
by other means.
You can use custom `encode` and `decode` functions, if present:
* `encode` definition must be ``def encode(value: bytes) -> str:``.
* `decode` definition must be ``def decode(value: str) -> bytes:``.
"""
def __init__(self, string: str = None):
super().__init__()
if string:
if string[0] != CURRENT_VERSION:
raise ValueError('Not a valid string')
string = string[1:]
ip_len = 4 if len(string) == 352 else 16
self._dc_id, ip, self._port, key = struct.unpack(
_STRUCT_PREFORMAT.format(ip_len), StringSession.decode(string))
self._server_address = ipaddress.ip_address(ip).compressed
if any(key):
self._auth_key = AuthKey(key)
@staticmethod
def encode(x: bytes) -> str:
return base64.urlsafe_b64encode(x).decode('ascii')
@staticmethod
def decode(x: str) -> bytes:
return base64.urlsafe_b64decode(x)
def save(self: Session):
if not self.auth_key:
return ''
ip = ipaddress.ip_address(self.server_address).packed
return CURRENT_VERSION + StringSession.encode(struct.pack(
_STRUCT_PREFORMAT.format(len(ip)),
self.dc_id,
ip,
self.port,
self.auth_key.key
))
|
class StringSession(MemorySession):
'''
This session file can be easily saved and loaded as a string. According
to the initial design, it contains only the data that is necessary for
successful connection and authentication, so takeout ID is not stored.
It is thought to be used where you don't want to create any on-disk
files but would still like to be able to save and load existing sessions
by other means.
You can use custom `encode` and `decode` functions, if present:
* `encode` definition must be ``def encode(value: bytes) -> str:``.
* `decode` definition must be ``def decode(value: str) -> bytes:``.
'''
def __init__(self, string: str = None):
pass
@staticmethod
def encode(x: bytes) -> str:
pass
@staticmethod
def decode(x: str) -> bytes:
pass
def save(self: Session):
pass
| 7 | 1 | 8 | 1 | 7 | 0 | 2 | 0.37 | 1 | 4 | 0 | 0 | 2 | 4 | 4 | 71 | 50 | 9 | 30 | 12 | 23 | 11 | 21 | 10 | 16 | 5 | 6 | 2 | 9 |
146,804 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/draft.py
|
telethon.tl.custom.draft.Draft
|
class Draft:
"""
Custom class that encapsulates a draft on the Telegram servers, providing
an abstraction to change the message conveniently. The library will return
instances of this class when calling :meth:`get_drafts()`.
Args:
date (`datetime`):
The date of the draft.
link_preview (`bool`):
Whether the link preview is enabled or not.
reply_to_msg_id (`int`):
The message ID that the draft will reply to.
"""
def __init__(self, client, entity, draft):
self._client = client
self._peer = get_peer(entity)
self._entity = entity
self._input_entity = get_input_peer(entity) if entity else None
if not draft or not isinstance(draft, DraftMessage):
draft = DraftMessage('', None, None, None, None)
self._text = markdown.unparse(draft.message, draft.entities)
self._raw_text = draft.message
self.date = draft.date
self.link_preview = not draft.no_webpage
self.reply_to_msg_id = draft.reply_to.reply_to_msg_id if isinstance(draft.reply_to, types.InputReplyToMessage) else None
@property
def entity(self):
"""
The entity that belongs to this dialog (user, chat or channel).
"""
return self._entity
@property
def input_entity(self):
"""
Input version of the entity.
"""
if not self._input_entity:
try:
self._input_entity = self._client._mb_entity_cache.get(
get_peer_id(self._peer, add_mark=False))._as_input_peer()
except AttributeError:
pass
return self._input_entity
async def get_entity(self):
"""
Returns `entity` but will make an API call if necessary.
"""
if not self.entity and await self.get_input_entity():
try:
self._entity =\
await self._client.get_entity(self._input_entity)
except ValueError:
pass
return self._entity
async def get_input_entity(self):
"""
Returns `input_entity` but will make an API call if necessary.
"""
# We don't actually have an API call we can make yet
# to get more info, but keep this method for consistency.
return self.input_entity
@property
def text(self):
"""
The markdown text contained in the draft. It will be
empty if there is no text (and hence no draft is set).
"""
return self._text
@property
def raw_text(self):
"""
The raw (text without formatting) contained in the draft.
It will be empty if there is no text (thus draft not set).
"""
return self._raw_text
@property
def is_empty(self):
"""
Convenience bool to determine if the draft is empty or not.
"""
return not self._text
async def set_message(
self, text=None, reply_to=0, parse_mode=(),
link_preview=None):
"""
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if left as None.
:param int reply_to: Message ID to reply to.
Preserved if left as 0, erased if set to None.
:param bool link_preview: Whether to attach a web page preview.
Preserved if left as None.
:param str parse_mode: The parse mode to be used for the text.
:return bool: `True` on success.
"""
if text is None:
text = self._text
if reply_to == 0:
reply_to = self.reply_to_msg_id
if link_preview is None:
link_preview = self.link_preview
raw_text, entities =\
await self._client._parse_message_text(text, parse_mode)
result = await self._client(SaveDraftRequest(
peer=self._peer,
message=raw_text,
no_webpage=not link_preview,
reply_to=None if reply_to is None else types.InputReplyToMessage(reply_to),
entities=entities
))
if result:
self._text = text
self._raw_text = raw_text
self.link_preview = link_preview
self.reply_to_msg_id = reply_to
self.date = datetime.datetime.now(tz=datetime.timezone.utc)
return result
async def send(self, clear=True, parse_mode=()):
"""
Sends the contents of this draft to the dialog. This is just a
wrapper around ``send_message(dialog.input_entity, *args, **kwargs)``.
"""
await self._client.send_message(
self._peer, self.text, reply_to=self.reply_to_msg_id,
link_preview=self.link_preview, parse_mode=parse_mode,
clear_draft=clear
)
async def delete(self):
"""
Deletes this draft, and returns `True` on success.
"""
return await self.set_message(text='')
def to_dict(self):
try:
entity = self.entity
except RPCError as e:
entity = e
return {
'_': 'Draft',
'text': self.text,
'entity': entity,
'date': self.date,
'link_preview': self.link_preview,
'reply_to_msg_id': self.reply_to_msg_id
}
def __str__(self):
return TLObject.pretty_format(self.to_dict())
def stringify(self):
return TLObject.pretty_format(self.to_dict(), indent=0)
|
class Draft:
'''
Custom class that encapsulates a draft on the Telegram servers, providing
an abstraction to change the message conveniently. The library will return
instances of this class when calling :meth:`get_drafts()`.
Args:
date (`datetime`):
The date of the draft.
link_preview (`bool`):
Whether the link preview is enabled or not.
reply_to_msg_id (`int`):
The message ID that the draft will reply to.
'''
def __init__(self, client, entity, draft):
pass
@property
def entity(self):
'''
The entity that belongs to this dialog (user, chat or channel).
'''
pass
@property
def input_entity(self):
'''
Input version of the entity.
'''
pass
async def get_entity(self):
'''
Returns `entity` but will make an API call if necessary.
'''
pass
async def get_input_entity(self):
'''
Returns `input_entity` but will make an API call if necessary.
'''
pass
@property
def text(self):
'''
The markdown text contained in the draft. It will be
empty if there is no text (and hence no draft is set).
'''
pass
@property
def raw_text(self):
'''
The raw (text without formatting) contained in the draft.
It will be empty if there is no text (thus draft not set).
'''
pass
@property
def is_empty(self):
'''
Convenience bool to determine if the draft is empty or not.
'''
pass
async def set_message(
self, text=None, reply_to=0, parse_mode=(),
link_preview=None):
'''
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if left as None.
:param int reply_to: Message ID to reply to.
Preserved if left as 0, erased if set to None.
:param bool link_preview: Whether to attach a web page preview.
Preserved if left as None.
:param str parse_mode: The parse mode to be used for the text.
:return bool: `True` on success.
'''
pass
async def send(self, clear=True, parse_mode=()):
'''
Sends the contents of this draft to the dialog. This is just a
wrapper around ``send_message(dialog.input_entity, *args, **kwargs)``.
'''
pass
async def delete(self):
'''
Deletes this draft, and returns `True` on success.
'''
pass
def to_dict(self):
pass
def __str__(self):
pass
def stringify(self):
pass
| 20 | 11 | 11 | 1 | 6 | 3 | 2 | 0.6 | 0 | 5 | 1 | 0 | 14 | 9 | 14 | 14 | 181 | 31 | 94 | 35 | 72 | 56 | 67 | 27 | 52 | 6 | 0 | 2 | 27 |
146,805 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/file.py
|
telethon.tl.custom.file.File
|
class File:
"""
Convenience class over media like photos or documents, which
supports accessing the attributes in a more convenient way.
If any of the attributes are not present in the current media,
the properties will be `None`.
The original media is available through the ``media`` attribute.
"""
def __init__(self, media):
self.media = media
@property
def id(self):
"""
The old bot-API style ``file_id`` representing this file.
.. warning::
This feature has not been maintained for a long time and
may not work. It will be removed in future versions.
.. note::
This file ID may not work under user accounts,
but should still be usable by bot accounts.
You can, however, still use it to identify
a file in for example a database.
"""
return utils.pack_bot_file_id(self.media)
@property
def name(self):
"""
The file name of this document.
"""
return self._from_attr(types.DocumentAttributeFilename, 'file_name')
@property
def ext(self):
"""
The extension from the mime type of this file.
If the mime type is unknown, the extension
from the file name (if any) will be used.
"""
return (
mimetypes.guess_extension(self.mime_type)
or os.path.splitext(self.name or '')[-1]
or None
)
@property
def mime_type(self):
"""
The mime-type of this file.
"""
if isinstance(self.media, types.Photo):
return 'image/jpeg'
elif isinstance(self.media, types.Document):
return self.media.mime_type
@property
def width(self):
"""
The width in pixels of this media if it's a photo or a video.
"""
if isinstance(self.media, types.Photo):
return max(getattr(s, 'w', 0) for s in self.media.sizes)
return self._from_attr((
types.DocumentAttributeImageSize, types.DocumentAttributeVideo), 'w')
@property
def height(self):
"""
The height in pixels of this media if it's a photo or a video.
"""
if isinstance(self.media, types.Photo):
return max(getattr(s, 'h', 0) for s in self.media.sizes)
return self._from_attr((
types.DocumentAttributeImageSize, types.DocumentAttributeVideo), 'h')
@property
def duration(self):
"""
The duration in seconds of the audio or video.
"""
return self._from_attr((
types.DocumentAttributeAudio, types.DocumentAttributeVideo), 'duration')
@property
def title(self):
"""
The title of the song.
"""
return self._from_attr(types.DocumentAttributeAudio, 'title')
@property
def performer(self):
"""
The performer of the song.
"""
return self._from_attr(types.DocumentAttributeAudio, 'performer')
@property
def emoji(self):
"""
A string with all emoji that represent the current sticker.
"""
return self._from_attr(types.DocumentAttributeSticker, 'alt')
@property
def sticker_set(self):
"""
The :tl:`InputStickerSet` to which the sticker file belongs.
"""
return self._from_attr(types.DocumentAttributeSticker, 'stickerset')
@property
def size(self):
"""
The size in bytes of this file.
For photos, this is the heaviest thumbnail, as it often repressents the largest dimensions.
"""
if isinstance(self.media, types.Photo):
return max(filter(None, map(utils._photo_size_byte_count, self.media.sizes)), default=None)
elif isinstance(self.media, types.Document):
return self.media.size
def _from_attr(self, cls, field):
if isinstance(self.media, types.Document):
for attr in self.media.attributes:
if isinstance(attr, cls):
return getattr(attr, field, None)
|
class File:
'''
Convenience class over media like photos or documents, which
supports accessing the attributes in a more convenient way.
If any of the attributes are not present in the current media,
the properties will be `None`.
The original media is available through the ``media`` attribute.
'''
def __init__(self, media):
pass
@property
def id(self):
'''
The old bot-API style ``file_id`` representing this file.
.. warning::
This feature has not been maintained for a long time and
may not work. It will be removed in future versions.
.. note::
This file ID may not work under user accounts,
but should still be usable by bot accounts.
You can, however, still use it to identify
a file in for example a database.
'''
pass
@property
def name(self):
'''
The file name of this document.
'''
pass
@property
def ext(self):
'''
The extension from the mime type of this file.
If the mime type is unknown, the extension
from the file name (if any) will be used.
'''
pass
@property
def mime_type(self):
'''
The mime-type of this file.
'''
pass
@property
def width(self):
'''
The width in pixels of this media if it's a photo or a video.
'''
pass
@property
def height(self):
'''
The height in pixels of this media if it's a photo or a video.
'''
pass
@property
def duration(self):
'''
The duration in seconds of the audio or video.
'''
pass
@property
def title(self):
'''
The title of the song.
'''
pass
@property
def performer(self):
'''
The performer of the song.
'''
pass
@property
def emoji(self):
'''
A string with all emoji that represent the current sticker.
'''
pass
@property
def sticker_set(self):
'''
The :tl:`InputStickerSet` to which the sticker file belongs.
'''
pass
@property
def size(self):
'''
The size in bytes of this file.
For photos, this is the heaviest thumbnail, as it often repressents the largest dimensions.
'''
pass
def _from_attr(self, cls, field):
pass
| 27 | 13 | 7 | 1 | 3 | 3 | 2 | 0.89 | 0 | 2 | 0 | 0 | 14 | 1 | 14 | 14 | 139 | 24 | 61 | 29 | 34 | 54 | 40 | 17 | 25 | 4 | 0 | 3 | 23 |
146,806 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/forward.py
|
telethon.tl.custom.forward.Forward
|
class Forward(ChatGetter, SenderGetter):
"""
Custom class that encapsulates a :tl:`MessageFwdHeader` providing an
abstraction to easily access information like the original sender.
Remember that this class implements `ChatGetter
<telethon.tl.custom.chatgetter.ChatGetter>` and `SenderGetter
<telethon.tl.custom.sendergetter.SenderGetter>` which means you
have access to all their sender and chat properties and methods.
Attributes:
original_fwd (:tl:`MessageFwdHeader`):
The original :tl:`MessageFwdHeader` instance.
Any other attribute:
Attributes not described here are the same as those available
in the original :tl:`MessageFwdHeader`.
"""
def __init__(self, client, original, entities):
# Copy all the fields, not reference! It would cause memory cycles:
# self.original_fwd.original_fwd.original_fwd.original_fwd
# ...would be valid if we referenced.
self.__dict__.update(original.__dict__)
self.original_fwd = original
sender_id = sender = input_sender = peer = chat = input_chat = None
if original.from_id:
ty = helpers._entity_type(original.from_id)
if ty == helpers._EntityType.USER:
sender_id = utils.get_peer_id(original.from_id)
sender, input_sender = utils._get_entity_pair(
sender_id, entities, client._mb_entity_cache)
elif ty in (helpers._EntityType.CHAT, helpers._EntityType.CHANNEL):
peer = original.from_id
chat, input_chat = utils._get_entity_pair(
utils.get_peer_id(peer), entities, client._mb_entity_cache)
# This call resets the client
ChatGetter.__init__(self, peer, chat=chat, input_chat=input_chat)
SenderGetter.__init__(self, sender_id, sender=sender, input_sender=input_sender)
self._client = client
|
class Forward(ChatGetter, SenderGetter):
'''
Custom class that encapsulates a :tl:`MessageFwdHeader` providing an
abstraction to easily access information like the original sender.
Remember that this class implements `ChatGetter
<telethon.tl.custom.chatgetter.ChatGetter>` and `SenderGetter
<telethon.tl.custom.sendergetter.SenderGetter>` which means you
have access to all their sender and chat properties and methods.
Attributes:
original_fwd (:tl:`MessageFwdHeader`):
The original :tl:`MessageFwdHeader` instance.
Any other attribute:
Attributes not described here are the same as those available
in the original :tl:`MessageFwdHeader`.
'''
def __init__(self, client, original, entities):
pass
| 2 | 1 | 24 | 3 | 17 | 4 | 4 | 1 | 2 | 1 | 1 | 0 | 1 | 2 | 1 | 38 | 43 | 7 | 18 | 6 | 16 | 18 | 15 | 6 | 13 | 4 | 5 | 2 | 4 |
146,807 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/docswriter.py
|
telethon_generator.docswriter.DocsWriter
|
class DocsWriter:
"""
Utility class used to write the HTML files used on the documentation.
"""
def __init__(self, filename, type_to_path):
"""
Initializes the writer to the specified output file,
creating the parent directories when used if required.
"""
self.filename = filename
self._parent = str(self.filename.parent)
self.handle = None
self.title = ''
# Should be set before calling adding items to the menu
self.menu_separator_tag = None
# Utility functions
self.type_to_path = lambda t: self._rel(type_to_path(t))
# Control signals
self.menu_began = False
self.table_columns = 0
self.table_columns_left = None
self.write_copy_script = False
self._script = ''
def _rel(self, path):
"""
Get the relative path for the given path from the current
file by working around https://bugs.python.org/issue20012.
"""
return os.path.relpath(
str(path), self._parent).replace(os.path.sep, '/')
# High level writing
def write_head(self, title, css_path, default_css):
"""Writes the head part for the generated document,
with the given title and CSS
"""
self.title = title
self.write(
'''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link id="style" href="{rel_css}/docs.dark.css" rel="stylesheet">
<script>
document.getElementById("style").href = "{rel_css}/docs."
+ (localStorage.getItem("theme") || "{def_css}")
+ ".css";
</script>
<link href="https://fonts.googleapis.com/css?family=Nunito|Source+Code+Pro"
rel="stylesheet">
</head>
<body>
<div id="main_div">''',
title=title,
rel_css=self._rel(css_path),
def_css=default_css
)
def set_menu_separator(self, img):
"""Sets the menu separator.
Must be called before adding entries to the menu
"""
if img:
self.menu_separator_tag = '<img src="{}" alt="/" />'.format(
self._rel(img))
else:
self.menu_separator_tag = None
def add_menu(self, name, link=None):
"""Adds a menu entry, will create it if it doesn't exist yet"""
if self.menu_began:
if self.menu_separator_tag:
self.write(self.menu_separator_tag)
else:
# First time, create the menu tag
self.write('<ul class="horizontal">')
self.menu_began = True
self.write('<li>')
if link:
self.write('<a href="{}">', self._rel(link))
# Write the real menu entry text
self.write(name)
if link:
self.write('</a>')
self.write('</li>')
def end_menu(self):
"""Ends an opened menu"""
if not self.menu_began:
raise RuntimeError('No menu had been started in the first place.')
self.write('</ul>')
def write_title(self, title, level=1, id=None):
"""Writes a title header in the document body,
with an optional depth level
"""
if id:
self.write('<h{lv} id="{id}">{title}</h{lv}>',
title=title, lv=level, id=id)
else:
self.write('<h{lv}>{title}</h{lv}>',
title=title, lv=level)
def write_code(self, tlobject):
"""Writes the code for the given 'tlobject' properly
formatted with hyperlinks
"""
self.write('<pre>---{}---\n',
'functions' if tlobject.is_function else 'types')
# Write the function or type and its ID
if tlobject.namespace:
self.write(tlobject.namespace)
self.write('.')
self.write('{}#{:08x}', tlobject.name, tlobject.id)
# Write all the arguments (or do nothing if there's none)
for arg in tlobject.args:
self.write(' ')
add_link = not arg.generic_definition and not arg.is_generic
# "Opening" modifiers
if arg.generic_definition:
self.write('{')
# Argument name
self.write(arg.name)
self.write(':')
# "Opening" modifiers
if arg.flag:
self.write('{}.{}?', arg.flag, arg.flag_index)
if arg.is_generic:
self.write('!')
if arg.is_vector:
self.write('<a href="{}">Vector</a><',
self.type_to_path('vector'))
# Argument type
if arg.type:
if add_link:
self.write('<a href="{}">', self.type_to_path(arg.type))
self.write(arg.type)
if add_link:
self.write('</a>')
else:
self.write('#')
# "Closing" modifiers
if arg.is_vector:
self.write('>')
if arg.generic_definition:
self.write('}')
# Now write the resulting type (result from a function/type)
self.write(' = ')
generic_name = next((arg.name for arg in tlobject.args
if arg.generic_definition), None)
if tlobject.result == generic_name:
# Generic results cannot have any link
self.write(tlobject.result)
else:
if re.search('^vector<', tlobject.result, re.IGNORECASE):
# Notice that we don't simply make up the "Vector" part,
# because some requests (as of now, only FutureSalts),
# use a lower type name for it (see #81)
vector, inner = tlobject.result.split('<')
inner = inner.strip('>')
self.write('<a href="{}">{}</a><',
self.type_to_path(vector), vector)
self.write('<a href="{}">{}</a>>',
self.type_to_path(inner), inner)
else:
self.write('<a href="{}">{}</a>',
self.type_to_path(tlobject.result), tlobject.result)
self.write('</pre>')
def begin_table(self, column_count):
"""Begins a table with the given 'column_count', required to automatically
create the right amount of columns when adding items to the rows"""
self.table_columns = column_count
self.table_columns_left = 0
self.write('<table>')
def add_row(self, text, link=None, bold=False, align=None):
"""This will create a new row, or add text to the next column
of the previously created, incomplete row, closing it if complete"""
if not self.table_columns_left:
# Starting a new row
self.write('<tr>')
self.table_columns_left = self.table_columns
self.write('<td')
if align:
self.write(' style="text-align:{}"', align)
self.write('>')
if bold:
self.write('<b>')
if link:
self.write('<a href="{}">', self._rel(link))
# Finally write the real table data, the given text
self.write(text)
if link:
self.write('</a>')
if bold:
self.write('</b>')
self.write('</td>')
self.table_columns_left -= 1
if not self.table_columns_left:
self.write('</tr>')
def end_table(self):
# If there was any column left, finish it before closing the table
if self.table_columns_left:
self.write('</tr>')
self.write('</table>')
def write_text(self, text):
"""Writes a paragraph of text"""
self.write('<p>{}</p>', text)
def write_copy_button(self, text, text_to_copy):
"""Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked."""
self.write_copy_script = True
self.write('<button onclick="cp(\'{}\');">{}</button>'
.format(text_to_copy, text))
def add_script(self, src='', path=None):
if path:
self._script += '<script src="{}"></script>'.format(
self._rel(path))
elif src:
self._script += '<script>{}</script>'.format(src)
def end_body(self):
"""Ends the whole document. This should be called the last"""
if self.write_copy_script:
self.write(
'<textarea id="c" class="invisible"></textarea>'
'<script>'
'function cp(t){'
'var c=document.getElementById("c");'
'c.value=t;'
'c.select();'
'try{document.execCommand("copy")}'
'catch(e){}}'
'</script>'
)
self.write('</div>{}</body></html>', self._script)
# "Low" level writing
def write(self, s, *args, **kwargs):
"""Wrapper around handle.write"""
if args or kwargs:
self.handle.write(s.format(*args, **kwargs))
else:
self.handle.write(s)
# With block
def __enter__(self):
# Sanity check
self.filename.parent.mkdir(parents=True, exist_ok=True)
self.handle = self.filename.open('w', encoding='utf-8')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.handle.close()
|
class DocsWriter:
'''
Utility class used to write the HTML files used on the documentation.
'''
def __init__(self, filename, type_to_path):
'''
Initializes the writer to the specified output file,
creating the parent directories when used if required.
'''
pass
def _rel(self, path):
'''
Get the relative path for the given path from the current
file by working around https://bugs.python.org/issue20012.
'''
pass
def write_head(self, title, css_path, default_css):
'''Writes the head part for the generated document,
with the given title and CSS
'''
pass
def set_menu_separator(self, img):
'''Sets the menu separator.
Must be called before adding entries to the menu
'''
pass
def add_menu(self, name, link=None):
'''Adds a menu entry, will create it if it doesn't exist yet'''
pass
def end_menu(self):
'''Ends an opened menu'''
pass
def write_title(self, title, level=1, id=None):
'''Writes a title header in the document body,
with an optional depth level
'''
pass
def write_code(self, tlobject):
'''Writes the code for the given 'tlobject' properly
formatted with hyperlinks
'''
pass
def begin_table(self, column_count):
'''Begins a table with the given 'column_count', required to automatically
create the right amount of columns when adding items to the rows'''
pass
def add_row(self, text, link=None, bold=False, align=None):
'''This will create a new row, or add text to the next column
of the previously created, incomplete row, closing it if complete'''
pass
def end_table(self):
pass
def write_text(self, text):
'''Writes a paragraph of text'''
pass
def write_copy_button(self, text, text_to_copy):
'''Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked.'''
pass
def add_script(self, src='', path=None):
pass
def end_body(self):
'''Ends the whole document. This should be called the last'''
pass
def write_head(self, title, css_path, default_css):
'''Wrapper around handle.write'''
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 19 | 15 | 15 | 2 | 10 | 3 | 3 | 0.32 | 0 | 2 | 0 | 0 | 18 | 11 | 18 | 18 | 291 | 46 | 187 | 34 | 168 | 60 | 136 | 34 | 117 | 15 | 0 | 3 | 51 |
146,808 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/utils.py
|
telethon.utils.AsyncClassWrapper
|
class AsyncClassWrapper:
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, item):
w = getattr(self.wrapped, item)
async def wrapper(*args, **kwargs):
val = w(*args, **kwargs)
return await val if inspect.isawaitable(val) else val
if callable(w):
return wrapper
else:
return w
|
class AsyncClassWrapper:
def __init__(self, wrapped):
pass
def __getattr__(self, item):
pass
async def wrapper(*args, **kwargs):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 14 | 2 | 12 | 7 | 8 | 0 | 11 | 7 | 7 | 2 | 0 | 1 | 5 |
146,809 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/tlobject.py
|
telethon.tl.tlobject.TLRequest
|
class TLRequest(TLObject):
"""
Represents a content-related `TLObject` (a request that can be sent).
"""
@staticmethod
def read_result(reader):
return reader.tgread_object()
async def resolve(self, client, utils):
pass
|
class TLRequest(TLObject):
'''
Represents a content-related `TLObject` (a request that can be sent).
'''
@staticmethod
def read_result(reader):
pass
async def resolve(self, client, utils):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.5 | 1 | 0 | 0 | 1 | 1 | 0 | 2 | 14 | 10 | 1 | 6 | 4 | 2 | 3 | 5 | 3 | 2 | 1 | 1 | 0 | 2 |
146,810 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/patched/__init__.py
|
telethon.tl.patched.MessageService
|
class MessageService(_Message, types.MessageService):
pass
|
class MessageService(_Message, types.MessageService):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 90 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
146,811 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/patched/__init__.py
|
telethon.tl.patched.MessageEmpty
|
class MessageEmpty(_Message, types.MessageEmpty):
pass
|
class MessageEmpty(_Message, types.MessageEmpty):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 90 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
146,812 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/patched/__init__.py
|
telethon.tl.patched.Message
|
class Message(_Message, types.Message):
pass
|
class Message(_Message, types.Message):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 90 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
146,813 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/qrlogin.py
|
telethon.tl.custom.qrlogin.QRLogin
|
class QRLogin:
"""
QR login information.
Most of the time, you will present the `url` as a QR code to the user,
and while it's being shown, call `wait`.
"""
def __init__(self, client, ignored_ids):
self._client = client
self._request = functions.auth.ExportLoginTokenRequest(
self._client.api_id, self._client.api_hash, ignored_ids)
self._resp = None
async def recreate(self):
"""
Generates a new token and URL for a new QR code, useful if the code
has expired before it was imported.
"""
self._resp = await self._client(self._request)
@property
def token(self) -> bytes:
"""
The binary data representing the token.
It can be used by a previously-authorized client in a call to
:tl:`auth.importLoginToken` to log the client that originally
requested the QR login.
"""
return self._resp.token
@property
def url(self) -> str:
"""
The ``tg://login`` URI with the token. When opened by a Telegram
application where the user is logged in, it will import the login
token.
If you want to display a QR code to the user, this is the URL that
should be launched when the QR code is scanned (the URL that should
be contained in the QR code image you generate).
Whether you generate the QR code image or not is up to you, and the
library can't do this for you due to the vast ways of generating and
displaying the QR code that exist.
The URL simply consists of `token` base64-encoded.
"""
return 'tg://login?token={}'.format(base64.urlsafe_b64encode(self._resp.token).decode('utf-8').rstrip('='))
@property
def expires(self) -> datetime.datetime:
"""
The `datetime` at which the QR code will expire.
If you want to try again, you will need to call `recreate`.
"""
return self._resp.expires
async def wait(self, timeout: float = None):
"""
Waits for the token to be imported by a previously-authorized client,
either by scanning the QR, launching the URL directly, or calling the
import method.
This method **must** be called before the QR code is scanned, and
must be executing while the QR code is being scanned. Otherwise, the
login will not complete.
Will raise `asyncio.TimeoutError` if the login doesn't complete on
time.
Arguments
timeout (float):
The timeout, in seconds, to wait before giving up. By default
the library will wait until the token expires, which is often
what you want.
Returns
On success, an instance of :tl:`User`. On failure it will raise.
"""
if timeout is None:
timeout = (self._resp.expires - datetime.datetime.now(tz=datetime.timezone.utc)).total_seconds()
event = asyncio.Event()
async def handler(_update):
event.set()
self._client.add_event_handler(handler, events.Raw(types.UpdateLoginToken))
try:
# Will raise timeout error if it doesn't complete quick enough,
# which we want to let propagate
await asyncio.wait_for(event.wait(), timeout=timeout)
finally:
self._client.remove_event_handler(handler)
# We got here without it raising timeout error, so we can proceed
resp = await self._client(self._request)
if isinstance(resp, types.auth.LoginTokenMigrateTo):
await self._client._switch_dc(resp.dc_id)
resp = await self._client(functions.auth.ImportLoginTokenRequest(resp.token))
# resp should now be auth.loginTokenSuccess
if isinstance(resp, types.auth.LoginTokenSuccess):
user = resp.authorization.user
await self._client._on_login(user)
return user
raise TypeError('Login token response was unexpected: {}'.format(resp))
|
class QRLogin:
'''
QR login information.
Most of the time, you will present the `url` as a QR code to the user,
and while it's being shown, call `wait`.
'''
def __init__(self, client, ignored_ids):
pass
async def recreate(self):
'''
Generates a new token and URL for a new QR code, useful if the code
has expired before it was imported.
'''
pass
@property
def token(self) -> bytes:
'''
The binary data representing the token.
It can be used by a previously-authorized client in a call to
:tl:`auth.importLoginToken` to log the client that originally
requested the QR login.
'''
pass
@property
def url(self) -> str:
'''
The ``tg://login`` URI with the token. When opened by a Telegram
application where the user is logged in, it will import the login
token.
If you want to display a QR code to the user, this is the URL that
should be launched when the QR code is scanned (the URL that should
be contained in the QR code image you generate).
Whether you generate the QR code image or not is up to you, and the
library can't do this for you due to the vast ways of generating and
displaying the QR code that exist.
The URL simply consists of `token` base64-encoded.
'''
pass
@property
def expires(self) -> datetime.datetime:
'''
The `datetime` at which the QR code will expire.
If you want to try again, you will need to call `recreate`.
'''
pass
async def wait(self, timeout: float = None):
'''
Waits for the token to be imported by a previously-authorized client,
either by scanning the QR, launching the URL directly, or calling the
import method.
This method **must** be called before the QR code is scanned, and
must be executing while the QR code is being scanned. Otherwise, the
login will not complete.
Will raise `asyncio.TimeoutError` if the login doesn't complete on
time.
Arguments
timeout (float):
The timeout, in seconds, to wait before giving up. By default
the library will wait until the token expires, which is often
what you want.
Returns
On success, an instance of :tl:`User`. On failure it will raise.
'''
pass
async def handler(_update):
pass
| 11 | 6 | 14 | 2 | 5 | 7 | 1 | 1.41 | 0 | 7 | 1 | 0 | 6 | 3 | 6 | 6 | 111 | 22 | 37 | 17 | 26 | 52 | 32 | 14 | 24 | 4 | 0 | 1 | 10 |
146,814 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/participantpermissions.py
|
telethon.tl.custom.participantpermissions.ParticipantPermissions
|
class ParticipantPermissions:
"""
Participant permissions information.
The properties in this objects are boolean values indicating whether the
user has the permission or not.
Example
.. code-block:: python
permissions = ...
if permissions.is_banned:
"this user is banned"
elif permissions.is_admin:
"this user is an administrator"
"""
def __init__(self, participant, chat: bool):
self.participant = participant
self.is_chat = chat
@property
def is_admin(self):
"""
Whether the user is an administrator of the chat or not. The creator
also counts as begin an administrator, since they have all permissions.
"""
return self.is_creator or isinstance(self.participant, (
types.ChannelParticipantAdmin,
types.ChatParticipantAdmin
))
@property
def is_creator(self):
"""
Whether the user is the creator of the chat or not.
"""
return isinstance(self.participant, (
types.ChannelParticipantCreator,
types.ChatParticipantCreator
))
@property
def has_default_permissions(self):
"""
Whether the user is a normal user of the chat (not administrator, but
not banned either, and has no restrictions applied).
"""
return isinstance(self.participant, (
types.ChannelParticipant,
types.ChatParticipant,
types.ChannelParticipantSelf
))
@property
def is_banned(self):
"""
Whether the user is banned in the chat.
"""
return isinstance(self.participant, types.ChannelParticipantBanned)
@property
def has_left(self):
"""
Whether the user left the chat.
"""
return isinstance(self.participant, types.ChannelParticipantLeft)
@property
def add_admins(self):
"""
Whether the administrator can add new administrators with the same or
less permissions than them.
"""
if not self.is_admin:
return False
if self.is_chat:
return self.is_creator
return self.participant.admin_rights.add_admins
ban_users = property(**_admin_prop('ban_users', """
Whether the administrator can ban other users or not.
"""))
pin_messages = property(**_admin_prop('pin_messages', """
Whether the administrator can pin messages or not.
"""))
invite_users = property(**_admin_prop('invite_users', """
Whether the administrator can add new users to the chat.
"""))
delete_messages = property(**_admin_prop('delete_messages', """
Whether the administrator can delete messages from other participants.
"""))
edit_messages = property(**_admin_prop('edit_messages', """
Whether the administrator can edit messages.
"""))
post_messages = property(**_admin_prop('post_messages', """
Whether the administrator can post messages in the broadcast channel.
"""))
change_info = property(**_admin_prop('change_info', """
Whether the administrator can change the information about the chat,
such as title or description.
"""))
anonymous = property(**_admin_prop('anonymous', """
Whether the administrator will remain anonymous when sending messages.
"""))
manage_call = property(**_admin_prop('manage_call', """
Whether the user will be able to manage group calls.
"""))
|
class ParticipantPermissions:
'''
Participant permissions information.
The properties in this objects are boolean values indicating whether the
user has the permission or not.
Example
.. code-block:: python
permissions = ...
if permissions.is_banned:
"this user is banned"
elif permissions.is_admin:
"this user is an administrator"
'''
def __init__(self, participant, chat: bool):
pass
@property
def is_admin(self):
'''
Whether the user is an administrator of the chat or not. The creator
also counts as begin an administrator, since they have all permissions.
'''
pass
@property
def is_creator(self):
'''
Whether the user is the creator of the chat or not.
'''
pass
@property
def has_default_permissions(self):
'''
Whether the user is a normal user of the chat (not administrator, but
not banned either, and has no restrictions applied).
'''
pass
@property
def is_banned(self):
'''
Whether the user is banned in the chat.
'''
pass
@property
def has_left(self):
'''
Whether the user left the chat.
'''
pass
@property
def add_admins(self):
'''
Whether the administrator can add new administrators with the same or
less permissions than them.
'''
pass
| 14 | 7 | 7 | 0 | 4 | 3 | 1 | 0.52 | 0 | 1 | 0 | 0 | 7 | 2 | 7 | 7 | 118 | 21 | 64 | 25 | 50 | 33 | 29 | 19 | 21 | 3 | 0 | 1 | 9 |
146,815 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/messagebutton.py
|
telethon.tl.custom.messagebutton.MessageButton
|
class MessageButton:
"""
.. note::
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
are instances of this type. If you want to **define** a reply
markup for e.g. sending messages, refer to `Button
<telethon.tl.custom.button.Button>` instead.
Custom class that encapsulates a message button providing
an abstraction to easily access some commonly needed features
(such as clicking the button itself).
Attributes:
button (:tl:`KeyboardButton`):
The original :tl:`KeyboardButton` object.
"""
def __init__(self, client, original, chat, bot, msg_id):
self.button = original
self._bot = bot
self._chat = chat
self._msg_id = msg_id
self._client = client
@property
def client(self):
"""
Returns the `telethon.client.telegramclient.TelegramClient`
instance that created this instance.
"""
return self._client
@property
def text(self):
"""The text string of the button."""
return self.button.text
@property
def data(self):
"""The `bytes` data for :tl:`KeyboardButtonCallback` objects."""
if isinstance(self.button, types.KeyboardButtonCallback):
return self.button.data
@property
def inline_query(self):
"""The query `str` for :tl:`KeyboardButtonSwitchInline` objects."""
if isinstance(self.button, types.KeyboardButtonSwitchInline):
return self.button.query
@property
def url(self):
"""The url `str` for :tl:`KeyboardButtonUrl` objects."""
if isinstance(self.button, types.KeyboardButtonUrl):
return self.button.url
async def click(self, share_phone=None, share_geo=None, *, password=None):
"""
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `Message <telethon.tl.custom.message.Message>` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
it will be "clicked" and the :tl:`BotCallbackAnswer` returned.
If it's an inline :tl:`KeyboardButtonSwitchInline` button, the
:tl:`StartBotRequest` will be invoked and the resulting updates
returned.
If it's a :tl:`KeyboardButtonUrl`, the URL of the button will
be passed to ``webbrowser.open`` and return `True` on success.
If it's a :tl:`KeyboardButtonRequestPhone`, you must indicate that you
want to ``share_phone=True`` in order to share it. Sharing it is not a
default because it is a privacy concern and could happen accidentally.
You may also use ``share_phone=phone`` to share a specific number, in
which case either `str` or :tl:`InputMediaContact` should be used.
If it's a :tl:`KeyboardButtonRequestGeoLocation`, you must pass a
tuple in ``share_geo=(longitude, latitude)``. Note that Telegram seems
to have some heuristics to determine impossible locations, so changing
this value a lot quickly may not work as expected. You may also pass a
:tl:`InputGeoPoint` if you find the order confusing.
"""
if isinstance(self.button, types.KeyboardButton):
return await self._client.send_message(
self._chat, self.button.text, parse_mode=None)
elif isinstance(self.button, types.KeyboardButtonCallback):
if password is not None:
pwd = await self._client(functions.account.GetPasswordRequest())
password = pwd_mod.compute_check(pwd, password)
req = functions.messages.GetBotCallbackAnswerRequest(
peer=self._chat, msg_id=self._msg_id, data=self.button.data,
password=password
)
try:
return await self._client(req)
except BotResponseTimeoutError:
return None
elif isinstance(self.button, types.KeyboardButtonSwitchInline):
return await self._client(functions.messages.StartBotRequest(
bot=self._bot, peer=self._chat, start_param=self.button.query
))
elif isinstance(self.button, types.KeyboardButtonUrl):
if "webbrowser" in sys.modules:
return webbrowser.open(self.button.url)
elif isinstance(self.button, types.KeyboardButtonGame):
req = functions.messages.GetBotCallbackAnswerRequest(
peer=self._chat, msg_id=self._msg_id, game=True
)
try:
return await self._client(req)
except BotResponseTimeoutError:
return None
elif isinstance(self.button, types.KeyboardButtonRequestPhone):
if not share_phone:
raise ValueError('cannot click on phone buttons unless share_phone=True')
if share_phone == True or isinstance(share_phone, str):
me = await self._client.get_me()
share_phone = types.InputMediaContact(
phone_number=me.phone if share_phone == True else share_phone,
first_name=me.first_name or '',
last_name=me.last_name or '',
vcard=''
)
return await self._client.send_file(self._chat, share_phone)
elif isinstance(self.button, types.KeyboardButtonRequestGeoLocation):
if not share_geo:
raise ValueError('cannot click on geo buttons unless share_geo=(longitude, latitude)')
if isinstance(share_geo, (tuple, list)):
long, lat = share_geo
share_geo = types.InputMediaGeoPoint(types.InputGeoPoint(lat=lat, long=long))
return await self._client.send_file(self._chat, share_geo)
|
class MessageButton:
'''
.. note::
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
are instances of this type. If you want to **define** a reply
markup for e.g. sending messages, refer to `Button
<telethon.tl.custom.button.Button>` instead.
Custom class that encapsulates a message button providing
an abstraction to easily access some commonly needed features
(such as clicking the button itself).
Attributes:
button (:tl:`KeyboardButton`):
The original :tl:`KeyboardButton` object.
'''
def __init__(self, client, original, chat, bot, msg_id):
pass
@property
def client(self):
'''
Returns the `telethon.client.telegramclient.TelegramClient`
instance that created this instance.
'''
pass
@property
def text(self):
'''The text string of the button.'''
pass
@property
def data(self):
'''The `bytes` data for :tl:`KeyboardButtonCallback` objects.'''
pass
@property
def inline_query(self):
'''The query `str` for :tl:`KeyboardButtonSwitchInline` objects.'''
pass
@property
def url(self):
'''The url `str` for :tl:`KeyboardButtonUrl` objects.'''
pass
async def click(self, share_phone=None, share_geo=None, *, password=None):
'''
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `Message <telethon.tl.custom.message.Message>` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
it will be "clicked" and the :tl:`BotCallbackAnswer` returned.
If it's an inline :tl:`KeyboardButtonSwitchInline` button, the
:tl:`StartBotRequest` will be invoked and the resulting updates
returned.
If it's a :tl:`KeyboardButtonUrl`, the URL of the button will
be passed to ``webbrowser.open`` and return `True` on success.
If it's a :tl:`KeyboardButtonRequestPhone`, you must indicate that you
want to ``share_phone=True`` in order to share it. Sharing it is not a
default because it is a privacy concern and could happen accidentally.
You may also use ``share_phone=phone`` to share a specific number, in
which case either `str` or :tl:`InputMediaContact` should be used.
If it's a :tl:`KeyboardButtonRequestGeoLocation`, you must pass a
tuple in ``share_geo=(longitude, latitude)``. Note that Telegram seems
to have some heuristics to determine impossible locations, so changing
this value a lot quickly may not work as expected. You may also pass a
:tl:`InputGeoPoint` if you find the order confusing.
'''
pass
| 13 | 7 | 16 | 2 | 10 | 4 | 4 | 0.57 | 0 | 4 | 0 | 0 | 7 | 5 | 7 | 7 | 140 | 22 | 75 | 22 | 62 | 43 | 51 | 17 | 43 | 17 | 0 | 2 | 26 |
146,816 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/message.py
|
telethon.tl.custom.message.Message
|
class Message(ChatGetter, SenderGetter, TLObject):
"""
This custom class aggregates both :tl:`Message` and
:tl:`MessageService` to ease accessing their members.
Remember that this class implements `ChatGetter
<telethon.tl.custom.chatgetter.ChatGetter>` and `SenderGetter
<telethon.tl.custom.sendergetter.SenderGetter>` which means you
have access to all their sender and chat properties and methods.
Members:
out (`bool`):
Whether the message is outgoing (i.e. you sent it from
another session) or incoming (i.e. someone else sent it).
Note that messages in your own chat are always incoming,
but this member will be `True` if you send a message
to your own chat. Messages you forward to your chat are
*not* considered outgoing, just like official clients
display them.
mentioned (`bool`):
Whether you were mentioned in this message or not.
Note that replies to your own messages also count
as mentions.
media_unread (`bool`):
Whether you have read the media in this message
or not, e.g. listened to the voice note media.
silent (`bool`):
Whether the message should notify people with sound or not.
Previously used in channels, but since 9 August 2019, it can
also be `used in private chats
<https://telegram.org/blog/silent-messages-slow-mode>`_.
post (`bool`):
Whether this message is a post in a broadcast
channel or not.
from_scheduled (`bool`):
Whether this message was originated from a previously-scheduled
message or not.
legacy (`bool`):
Whether this is a legacy message or not.
edit_hide (`bool`):
Whether the edited mark of this message is edited
should be hidden (e.g. in GUI clients) or shown.
pinned (`bool`):
Whether this message is currently pinned or not.
noforwards (`bool`):
Whether this message can be forwarded or not.
invert_media (`bool`):
Whether the media in this message should be inverted.
offline (`bool`):
Whether the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.
id (`int`):
The ID of this message. This field is *always* present.
Any other member is optional and may be `None`.
from_id (:tl:`Peer`):
The peer who sent this message, which is either
:tl:`PeerUser`, :tl:`PeerChat` or :tl:`PeerChannel`.
This value will be `None` for anonymous messages.
peer_id (:tl:`Peer`):
The peer to which this message was sent, which is either
:tl:`PeerUser`, :tl:`PeerChat` or :tl:`PeerChannel`. This
will always be present except for empty messages.
fwd_from (:tl:`MessageFwdHeader`):
The original forward header if this message is a forward.
You should probably use the `forward` property instead.
via_bot_id (`int`):
The ID of the bot used to send this message
through its inline mode (e.g. "via @like").
reply_to (:tl:`MessageReplyHeader`):
The original reply header if this message is replying to another.
date (`datetime`):
The UTC+0 `datetime` object indicating when this message
was sent. This will always be present except for empty
messages.
message (`str`):
The string text of the message for `Message
<telethon.tl.custom.message.Message>` instances,
which will be `None` for other types of messages.
media (:tl:`MessageMedia`):
The media sent with this message if any (such as
photos, videos, documents, gifs, stickers, etc.).
You may want to access the `photo`, `document`
etc. properties instead.
If the media was not present or it was :tl:`MessageMediaEmpty`,
this member will instead be `None` for convenience.
reply_markup (:tl:`ReplyMarkup`):
The reply markup for this message (which was sent
either via a bot or by a bot). You probably want
to access `buttons` instead.
entities (List[:tl:`MessageEntity`]):
The list of markup entities in this message,
such as bold, italics, code, hyperlinks, etc.
views (`int`):
The number of views this message from a broadcast
channel has. This is also present in forwards.
forwards (`int`):
The number of times this message has been forwarded.
replies (`int`):
The number of times another message has replied to this message.
edit_date (`datetime`):
The date when this message was last edited.
post_author (`str`):
The display name of the message sender to
show in messages sent to broadcast channels.
grouped_id (`int`):
If this message belongs to a group of messages
(photo albums or video albums), all of them will
have the same value here.
reactions (:tl:`MessageReactions`)
Reactions to this message.
restriction_reason (List[:tl:`RestrictionReason`])
An optional list of reasons why this message was restricted.
If the list is `None`, this message has not been restricted.
ttl_period (`int`):
The Time To Live period configured for this message.
The message should be erased from wherever it's stored (memory, a
local database, etc.) when
``datetime.now() > message.date + timedelta(seconds=message.ttl_period)``.
action (:tl:`MessageAction`):
The message action object of the message for :tl:`MessageService`
instances, which will be `None` for other types of messages.
saved_peer_id (:tl:`Peer`)
"""
# region Initialization
def __init__(
self,
id: int, peer_id: types.TypePeer,
date: Optional[datetime]=None, message: Optional[str]=None,
# Copied from Message.__init__ signature
out: Optional[bool]=None, mentioned: Optional[bool]=None, media_unread: Optional[bool]=None, silent: Optional[bool]=None, post: Optional[bool]=None, from_scheduled: Optional[bool]=None, legacy: Optional[bool]=None, edit_hide: Optional[bool]=None, pinned: Optional[bool]=None, noforwards: Optional[bool]=None, invert_media: Optional[bool]=None, offline: Optional[bool]=None, video_processing_pending: Optional[bool]=None, from_id: Optional[types.TypePeer]=None, from_boosts_applied: Optional[int]=None, saved_peer_id: Optional[types.TypePeer]=None, fwd_from: Optional[types.TypeMessageFwdHeader]=None, via_bot_id: Optional[int]=None, via_business_bot_id: Optional[int]=None, reply_to: Optional[types.TypeMessageReplyHeader]=None, media: Optional[types.TypeMessageMedia]=None, reply_markup: Optional[types.TypeReplyMarkup]=None, entities: Optional[List[types.TypeMessageEntity]]=None, views: Optional[int]=None, forwards: Optional[int]=None, replies: Optional[types.TypeMessageReplies]=None, edit_date: Optional[datetime]=None, post_author: Optional[str]=None, grouped_id: Optional[int]=None, reactions: Optional[types.TypeMessageReactions]=None, restriction_reason: Optional[List[types.TypeRestrictionReason]]=None, ttl_period: Optional[int]=None, quick_reply_shortcut_id: Optional[int]=None, effect: Optional[int]=None, factcheck: Optional[types.TypeFactCheck]=None, report_delivery_until_date: Optional[datetime]=None,
# Copied from MessageService.__init__ signature
action: Optional[types.TypeMessageAction]=None, reactions_are_possible: Optional[bool]=None
):
# Copied from Message.__init__ body
self.id = id
self.peer_id = peer_id
self.date = date
self.message = message
self.out = bool(out)
self.mentioned = mentioned
self.media_unread = media_unread
self.silent = silent
self.post = post
self.from_scheduled = from_scheduled
self.legacy = legacy
self.edit_hide = edit_hide
self.pinned = pinned
self.noforwards = noforwards
self.invert_media = invert_media
self.offline = offline
self.video_processing_pending = video_processing_pending
self.from_id = from_id
self.from_boosts_applied = from_boosts_applied
self.saved_peer_id = saved_peer_id
self.fwd_from = fwd_from
self.via_bot_id = via_bot_id
self.via_business_bot_id = via_business_bot_id
self.reply_to = reply_to
self.media = None if isinstance(media, types.MessageMediaEmpty) else media
self.reply_markup = reply_markup
self.entities = entities
self.views = views
self.forwards = forwards
self.replies = replies
self.edit_date = edit_date
self.post_author = post_author
self.grouped_id = grouped_id
self.reactions = reactions
self.restriction_reason = restriction_reason
self.ttl_period = ttl_period
self.quick_reply_shortcut_id = quick_reply_shortcut_id
self.effect = effect
self.factcheck = factcheck
self.report_delivery_until_date = report_delivery_until_date
# Copied from MessageService.__init__ body
self.action = action
self.reactions_are_possible = reactions_are_possible
# Convenient storage for custom functions
# TODO This is becoming a bit of bloat
self._client = None
self._text = None
self._file = None
self._reply_message = None
self._buttons = None
self._buttons_flat = None
self._buttons_count = None
self._via_bot = None
self._via_input_bot = None
self._action_entities = None
self._linked_chat = None
sender_id = None
if from_id is not None:
sender_id = utils.get_peer_id(from_id)
elif peer_id:
# If the message comes from a Channel, let the sender be it
# ...or...
# incoming messages in private conversations no longer have from_id
# (layer 119+), but the sender can only be the chat we're in.
if post or (not out and isinstance(peer_id, types.PeerUser)):
sender_id = utils.get_peer_id(peer_id)
# Note that these calls would reset the client
ChatGetter.__init__(self, peer_id, broadcast=post)
SenderGetter.__init__(self, sender_id)
self._forward = None
self._reply_to_chat = None
self._reply_to_sender = None
def _finish_init(self, client, entities, input_chat):
"""
Finishes the initialization of this message by setting
the client that sent the message and making use of the
known entities.
"""
self._client = client
# Make messages sent to ourselves outgoing unless they're forwarded.
# This makes it consistent with official client's appearance.
if self.peer_id == types.PeerUser(client._self_id) and not self.fwd_from:
self.out = True
cache = client._mb_entity_cache
self._sender, self._input_sender = utils._get_entity_pair(
self.sender_id, entities, cache)
self._chat, self._input_chat = utils._get_entity_pair(
self.chat_id, entities, cache)
if input_chat: # This has priority
self._input_chat = input_chat
if self.via_bot_id:
self._via_bot, self._via_input_bot = utils._get_entity_pair(
self.via_bot_id, entities, cache)
if self.fwd_from:
self._forward = Forward(self._client, self.fwd_from, entities)
if self.action:
if isinstance(self.action, (types.MessageActionChatAddUser,
types.MessageActionChatCreate)):
self._action_entities = [entities.get(i)
for i in self.action.users]
elif isinstance(self.action, types.MessageActionChatDeleteUser):
self._action_entities = [entities.get(self.action.user_id)]
elif isinstance(self.action, types.MessageActionChatJoinedByLink):
self._action_entities = [entities.get(self.action.inviter_id)]
elif isinstance(self.action, types.MessageActionChatMigrateTo):
self._action_entities = [entities.get(utils.get_peer_id(
types.PeerChannel(self.action.channel_id)))]
elif isinstance(
self.action, types.MessageActionChannelMigrateFrom):
self._action_entities = [entities.get(utils.get_peer_id(
types.PeerChat(self.action.chat_id)))]
if self.replies and self.replies.channel_id:
self._linked_chat = entities.get(utils.get_peer_id(
types.PeerChannel(self.replies.channel_id)))
if isinstance(self.reply_to, types.MessageReplyHeader):
if self.reply_to.reply_to_peer_id:
self._reply_to_chat = entities.get(utils.get_peer_id(self.reply_to.reply_to_peer_id))
if self.reply_to.reply_from:
if self.reply_to.reply_from.from_id:
self._reply_to_sender = entities.get(utils.get_peer_id(self.reply_to.reply_from.from_id))
# endregion Initialization
# region Public Properties
@property
def client(self):
"""
Returns the `TelegramClient <telethon.client.telegramclient.TelegramClient>`
that *patched* this message. This will only be present if you
**use the friendly methods**, it won't be there if you invoke
raw API methods manually, in which case you should only access
members, not properties.
"""
return self._client
@property
def text(self):
"""
The message text, formatted using the client's default
parse mode. Will be `None` for :tl:`MessageService`.
"""
if self._text is None and self._client:
if not self._client.parse_mode:
self._text = self.message
else:
self._text = self._client.parse_mode.unparse(
self.message, self.entities)
return self._text
@text.setter
def text(self, value):
self._text = value
if self._client and self._client.parse_mode:
self.message, self.entities = self._client.parse_mode.parse(value)
else:
self.message, self.entities = value, []
@property
def raw_text(self):
"""
The raw message text, ignoring any formatting.
Will be `None` for :tl:`MessageService`.
Setting a value to this field will erase the
`entities`, unlike changing the `message` member.
"""
return self.message
@raw_text.setter
def raw_text(self, value):
self.message = value
self.entities = []
self._text = None
@property
def is_reply(self):
"""
`True` if the message is a reply to some other message.
Remember that you can access the ID of the message
this one is replying to through `reply_to.reply_to_msg_id`,
and the `Message` object with `get_reply_message()`.
"""
return self.reply_to is not None
@property
def forward(self):
"""
The `Forward <telethon.tl.custom.forward.Forward>`
information if this message is a forwarded message.
"""
return self._forward
@property
def reply_to_chat(self):
"""
The :tl:`Channel` in which the replied-to message was sent,
if this message is a reply in another chat
"""
return self._reply_to_chat
@property
def reply_to_sender(self):
"""
The :tl:`User`, :tl:`Channel`, or whatever other entity that
sent the replied-to message, if this message is a reply in another chat.
"""
return self._reply_to_sender
@property
def buttons(self):
"""
Returns a list of lists of `MessageButton
<telethon.tl.custom.messagebutton.MessageButton>`,
if any.
Otherwise, it returns `None`.
"""
if self._buttons is None and self.reply_markup:
if not self.input_chat:
return
try:
bot = self._needed_markup_bot()
except ValueError:
return
else:
self._set_buttons(self._input_chat, bot)
return self._buttons
async def get_buttons(self):
"""
Returns `buttons` when that property fails (this is rarely needed).
"""
if not self.buttons and self.reply_markup:
chat = await self.get_input_chat()
if not chat:
return
try:
bot = self._needed_markup_bot()
except ValueError:
await self._reload_message()
bot = self._needed_markup_bot() # TODO use via_input_bot
self._set_buttons(chat, bot)
return self._buttons
@property
def button_count(self):
"""
Returns the total button count (sum of all `buttons` rows).
"""
if self._buttons_count is None:
if isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
self._buttons_count = sum(
len(row.buttons) for row in self.reply_markup.rows)
else:
self._buttons_count = 0
return self._buttons_count
@property
def file(self):
"""
Returns a `File <telethon.tl.custom.file.File>` wrapping the
`photo` or `document` in this message. If the media type is different
(polls, games, none, etc.), this property will be `None`.
This instance lets you easily access other properties, such as
`file.id <telethon.tl.custom.file.File.id>`,
`file.name <telethon.tl.custom.file.File.name>`,
etc., without having to manually inspect the ``document.attributes``.
"""
if not self._file:
media = self.photo or self.document
if media:
self._file = File(media)
return self._file
@property
def photo(self):
"""
The :tl:`Photo` media in this message, if any.
This will also return the photo for :tl:`MessageService` if its
action is :tl:`MessageActionChatEditPhoto`, or if the message has
a web preview with a photo.
"""
if isinstance(self.media, types.MessageMediaPhoto):
if isinstance(self.media.photo, types.Photo):
return self.media.photo
elif isinstance(self.action, types.MessageActionChatEditPhoto):
return self.action.photo
else:
web = self.web_preview
if web and isinstance(web.photo, types.Photo):
return web.photo
@property
def document(self):
"""
The :tl:`Document` media in this message, if any.
"""
if isinstance(self.media, types.MessageMediaDocument):
if isinstance(self.media.document, types.Document):
return self.media.document
else:
web = self.web_preview
if web and isinstance(web.document, types.Document):
return web.document
@property
def web_preview(self):
"""
The :tl:`WebPage` media in this message, if any.
"""
if isinstance(self.media, types.MessageMediaWebPage):
if isinstance(self.media.webpage, types.WebPage):
return self.media.webpage
@property
def audio(self):
"""
The :tl:`Document` media in this message, if it's an audio file.
"""
return self._document_by_attribute(types.DocumentAttributeAudio,
lambda attr: not attr.voice)
@property
def voice(self):
"""
The :tl:`Document` media in this message, if it's a voice note.
"""
return self._document_by_attribute(types.DocumentAttributeAudio,
lambda attr: attr.voice)
@property
def video(self):
"""
The :tl:`Document` media in this message, if it's a video.
"""
return self._document_by_attribute(types.DocumentAttributeVideo)
@property
def video_note(self):
"""
The :tl:`Document` media in this message, if it's a video note.
"""
return self._document_by_attribute(types.DocumentAttributeVideo,
lambda attr: attr.round_message)
@property
def gif(self):
"""
The :tl:`Document` media in this message, if it's a "gif".
"Gif" files by Telegram are normally ``.mp4`` video files without
sound, the so called "animated" media. However, it may be the actual
gif format if the file is too large.
"""
return self._document_by_attribute(types.DocumentAttributeAnimated)
@property
def sticker(self):
"""
The :tl:`Document` media in this message, if it's a sticker.
"""
return self._document_by_attribute(types.DocumentAttributeSticker)
@property
def contact(self):
"""
The :tl:`MessageMediaContact` in this message, if it's a contact.
"""
if isinstance(self.media, types.MessageMediaContact):
return self.media
@property
def game(self):
"""
The :tl:`Game` media in this message, if it's a game.
"""
if isinstance(self.media, types.MessageMediaGame):
return self.media.game
@property
def geo(self):
"""
The :tl:`GeoPoint` media in this message, if it has a location.
"""
if isinstance(self.media, (types.MessageMediaGeo,
types.MessageMediaGeoLive,
types.MessageMediaVenue)):
return self.media.geo
@property
def invoice(self):
"""
The :tl:`MessageMediaInvoice` in this message, if it's an invoice.
"""
if isinstance(self.media, types.MessageMediaInvoice):
return self.media
@property
def poll(self):
"""
The :tl:`MessageMediaPoll` in this message, if it's a poll.
"""
if isinstance(self.media, types.MessageMediaPoll):
return self.media
@property
def venue(self):
"""
The :tl:`MessageMediaVenue` in this message, if it's a venue.
"""
if isinstance(self.media, types.MessageMediaVenue):
return self.media
@property
def dice(self):
"""
The :tl:`MessageMediaDice` in this message, if it's a dice roll.
"""
if isinstance(self.media, types.MessageMediaDice):
return self.media
@property
def action_entities(self):
"""
Returns a list of entities that took part in this action.
Possible cases for this are :tl:`MessageActionChatAddUser`,
:tl:`types.MessageActionChatCreate`, :tl:`MessageActionChatDeleteUser`,
:tl:`MessageActionChatJoinedByLink` :tl:`MessageActionChatMigrateTo`
and :tl:`MessageActionChannelMigrateFrom`.
If the action is neither of those, the result will be `None`.
If some entities could not be retrieved, the list may contain
some `None` items in it.
"""
return self._action_entities
@property
def via_bot(self):
"""
The bot :tl:`User` if the message was sent via said bot.
This will only be present if `via_bot_id` is not `None` and
the entity is known.
"""
return self._via_bot
@property
def via_input_bot(self):
"""
Returns the input variant of `via_bot`.
"""
return self._via_input_bot
@property
def reply_to_msg_id(self):
"""
Returns the message ID this message is replying to, if any.
This is equivalent to accessing ``.reply_to.reply_to_msg_id``.
"""
return self.reply_to.reply_to_msg_id if self.reply_to else None
@property
def to_id(self):
"""
Returns the peer to which this message was sent to. This used to exist
to infer the ``.peer_id``.
"""
# If the client wasn't set we can't emulate the behaviour correctly,
# so as a best-effort simply return the chat peer.
if self._client and not self.out and self.is_private:
return types.PeerUser(self._client._self_id)
return self.peer_id
# endregion Public Properties
# region Public Methods
def get_entities_text(self, cls=None):
"""
Returns a list of ``(markup entity, inner text)``
(like bold or italics).
The markup entity is a :tl:`MessageEntity` that represents bold,
italics, etc., and the inner text is the `str` inside that markup
entity.
For example:
.. code-block:: python
print(repr(message.text)) # shows: 'Hello **world**!'
for ent, txt in message.get_entities_text():
print(ent) # shows: MessageEntityBold(offset=6, length=5)
print(txt) # shows: world
Args:
cls (`type`):
Returns entities matching this type only. For example,
the following will print the text for all ``code`` entities:
>>> from telethon.tl.types import MessageEntityCode
>>>
>>> m = ... # get the message
>>> for _, inner_text in m.get_entities_text(MessageEntityCode):
>>> print(inner_text)
"""
ent = self.entities
if not ent:
return []
if cls:
ent = [c for c in ent if isinstance(c, cls)]
texts = utils.get_inner_text(self.message, ent)
return list(zip(ent, texts))
async def get_reply_message(self):
"""
The `Message` that this message is replying to, or `None`.
The result will be cached after its first use.
"""
if self._reply_message is None and self._client:
if not self.reply_to:
return None
# Bots cannot access other bots' messages by their ID.
# However they can access them through replies...
self._reply_message = await self._client.get_messages(
await self.get_input_chat() if self.is_channel else None,
ids=types.InputMessageReplyTo(self.id)
)
if not self._reply_message:
# ...unless the current message got deleted.
#
# If that's the case, give it a second chance accessing
# directly by its ID.
self._reply_message = await self._client.get_messages(
self._input_chat if self.is_channel else None,
ids=self.reply_to.reply_to_msg_id
)
return self._reply_message
async def respond(self, *args, **kwargs):
"""
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
"""
if self._client:
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def reply(self, *args, **kwargs):
"""
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
"""
if self._client:
kwargs['reply_to'] = self.id
return await self._client.send_message(
await self.get_input_chat(), *args, **kwargs)
async def forward_to(self, *args, **kwargs):
"""
Forwards the message. Shorthand for
`telethon.client.messages.MessageMethods.forward_messages`
with both ``messages`` and ``from_peer`` already set.
If you need to forward more than one message at once, don't use
this `forward_to` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
"""
if self._client:
kwargs['messages'] = self.id
kwargs['from_peer'] = await self.get_input_chat()
return await self._client.forward_messages(*args, **kwargs)
async def edit(self, *args, **kwargs):
"""
Edits the message if it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns
The edited `Message <telethon.tl.custom.message.Message>`,
unless `entity` was a :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64` in which
case this method returns a boolean.
Raises
``MessageAuthorRequiredError`` if you're not the author of the
message but tried editing it anyway.
``MessageNotModifiedError`` if the contents of the message were
not modified at all.
``MessageIdInvalidError`` if the ID of the message is invalid
(the ID itself may be correct, but the message with that ID
cannot be edited). For example, when trying to edit messages
with a reply markup (or clear markup) this error will be raised.
.. note::
This is different from `client.edit_message
<telethon.client.messages.MessageMethods.edit_message>`
and **will respect** the previous state of the message.
For example, if the message didn't have a link preview,
the edit won't add one by default, and you should force
it by setting it to `True` if you want it.
This is generally the most desired and convenient behaviour,
and will work for link previews and message buttons.
"""
if 'link_preview' not in kwargs:
kwargs['link_preview'] = bool(self.web_preview)
if 'buttons' not in kwargs:
kwargs['buttons'] = self.reply_markup
return await self._client.edit_message(
await self.get_input_chat(), self.id,
*args, **kwargs
)
async def delete(self, *args, **kwargs):
"""
Deletes the message. You're responsible for checking whether you
have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
If you need to delete more than one message at once, don't use
this `delete` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
"""
if self._client:
return await self._client.delete_messages(
await self.get_input_chat(), [self.id],
*args, **kwargs
)
async def download_media(self, *args, **kwargs):
"""
Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set.
"""
if self._client:
# Passing the entire message is important, in case it has to be
# refetched for a fresh file reference.
return await self._client.download_media(self, *args, **kwargs)
async def click(self, i=None, j=None,
*, text=None, filter=None, data=None, share_phone=None,
share_geo=None, password=None):
"""
Calls :tl:`SendVote` with the specified poll option
or `button.click <telethon.tl.custom.messagebutton.MessageButton.click>`
on the specified button.
Does nothing if the message is not a poll or has no buttons.
Args:
i (`int` | `list`):
Clicks the i'th button or poll option (starting from the index 0).
For multiple-choice polls, a list with the indices should be used.
Will ``raise IndexError`` if out of bounds. Example:
>>> message = ... # get the message somehow
>>> # Clicking the 3rd button
>>> # [button1] [button2]
>>> # [ button3 ]
>>> # [button4] [button5]
>>> await message.click(2) # index
j (`int`):
Clicks the button at position (i, j), these being the
indices for the (row, column) respectively. Example:
>>> # Clicking the 2nd button on the 1st row.
>>> # [button1] [button2]
>>> # [ button3 ]
>>> # [button4] [button5]
>>> await message.click(0, 1) # (row, column)
This is equivalent to ``message.buttons[0][1].click()``.
text (`str` | `callable`):
Clicks the first button or poll option with the text "text". This may
also be a callable, like a ``re.compile(...).match``,
and the text will be passed to it.
If you need to select multiple options in a poll,
pass a list of indices to the ``i`` parameter.
filter (`callable`):
Clicks the first button or poll option for which the callable
returns `True`. The callable should accept a single
`MessageButton <telethon.tl.custom.messagebutton.MessageButton>`
or `PollAnswer <telethon.tl.types.PollAnswer>` argument.
If you need to select multiple options in a poll,
pass a list of indices to the ``i`` parameter.
data (`bytes`):
This argument overrides the rest and will not search any
buttons. Instead, it will directly send the request to
behave as if it clicked a button with said data. Note
that if the message does not have this data, it will
``raise DataInvalidError``.
share_phone (`bool` | `str` | tl:`InputMediaContact`):
When clicking on a keyboard button requesting a phone number
(:tl:`KeyboardButtonRequestPhone`), this argument must be
explicitly set to avoid accidentally sharing the number.
It can be `True` to automatically share the current user's
phone, a string to share a specific phone number, or a contact
media to specify all details.
If the button is pressed without this, `ValueError` is raised.
share_geo (`tuple` | `list` | tl:`InputMediaGeoPoint`):
When clicking on a keyboard button requesting a geo location
(:tl:`KeyboardButtonRequestGeoLocation`), this argument must
be explicitly set to avoid accidentally sharing the location.
It must be a `tuple` of `float` as ``(longitude, latitude)``,
or a :tl:`InputGeoPoint` instance to avoid accidentally using
the wrong roder.
If the button is pressed without this, `ValueError` is raised.
password (`str`):
When clicking certain buttons (such as BotFather's confirmation
button to transfer ownership), if your account has 2FA enabled,
you need to provide your account's password. Otherwise,
`teltehon.errors.PasswordHashInvalidError` is raised.
Example:
.. code-block:: python
# Click the first button
await message.click(0)
# Click some row/column
await message.click(row, column)
# Click by text
await message.click(text='👍')
# Click by data
await message.click(data=b'payload')
# Click on a button requesting a phone
await message.click(0, share_phone=True)
"""
if not self._client:
return
if data:
chat = await self.get_input_chat()
if not chat:
return None
but = types.KeyboardButtonCallback('', data)
return await MessageButton(self._client, but, chat, None, self.id).click(
share_phone=share_phone, share_geo=share_geo, password=password)
if sum(int(x is not None) for x in (i, text, filter)) >= 2:
raise ValueError('You can only set either of i, text or filter')
# Finding the desired poll options and sending them
if self.poll is not None:
def find_options():
answers = self.poll.poll.answers
if i is not None:
if utils.is_list_like(i):
return [answers[idx].option for idx in i]
return [answers[i].option]
if text is not None:
if callable(text):
for answer in answers:
if text(answer.text):
return [answer.option]
else:
for answer in answers:
if answer.text == text:
return [answer.option]
return
if filter is not None:
for answer in answers:
if filter(answer):
return [answer.option]
return
options = find_options()
if options is None:
options = []
return await self._client(
functions.messages.SendVoteRequest(
peer=self._input_chat,
msg_id=self.id,
options=options
)
)
if not await self.get_buttons():
return # Accessing the property sets self._buttons[_flat]
def find_button():
nonlocal i
if text is not None:
if callable(text):
for button in self._buttons_flat:
if text(button.text):
return button
else:
for button in self._buttons_flat:
if button.text == text:
return button
return
if filter is not None:
for button in self._buttons_flat:
if filter(button):
return button
return
if i is None:
i = 0
if j is None:
return self._buttons_flat[i]
else:
return self._buttons[i][j]
button = find_button()
if button:
return await button.click(
share_phone=share_phone, share_geo=share_geo, password=password)
async def mark_read(self):
"""
Marks the message as read. Shorthand for
`client.send_read_acknowledge()
<telethon.client.messages.MessageMethods.send_read_acknowledge>`
with both ``entity`` and ``message`` already set.
"""
if self._client:
await self._client.send_read_acknowledge(
await self.get_input_chat(), max_id=self.id)
async def pin(self, *, notify=False, pm_oneside=False):
"""
Pins the message. Shorthand for
`telethon.client.messages.MessageMethods.pin_message`
with both ``entity`` and ``message`` already set.
"""
# TODO Constantly checking if client is a bit annoying,
# maybe just make it illegal to call messages from raw API?
# That or figure out a way to always set it directly.
if self._client:
return await self._client.pin_message(
await self.get_input_chat(), self.id, notify=notify, pm_oneside=pm_oneside)
async def unpin(self):
"""
Unpins the message. Shorthand for
`telethon.client.messages.MessageMethods.unpin_message`
with both ``entity`` and ``message`` already set.
"""
if self._client:
return await self._client.unpin_message(
await self.get_input_chat(), self.id)
# endregion Public Methods
# region Private Methods
async def _reload_message(self):
"""
Re-fetches this message to reload the sender and chat entities,
along with their input versions.
"""
if not self._client:
return
try:
chat = await self.get_input_chat() if self.is_channel else None
msg = await self._client.get_messages(chat, ids=self.id)
except ValueError:
return # We may not have the input chat/get message failed
if not msg:
return # The message may be deleted and it will be None
self._sender = msg._sender
self._input_sender = msg._input_sender
self._chat = msg._chat
self._input_chat = msg._input_chat
self._via_bot = msg._via_bot
self._via_input_bot = msg._via_input_bot
self._forward = msg._forward
self._action_entities = msg._action_entities
async def _refetch_sender(self):
await self._reload_message()
def _set_buttons(self, chat, bot):
"""
Helper methods to set the buttons given the input sender and chat.
"""
if self._client and isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
self._buttons = [[
MessageButton(self._client, button, chat, bot, self.id)
for button in row.buttons
] for row in self.reply_markup.rows]
self._buttons_flat = [x for row in self._buttons for x in row]
def _needed_markup_bot(self):
"""
Returns the input peer of the bot that's needed for the reply markup.
This is necessary for :tl:`KeyboardButtonSwitchInline` since we need
to know what bot we want to start. Raises ``ValueError`` if the bot
cannot be found but is needed. Returns `None` if it's not needed.
"""
if self._client and not isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
return None
for row in self.reply_markup.rows:
for button in row.buttons:
if isinstance(button, types.KeyboardButtonSwitchInline):
# no via_bot_id means the bot sent the message itself (#1619)
if button.same_peer or not self.via_bot_id:
bot = self.input_sender
if not bot:
raise ValueError('No input sender')
return bot
else:
try:
return self._client._mb_entity_cache.get(
utils.resolve_id(self.via_bot_id)[0])._as_input_peer()
except AttributeError:
raise ValueError('No input sender') from None
def _document_by_attribute(self, kind, condition=None):
"""
Helper method to return the document only if it has an attribute
that's an instance of the given kind, and passes the condition.
"""
doc = self.document
if doc:
for attr in doc.attributes:
if isinstance(attr, kind):
if not condition or condition(attr):
return doc
return None
|
class Message(ChatGetter, SenderGetter, TLObject):
'''
This custom class aggregates both :tl:`Message` and
:tl:`MessageService` to ease accessing their members.
Remember that this class implements `ChatGetter
<telethon.tl.custom.chatgetter.ChatGetter>` and `SenderGetter
<telethon.tl.custom.sendergetter.SenderGetter>` which means you
have access to all their sender and chat properties and methods.
Members:
out (`bool`):
Whether the message is outgoing (i.e. you sent it from
another session) or incoming (i.e. someone else sent it).
Note that messages in your own chat are always incoming,
but this member will be `True` if you send a message
to your own chat. Messages you forward to your chat are
*not* considered outgoing, just like official clients
display them.
mentioned (`bool`):
Whether you were mentioned in this message or not.
Note that replies to your own messages also count
as mentions.
media_unread (`bool`):
Whether you have read the media in this message
or not, e.g. listened to the voice note media.
silent (`bool`):
Whether the message should notify people with sound or not.
Previously used in channels, but since 9 August 2019, it can
also be `used in private chats
<https://telegram.org/blog/silent-messages-slow-mode>`_.
post (`bool`):
Whether this message is a post in a broadcast
channel or not.
from_scheduled (`bool`):
Whether this message was originated from a previously-scheduled
message or not.
legacy (`bool`):
Whether this is a legacy message or not.
edit_hide (`bool`):
Whether the edited mark of this message is edited
should be hidden (e.g. in GUI clients) or shown.
pinned (`bool`):
Whether this message is currently pinned or not.
noforwards (`bool`):
Whether this message can be forwarded or not.
invert_media (`bool`):
Whether the media in this message should be inverted.
offline (`bool`):
Whether the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message.
id (`int`):
The ID of this message. This field is *always* present.
Any other member is optional and may be `None`.
from_id (:tl:`Peer`):
The peer who sent this message, which is either
:tl:`PeerUser`, :tl:`PeerChat` or :tl:`PeerChannel`.
This value will be `None` for anonymous messages.
peer_id (:tl:`Peer`):
The peer to which this message was sent, which is either
:tl:`PeerUser`, :tl:`PeerChat` or :tl:`PeerChannel`. This
will always be present except for empty messages.
fwd_from (:tl:`MessageFwdHeader`):
The original forward header if this message is a forward.
You should probably use the `forward` property instead.
via_bot_id (`int`):
The ID of the bot used to send this message
through its inline mode (e.g. "via @like").
reply_to (:tl:`MessageReplyHeader`):
The original reply header if this message is replying to another.
date (`datetime`):
The UTC+0 `datetime` object indicating when this message
was sent. This will always be present except for empty
messages.
message (`str`):
The string text of the message for `Message
<telethon.tl.custom.message.Message>` instances,
which will be `None` for other types of messages.
media (:tl:`MessageMedia`):
The media sent with this message if any (such as
photos, videos, documents, gifs, stickers, etc.).
You may want to access the `photo`, `document`
etc. properties instead.
If the media was not present or it was :tl:`MessageMediaEmpty`,
this member will instead be `None` for convenience.
reply_markup (:tl:`ReplyMarkup`):
The reply markup for this message (which was sent
either via a bot or by a bot). You probably want
to access `buttons` instead.
entities (List[:tl:`MessageEntity`]):
The list of markup entities in this message,
such as bold, italics, code, hyperlinks, etc.
views (`int`):
The number of views this message from a broadcast
channel has. This is also present in forwards.
forwards (`int`):
The number of times this message has been forwarded.
replies (`int`):
The number of times another message has replied to this message.
edit_date (`datetime`):
The date when this message was last edited.
post_author (`str`):
The display name of the message sender to
show in messages sent to broadcast channels.
grouped_id (`int`):
If this message belongs to a group of messages
(photo albums or video albums), all of them will
have the same value here.
reactions (:tl:`MessageReactions`)
Reactions to this message.
restriction_reason (List[:tl:`RestrictionReason`])
An optional list of reasons why this message was restricted.
If the list is `None`, this message has not been restricted.
ttl_period (`int`):
The Time To Live period configured for this message.
The message should be erased from wherever it's stored (memory, a
local database, etc.) when
``datetime.now() > message.date + timedelta(seconds=message.ttl_period)``.
action (:tl:`MessageAction`):
The message action object of the message for :tl:`MessageService`
instances, which will be `None` for other types of messages.
saved_peer_id (:tl:`Peer`)
'''
def __init__(
self,
id: int, peer_id: types.TypePeer,
date: Optional[datetime]=None, message: Optional[str]=None,
# Copied from Message.__init__ signature
out: Optional[bool]=None, mentioned: Optional[bool]=None, media_unread: Optional[bool]=None, silent: Optional[bool]=None, post: Optional[bool]=None, from_scheduled: Optional[bool]=None, legacy: Optional[bool]=None, edit_hide: Optional[bool]=None, pinned: Optional[bool]=None, noforwards: Optional[bool]=None, invert_media: Optional[bool]=None, offline: Optional[bool]=None, video_processing_pending: Optional[bool]=None, from_id: Optional[types.TypePeer]=None, from_boosts_applied: Optional[int]=None, saved_peer_id: Optional[types.TypePeer]=None, fwd_from: Optional[types.TypeMessageFwdHeader]=None, via_bot_id: Optional[int]=None, via_business_bot_id: Optional[int]=None, reply_to: Optional[types.TypeMessageReplyHeader]=None, media: Optional[types.TypeMessageMedia]=None, reply_markup: Optional[types.TypeReplyMarkup]=None, entities: Optional[List[types.TypeMessageEntity]]=None, views: Optional[int]=None, forwards: Optional[int]=None, replies: Optional[types.TypeMessageReplies]=None, edit_date: Optional[datetime]=None, post_author: Optional[str]=None, grouped_id: Optional[int]=None, reactions: Optional[types.TypeMessageReactions]=None, restriction_reason: Optional[List[types.TypeRestrictionReason]]=None, ttl_period: Optional[int]=None, quick_reply_shortcut_id: Optional[int]=None, effect: Optional[int]=None, factcheck: Optional[types.TypeFactCheck]=None, report_delivery_until_date: Optional[datetime]=None,
# Copied from MessageService.__init__ signature
action: Optional[types.TypeMessageAction]=None, reactions_are_possible: Optional[bool]=None
):
pass
def _finish_init(self, client, entities, input_chat):
'''
Finishes the initialization of this message by setting
the client that sent the message and making use of the
known entities.
'''
pass
@property
def client(self):
'''
Returns the `TelegramClient <telethon.client.telegramclient.TelegramClient>`
that *patched* this message. This will only be present if you
**use the friendly methods**, it won't be there if you invoke
raw API methods manually, in which case you should only access
members, not properties.
'''
pass
@property
def text(self):
'''
The message text, formatted using the client's default
parse mode. Will be `None` for :tl:`MessageService`.
'''
pass
@text.setter
def text(self):
pass
@property
def raw_text(self):
'''
The raw message text, ignoring any formatting.
Will be `None` for :tl:`MessageService`.
Setting a value to this field will erase the
`entities`, unlike changing the `message` member.
'''
pass
@raw_text.setter
def raw_text(self):
pass
@property
def is_reply(self):
'''
`True` if the message is a reply to some other message.
Remember that you can access the ID of the message
this one is replying to through `reply_to.reply_to_msg_id`,
and the `Message` object with `get_reply_message()`.
'''
pass
@property
def forward(self):
'''
The `Forward <telethon.tl.custom.forward.Forward>`
information if this message is a forwarded message.
'''
pass
@property
def reply_to_chat(self):
'''
The :tl:`Channel` in which the replied-to message was sent,
if this message is a reply in another chat
'''
pass
@property
def reply_to_sender(self):
'''
The :tl:`User`, :tl:`Channel`, or whatever other entity that
sent the replied-to message, if this message is a reply in another chat.
'''
pass
@property
def buttons(self):
'''
Returns a list of lists of `MessageButton
<telethon.tl.custom.messagebutton.MessageButton>`,
if any.
Otherwise, it returns `None`.
'''
pass
async def get_buttons(self):
'''
Returns `buttons` when that property fails (this is rarely needed).
'''
pass
@property
def button_count(self):
'''
Returns the total button count (sum of all `buttons` rows).
'''
pass
@property
def file(self):
'''
Returns a `File <telethon.tl.custom.file.File>` wrapping the
`photo` or `document` in this message. If the media type is different
(polls, games, none, etc.), this property will be `None`.
This instance lets you easily access other properties, such as
`file.id <telethon.tl.custom.file.File.id>`,
`file.name <telethon.tl.custom.file.File.name>`,
etc., without having to manually inspect the ``document.attributes``.
'''
pass
@property
def photo(self):
'''
The :tl:`Photo` media in this message, if any.
This will also return the photo for :tl:`MessageService` if its
action is :tl:`MessageActionChatEditPhoto`, or if the message has
a web preview with a photo.
'''
pass
@property
def document(self):
'''
The :tl:`Document` media in this message, if any.
'''
pass
@property
def web_preview(self):
'''
The :tl:`WebPage` media in this message, if any.
'''
pass
@property
def audio(self):
'''
The :tl:`Document` media in this message, if it's an audio file.
'''
pass
@property
def voice(self):
'''
The :tl:`Document` media in this message, if it's a voice note.
'''
pass
@property
def video(self):
'''
The :tl:`Document` media in this message, if it's a video.
'''
pass
@property
def video_note(self):
'''
The :tl:`Document` media in this message, if it's a video note.
'''
pass
@property
def gif(self):
'''
The :tl:`Document` media in this message, if it's a "gif".
"Gif" files by Telegram are normally ``.mp4`` video files without
sound, the so called "animated" media. However, it may be the actual
gif format if the file is too large.
'''
pass
@property
def sticker(self):
'''
The :tl:`Document` media in this message, if it's a sticker.
'''
pass
@property
def contact(self):
'''
The :tl:`MessageMediaContact` in this message, if it's a contact.
'''
pass
@property
def game(self):
'''
The :tl:`Game` media in this message, if it's a game.
'''
pass
@property
def geo(self):
'''
The :tl:`GeoPoint` media in this message, if it has a location.
'''
pass
@property
def invoice(self):
'''
The :tl:`MessageMediaInvoice` in this message, if it's an invoice.
'''
pass
@property
def poll(self):
'''
The :tl:`MessageMediaPoll` in this message, if it's a poll.
'''
pass
@property
def venue(self):
'''
The :tl:`MessageMediaVenue` in this message, if it's a venue.
'''
pass
@property
def dice(self):
'''
The :tl:`MessageMediaDice` in this message, if it's a dice roll.
'''
pass
@property
def action_entities(self):
'''
Returns a list of entities that took part in this action.
Possible cases for this are :tl:`MessageActionChatAddUser`,
:tl:`types.MessageActionChatCreate`, :tl:`MessageActionChatDeleteUser`,
:tl:`MessageActionChatJoinedByLink` :tl:`MessageActionChatMigrateTo`
and :tl:`MessageActionChannelMigrateFrom`.
If the action is neither of those, the result will be `None`.
If some entities could not be retrieved, the list may contain
some `None` items in it.
'''
pass
@property
def via_bot(self):
'''
The bot :tl:`User` if the message was sent via said bot.
This will only be present if `via_bot_id` is not `None` and
the entity is known.
'''
pass
@property
def via_input_bot(self):
'''
Returns the input variant of `via_bot`.
'''
pass
@property
def reply_to_msg_id(self):
'''
Returns the message ID this message is replying to, if any.
This is equivalent to accessing ``.reply_to.reply_to_msg_id``.
'''
pass
@property
def to_id(self):
'''
Returns the peer to which this message was sent to. This used to exist
to infer the ``.peer_id``.
'''
pass
def get_entities_text(self, cls=None):
'''
Returns a list of ``(markup entity, inner text)``
(like bold or italics).
The markup entity is a :tl:`MessageEntity` that represents bold,
italics, etc., and the inner text is the `str` inside that markup
entity.
For example:
.. code-block:: python
print(repr(message.text)) # shows: 'Hello **world**!'
for ent, txt in message.get_entities_text():
print(ent) # shows: MessageEntityBold(offset=6, length=5)
print(txt) # shows: world
Args:
cls (`type`):
Returns entities matching this type only. For example,
the following will print the text for all ``code`` entities:
>>> from telethon.tl.types import MessageEntityCode
>>>
>>> m = ... # get the message
>>> for _, inner_text in m.get_entities_text(MessageEntityCode):
>>> print(inner_text)
'''
pass
async def get_reply_message(self):
'''
The `Message` that this message is replying to, or `None`.
The result will be cached after its first use.
'''
pass
async def respond(self, *args, **kwargs):
'''
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
'''
pass
def reply_to_chat(self):
'''
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
'''
pass
async def forward_to(self, *args, **kwargs):
'''
Forwards the message. Shorthand for
`telethon.client.messages.MessageMethods.forward_messages`
with both ``messages`` and ``from_peer`` already set.
If you need to forward more than one message at once, don't use
this `forward_to` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
'''
pass
async def edit(self, *args, **kwargs):
'''
Edits the message if it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns
The edited `Message <telethon.tl.custom.message.Message>`,
unless `entity` was a :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64` in which
case this method returns a boolean.
Raises
``MessageAuthorRequiredError`` if you're not the author of the
message but tried editing it anyway.
``MessageNotModifiedError`` if the contents of the message were
not modified at all.
``MessageIdInvalidError`` if the ID of the message is invalid
(the ID itself may be correct, but the message with that ID
cannot be edited). For example, when trying to edit messages
with a reply markup (or clear markup) this error will be raised.
.. note::
This is different from `client.edit_message
<telethon.client.messages.MessageMethods.edit_message>`
and **will respect** the previous state of the message.
For example, if the message didn't have a link preview,
the edit won't add one by default, and you should force
it by setting it to `True` if you want it.
This is generally the most desired and convenient behaviour,
and will work for link previews and message buttons.
'''
pass
async def delete(self, *args, **kwargs):
'''
Deletes the message. You're responsible for checking whether you
have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
If you need to delete more than one message at once, don't use
this `delete` method. Use a
`telethon.client.telegramclient.TelegramClient` instance directly.
'''
pass
async def download_media(self, *args, **kwargs):
'''
Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set.
'''
pass
async def click(self, i=None, j=None,
*, text=None, filter=None, data=None, share_phone=None,
share_geo=None, password=None):
'''
Calls :tl:`SendVote` with the specified poll option
or `button.click <telethon.tl.custom.messagebutton.MessageButton.click>`
on the specified button.
Does nothing if the message is not a poll or has no buttons.
Args:
i (`int` | `list`):
Clicks the i'th button or poll option (starting from the index 0).
For multiple-choice polls, a list with the indices should be used.
Will ``raise IndexError`` if out of bounds. Example:
>>> message = ... # get the message somehow
>>> # Clicking the 3rd button
>>> # [button1] [button2]
>>> # [ button3 ]
>>> # [button4] [button5]
>>> await message.click(2) # index
j (`int`):
Clicks the button at position (i, j), these being the
indices for the (row, column) respectively. Example:
>>> # Clicking the 2nd button on the 1st row.
>>> # [button1] [button2]
>>> # [ button3 ]
>>> # [button4] [button5]
>>> await message.click(0, 1) # (row, column)
This is equivalent to ``message.buttons[0][1].click()``.
text (`str` | `callable`):
Clicks the first button or poll option with the text "text". This may
also be a callable, like a ``re.compile(...).match``,
and the text will be passed to it.
If you need to select multiple options in a poll,
pass a list of indices to the ``i`` parameter.
filter (`callable`):
Clicks the first button or poll option for which the callable
returns `True`. The callable should accept a single
`MessageButton <telethon.tl.custom.messagebutton.MessageButton>`
or `PollAnswer <telethon.tl.types.PollAnswer>` argument.
If you need to select multiple options in a poll,
pass a list of indices to the ``i`` parameter.
data (`bytes`):
This argument overrides the rest and will not search any
buttons. Instead, it will directly send the request to
behave as if it clicked a button with said data. Note
that if the message does not have this data, it will
``raise DataInvalidError``.
share_phone (`bool` | `str` | tl:`InputMediaContact`):
When clicking on a keyboard button requesting a phone number
(:tl:`KeyboardButtonRequestPhone`), this argument must be
explicitly set to avoid accidentally sharing the number.
It can be `True` to automatically share the current user's
phone, a string to share a specific phone number, or a contact
media to specify all details.
If the button is pressed without this, `ValueError` is raised.
share_geo (`tuple` | `list` | tl:`InputMediaGeoPoint`):
When clicking on a keyboard button requesting a geo location
(:tl:`KeyboardButtonRequestGeoLocation`), this argument must
be explicitly set to avoid accidentally sharing the location.
It must be a `tuple` of `float` as ``(longitude, latitude)``,
or a :tl:`InputGeoPoint` instance to avoid accidentally using
the wrong roder.
If the button is pressed without this, `ValueError` is raised.
password (`str`):
When clicking certain buttons (such as BotFather's confirmation
button to transfer ownership), if your account has 2FA enabled,
you need to provide your account's password. Otherwise,
`teltehon.errors.PasswordHashInvalidError` is raised.
Example:
.. code-block:: python
# Click the first button
await message.click(0)
# Click some row/column
await message.click(row, column)
# Click by text
await message.click(text='👍')
# Click by data
await message.click(data=b'payload')
# Click on a button requesting a phone
await message.click(0, share_phone=True)
'''
pass
def find_options():
pass
def find_button():
pass
async def mark_read(self):
'''
Marks the message as read. Shorthand for
`client.send_read_acknowledge()
<telethon.client.messages.MessageMethods.send_read_acknowledge>`
with both ``entity`` and ``message`` already set.
'''
pass
async def pin(self, *, notify=False, pm_oneside=False):
'''
Pins the message. Shorthand for
`telethon.client.messages.MessageMethods.pin_message`
with both ``entity`` and ``message`` already set.
'''
pass
async def unpin(self):
'''
Unpins the message. Shorthand for
`telethon.client.messages.MessageMethods.unpin_message`
with both ``entity`` and ``message`` already set.
'''
pass
async def _reload_message(self):
'''
Re-fetches this message to reload the sender and chat entities,
along with their input versions.
'''
pass
async def _refetch_sender(self):
pass
def _set_buttons(self, chat, bot):
'''
Helper methods to set the buttons given the input sender and chat.
'''
pass
def _needed_markup_bot(self):
'''
Returns the input peer of the bot that's needed for the reply markup.
This is necessary for :tl:`KeyboardButtonSwitchInline` since we need
to know what bot we want to start. Raises ``ValueError`` if the bot
cannot be found but is needed. Returns `None` if it's not needed.
'''
pass
def _document_by_attribute(self, kind, condition=None):
'''
Helper method to return the document only if it has an attribute
that's an instance of the given kind, and passes the condition.
'''
pass
| 89 | 50 | 17 | 2 | 9 | 7 | 3 | 1.03 | 3 | 12 | 3 | 3 | 53 | 61 | 53 | 90 | 1,167 | 193 | 482 | 181 | 384 | 497 | 378 | 140 | 321 | 16 | 5 | 5 | 168 |
146,817 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/inlinebuilder.py
|
telethon.tl.custom.inlinebuilder.InlineBuilder
|
class InlineBuilder:
"""
Helper class to allow defining `InlineQuery
<telethon.events.inlinequery.InlineQuery>` ``results``.
Common arguments to all methods are
explained here to avoid repetition:
text (`str`, optional):
If present, the user will send a text
message with this text upon being clicked.
link_preview (`bool`, optional):
Whether to show a link preview in the sent
text message or not.
geo (:tl:`InputGeoPoint`, :tl:`GeoPoint`, :tl:`InputMediaVenue`, :tl:`MessageMediaVenue`, optional):
If present, it may either be a geo point or a venue.
period (int, optional):
The period in seconds to be used for geo points.
contact (:tl:`InputMediaContact`, :tl:`MessageMediaContact`, optional):
If present, it must be the contact information to send.
game (`bool`, optional):
May be `True` to indicate that the game will be sent.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`, optional):
Same as ``buttons`` for `client.send_message()
<telethon.client.messages.MessageMethods.send_message>`.
parse_mode (`str`, optional):
Same as ``parse_mode`` for `client.send_message()
<telethon.client.messageparse.MessageParseMethods.parse_mode>`.
id (`str`, optional):
The string ID to use for this result. If not present, it
will be the SHA256 hexadecimal digest of converting the
created :tl:`InputBotInlineResult` with empty ID to ``bytes()``,
so that the ID will be deterministic for the same input.
.. note::
If two inputs are exactly the same, their IDs will be the same
too. If you send two articles with the same ID, it will raise
``ResultIdDuplicateError``. Consider giving them an explicit
ID if you need to send two results that are the same.
"""
def __init__(self, client):
self._client = client
# noinspection PyIncorrectDocstring
async def article(
self, title, description=None,
*, url=None, thumb=None, content=None,
id=None, text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
"""
Creates new inline result of article type.
Args:
title (`str`):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
url (`str`, optional):
The URL to be shown for this result.
thumb (:tl:`InputWebDocument`, optional):
The thumbnail to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
content (:tl:`InputWebDocument`, optional):
The content to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
Example:
.. code-block:: python
results = [
# Option with title and description sending a message.
builder.article(
title='First option',
description='This is the first option',
text='Text sent after clicking this option',
),
# Option with title URL to be opened when clicked.
builder.article(
title='Second option',
url='https://example.com',
text='Text sent if the user clicks the option and not the URL',
),
# Sending a message with buttons.
# You can use a list or a list of lists to include more buttons.
builder.article(
title='Third option',
text='Text sent with buttons below',
buttons=Button.url('https://example.com'),
),
]
"""
# TODO Does 'article' work always?
# article, photo, gif, mpeg4_gif, video, audio,
# voice, document, location, venue, contact, game
result = types.InputBotInlineResult(
id=id or '',
type='article',
send_message=await self._message(
text=text, parse_mode=parse_mode, link_preview=link_preview,
geo=geo, period=period,
contact=contact,
game=game,
buttons=buttons
),
title=title,
description=description,
url=url,
thumb=thumb,
content=content
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
async def photo(
self, file, *, id=None, include_media=True,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
"""
Creates a new inline result of photo type.
Args:
include_media (`bool`, optional):
Whether the photo file used to display the result should be
included in the message itself or not. By default, the photo
is included, and the text parameter alters the caption.
file (`obj`, optional):
Same as ``file`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
Example:
.. code-block:: python
results = [
# Sending just the photo when the user selects it.
builder.photo('/path/to/photo.jpg'),
# Including a caption with some in-memory photo.
photo_bytesio = ...
builder.photo(
photo_bytesio,
text='This will be the caption of the sent photo',
),
# Sending just the message without including the photo.
builder.photo(
photo,
text='This will be a normal text message',
include_media=False,
),
]
"""
try:
fh = utils.get_input_photo(file)
except TypeError:
_, media, _ = await self._client._file_to_media(
file, allow_cache=True, as_image=True
)
if isinstance(media, types.InputPhoto):
fh = media
else:
r = await self._client(functions.messages.UploadMediaRequest(
types.InputPeerSelf(), media=media
))
fh = utils.get_input_photo(r.photo)
result = types.InputBotInlineResultPhoto(
id=id or '',
type='photo',
photo=fh,
send_message=await self._message(
text=text or '',
parse_mode=parse_mode,
link_preview=link_preview,
media=include_media,
geo=geo,
period=period,
contact=contact,
game=game,
buttons=buttons
)
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
async def document(
self, file, title=None, *, description=None, type=None,
mime_type=None, attributes=None, force_document=False,
voice_note=False, video_note=False, use_cache=True, id=None,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None,
include_media=True
):
"""
Creates a new inline result of document type.
`use_cache`, `mime_type`, `attributes`, `force_document`,
`voice_note` and `video_note` are described in `client.send_file
<telethon.client.uploads.UploadMethods.send_file>`.
Args:
file (`obj`):
Same as ``file`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
title (`str`, optional):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
type (`str`, optional):
The type of the document. May be one of: article, audio,
contact, file, geo, gif, photo, sticker, venue, video, voice.
It will be automatically set if ``mime_type`` is specified,
and default to ``'file'`` if no matching mime type is found.
you may need to pass ``attributes`` in order to use ``type``
effectively.
attributes (`list`, optional):
Optional attributes that override the inferred ones, like
:tl:`DocumentAttributeFilename` and so on.
include_media (`bool`, optional):
Whether the document file used to display the result should be
included in the message itself or not. By default, the document
is included, and the text parameter alters the caption.
Example:
.. code-block:: python
results = [
# Sending just the file when the user selects it.
builder.document('/path/to/file.pdf'),
# Including a caption with some in-memory file.
file_bytesio = ...
builder.document(
file_bytesio,
text='This will be the caption of the sent file',
),
# Sending just the message without including the file.
builder.document(
photo,
text='This will be a normal text message',
include_media=False,
),
]
"""
if type is None:
if voice_note:
type = 'voice'
elif mime_type:
for ty, mimes in _TYPE_TO_MIMES.items():
for mime in mimes:
if mime_type == mime:
type = ty
break
if type is None:
type = 'file'
try:
fh = utils.get_input_document(file)
except TypeError:
_, media, _ = await self._client._file_to_media(
file,
mime_type=mime_type,
attributes=attributes,
force_document=force_document,
voice_note=voice_note,
video_note=video_note,
allow_cache=use_cache
)
if isinstance(media, types.InputDocument):
fh = media
else:
r = await self._client(functions.messages.UploadMediaRequest(
types.InputPeerSelf(), media=media
))
fh = utils.get_input_document(r.document)
result = types.InputBotInlineResultDocument(
id=id or '',
type=type,
document=fh,
send_message=await self._message(
# Empty string for text if there's media but text is None.
# We may want to display a document but send text; however
# default to sending the media (without text, i.e. stickers).
text=text or '',
parse_mode=parse_mode,
link_preview=link_preview,
media=include_media,
geo=geo,
period=period,
contact=contact,
game=game,
buttons=buttons
),
title=title,
description=description
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
async def game(
self, short_name, *, id=None,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
"""
Creates a new inline result of game type.
Args:
short_name (`str`):
The short name of the game to use.
"""
result = types.InputBotInlineResultGame(
id=id or '',
short_name=short_name,
send_message=await self._message(
text=text, parse_mode=parse_mode, link_preview=link_preview,
geo=geo, period=period,
contact=contact,
game=game,
buttons=buttons
)
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
async def _message(
self, *,
text=None, parse_mode=(), link_preview=True, media=False,
geo=None, period=60, contact=None, game=False, buttons=None
):
# Empty strings are valid but false-y; if they're empty use dummy '\0'
args = ('\0' if text == '' else text, geo, contact, game)
if sum(1 for x in args if x is not None and x is not False) != 1:
raise ValueError(
'Must set exactly one of text, geo, contact or game (set {})'
.format(', '.join(x[0] for x in zip(
'text geo contact game'.split(), args) if x[1]) or 'none')
)
markup = self._client.build_reply_markup(buttons, inline_only=True)
if text is not None:
text, msg_entities = await self._client._parse_message_text(
text, parse_mode
)
if media:
# "MediaAuto" means it will use whatever media the inline
# result itself has (stickers, photos, or documents), while
# respecting the user's text (caption) and formatting.
return types.InputBotInlineMessageMediaAuto(
message=text,
entities=msg_entities,
reply_markup=markup
)
else:
return types.InputBotInlineMessageText(
message=text,
no_webpage=not link_preview,
entities=msg_entities,
reply_markup=markup
)
elif isinstance(geo, (types.InputGeoPoint, types.GeoPoint)):
return types.InputBotInlineMessageMediaGeo(
geo_point=utils.get_input_geo(geo),
period=period,
reply_markup=markup
)
elif isinstance(geo, (types.InputMediaVenue, types.MessageMediaVenue)):
if isinstance(geo, types.InputMediaVenue):
geo_point = geo.geo_point
else:
geo_point = geo.geo
return types.InputBotInlineMessageMediaVenue(
geo_point=geo_point,
title=geo.title,
address=geo.address,
provider=geo.provider,
venue_id=geo.venue_id,
venue_type=geo.venue_type,
reply_markup=markup
)
elif isinstance(contact, (
types.InputMediaContact, types.MessageMediaContact)):
return types.InputBotInlineMessageMediaContact(
phone_number=contact.phone_number,
first_name=contact.first_name,
last_name=contact.last_name,
vcard=contact.vcard,
reply_markup=markup
)
elif game:
return types.InputBotInlineMessageGame(
reply_markup=markup
)
else:
raise ValueError('No text, game or valid geo or contact given')
|
class InlineBuilder:
'''
Helper class to allow defining `InlineQuery
<telethon.events.inlinequery.InlineQuery>` ``results``.
Common arguments to all methods are
explained here to avoid repetition:
text (`str`, optional):
If present, the user will send a text
message with this text upon being clicked.
link_preview (`bool`, optional):
Whether to show a link preview in the sent
text message or not.
geo (:tl:`InputGeoPoint`, :tl:`GeoPoint`, :tl:`InputMediaVenue`, :tl:`MessageMediaVenue`, optional):
If present, it may either be a geo point or a venue.
period (int, optional):
The period in seconds to be used for geo points.
contact (:tl:`InputMediaContact`, :tl:`MessageMediaContact`, optional):
If present, it must be the contact information to send.
game (`bool`, optional):
May be `True` to indicate that the game will be sent.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`, optional):
Same as ``buttons`` for `client.send_message()
<telethon.client.messages.MessageMethods.send_message>`.
parse_mode (`str`, optional):
Same as ``parse_mode`` for `client.send_message()
<telethon.client.messageparse.MessageParseMethods.parse_mode>`.
id (`str`, optional):
The string ID to use for this result. If not present, it
will be the SHA256 hexadecimal digest of converting the
created :tl:`InputBotInlineResult` with empty ID to ``bytes()``,
so that the ID will be deterministic for the same input.
.. note::
If two inputs are exactly the same, their IDs will be the same
too. If you send two articles with the same ID, it will raise
``ResultIdDuplicateError``. Consider giving them an explicit
ID if you need to send two results that are the same.
'''
def __init__(self, client):
pass
async def article(
self, title, description=None,
*, url=None, thumb=None, content=None,
id=None, text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
'''
Creates new inline result of article type.
Args:
title (`str`):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
url (`str`, optional):
The URL to be shown for this result.
thumb (:tl:`InputWebDocument`, optional):
The thumbnail to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
content (:tl:`InputWebDocument`, optional):
The content to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
Example:
.. code-block:: python
results = [
# Option with title and description sending a message.
builder.article(
title='First option',
description='This is the first option',
text='Text sent after clicking this option',
),
# Option with title URL to be opened when clicked.
builder.article(
title='Second option',
url='https://example.com',
text='Text sent if the user clicks the option and not the URL',
),
# Sending a message with buttons.
# You can use a list or a list of lists to include more buttons.
builder.article(
title='Third option',
text='Text sent with buttons below',
buttons=Button.url('https://example.com'),
),
]
'''
pass
async def photo(
self, file, *, id=None, include_media=True,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
'''
Creates a new inline result of photo type.
Args:
include_media (`bool`, optional):
Whether the photo file used to display the result should be
included in the message itself or not. By default, the photo
is included, and the text parameter alters the caption.
file (`obj`, optional):
Same as ``file`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
Example:
.. code-block:: python
results = [
# Sending just the photo when the user selects it.
builder.photo('/path/to/photo.jpg'),
# Including a caption with some in-memory photo.
photo_bytesio = ...
builder.photo(
photo_bytesio,
text='This will be the caption of the sent photo',
),
# Sending just the message without including the photo.
builder.photo(
photo,
text='This will be a normal text message',
include_media=False,
),
]
'''
pass
async def document(
self, file, title=None, *, description=None, type=None,
mime_type=None, attributes=None, force_document=False,
voice_note=False, video_note=False, use_cache=True, id=None,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None,
include_media=True
):
'''
Creates a new inline result of document type.
`use_cache`, `mime_type`, `attributes`, `force_document`,
`voice_note` and `video_note` are described in `client.send_file
<telethon.client.uploads.UploadMethods.send_file>`.
Args:
file (`obj`):
Same as ``file`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
title (`str`, optional):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
type (`str`, optional):
The type of the document. May be one of: article, audio,
contact, file, geo, gif, photo, sticker, venue, video, voice.
It will be automatically set if ``mime_type`` is specified,
and default to ``'file'`` if no matching mime type is found.
you may need to pass ``attributes`` in order to use ``type``
effectively.
attributes (`list`, optional):
Optional attributes that override the inferred ones, like
:tl:`DocumentAttributeFilename` and so on.
include_media (`bool`, optional):
Whether the document file used to display the result should be
included in the message itself or not. By default, the document
is included, and the text parameter alters the caption.
Example:
.. code-block:: python
results = [
# Sending just the file when the user selects it.
builder.document('/path/to/file.pdf'),
# Including a caption with some in-memory file.
file_bytesio = ...
builder.document(
file_bytesio,
text='This will be the caption of the sent file',
),
# Sending just the message without including the file.
builder.document(
photo,
text='This will be a normal text message',
include_media=False,
),
]
'''
pass
async def game(
self, short_name, *, id=None,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, contact=None, game=False, buttons=None
):
'''
Creates a new inline result of game type.
Args:
short_name (`str`):
The short name of the game to use.
'''
pass
async def _message(
self, *,
text=None, parse_mode=(), link_preview=True, media=False,
geo=None, period=60, contact=None, game=False, buttons=None
):
pass
| 7 | 5 | 62 | 6 | 35 | 22 | 5 | 0.82 | 0 | 4 | 0 | 0 | 6 | 1 | 6 | 6 | 430 | 52 | 208 | 49 | 177 | 170 | 67 | 24 | 60 | 11 | 0 | 5 | 30 |
146,818 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/inlineresult.py
|
telethon.tl.custom.inlineresult.InlineResult
|
class InlineResult:
"""
Custom class that encapsulates a bot inline result providing
an abstraction to easily access some commonly needed features
(such as clicking a result to select it).
Attributes:
result (:tl:`BotInlineResult`):
The original :tl:`BotInlineResult` object.
"""
# tdlib types are the following (InlineQueriesManager::answer_inline_query @ 1a4a834):
# gif, article, audio, contact, file, geo, photo, sticker, venue, video, voice
#
# However, those documented in https://core.telegram.org/bots/api#inline-mode are different.
ARTICLE = 'article'
PHOTO = 'photo'
GIF = 'gif'
VIDEO = 'video'
VIDEO_GIF = 'mpeg4_gif'
AUDIO = 'audio'
DOCUMENT = 'document'
LOCATION = 'location'
VENUE = 'venue'
CONTACT = 'contact'
GAME = 'game'
def __init__(self, client, original, query_id=None, *, entity=None):
self._client = client
self.result = original
self._query_id = query_id
self._entity = entity
@property
def type(self):
"""
The always-present type of this result. It will be one of:
``'article'``, ``'photo'``, ``'gif'``, ``'mpeg4_gif'``, ``'video'``,
``'audio'``, ``'voice'``, ``'document'``, ``'location'``, ``'venue'``,
``'contact'``, ``'game'``.
You can access all of these constants through `InlineResult`,
such as `InlineResult.ARTICLE`, `InlineResult.VIDEO_GIF`, etc.
"""
return self.result.type
@property
def message(self):
"""
The always-present :tl:`BotInlineMessage` that
will be sent if `click` is called on this result.
"""
return self.result.send_message
@property
def title(self):
"""
The title for this inline result. It may be `None`.
"""
return self.result.title
@property
def description(self):
"""
The description for this inline result. It may be `None`.
"""
return self.result.description
@property
def url(self):
"""
The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.url
@property
def photo(self):
"""
Returns either the :tl:`WebDocument` thumbnail for
normal results or the :tl:`Photo` for media results.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.thumb
elif isinstance(self.result, types.BotInlineMediaResult):
return self.result.photo
@property
def document(self):
"""
Returns either the :tl:`WebDocument` content for
normal results or the :tl:`Document` for media results.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.content
elif isinstance(self.result, types.BotInlineMediaResult):
return self.result.document
async def click(self, entity=None, reply_to=None, comment_to=None,
silent=False, clear_draft=False, hide_via=False,
background=None):
"""
Clicks this result and sends the associated `message`.
Args:
entity (`entity`):
The entity to which the message of this result should be sent.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
If present, the sent message will reply to this ID or message.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to"
the specified message).
silent (`bool`, optional):
Whether the message should notify people with sound or not.
Defaults to `False` (send with a notification sound unless
the person has the chat muted). Set it to `True` to alter
this behaviour.
clear_draft (`bool`, optional):
Whether the draft should be removed after sending the
message from this result or not. Defaults to `False`.
hide_via (`bool`, optional):
Whether the "via @bot" should be hidden or not.
Only works with certain bots (like @bing or @gif).
background (`bool`, optional):
Whether the message should be send in background.
"""
if entity:
entity = await self._client.get_input_entity(entity)
elif self._entity:
entity = self._entity
else:
raise ValueError('You must provide the entity where the result should be sent to')
if comment_to:
entity, reply_id = await self._client._get_comment_data(entity, comment_to)
else:
reply_id = None if reply_to is None else utils.get_message_id(reply_to)
req = functions.messages.SendInlineBotResultRequest(
peer=entity,
query_id=self._query_id,
id=self.result.id,
silent=silent,
background=background,
clear_draft=clear_draft,
hide_via=hide_via,
reply_to=None if reply_id is None else types.InputReplyToMessage(reply_id)
)
return self._client._get_response_message(
req, await self._client(req), entity)
async def download_media(self, *args, **kwargs):
"""
Downloads the media in this result (if there is a document, the
document will be downloaded; otherwise, the photo will if present).
This is a wrapper around `client.download_media
<telethon.client.downloads.DownloadMethods.download_media>`.
"""
if self.document or self.photo:
return await self._client.download_media(
self.document or self.photo, *args, **kwargs)
|
class InlineResult:
'''
Custom class that encapsulates a bot inline result providing
an abstraction to easily access some commonly needed features
(such as clicking a result to select it).
Attributes:
result (:tl:`BotInlineResult`):
The original :tl:`BotInlineResult` object.
'''
def __init__(self, client, original, query_id=None, *, entity=None):
pass
@property
def type(self):
'''
The always-present type of this result. It will be one of:
``'article'``, ``'photo'``, ``'gif'``, ``'mpeg4_gif'``, ``'video'``,
``'audio'``, ``'voice'``, ``'document'``, ``'location'``, ``'venue'``,
``'contact'``, ``'game'``.
You can access all of these constants through `InlineResult`,
such as `InlineResult.ARTICLE`, `InlineResult.VIDEO_GIF`, etc.
'''
pass
@property
def message(self):
'''
The always-present :tl:`BotInlineMessage` that
will be sent if `click` is called on this result.
'''
pass
@property
def title(self):
'''
The title for this inline result. It may be `None`.
'''
pass
@property
def description(self):
'''
The description for this inline result. It may be `None`.
'''
pass
@property
def url(self):
'''
The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task.
'''
pass
@property
def photo(self):
'''
Returns either the :tl:`WebDocument` thumbnail for
normal results or the :tl:`Photo` for media results.
'''
pass
@property
def document(self):
'''
Returns either the :tl:`WebDocument` content for
normal results or the :tl:`Document` for media results.
'''
pass
async def click(self, entity=None, reply_to=None, comment_to=None,
silent=False, clear_draft=False, hide_via=False,
background=None):
'''
Clicks this result and sends the associated `message`.
Args:
entity (`entity`):
The entity to which the message of this result should be sent.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
If present, the sent message will reply to this ID or message.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to"
the specified message).
silent (`bool`, optional):
Whether the message should notify people with sound or not.
Defaults to `False` (send with a notification sound unless
the person has the chat muted). Set it to `True` to alter
this behaviour.
clear_draft (`bool`, optional):
Whether the draft should be removed after sending the
message from this result or not. Defaults to `False`.
hide_via (`bool`, optional):
Whether the "via @bot" should be hidden or not.
Only works with certain bots (like @bing or @gif).
background (`bool`, optional):
Whether the message should be send in background.
'''
pass
async def download_media(self, *args, **kwargs):
'''
Downloads the media in this result (if there is a document, the
document will be downloaded; otherwise, the photo will if present).
This is a wrapper around `client.download_media
<telethon.client.downloads.DownloadMethods.download_media>`.
'''
pass
| 18 | 10 | 13 | 1 | 6 | 6 | 2 | 1 | 0 | 1 | 0 | 0 | 10 | 4 | 10 | 10 | 172 | 24 | 74 | 37 | 54 | 74 | 49 | 28 | 38 | 6 | 0 | 1 | 21 |
146,819 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/inlineresults.py
|
telethon.tl.custom.inlineresults.InlineResults
|
class InlineResults(list):
"""
Custom class that encapsulates :tl:`BotResults` providing
an abstraction to easily access some commonly needed features
(such as clicking one of the results to select it)
Note that this is a list of `InlineResult
<telethon.tl.custom.inlineresult.InlineResult>`
so you can iterate over it or use indices to
access its elements. In addition, it has some
attributes.
Attributes:
result (:tl:`BotResults`):
The original :tl:`BotResults` object.
query_id (`int`):
The random ID that identifies this query.
cache_time (`int`):
For how long the results should be considered
valid. You can call `results_valid` at any
moment to determine if the results are still
valid or not.
users (:tl:`User`):
The users present in this inline query.
gallery (`bool`):
Whether these results should be presented
in a grid (as a gallery of images) or not.
next_offset (`str`, optional):
The string to be used as an offset to get
the next chunk of results, if any.
switch_pm (:tl:`InlineBotSwitchPM`, optional):
If presents, the results should show a button to
switch to a private conversation with the bot using
the text in this object.
"""
def __init__(self, client, original, *, entity=None):
super().__init__(InlineResult(client, x, original.query_id, entity=entity)
for x in original.results)
self.result = original
self.query_id = original.query_id
self.cache_time = original.cache_time
self._valid_until = time.time() + self.cache_time
self.users = original.users
self.gallery = bool(original.gallery)
self.next_offset = original.next_offset
self.switch_pm = original.switch_pm
def results_valid(self):
"""
Returns `True` if the cache time has not expired
yet and the results can still be considered valid.
"""
return time.time() < self._valid_until
def _to_str(self, item_function):
return ('[{}, query_id={}, cache_time={}, users={}, gallery={}, '
'next_offset={}, switch_pm={}]'.format(
', '.join(item_function(x) for x in self),
self.query_id,
self.cache_time,
self.users,
self.gallery,
self.next_offset,
self.switch_pm
))
def __str__(self):
return self._to_str(str)
def __repr__(self):
return self._to_str(repr)
|
class InlineResults(list):
'''
Custom class that encapsulates :tl:`BotResults` providing
an abstraction to easily access some commonly needed features
(such as clicking one of the results to select it)
Note that this is a list of `InlineResult
<telethon.tl.custom.inlineresult.InlineResult>`
so you can iterate over it or use indices to
access its elements. In addition, it has some
attributes.
Attributes:
result (:tl:`BotResults`):
The original :tl:`BotResults` object.
query_id (`int`):
The random ID that identifies this query.
cache_time (`int`):
For how long the results should be considered
valid. You can call `results_valid` at any
moment to determine if the results are still
valid or not.
users (:tl:`User`):
The users present in this inline query.
gallery (`bool`):
Whether these results should be presented
in a grid (as a gallery of images) or not.
next_offset (`str`, optional):
The string to be used as an offset to get
the next chunk of results, if any.
switch_pm (:tl:`InlineBotSwitchPM`, optional):
If presents, the results should show a button to
switch to a private conversation with the bot using
the text in this object.
'''
def __init__(self, client, original, *, entity=None):
pass
def results_valid(self):
'''
Returns `True` if the cache time has not expired
yet and the results can still be considered valid.
'''
pass
def _to_str(self, item_function):
pass
def __str__(self):
pass
def __repr__(self):
pass
| 6 | 2 | 7 | 0 | 6 | 1 | 1 | 1.24 | 1 | 4 | 1 | 0 | 5 | 8 | 5 | 38 | 78 | 13 | 29 | 14 | 23 | 36 | 19 | 14 | 13 | 1 | 2 | 0 | 5 |
146,820 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/inputsizedfile.py
|
telethon.tl.custom.inputsizedfile.InputSizedFile
|
class InputSizedFile(InputFile):
"""InputFile class with two extra parameters: md5 (digest) and size"""
def __init__(self, id_, parts, name, md5, size):
super().__init__(id_, parts, name, md5.hexdigest())
self.md5 = md5.digest()
self.size = size
|
class InputSizedFile(InputFile):
'''InputFile class with two extra parameters: md5 (digest) and size'''
def __init__(self, id_, parts, name, md5, size):
pass
| 2 | 1 | 4 | 0 | 4 | 0 | 1 | 0.2 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 1 | 6 | 0 | 5 | 4 | 3 | 1 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
146,821 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/messagedeleted.py
|
telethon.events.messagedeleted.MessageDeleted.Event
|
class Event(EventCommon):
def __init__(self, deleted_ids, peer):
super().__init__(
chat_peer=peer, msg_id=(deleted_ids or [0])[0]
)
self.deleted_id = None if not deleted_ids else deleted_ids[0]
self.deleted_ids = deleted_ids
|
class Event(EventCommon):
def __init__(self, deleted_ids, peer):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 37 | 7 | 0 | 7 | 4 | 5 | 0 | 5 | 4 | 3 | 2 | 6 | 0 | 2 |
146,822 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/messageedited.py
|
telethon.events.messageedited.MessageEdited.Event
|
class Event(NewMessage.Event):
pass
|
class Event(NewMessage.Event):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 2 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 7 | 0 | 0 |
146,823 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/album.py
|
telethon.events.album.Album.Event
|
class Event(EventCommon, SenderGetter):
"""
Represents the event of a new album.
Members:
messages (Sequence[`Message <telethon.tl.custom.message.Message>`]):
The list of messages belonging to the same album.
"""
def __init__(self, messages):
message = messages[0]
super().__init__(chat_peer=message.peer_id,
msg_id=message.id, broadcast=bool(message.post))
SenderGetter.__init__(self, message.sender_id)
self.messages = messages
def _set_client(self, client):
super()._set_client(client)
self._sender, self._input_sender = utils._get_entity_pair(
self.sender_id, self._entities, client._mb_entity_cache)
for msg in self.messages:
msg._finish_init(client, self._entities, None)
if len(self.messages) == 1:
# This will require hacks to be a proper album event
hack = client._albums.get(self.grouped_id)
if hack is None:
client._albums[self.grouped_id] = AlbumHack(client, self)
else:
hack.extend(self.messages)
@property
def grouped_id(self):
"""
The shared ``grouped_id`` between all the messages.
"""
return self.messages[0].grouped_id
@property
def text(self):
"""
The message text of the first photo with a caption,
formatted using the client's default parse mode.
"""
return next((m.text for m in self.messages if m.text), '')
@property
def raw_text(self):
"""
The raw message text of the first photo
with a caption, ignoring any formatting.
"""
return next((m.raw_text for m in self.messages if m.raw_text), '')
@property
def is_reply(self):
"""
`True` if the album is a reply to some other message.
Remember that you can access the ID of the message
this one is replying to through `reply_to_msg_id`,
and the `Message` object with `get_reply_message()`.
"""
# Each individual message in an album all reply to the same message
return self.messages[0].is_reply
@property
def forward(self):
"""
The `Forward <telethon.tl.custom.forward.Forward>`
information for the first message in the album if it was forwarded.
"""
# Each individual message in an album all reply to the same message
return self.messages[0].forward
# endregion Public Properties
# region Public Methods
async def get_reply_message(self):
"""
The `Message <telethon.tl.custom.message.Message>`
that this album is replying to, or `None`.
The result will be cached after its first use.
"""
return await self.messages[0].get_reply_message()
async def respond(self, *args, **kwargs):
"""
Responds to the album (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
"""
return await self.messages[0].respond(*args, **kwargs)
async def reply(self, *args, **kwargs):
"""
Replies to the first photo in the album (as a reply). Shorthand
for `telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
"""
return await self.messages[0].reply(*args, **kwargs)
async def forward_to(self, *args, **kwargs):
"""
Forwards the entire album. Shorthand for
`telethon.client.messages.MessageMethods.forward_messages`
with both ``messages`` and ``from_peer`` already set.
"""
if self._client:
kwargs['messages'] = self.messages
kwargs['from_peer'] = await self.get_input_chat()
return await self._client.forward_messages(*args, **kwargs)
async def edit(self, *args, **kwargs):
"""
Edits the first caption or the message, or the first messages'
caption if no caption is set, iff it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns `None` if the message was incoming,
or the edited `Message` otherwise.
.. note::
This is different from `client.edit_message
<telethon.client.messages.MessageMethods.edit_message>`
and **will respect** the previous state of the message.
For example, if the message didn't have a link preview,
the edit won't add one by default, and you should force
it by setting it to `True` if you want it.
This is generally the most desired and convenient behaviour,
and will work for link previews and message buttons.
"""
for msg in self.messages:
if msg.raw_text:
return await msg.edit(*args, **kwargs)
return await self.messages[0].edit(*args, **kwargs)
async def delete(self, *args, **kwargs):
"""
Deletes the entire album. You're responsible for checking whether
you have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
"""
if self._client:
return await self._client.delete_messages(
await self.get_input_chat(), self.messages,
*args, **kwargs
)
async def mark_read(self):
"""
Marks the entire album as read. Shorthand for
`client.send_read_acknowledge()
<telethon.client.messages.MessageMethods.send_read_acknowledge>`
with both ``entity`` and ``message`` already set.
"""
if self._client:
await self._client.send_read_acknowledge(
await self.get_input_chat(), max_id=self.messages[-1].id)
async def pin(self, *, notify=False):
"""
Pins the first photo in the album. Shorthand for
`telethon.client.messages.MessageMethods.pin_message`
with both ``entity`` and ``message`` already set.
"""
return await self.messages[0].pin(notify=notify)
def __len__(self):
"""
Return the amount of messages in the album.
Equivalent to ``len(self.messages)``.
"""
return len(self.messages)
def __iter__(self):
"""
Iterate over the messages in the album.
Equivalent to ``iter(self.messages)``.
"""
return iter(self.messages)
def __getitem__(self, n):
"""
Access the n'th message in the album.
Equivalent to ``event.messages[n]``.
"""
return self.messages[n]
|
class Event(EventCommon, SenderGetter):
'''
Represents the event of a new album.
Members:
messages (Sequence[`Message <telethon.tl.custom.message.Message>`]):
The list of messages belonging to the same album.
'''
def __init__(self, messages):
pass
def _set_client(self, client):
pass
@property
def grouped_id(self):
'''
The shared ``grouped_id`` between all the messages.
'''
pass
@property
def text(self):
'''
The message text of the first photo with a caption,
formatted using the client's default parse mode.
'''
pass
@property
def raw_text(self):
'''
The raw message text of the first photo
with a caption, ignoring any formatting.
'''
pass
@property
def is_reply(self):
'''
`True` if the album is a reply to some other message.
Remember that you can access the ID of the message
this one is replying to through `reply_to_msg_id`,
and the `Message` object with `get_reply_message()`.
'''
pass
@property
def forward(self):
'''
The `Forward <telethon.tl.custom.forward.Forward>`
information for the first message in the album if it was forwarded.
'''
pass
async def get_reply_message(self):
'''
The `Message <telethon.tl.custom.message.Message>`
that this album is replying to, or `None`.
The result will be cached after its first use.
'''
pass
async def respond(self, *args, **kwargs):
'''
Responds to the album (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
'''
pass
async def reply(self, *args, **kwargs):
'''
Replies to the first photo in the album (as a reply). Shorthand
for `telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
'''
pass
async def forward_to(self, *args, **kwargs):
'''
Forwards the entire album. Shorthand for
`telethon.client.messages.MessageMethods.forward_messages`
with both ``messages`` and ``from_peer`` already set.
'''
pass
async def edit(self, *args, **kwargs):
'''
Edits the first caption or the message, or the first messages'
caption if no caption is set, iff it's outgoing. Shorthand for
`telethon.client.messages.MessageMethods.edit_message`
with both ``entity`` and ``message`` already set.
Returns `None` if the message was incoming,
or the edited `Message` otherwise.
.. note::
This is different from `client.edit_message
<telethon.client.messages.MessageMethods.edit_message>`
and **will respect** the previous state of the message.
For example, if the message didn't have a link preview,
the edit won't add one by default, and you should force
it by setting it to `True` if you want it.
This is generally the most desired and convenient behaviour,
and will work for link previews and message buttons.
'''
pass
async def delete(self, *args, **kwargs):
'''
Deletes the entire album. You're responsible for checking whether
you have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
'''
pass
async def mark_read(self):
'''
Marks the entire album as read. Shorthand for
`client.send_read_acknowledge()
<telethon.client.messages.MessageMethods.send_read_acknowledge>`
with both ``entity`` and ``message`` already set.
'''
pass
async def pin(self, *, notify=False):
'''
Pins the first photo in the album. Shorthand for
`telethon.client.messages.MessageMethods.pin_message`
with both ``entity`` and ``message`` already set.
'''
pass
def __len__(self):
'''
Return the amount of messages in the album.
Equivalent to ``len(self.messages)``.
'''
pass
def __iter__(self):
'''
Iterate over the messages in the album.
Equivalent to ``iter(self.messages)``.
'''
pass
def __getitem__(self, n):
'''
Access the n'th message in the album.
Equivalent to ``event.messages[n]``.
'''
pass
| 24 | 17 | 9 | 1 | 3 | 5 | 1 | 1.46 | 2 | 3 | 1 | 0 | 18 | 3 | 18 | 61 | 199 | 32 | 68 | 30 | 44 | 99 | 56 | 25 | 37 | 4 | 6 | 2 | 26 |
146,824 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/newmessage.py
|
telethon.events.newmessage.NewMessage.Event
|
class Event(EventCommon):
"""
Represents the event of a new message. This event can be treated
to all effects as a `Message <telethon.tl.custom.message.Message>`,
so please **refer to its documentation** to know what you can do
with this event.
Members:
message (`Message <telethon.tl.custom.message.Message>`):
This is the only difference with the received
`Message <telethon.tl.custom.message.Message>`, and will
return the `telethon.tl.custom.message.Message` itself,
not the text.
See `Message <telethon.tl.custom.message.Message>` for
the rest of available members and methods.
pattern_match (`obj`):
The resulting object from calling the passed ``pattern`` function.
Here's an example using a string (defaults to regex match):
>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage(pattern=r'hi (\\w+)!'))
... async def handler(event):
... # In this case, the result is a ``Match`` object
... # since the `str` pattern was converted into
... # the ``re.compile(pattern).match`` function.
... print('Welcomed', event.pattern_match.group(1))
...
>>>
"""
def __init__(self, message):
self.__dict__['_init'] = False
super().__init__(chat_peer=message.peer_id,
msg_id=message.id, broadcast=bool(message.post))
self.pattern_match = None
self.message = message
def _set_client(self, client):
super()._set_client(client)
m = self.message
m._finish_init(client, self._entities, None)
self.__dict__['_init'] = True # No new attributes can be set
def __getattr__(self, item):
if item in self.__dict__:
return self.__dict__[item]
else:
return getattr(self.message, item)
def __setattr__(self, name, value):
if not self.__dict__['_init'] or name in self.__dict__:
self.__dict__[name] = value
else:
setattr(self.message, name, value)
|
class Event(EventCommon):
'''
Represents the event of a new message. This event can be treated
to all effects as a `Message <telethon.tl.custom.message.Message>`,
so please **refer to its documentation** to know what you can do
with this event.
Members:
message (`Message <telethon.tl.custom.message.Message>`):
This is the only difference with the received
`Message <telethon.tl.custom.message.Message>`, and will
return the `telethon.tl.custom.message.Message` itself,
not the text.
See `Message <telethon.tl.custom.message.Message>` for
the rest of available members and methods.
pattern_match (`obj`):
The resulting object from calling the passed ``pattern`` function.
Here's an example using a string (defaults to regex match):
>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage(pattern=r'hi (\w+)!'))
... async def handler(event):
... # In this case, the result is a ``Match`` object
... # since the `str` pattern was converted into
... # the ``re.compile(pattern).match`` function.
... print('Welcomed', event.pattern_match.group(1))
...
>>>
'''
def __init__(self, message):
pass
def _set_client(self, client):
pass
def __getattr__(self, item):
pass
def __setattr__(self, name, value):
pass
| 5 | 1 | 6 | 0 | 5 | 0 | 2 | 1.32 | 1 | 2 | 0 | 1 | 4 | 2 | 4 | 40 | 58 | 8 | 22 | 8 | 17 | 29 | 19 | 8 | 14 | 2 | 6 | 1 | 6 |
146,825 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/core/tlmessage.py
|
telethon.tl.core.tlmessage.TLMessage
|
class TLMessage(TLObject):
"""
https://core.telegram.org/mtproto/service_messages#simple-container.
Messages are what's ultimately sent to Telegram:
message msg_id:long seqno:int bytes:int body:bytes = Message;
Each message has its own unique identifier, and the body is simply
the serialized request that should be executed on the server, or
the response object from Telegram. Since the body is always a valid
object, it makes sense to store the object and not the bytes to
ease working with them.
There is no need to add serializing logic here since that can be
inlined and is unlikely to change. Thus these are only needed to
encapsulate responses.
"""
SIZE_OVERHEAD = 12
def __init__(self, msg_id, seq_no, obj):
self.msg_id = msg_id
self.seq_no = seq_no
self.obj = obj
def to_dict(self):
return {
'_': 'TLMessage',
'msg_id': self.msg_id,
'seq_no': self.seq_no,
'obj': self.obj
}
|
class TLMessage(TLObject):
'''
https://core.telegram.org/mtproto/service_messages#simple-container.
Messages are what's ultimately sent to Telegram:
message msg_id:long seqno:int bytes:int body:bytes = Message;
Each message has its own unique identifier, and the body is simply
the serialized request that should be executed on the server, or
the response object from Telegram. Since the body is always a valid
object, it makes sense to store the object and not the bytes to
ease working with them.
There is no need to add serializing logic here since that can be
inlined and is unlikely to change. Thus these are only needed to
encapsulate responses.
'''
def __init__(self, msg_id, seq_no, obj):
pass
def to_dict(self):
pass
| 3 | 1 | 6 | 0 | 6 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 2 | 31 | 5 | 13 | 7 | 10 | 13 | 8 | 7 | 5 | 1 | 1 | 0 | 2 |
146,826 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/core/rpcresult.py
|
telethon.tl.core.rpcresult.RpcResult
|
class RpcResult(TLObject):
CONSTRUCTOR_ID = 0xf35c6d01
def __init__(self, req_msg_id, body, error):
self.req_msg_id = req_msg_id
self.body = body
self.error = error
@classmethod
def from_reader(cls, reader):
msg_id = reader.read_long()
inner_code = reader.read_int(signed=False)
if inner_code == RpcError.CONSTRUCTOR_ID:
return RpcResult(msg_id, None, RpcError.from_reader(reader))
if inner_code == GzipPacked.CONSTRUCTOR_ID:
return RpcResult(msg_id, GzipPacked.from_reader(reader).data, None)
reader.seek(-4)
# This reader.read() will read more than necessary, but it's okay.
# We could make use of MessageContainer's length here, but since
# it's not necessary we don't need to care about it.
return RpcResult(msg_id, reader.read(), None)
def to_dict(self):
return {
'_': 'RpcResult',
'req_msg_id': self.req_msg_id,
'body': self.body,
'error': self.error
}
|
class RpcResult(TLObject):
def __init__(self, req_msg_id, body, error):
pass
@classmethod
def from_reader(cls, reader):
pass
def to_dict(self):
pass
| 5 | 0 | 8 | 0 | 7 | 1 | 2 | 0.13 | 1 | 1 | 1 | 0 | 2 | 3 | 3 | 3 | 30 | 4 | 23 | 11 | 18 | 3 | 17 | 10 | 13 | 3 | 1 | 1 | 5 |
146,827 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/core/messagecontainer.py
|
telethon.tl.core.messagecontainer.MessageContainer
|
class MessageContainer(TLObject):
CONSTRUCTOR_ID = 0x73f1f8dc
# Maximum size in bytes for the inner payload of the container.
# Telegram will close the connection if the payload is bigger.
# The overhead of the container itself is subtracted.
MAXIMUM_SIZE = 1044456 - 8
# Maximum amount of messages that can't be sent inside a single
# container, inclusive. Beyond this limit Telegram will respond
# with BAD_MESSAGE 64 (invalid container).
#
# This limit is not 100% accurate and may in some cases be higher.
# However, sending up to 100 requests at once in a single container
# is a reasonable conservative value, since it could also depend on
# other factors like size per request, but we cannot know this.
MAXIMUM_LENGTH = 100
def __init__(self, messages):
self.messages = messages
def to_dict(self):
return {
'_': 'MessageContainer',
'messages':
[] if self.messages is None else [
None if x is None else x.to_dict() for x in self.messages
],
}
@classmethod
def from_reader(cls, reader):
# This assumes that .read_* calls are done in the order they appear
messages = []
for _ in range(reader.read_int()):
msg_id = reader.read_long()
seq_no = reader.read_int()
length = reader.read_int()
before = reader.tell_position()
obj = reader.tgread_object() # May over-read e.g. RpcResult
reader.set_position(before + length)
messages.append(TLMessage(msg_id, seq_no, obj))
return MessageContainer(messages)
|
class MessageContainer(TLObject):
def __init__(self, messages):
pass
def to_dict(self):
pass
@classmethod
def from_reader(cls, reader):
pass
| 5 | 0 | 7 | 0 | 7 | 1 | 2 | 0.5 | 1 | 2 | 1 | 0 | 2 | 1 | 3 | 15 | 43 | 5 | 26 | 16 | 21 | 13 | 19 | 15 | 15 | 3 | 1 | 1 | 6 |
146,828 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/messageread.py
|
telethon.events.messageread.MessageRead.Event
|
class Event(EventCommon):
"""
Represents the event of one or more messages being read.
Members:
max_id (`int`):
Up to which message ID has been read. Every message
with an ID equal or lower to it have been read.
outbox (`bool`):
`True` if someone else has read your messages.
contents (`bool`):
`True` if what was read were the contents of a message.
This will be the case when e.g. you play a voice note.
It may only be set on ``inbox`` events.
"""
def __init__(self, peer=None, max_id=None, out=False, contents=False,
message_ids=None):
self.outbox = out
self.contents = contents
self._message_ids = message_ids or []
self._messages = None
self.max_id = max_id or max(message_ids or [], default=None)
super().__init__(peer, self.max_id)
@property
def inbox(self):
"""
`True` if you have read someone else's messages.
"""
return not self.outbox
@property
def message_ids(self):
"""
The IDs of the messages **which contents'** were read.
Use :meth:`is_read` if you need to check whether a message
was read instead checking if it's in here.
"""
return self._message_ids
async def get_messages(self):
"""
Returns the list of `Message <telethon.tl.custom.message.Message>`
**which contents'** were read.
Use :meth:`is_read` if you need to check whether a message
was read instead checking if it's in here.
"""
if self._messages is None:
chat = await self.get_input_chat()
if not chat:
self._messages = []
else:
self._messages = await self._client.get_messages(
chat, ids=self._message_ids)
return self._messages
def is_read(self, message):
"""
Returns `True` if the given message (or its ID) has been read.
If a list-like argument is provided, this method will return a
list of booleans indicating which messages have been read.
"""
if utils.is_list_like(message):
return [(m if isinstance(m, int) else m.id) <= self.max_id
for m in message]
else:
return (message if isinstance(message, int)
else message.id) <= self.max_id
def __contains__(self, message):
"""`True` if the message(s) are read message."""
if utils.is_list_like(message):
return all(self.is_read(message))
else:
return self.is_read(message)
|
class Event(EventCommon):
'''
Represents the event of one or more messages being read.
Members:
max_id (`int`):
Up to which message ID has been read. Every message
with an ID equal or lower to it have been read.
outbox (`bool`):
`True` if someone else has read your messages.
contents (`bool`):
`True` if what was read were the contents of a message.
This will be the case when e.g. you play a voice note.
It may only be set on ``inbox`` events.
'''
def __init__(self, peer=None, max_id=None, out=False, contents=False,
message_ids=None):
pass
@property
def inbox(self):
'''
`True` if you have read someone else's messages.
'''
pass
@property
def message_ids(self):
'''
The IDs of the messages **which contents'** were read.
Use :meth:`is_read` if you need to check whether a message
was read instead checking if it's in here.
'''
pass
async def get_messages(self):
'''
Returns the list of `Message <telethon.tl.custom.message.Message>`
**which contents'** were read.
Use :meth:`is_read` if you need to check whether a message
was read instead checking if it's in here.
'''
pass
def is_read(self, message):
'''
Returns `True` if the given message (or its ID) has been read.
If a list-like argument is provided, this method will return a
list of booleans indicating which messages have been read.
'''
pass
def __contains__(self, message):
'''`True` if the message(s) are read message.'''
pass
| 9 | 6 | 10 | 1 | 6 | 3 | 2 | 0.92 | 1 | 2 | 0 | 0 | 6 | 5 | 6 | 42 | 81 | 12 | 36 | 16 | 26 | 33 | 27 | 13 | 20 | 4 | 6 | 2 | 12 |
146,829 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/button.py
|
telethon.tl.custom.button.Button
|
class Button:
"""
.. note::
This class is used to **define** reply markups, e.g. when
sending a message or replying to events. When you access
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
they are actually `MessageButton
<telethon.tl.custom.messagebutton.MessageButton>`,
so you might want to refer to that class instead.
Helper class to allow defining ``reply_markup`` when
sending a message with inline or keyboard buttons.
You should make use of the defined class methods to create button
instances instead making them yourself (i.e. don't do ``Button(...)``
but instead use methods line `Button.inline(...) <inline>` etc.
You can use `inline`, `switch_inline`, `url`, `auth`, `buy` and `game`
together to create inline buttons (under the message).
You can use `text`, `request_location`, `request_phone` and `request_poll`
together to create a reply markup (replaces the user keyboard).
You can also configure the aspect of the reply with these.
The latest message with a reply markup will be the one shown to the user
(messages contain the buttons, not the chat itself).
You **cannot** mix the two type of buttons together,
and it will error if you try to do so.
The text for all buttons may be at most 142 characters.
If more characters are given, Telegram will cut the text
to 128 characters and add the ellipsis (…) character as
the 129.
"""
def __init__(self, button, *, resize, single_use, selective):
self.button = button
self.resize = resize
self.single_use = single_use
self.selective = selective
@staticmethod
def _is_inline(button):
"""
Returns `True` if the button belongs to an inline keyboard.
"""
return isinstance(button, (
types.KeyboardButtonBuy,
types.KeyboardButtonCallback,
types.KeyboardButtonGame,
types.KeyboardButtonSwitchInline,
types.KeyboardButtonUrl,
types.InputKeyboardButtonUrlAuth,
types.KeyboardButtonWebView,
))
@staticmethod
def inline(text, data=None):
"""
Creates a new inline button with some payload data in it.
If `data` is omitted, the given `text` will be used as `data`.
In any case `data` should be either `bytes` or `str`.
Note that the given `data` must be less or equal to 64 bytes.
If more than 64 bytes are passed as data, ``ValueError`` is raised.
If you need to store more than 64 bytes, consider saving the real
data in a database and a reference to that data inside the button.
When the user clicks this button, `events.CallbackQuery
<telethon.events.callbackquery.CallbackQuery>` will trigger with the
same data that the button contained, so that you can determine which
button was pressed.
"""
if not data:
data = text.encode('utf-8')
elif not isinstance(data, (bytes, bytearray, memoryview)):
data = str(data).encode('utf-8')
if len(data) > 64:
raise ValueError('Too many bytes for the data')
return types.KeyboardButtonCallback(text, data)
@staticmethod
def switch_inline(text, query='', same_peer=False):
"""
Creates a new inline button to switch to inline query.
If `query` is given, it will be the default text to be used
when making the inline query.
If ``same_peer is True`` the inline query will directly be
set under the currently opened chat. Otherwise, the user will
have to select a different dialog to make the query.
When the user clicks this button, after a chat is selected, their
input field will be filled with the username of your bot followed
by the query text, ready to make inline queries.
"""
return types.KeyboardButtonSwitchInline(text, query, same_peer)
@staticmethod
def url(text, url=None):
"""
Creates a new inline button to open the desired URL on click.
If no `url` is given, the `text` will be used as said URL instead.
You cannot detect that the user clicked this button directly.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to open the displayed URL unless
the domain is trusted, and once confirmed the URL will open in their
device.
"""
return types.KeyboardButtonUrl(text, url or text)
@staticmethod
def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None):
"""
Creates a new inline button to authorize the user at the given URL.
You should set the `url` to be on the same domain as the one configured
for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using
the ``/setdomain`` command.
For more information about letting the user login via Telegram to
a certain domain, see https://core.telegram.org/widgets/login.
If no `url` is specified, it will default to `text`.
Args:
bot (`hints.EntityLike`):
The bot that requires this authorization. By default, this
is the bot that is currently logged in (itself), although
you may pass a different input peer.
.. note::
For now, you cannot use ID or username for this argument.
If you want to use a different bot than the one currently
logged in, you must manually use `client.get_input_entity()
<telethon.client.users.UserMethods.get_input_entity>`.
write_access (`bool`):
Whether write access is required or not.
This is `False` by default (read-only access).
fwd_text (`str`):
The new text to show in the button if the message is
forwarded. By default, the button text will be the same.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to login to the specified domain.
"""
return types.InputKeyboardButtonUrlAuth(
text=text,
url=url or text,
bot=utils.get_input_user(bot or types.InputUserSelf()),
request_write_access=write_access,
fwd_text=fwd_text
)
@classmethod
def text(cls, text, *, resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_use (`bool`):
If present, the entire keyboard will be reconfigured to
be usable only once before it hides itself.
selective (`bool`):
If present, the entire keyboard will be reconfigured to
be "selective". The keyboard will be shown only to specific
users. It will target users that are @mentioned in the text
of the message or to the sender of the message you reply to.
When the user clicks this button, a text message with the same text
as the button will be sent, and can be handled with `events.NewMessage
<telethon.events.newmessage.NewMessage>`. You cannot distinguish
between a button press and the user typing and sending exactly the
same text on their own.
"""
return cls(types.KeyboardButton(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_location(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user's location on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their location with the
bot, and if confirmed a message with geo media will be sent.
"""
return cls(types.KeyboardButtonRequestGeoLocation(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user's phone on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their phone with the
bot, and if confirmed a message with contact media will be sent.
"""
return cls(types.KeyboardButtonRequestPhone(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_poll(cls, text, *, force_quiz=False,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user to create a poll.
If `force_quiz` is `False`, the user will be allowed to choose whether
they want their poll to be a quiz or not. Otherwise, the user will be
forced to create a quiz when creating the poll.
If a poll is a quiz, there will be only one answer that is valid, and
the votes cannot be retracted. Otherwise, users can vote and retract
the vote, and the pol might be multiple choice.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a screen letting the user create a
poll will be shown, and if they do create one, the poll will be sent.
"""
return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz),
resize=resize, single_use=single_use, selective=selective)
@staticmethod
def clear(selective=None):
"""
Clears all keyboard buttons after sending a message with this markup.
When used, no other button should be present or it will be ignored.
``selective`` is as documented in `text`.
"""
return types.ReplyKeyboardHide(selective=selective)
@staticmethod
def force_reply(single_use=None, selective=None, placeholder=None):
"""
Forces a reply to the message with this markup. If used,
no other button should be present or it will be ignored.
``single_use`` and ``selective`` are as documented in `text`.
Args:
placeholder (str):
text to show the user at typing place of message.
If the placeholder is too long, Telegram applications will
crop the text (for example, to 64 characters and adding an
ellipsis (…) character as the 65th).
"""
return types.ReplyKeyboardForceReply(
single_use=single_use,
selective=selective,
placeholder=placeholder)
@staticmethod
def buy(text):
"""
Creates a new inline button to buy a product.
This can only be used when sending files of type
:tl:`InputMediaInvoice`, and must be the first button.
If the button is not specified, Telegram will automatically
add the button to the message. See the
`Payments API <https://core.telegram.org/api/payments>`__
documentation for more information.
"""
return types.KeyboardButtonBuy(text)
@staticmethod
def game(text):
"""
Creates a new inline button to start playing a game.
This should be used when sending files of type
:tl:`InputMediaGame`, and must be the first button.
See the
`Games <https://core.telegram.org/api/bots/games>`__
documentation for more information on using games.
"""
return types.KeyboardButtonGame(text)
|
class Button:
'''
.. note::
This class is used to **define** reply markups, e.g. when
sending a message or replying to events. When you access
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
they are actually `MessageButton
<telethon.tl.custom.messagebutton.MessageButton>`,
so you might want to refer to that class instead.
Helper class to allow defining ``reply_markup`` when
sending a message with inline or keyboard buttons.
You should make use of the defined class methods to create button
instances instead making them yourself (i.e. don't do ``Button(...)``
but instead use methods line `Button.inline(...) <inline>` etc.
You can use `inline`, `switch_inline`, `url`, `auth`, `buy` and `game`
together to create inline buttons (under the message).
You can use `text`, `request_location`, `request_phone` and `request_poll`
together to create a reply markup (replaces the user keyboard).
You can also configure the aspect of the reply with these.
The latest message with a reply markup will be the one shown to the user
(messages contain the buttons, not the chat itself).
You **cannot** mix the two type of buttons together,
and it will error if you try to do so.
The text for all buttons may be at most 142 characters.
If more characters are given, Telegram will cut the text
to 128 characters and add the ellipsis (…) character as
the 129.
'''
def __init__(self, button, *, resize, single_use, selective):
pass
@staticmethod
def _is_inline(button):
'''
Returns `True` if the button belongs to an inline keyboard.
'''
pass
@staticmethod
def inline(text, data=None):
'''
Creates a new inline button with some payload data in it.
If `data` is omitted, the given `text` will be used as `data`.
In any case `data` should be either `bytes` or `str`.
Note that the given `data` must be less or equal to 64 bytes.
If more than 64 bytes are passed as data, ``ValueError`` is raised.
If you need to store more than 64 bytes, consider saving the real
data in a database and a reference to that data inside the button.
When the user clicks this button, `events.CallbackQuery
<telethon.events.callbackquery.CallbackQuery>` will trigger with the
same data that the button contained, so that you can determine which
button was pressed.
'''
pass
@staticmethod
def switch_inline(text, query='', same_peer=False):
'''
Creates a new inline button to switch to inline query.
If `query` is given, it will be the default text to be used
when making the inline query.
If ``same_peer is True`` the inline query will directly be
set under the currently opened chat. Otherwise, the user will
have to select a different dialog to make the query.
When the user clicks this button, after a chat is selected, their
input field will be filled with the username of your bot followed
by the query text, ready to make inline queries.
'''
pass
@staticmethod
def url(text, url=None):
'''
Creates a new inline button to open the desired URL on click.
If no `url` is given, the `text` will be used as said URL instead.
You cannot detect that the user clicked this button directly.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to open the displayed URL unless
the domain is trusted, and once confirmed the URL will open in their
device.
'''
pass
@staticmethod
def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None):
'''
Creates a new inline button to authorize the user at the given URL.
You should set the `url` to be on the same domain as the one configured
for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using
the ``/setdomain`` command.
For more information about letting the user login via Telegram to
a certain domain, see https://core.telegram.org/widgets/login.
If no `url` is specified, it will default to `text`.
Args:
bot (`hints.EntityLike`):
The bot that requires this authorization. By default, this
is the bot that is currently logged in (itself), although
you may pass a different input peer.
.. note::
For now, you cannot use ID or username for this argument.
If you want to use a different bot than the one currently
logged in, you must manually use `client.get_input_entity()
<telethon.client.users.UserMethods.get_input_entity>`.
write_access (`bool`):
Whether write access is required or not.
This is `False` by default (read-only access).
fwd_text (`str`):
The new text to show in the button if the message is
forwarded. By default, the button text will be the same.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to login to the specified domain.
'''
pass
@classmethod
def text(cls, text, *, resize=None, single_use=None, selective=None):
'''
Creates a new keyboard button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_use (`bool`):
If present, the entire keyboard will be reconfigured to
be usable only once before it hides itself.
selective (`bool`):
If present, the entire keyboard will be reconfigured to
be "selective". The keyboard will be shown only to specific
users. It will target users that are @mentioned in the text
of the message or to the sender of the message you reply to.
When the user clicks this button, a text message with the same text
as the button will be sent, and can be handled with `events.NewMessage
<telethon.events.newmessage.NewMessage>`. You cannot distinguish
between a button press and the user typing and sending exactly the
same text on their own.
'''
pass
@classmethod
def request_location(cls, text, *,
resize=None, single_use=None, selective=None):
'''
Creates a new keyboard button to request the user's location on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their location with the
bot, and if confirmed a message with geo media will be sent.
'''
pass
@classmethod
def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
'''
Creates a new keyboard button to request the user's phone on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their phone with the
bot, and if confirmed a message with contact media will be sent.
'''
pass
@classmethod
def request_poll(cls, text, *, force_quiz=False,
resize=None, single_use=None, selective=None):
'''
Creates a new keyboard button to request the user to create a poll.
If `force_quiz` is `False`, the user will be allowed to choose whether
they want their poll to be a quiz or not. Otherwise, the user will be
forced to create a quiz when creating the poll.
If a poll is a quiz, there will be only one answer that is valid, and
the votes cannot be retracted. Otherwise, users can vote and retract
the vote, and the pol might be multiple choice.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a screen letting the user create a
poll will be shown, and if they do create one, the poll will be sent.
'''
pass
@staticmethod
def clear(selective=None):
'''
Clears all keyboard buttons after sending a message with this markup.
When used, no other button should be present or it will be ignored.
``selective`` is as documented in `text`.
'''
pass
@staticmethod
def force_reply(single_use=None, selective=None, placeholder=None):
'''
Forces a reply to the message with this markup. If used,
no other button should be present or it will be ignored.
``single_use`` and ``selective`` are as documented in `text`.
Args:
placeholder (str):
text to show the user at typing place of message.
If the placeholder is too long, Telegram applications will
crop the text (for example, to 64 characters and adding an
ellipsis (…) character as the 65th).
'''
pass
@staticmethod
def buy(text):
'''
Creates a new inline button to buy a product.
This can only be used when sending files of type
:tl:`InputMediaInvoice`, and must be the first button.
If the button is not specified, Telegram will automatically
add the button to the message. See the
`Payments API <https://core.telegram.org/api/payments>`__
documentation for more information.
'''
pass
@staticmethod
def game(text):
'''
Creates a new inline button to start playing a game.
This should be used when sending files of type
:tl:`InputMediaGame`, and must be the first button.
See the
`Games <https://core.telegram.org/api/bots/games>`__
documentation for more information on using games.
'''
pass
| 28 | 14 | 17 | 3 | 4 | 10 | 1 | 2.25 | 0 | 5 | 0 | 0 | 1 | 4 | 14 | 14 | 305 | 61 | 75 | 35 | 44 | 169 | 37 | 19 | 22 | 4 | 0 | 1 | 17 |
146,830 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/conversation.py
|
telethon.tl.custom.conversation.Conversation
|
class Conversation(ChatGetter):
"""
Represents a conversation inside an specific chat.
A conversation keeps track of new messages since it was
created until its exit and easily lets you query the
current state.
If you need a conversation across two or more chats,
you should use two conversations and synchronize them
as you better see fit.
"""
_id_counter = 0
_custom_counter = 0
def __init__(self, client, input_chat,
*, timeout, total_timeout, max_messages,
exclusive, replies_are_responses):
# This call resets the client
ChatGetter.__init__(self, input_chat=input_chat)
self._id = Conversation._id_counter
Conversation._id_counter += 1
self._client = client
self._timeout = timeout
self._total_timeout = total_timeout
self._total_due = None
self._outgoing = set()
self._last_outgoing = 0
self._incoming = []
self._last_incoming = 0
self._max_incoming = max_messages
self._last_read = None
self._custom = {}
self._pending_responses = {}
self._pending_replies = {}
self._pending_edits = {}
self._pending_reads = {}
self._exclusive = exclusive
self._cancelled = False
# The user is able to expect two responses for the same message.
# {desired message ID: next incoming index}
self._response_indices = {}
if replies_are_responses:
self._reply_indices = self._response_indices
else:
self._reply_indices = {}
self._edit_dates = {}
@_checks_cancelled
async def send_message(self, *args, **kwargs):
"""
Sends a message in the context of this conversation. Shorthand
for `telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
"""
sent = await self._client.send_message(
self._input_chat, *args, **kwargs)
# Albums will be lists, so handle that
ms = sent if isinstance(sent, list) else (sent,)
self._outgoing.update(m.id for m in ms)
self._last_outgoing = ms[-1].id
return sent
@_checks_cancelled
async def send_file(self, *args, **kwargs):
"""
Sends a file in the context of this conversation. Shorthand
for `telethon.client.uploads.UploadMethods.send_file` with
``entity`` already set.
"""
sent = await self._client.send_file(
self._input_chat, *args, **kwargs)
# Albums will be lists, so handle that
ms = sent if isinstance(sent, list) else (sent,)
self._outgoing.update(m.id for m in ms)
self._last_outgoing = ms[-1].id
return sent
@_checks_cancelled
def mark_read(self, message=None):
"""
Marks as read the latest received message if ``message is None``.
Otherwise, marks as read until the given message (or message ID).
This is equivalent to calling `client.send_read_acknowledge
<telethon.client.messages.MessageMethods.send_read_acknowledge>`.
"""
if message is None:
if self._incoming:
message = self._incoming[-1].id
else:
message = 0
elif not isinstance(message, int):
message = message.id
return self._client.send_read_acknowledge(
self._input_chat, max_id=message)
def get_response(self, message=None, *, timeout=None):
"""
Gets the next message that responds to a previous one. This is
the method you need most of the time, along with `get_edit`.
Args:
message (`Message <telethon.tl.custom.message.Message>` | `int`, optional):
The message (or the message ID) for which a response
is expected. By default this is the last sent message.
timeout (`int` | `float`, optional):
If present, this `timeout` (in seconds) will override the
per-action timeout defined for the conversation.
.. code-block:: python
async with client.conversation(...) as conv:
await conv.send_message('Hey, what is your name?')
response = await conv.get_response()
name = response.text
await conv.send_message('Nice to meet you, {}!'.format(name))
"""
return self._get_message(
message, self._response_indices, self._pending_responses, timeout,
lambda x, y: True
)
def get_reply(self, message=None, *, timeout=None):
"""
Gets the next message that explicitly replies to a previous one.
"""
return self._get_message(
message, self._reply_indices, self._pending_replies, timeout,
lambda x, y: x.reply_to and x.reply_to.reply_to_msg_id == y
)
def _get_message(
self, target_message, indices, pending, timeout, condition):
"""
Gets the next desired message under the desired condition.
Args:
target_message (`object`):
The target message for which we want to find another
response that applies based on `condition`.
indices (`dict`):
This dictionary remembers the last ID chosen for the
input `target_message`.
pending (`dict`):
This dictionary remembers {msg_id: Future} to be set
once `condition` is met.
timeout (`int`):
The timeout (in seconds) override to use for this operation.
condition (`callable`):
The condition callable that checks if an incoming
message is a valid response.
"""
start_time = time.time()
target_id = self._get_message_id(target_message)
# If there is no last-chosen ID, make sure to pick one *after*
# the input message, since we don't want responses back in time
if target_id not in indices:
for i, incoming in enumerate(self._incoming):
if incoming.id > target_id:
indices[target_id] = i
break
else:
indices[target_id] = len(self._incoming)
# We will always return a future from here, even if the result
# can be set immediately. Otherwise, needing to await only
# sometimes is an annoying edge case (i.e. we would return
# a `Message` but `get_response()` always `await`'s).
future = self._client.loop.create_future()
# If there are enough responses saved return the next one
last_idx = indices[target_id]
if last_idx < len(self._incoming):
incoming = self._incoming[last_idx]
if condition(incoming, target_id):
indices[target_id] += 1
future.set_result(incoming)
return future
# Otherwise the next incoming response will be the one to use
#
# Note how we fill "pending" before giving control back to the
# event loop through "await". We want to register it as soon as
# possible, since any other task switch may arrive with the result.
pending[target_id] = future
return self._get_result(future, start_time, timeout, pending, target_id)
def get_edit(self, message=None, *, timeout=None):
"""
Awaits for an edit after the last message to arrive.
The arguments are the same as those for `get_response`.
"""
start_time = time.time()
target_id = self._get_message_id(message)
target_date = self._edit_dates.get(target_id, 0)
earliest_edit = min(
(x for x in self._incoming
if x.edit_date
and x.id > target_id
and x.edit_date.timestamp() > target_date
),
key=lambda x: x.edit_date.timestamp(),
default=None
)
future = self._client.loop.create_future()
if earliest_edit and earliest_edit.edit_date.timestamp() > target_date:
self._edit_dates[target_id] = earliest_edit.edit_date.timestamp()
future.set_result(earliest_edit)
return future # we should always return something we can await
# Otherwise the next incoming response will be the one to use
self._pending_edits[target_id] = future
return self._get_result(future, start_time, timeout, self._pending_edits, target_id)
def wait_read(self, message=None, *, timeout=None):
"""
Awaits for the sent message to be marked as read. Note that
receiving a response doesn't imply the message was read, and
this action will also trigger even without a response.
"""
start_time = time.time()
future = self._client.loop.create_future()
target_id = self._get_message_id(message)
if self._last_read is None:
self._last_read = target_id - 1
if self._last_read >= target_id:
return
self._pending_reads[target_id] = future
return self._get_result(future, start_time, timeout, self._pending_reads, target_id)
async def wait_event(self, event, *, timeout=None):
"""
Waits for a custom event to occur. Timeouts still apply.
.. note::
**Only use this if there isn't another method available!**
For example, don't use `wait_event` for new messages,
since `get_response` already exists, etc.
Unless you're certain that your code will run fast enough,
generally you should get a "handle" of this special coroutine
before acting. In this example you will see how to wait for a user
to join a group with proper use of `wait_event`:
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
group_id = ...
async def main():
# Could also get the user id from an event; this is just an example
user_id = ...
async with client.conversation(user_id) as conv:
# Get a handle to the future event we'll wait for
handle = conv.wait_event(events.ChatAction(
group_id,
func=lambda e: e.user_joined and e.user_id == user_id
))
# Perform whatever action in between
await conv.send_message('Please join this group before speaking to me!')
# Wait for the event we registered above to fire
event = await handle
# Continue with the conversation
await conv.send_message('Thanks!')
This way your event can be registered before acting,
since the response may arrive before your event was
registered. It depends on your use case since this
also means the event can arrive before you send
a previous action.
"""
start_time = time.time()
if isinstance(event, type):
event = event()
await event.resolve(self._client)
counter = Conversation._custom_counter
Conversation._custom_counter += 1
future = self._client.loop.create_future()
self._custom[counter] = (event, future)
try:
return await self._get_result(future, start_time, timeout, self._custom, counter)
finally:
# Need to remove it from the dict if it times out, else we may
# try and fail to set the result later (#1618).
self._custom.pop(counter, None)
async def _check_custom(self, built):
for key, (ev, fut) in list(self._custom.items()):
ev_type = type(ev)
inst = built[ev_type]
if inst:
filter = ev.filter(inst)
if inspect.isawaitable(filter):
filter = await filter
if filter:
fut.set_result(inst)
del self._custom[key]
def _on_new_message(self, response):
response = response.message
if response.chat_id != self.chat_id or response.out:
return
if len(self._incoming) == self._max_incoming:
self._cancel_all(ValueError('Too many incoming messages'))
return
self._incoming.append(response)
# Most of the time, these dictionaries will contain just one item
# TODO In fact, why not make it be that way? Force one item only.
# How often will people want to wait for two responses at
# the same time? It's impossible, first one will arrive
# and then another, so they can do that.
for msg_id, future in list(self._pending_responses.items()):
self._response_indices[msg_id] = len(self._incoming)
future.set_result(response)
del self._pending_responses[msg_id]
for msg_id, future in list(self._pending_replies.items()):
if response.reply_to and msg_id == response.reply_to.reply_to_msg_id:
self._reply_indices[msg_id] = len(self._incoming)
future.set_result(response)
del self._pending_replies[msg_id]
def _on_edit(self, message):
message = message.message
if message.chat_id != self.chat_id or message.out:
return
# We have to update our incoming messages with the new edit date
for i, m in enumerate(self._incoming):
if m.id == message.id:
self._incoming[i] = message
break
for msg_id, future in list(self._pending_edits.items()):
if msg_id < message.id:
edit_ts = message.edit_date.timestamp()
# We compare <= because edit_ts resolution is always to
# seconds, but we may have increased _edit_dates before.
# Since the dates are ever growing this is not a problem.
if edit_ts <= self._edit_dates.get(msg_id, 0):
self._edit_dates[msg_id] += _EDIT_COLLISION_DELTA
else:
self._edit_dates[msg_id] = message.edit_date.timestamp()
future.set_result(message)
del self._pending_edits[msg_id]
def _on_read(self, event):
if event.chat_id != self.chat_id or event.inbox:
return
self._last_read = event.max_id
for msg_id, pending in list(self._pending_reads.items()):
if msg_id >= self._last_read:
pending.set_result(True)
del self._pending_reads[msg_id]
def _get_message_id(self, message):
if message is not None: # 0 is valid but false-y, check for None
return message if isinstance(message, int) else message.id
elif self._last_outgoing:
return self._last_outgoing
else:
raise ValueError('No message was sent previously')
@_checks_cancelled
def _get_result(self, future, start_time, timeout, pending, target_id):
due = self._total_due
if timeout is None:
timeout = self._timeout
if timeout is not None:
due = min(due, start_time + timeout)
# NOTE: We can't try/finally to pop from pending here because
# the event loop needs to get back to us, but it might
# dispatch another update before, and in that case a
# response could be set twice. So responses must be
# cleared when their futures are set to a result.
return asyncio.wait_for(
future,
timeout=None if due == float('inf') else due - time.time()
)
def _cancel_all(self, exception=None):
self._cancelled = True
for pending in itertools.chain(
self._pending_responses.values(),
self._pending_replies.values(),
self._pending_edits.values()):
if exception:
pending.set_exception(exception)
else:
pending.cancel()
for _, fut in self._custom.values():
if exception:
fut.set_exception(exception)
else:
fut.cancel()
async def __aenter__(self):
self._input_chat = \
await self._client.get_input_entity(self._input_chat)
self._chat_peer = utils.get_peer(self._input_chat)
# Make sure we're the only conversation in this chat if it's exclusive
chat_id = utils.get_peer_id(self._chat_peer)
conv_set = self._client._conversations[chat_id]
if self._exclusive and conv_set:
raise errors.AlreadyInConversationError()
conv_set.add(self)
self._cancelled = False
self._last_outgoing = 0
self._last_incoming = 0
for d in (
self._outgoing, self._incoming,
self._pending_responses, self._pending_replies,
self._pending_edits, self._response_indices,
self._reply_indices, self._edit_dates, self._custom):
d.clear()
if self._total_timeout:
self._total_due = time.time() + self._total_timeout
else:
self._total_due = float('inf')
return self
def cancel(self):
"""
Cancels the current conversation. Pending responses and subsequent
calls to get a response will raise ``asyncio.CancelledError``.
This method is synchronous and should not be awaited.
"""
self._cancel_all()
async def cancel_all(self):
"""
Calls `cancel` on *all* conversations in this chat.
Note that you should ``await`` this method, since it's meant to be
used outside of a context manager, and it needs to resolve the chat.
"""
chat_id = await self._client.get_peer_id(self._input_chat)
for conv in self._client._conversations[chat_id]:
conv.cancel()
async def __aexit__(self, exc_type, exc_val, exc_tb):
chat_id = utils.get_peer_id(self._chat_peer)
conv_set = self._client._conversations[chat_id]
conv_set.discard(self)
if not conv_set:
del self._client._conversations[chat_id]
self._cancel_all()
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit
|
class Conversation(ChatGetter):
'''
Represents a conversation inside an specific chat.
A conversation keeps track of new messages since it was
created until its exit and easily lets you query the
current state.
If you need a conversation across two or more chats,
you should use two conversations and synchronize them
as you better see fit.
'''
def __init__(self, client, input_chat,
*, timeout, total_timeout, max_messages,
exclusive, replies_are_responses):
pass
@_checks_cancelled
async def send_message(self, *args, **kwargs):
'''
Sends a message in the context of this conversation. Shorthand
for `telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
'''
pass
@_checks_cancelled
async def send_file(self, *args, **kwargs):
'''
Sends a file in the context of this conversation. Shorthand
for `telethon.client.uploads.UploadMethods.send_file` with
``entity`` already set.
'''
pass
@_checks_cancelled
def mark_read(self, message=None):
'''
Marks as read the latest received message if ``message is None``.
Otherwise, marks as read until the given message (or message ID).
This is equivalent to calling `client.send_read_acknowledge
<telethon.client.messages.MessageMethods.send_read_acknowledge>`.
'''
pass
def get_response(self, message=None, *, timeout=None):
'''
Gets the next message that responds to a previous one. This is
the method you need most of the time, along with `get_edit`.
Args:
message (`Message <telethon.tl.custom.message.Message>` | `int`, optional):
The message (or the message ID) for which a response
is expected. By default this is the last sent message.
timeout (`int` | `float`, optional):
If present, this `timeout` (in seconds) will override the
per-action timeout defined for the conversation.
.. code-block:: python
async with client.conversation(...) as conv:
await conv.send_message('Hey, what is your name?')
response = await conv.get_response()
name = response.text
await conv.send_message('Nice to meet you, {}!'.format(name))
'''
pass
def get_reply(self, message=None, *, timeout=None):
'''
Gets the next message that explicitly replies to a previous one.
'''
pass
def _get_message(
self, target_message, indices, pending, timeout, condition):
'''
Gets the next desired message under the desired condition.
Args:
target_message (`object`):
The target message for which we want to find another
response that applies based on `condition`.
indices (`dict`):
This dictionary remembers the last ID chosen for the
input `target_message`.
pending (`dict`):
This dictionary remembers {msg_id: Future} to be set
once `condition` is met.
timeout (`int`):
The timeout (in seconds) override to use for this operation.
condition (`callable`):
The condition callable that checks if an incoming
message is a valid response.
'''
pass
def get_edit(self, message=None, *, timeout=None):
'''
Awaits for an edit after the last message to arrive.
The arguments are the same as those for `get_response`.
'''
pass
def wait_read(self, message=None, *, timeout=None):
'''
Awaits for the sent message to be marked as read. Note that
receiving a response doesn't imply the message was read, and
this action will also trigger even without a response.
'''
pass
async def wait_event(self, event, *, timeout=None):
'''
Waits for a custom event to occur. Timeouts still apply.
.. note::
**Only use this if there isn't another method available!**
For example, don't use `wait_event` for new messages,
since `get_response` already exists, etc.
Unless you're certain that your code will run fast enough,
generally you should get a "handle" of this special coroutine
before acting. In this example you will see how to wait for a user
to join a group with proper use of `wait_event`:
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
group_id = ...
async def main():
# Could also get the user id from an event; this is just an example
user_id = ...
async with client.conversation(user_id) as conv:
# Get a handle to the future event we'll wait for
handle = conv.wait_event(events.ChatAction(
group_id,
func=lambda e: e.user_joined and e.user_id == user_id
))
# Perform whatever action in between
await conv.send_message('Please join this group before speaking to me!')
# Wait for the event we registered above to fire
event = await handle
# Continue with the conversation
await conv.send_message('Thanks!')
This way your event can be registered before acting,
since the response may arrive before your event was
registered. It depends on your use case since this
also means the event can arrive before you send
a previous action.
'''
pass
async def _check_custom(self, built):
pass
def _on_new_message(self, response):
pass
def _on_edit(self, message):
pass
def _on_read(self, event):
pass
def _get_message_id(self, message):
pass
@_checks_cancelled
def _get_result(self, future, start_time, timeout, pending, target_id):
pass
def _cancel_all(self, exception=None):
pass
async def __aenter__(self):
pass
def cancel(self):
'''
Cancels the current conversation. Pending responses and subsequent
calls to get a response will raise ``asyncio.CancelledError``.
This method is synchronous and should not be awaited.
'''
pass
async def cancel_all(self):
'''
Calls `cancel` on *all* conversations in this chat.
Note that you should ``await`` this method, since it's meant to be
used outside of a context manager, and it needs to resolve the chat.
'''
pass
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
| 26 | 12 | 22 | 3 | 12 | 7 | 3 | 0.6 | 1 | 8 | 1 | 0 | 21 | 23 | 21 | 51 | 504 | 95 | 257 | 95 | 228 | 154 | 212 | 87 | 190 | 7 | 5 | 3 | 68 |
146,831 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/adminlogevent.py
|
telethon.tl.custom.adminlogevent.AdminLogEvent
|
class AdminLogEvent:
"""
Represents a more friendly interface for admin log events.
Members:
original (:tl:`ChannelAdminLogEvent`):
The original :tl:`ChannelAdminLogEvent`.
entities (`dict`):
A dictionary mapping user IDs to :tl:`User`.
When `old` and `new` are :tl:`ChannelParticipant`, you can
use this dictionary to map the ``user_id``, ``kicked_by``,
``inviter_id`` and ``promoted_by`` IDs to their :tl:`User`.
user (:tl:`User`):
The user that caused this action (``entities[original.user_id]``).
input_user (:tl:`InputPeerUser`):
Input variant of `user`.
"""
def __init__(self, original, entities):
self.original = original
self.entities = entities
self.user = entities[original.user_id]
self.input_user = get_input_peer(self.user)
@property
def id(self):
"""
The ID of this event.
"""
return self.original.id
@property
def date(self):
"""
The date when this event occurred.
"""
return self.original.date
@property
def user_id(self):
"""
The ID of the user that triggered this event.
"""
return self.original.user_id
@property
def action(self):
"""
The original :tl:`ChannelAdminLogEventAction`.
"""
return self.original.action
@property
def old(self):
"""
The old value from the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUsername,
types.ChannelAdminLogEventActionChangeLocation,
types.ChannelAdminLogEventActionChangeHistoryTTL,
)):
return ori.prev_value
elif isinstance(ori, types.ChannelAdminLogEventActionChangePhoto):
return ori.prev_photo
elif isinstance(ori, types.ChannelAdminLogEventActionChangeStickerSet):
return ori.prev_stickerset
elif isinstance(ori, types.ChannelAdminLogEventActionEditMessage):
return ori.prev_message
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantToggleAdmin,
types.ChannelAdminLogEventActionParticipantToggleBan
)):
return ori.prev_participant
elif isinstance(ori, (
types.ChannelAdminLogEventActionToggleInvites,
types.ChannelAdminLogEventActionTogglePreHistoryHidden,
types.ChannelAdminLogEventActionToggleSignatures
)):
return not ori.new_value
elif isinstance(ori, types.ChannelAdminLogEventActionDeleteMessage):
return ori.message
elif isinstance(ori, types.ChannelAdminLogEventActionDefaultBannedRights):
return ori.prev_banned_rights
elif isinstance(ori, types.ChannelAdminLogEventActionDiscardGroupCall):
return ori.call
elif isinstance(ori, (
types.ChannelAdminLogEventActionExportedInviteDelete,
types.ChannelAdminLogEventActionExportedInviteRevoke,
types.ChannelAdminLogEventActionParticipantJoinByInvite,
)):
return ori.invite
elif isinstance(ori, types.ChannelAdminLogEventActionExportedInviteEdit):
return ori.prev_invite
@property
def new(self):
"""
The new value present in the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUsername,
types.ChannelAdminLogEventActionToggleInvites,
types.ChannelAdminLogEventActionTogglePreHistoryHidden,
types.ChannelAdminLogEventActionToggleSignatures,
types.ChannelAdminLogEventActionChangeLocation,
types.ChannelAdminLogEventActionChangeHistoryTTL,
)):
return ori.new_value
elif isinstance(ori, types.ChannelAdminLogEventActionChangePhoto):
return ori.new_photo
elif isinstance(ori, types.ChannelAdminLogEventActionChangeStickerSet):
return ori.new_stickerset
elif isinstance(ori, types.ChannelAdminLogEventActionEditMessage):
return ori.new_message
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantToggleAdmin,
types.ChannelAdminLogEventActionParticipantToggleBan
)):
return ori.new_participant
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantInvite,
types.ChannelAdminLogEventActionParticipantVolume,
)):
return ori.participant
elif isinstance(ori, types.ChannelAdminLogEventActionDefaultBannedRights):
return ori.new_banned_rights
elif isinstance(ori, types.ChannelAdminLogEventActionStopPoll):
return ori.message
elif isinstance(ori, types.ChannelAdminLogEventActionStartGroupCall):
return ori.call
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantMute,
types.ChannelAdminLogEventActionParticipantUnmute,
)):
return ori.participant
elif isinstance(ori, types.ChannelAdminLogEventActionToggleGroupCallSetting):
return ori.join_muted
elif isinstance(ori, types.ChannelAdminLogEventActionExportedInviteEdit):
return ori.new_invite
@property
def changed_about(self):
"""
Whether the channel's about was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeAbout)
@property
def changed_title(self):
"""
Whether the channel's title was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeTitle)
@property
def changed_username(self):
"""
Whether the channel's username was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeUsername)
@property
def changed_photo(self):
"""
Whether the channel's photo was changed or not.
If `True`, `old` and `new` will be present as :tl:`Photo`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangePhoto)
@property
def changed_sticker_set(self):
"""
Whether the channel's sticker set was changed or not.
If `True`, `old` and `new` will be present as :tl:`InputStickerSet`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeStickerSet)
@property
def changed_message(self):
"""
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionEditMessage)
@property
def deleted_message(self):
"""
Whether a message in this channel was deleted or not.
If `True`, `old` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDeleteMessage)
@property
def changed_admin(self):
"""
Whether the permissions for an admin in this channel
changed or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(
self.original.action,
types.ChannelAdminLogEventActionParticipantToggleAdmin)
@property
def changed_restrictions(self):
"""
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(
self.original.action,
types.ChannelAdminLogEventActionParticipantToggleBan)
@property
def changed_invites(self):
"""
Whether the invites in the channel were toggled or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleInvites)
@property
def changed_location(self):
"""
Whether the location setting of the channel has changed or not.
If `True`, `old` and `new` will be present as :tl:`ChannelLocation`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeLocation)
@property
def joined(self):
"""
Whether `user` joined through the channel's
public username or not.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantJoin)
@property
def joined_invite(self):
"""
Whether a new user joined through an invite
link to the channel or not.
If `True`, `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantInvite)
@property
def left(self):
"""
Whether `user` left the channel or not.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantLeave)
@property
def changed_hide_history(self):
"""
Whether hiding the previous message history for new members
in the channel was toggled or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionTogglePreHistoryHidden)
@property
def changed_signatures(self):
"""
Whether the message signatures in the channel were toggled
or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleSignatures)
@property
def changed_pin(self):
"""
Whether a new message in this channel was pinned or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionUpdatePinned)
@property
def changed_default_banned_rights(self):
"""
Whether the default banned rights were changed or not.
If `True`, `old` and `new` will
be present as :tl:`ChatBannedRights`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDefaultBannedRights)
@property
def stopped_poll(self):
"""
Whether a poll was stopped or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionStopPoll)
@property
def started_group_call(self):
"""
Whether a group call was started or not.
If `True`, `new` will be present as :tl:`InputGroupCall`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionStartGroupCall)
@property
def discarded_group_call(self):
"""
Whether a group call was started or not.
If `True`, `old` will be present as :tl:`InputGroupCall`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDiscardGroupCall)
@property
def user_muted(self):
"""
Whether a participant was muted in the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantMute)
@property
def user_unmutted(self):
"""
Whether a participant was unmuted from the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantUnmute)
@property
def changed_call_settings(self):
"""
Whether the group call settings were changed or not.
If `True`, `new` will be `True` if new users are muted on join.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleGroupCallSetting)
@property
def changed_history_ttl(self):
"""
Whether the Time To Live of the message history has changed.
Messages sent after this change will have a ``ttl_period`` in seconds
indicating how long they should live for before being auto-deleted.
If `True`, `old` will be the old TTL, and `new` the new TTL, in seconds.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeHistoryTTL)
@property
def deleted_exported_invite(self):
"""
Whether the exported chat invite has been deleted.
If `True`, `old` will be the deleted :tl:`ExportedChatInvite`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteDelete)
@property
def edited_exported_invite(self):
"""
Whether the exported chat invite has been edited.
If `True`, `old` and `new` will be the old and new
:tl:`ExportedChatInvite`, respectively.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteEdit)
@property
def revoked_exported_invite(self):
"""
Whether the exported chat invite has been revoked.
If `True`, `old` will be the revoked :tl:`ExportedChatInvite`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteRevoke)
@property
def joined_by_invite(self):
"""
Whether a new participant has joined with the use of an invite link.
If `True`, `old` will be pre-existing (old) :tl:`ExportedChatInvite`
used to join.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantJoinByInvite)
@property
def changed_user_volume(self):
"""
Whether a participant's volume in a call has been changed.
If `True`, `new` will be the updated :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantVolume)
def __str__(self):
return str(self.original)
def stringify(self):
return self.original.stringify()
|
class AdminLogEvent:
'''
Represents a more friendly interface for admin log events.
Members:
original (:tl:`ChannelAdminLogEvent`):
The original :tl:`ChannelAdminLogEvent`.
entities (`dict`):
A dictionary mapping user IDs to :tl:`User`.
When `old` and `new` are :tl:`ChannelParticipant`, you can
use this dictionary to map the ``user_id``, ``kicked_by``,
``inviter_id`` and ``promoted_by`` IDs to their :tl:`User`.
user (:tl:`User`):
The user that caused this action (``entities[original.user_id]``).
input_user (:tl:`InputPeerUser`):
Input variant of `user`.
'''
def __init__(self, original, entities):
pass
@property
def id(self):
'''
The ID of this event.
'''
pass
@property
def date(self):
'''
The date when this event occurred.
'''
pass
@property
def user_id(self):
'''
The ID of the user that triggered this event.
'''
pass
@property
def action(self):
'''
The original :tl:`ChannelAdminLogEventAction`.
'''
pass
@property
def old(self):
'''
The old value from the event.
'''
pass
@property
def new(self):
'''
The new value present in the event.
'''
pass
@property
def changed_about(self):
'''
Whether the channel's about was changed or not.
If `True`, `old` and `new` will be present as `str`.
'''
pass
@property
def changed_title(self):
'''
Whether the channel's title was changed or not.
If `True`, `old` and `new` will be present as `str`.
'''
pass
@property
def changed_username(self):
'''
Whether the channel's username was changed or not.
If `True`, `old` and `new` will be present as `str`.
'''
pass
@property
def changed_photo(self):
'''
Whether the channel's photo was changed or not.
If `True`, `old` and `new` will be present as :tl:`Photo`.
'''
pass
@property
def changed_sticker_set(self):
'''
Whether the channel's sticker set was changed or not.
If `True`, `old` and `new` will be present as :tl:`InputStickerSet`.
'''
pass
@property
def changed_message(self):
'''
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
'''
pass
@property
def deleted_message(self):
'''
Whether a message in this channel was deleted or not.
If `True`, `old` will be present as
`Message <telethon.tl.custom.message.Message>`.
'''
pass
@property
def changed_admin(self):
'''
Whether the permissions for an admin in this channel
changed or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
'''
pass
@property
def changed_restrictions(self):
'''
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
'''
pass
@property
def changed_invites(self):
'''
Whether the invites in the channel were toggled or not.
If `True`, `old` and `new` will be present as `bool`.
'''
pass
@property
def changed_location(self):
'''
Whether the location setting of the channel has changed or not.
If `True`, `old` and `new` will be present as :tl:`ChannelLocation`.
'''
pass
@property
def joined(self):
'''
Whether `user` joined through the channel's
public username or not.
'''
pass
@property
def joined_invite(self):
'''
Whether a new user joined through an invite
link to the channel or not.
If `True`, `new` will be present as
:tl:`ChannelParticipant`.
'''
pass
@property
def left(self):
'''
Whether `user` left the channel or not.
'''
pass
@property
def changed_hide_history(self):
'''
Whether hiding the previous message history for new members
in the channel was toggled or not.
If `True`, `old` and `new` will be present as `bool`.
'''
pass
@property
def changed_signatures(self):
'''
Whether the message signatures in the channel were toggled
or not.
If `True`, `old` and `new` will be present as `bool`.
'''
pass
@property
def changed_pin(self):
'''
Whether a new message in this channel was pinned or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
'''
pass
@property
def changed_default_banned_rights(self):
'''
Whether the default banned rights were changed or not.
If `True`, `old` and `new` will
be present as :tl:`ChatBannedRights`.
'''
pass
@property
def stopped_poll(self):
'''
Whether a poll was stopped or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
'''
pass
@property
def started_group_call(self):
'''
Whether a group call was started or not.
If `True`, `new` will be present as :tl:`InputGroupCall`.
'''
pass
@property
def discarded_group_call(self):
'''
Whether a group call was started or not.
If `True`, `old` will be present as :tl:`InputGroupCall`.
'''
pass
@property
def user_muted(self):
'''
Whether a participant was muted in the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
'''
pass
@property
def user_unmutted(self):
'''
Whether a participant was unmuted from the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
'''
pass
@property
def changed_call_settings(self):
'''
Whether the group call settings were changed or not.
If `True`, `new` will be `True` if new users are muted on join.
'''
pass
@property
def changed_history_ttl(self):
'''
Whether the Time To Live of the message history has changed.
Messages sent after this change will have a ``ttl_period`` in seconds
indicating how long they should live for before being auto-deleted.
If `True`, `old` will be the old TTL, and `new` the new TTL, in seconds.
'''
pass
@property
def deleted_exported_invite(self):
'''
Whether the exported chat invite has been deleted.
If `True`, `old` will be the deleted :tl:`ExportedChatInvite`.
'''
pass
@property
def edited_exported_invite(self):
'''
Whether the exported chat invite has been edited.
If `True`, `old` and `new` will be the old and new
:tl:`ExportedChatInvite`, respectively.
'''
pass
@property
def revoked_exported_invite(self):
'''
Whether the exported chat invite has been revoked.
If `True`, `old` will be the revoked :tl:`ExportedChatInvite`.
'''
pass
@property
def joined_by_invite(self):
'''
Whether a new participant has joined with the use of an invite link.
If `True`, `old` will be pre-existing (old) :tl:`ExportedChatInvite`
used to join.
'''
pass
@property
def changed_user_volume(self):
'''
Whether a participant's volume in a call has been changed.
If `True`, `new` will be the updated :tl:`GroupCallParticipant`.
'''
pass
def __str__(self):
pass
def stringify(self):
pass
| 76 | 37 | 10 | 1 | 5 | 4 | 2 | 0.73 | 0 | 1 | 0 | 0 | 39 | 4 | 39 | 39 | 471 | 72 | 231 | 82 | 155 | 168 | 107 | 46 | 67 | 13 | 0 | 1 | 62 |
146,832 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon/tl/custom/dialog.py
|
telethon.tl.custom.dialog.Dialog
|
class Dialog:
"""
Custom class that encapsulates a dialog (an open "conversation" with
someone, a group or a channel) providing an abstraction to easily
access the input version/normal entity/message etc. The library will
return instances of this class when calling :meth:`.get_dialogs()`.
Args:
dialog (:tl:`Dialog`):
The original ``Dialog`` instance.
pinned (`bool`):
Whether this dialog is pinned to the top or not.
folder_id (`folder_id`):
The folder ID that this dialog belongs to.
archived (`bool`):
Whether this dialog is archived or not (``folder_id is None``).
message (`Message <telethon.tl.custom.message.Message>`):
The last message sent on this dialog. Note that this member
will not be updated when new messages arrive, it's only set
on creation of the instance.
date (`datetime`):
The date of the last message sent on this dialog.
entity (`entity`):
The entity that belongs to this dialog (user, chat or channel).
input_entity (:tl:`InputPeer`):
Input version of the entity.
id (`int`):
The marked ID of the entity, which is guaranteed to be unique.
name (`str`):
Display name for this dialog. For chats and channels this is
their title, and for users it's "First-Name Last-Name".
title (`str`):
Alias for `name`.
unread_count (`int`):
How many messages are currently unread in this dialog. Note that
this value won't update when new messages arrive.
unread_mentions_count (`int`):
How many mentions are currently unread in this dialog. Note that
this value won't update when new messages arrive.
draft (`Draft <telethon.tl.custom.draft.Draft>`):
The draft object in this dialog. It will not be `None`,
so you can call ``draft.set_message(...)``.
is_user (`bool`):
`True` if the `entity` is a :tl:`User`.
is_group (`bool`):
`True` if the `entity` is a :tl:`Chat`
or a :tl:`Channel` megagroup.
is_channel (`bool`):
`True` if the `entity` is a :tl:`Channel`.
"""
def __init__(self, client, dialog, entities, message):
# Both entities and messages being dicts {ID: item}
self._client = client
self.dialog = dialog
self.pinned = bool(dialog.pinned)
self.folder_id = dialog.folder_id
self.archived = dialog.folder_id is not None
self.message = message
self.date = getattr(self.message, 'date', None)
self.entity = entities[utils.get_peer_id(dialog.peer)]
self.input_entity = utils.get_input_peer(self.entity)
self.id = utils.get_peer_id(self.entity) # ^ May be InputPeerSelf()
self.name = self.title = utils.get_display_name(self.entity)
self.unread_count = dialog.unread_count
self.unread_mentions_count = dialog.unread_mentions_count
self.draft = Draft(client, self.entity, self.dialog.draft)
self.is_user = isinstance(self.entity, types.User)
self.is_group = (
isinstance(self.entity, (types.Chat, types.ChatForbidden)) or
(isinstance(self.entity, types.Channel) and self.entity.megagroup)
)
self.is_channel = isinstance(self.entity, types.Channel)
async def send_message(self, *args, **kwargs):
"""
Sends a message to this dialog. This is just a wrapper around
``client.send_message(dialog.input_entity, *args, **kwargs)``.
"""
return await self._client.send_message(
self.input_entity, *args, **kwargs)
async def delete(self, revoke=False):
"""
Deletes the dialog from your dialog list. If you own the
channel this won't destroy it, only delete it from the list.
Shorthand for `telethon.client.dialogs.DialogMethods.delete_dialog`
with ``entity`` already set.
"""
# Pass the entire entity so the method can determine whether
# the `Chat` is deactivated (in which case we don't kick ourselves,
# or it would raise `PEER_ID_INVALID`).
await self._client.delete_dialog(self.entity, revoke=revoke)
async def archive(self, folder=1):
"""
Archives (or un-archives) this dialog.
Args:
folder (`int`, optional):
The folder to which the dialog should be archived to.
If you want to "un-archive" it, use ``folder=0``.
Returns:
The :tl:`Updates` object that the request produces.
Example:
.. code-block:: python
# Archiving
dialog.archive()
# Un-archiving
dialog.archive(0)
"""
return await self._client(functions.folders.EditPeerFoldersRequest([
types.InputFolderPeer(self.input_entity, folder_id=folder)
]))
def to_dict(self):
return {
'_': 'Dialog',
'name': self.name,
'date': self.date,
'draft': self.draft,
'message': self.message,
'entity': self.entity,
}
def __str__(self):
return TLObject.pretty_format(self.to_dict())
def stringify(self):
return TLObject.pretty_format(self.to_dict(), indent=0)
|
class Dialog:
'''
Custom class that encapsulates a dialog (an open "conversation" with
someone, a group or a channel) providing an abstraction to easily
access the input version/normal entity/message etc. The library will
return instances of this class when calling :meth:`.get_dialogs()`.
Args:
dialog (:tl:`Dialog`):
The original ``Dialog`` instance.
pinned (`bool`):
Whether this dialog is pinned to the top or not.
folder_id (`folder_id`):
The folder ID that this dialog belongs to.
archived (`bool`):
Whether this dialog is archived or not (``folder_id is None``).
message (`Message <telethon.tl.custom.message.Message>`):
The last message sent on this dialog. Note that this member
will not be updated when new messages arrive, it's only set
on creation of the instance.
date (`datetime`):
The date of the last message sent on this dialog.
entity (`entity`):
The entity that belongs to this dialog (user, chat or channel).
input_entity (:tl:`InputPeer`):
Input version of the entity.
id (`int`):
The marked ID of the entity, which is guaranteed to be unique.
name (`str`):
Display name for this dialog. For chats and channels this is
their title, and for users it's "First-Name Last-Name".
title (`str`):
Alias for `name`.
unread_count (`int`):
How many messages are currently unread in this dialog. Note that
this value won't update when new messages arrive.
unread_mentions_count (`int`):
How many mentions are currently unread in this dialog. Note that
this value won't update when new messages arrive.
draft (`Draft <telethon.tl.custom.draft.Draft>`):
The draft object in this dialog. It will not be `None`,
so you can call ``draft.set_message(...)``.
is_user (`bool`):
`True` if the `entity` is a :tl:`User`.
is_group (`bool`):
`True` if the `entity` is a :tl:`Chat`
or a :tl:`Channel` megagroup.
is_channel (`bool`):
`True` if the `entity` is a :tl:`Channel`.
'''
def __init__(self, client, dialog, entities, message):
pass
async def send_message(self, *args, **kwargs):
'''
Sends a message to this dialog. This is just a wrapper around
``client.send_message(dialog.input_entity, *args, **kwargs)``.
'''
pass
async def delete(self, revoke=False):
'''
Deletes the dialog from your dialog list. If you own the
channel this won't destroy it, only delete it from the list.
Shorthand for `telethon.client.dialogs.DialogMethods.delete_dialog`
with ``entity`` already set.
'''
pass
async def archive(self, folder=1):
'''
Archives (or un-archives) this dialog.
Args:
folder (`int`, optional):
The folder to which the dialog should be archived to.
If you want to "un-archive" it, use ``folder=0``.
Returns:
The :tl:`Updates` object that the request produces.
Example:
.. code-block:: python
# Archiving
dialog.archive()
# Un-archiving
dialog.archive(0)
'''
pass
def to_dict(self):
pass
def __str__(self):
pass
def stringify(self):
pass
| 8 | 4 | 12 | 2 | 6 | 4 | 1 | 1.77 | 0 | 1 | 0 | 0 | 7 | 18 | 7 | 7 | 156 | 35 | 44 | 25 | 36 | 78 | 31 | 25 | 23 | 1 | 0 | 0 | 7 |
146,833 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/sourcebuilder.py
|
telethon_generator.sourcebuilder.SourceBuilder
|
class SourceBuilder:
"""This class should be used to build .py source files"""
def __init__(self, out_stream, indent_size=4):
self.current_indent = 0
self.on_new_line = False
self.indent_size = indent_size
self.out_stream = out_stream
# Was a new line added automatically before? If so, avoid it
self.auto_added_line = False
def indent(self):
"""Indents the current source code line
by the current indentation level
"""
self.write(' ' * (self.current_indent * self.indent_size))
def write(self, string, *args, **kwargs):
"""Writes a string into the source code,
applying indentation if required
"""
if self.on_new_line:
self.on_new_line = False # We're not on a new line anymore
# If the string was not empty, indent; Else probably a new line
if string.strip():
self.indent()
if args or kwargs:
self.out_stream.write(string.format(*args, **kwargs))
else:
self.out_stream.write(string)
def writeln(self, string='', *args, **kwargs):
"""Writes a string into the source code _and_ appends a new line,
applying indentation if required
"""
self.write(string + '\n', *args, **kwargs)
self.on_new_line = True
# If we're writing a block, increment indent for the next time
if string and string[-1] == ':':
self.current_indent += 1
# Clear state after the user adds a new line
self.auto_added_line = False
def end_block(self):
"""Ends an indentation block, leaving an empty line afterwards"""
self.current_indent -= 1
# If we did not add a new line automatically yet, now it's the time!
if not self.auto_added_line:
self.writeln()
self.auto_added_line = True
def __str__(self):
self.out_stream.seek(0)
return self.out_stream.read()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.out_stream.close()
|
class SourceBuilder:
'''This class should be used to build .py source files'''
def __init__(self, out_stream, indent_size=4):
pass
def indent(self):
'''Indents the current source code line
by the current indentation level
'''
pass
def write(self, string, *args, **kwargs):
'''Writes a string into the source code,
applying indentation if required
'''
pass
def writeln(self, string='', *args, **kwargs):
'''Writes a string into the source code _and_ appends a new line,
applying indentation if required
'''
pass
def end_block(self):
'''Ends an indentation block, leaving an empty line afterwards'''
pass
def __str__(self):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 9 | 5 | 7 | 1 | 4 | 2 | 2 | 0.47 | 0 | 0 | 0 | 0 | 8 | 5 | 8 | 8 | 65 | 13 | 36 | 14 | 27 | 17 | 35 | 14 | 26 | 4 | 0 | 2 | 13 |
146,834 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/tests/telethon/test_helpers.py
|
tests.telethon.test_helpers.TestSyncifyAsyncContext
|
class TestSyncifyAsyncContext:
class NoopContextManager:
def __init__(self, loop):
self.count = 0
self.loop = loop
async def __aenter__(self):
self.count += 1
return self
async def __aexit__(self, exc_type, *args):
assert exc_type is None
self.count -= 1
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit
def test_sync_acontext(self, event_loop):
contm = self.NoopContextManager(event_loop)
assert contm.count == 0
with contm:
assert contm.count == 1
assert contm.count == 0
@pytest.mark.asyncio
async def test_async_acontext(self, event_loop):
contm = self.NoopContextManager(event_loop)
assert contm.count == 0
async with contm:
assert contm.count == 1
assert contm.count == 0
|
class TestSyncifyAsyncContext:
class NoopContextManager:
def __init__(self, loop):
pass
async def __aenter__(self):
pass
async def __aexit__(self, exc_type, *args):
pass
def test_sync_acontext(self, event_loop):
pass
@pytest.mark.asyncio
async def test_async_acontext(self, event_loop):
pass
| 8 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 35 | 9 | 26 | 14 | 18 | 0 | 25 | 13 | 18 | 1 | 0 | 1 | 5 |
146,835 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/tests/telethon/client/test_messages.py
|
tests.telethon.client.test_messages.test_send_message_with_file_forwards_args.MockedClient
|
class MockedClient(TelegramClient):
# noinspection PyMissingConstructor
def __init__(self):
pass
async def send_file(self, entity, file, **kwargs):
assert entity == 'a'
assert file == 'b'
for k, v in arguments.items():
assert k in kwargs
assert kwargs[k] == v
return sentinel
|
class MockedClient(TelegramClient):
def __init__(self):
pass
async def send_file(self, entity, file, **kwargs):
pass
| 3 | 0 | 5 | 1 | 5 | 0 | 2 | 0.1 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 13 | 2 | 10 | 4 | 7 | 1 | 10 | 4 | 7 | 2 | 2 | 1 | 3 |
146,836 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/tests/telethon/client/test_messages.py
|
tests.telethon.client.test_messages.TestMessageMethods
|
class TestMessageMethods:
@pytest.mark.asyncio
@pytest.mark.parametrize(
'formatting_entities',
([MessageEntityBold(offset=0, length=0)], None)
)
async def test_send_msg_and_file(self, formatting_entities):
async def async_func(result): # AsyncMock was added only in 3.8
return result
msg_methods = MessageMethods()
expected_result = Message(
id=0, peer_id=PeerChat(chat_id=0), message='', date=None,
)
entity = 'test_entity'
message = Message(
id=1, peer_id=PeerChat(chat_id=0), message='expected_caption', date=None,
entities=[MessageEntityBold(offset=9, length=9)],
)
media_file = MessageMediaDocument()
with mock.patch.object(
target=MessageMethods, attribute='send_file',
new=MagicMock(return_value=async_func(expected_result)), create=True,
) as mock_obj:
result = await msg_methods.send_message(
entity=entity, message=message, file=media_file,
formatting_entities=formatting_entities,
)
mock_obj.assert_called_once_with(
entity, media_file, caption=message.message,
formatting_entities=formatting_entities or message.entities,
reply_to=None, silent=None, attributes=None, parse_mode=(),
force_document=False, thumb=None, buttons=None,
clear_draft=False, schedule=None, supports_streaming=False,
comment_to=None, background=None, nosound_video=None,
)
assert result == expected_result
|
class TestMessageMethods:
@pytest.mark.asyncio
@pytest.mark.parametrize(
'formatting_entities',
([MessageEntityBold(offset=0, length=0)], None)
)
async def test_send_msg_and_file(self, formatting_entities):
pass
async def async_func(result):
pass
| 5 | 0 | 17 | 1 | 16 | 1 | 1 | 0.03 | 0 | 2 | 1 | 0 | 1 | 0 | 1 | 1 | 37 | 1 | 36 | 11 | 28 | 1 | 13 | 9 | 10 | 1 | 0 | 1 | 2 |
146,837 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/sessions/sqlite.py
|
telethon.sessions.sqlite.SQLiteSession
|
class SQLiteSession(MemorySession):
"""This session contains the required information to login into your
Telegram account. NEVER give the saved session file to anyone, since
they would gain instant access to all your messages and contacts.
If you think the session has been compromised, close all the sessions
through an official Telegram client to revoke the authorization.
"""
def __init__(self, session_id=None):
if sqlite3 is None:
raise sqlite3_err
super().__init__()
self.filename = ':memory:'
self.save_entities = True
if session_id:
self.filename = session_id
if not self.filename.endswith(EXTENSION):
self.filename += EXTENSION
self._conn = None
c = self._cursor()
c.execute("select name from sqlite_master "
"where type='table' and name='version'")
if c.fetchone():
# Tables already exist, check for the version
c.execute("select version from version")
version = c.fetchone()[0]
if version < CURRENT_VERSION:
self._upgrade_database(old=version)
c.execute("delete from version")
c.execute("insert into version values (?)", (CURRENT_VERSION,))
self.save()
# These values will be saved
c.execute('select * from sessions')
tuple_ = c.fetchone()
if tuple_:
self._dc_id, self._server_address, self._port, key, \
self._takeout_id = tuple_
self._auth_key = AuthKey(data=key)
c.close()
else:
# Tables don't exist, create new ones
self._create_table(
c,
"version (version integer primary key)",
"""sessions (
dc_id integer primary key,
server_address text,
port integer,
auth_key blob,
takeout_id integer
)""",
"""entities (
id integer primary key,
hash integer not null,
username text,
phone integer,
name text,
date integer
)""",
"""sent_files (
md5_digest blob,
file_size integer,
type integer,
id integer,
hash integer,
primary key(md5_digest, file_size, type)
)""",
"""update_state (
id integer primary key,
pts integer,
qts integer,
date integer,
seq integer
)"""
)
c.execute("insert into version values (?)", (CURRENT_VERSION,))
self._update_session_table()
c.close()
self.save()
def clone(self, to_instance=None):
cloned = super().clone(to_instance)
cloned.save_entities = self.save_entities
return cloned
def _upgrade_database(self, old):
c = self._cursor()
if old == 1:
old += 1
# old == 1 doesn't have the old sent_files so no need to drop
if old == 2:
old += 1
# Old cache from old sent_files lasts then a day anyway, drop
c.execute('drop table sent_files')
self._create_table(c, """sent_files (
md5_digest blob,
file_size integer,
type integer,
id integer,
hash integer,
primary key(md5_digest, file_size, type)
)""")
if old == 3:
old += 1
self._create_table(c, """update_state (
id integer primary key,
pts integer,
qts integer,
date integer,
seq integer
)""")
if old == 4:
old += 1
c.execute("alter table sessions add column takeout_id integer")
if old == 5:
# Not really any schema upgrade, but potentially all access
# hashes for User and Channel are wrong, so drop them off.
old += 1
c.execute('delete from entities')
if old == 6:
old += 1
c.execute("alter table entities add column date integer")
c.close()
@staticmethod
def _create_table(c, *definitions):
for definition in definitions:
c.execute('create table {}'.format(definition))
# Data from sessions should be kept as properties
# not to fetch the database every time we need it
def set_dc(self, dc_id, server_address, port):
super().set_dc(dc_id, server_address, port)
self._update_session_table()
# Fetch the auth_key corresponding to this data center
row = self._execute('select auth_key from sessions')
if row and row[0]:
self._auth_key = AuthKey(data=row[0])
else:
self._auth_key = None
@MemorySession.auth_key.setter
def auth_key(self, value):
self._auth_key = value
self._update_session_table()
@MemorySession.takeout_id.setter
def takeout_id(self, value):
self._takeout_id = value
self._update_session_table()
def _update_session_table(self):
c = self._cursor()
# While we can save multiple rows into the sessions table
# currently we only want to keep ONE as the tables don't
# tell us which auth_key's are usable and will work. Needs
# some more work before being able to save auth_key's for
# multiple DCs. Probably done differently.
c.execute('delete from sessions')
c.execute('insert or replace into sessions values (?,?,?,?,?)', (
self._dc_id,
self._server_address,
self._port,
self._auth_key.key if self._auth_key else b'',
self._takeout_id
))
c.close()
def get_update_state(self, entity_id):
row = self._execute('select pts, qts, date, seq from update_state '
'where id = ?', entity_id)
if row:
pts, qts, date, seq = row
date = datetime.datetime.fromtimestamp(
date, tz=datetime.timezone.utc)
return types.updates.State(pts, qts, date, seq, unread_count=0)
def set_update_state(self, entity_id, state):
self._execute('insert or replace into update_state values (?,?,?,?,?)',
entity_id, state.pts, state.qts,
state.date.timestamp(), state.seq)
def get_update_states(self):
c = self._cursor()
try:
rows = c.execute(
'select id, pts, qts, date, seq from update_state').fetchall()
return ((row[0], types.updates.State(
pts=row[1],
qts=row[2],
date=datetime.datetime.fromtimestamp(
row[3], tz=datetime.timezone.utc),
seq=row[4],
unread_count=0)
) for row in rows)
finally:
c.close()
def save(self):
"""Saves the current session object as session_user_id.session"""
# This is a no-op if there are no changes to commit, so there's
# no need for us to keep track of an "unsaved changes" variable.
if self._conn is not None:
self._conn.commit()
def _cursor(self):
"""Asserts that the connection is open and returns a cursor"""
if self._conn is None:
self._conn = sqlite3.connect(self.filename,
check_same_thread=False)
return self._conn.cursor()
def _execute(self, stmt, *values):
"""
Gets a cursor, executes `stmt` and closes the cursor,
fetching one row afterwards and returning its result.
"""
c = self._cursor()
try:
return c.execute(stmt, values).fetchone()
finally:
c.close()
def close(self):
"""Closes the connection unless we're working in-memory"""
if self.filename != ':memory:':
if self._conn is not None:
self._conn.commit()
self._conn.close()
self._conn = None
def delete(self):
"""Deletes the current session file"""
if self.filename == ':memory:':
return True
try:
os.remove(self.filename)
return True
except OSError:
return False
@classmethod
def list_sessions(cls):
"""Lists all the sessions of the users who have ever connected
using this client and never logged out
"""
return [os.path.splitext(os.path.basename(f))[0]
for f in os.listdir('.') if f.endswith(EXTENSION)]
# Entity processing
def process_entities(self, tlo):
"""
Processes all the found entities on the given TLObject,
unless .save_entities is False.
"""
if not self.save_entities:
return
rows = self._entities_to_rows(tlo)
if not rows:
return
c = self._cursor()
try:
now_tup = (int(time.time()),)
rows = [row + now_tup for row in rows]
c.executemany(
'insert or replace into entities values (?,?,?,?,?,?)', rows)
finally:
c.close()
def get_entity_rows_by_phone(self, phone):
return self._execute(
'select id, hash from entities where phone = ?', phone)
def get_entity_rows_by_username(self, username):
c = self._cursor()
try:
results = c.execute(
'select id, hash, date from entities where username = ?',
(username,)
).fetchall()
if not results:
return None
# If there is more than one result for the same username, evict the oldest one
if len(results) > 1:
results.sort(key=lambda t: t[2] or 0)
c.executemany('update entities set username = null where id = ?',
[(t[0],) for t in results[:-1]])
return results[-1][0], results[-1][1]
finally:
c.close()
def get_entity_rows_by_name(self, name):
return self._execute(
'select id, hash from entities where name = ?', name)
def get_entity_rows_by_id(self, id, exact=True):
if exact:
return self._execute(
'select id, hash from entities where id = ?', id)
else:
return self._execute(
'select id, hash from entities where id in (?,?,?)',
utils.get_peer_id(PeerUser(id)),
utils.get_peer_id(PeerChat(id)),
utils.get_peer_id(PeerChannel(id))
)
# File processing
def get_file(self, md5_digest, file_size, cls):
row = self._execute(
'select id, hash from sent_files '
'where md5_digest = ? and file_size = ? and type = ?',
md5_digest, file_size, _SentFileType.from_type(cls).value
)
if row:
# Both allowed classes have (id, access_hash) as parameters
return cls(row[0], row[1])
def cache_file(self, md5_digest, file_size, instance):
if not isinstance(instance, (InputDocument, InputPhoto)):
raise TypeError('Cannot cache %s instance' % type(instance))
self._execute(
'insert or replace into sent_files values (?,?,?,?,?)',
md5_digest, file_size,
_SentFileType.from_type(type(instance)).value,
instance.id, instance.access_hash
)
|
class SQLiteSession(MemorySession):
'''This session contains the required information to login into your
Telegram account. NEVER give the saved session file to anyone, since
they would gain instant access to all your messages and contacts.
If you think the session has been compromised, close all the sessions
through an official Telegram client to revoke the authorization.
'''
def __init__(self, session_id=None):
pass
def clone(self, to_instance=None):
pass
def _upgrade_database(self, old):
pass
@staticmethod
def _create_table(c, *definitions):
pass
def set_dc(self, dc_id, server_address, port):
pass
@MemorySession.auth_key.setter
def auth_key(self, value):
pass
@MemorySession.takeout_id.setter
def takeout_id(self, value):
pass
def _update_session_table(self):
pass
def get_update_state(self, entity_id):
pass
def set_update_state(self, entity_id, state):
pass
def get_update_states(self):
pass
def save(self):
'''Saves the current session object as session_user_id.session'''
pass
def _cursor(self):
'''Asserts that the connection is open and returns a cursor'''
pass
def _execute(self, stmt, *values):
'''
Gets a cursor, executes `stmt` and closes the cursor,
fetching one row afterwards and returning its result.
'''
pass
def close(self):
'''Closes the connection unless we're working in-memory'''
pass
def delete(self):
'''Deletes the current session file'''
pass
@classmethod
def list_sessions(cls):
'''Lists all the sessions of the users who have ever connected
using this client and never logged out
'''
pass
def process_entities(self, tlo):
'''
Processes all the found entities on the given TLObject,
unless .save_entities is False.
'''
pass
def get_entity_rows_by_phone(self, phone):
pass
def get_entity_rows_by_username(self, username):
pass
def get_entity_rows_by_name(self, name):
pass
def get_entity_rows_by_id(self, id, exact=True):
pass
def get_file(self, md5_digest, file_size, cls):
pass
def cache_file(self, md5_digest, file_size, instance):
pass
| 29 | 8 | 13 | 1 | 11 | 1 | 2 | 0.16 | 1 | 7 | 1 | 0 | 22 | 8 | 24 | 91 | 345 | 40 | 263 | 54 | 234 | 42 | 160 | 49 | 135 | 7 | 6 | 2 | 53 |
146,838 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/network/connection/connection.py
|
telethon.network.connection.connection.Connection._proxy_connect.ConnectionErrorExtra
|
class ConnectionErrorExtra(ConnectionError):
def __init__(self, message, error_code=None):
super().__init__(message)
self.error_code = error_code
|
class ConnectionErrorExtra(ConnectionError):
def __init__(self, message, error_code=None):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 15 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
146,839 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/telethon/events/userupdate.py
|
telethon.events.userupdate.UserUpdate.Event
|
class Event(EventCommon, SenderGetter):
"""
Represents the event of a user update
such as gone online, started typing, etc.
Members:
status (:tl:`UserStatus`, optional):
The user status if the update is about going online or offline.
You should check this attribute first before checking any
of the seen within properties, since they will all be `None`
if the status is not set.
action (:tl:`SendMessageAction`, optional):
The "typing" action if any the user is performing if any.
You should check this attribute first before checking any
of the typing properties, since they will all be `None`
if the action is not set.
"""
def __init__(self, peer, *, status=None, chat_peer=None, typing=None):
super().__init__(chat_peer or peer)
SenderGetter.__init__(self, utils.get_peer_id(peer))
self.status = status
self.action = typing
def _set_client(self, client):
super()._set_client(client)
self._sender, self._input_sender = utils._get_entity_pair(
self.sender_id, self._entities, client._mb_entity_cache)
@property
def user(self):
"""Alias for `sender <telethon.tl.custom.sendergetter.SenderGetter.sender>`."""
return self.sender
async def get_user(self):
"""Alias for `get_sender <telethon.tl.custom.sendergetter.SenderGetter.get_sender>`."""
return await self.get_sender()
@property
def input_user(self):
"""Alias for `input_sender <telethon.tl.custom.sendergetter.SenderGetter.input_sender>`."""
return self.input_sender
async def get_input_user(self):
"""Alias for `get_input_sender <telethon.tl.custom.sendergetter.SenderGetter.get_input_sender>`."""
return await self.get_input_sender()
@property
def user_id(self):
"""Alias for `sender_id <telethon.tl.custom.sendergetter.SenderGetter.sender_id>`."""
return self.sender_id
@property
@_requires_action
def typing(self):
"""
`True` if the action is typing a message.
"""
return isinstance(self.action, types.SendMessageTypingAction)
@property
@_requires_action
def uploading(self):
"""
`True` if the action is uploading something.
"""
return isinstance(self.action, (
types.SendMessageChooseContactAction,
types.SendMessageChooseStickerAction,
types.SendMessageUploadAudioAction,
types.SendMessageUploadDocumentAction,
types.SendMessageUploadPhotoAction,
types.SendMessageUploadRoundAction,
types.SendMessageUploadVideoAction
))
@property
@_requires_action
def recording(self):
"""
`True` if the action is recording something.
"""
return isinstance(self.action, (
types.SendMessageRecordAudioAction,
types.SendMessageRecordRoundAction,
types.SendMessageRecordVideoAction
))
@property
@_requires_action
def playing(self):
"""
`True` if the action is playing a game.
"""
return isinstance(self.action, types.SendMessageGamePlayAction)
@property
@_requires_action
def cancel(self):
"""
`True` if the action was cancelling other actions.
"""
return isinstance(self.action, types.SendMessageCancelAction)
@property
@_requires_action
def geo(self):
"""
`True` if what's being uploaded is a geo.
"""
return isinstance(self.action, types.SendMessageGeoLocationAction)
@property
@_requires_action
def audio(self):
"""
`True` if what's being recorded/uploaded is an audio.
"""
return isinstance(self.action, (
types.SendMessageRecordAudioAction,
types.SendMessageUploadAudioAction
))
@property
@_requires_action
def round(self):
"""
`True` if what's being recorded/uploaded is a round video.
"""
return isinstance(self.action, (
types.SendMessageRecordRoundAction,
types.SendMessageUploadRoundAction
))
@property
@_requires_action
def video(self):
"""
`True` if what's being recorded/uploaded is an video.
"""
return isinstance(self.action, (
types.SendMessageRecordVideoAction,
types.SendMessageUploadVideoAction
))
@property
@_requires_action
def contact(self):
"""
`True` if what's being uploaded (selected) is a contact.
"""
return isinstance(self.action, types.SendMessageChooseContactAction)
@property
@_requires_action
def document(self):
"""
`True` if what's being uploaded is document.
"""
return isinstance(self.action, types.SendMessageUploadDocumentAction)
@property
@_requires_action
def sticker(self):
"""
`True` if what's being uploaded is a sticker.
"""
return isinstance(self.action, types.SendMessageChooseStickerAction)
@property
@_requires_action
def photo(self):
"""
`True` if what's being uploaded is a photo.
"""
return isinstance(self.action, types.SendMessageUploadPhotoAction)
@property
@_requires_status
def last_seen(self):
"""
Exact `datetime.datetime` when the user was last seen if known.
"""
if isinstance(self.status, types.UserStatusOffline):
return self.status.was_online
@property
@_requires_status
def until(self):
"""
The `datetime.datetime` until when the user should appear online.
"""
if isinstance(self.status, types.UserStatusOnline):
return self.status.expires
def _last_seen_delta(self):
if isinstance(self.status, types.UserStatusOffline):
return datetime.datetime.now(tz=datetime.timezone.utc) - self.status.was_online
elif isinstance(self.status, types.UserStatusOnline):
return datetime.timedelta(days=0)
elif isinstance(self.status, types.UserStatusRecently):
return datetime.timedelta(days=1)
elif isinstance(self.status, types.UserStatusLastWeek):
return datetime.timedelta(days=7)
elif isinstance(self.status, types.UserStatusLastMonth):
return datetime.timedelta(days=30)
else:
return datetime.timedelta(days=365)
@property
@_requires_status
def online(self):
"""
`True` if the user is currently online,
"""
return self._last_seen_delta() <= datetime.timedelta(days=0)
@property
@_requires_status
def recently(self):
"""
`True` if the user was seen within a day.
"""
return self._last_seen_delta() <= datetime.timedelta(days=1)
@property
@_requires_status
def within_weeks(self):
"""
`True` if the user was seen within 7 days.
"""
return self._last_seen_delta() <= datetime.timedelta(days=7)
@property
@_requires_status
def within_months(self):
"""
`True` if the user was seen within 30 days.
"""
return self._last_seen_delta() <= datetime.timedelta(days=30)
|
class Event(EventCommon, SenderGetter):
'''
Represents the event of a user update
such as gone online, started typing, etc.
Members:
status (:tl:`UserStatus`, optional):
The user status if the update is about going online or offline.
You should check this attribute first before checking any
of the seen within properties, since they will all be `None`
if the status is not set.
action (:tl:`SendMessageAction`, optional):
The "typing" action if any the user is performing if any.
You should check this attribute first before checking any
of the typing properties, since they will all be `None`
if the action is not set.
'''
def __init__(self, peer, *, status=None, chat_peer=None, typing=None):
pass
def _set_client(self, client):
pass
@property
def user(self):
'''Alias for `sender <telethon.tl.custom.sendergetter.SenderGetter.sender>`.'''
pass
async def get_user(self):
'''Alias for `get_sender <telethon.tl.custom.sendergetter.SenderGetter.get_sender>`.'''
pass
@property
def input_user(self):
'''Alias for `input_sender <telethon.tl.custom.sendergetter.SenderGetter.input_sender>`.'''
pass
async def get_input_user(self):
'''Alias for `get_input_sender <telethon.tl.custom.sendergetter.SenderGetter.get_input_sender>`.'''
pass
@property
def user_id(self):
'''Alias for `sender_id <telethon.tl.custom.sendergetter.SenderGetter.sender_id>`.'''
pass
@property
@_requires_action
def typing(self):
'''
`True` if the action is typing a message.
'''
pass
@property
@_requires_action
def uploading(self):
'''
`True` if the action is uploading something.
'''
pass
@property
@_requires_action
def recording(self):
'''
`True` if the action is recording something.
'''
pass
@property
@_requires_action
def playing(self):
'''
`True` if the action is playing a game.
'''
pass
@property
@_requires_action
def cancel(self):
'''
`True` if the action was cancelling other actions.
'''
pass
@property
@_requires_action
def geo(self):
'''
`True` if what's being uploaded is a geo.
'''
pass
@property
@_requires_action
def audio(self):
'''
`True` if what's being recorded/uploaded is an audio.
'''
pass
@property
@_requires_action
def round(self):
'''
`True` if what's being recorded/uploaded is a round video.
'''
pass
@property
@_requires_action
def video(self):
'''
`True` if what's being recorded/uploaded is an video.
'''
pass
@property
@_requires_action
def contact(self):
'''
`True` if what's being uploaded (selected) is a contact.
'''
pass
@property
@_requires_action
def document(self):
'''
`True` if what's being uploaded is document.
'''
pass
@property
@_requires_action
def sticker(self):
'''
`True` if what's being uploaded is a sticker.
'''
pass
@property
@_requires_action
def photo(self):
'''
`True` if what's being uploaded is a photo.
'''
pass
@property
@_requires_status
def last_seen(self):
'''
Exact `datetime.datetime` when the user was last seen if known.
'''
pass
@property
@_requires_status
def until(self):
'''
The `datetime.datetime` until when the user should appear online.
'''
pass
def _last_seen_delta(self):
pass
@property
@_requires_status
def online(self):
'''
`True` if the user is currently online,
'''
pass
@property
@_requires_status
def recently(self):
'''
`True` if the user was seen within a day.
'''
pass
@property
@_requires_status
def within_weeks(self):
'''
`True` if the user was seen within 7 days.
'''
pass
@property
@_requires_status
def within_months(self):
'''
`True` if the user was seen within 30 days.
'''
pass
| 69 | 25 | 6 | 0 | 3 | 2 | 1 | 0.57 | 2 | 4 | 0 | 0 | 27 | 4 | 27 | 70 | 243 | 31 | 135 | 53 | 66 | 77 | 67 | 31 | 39 | 6 | 6 | 1 | 34 |
146,840 |
LonamiWebs/Telethon
|
LonamiWebs_Telethon/telethon_generator/parsers/tlobject/tlobject.py
|
telethon_generator.parsers.tlobject.tlobject.TLObject
|
class TLObject:
def __init__(self, fullname, object_id, args, result,
is_function, usability, friendly, layer):
"""
Initializes a new TLObject, given its properties.
:param fullname: The fullname of the TL object (namespace.name)
The namespace can be omitted.
:param object_id: The hexadecimal string representing the object ID
:param args: The arguments, if any, of the TL object
:param result: The result type of the TL object
:param is_function: Is the object a function or a type?
:param usability: The usability for this method.
:param friendly: A tuple (namespace, friendly method name) if known.
:param layer: The layer this TLObject belongs to.
"""
# The name can or not have a namespace
self.fullname = fullname
if '.' in fullname:
self.namespace, self.name = fullname.split('.', maxsplit=1)
else:
self.namespace, self.name = None, fullname
self.args = args
self.result = result
self.is_function = is_function
self.usability = usability
self.friendly = friendly
self.id = None
if object_id is None:
self.id = self.infer_id()
else:
self.id = int(object_id, base=16)
whitelist = WHITELISTED_MISMATCHING_IDS[0] |\
WHITELISTED_MISMATCHING_IDS.get(layer, set())
if self.fullname not in whitelist:
assert self.id == self.infer_id(),\
'Invalid inferred ID for ' + repr(self)
self.class_name = snake_to_camel_case(
self.name, suffix='Request' if self.is_function else '')
self.real_args = list(a for a in self.sorted_args() if not
(a.flag_indicator or a.generic_definition))
@property
def innermost_result(self):
index = self.result.find('<')
if index == -1:
return self.result
else:
return self.result[index + 1:-1]
def sorted_args(self):
"""Returns the arguments properly sorted and ready to plug-in
into a Python's method header (i.e., flags and those which
can be inferred will go last so they can default =None)
"""
return sorted(self.args,
key=lambda x: bool(x.flag) or x.can_be_inferred)
def __repr__(self, ignore_id=False):
if self.id is None or ignore_id:
hex_id = ''
else:
hex_id = '#{:08x}'.format(self.id)
if self.args:
args = ' ' + ' '.join([repr(arg) for arg in self.args])
else:
args = ''
return '{}{}{} = {}'.format(self.fullname, hex_id, args, self.result)
def infer_id(self):
representation = self.__repr__(ignore_id=True)
representation = representation\
.replace(':bytes ', ':string ')\
.replace('?bytes ', '?string ')\
.replace('<', ' ').replace('>', '')\
.replace('{', '').replace('}', '')
# Remove optional empty values (special-cased to the true type)
representation = re.sub(
r' \w+:\w+\.\d+\?true',
r'',
representation
)
return zlib.crc32(representation.encode('ascii'))
def to_dict(self):
return {
'id':
str(struct.unpack('i', struct.pack('I', self.id))[0]),
'method' if self.is_function else 'predicate':
self.fullname,
'params':
[x.to_dict() for x in self.args if not x.generic_definition],
'type':
self.result
}
def is_good_example(self):
return not self.class_name.endswith('Empty')
def as_example(self, f, indent=0):
f.write('functions' if self.is_function else 'types')
if self.namespace:
f.write('.')
f.write(self.namespace)
f.write('.')
f.write(self.class_name)
f.write('(')
args = [arg for arg in self.real_args if not arg.omit_example()]
if not args:
f.write(')')
return
f.write('\n')
indent += 1
remaining = len(args)
for arg in args:
remaining -= 1
f.write(' ' * indent)
f.write(arg.name)
f.write('=')
if arg.is_vector:
f.write('[')
arg.as_example(f, indent)
if arg.is_vector:
f.write(']')
if remaining:
f.write(',')
f.write('\n')
indent -= 1
f.write(' ' * indent)
f.write(')')
|
class TLObject:
def __init__(self, fullname, object_id, args, result,
is_function, usability, friendly, layer):
'''
Initializes a new TLObject, given its properties.
:param fullname: The fullname of the TL object (namespace.name)
The namespace can be omitted.
:param object_id: The hexadecimal string representing the object ID
:param args: The arguments, if any, of the TL object
:param result: The result type of the TL object
:param is_function: Is the object a function or a type?
:param usability: The usability for this method.
:param friendly: A tuple (namespace, friendly method name) if known.
:param layer: The layer this TLObject belongs to.
'''
pass
@property
def innermost_result(self):
pass
def sorted_args(self):
'''Returns the arguments properly sorted and ready to plug-in
into a Python's method header (i.e., flags and those which
can be inferred will go last so they can default =None)
'''
pass
def __repr__(self, ignore_id=False):
pass
def infer_id(self):
pass
def to_dict(self):
pass
def is_good_example(self):
pass
def as_example(self, f, indent=0):
pass
| 10 | 2 | 17 | 2 | 13 | 2 | 3 | 0.18 | 0 | 5 | 0 | 0 | 8 | 11 | 8 | 8 | 141 | 19 | 104 | 28 | 93 | 19 | 75 | 26 | 66 | 8 | 0 | 2 | 23 |
146,841 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/tests/telethon/test_helpers.py
|
tests.telethon.test_helpers.TestSyncifyAsyncContext.NoopContextManager
|
class NoopContextManager:
def __init__(self, loop):
self.count = 0
self.loop = loop
async def __aenter__(self):
self.count += 1
return self
async def __aexit__(self, exc_type, *args):
assert exc_type is None
self.count -= 1
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit
|
class NoopContextManager:
def __init__(self, loop):
pass
async def __aenter__(self):
pass
async def __aexit__(self, exc_type, *args):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 15 | 3 | 12 | 8 | 8 | 0 | 12 | 8 | 8 | 1 | 0 | 0 | 3 |
146,842 |
LonamiWebs/Telethon
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LonamiWebs_Telethon/tests/telethon/test_utils.py
|
tests.telethon.test_utils.test_private_get_extension.CustomFd
|
class CustomFd:
def __init__(self, name):
self.name = name
|
class CustomFd:
def __init__(self, name):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 3 | 0 | 3 | 3 | 1 | 0 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
146,843 |
LordDarkula/chess_py
|
LordDarkula_chess_py/chess_py/core/color.py
|
chess_py.core.color.Color
|
class Color:
_color_dict = {
'white': True,
'black': False,
}
def __init__(self, raw):
"""
Initializes new color using a boolean
True is white and False is black
:type: raw: bool
"""
self._bool = raw
@classmethod
def from_string(cls, string):
"""
Converts string "white" or "black" into
corresponding color
:type: string: str
:rtype: Color
"""
return cls(cls._color_dict[string])
def __repr__(self):
return "color.{}".format(str(self))
def __str__(self):
if self._bool:
return "white"
else:
return "black"
def __bool__(self):
return self._bool
def __int__(self):
if self._bool:
return 1
else:
return -1
def __key(self):
return bool(self)
def __hash__(self):
return hash(self.__key())
def __neg__(self):
return Color(not self._bool)
def __eq__(self, other):
"""
Finds out this color is the same as another color.
:type: other: Color
:rtype: bool
"""
return bool(self) == bool(other)
def __ne__(self, other):
return not self.__eq__(other)
|
class Color:
def __init__(self, raw):
'''
Initializes new color using a boolean
True is white and False is black
:type: raw: bool
'''
pass
@classmethod
def from_string(cls, string):
'''
Converts string "white" or "black" into
corresponding color
:type: string: str
:rtype: Color
'''
pass
def __repr__(self):
pass
def __str__(self):
pass
def __bool__(self):
pass
def __int__(self):
pass
def __key(self):
pass
def __hash__(self):
pass
def __neg__(self):
pass
def __eq__(self, other):
'''
Finds out this color is the same as another color.
:type: other: Color
:rtype: bool
'''
pass
def __ne__(self, other):
pass
| 13 | 3 | 4 | 0 | 3 | 1 | 1 | 0.47 | 0 | 2 | 0 | 0 | 10 | 1 | 11 | 11 | 65 | 15 | 34 | 15 | 21 | 16 | 28 | 14 | 16 | 2 | 0 | 1 | 13 |
146,844 |
LordDarkula/chess_py
|
LordDarkula_chess_py/chess_py/game/game.py
|
chess_py.game.game.Game
|
class Game:
def __init__(self, player_white, player_black):
"""
Creates new game given the players.
:type: player_white: Player
:type: player_black: Player
"""
self.player_white = player_white
self.player_black = player_black
self.position = Board.init_default()
def play(self):
"""
Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int
"""
colors = [lambda: self.white_move(), lambda: self.black_move()]
colors = itertools.cycle(colors)
while True:
color_fn = next(colors)
if game_state.no_moves(self.position):
if self.position.get_king(color.white).in_check(self.position):
return 1
elif self.position.get_king(color.black).in_check(self.position):
return 0
else:
return 0.5
color_fn()
def white_move(self):
"""
Calls the white player's ``generate_move()``
method and updates the board with the move returned.
"""
move = self.player_white.generate_move(self.position)
move = make_legal(move, self.position)
self.position.update(move)
def black_move(self):
"""
Calls the black player's ``generate_move()``
method and updates the board with the move returned.
"""
move = self.player_black.generate_move(self.position)
move = make_legal(move, self.position)
self.position.update(move)
def all_possible_moves(self, input_color):
"""
Finds all possible moves a particular player can
play during a game. Calling this method is recommended over
calling the ``all_possible_moves(input_color)``
from this ``Board`` directly.
"""
return self.position.all_possible_moves(input_color)
|
class Game:
def __init__(self, player_white, player_black):
'''
Creates new game given the players.
:type: player_white: Player
:type: player_black: Player
'''
pass
def play(self):
'''
Starts game and returns one of 3 results .
Iterates between methods ``white_move()`` and
``black_move()`` until game ends. Each
method calls the respective player's ``generate_move()``
method.
:rtype: int
'''
pass
def white_move(self):
'''
Calls the white player's ``generate_move()``
method and updates the board with the move returned.
'''
pass
def black_move(self):
'''
Calls the black player's ``generate_move()``
method and updates the board with the move returned.
'''
pass
def all_possible_moves(self, input_color):
'''
Finds all possible moves a particular player can
play during a game. Calling this method is recommended over
calling the ``all_possible_moves(input_color)``
from this ``Board`` directly.
'''
pass
| 6 | 5 | 12 | 1 | 5 | 5 | 2 | 0.96 | 0 | 2 | 1 | 0 | 5 | 3 | 5 | 5 | 65 | 10 | 28 | 13 | 22 | 27 | 26 | 13 | 20 | 5 | 0 | 3 | 9 |
146,845 |
LordDarkula/chess_py
|
LordDarkula_chess_py/chess_py/pieces/rook.py
|
chess_py.pieces.rook.Rook
|
class Rook(Piece):
def __init__(self, input_color, location):
"""
Initializes a rook that is capable of being compared to another rook,
and returning a list of possible moves.
:type: input_color: Color
:type: location: Location
"""
super(Rook, self).__init__(input_color, location)
self.has_moved = False
def _symbols(self):
return {color.white: "♜", color.black: "♖"}
def __str__(self):
return "R"
def moves_in_direction(self, direction, position):
"""
Finds moves in a given direction
:type: direction: lambda
:type: position: Board
:rtype: list
"""
current_square = self.location
while True:
try:
current_square = direction(current_square)
except IndexError:
return
if self.contains_opposite_color_piece(current_square, position):
yield self.create_move(current_square, notation_const.CAPTURE)
if not position.is_square_empty(current_square):
return
yield self.create_move(current_square, notation_const.MOVEMENT)
def possible_moves(self, position):
"""
Returns all possible rook moves.
:type: position: Board
:rtype: list
"""
for move in itertools.chain(*[self.moves_in_direction(fn, position) for fn in self.cross_fn]):
yield move
|
class Rook(Piece):
def __init__(self, input_color, location):
'''
Initializes a rook that is capable of being compared to another rook,
and returning a list of possible moves.
:type: input_color: Color
:type: location: Location
'''
pass
def _symbols(self):
pass
def __str__(self):
pass
def moves_in_direction(self, direction, position):
'''
Finds moves in a given direction
:type: direction: lambda
:type: position: Board
:rtype: list
'''
pass
def possible_moves(self, position):
'''
Returns all possible rook moves.
:type: position: Board
:rtype: list
'''
pass
| 6 | 3 | 9 | 1 | 4 | 3 | 2 | 0.74 | 1 | 3 | 0 | 2 | 5 | 1 | 5 | 18 | 51 | 11 | 23 | 9 | 17 | 17 | 23 | 9 | 17 | 5 | 1 | 2 | 10 |
146,846 |
LordDarkula/chess_py
|
LordDarkula_chess_py/chess_py/players/human.py
|
chess_py.players.human.Human
|
class Human(Player):
def __init__(self, input_color):
"""
Creates interface for human player.
:type: input_color: Color
"""
super(Human, self).__init__(input_color)
def generate_move(self, position):
"""
Returns valid and legal move given position
:type: position: Board
:rtype: Move
"""
while True:
print(position)
raw = input(str(self.color) + "\'s move \n")
move = converter.short_alg(raw, self.color, position)
if move is None:
continue
return move
|
class Human(Player):
def __init__(self, input_color):
'''
Creates interface for human player.
:type: input_color: Color
'''
pass
def generate_move(self, position):
'''
Returns valid and legal move given position
:type: position: Board
:rtype: Move
'''
pass
| 3 | 2 | 12 | 2 | 5 | 5 | 2 | 0.82 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 6 | 25 | 5 | 11 | 5 | 8 | 9 | 11 | 5 | 8 | 3 | 1 | 2 | 4 |
146,847 |
LordDarkula/chess_py
|
LordDarkula_chess_py/tests/test_core/test_algebraic/test_move.py
|
tests.test_core.test_algebraic.test_move.TestMove
|
class TestMove(unittest.TestCase):
def setUp(self):
self.white_pawn = Pawn(color.white, Location(1, 0))
self.black_pawn = Pawn(color.black, Location(1, 0))
self.white_pawn_move = Move(Location(2, 0),
piece=self.white_pawn,
status=notation_const.MOVEMENT,
start_loc=Location(1, 0))
self.start_specified = Move(Location(2, 0),
piece=self.white_pawn,
status=notation_const.MOVEMENT,
start_loc=Location(3, 5))
def testStr(self):
self.assertEqual(str(self.start_specified), "f4a3")
self.white_pawn_move = Move(Location(7, 0),
piece=self.white_pawn,
status=notation_const.MOVEMENT,
start_loc=Location(6, 0),
promoted_to_piece=Queen(color.white,
Location(7, 0)))
def testEquals(self):
self.assertEqual(self.white_pawn_move, Move(end_loc=Location(2, 0),
piece=self.white_pawn,
status=notation_const.MOVEMENT,
start_loc=Location(1, 0)))
|
class TestMove(unittest.TestCase):
def setUp(self):
pass
def testStr(self):
pass
def testEquals(self):
pass
| 4 | 0 | 9 | 1 | 8 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 4 | 3 | 75 | 30 | 5 | 25 | 8 | 21 | 0 | 11 | 8 | 7 | 1 | 2 | 0 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.