Commit b50d1c44 authored by Samuel Bancal's avatar Samuel Bancal
Browse files

+WOL +PING +several attempts +Notification when up

parent 155233b9
import json
import logging
import subprocess
from telegram.ext import Updater, CommandHandler
SECRET_JSON = './secret.json'
WOL_BIN = '/usr/bin/wakeonlan'
PING_BIN = '/bin/ping'
CHECK_INTERVAL = 1 # seconds
MAX_PING_HOST = 30 # attemps to ping WOLed host
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def send_wol(mac_address):
cmd = [WOL_BIN, mac_address]
subprocess.call(cmd)
def check_user_allowed(bot, update):
......@@ -45,13 +61,25 @@ def list_command(bot, update):
update.message.reply_text(answer)
def wol_command(bot, update, args):
def wol_command(bot, update, args, job_queue):
if check_user_allowed(bot, update):
if len(args) == 1:
name = args[0]
chat_id = update.message.chat_id
username = update.message.from_user.username
name = args[0]
try:
host = secret['users'][username][name]
send_wol(host['mac'])
job = job_queue.run_once(
ping_host,
CHECK_INTERVAL,
context={
'chat_id': chat_id,
'checks_left': MAX_PING_HOST,
'hostname': host['hostname'],
'job_queue': job_queue,
}
)
update.message.reply_text(
'''\
WakeOnLan packet was sent to %s
......@@ -61,6 +89,32 @@ We'll let you know within 2 minutes when %s is up.''' % (host['mac'], host['host
else:
update.message.reply_text('this command requires one argument.')
def ping_host(bot, job):
logger.info('ping_host')
cmd = [PING_BIN, '-c1', '-w1', job.context['hostname']]
return_code = subprocess.call(cmd)
if return_code == 0:
bot.send_message(
job.context['chat_id'],
text='%s is up now!' % job.context['hostname'])
else:
if job.context['checks_left'] <= 0:
bot.send_message(
job.context['chat_id'],
text='%s could not be awake : (' % job.context['hostname'])
else:
job.context['job_queue'].run_once(
ping_host,
CHECK_INTERVAL,
context={
'chat_id': job.context['chat_id'],
'checks_left': job.context['checks_left'] - 1,
'hostname': job.context['hostname'],
'job_queue': job.context['job_queue'],
}
)
if __name__ == '__main__':
with open(SECRET_JSON, 'r') as f:
......@@ -70,7 +124,9 @@ if __name__ == '__main__':
updater.dispatcher.add_handler(CommandHandler('start', start_command))
updater.dispatcher.add_handler(CommandHandler('help', help_command))
updater.dispatcher.add_handler(CommandHandler('list', list_command))
updater.dispatcher.add_handler(CommandHandler('wol', wol_command, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('wol', wol_command,
pass_args=True,
pass_job_queue=True))
updater.start_polling()
updater.idle()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment