slidgram.telegram

Attributes

Exceptions

InvalidUserException

Common base class for all non-exit exceptions.

Classes

InvalidUser

Client

Pyrogram Client, the main means for interacting with Telegram.

LimitedSizeDict

dict() -> new empty dictionary

MessageCache

Functions

handle_flood(func)

Module Contents

slidgram.telegram.P[source]
slidgram.telegram.R[source]
slidgram.telegram.WrappedMethod[source]
slidgram.telegram.AVATAR_DOWNLOAD_SLEEP = 15[source]
slidgram.telegram.MAX_FLOOD_ATTEMPTS = 10[source]
class slidgram.telegram.InvalidUser[source]
exception slidgram.telegram.InvalidUserException[source]

Bases: Exception

Common base class for all non-exit exceptions.

Initialize self. See help(type(self)) for accurate signature.

class slidgram.telegram.Client(name)[source]

Bases: pyrogram.Client

Pyrogram Client, the main means for interacting with Telegram.

Parameters:
name (str):

A name for the client, e.g.: “my_account”.

api_id (int | str, optional):

The api_id part of the Telegram API key, as integer or string. E.g.: 12345 or “12345”.

api_hash (str, optional):

The api_hash part of the Telegram API key, as string. E.g.: “0123456789abcdef0123456789abcdef”.

app_version (str, optional):

Application version. Defaults to “Pyrogram x.y.z”.

device_model (str, optional):

Device model. Defaults to platform.python_implementation() + “ “ + platform.python_version().

system_version (str, optional):

Operating System version. Defaults to platform.system() + “ “ + platform.release().

lang_code (str, optional):

Code of the language used on the client, in ISO 639-1 standard. Defaults to “en”.

ipv6 (bool, optional):

Pass True to connect to Telegram using IPv6. Defaults to False (IPv4).

alt_port (bool, optional):

Pass True to connect to Telegram using alternative port (5222). Defaults to False (443).

proxy (dict, optional):

The Proxy settings as dict. E.g.: dict(scheme=”socks5”, hostname=”11.22.33.44”, port=1234, username=”user”, password=”pass”). The username and password can be omitted if the proxy doesn’t require authorization.

test_mode (bool, optional):

Enable or disable login to the test servers. Only applicable for new sessions and will be ignored in case previously created sessions are loaded. Defaults to False.

bot_token (str, optional):

Pass the Bot API token to create a bot session, e.g.: “123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11” Only applicable for new sessions.

session_string (str, optional):

Pass a session string to load the session in-memory. Implies in_memory=True.

in_memory (bool, optional):

Pass True to start an in-memory session that will be discarded as soon as the client stops. In order to reconnect again using an in-memory session without having to login again, you can use export_session_string() before stopping the client to get a session string you can pass to the session_string parameter. Defaults to False.

mongodb (dict, optional):

Mongodb config as dict, e.g.: dict(connection=async_pymongo.AsyncClient(“mongodb://…”), remove_peers=False). Only applicable for new sessions.

storage (Storage, optional):

Custom session storage.

phone_number (str, optional):

Pass the phone number as string (with the Country Code prefix included) to avoid entering it manually. Only applicable for new sessions.

phone_code (str, optional):

Pass the phone code as string (for test numbers only) to avoid entering it manually. Only applicable for new sessions.

password (str, optional):

Pass the Two-Step Verification password as string (if required) to avoid entering it manually. Only applicable for new sessions.

workers (int, optional):

Number of maximum concurrent workers for handling incoming updates. Defaults to min(32, os.cpu_count() + 4).

workdir (str, optional):

Define a custom working directory. The working directory is the location in the filesystem where Pyrogram will store the session files. Defaults to the parent directory of the main script.

plugins (dict, optional):

Smart Plugins settings as dict, e.g.: dict(root=”plugins”).

parse_mode (ParseMode, optional):

Set the global parse mode of the client. By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together.

no_updates (bool, optional):

Pass True to disable incoming updates. When updates are disabled the client can’t receive messages or other updates. Useful for batch programs that don’t need to deal with updates. Defaults to False (updates enabled and received).

skip_updates (bool, optional):

Pass True to skip pending updates that arrived while the client was offline. Defaults to True.

takeout (bool, optional):

Pass True to let the client use a takeout session instead of a normal one, implies no_updates=True. Useful for exporting Telegram data. Methods invoked inside a takeout session (such as get_chat_history, download_media, …) are less prone to throw FloodWait exceptions. Only available for users, bots will ignore this parameter. Defaults to False (normal session).

sleep_threshold (int, optional):

Set a sleep threshold for flood wait exceptions happening globally in this client instance, below which any request that raises a flood wait will be automatically invoked again after sleeping for the required amount of time. Flood wait exceptions requiring higher waiting times will be raised. Defaults to 10 seconds.

hide_password (bool, optional):

Pass True to hide the password when typing it during the login. Defaults to False, because getpass (the library used) is known to be problematic in some terminal environments.

max_concurrent_transmissions (bool, optional):

Set the maximum amount of concurrent transmissions (uploads & downloads). A value that is too high may result in network related issues. Defaults to 1.

max_message_cache_size (int, optional):

Set the maximum size of the message cache. Defaults to 10000.

max_business_user_connection_cache_size (int, optional):

Set the maximum size of the message cache. Defaults to 10000.

client_platform (ClientPlatform, optional):

The platform where this client is running. Defaults to ‘other’

Parameters:

name (str)

message_cache: MessageCache[source]
_available_reactions: set[str] | None = None[source]
log[source]
get_chat[source]

Get up to date information about a chat.

Information include current name of the user for one-on-one conversations, current username of a user, group or channel, etc.

Parameters:
chat_id (int | str):

Unique identifier (int) or username (str) of the target chat. Unique identifier for the target chat in form of a t.me/joinchat/ or t.me/<username> link link, identifier (int) or username of the target channel/supergroup (in the format @username). You can also use chat public link in form of t.me/<username> (str).

Returns:

Chat | ChatPreview: On success, if you’ve already joined the chat, a chat object is returned, otherwise, a chat preview object is returned.

Raises:

ValueError: In case the chat invite link points to a chat you haven’t joined yet.

Example:
chat = await app.get_chat("pyrogram")
print(chat)
get_contacts[source]

Get contacts from your Telegram address book.

Returns:

List of User: On success, a list of users is returned.

Example:
contacts = await app.get_contacts()
print(contacts)
get_users[source]

Get information about a user. You can retrieve up to 200 users at once.

Parameters:
user_ids (int | str | Iterable of int or str):

A list of User identifiers (id or username) or a single user id/username. For a contact that exists in your Telegram address book you can use his phone number (str). You can also use user profile link in form of t.me/<username> (str).

Returns:

User | List of User: In case user_ids was not a list, a single user is returned, otherwise a list of users is returned.

Example:
# Get information about one user
await app.get_users("me")

# Get information about multiple users at once
await app.get_users([user_id1, user_id2, user_id3])
download_media[source]

Download the media from a message.

Parameters:
message (Message | Story | str):

Pass a Message/Story containing the media, the media itself (message.audio, message.video, …) or a file id as string.

file_name (str, optional):

A custom file_name to be used instead of the one provided by Telegram. By default, all files are downloaded in the downloads folder in your working directory. You can also specify a path for downloading files in a custom location: paths that end with “/” are considered directories. All non-existent folders will be created automatically.

in_memory (bool, optional):

Pass True to download the media in-memory. A binary file-like object with its attribute “.name” set will be returned. Defaults to False.

block (bool, optional):

Blocks the code execution until the file has been downloaded. Defaults to True.

progress (Callable, optional):

Pass a callback function to view the file transmission progress. The function must take (current, total) as positional arguments (look at Other Parameters below for a detailed description) and will be called back each time a new file chunk has been successfully transmitted.

progress_args (tuple, optional):

Extra custom arguments for the progress callback function. You can pass anything you need to be available in the progress callback scope; for example, a Message object or a Client instance in order to edit the message with the updated progress status.

Other Parameters:
current (int):

The amount of bytes transmitted so far.

total (int):

The total size of the file.

args (``tuple``, *optional):

Extra custom arguments as defined in the progress_args parameter. You can either keep *args or add every single extra argument in your function signature.

Returns:

str | None | BinaryIO: On success, the absolute path of the downloaded file is returned, otherwise, in case the download failed or was deliberately stopped with stop_transmission(), None is returned. Otherwise, in case in_memory=True, a binary file-like object with its attribute “.name” set is returned.

Raises:

ValueError: if the message doesn’t contain any downloadable media

Example:

Download media to file

# Download from Message
await app.download_media(message)

# Download from file id
await app.download_media(message.photo.file_id)

# Keep track of the progress while downloading
async def progress(current, total):
    print(f"{current * 100 / total:.1f}%")

await app.download_media(message, progress=progress)

Download media in-memory

file = await app.download_media(message, in_memory=True)

file_name = file.name
file_bytes = bytes(file.getbuffer())
get_chat_member[source]

Get information about one member of a chat.

Parameters:
chat_id (int | str):

Unique identifier (int) or username (str) of the target chat. You can also use chat public link in form of t.me/<username> (str).

user_id (int | str):

Unique identifier (int) or username (str) of the target user. For you yourself you can simply use “me” or “self”. For a contact that exists in your Telegram address book you can use his phone number (str). You can also use user profile link in form of t.me/<username> (str).

Returns:

ChatMember: On success, a chat member is returned.

Example:
member = await app.get_chat_member(chat_id, "me")
print(member)
_download_avatar_lock[source]
_get_user_lock[source]
_users_to_get[source]
_reactions[source]
_user_cache: OrderedDict[int, pyrogram.raw.types.User | InvalidUser][source]
_reaction_handler: Callable[[pyrogram.types.Message, int, str | None], Awaitable[None]] | None = None[source]
is_me(user)[source]
Parameters:

user (pyrogram.types.User | int)

Return type:

bool

property download_path[source]
async download_avatar(file_id)[source]
Parameters:

file_id (str)

Return type:

pathlib.Path | None

get_downloader(file_id_str)[source]
Parameters:

file_id_str (str)

Return type:

AsyncIterator[bytes] | None

async get_available_reactions()[source]
Return type:

pyrogram.raw.types.messages.AvailableReactions

async available_reactions()[source]
Return type:

set[str]

on_reaction(callback)[source]
async _on_edited_message(_tg, message)[source]
Parameters:
  • _tg (pyrogram.Client)

  • message (pyrogram.types.Message)

async _on_reaction(message)[source]
Parameters:

message (pyrogram.types.Message)

async _on_raw(_tg, update, _users, _chats)[source]
Parameters:
  • update (pyrogram.types.Update)

  • _users (dict[int, pyrogram.types.User])

  • _chats (dict[int, pyrogram.types.Chat])

async get_user(user_id)[source]

Get a telegram user from local cache or through a RPC if needed.

Parameters:

user_id (int)

Returns:

Return type:

pyrogram.types.User

async invoke(*a, **k)[source]

Invoke raw Telegram functions.

This method makes it possible to manually call every single Telegram API method in a low-level manner. Available functions are listed in the functions package and may accept compound data types from types as well as bare types such as int, str, etc…

Note

This is a utility method intended to be used only when working with raw functions (i.e: a Telegram API method you wish to use which is not available yet in the Client class as an easy-to-use method).

Parameters:
query (RawFunction):

The API Schema function filled with proper arguments.

retries (int):

Number of retries.

timeout (float):

Timeout in seconds.

sleep_threshold (float):

Sleep threshold in seconds.

Returns:

RawType: The raw type response generated by the query.

Raises:

RPCError: In case of a Telegram RPC error.

__update_user_cache(raw_obj)[source]
async edit_chat_admin(chat_id, user_id, is_admin)[source]
Parameters:
Return type:

bool

class slidgram.telegram.LimitedSizeDict(size, *args, **kwargs)[source]

Bases: OrderedDict

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

Initialize self. See help(type(self)) for accurate signature.

Parameters:

size (int)

_size[source]
__setitem__(key, value)[source]

Set self[key] to value.

update(*args, **kwargs)[source]

D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

_check_size_limit()[source]
class slidgram.telegram.MessageCache(*args, **kwargs)[source]

Bases: pyrogram.client.Cache

_chat_by_message_ids[source]
__setitem__(key, value)[source]
Parameters:
Return type:

None

get_by_message_id(message_id)[source]
Parameters:

message_id (int)

Return type:

pyrogram.types.Message

remove_chat(chat_id)[source]
Parameters:

chat_id (int)

Return type:

None

slidgram.telegram.invalid_user[source]
slidgram.telegram.handle_flood(func)[source]
Parameters:

func (WrappedMethod)

Return type:

WrappedMethod

slidgram.telegram.log[source]