Follow

cat telegram-cli-note

adduser --system --no-create-home --disabled-login telegramd

github.com/vysheng/tg/wiki/Run

Running Telegram CLI as Daemon
Muhammad Zamroni edited this page on Jun 14, 2015 · 4 revisions
Pages 7

Home
Running Telegram CLI as Daemon
Scripting notes
Telegram CLI Arguments
Telegram CLI Commands
TODO
User level daemon on Arch linux with systemd

Clone this wiki locally

This is how Telegram run as daemon on debian-based. We will run it using sudo.

All commands are executed from telegram-cli's repository directory.
Add User telegramd

This telegramd user will run the telegram-daemon

sudo adduser telegramd

Add Script telegram-daemon to /etc/init.d

sudo cp telegram-daemon /etc/init.d/

Create Base Directory for telegram-daemon

This directory is place for binlogs and lua-scripts. It is also default directory for telegram-daemon user.

sudo mkdir /var/lib/telegram-daemon

The contents of /var/lib/telegram-daemon directory, will be:

binlog-achat.bin
binlog-z5.bin
config-achat
config-z5
downloads
script-achat.lua
script-z5.lua

Files config-* are auto generated by telegram-daemon, you don't need to edit them.

Files binlog-*.bin are binlogs. You have to authorize separately then copy the binlog file here. You can edit the scripts to use version without binlogs.

Files script-*.lua are lua scripts.
Create Binaries Directory

This directory is place for binaries (telegram-cli) and start/stop (start-telegram-daemon)

sudo mkdir /usr/share/telegram-daemon
sudo mkdir /usr/share/telegram-daemon/bin
sudo cp bin/telegram-cli /usr/share/telegram-daemon/bin/
sudo cp start-telegram-daemon /usr/share/telegram-daemon/bin

The contents of /usr/share/telegram-daemon/bin/ directory will be:

start-telegram-daemon
telegram-cli

Create Config Directory

sudo mkdir /etc/telegram-daemon

Create telegram-daemon.achat.conf

In folder /etc/telegram-daemon, create this file using sudo nano /etc/telegram-daemon/telegram-daemon.achat.conf command.

execute telegram-cli
-d
-vvvv
-E
-R
-D
-C
-P 2391

This script will run daemon on port 2391. Feel free to change the port number.
Create telegram-daemon.z5.conf
Create Logs Directory

sudo mkdir /var/log/telegram-daemon

Create Server Key Directory

This is place for server's public key.

sudo mkdir /etc/telegram-cli
sudo cp server.pub /etc/telegram-cli/server.pub

Usage

server:~# /etc/init.d/telegram-daemon status
telegram-daemon-achat: 19901 0 Sep23 00:00:02 telegram-cli -vvvv -E -R -D -C -P 2391 -u telegramd -L /var/log/telegram-daemon/telegram-daemon-achat.log -c config-achat
telegram-daemon-z5: failed (pid 19900)
server:~# /etc/init.d/telegram-daemon restart z5
start-stop-daemon: warning: failed to kill 19900: No such process
telegram-daemon-z5: stopped
restarting telegram-daemon-z5...
server:~# /etc/init.d/telegram-daemon status
telegram-daemon-achat: 19901 0 Sep23 00:00:02 telegram-cli -vvvv -E -R -D -C -P 2391 -u telegramd -L /var/log/telegram-daemon/telegram-daemon-achat.log -c config-achat
telegram-daemon-z5: 22222 15 14:22 00:00:00 telegram-cli -vvvv -E -R -D -C -P 2392 -u telegramd -L /var/log/telegram-daemon/telegram-daemon-z5.log -c config-z5

By using listening to tcp port, we can send commands to daemon via netcat or telnet. Example using netcat:

nc localhost 2391
dialog_list
msg vysheng kudos

Contact GitHub API Training Shop Blog About

---------------------------------------------------------------

if you are using telegram-cli binary:
apt-get install libjansson4 libconfig9

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------


apt-get update && apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev libpython-dev make git
cd ~ && git clone --recursive github.com/vysheng/tg.git && cd tg

stable branch:
./configure && make

test branch:
git checkout test to test latest branch
./configure
make clean && git submodule update --recursive && ./configure -q && make -j4

..
cp bin/telegram-cli /usr/local/bin/
mkdir -p /etc/telegram-cli
-cli -k tg-server.pub
mv tg-server.pub /etc/telegram-cli/server.pub


telegram-cli -W


rm -rf ~/.telegram-cli # remove account

#!/bin/bash
telegram-cli -W -e "msg <replace_with_peer> $1"
telegram-cli -W -e "send_document <replace_with_peer> $1"
telegram-cli -W -e "post <channel> $1"

include apostrophe and newline
#!/bin/bash
text=$(echo $* | sed "s|\x27|\\\'|g")
telegram-cli -W -e "post <channel> '$text'"
telegram-cli -W -e "post <channel> '$text'" --disable-link-preview

you are using bin to another machine,
apt-get install -y libjansson4 libconfig9 liblua5.2-0

script
telegram-cli -s

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

LONG:

Send Push Notifications and Any File with Telegram Messenger on the Raspberry Pi
Posted Wednesday, 07 Jan by madcoffee
Tags: Telegram-Messenger, Push-Notification, Raspb

With the telegram-cli command-line client, you can send text, picture or video messages as push notifications from any application, send end-to-end encrypted messages that can destruct themselves, build a bot that executes tasks based on the message you send it, ...

alt
This article covers

How Telegram Messenger is different from WhatsApp
How to install and configure telegram-cli on the Raspberry Pi
Examples how to use telegram-cli
How to send push notifications, pictures, videos or files from the RaspberryPi to your mobile phone
Thoughts about Building a Telegram Bot

Telegram Messenger vs WhatsApp

Works on the Phone AND on the computer
WhatsApp only runs on mobile Phone operating systems. If you want to use it on a PC, you need an emulator and another phone number.
Telegram can be installed directly on a PC. So you can respond to messages using a keyboard instead of having to type on a touch screen. Also if you just saw a video on your PC, then you could send it to a contact from your PC directly. There is no need to first get the URL somehow to your mobile phone to send it. Telegram runs on iPhone, iPad, Android, Windows Phone 8, most linux systems, Mac OS X, Windows, and as Telegram Web App from the Browser. (See Telegram Applications)
Messages are synchronized across devices
The only synchronization by WhatsApp is a backup copy once a day that excludes videos and other content.
With Telegram, you can switch from your phone to your PC, and all the chat history (except of secret chats) is synchronized. If you get a message, then it will be delivered to all your devices. You can choose where you want to respond. If you have a second mobile phone, then you can use the same telegram account (login phone number) on both phones. Skype users would say that synchronization is nothing new, but being used to WhatsApp, it fells like going from 2D to 3D.
You can send any FILE to others or to yourself
Can you send PDF files with WhatsApp? No, just pictures, videos, contacts and the location. WhatsApp will downsize your picture and video without asking, which is often annoying.
Telegram in contrast gives you more choice. When you send a picture as 'file' then the original size and filename will be retained. If you send a video you will be asked if you want to send a compressed version or the original version. Further, you can send a PDF or any other file type from your PC to yourself and then access it on any device. So it can be used as cloud storage like Dropbox. A single file can be up to 1.5 GB. I tried sending two 1 GB files plus one 0.5 GB file without problems.
Chat with people without giving them your phone number
Telegram uses the phone number of your contacts to find friends that you can chat with. However you can also chat with people from which you only know the username like with Skype. For example, if a website wants to interact with its users, then it could post a telegram.me/YourUsername link. This link will open the Telegram Web App or mobile phone Telegram App. Then you can chat and neither side can see the phone number from the other. If you set a username, then you can be found in the global address book by anyone, like with Skype.
Geochats
A Geochat is a public chat between people within a specific geographic radius. Your Telegram app may automatically notify you if there is a geochat within your coordinates. In the Windows Phone App for Telegram, you can activate location services under Telegram settings. WhatsApp does not have this feature. (See Geochats API)
End-to-End encryption
End-to-End encryption means that the data that you send is encrypted on your device and only the receiver can decrypt it. To be absolutely secure, you need to verify that the person you are talking to actually is the one you think she is.
WhatsApp actually has End-To-End encryption on Android now (see here).
For telegram, End-To-End encryption works on every platform (except the Web App). However, to use it you need to create a 'secret chat'. You can verify that the person you are talking to actually is the one you think she is by comparing a visualization of the encryption key.
Unfortunately, there are some drawbacks. First, secret chats are not synchronized. Rather they are between the two devices from which the secret chat was created. Second, you cannot send yourself a secret chat message (without creating a new user). Third, group chats cannot be secret. There is however a workaround to get secret group chats with the help of telegram-cli (see here).
So having End-To-End encryption is nice, but it is not as well integrated in the Telegram Messenger as in Threema.

Protection against hacker attacks
How secure against hacker attacks are WhatsApp chats? Based on the following quote from somebody who analyzed the service to build his own WhatsApp client, I do not feel very comfortable. He states

During the two weeks of analysis of service mechanisms, we stumbled upon serious design and security flaws (they fixed some of them since 2011). For a company with such massive user base, we expected better practises and engineering. (See here)

For telegram, all traffic is safely encrypted, even if you do not use the secret chat. Additionally data that is stored on the servers is also encrypted. The people behind Telegram even offer a $300,000 reward for the first person to break this encryption. So you do not need to worry about hackers. BUT, if the people behind Telegram wanted to, they could read your messages, except secret chats, because they have access to the keys. Supposedly, some government could also force them to provide chat data about users.
Open API
For WhatsApp, there is an inofficial API , which is reverse engineered and written in PHP. My opinion is that if WhatsApp would want you to write your own client, then they would publish an official API.
For Telegram, there is an official API and you are explicitly invited to write your own clients.
For example a company may use the open source code of the existing client applications to build a modified version that uses the company address book as contact list. Another example would be somebody who would build a telegram client, where all chats are End-To-End encrypted.
Further, you can build a bot with the open API. It could perform some task based on the message you send it. For example, if the device has GPS, then you could make a bot for it that would return its GPS coordinates when you send it a specific message. Or you could make a bot that runs on your home-automation server, which you can send a message like 'wake me up at 5:00' and it will turn on the light and music at that time.
You can even use the API if you are not building a chat application, but if you want to use features like sending files with End-to-End encryption, traverse firewalls, or send push notification to all devices of the receiver. (See Using Telegram API and Source code of existing Telegram Applications)
Free
Using any of the telegram messenger clients or the API is as free as using Wikipedia. There are also no ads if you use a client from here and the messenger is not intended to be sold like WhatsApp to Facebook, but to stay free.
But how do they cover their costs? Currently only through donations. In the future, non-essential paid options might be added.

Sources: Telegram FAQ, Advanced user FAQ, Secret chats, end-to-end encryption, MTProto Mobile Protocol

In conclusion, Telegram Messenger is more powerful than WhatsApp in any aspect. The two features I like most are, the ability to access my account from any device and to be able to send any file up to 1.5 GB. The secret chat feature can give absolute security but it is not as well integrated in the messenger as in Threema.

Installing and Configuring telegram-cli on the Raspberry Pi

To install telegram-cli on the RPi, type:

sudo apt-get update
sudo apt-get install -y libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev
cd ~
git clone --recursive github.com/vysheng/tg.git
cd tg
./configure
make

telegram-cli should now be in the folder /home/pi/tg/bin.
Now run

sudo cp ~/tg/bin/telegram-cli /usr/bin
sudo mkdir -p /etc/telegram-cli
sudo mv ~/tg/tg-server.pub /etc/telegram-cli/server.pub

These two commands will allow you to start the tool without specifying the full path and without needing to specify the path of the public key.
When you start telegram-cli for the first time, then you will be authorized. During the authorization, the config directory ~/.telegram-cli is created. It contains a file for the authorization key, a file with configuration settings, a file for secret chats (probably the key or part of it) and a downloads folder.
To start the authorization for your linux user type telegram-cli -W.
alt You will be asked for a phone number. This does not need to be a mobile phone number, just some number that can receive SMS OR that you can be called on. Then an SMS is sent to that number. If your number cannot receive SMS then enter "call". In that case a computer voice will call you, say the code a few times and then hang up.
Now exit with quit.
Source: telegram-cli on github

Telegram-cli Examples

After you have run the commands in the previous section and quit the tool, you can display the command line options with telegram-cli -h. To start telegram-cli type telegram-cli -W.
The "-W" argument will load information about your contacts, similar to executing "dialog_list", or "contact_list" after startup. Without the "-W" argument or executing "dialog_list" or "contact_list", I was not able to send messages.
I assume that you have telegram already installed on your PC or mobile phone so that you can send messages to yourself and/or others.
Type help to see the available commands. Then type contact_ist to see the first name and last name of your contacts and dialog_list to see your chats and group chats. Note that tab completion works. So you can write co<tab>l<tab> to get the contact list.
Messages can be send with msg <peer> text text text.
But what is peer? Peer can be a user, a chat or a secret chat. For user, it is the first name and last name, as displayed by "dialog_list" and "contact_list", separated by an underscore like "David_New". For chats, it is the chat title with spaces replaced by underscore, like "Functional_programming_news". For secret chats, it is the same as for user but with a "!_" prefix like "!_David_New". Note that you can use tab completion on the peer name and that the peer name is case sensitive.
You can only send messages to the people in your contact list or to people with a username. Type contact_list and dialog_list to see your current contact list and chats. To add somebody to your contact list type add_contact <phone> <first name> <last name>. With the first name and last name arguments you can specify the name under which the phone number appears in your contact list. So you can add yourself to your contact list with add_contact +<your_country_code><your_phone_number> <first name> <last name>. After this command the first name and last name of the added user is displayed. If you have the username but not the phone number, then run contact_search @<username>. It will display the first name and last name, which you can use to send messages and to start a secret chat.
To send a text message to yourself, type msg <YourFirstname_YourLastname> text text text or msg <YourFirstname<tab>> text text text.
If you want all input to be directly send to a specific peer, you can use chat_with_peer <peer>. You will still see messages from other chats. Quit this mode with /quit.
To write encrypted, secret chat messages, you first need to create a secret chat with create_secret_chat <user>. For example create_secret_chat David_New. You can read information about secret chats in the "Telegram Messenger vs WhatsApp" comparison above. Then you can write messages as usual but with the peer prefixed with "!_" as msg !_David_New my secret message.
Creating a secret chat only has to be done once. If you log out of telegram-cli and start it again, then the secret chat history will be lost but the secret chat needs not be created again. You can check this by executing visualize_key !_<user>. If this command displays a picture (a visualization of the encryption key for the secret chat), then you do not need to create the chat again but can directly send secret messages.
To send a document End-to-End encrypted type send_document !_<peer> <path to document>.
alt
Send Push Notifications from Any Application

If you use the Raspberry Pi or another single-board computer as home-automation central then you might want to be notified in certain cases. For example if you are on holidays and your house door opens or if somebody opens a drawer that contains your personal documents.
With telegram-cli, you can send a push notification to your mobile phone, so that the phone will ring or vibrate when the message arrives.
You should be aware, that when you send a message to yourself, it will arrive but the phone will not ring or vibrate (tested on windows phone 8.1 and android). So you have to use a different phone number for telegram-cli than for your mobile phone. One way to change the telegram-cli phone number is to delete the application data with rm -rf ~/.telegram-cli and then authorize the new phone number by starting telegram again.
To send a push notification from the command line type telegram-cli -W -e "msg <peer> hello from the command line". To send a picture type telegram-cli -W -e "send_photo <peer> <path_to_picture>". And to send any kind of file type telegram-cli -W -e "send_document <peer> <path_to_file>". If you want to send files with End-to-End encryption then simply prefix peer with "!_". Note, that you must have created a secret chat to send End-to-End encrypted messages, as explained in the previous section.
While the command line is not complex, I will not remember it a few weeks from now when I need it. So I created two batch files in the home directory. One to send messages and one to send any file.
The contents of "telegram_send_message.sh" are

#!/bin/bash
telegram-cli -W -e "msg <replace_with_peer> $1"

The contents of "telegram_send_file.sh" are

#!/bin/bash
telegram-cli -W -e "send_document <replace_with_peer> $1"

You need to replace <replace_with_peer> with the peer you want to send messages to. Then make the files executable with chmod ug+x telegram_send_message.sh telegram_send_file.sh. And test them with ./telegram_send_message.sh "hello wold" and ./telegram_send_file.sh "<path_to_some_file>".
You can run these shell commands from any application. For example in python you can send a push notification with

