- How to Install Telegram Messenger Application on Linux
- Features of Telegram
- Why Telegram?
- Installation of Telegram Messenger in Linux
- Less Interesting Points
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Install telegram-cli on CentOS
- telegram-cli
- Command-line interface for Telegram. Uses the readline interface.
- Details for telegram-cli
- Enable snaps on CentOS and install telegram-cli
- Enable snapd
- Install telegram-cli
- Telegram bot для Linux сервера: мониторинг, уведомления, управление
- Создание чат-бота в Telegram
- Отправка в чат Telegram уведомлений с сервера
- Управление Linux сервером в чат-боте Telegram
How to Install Telegram Messenger Application on Linux
Telegram is an Instant Messaging (IM) application similar to whatsapp. It has a very large user base. It has a lot of features that differentiate it from other messaging application.
This article aims at making you aware of telegram application followed by detailed installation instructions on Linux Box.
Features of Telegram
- Implementation for mobile devices
- Available for Desktop.
- Application Program Interface (API) of Telegram can be Accessed by third party developers.
- Available for Android, iphone/ipad, Windows Phone, Web-Version, PC, Mac and Linux
- The above application provides Heavily Encrypted and self destruct messages.
- Lets you access your message from multiple devices and platform.
- The overall processing and message delivery is lightening fast.
- Distributed server across the globe for security and speed.
- Open API and Free Protocol
- NoAds, No Subscription charge. – Free forever.
- Powerful – No limit to media and chats
- Several security measures that make it safe from Hackers.
- Reply to Specific message in group. Mention @username to notify multiple users in group.
Why Telegram?
When Applications like whatsapp and other IM are providing almost same things in bag, why should someone opt for Telegram?
Well Availability of API to third party developer is enough to say. Moreover availability for PC which means you won’t have to struggle typing message using your mobile, but you can use your PC and that is pretty more than sufficient.
Also The option to connect on remote locations, Co-ordinate – Group of upto 200 Members, Sync all your devices, Send – Documents of all kind, Encrypt message, Self destruction of message, Storage of Media in Cloud, Build own tool on freely available API and what not.
Testing Environment
We have used Debian GNU/Linux, x86_64 architecture to test it and the overall process went very smooth for us. Here what we did stepwise.
Installation of Telegram Messenger in Linux
First go to the official Telegram site, and download Telegram source package (tsetup.1.1.23.tar.xz) for Linux system or you may use following wget command to download directly.
Once package has been downloaded, unpack the tarball and switch from current working directory to the extracted directory.
Next, execute the binary file ‘Telegram’ from the command line as shown below.
1. The first Impression. Click “START MESSAGING”.
Start Messaging
2. Enter Your phone Number. Click “NEXT”. If you have not registered for telegram before this, using the same number as entered above you will get a warning that you don’t have a telegram account yet. Click “Register Here”.
Signup for Telegram
3. After submitting your phone number, telegram will send you a verification code, shortly. You need to Enter it.
Telegram Verification Code
4. Enter your First_Name, Last_name and pics and click “SIGNUP”.
Enter Account Details
5. After account creation, I got this interface. Everything seems at its place, even when I am new to telegram Application. The interface is really simple.
Telegram Interface
6. Click Add a contact and Enter Their first_name, last_name and Phone number. Click create when done!.
Add New Telegram Contact
7. If the contact you added is not on telegram already, You get a warning message and telegram will acknowledge you when your contact joins telegram.
Telegram Contact Notification
8. As soon as the contact joins telegram you get a message (pop-out like) that reads [YOUR_CONTACT] joined telegram.
9. A formal chat window on Linux Machine. Nice experience…
Telegram Contact Join Message
10. At the same time, I’ve tried messaging from my android mobile device, the interface looks similar on both.
Telegram Mobile Interface
11. Telegram settings page. You have a lot of options to configure.
Telegram Settings
12. About Telegram.
About Telegram
Less Interesting Points
- Telegram usage protocol MTProto Mobile protocol.
- Released Initially for iPhone in the year 2013 (August 14)..
- People Behind this Amazing Project: Pavel and Nikolai Durov..
That’s all for now. I’ll be here again with another interesting article you will love to read. I take the pleasure on behalf of Tecmint to thank all our valuable readers and critics who made us stand where we are now through continuous self evolving process. Keep Connected! Keep Commenting. Share if you care for us.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Install telegram-cli
on CentOS
telegram-cli
- Marius Quabeck (marius-quabeck) Publisher
- Social
Command-line interface for Telegram. Uses the readline interface.
Telegram-cli is a command-line interface for Telegram, using the Telegram API and libopenssl for encryption. Type help to list all commands, the app comes with exhaustive tab-completion. Source code available at https://github.com/vysheng/tg
Details for telegram-cli
Enable snaps on CentOS and install telegram-cli
Snaps are applications packaged with all their dependencies to run on all popular Linux distributions from a single build. They update automatically and roll back gracefully.
Snaps are discoverable and installable from the Snap Store, an app store with an audience of millions.
Enable snapd
Snap is available for CentOS 7.6+, and Red Hat Enterprise Linux 7.6+, from the Extra Packages for Enterprise Linux (EPEL) repository. The EPEL repository can be added to your system with the following command:
Snap can now be installed as follows:
Once installed, the systemd unit that manages the main snap communication socket needs to be enabled:
To enable classic snap support, enter the following to create a symbolic link between /var/lib/snapd/snap and /snap :
Either log out and back in again, or restart your system, to ensure snap’s paths are updated correctly.
Install telegram-cli
To install telegram-cli, simply use the following command:
Источник
Telegram bot для Linux сервера: мониторинг, уведомления, управление
В этой статье мы рассмотрим пример использования Telegram бота на сервере с Linux CentOS, покажем, как настроить простые уведомления в чат-бот для мониторинга вашего сервера, а также несколько управляющих команд.
В эпоху мобильных гаджетов, стало актуально использование различных мессенджеров не только для общения с реальными людьми, но и использование различных ботов. Например, в Telegram существует широкий функционал для бота, который можно использовать в различных целях — выдать информацию о заказе клиенту, информация по посылке у почтового оператора и, например, мониторинг собственного сервера.
Создание чат-бота в Telegram
Для создания чат-бота в Telegram используется бот @BotFather. Чтобы создать своего бота, нужно найти @BotFather у себя в Telegram и перейти в чат с ним:
Нажмите START. Чтобы создать нового бота, выберете в меню /newbot, введите имя бота в формате “имя_bot». После создания бота, вы получите API токен бота, который нужен будет в дальнейшей настройке.
Теперь нужно узнать user_id — это ID часа с ботом, в который он будет отправлять уведомления. Перейдите в ваш с ним чат и нажмите старт и отправить любой символ. После этого в браузере перейдите по адресу:
https://api.telegram.org/bot /getUpdates — где это API который выдал BotFather.
На скриншоте выделен ваш ID.
Итак, мы создали бота в Telegram и получили авторизационные данные.
Отправка в чат Telegram уведомлений с сервера
С помощью ранее созданного бота и полученных ID можно отсылать с сервера уведомления в Telegram чат, и таким образом получать какие-то интересные нам данные или алерты.
Для отправки сообщения в чат, нужно использовать следующий URL:
https://api.telegram.org/bot /sendMessage?chat_id= &text=
# curl -s -X POST https://api.telegram.org/bot944496485:AAEtGaGCVrQ7d26Rc3r_cqXPIhrKVokh8e4/sendMessage -d chat_id=336116180 -d text=»Доброе утро, страна»
Для чего можно использовать такие Telegram уведомления? Например, при создании резервной копии вы можете отправлять уведомления о ее создании или же отправлять ссылку на скачивание копии в чат с ботом. Вы можете отправлять себе в Telegram уведомления с информацией о сбоях в системе. Можно добавить в крон выполнение каких-либо проверок с последующей отправкой в Telegram.
Еще пример использования подобных уведомлений:
# curl -s -X POST https://api.telegram.org/bot944496485:AAEtGaGCVrQ7d26Rc3r_cqXPIhrKVokh8e4/sendMessage -d chat_id=336116180 -d text=» User $(whoami) logged into $(hostname) on $(date) from $(echo $SSH_CLIENT | awk ‘< print $1>‘)» &>/dev/null 2>&1
Добавьте этот код в /etc/profile и будете получать уведомления в Telegram при каждом входе пользователей на сервер:
Хочу напомнить, что во всех командах, нужно указывать именно своей token(API) и ID чата.
Управление Linux сервером в чат-боте Telegram
Есть набор скриптов, которые позволяет управлять сервером Linux из Telegram чата, отправляя различные команды в чат с ботом. Для этого нужно установить Python, ряд инструментов и загрузить на сервер скрипты.
# wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
# yum install xz -y
# tar -xpJf Python-3.6.0.tar.xz
# cd Python-3.6.0
# yum groupinstall «Development tools» -y
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel -y
# ./configure
# make
# make install
Создайте симлинк для Python:
# ln -s /usr/local/bin/python3 /usr/bin/python3
И установите ПО для самого бота:
# pip3 install python-telegram-bot —upgrade
Теперь скачайте и распакуйте к себе на сервер в каталог root/admin три файла из архива telegram_bot.zip:
Рассмотрим файл config.py. В нем нам нужно указать token(API) и ID вашего чата с ботом, а также путь до директорий с бэкапами и директории, размер которой вы будете в дальнейшем проверять:
Файл bot.sh не требует настройки, в нем лишь указываем путь до bot.py:
И самый основной файл, который собственно и позволит нам управлять сервером, это bot.py. В нем описаны функции, которые будут доступны в чате с ботом и собственно туда, мы можем добавлять свой собственный функционал. Например, в первом блоке описываются доступные команды бота в чате:
Тут описываются все функции, которые будут доступны, после ввода команды /help.
Ниже описывается сама функция, например,
И эту функцию, нужно описать как команду:
То есть как видим, это выполнение стандартной функции проверки сетевых настроек ifconfig.
При знакомстве с ботом я попытался добавить собственную команду, например для проверки Apache:
# service httpd status
Но только через настройку данного файла это не сработало. Как я понял, здесь можно выполнить только команду описанную одним словом или символами. Я решил проблему создав файл apache_status.sh с содержимым:
#!/bin/bash
service httpd status
И создал на него симлинк:
# ln -s /root/admin/apache_status.sh /usr/local/sbin/apachestatus
Теперь при вызове команды apachestatus, у меня выводит статус веб-сервера apache:
В файле bot.py я заполнил все три блока, согласно других функций. Чтобы bot заработал, нужно запустить файл bot.sh. Для удобства, создадим отдельный сервис для Telegram бота. Создаем нужный файл и выставляем права:
# touch /etc/systemd/system/telegram-bot.service
# chmod 664 /etc/systemd/system/telegram-bot.service
После чего заходим в файл сервиса:
И добавляем содержимое:
# systemctl start telegram-bot.service
# systemctl enable telegram-bot.service
# systemctl status telegram-bot.service
Теперь, если в чате с вашим ботом ввести /help, вы получите список доступных команд.
Например, в данный момент у меня на сервере остановлен веб-сервер Apache:
Запустим его на сервере и проверим статус через Telegram:
Еще несколько примеров выполнения команд:
Таким образом, вы можете выполнять мониторинг своего Linux сервера или даже частичное администрирование через Telegram, что поможет сильно сократить время на выполнение типовых действий.
Так же хотел бы заметить, что авторизация сервера с ботом происходит именно по ID и token(API) (любой другой человек, не зная ваших данных, подключиться не сможет).
На момент выпуска статьи, тестовый бот удален.
Источник