hello.pbaumgarten.com

Sending messages to your phone from your project

project-ideas
python

#1

One thing that has come up a couple of times recently is student projects that require sending alerts or notifications to their phone from the project they’ve built. Immediately the mind turns to, “why not send an SMS or Email?”. Without getting into the detail, to do SMS or Email results in needing to choose to sacrifice one of the three things you want: (1) ease of setup, (2) reliable & prompt delivery, (3) zero or almost zero financial cost. … you can have two of those things but not all three.

The next place my mind turns to is, “I wonder how viable it would be to send a message via Instagram or Whatsapp” since most students already have those on their phones. Unfortunately, this also fails the “ease of setup” test.

Last time I looked at this, I successfully helped a student integrate the Slack messaging tool. Their documentation was a bit unintuitive but one evening of playing with it was all it took. If you ever want the sample code for that, send me a message.

I’ve been looking at the topic again this evening for another student, and I think I’ve decided that next time I’ll try Telegram rather than Slack (with Twitter being my next fallback option if required).

Telegram looks really good, and probably about as simple to program as it get could get. You can use it to send attachments such as images, and have the phone user send reply messages back to your project. Some of the example projects are really interesting, everything from setting a Raspberry Pi powered alarm clock, through to running sudo commands on your server (Paolo that one’s for you). Should be some good fun to play with.

For the record, in case anyone particularly wants Twitter, take a look at the Tweepy library and this additional tut here). Finally another product that made it onto my shortlist but costs (an admittedly trivial) $5 after 7 days trial was pushover.net.


#2

Well, by sending notifications, I think what’s generally most useful is a push notification because the use of social media for notifications sounds like using a hammer for screws. Isn’t there any other options? I’ve found email is generally fine because it’s free/cheap, very cross-platform, though the setup process is probably best done by those who have prior experience with building servers.


#3

Well that was fun! The functionality is remarkably straight forward to implement. I’ll do up a proper how-to guide and add it to my Python website in coming days to include examples using sending/receiving photos etc.

Signing up for the Bot API key is incredibly easy. You just ask the BotFather! Check the instructions here.

These code snippets are really useful for working out the basics.

Before going into the proof of concept, a couple of important notes:

  • Bots can’t initiate conversations with users. A user must either add them to a group or send them a message first (ie: the first message has to be from human to bot).
  • Your bot is publicly listed via telegram.me/<bot_username> and can be searched for or username search to find your bot
  • Because bots can be publicly added by anyone, don’t assume just you are the only one ever talking to your bot - Include security checks (check the user_id) before acting on the messages received.
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
from datetime import datetime
import logging
import telegram

api_key = "---INSERT YOUR API KEY HERE---"
owner_id = 00000000 # Your Telegram ID number here

# Initiate logging
logging.basicConfig(filename="python.log", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

def hello(bot, update):
    print("hello received ",update.message.chat_id)
    date_str = datetime.now().strftime("%d/%m/%Y %H:%M")
    uid = update.message.from_user
    update.message.reply_text("Hello {}! Test was received at {}".format(uid.username, date_str))

def echo(bot, update):
    print("echo received ",update.message.chat_id)
    date_str = datetime.now().strftime("%d/%m/%Y %H:%M")
    uid = update.message.from_user # .id .first_name .last_name .username
    msg = update.message.text
    update.message.reply_text("Hello {}! You said: {}".format(uid.first_name, msg))

def error(bot, update, context):
    logger.warning('Update "%s" caused error "%s"', update, context.error)

if __name__ == "__main__":
    print("Welcome")
    # Create the bot object
    bot = Updater(token=api_key)
    me = bot.bot.get_me()
    print("Welcome to my Telegram bot")
    print(f"username:     {me['username']}")
    print(f"display name: {me['first_name']}")
    # Setup response paths
    bot.dispatcher.add_handler(CommandHandler("hello", hello))
    bot.dispatcher.add_handler(MessageHandler(Filters.text, echo))
    bot.dispatcher.add_error_handler(error)
    bot.start_polling() # Start the bot (non-blocking)
    bot.bot.send_message(chat_id=owner_id, text="I'm up and running...") # let my owner know I've been turned on
    bot.idle() # Run the bot until you press Ctrl-C

#4

When considering security, the number 1 thing is to obviously not rely on Telegram for possibly sensitive data and anything account-wise. If you’re doing a small project which perhaps has a username/password, only allow some quite harmless commands through telegram. If you’re planning on using Telegram also for anything like restarting the computer your application is running on or perhaps changing settings, the extra hassle and security risks of running those through Telegram means those things are probably not worth it.

By the way, if you’re thinking of getting other people using your program too, consider verifying their user id by having them tell your application AND send some sort of “yes, I’m user foo” to your bot. That should make it easier also to make sure people haven’t mispelled the user id. It’s basically what those email activation things do.


#5

What I was thinking for the use-case of Raspberry Pi projects etc, was to have a manually maintained text file containing a whitelist of Telegram user accounts that are authorised to execute the bot commands. Nice and simple for low risk projects (provided people don’t share their Telegram account details around)


#6

Yes for projects involving mostly notifying people who like social media stuff, telegram should be fine. Also, despite the jukebox and vending machine being paid, if the application has an admins whitelist, it should still be low risk enough to use telegram. I agree completely for many of the current projects. I don’t agree so much if it were setting up a script forwarding social media messages to production servers :slight_smile:.


#7

It would be nice if Telegram enabled end-to-end encryption on their bot protocols. This stackoverflow comment sums it up pretty well:

Telegram’s Bot API does not support secret chats at the moment. You can read the documentation, but a short explanation is: end-to-end encryption is used in secret chats which is tricky to implement for bots and requires additional work.
There’s no word on when it’ll be supported, if ever. At any rate, Telegram Bots are generally meant as a useful aid or for fun, not for sensitive things like financial transactions.


#8

By the way, lest anyone interpret the previous to suggest that Telegram is insecure, that is not the case. It is actually 1000s of times better than using decades old technology such as email and SMS which are transmitted in the clear and easily spoofed. All network traffic over Telegram is encrypted using industry standard protocols (HTTPS/TLS in the case of bots). The lack of end-to-end encryption simply means that the data is unencrypted when stored on Telegram’s servers meaning they can read/modify it, or grant access to government agencies, law enforcement etc. Used properly there is no reason it can’t be used for professional projects, and in fact there are many that do. Moral of the story: Enjoy learning and making making cool projects, including with tools such as Telegram.