Advertisement
askanton

Бот який перевіряє чи є вдома світло

Jan 20th, 2023 (edited)
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.45 KB | None | 0 0
  1. import telebot
  2. import subprocess
  3. from database import ab_list_on, ab_list_of
  4. from telebot import types
  5. import time
  6. import threading
  7.  
  8.  
  9. token = "888888888:AAAAAAAAAAAAAAAAAAAAAAAA-AAAA"
  10. bot = telebot.TeleBot(token)
  11. button_foo = types.InlineKeyboardButton('Так', callback_data='foo')
  12. button_bar = types.InlineKeyboardButton('Ні', callback_data='bar')
  13.  
  14. keyboard = types.InlineKeyboardMarkup()
  15. keyboard.add(button_foo, button_bar)
  16. global adress_to_mon
  17.  
  18.  
  19. def my_timer_on():
  20.     while True:
  21.         try:
  22.             from database import ab_list_on, ab_list_of
  23.             #print("my_timer_on")
  24.             time.sleep(180)
  25.             for i in range(len(ab_list_on)):
  26.                 # print(i, list(ab_list_on.values())[i])
  27.                 status, result = subprocess.getstatusoutput("ping -c1 -w2 " + str(list(ab_list_on.values())[i]))
  28.                 #print(f'Status {status}')
  29.                 if status != 0:
  30.                     bot.send_message(list(ab_list_on)[i], f"🔴Адреса {list(ab_list_on.values())[i]} не доступна🔴")
  31.                     ab_list_of.update({list(ab_list_on)[i]: list(ab_list_on.values())[i]})
  32.                     ab_list_on.pop(list(ab_list_on)[i])
  33.                     output = open("database.py", 'w')
  34.                     print("ab_list_on =", ab_list_on, file=output)
  35.                     print("ab_list_of =", ab_list_of, file=output)
  36.                     output.close()
  37.         except Exception as e:
  38.             print(e)
  39.  
  40. def my_timer_off():
  41.     time.sleep(10)
  42.     while True:
  43.         try:
  44.             from database import ab_list_on, ab_list_of
  45.             #print("my_timer_of")
  46.             time.sleep(180)
  47.             for i in range(len(ab_list_of)):
  48.                 # print(i, list(ab_list_on.values())[i])
  49.                 status, result = subprocess.getstatusoutput("ping -c1 -w2 " + str(list(ab_list_of.values())[i]))
  50.                 #print(f'Status {status}')
  51.                 if status == 0:
  52.                     bot.send_message(list(ab_list_of)[i], f"🟢Адреса {list(ab_list_of.values())[i]} знову доступна🟢")
  53.                     ab_list_on.update({list(ab_list_of)[i]: list(ab_list_of.values())[i]})
  54.                     ab_list_of.pop(list(ab_list_of)[i])
  55.                     output = open("database.py", 'w')
  56.                     print("ab_list_on =", ab_list_on, file=output)
  57.                     print("ab_list_of =", ab_list_of, file=output)
  58.                     output.close()
  59.         except Exception as e:
  60.             print(e)
  61.  
  62. def botter():
  63.     @bot.message_handler(commands=['help'])
  64.     def send_help(message):
  65.         print("Help")
  66.         keyboard = telebot.types.ReplyKeyboardMarkup(True)
  67.         keyboard.row('/start', '/help', '/restart')
  68.         bot.send_message(message.chat.id, "Натисність /start і вбийте ip адресу вашого роутера. Якщо адреса буде доступна то бот "
  69.                                           "запропонує вам додати адресу до моніторинга. Після цього він буде перевіряти доступність адреси кожні 3 хвилини."
  70.                                           "у випадку якщо адреса недостпна, бот надішле вам повідомлення. \nНатисніть /help щоб побачити цю інструкію \n"
  71.                                           "Натисніть /restart щоб видалити свої данні з бота", reply_markup=keyboard)
  72.  
  73.     @bot.message_handler(commands=['restart'])
  74.     def send_restart(message):
  75.         print("Restart")
  76.         keyboard = telebot.types.ReplyKeyboardMarkup(True)
  77.         keyboard.row('/start', '/help', '/restart')
  78.         print(ab_list_on)
  79.         try:
  80.             ab_list_of.pop(message.chat.id)
  81.         except Exception as e:
  82.             print(e)
  83.         try:
  84.             ab_list_on.pop(message.chat.id)
  85.         except Exception as e:
  86.             print(e)
  87.         output = open("database.py", 'w')
  88.         print("ab_list_on =", ab_list_on, file=output)
  89.         print("ab_list_of =", ab_list_of, file=output)
  90.         output.close()
  91.         print(ab_list_on)
  92.         bot.send_message(message.chat.id, "Ваші данні видалені з бота", reply_markup=keyboard)
  93.  
  94.     @bot.message_handler(commands=['start'])
  95.     def send_welcome(message):
  96.         print("Start")
  97.         msg = bot.send_message(message.chat.id, "Введіть IP адресу вашого роутера. Наприклад: 222.33.55.111")
  98.         bot.register_next_step_handler(msg, process_firstname_step)
  99.  
  100.     def process_firstname_step(message):
  101.         global adress_to_mon
  102.         print(f"Got address {message.text}")
  103.         try:
  104.             bot.send_message(message.chat.id, "Дякую, перевіряємо доступність")
  105.             status, result = subprocess.getstatusoutput("ping -c1 -w2 " + str(message.text))
  106.             print(f'Status {status}')
  107.             if status != 0:
  108.                 bot.send_message(message.chat.id, "Адреса недоступна")
  109.             else:
  110.                 bot.send_message(message.chat.id, "Адреса доступна. Додати в моніторинг?", reply_markup=keyboard)
  111.                 adress_to_mon = message.text
  112.         except Exception as e:
  113.             print(e)
  114.  
  115.     @bot.callback_query_handler(func=lambda call: True)
  116.     def query_handler(call):
  117.         global adress_to_mon
  118.         bot.answer_callback_query(callback_query_id=call.id, text='Answer accepted!')
  119.         if call.data == 'foo':
  120.             ab_list_on.update({call.message.chat.id: adress_to_mon})
  121.             output = open("database.py", 'w')
  122.             print("ab_list_on =", ab_list_on, file=output)
  123.             print("ab_list_of =", ab_list_of, file=output)
  124.             output.close()
  125.             print(ab_list_on)
  126.             answer = 'Адресу додано!'
  127.         else:
  128.             answer = 'Можливо іншим разом.'
  129.  
  130.         keyboard = telebot.types.ReplyKeyboardMarkup(True)
  131.         keyboard.row('/start', '/help', '/restart')
  132.         bot.send_message(call.message.chat.id, answer, reply_markup=keyboard)
  133.  
  134.     if __name__ == '__main__':
  135.         bot.polling(none_stop=True)
  136.  
  137.  
  138. t1 = threading.Thread(target=botter)
  139. t2 = threading.Thread(target=my_timer_on)
  140. t3 = threading.Thread(target=my_timer_off)
  141.  
  142. t1.start()
  143. t2.start()
  144. t3.start()
  145.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement