Telegram cli for windows

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

  1. 1. Download Cygwin: https://cygwin.com/install.html

  2. 2. Select these packages in Cygwin installer: cygwin32-gcc-core, cygwin32-gcc-g++, gcc-core, gcc-g++, make, wget, patch, diffutils, grep, tar, gzip, libevent-devel, openssl-devel, libreadline-devel, lua-devel, python3, dos2unix, zlib, zlib-devel

  3. 3. In Cygwin Terminal execute commands:

  4. 1) Install libconfig:

  5. wget https://sources.voidlinux.eu/libconfig-1.5/libconfig-1.5.tar.gz

  6. tar xvf libconfig-1.5.tar.gz && cd libconfig-1.5

  7. ./configure

  8. make && make install && cd ..

  9. 2) Install libjansson:

  10. wget http://www.digip.org/jansson/releases/jansson-2.7.tar.gz

  11. tar xvf jansson-2.7.tar.gz && cd jansson-2.7

  12. ./configure

  13. make && make install && cd ..

  14. 3) Download telegram-cli (git required):

  15. git clone —recursive https://github.com/vysheng/tg.git

  16. cd tg

  17. 4) Fix line-endings and configure:

  18. dos2unix —force configure

  19. ./configure

  20. 5) Patch makefile and loop.c:

  21. wget https://cloud.githubusercontent.com/assets/26854204/24589037/03d66608-17e9-11e7-8d4b-d4a790521fee.jpg

  22. mv 03d666*.jpg makefileloopc.zip

  23. 6) unzip makefileloopc.zip in tg then execute

  24. make

  25. 7) If u get some spooky errors add

  26. #define EVENT_V2 1

  27. at the end of config.h then execute make again

  28. 8) Now you can run telegram-cli from Cygwin Terminal:

  29. bin/telegram-cli -k tg-server.pub

Всем привет. На днях начал своё знакомство с консольным клиентом для Telegram. Решил по этому поводу написать пару статей.
Для начала расскажу, как это дело установить, в следующей части опишу, как запускать telegram-cli в виде демона в системах с systemd, а в качестве бонуса будет статья о том, как написать обёртку под всё это для zsh, и, моё любимое, автодополнение по tab’у.

Установка

У меня стоит Fedora 22 в репозиториях которой присутствует telegram-cli, поэтому если вы в таких же условиях, то можно сделать так:

sudo dnf install telegram-cli

Но мы пойдём другим путём и установим его из сорцов, тем более что это делается очень просто.

Сборка из исходников

Историческая справка
Раньше в UNIX системах директория /opt использовалась для пакетов сторонних производителей. opt это сокращение от option, что можно перевести как опциональный или необязательный; туда, например попадали пакеты, за которые вы заплатили деньги. В BSD Unix системах вместо /opt для этих целей использовали /usr/local.
via

Я предпочитаю устанавливать сторонние программы в директорию /opt. Перейдём в неё и клонируем репозиторий

sudo git clone --recursive https://github.com/vysheng/tg.git /opt/tg
cd /opt/tg

Дальше нужно установить зависимости. В исторукции из репозитория написано установить libjansson-devel, который моему dnf’у найти не удалось, зато он нашёл jansson-devel.

sudo dnf install -y lua-devel openssl-devel libconfig-devel readline-devel libevent-devel jansson-devel python-devel

Мы уже находимся в каталоге /opt/tg поэтому начнем сборку.

Если всё прошло хорошо, то в папке bin должен появиться telegram-cli. Осталось запихнуть его куда-нибудь в пути.

ln -s /opt/tg/bin/telegram-cli /usr/bin/

Пробуем запустить

Получилось? Тогда учимся пользоваться.

Запуск

Сначала telegram-cli спросит номер телефона. Вводим. Ждём сообщения с кодом. Вводим код. Получаем доступ к командной строке.

Вид из командной строки Пришедший код

Использование

Что первым делом нужно вводить в любую консоль?

Посмотрим, что у нас есть

Доступные команды

Для начала сделаю лирическое отступление и расскажу, что такое peer и как его употреблять.

Из официальной документации
Peer это имя контакта или диалога; можно дополнять по TAB’у. Все пробелы заменяются на нижние подчеркивания.
Если у двух пользователей одинаковые имена, то к ним добавляется номер телефона. (например, Имя_Фамилия будет Имя_Фамилия#1, Имя_Фамилия#2 и так далее)

Чтобы появилась возможность отправлять сообщения, нужно сначала получить все диалоги с помощью dialog_list, либо запускать клиент с параметром -W. Рекомендую второе.

peer я оставлю без перевода и буду писать пир

Общение

  • msg <peer> Text — отправить сообщение пиру
  • fwd <user> <msg-seqno> — переслать сообщение пользователю. Вы можете видеть номера сообщений, запуская клиент с опцией -N
  • chat_with_peer <peer> — начать переписку с этим пиром. /exit или /quit для завершения этого режима.
  • add_contact <phone-number> <first-name> <last-name> — попытаться добавить контакт в список контактов по номеру телефона
  • rename_contact <user> <first-name> <last-name> — попытаться переименовать контакт. Если у вас есть несколько устройств, то будет битва
  • mark_read <peer> — отметить прочитанными все сообщения от пира
  • delete_msg <msg-seqno> — удалить сообщение (но не полностью)
  • restore_msg <msg-seqno> — восстановить удалённое сообщение. Невозможно для серкретного чата. Возможно только некоторое время спустя (один час, я думаю) после удаления

Мультимедия

  • send_photo <peer> <photo-file-name> — отправить фото
  • send_video <peer> <video-file-name> — отправить видео
  • send_text <peer> <text-file-name> — отправить содержимое файла текстом
  • load_photo/load_video/load_video_thumb/load_audio/load_document/load_document_thumb <msg-seqno> — загрузить фото/видео/аудио/документ в директорию загрузок
  • view_photo/view_video/view_video_thumb/view_audio/view_document/view_document_thumb <msg-seqno> — загрузить фото/видео в папку загрузок и открыть стандартным просмоторщиком
  • fwd_media <msg-seqno> послать медиа файл в сообщении. Используйте это, чтобы скрыть информацию об авторе медиа файла (хотя всё ещё будет возможно найтиuser_id из самого медиа файла, но невозможно получить access_hash этого пользователя)
  • set_profile_photo <photo-file-name> — установить фотографию профиля. Обрезается до квадрата

Групповые чаты

  • chat_info <chat> — вывести информацию о чате
  • chat_add_user <chat> <user> — добавить пользователя в чат
  • chat_del_user <chat> <user> — удалить пользователя из чата
  • rename_chat <chat> <new-name>
  • create_group_chat <chat topic> <user1> <user2> <user3> … — создать групповой чат с пользователями, используйте chat_add_user чтобы добавить больше пользователей
  • chat_set_photo <chat> <photo-file-name> — поставить фото на чат. Обрезается до квадрата

Поиск

  • search <peer> pattern — поиск pattern в сообщениях с пиром
  • global_search pattern — поиск pattern во всех сообщениях

Секретный чат

  • create_secret_chat <user> — создать секретный чат с пользователем
  • visualize_key <secret_chat> — вывести визуализацию ключа шифрования. Вы должны сравнить его с ключем вашего собеседника
  • set_ttl <secret_chat> <ttl> — установить ttl в секретном чате. Не смотря на то, что клиент игнорирует это, вашему собеседнику это может быть полезно
  • accept_secret_chat <secret_chat> — вручную принять секретный чат (действенно только если клиент запущен с ключём -E)

Статистика и информация

  • user_info <user> — вывести информацию о пользователе
  • history <peer> [limit] — вывести историю (и пометить прочитаными). Лимит по умолчанию = 40
  • dialog_list — вывести информацию о диалогах
  • contact_list — вывести информацию о пользователях в вашем списке контактов
  • suggested_contacts — вывести информацию о пользователях с которыми у вас много общих друзей
  • stats — для отладки
  • show_license — показать лицензию(GPLv2)
  • help — вывести этот хэлп
  • get_self — получить инфорцию о своем пользователе

Карточки

  • export_card — вывести ваше ‘карточку’ которую каждый позже может импортировать себе в контакты
  • import_card <card> — получить пользователя по карточке. После этого вы сможете писать ему сообщения

Остальное

  • quit — выйти
  • safe_quit — подождать завершения всех запросов и выйти

Практика

Напишем сообщение Даниле и посмотрим, что он ответит. Отправить сообщение можно не сразу, сначала нужно дождаться, пока прогрузяться все контакты.

telegram-cli -W
msg Данила ping

Готово! Вы восхетительны.

В следующей статье мы рассмотрим, как сделать из этого добра systemd демона, чтобы не ждать каждый раз прогрузки контактов.

Apps

Published on June 1st, 2014 | by Sunit Nandi

Telegram has grabbed the headlines for being a non-profit and open alternative to the existing mobile messengers. It is often touted as the service which has the capability to replace WhatsApp, given the features it provides:

  • Telegram messages are heavily encrypted and can self-destruct.
  • Telegram lets you access your messages from multiple devices.
  • Telegram delivers messages faster than any other application.
  • Telegram servers are spread worldwide for security and speed.
  • Telegram has an open API and protocol free for everyone.
  • Telegram is free forever. No ads. No subscription fees.
  • Telegram keeps your messages safe from hacker attacks.
  • Telegram has no limits on the size of your media and chats.

Okay, so that was the whole point of using Telegram messenger in a gist. What we’ll be focussing on now, is its ability to be used on multiple devices, even devices (or computers) that have no GUI.

If you are one of those guys who are referred to as a developer, a hacker, an administrator or you simply need to spend a lot of time in the command-line, you know how much of a pain it is to switch between windows with the mouse to use a GUI application all of a sudden. So you’d prefer using the terminal for almost everything you can do. Your choice of messaging would definitely be irssi for IRC, and some of you might be familiar with BitlBee, which is an IRC-to-IM gateway which eliminates your need to install multiple IM software. If this is your case, read on to know how to use Telegram in the command-line.

Introducing Telegram CLI

Oh yes, you heard it right. Telegram CLI is a command-line client for Telegram, made by Vitaly Valtman. It uses the readline interface to take input from the user to perform requested actions. This client runs on Linux, BSD and Mac.

Telegram CLI’s source code is on GitHub.

Lets us proceed with the installation.

Installation

Installing from distribution repositories

On Fedora type the following into the terminal:

yum install telegram-cli

Make sure you have the latest version of Fedora (i.e. Fedora 20 at the time of writing this post).

On Ubuntu 13.04 and 13.10 type the following into the terminal:

sudo apt-add-repository ppa:miry/ppa
sudo apt-get update && sudo apt-get install telegram-cli

On Ubuntu 14.04 64-bit type the following into the terminal command by command:

wget https://bugs.launchpad.net/~miry/+archive/ppa/+files/telegram-cli_0.0.20140125-1_amd64.deb
sudo dpkg -i ./telegram-cli_0.0.20140125-1_amd64.deb
sudo apt-get -f install

On Ubuntu 14.04 32-bit type the following into the terminal command by command:

wget https://bugs.launchpad.net/~miry/+archive/ppa/+files/telegram-cli_0.0.20140125-1_i386.deb
sudo dpkg -i ./telegram-cli_0.0.20140125-1_i386.deb
sudo apt-get -f install

I would like to thank Miriam Ruiz for the PPA, and hence making our lives easier.

Arch Linux has the telegram-git PKGBUILD on AUR (thanks to the maintainers atweiden and trichards). If you have the yaourt utility, you can easily install it by typing the following in the terminal:

yaourt -S telegram-git

Gentoo users can use this EBUILD: http://gpo.zugaina.org/net-im/telegram-cli

All the above methods take care of the dependencies automatically.

Building Telegram

Building Telegram CLI on Arch Linux

Installing from source

If your distribution is not listed above or if you prefer to manually compile from source, try this method.

First of all, lets install the dependencies.

On Ubuntu and Debian use:

sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev

On Gentoo use:

sudo emerge -av sys-libs/readline dev-libs/libconfig dev-libs/openssl dev-lang/lua

On Fedora use:

sudo yum install lua-devel openssl-devel libconfig-devel readline-devel

On Arch Linux use:

pacman -S libconfig lua

On FreeBSD use:

pkg install libconfig libexecinfo lua52

On OpenBSD use:

pkg_add libconfig libexecinfo lua

After that we need to clone the Telegram CLI GitHub repository. Make sure git is installed. Then type the following:

git clone https://github.com/vysheng/tg.git && cd tg

Alternatively you can download and extract the zip:

wget https://github.com/vysheng/tg/archive/master.zip -O tg-master.zip
unzip tg-master.zip
cd tg-master

Then, we need to run the compile process:

./configure
make

Telegram CLI will be compiled in current directory itself.

If you are on Mac OS X, you need Homebrew to install the readline library and libconfig in the following manner:

brew install libconfig
brew install readline
brew install lua
export CFLAGS="-I/usr/local/include -I/usr/local/Cellar/readline/6.2.4/include"
export LDFLAGS="-L/usr/local/lib -L/usr/local/Cellar/readline/6.2.4/lib"
./configure && make

Then install these ports:

  • devel/libconfig
  • devel/libexecinfo
  • lang/lua52

After that, compile Telegram CLI this way:

env CC=clang CFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib LUA=/usr/local/bin/lua52 LUA_INCLUDE=-I/usr/local/include/lua52 LUA_LIB=-llua-5.2
./configure
make

Telegram CLI will be compiled in current directory itself.

Now, lets try using it.

Usage

Running the application

If you installed Telegram CLI from your distribution’s repositories, launch the application by:

telegram -k /etc/telegram/tg.pub

Otherwise, if you compiled from source, run it from its directory with:

./telegram -k tg-server.pub

It will ask for your phone number. Type in the number and press ENTER. After that, a code will be generated which will be sent to your phone via SMS or chat. Type that code into the terminal when it asks for it.

Telegram CLI first run

Running Telegram CLI for the first time

Supported commands

The application supports TAB completion and command history.

Also, the official documentation states the definition of ‘peers’ :

“Peer refers to the name of the contact or dialog and can be accessed by TAB completion. For user contacts peer name is Name Lastname with all spaces changed to underscores. For chats it is it’s title with all spaces changed to underscores For encrypted chats it is Name Lastname with all spaces changed to underscores.

If two or more peers have same name, number is appended to the name. (for example A_B, A_B#1, A_B#2 and so on)”

The supported commands are (from ‘help’ command):

'help' command

‘help’ command

Messaging

  • msg <peer> Text – sends message to this peer
  • fwd <user> <msg-seqno> – forward message to user. You can see message numbers starting client with -N
  • chat_with_peer <peer> starts one on one chat session with this peer. /exit or /quit to end this mode.
  • add_contact <phone-number> <first-name> <last-name> – tries to add contact to contact-list by phone
  • rename_contact <user> <first-name> <last-name> – tries to rename contact. If you have another device it will be a fight
  • mark_read <peer> – mark read all received messages with peer

Multimedia

  • send_photo <peer> <photo-file-name> – sends photo to peer
  • send_video <peer> <video-file-name> – sends video to peer
  • send_text <peer> <text-file-name> – sends text file as plain messages
  • load_photo/load_video/load_video_thumb <msg-seqno> – loads photo/video to download dir
  • view_photo/view_video/view_video_thumb <msg-seqno> – loads photo/video to download dir and starts system default viewer

Group chat options

  • chat_info <chat> – prints info about chat
  • chat_add_user <chat> <user> – add user to chat
  • chat_del_user <chat> <user> – remove user from chat
  • rename_chat <chat> <new-name>
  • create_group_chat <user> <chat topic> – creates a groupchat with user, use chat_add_user to add more users

Search

  • search <peer> pattern – searches pattern in messages with peer
  • global_search pattern – searches pattern in all messages

Secret chat

  • create_secret_chat <user> – creates secret chat with this user
  • visualize_key <secret_chat> – prints visualization of encryption key. You should compare it to your partner’s one

Stats and various info

  • user_info <user> – prints info about user
  • history <peer> [limit] – prints history (and marks it as read). Default limit = 40
  • dialog_list – prints info about your dialogs
  • contact_list – prints info about users in your contact list
  • suggested_contacts – print info about contacts, you have max common friends
  • stats – just for debugging
  • show_license – prints contents of GPLv2
  • help – prints this help

Experience

Telegram CLI is pretty full-featured even though it is marked as ‘beta’. It does everything what the official mobile client does. Multimedia sending and secret chats work as expected. Chatting with buddies makes one nostalgic of the good ol’ CLI (read DOS) days.

'user_info' command

Displaying details for a contact

Chat history

Viewing the chat history

Live chat

Chatting with a buddy

The client is a bit too verbose with status messages while chatting, which I think could have been reduced to a certain extent, which in turn, will make the output look a lot cleaner.

Nevertheless, it works perfectly and I do not have any more complaints.

Conclusion

Telegram CLI is a pretty handy tool if you are use the terminal a lot and too often. It frees you from having to move the mouse to switch windows or lifting your phone from your pocket to reply to your friends in the midst of work. Combined with the GNU screen utility, you’ll have the ability to chat with your friends and develop/administer at the same time. Such is the convenience of having an open mobile messenger platform that WhatsApp, Hike, WeChat, Line, etc. cannot offer.

If setting up a CLI client is too hard for you, you can give Webogram a try. It works right inside a browser and is also available as a Chrome app. However, it lacks support for secret chats and many other features.

I hope that this guide has helped you. If you have anything to suggest, feel free to leave a comment.

If you have trouble setting up and using Telegram CLI, you can open a discussion on our forum or Facebook group and I’ll try my best to help you out.

Don’t have the requirements to try out this guide? You can use a really cheap Linux/Unix virtual machine on the DigitalOcean cloud to try Telegram CLI out.

Thank you for reading this article. Make a great day!

Tags: CLI, command line, libconfig, liblua, lua, messaging, readline, Telegram

About the Author

I’m the leader of Techno FAQ. Also an engineering college student with immense interest in science and technology. Other interests include literature, coin collecting, gardening and photography. Always wish to live life like there’s no tomorrow.

/apt

sh

sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev libpython-dev libpython3-dev libgcrypt-dev zlib1g-dev lua-lgi make \
&& ./configure \
&& make
gentoo/emerge

sh

sudo emerge -av sys-libs/readline dev-libs/libconfig dev-libs/openssl dev-lang/lua dev-libs/libevent dev-libs/jansson dev-lang/python \
&& ./configure \
&& make
darwin/brew

sh

brew tap ivoputzer/tg && brew install tg
arch/yay

sh

sudo yay -S telegram-cli-git \
&& ./configure \
&& make
centos/yum

sh

sudo yum install lua-devel openssl-devel libconfig-devel readline-devel libevent-devel jansson-devel python-devel \
&& ./configure \
&& make
fedora/dnf

sh

sudo dnf install lua-devel openssl-devel libconfig-devel readline-devel libevent-devel jansson-devel python-devel libgcrypt-devel \
&& ./configure \
&& make
freebsd/pkg

sh

sudo pkg install telegram-cli
openbsd/pkg_add

sh

sudo pkg_add libconfig libexecinfo lua python
opensuse/zypper

sh

sudo zypper in lua-devel libconfig-devel readline-devel libevent-devel libjansson-devel python-devel libopenssl-devel \
&& ./configure \
&& make

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Драйвер qualcomm atheros ar9002wb 1ng wireless network adapter windows 10
  • Как настроить блокировку экрана на windows 11
  • Где взять темы для windows 10
  • Нет папки msahci в реестре windows 10
  • Myfinepix studio для ос windows