Skip to content

Instantly share code, notes, and snippets.

@k4ml
Last active November 9, 2016 00:31
Show Gist options
  • Save k4ml/b94fe0e09b4233d837e397dfe2eac269 to your computer and use it in GitHub Desktop.
Save k4ml/b94fe0e09b4233d837e397dfe2eac269 to your computer and use it in GitHub Desktop.
Script to quickly send message using telegram bot

Bot request

This is how telegram send the request:-

POST / HTTP/1.1
Host: xxx.ngrok.io
Content-Type: application/json
Content-Length: 247
Accept-Encoding: gzip, deflate
X-Forwarded-Proto: https
X-Forwarded-For: 149.0.16.14

{"update_id":695672305,
"message":{"message_id":29,"from":{"id":3339704,"first_name":"Kamal","username":"kamal"},"chat":{"id":3339704,"first_name":"Kamal","username":"kamal","type":"private"},"date":1478650973,"text":"test ngrok"}}
import sys
from telegram.ext import Updater, CommandHandler
import argparse
"""
Requirements:-
Install python-telegram-bot package:-
python3 -mvenv . # create virtualenv in current directory
./bin/pip install python-telegram-bot
Usage:-
./bin/python tgsend.py <TOKEN> --send="test direct cli group" --chat_id=-<chat_id>
./bin/python tgsend.py <TOKEN> # listen for message
"""
parser = argparse.ArgumentParser(description='Run TG Bot')
parser.add_argument('token', type=str)
parser.add_argument('--send', dest='message')
parser.add_argument('--chat_id', dest='chat_id')
parser.add_argument('--webhook', dest='webhook')
args = parser.parse_args()
updater = Updater(args.token)
if args.message is not None:
updater.bot.sendMessage(args.chat_id, text=args.message)
updater.stop()
sys.exit()
if args.webhook is not None:
if args.webhook == 'info':
print(updater.bot.get_webhook_info())
else:
updater.bot.setWebhook(args.webhook)
updater.stop()
sys.exit()
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hello World! The chat_id for this is %d' % update.message.chat_id)
def hello(bot, update):
print(update)
bot.sendMessage(update.message.chat_id,
text='Hello {}'.format(update.message.from_user.first_name))
def chat_id(bot, update):
bot.sendMessage(update.message.chat_id, text='The chat_id for this is %d' % update.message.chat_id)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('hello', hello))
updater.dispatcher.add_handler(CommandHandler('chat_id', chat_id))
updater.start_polling()
updater.idle()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment