Skip to content

Instantly share code, notes, and snippets.

@gintsmurans
Last active June 25, 2016 19:30
Show Gist options
  • Save gintsmurans/27db83d9f058183f0a8b to your computer and use it in GitHub Desktop.
Save gintsmurans/27db83d9f058183f0a8b to your computer and use it in GitHub Desktop.
Telegram (tg) + python cli
#!/usr/bin/env python3
import argparse
import subprocess
import time
import select
PATH_TO_TELEGRAM = '/root/tg/telegram'
# Parse commandline arguments
parser = argparse.ArgumentParser(description='Telegram python cli')
parser.add_argument('--debug', action='store_true', help='Debug')
subparsers = parser.add_subparsers(help='Available commands', dest='cmd')
# Send msg
parser_send = subparsers.add_parser('msg', help='Send message')
parser_send.add_argument('recipient', type=str, default='', help='Message recipient')
parser_send.add_argument('text', type=str, default='', help='Text to send')
# Send photo
parser_send = subparsers.add_parser('send_photo', help='Send photo')
parser_send.add_argument('recipient', type=str, default='', help='Recipient')
parser_send.add_argument('file', type=str, default='', help='Path to file')
# Send video
parser_send = subparsers.add_parser('send_video', help='Send video')
parser_send.add_argument('recipient', type=str, default='', help='Recipient')
parser_send.add_argument('file', type=str, default='', help='Path to file')
# Parse args
args = parser.parse_args()
def debug_print(msg):
if args.debug == True:
print(msg)
def do_telegram(command):
p = subprocess.Popen([PATH_TO_TELEGRAM], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1, shell=True)
debug_print('Launching telegram')
time.sleep(5)
debug_print('Executing: "%s"' % command)
p.stdin.write(("%s\n" % command).encode('utf-8'))
p.stdin.flush()
debug_print('Done')
while p.stdout in select.select([p.stdout], [], [], 10)[0]:
line = p.stdout.readline()
if line:
debug_print(line.decode('utf-8').rstrip())
else:
break
debug_print('Terminating process')
p.stdin.write("quit\n".encode('utf-8'))
p.stdin.flush()
# Send message
if args.cmd == 'msg':
do_telegram( ("msg %s %s" % (args.recipient, args.text)) )
if args.cmd == 'send_photo':
do_telegram( ("send_photo %s %s" % (args.recipient, args.file)) )
if args.cmd == 'send_video':
do_telegram( ("send_video %s %s" % (args.recipient, args.file)) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment