Telethon is a Python library, which means you need to download and install
Python from https://www.python.org/downloads/ if you haven’t already. Once
you have Python installed, upgrade pip and run:
python3 -m pip install --upgrade pip python3 -m pip install --upgrade telethon
…to install or upgrade the library to the latest version.
Installing Development Versions
If you want the latest unreleased changes,
you can run the following command instead:
python3 -m pip install --upgrade https://github.com/LonamiWebs/Telethon/archive/v1.zip
Note
The development version may have bugs and is not recommended for production
use. However, when you are reporting a library bug, you should try if the
bug still occurs in this version.
Verification
To verify that the library is installed correctly, run the following command:
python3 -c "import telethon; print(telethon.__version__)"
The version number of the library should show in the output.
Optional Dependencies
If cryptg is installed, the library will work a lot faster, since
encryption and decryption will be made in C instead of Python. If your
code deals with a lot of updates or you are downloading/uploading a lot
of files, you will notice a considerable speed-up (from a hundred kilobytes
per second to several megabytes per second, if your connection allows it).
If it’s not installed, pyaes will be used (which is pure Python, so it’s
much slower).
If pillow is installed, large images will be automatically resized when
sending photos to prevent Telegram from failing with “invalid image”.
Official clients also do this.
If aiohttp is installed, the library will be able to download
WebDocument media files (otherwise you will get an error).
If hachoir is installed, it will be used to extract metadata from files
when sending documents. Telegram uses this information to show the song’s
performer, artist, title, duration, and for videos too (including size).
Otherwise, they will default to empty values, and you can set the attributes
manually.
Note
Some of the modules may require additional dependencies before being
installed through pip
. If you have an apt
-based system, consider
installing the most commonly missing dependencies (with the right pip
):
apt update apt install clang lib{jpeg-turbo,webp}-dev python{,-dev} zlib-dev pip install -U --user setuptools pip install -U --user telethon cryptg pillow
Thanks to @bb010g for writing down this nice list.
⭐️ Thanks everyone who has starred the project, it means a lot!
Telethon is an asyncio Python 3
MTProto library to interact with Telegram’s API
as a user or through a bot account (bot API alternative).
What is this?
Telegram is a popular messaging application. This library is meant
to make it easy for you to write Python programs that can interact
with Telegram. Think of it as a wrapper that has already done the
heavy job for you, so you can focus on developing an application.
Installing
pip3 install telethon
Creating a client
from telethon import TelegramClient, events, sync
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
Doing stuff
print(client.get_me().stringify())
client.send_message('username', 'Hello! Talking to you from Telethon')
client.send_file('username', '/home/myself/Pictures/holidays.jpg')
client.download_profile_photo('me')
messages = client.get_messages('username')
messages[0].download_media()
@client.on(events.NewMessage(pattern='(?i)hi|hello'))
async def handler(event):
await event.respond('Hey!')
Next steps
Do you like how Telethon looks? Check out Read The Docs for a more
in-depth explanation, with examples, troubleshooting issues, and more
useful information.
Telethon
⭐️ Thanks everyone who has starred the project, it means a lot!
Telethon is an asyncio Python 3
MTProto library to interact with Telegram’s API
as a user or through a bot account (bot API alternative).
What is this?
Telegram is a popular messaging application. This library is meant
to make it easy for you to write Python programs that can interact
with Telegram. Think of it as a wrapper that has already done the
heavy job for you, so you can focus on developing an application.
Installing
Creating a client
from telethon import TelegramClient, events, sync # These example values won't work. You must get your own api_id and # api_hash from https://my.telegram.org, under API Development. api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' client = TelegramClient('session_name', api_id, api_hash) client.start()
Doing stuff
print(client.get_me().stringify()) client.send_message('username', 'Hello! Talking to you from Telethon') client.send_file('username', '/home/myself/Pictures/holidays.jpg') client.download_profile_photo('me') messages = client.get_messages('username') messages[0].download_media() @client.on(events.NewMessage(pattern='(?i)hi|hello')) async def handler(event): await event.respond('Hey!')
Next steps
Do you like how Telethon looks? Check out Read The Docs for a more
in-depth explanation, with examples, troubleshooting issues, and more
useful information.
Contents
- Installation
- Automatic Installation
- Manual Installation
- Optional dependencies
Automatic Installation¶
To install Telethon, simply do:
Needless to say, you must have Python 3 and PyPi installed in your system.
See https://python.org and https://pypi.python.org/pypi/pip for more.
If you already have the library installed, upgrade with:
pip3 install --upgrade telethon
You can also install the library directly from GitHub or a fork:
# pip3 install git+https://github.com/LonamiWebs/Telethon.git or $ git clone https://github.com/LonamiWebs/Telethon.git $ cd Telethon/ # pip install -Ue .
If you don’t have root access, simply pass the --user
flag to the pip
command. If you want to install a specific branch, append @branch
to
the end of the first install command.
By default the library will use a pure Python implementation for encryption,
which can be really slow when uploading or downloading files. If you don’t
mind using a C extension, install cryptg
via pip
or as an extra:
pip3 install telethon[cryptg]
Manual Installation¶
-
Install the required
pyaes
(GitHub | PyPi) and
rsa
(GitHub | PyPi) modules: -
Clone Telethon’s GitHub repository:
git clone https://github.com/LonamiWebs/Telethon.git
-
Enter the cloned repository:
-
Run the code generator:
-
Done!
To generate the method documentation, python3 setup.py gen docs
.
Optional dependencies¶
If pillow is installed, large images will be automatically resized when
sending photos to prevent Telegram from failing with “invalid image”.
Official clients also do this.
If aiohttp is installed, the library will be able to download
WebDocument media files (otherwise you will get an error).
If hachoir is installed, it will be used to extract metadata from files
when sending documents. Telegram uses this information to show the song’s
performer, artist, title, duration, and for videos too (including size).
Otherwise, they will default to empty values, and you can set the attributes
manually.
If cryptg is installed, encryption and decryption will be made in C instead
of Python which will be a lot faster. If your code deals with a lot of
updates or you are downloading/uploading a lot of files, you will notice
a considerable speed-up (from a hundred kilobytes per second to several
megabytes per second, if your connection allows it). If it’s not installed,
pyaes will be used (which is pure Python, so it’s much slower).
Уровень сложностиПростой
Время на прочтение6 мин
Количество просмотров34K
Бывает так: девушка ждет внимания, а вы увлечены работой, хобби или ещё чем-то, и забываете о ней. Установка отложенных сообщений — идеальный компромисс. Эта статья не о создании чат-бота, который будет «любить» за вас. Речь о ненавязчивом напоминании для самого себя и создании точки входа для настоящего диалога.
Зачем это всё?
Автоматизация позволяет отправлять заранее подготовленные, теплые и заботливые сообщения без излишнего пафоса в случайное время в заданном диапазоне. Представьте, «утро начинается не с кофе», а с вашего сообщения. Вот пример списка фраз для утреннего приветствия:
greetings = [
"Доброе утро! Как ты себя чувствуешь сегодня?",
"Привет, как настроение? Готовность к новому дню?",
"Доброе утро! Что нового на сегодня?",
"Утро доброе! Как у тебя всё происходит с утра?",
"Доброе утро, как ты себя сегодня чувствуешь?",
"Привет! Как ты, как сны?",
"Как твои дела, готовность к этому дню?",
"Доброе утро! Как настроение, что планируешь на день?",
"Здравствуй! Как ты себя чувствуешь после сна?"
]
Даже пара теплых слов не оставит девушку равнодушной, и это перейдёт уже в настоящий разговор.
Автоматизация не заменяет заботу, а помогает ее проявить, напоминая о важном человеке, даже если вы очень заняты.
Puppeteer: почему это не лучший вариант
Изначально я пытался автоматизировать переписку через веб-версию Telegram, используя Puppeteer. Идея казалась простой: скрипт заходит в Telegram, отправляет сообщения.
Был создан даже модуль авторизации через QR-код с двухфакторной аутентификацией. На практике же возникли сложности: изменения разметки веб-версии Telegram, сложности с реализацией отложенной отправки сообщений. Но для WhatsApp, например, есть подобная уже готовая JavaScript-библиотека для автоматизации задач whatsapp-web.js.
Этот опыт показал: не всегда нужно изобретать велосипед. Puppeteer — отличный инструмент, но в этом случае он не оправдал себя. К счастью, существует более эффективное решение — библиотека Telethon на Python.
Telethon: находка для автоматизации
Telethon упрощает взаимодействие с Telegram. Забудьте о сложных настройках Puppeteer. Telethon — ваш личный программный ассистент.
Как это работает?
-
Регистрация приложения на my.telegram.org для получения
api_id
иapi_hash
. -
Авторизация своего скрипта с помощью номера телефона и кода подтверждения (если установлен).
Преимущества Telethon:
-
Простая установка (
pip install telethon
). -
Дополнительные возможности: чтение диалогов, создание чатов и каналов, скачивание медиафайлов.
С Telethon можно создавать сценарии общения. Главное — не переусердствовать, чтобы не попасть под бан аккаунта в Telegram.
Как избежать бана
Telegram не любит автоматизацию и тщательно следит за подозрительной активностью. Поэтому, если вы не хотите потерять доступ к своему аккаунту, нужно быть предельно аккуратным.
Чего точно не стоит делать? Массовая рассылка одинаковых сообщений. Но вам это не понадобится, ведь цель скрипта — общение с одним человеком, а не спам.
Как обезопасить себя? Используйте скрипт только для личного общения. Это уменьшает риск привлечь внимание системы.
Соблюдайте лимиты API, описанные в статье на Хабре. Например, не отправляйте больше 10 медиасообщений за 5 минут — даже с лёгкой анимацией это вызовет ошибку.
Скрипт: первая версия
# pip install telethon python-dotenv pytz
import asyncio
from telethon import TelegramClient
from datetime import datetime, timedelta, time
import random
import pytz
from dotenv import load_dotenv
import os
# Загрузка конфигурации
load_dotenv()
api_id = os.getenv("api_id")
api_hash = os.getenv("api_hash")
session_name = 'session_name'
# Таймзона и сообщения
ekb_timezone = pytz.timezone('Asia/Yekaterinburg')
messages = ["Доброе утро! Как твои дела?", "Привет! Надеюсь, у тебя всё отлично!"]
async def schedule_messages(client, user, messages, days):
for day in range(days):
send_time = ekb_timezone.localize(
datetime.combine(datetime.now().date() + timedelta(days=day + 1),
time(random.randint(8, 10), random.randint(0, 59)))
)
message = random.choice(messages)
await client.send_message(user, message, schedule=send_time.astimezone(pytz.UTC))
print(f"Сообщение запланировано: {message} на {send_time}")
async def main():
client = TelegramClient(session_name, api_id, api_hash)
await client.start()
user = await client.get_entity("USERNAME")
await schedule_messages(client, user, messages, 7)
await client.disconnect()
asyncio.run(main())
Подготовка:
-
Установите необходимые библиотеки:
pip install telethon python-dotenv pytz
. -
Создайте файл
.env
и добавьте тудаapi_id
иapi_hash
, полученные на my.telegram.org. -
Замените
USERNAME
на имя пользователя или номер телефона.
Полная версия скрипта
Полная версия скрипта автоматизации своей переписки с девушкой в Telegram представлена ниже. Скрипт подключается к аккаунту через API, загружает данные аутентификации из .env
, и планирует отправку случайных сообщений (утренних и дневных) для заданных пользователей в определённое время:
# pip install telethon python-dotenv pytz
import sys
sys.stdout.reconfigure(encoding='utf-8')
import asyncio
from telethon import TelegramClient, utils
from datetime import datetime, timedelta, time
import random
from dotenv import load_dotenv
import os
import pytz
# Загрузка переменных окружения из .env
load_dotenv()
api_id = os.getenv("api_id") # Ваш API ID
api_hash = os.getenv("api_hash") # Ваш API Hash
session_name = 'nodejs_session' # Название сессии
# Сообщения
greetings = [
"Доброе утро! Как ты себя чувствуешь сегодня?",
"Привет, как настроение? Готовность к новому дню?",
"Доброе утро! Что нового на сегодня?",
"Утро доброе! Как у тебя всё происходит с утра?",
"Доброе утро, как ты себя сегодня чувствуешь?",
"Привет! Как ты, как сны?",
"Как твои дела, готовность к этому дню?",
"Доброе утро! Как настроение, что планируешь на день?",
"Здравствуй! Как ты себя чувствуешь после сна?"
]
supportive_messages = [
"Как ты там? Всё в порядке?",
"Как проходит твой день?",
"Надеюсь, день не слишком утомительный для тебя!",
"Как настроение? Всё ли хорошо?",
"Не забывай делать перерывы, если устала!",
"Как ты? Чем занимаешься сейчас?",
"Если что-то нужно, не стесняйся мне писать.",
"Надеюсь, день приносит тебе только положительные моменты!",
"Как ты себя чувствуешь? Хочешь поговорить?"
]
# Таймзона Екатеринбурга
ekb_timezone = pytz.timezone('Asia/Yekaterinburg')
async def schedule_messages(client, user, messages, start_hour, end_hour, days, description):
"""Планирует сообщения для заданного пользователя на несколько дней."""
for day in range(days):
# Вычисляем дату и время в Екатеринбурге
now_ekb = datetime.now(ekb_timezone)
schedule_date_ekb = now_ekb.date() + timedelta(days=day + 1)
schedule_time_ekb = ekb_timezone.localize(datetime.combine(schedule_date_ekb, time(hour=random.randint(start_hour, end_hour), minute=random.randint(0, 30))))
# Конвертируем время в UTC для Telethon
schedule_time_utc = schedule_time_ekb.astimezone(pytz.UTC)
message_text = random.choice(messages)
try:
await client.send_message(user, message_text, schedule=schedule_time_utc)
print(f"✅ Отложенное сообщение отправлено для {description} на {schedule_time_ekb.strftime('%Y-%m-%d %H:%M:%S')}")
except Exception as e:
print(f"❌ Ошибка при отправке сообщения для {description}: {e}")
async def main():
client = TelegramClient(session_name, api_id, api_hash)
await client.start()
print("🚀 Запуск программы...")
try:
tasks = []
user_Name1 = await client.get_entity("empenoso") # имя пользователя
tasks.append(schedule_messages(client, user_Name1, greetings, 7, 7, 3, "пользователя userName")) # Утренние сообщения
tasks.append(schedule_messages(client, user_Name1, supportive_messages, 12, 12, 3, "пользователя userName")) # Дневные сообщения
user_Name2 = await client.get_input_entity("+7912XXXXX") # Непосредственно номер телефона
tasks.append(schedule_messages(client, user_Name2, greetings, 7, 7, 3, "пользователя +7912XXXXX")) # Утренние сообщения
await asyncio.gather(*tasks)
print("🎉 Все сообщения успешно настроены.")
except Exception as e:
print(f"❌ Ошибка: {e}")
finally:
await client.disconnect()
print("🔌 Соединение с Telegram завершено.")
if __name__ == '__main__':
asyncio.run(main())
Часовой пояс Екатеринбурга используется потому что я живу в Перми.
Заключение
Данная автоматизация — инструмент для выражения эмоций. Скрипт не заменит живое общение, но поможет не забыть проявить внимание. Отложенные сообщения — это лишь начало. Не переставайте общаться лично. Автоматизируйте с душой, искренностью и чувством меры!
Автор: Михаил Шардин
🔗 Моя онлайн-визитка
📢 Telegram «Умный Дом Инвестора»
27 января 2025 г.