Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Telegram message from Python

I want to send a message from a Python script via Telegram. I have tried to do that via telegram-cli, both the original version from vysheng and the patched version from luckydonald. With both of them I could successfully send messages to my phone. My problem is that:

  • pytg2 didn't install cleanly (import DictObject fails, apparently author has this on pypi separately, but I stopped at that point), required Python 3 (unlike the rest of my project, but semi-acceptable) and can do a lot more than I need.
  • I cannot get input into the tg console environment that is then executed there. Inputting via <<EOF ... EOF as in this SO question failed; the program opens on console, but doesn't output anything.
  • Opening a port via -P option worked. I could then operate from nc environment (similar to tg wiki), but I'm not sure if it is wise to implement all these calls in my Python script.

  • I also found another script that echoes commands into tg (forgot source), but it didn't work either (similar behavior to <<EOF above)

    #!/bin/bash
    to=Matthias_SG
    msg="test message"
    tgpath=/home/matthias/dvl/tg
    cd ${tgpath}
    (echo "add_contact +xxx Matthias SG"; echo "msg $to $msg") | ${tgpath}/bin/telegram-cli -k tg-server.pub
    

So my question is: Should I go back to the older pytg? Can I fix the shell scripts or amend them to Python by inputting a stringIO from subprocess.call or popen? Is anyone out there using this in a robust fashion?

Background

  • http://www.instructables.com/id/Raspberry-remote-control-with-Telegram/ showing how to reply to a 'ping' message with a 'pong' message using a Lua script. Worked for me.
  • http://technofaq.org/posts/2014/06/chat-with-telegram-buddies-the-geeky-way-with-telegram-cli/
like image 207
Matthias Kauer Avatar asked Mar 12 '15 06:03

Matthias Kauer


2 Answers

The first step is to create a bot and get the token.

The second step is go get the chat_id:

  • Write something in the chat
  • Visit https://api.telegram.org/bot<YourBOTToken>/getUpdates and get the chat_id under the key message['chat']['id'].

The last step is to use this code:

import requests

def telegram_bot_sendtext(bot_message):

   bot_token = ''
   bot_chatID = ''
   send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

   response = requests.get(send_text)

   return response.json()


test = telegram_bot_sendtext("Testing Telegram bot")
print(test)

Code extracted from Medium.com: How to create a Telegram bot, and send messages with Python

like image 98
juanmah Avatar answered Oct 16 '22 10:10

juanmah


I'd rather use the package python-telegram-bot, it works well for me.

You can find here documentation and an easy example to get started.

In order to reply to text messages, you can add a MessageHandler after the CommandHandler such as:

updater.dispatcher.add_handler(MessageHandler(Filters.text, text_reply))

def text_reply(bot, updater):
    text = update.message.text

    if text == 'ping':
        reply = 'pong'

    elif text == 'pong':
        reply = 'ping'

    # add any process to the text

    else:
        reply = "I only respond to ping pong"

    update.message.reply_text(reply)

Don't forget to import from telegram.ext import MessageHandler.

Hope this helped!

like image 43
ebeneditos Avatar answered Oct 16 '22 09:10

ebeneditos