Thursday, December 15, 2016

Send IP address and webcam image with Telegram using Python, Streamer and twx.botapi.

Send a Telegram message with current IP address of your PC using a Python script. Get ip address:
import socket

def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 0))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP
http://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python

Or using subprocess.
import subprocess
ip = check_output(['hostname', '--all-ip-addresses'])

And send that information to Telegram using twx.botapi.
from twx.botapi import TelegramBot

bot = TelegramBot('123456789:abcdefghijklmnopqrstuvwxyz')
bot.update_bot_info().wait()
print(bot.username)
user_id = int(1234567)
result = bot.send_message(user_id, 'PC started at IP:%s'%get_ip()).wait()
print(result)
https://github.com/datamachine/twx.botapi

And let's send a web-cam image using Streamer too.
import os
from twx.botapi import InputFile, InputFileInfo 

os.system("streamer -c /dev/video0 -b 16 -o /home/outfile.jpeg")
fp = open('/home/outfile.jpeg', 'rb')
file_info = InputFileInfo('foo.png', fp, 'image/png')
photo = InputFile('photo', file_info)
bot.send_photo(user_id, photo)
http://pythonhosted.org/twx.botapi/