import subprocess
subprocess.Popen(["/home/pi/telegram_send_message.sh", "hello world"])

If you call the batch files as a different user then the one you used when you authorized your phone number, then telegram-cli will not find its configuration files. So if you want to be able to use these commands also as root, then just run sudo telegram-cli -W and you will be able to provide your phone number for the root user.

Thoughts about Building a Telegram Bot

If you want to write a bot for telegram, that performs some actions when a message is received, then you have several options. First, you could start telegram-cli with the "-s" argument and specify a lua script file (see the example test.lua script in the tg folder). Second, you could start telegram-cli with the "-S /tmp/linuxsockfile" command and query information or send commands through a socket. Third, you could directly write a client for the telegram API.
The first option is relatively simple and has the advantage that you get notified when a message arrives and that the content and sender are already parsed. The second option is not very nice because you have to poll for content and then parse it yourself. The third one has the advantage that you are not dependent on telegram-cli, so you could write a cross-platform client. Somebody already uploaded his Java Telegram Bot to GitHub here. There is also a thread about the topic here.

telegram-cli -W -P 2391 -vvvv -d

github.com/vysheng/tg/issues/9
bemod@wohnpi:~$ /usr/bin/telegram-cli -W -k /etc/telegram-cli/server.pub -vvvRC -d
bemod@wohnpi:~$ echo "create_secret_chat be_handy" | nc -q 1 localhost 1234
bemod@wohnpi:~$ echo 'msg !_be_handy hurz' | nc -q 1 localhost 1234
bemod@wohnpi:~$ echo "safe_quit" | nc -q 1 localhost 1234

#!/bin/sh
#
# send telegram message to telegram-cli deamon
#

host=localhost
port=2391

user=''
msgtxt=''
while [ $# -ge 2 ]
do
case $1 in
--user )
user="$2"
shift; shift
;;
--msg )
msgtxt="$2"
shift; shift
;;
* )
shift
;;
esac
done

if [ "${user}" != '' -a "${msgtxt}" != '' ]
then
baseuser=''
cmdstr1=''
cmdstr1=''

# echo "USER:${user}"
# echo "MSG :${msgtxt}"

# check if secret chat should be used
eval testuser="'${user}'"
echo "${testuser}" | grep -q '^\!'

if [ $? -eq 0 ]
then
# secret chat has been requested
baseuser=`echo ${testuser} | sed 's/!_//'`

# add default chat index
user="${user}#1"

# create command string
cmdstr1="create_secret_chat ${baseuser}"
fi

# create command string
eval cmdstr2="'${msgtxt}'"

# echo 'msg !_TOM#1 Hello world'
# ANSWER 8
# SUCCESS
result=`echo msg ${user} ${cmdstr2} | nc -q 1 ${host} ${port}`

# check if message has successfully been sent
echo "${result}" | grep -q "SUCCESS"

if [ $? -ne 0 ]
then
# an error was reported while sending the message

if [ "${baseuser}" != '' ]
then
# a secret chat does not exist, create it
#
# echo "create_secret_chat TOM"
# ANSWER 45
# Encrypted chat !_TOM#1 is now in wait state
result=`echo ${cmdstr1} | nc -q 1 ${host} ${port}`

echo "${result}" | grep -q -E "Encrypted chat.*is now in wait state"

if [ $? -eq 0 ]
then
# new secret chat has been created, resend message
#
# echo 'msg !_TOM#1 Hello world'
# ANSWER 8
# SUCCESS
result=`echo msg ${user} ${cmdstr2} | nc -q 1 ${host} ${port}`

# check if message has successfully been sent
echo "${result}" | grep -q "SUCCESS"

if [ $? -ne 0 ]
then
# an error was reported while sending the message
echo "ERROR: The secret chat message to '${user}' could not be send!"
fi
else
# an error was reported while creating a secret chat
echo "ERROR: A secret chat to '${user}' could not be created!"
fi
else
# an error was reported while sending the message
echo "ERROR: The chat message to '${user}' could not be send!"
fi
fi
else
echo "Usage: $0 --user USER --msg MESSAGE-TEXT"
fi

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.