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:
<<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?
The first step is to create a bot and get the token
.
The second step is go get the chat_id
:
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With