Sending messages with Telegram - APIs or CLI? Sending messages with Telegram - APIs or CLI? python python

Sending messages with Telegram - APIs or CLI?


Telegram recently released their new Bot API which makes sending/receiving messages trivial. I suggest you also take a look at that and see if it fits your needs, it beats wrapping the client library or integrating with their MTProto API.

import urllibimport urllib2# Generate a bot ID here: https://core.telegram.org/bots#botfatherbot_id = "{YOUR_BOT_ID}"# Request latest messagesresult = urllib2.urlopen("https://api.telegram.org/bot" + bot_id + "/getUpdates").read()print result# Send a message to a chat room (chat room ID retrieved from getUpdates)result = urllib2.urlopen("https://api.telegram.org/bot" + bot_id + "/sendMessage", urllib.urlencode({ "chat_id": 0, "text": 'my message' })).read()print result

Unfortunately I haven't seen any Python libraries you can interact directly with, but here is a NodeJS equivalent I worked on for reference.


Since version 1.05 you can use the -P option to accept messages from a socket, which is a third option to solve your problem. Sorry that it is not really the answer to your question, but I am not able to comment your question because I do not have enough reputation.


First create a bash script for telegram called tg.sh:

#!/bin/bashnow=$(date)to=$1subject=$2body=$3tgpath=/home/youruser/tgLOGFILE="/home/youruser/tg.log"cd ${tgpath}${tgpath}/telegram -k ${tgpath}/tg-server.pub -W <<EOFmsg $to $subjectsafe_quitEOFecho "$now Recipient=$to Message=$subject" >> ${LOGFILE}echo "Finished" >> ${LOGFILE}

Then put the script in the same folder than your python script, and give it +x permission with chmod +x tg.sh

And finally from python, you can do:

import subprocesssubprocess.call(["./tg.sh", "user#****", "message here"])