Sending Telegram message from Python
Asked Answered
J

3

17

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

Jacky answered 12/3, 2015 at 6:36 Comment(0)
E
48

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

Equipotential answered 22/11, 2019 at 5:11 Comment(0)
A
3
  1. Talk to @BotFather. Send /newbot to them and follow the prompts. In response you will get an HTTP API token (it will look something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).

  2. Talk to your newly created bot, it is enough to just /start it.

  3. Immediately open https://api.telegram.org/bot<token>/getUpdates?offset=-1 in your web-browser (literally paste the token you received from the BotFather, complete with all the letters and punctuation). Copy the chat id from the returned JSON object.

  4. With the data above, sending a message is a matter of a simple POST request.

    For example, using the Requests library:

    import requests
    
    TOKEN = '...'
    CHAT_ID = '...'
    SEND_URL = f'https://api.telegram.org/bot{TOKEN}/sendMessage'
    
    requests.post(SEND_URL, json={'chat_id': CHAT_ID, 'text': your_message})  
    
Alrzc answered 30/3, 2022 at 16:13 Comment(2)
I try this and it worked. My doubt: can I only send messages to the created bot? Can I do it to another chat? If so, how can I get the chat_id of it?Leonard
@MarioMey you do not send messages to the bot, you send messages from the bot to users who activated it. You can get chat_ids from your program by using that same getUpdates endpoint.Alrzc
S
2

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!

Seed answered 23/5, 2017 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.