opentele2.tl
The Telethon integration: TelegramClient, a subclass of telethon.TelegramClient, and the
helpers that read and write Telethon .session + .json pairs.
from opentele2.tl import TelegramClientTelegramClient
class TelegramClient(telethon.TelegramClient):
def __init__(
self,
session: str | Session | None = None,
api: type[APIData] | APIData | int | str | None = None,
api_id: int | str = 0,
api_hash: str | None = None,
*,
fingerprint_config: FingerprintConfig | None = None,
auto_post_login: bool = True,
**kwargs: Unpack[TelethonClientKwargs],
) -> None: ...| Argument | Description |
|---|---|
session | A Telethon session name or Session; None is a MemorySession. |
api | An APIData class or instance whose api_id, api_hash, device_model, system_version, app_version, lang_code, system_lang_code and lang_pack the client sends. Without api, api_id and api_hash, the client uses API.TelegramDesktop. Telethon’s positional Telegram form also works. |
fingerprint_config | The FingerprintConfig the initConnection fields are validated with when the client is built; DEFAULT_CONFIG by default. |
auto_post_login | Whether connect sends the requests an official client sends after login, once, when the session is authorised; True by default. |
**kwargs | The keyword arguments of telethon., forwarded as they are; explicit device_model and friends win over the profile. |
What the client changes against plain Telethon:
- the transport defaults to
ConnectionTcpObfuscated, the one official clients use (ConnectionTcpFullwhen it is unavailable); lang_packis the profile’s, where Telethon always sends"";- with the
tdesktoplang pack,initConnectioncarriesparamswithtz_offset, recomputed on everyconnect, as Telegram Desktop sends it.
Session admin
async def GetSessions(self) -> types.account.Authorizations | None: ...
async def GetCurrentSession(self) -> types.Authorization | None: ...
async def TerminateSession(self, hash: int) -> None: ...
async def TerminateAllSessions(self) -> bool: ...
async def PrintSessions(self, sessions: types.account.Authorizations | None = None) -> None: ...
async def is_official_app(self) -> bool: ...
async def RunConsistencyChecks(self, *, auto_warn: bool = True) -> ConsistencyReport: ...
@property
def UserId(self) -> int | None: ...| Method | Description |
|---|---|
GetSessions() | The account’s sessions (account.). |
GetCurrentSession() | The session flagged current, else None. |
TerminateSession(hash) | Ends one session (account.); raises Fresh within 24 hours of login and HashInvalidError for an unknown hash. |
TerminateAllSessions() | Ends every session but the current one; False when the sessions cannot be fetched. |
Print | Prints the sessions as a table; raises OpenTeleException when they cannot be fetched. |
is_official_app() | Whether the current session is flagged official_app. |
Run | Runs the seven consistency checks and warns about failures when auto_warn is on. |
UserId | The self user id once known, else the id set from tdata or a .json; settable. |
Login and conversion
async def QRLoginToNewClient(
self,
session: str | Session | None = None,
api: type[APIData] | APIData = API.TelegramDesktop,
password: str | None = None,
**kwargs: Unpack[TelethonClientKwargs],
) -> TelegramClient: ...
async def ToTDesktop(
self,
flag: type[LoginFlag] = CreateNewSession,
api: type[APIData] | APIData = API.TelegramDesktop,
password: str | None = None,
) -> td.TDesktop: ...
@staticmethod
async def FromTDesktop(
account: td.TDesktop | td.Account,
session: str | Session | None = None,
flag: type[LoginFlag] = CreateNewSession,
api: type[APIData] | APIData = API.TelegramDesktop,
password: str | None = None,
**kwargs: Unpack[TelethonClientKwargs],
) -> TelegramClient: ...QRLoginToNewClient
Logs a new client in through this authorised one by QR code: the new client connects (moving to
this client’s DC), exports a login token, this client accepts it, and a 2FA account is finished
with password. Then the post-login requests run. A new client that is already authorised keeps
its session when its api_id is the profile’s and is logged in again otherwise, with a warning
either way. Raises NoPasswordProvided for 2FA without a password, PasswordIncorrect for a
wrong one and TimeoutError when no attempt logged in; the AuthToken*Errors of Telethon are
re-raised.
ToTDesktop
TDesktop.FromTelethon(self, flag, api, password): a new tdata folder with this client’s own
session (UseCurrentSession) or with a new session logged in by QR code on the device of api
(CreateNewSession).
FromTDesktop
A client for a tdata account (a TDesktop gives its main account), built on the account’s own
api; the api argument is the device of a new session. The client connects to the
first TCP endpoint of the main DC, from the stored MTP config when there is one, IPv6 when
use_ipv6=True and the DC has one.
UseCurrentSession: the client gets the account’s auth key, insession(aSQLiteSessionfor a name), and works offline until you connect. Anapithat is not anAPIDatawarns.CreateNewSession: the account’s key connects, thenQRLoginToNewClientlogs a new session in on the device ofapi, intosession. RaisesTDesktopUnauthorizedwhen the tdata session is not authorised.
.session + .json pairs
@staticmethod
async def FromSessionJson(
session_path: str,
json_path: str | None = None,
flag: type[LoginFlag] = UseCurrentSession,
password: str | None = None,
**kwargs: Unpack[TelethonClientKwargs],
) -> TelegramClient: ...
async def SaveSessionJson(
self,
session_path: str,
api: type[APIData] | APIData | None = None,
fetch_user_info: bool = False,
) -> tuple[str, str]: ...| Method | Description |
|---|---|
FromSessionJson(...) | A client for the pair: the .session file as its SQLiteSession and the API profile read from the .json (APIData.from_json), with UserId from its id. session_path may name the base, the .session or the .json; json_path overrides the companion. With CreateNewSession it logs a new session in by QR code. Raises SessionFileNotFound when either file is missing. |
SaveSessionJson(...) | Writes the client’s session as a Telethon version 8 .session file and the .json companion, and returns both paths. api defaults to the client’s profile; fetch_user_info=True on a connected client fills id, phone, username, the names and is_premium from get_me(). Raises SessionFileInvalid without an auth key. |
The keys of the companion and how they map to the profile are listed in the
.session + .json guide; APIData.from_json and
APIData.to_json are on the opentele2.api page.
Session helpers
The module functions behind FromSessionJson and SaveSessionJson.
SESSION_VERSION = _native.TELETHON_SESSION_VERSION # 8
def write_session_file(path: str, dc_id: int, server_address: str, port: int,
auth_key_bytes: bytes) -> str: ...
async def from_session_json(session_path: str, json_path: str | None = None,
flag: type[LoginFlag] = UseCurrentSession,
password: str | None = None,
**kwargs: Unpack[TelethonClientKwargs]) -> TelegramClient: ...
async def save_session_json(client: TelegramClient, session_path: str,
api: type[APIData] | APIData | None = None,
fetch_user_info: bool = False) -> tuple[str, str]: ...| Function | Description |
|---|---|
write_ | Writes a Telethon CURRENT_VERSION = 8 session file and returns its path. A schema that is not the version 8 layout is dropped and rebuilt; takeout_id and tmp_auth_key are written as NULL. |
from_session_json(...) | Telegram. |
save_session_json(...) | Telegram for client. |
Keyword arguments
class TelethonClientKwargs(TypedDict, total=False):
connection: type[Connection]
use_ipv6: bool
proxy: tuple | dict
local_addr: str | tuple
timeout: int
request_retries: int
connection_retries: int
retry_delay: int
auto_reconnect: bool
sequential_updates: bool
flood_sleep_threshold: int
raise_last_call_error: bool
device_model: str
system_version: str
app_version: str
lang_code: str
system_lang_code: str
loop: asyncio.AbstractEventLoop
base_logger: str | logging.Logger
receive_updates: bool
catch_up: bool
entity_cache_limit: int
class ClientKwargs(TelethonClientKwargs, total=False):
fingerprint_config: FingerprintConfig | None
auto_post_login: boolTelethonClientKwargs are the keyword parameters of telethon.TelegramClient.__init__, as
Telethon declares them; every entry point that builds a client forwards them. request_retries
also sets how many QR login attempts are made (5 by default).
Re-exports
opentele2.tl.shared gathers the names a Telethon script uses next to the client:
TelegramClient, ConsistencyChecker, ConsistencyReport, CheckResult (from
opentele2.consistency) and DEFAULT_CONFIG, LAYER,
PLATFORM_VERSIONS, FingerprintConfig, PlatformVersions, StrictMode,
TransportRecommendation, validate_init_connection_params (from
opentele2.fingerprint).