Advertisement
load-net

Bot opros servera linux

Jan 24th, 2025 (edited)
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.56 KB | None | 0 0
  1. https://www.youtube.com/watch?v=Bj_6xBqvCrw
  2.  
  3.  
  4.  
  5. #Если нужно обновим систему
  6. apt-get update && apt-get upgrade -y
  7.  
  8. # Уствновим mc мне так удобней
  9. apt install mc -y
  10.  
  11. # Установим client URL
  12. apt install curl -y
  13.  
  14. #Создаем папку
  15. mkdir /usr/src/bottgservce
  16. cd /usr/src/
  17.  
  18.  
  19.  
  20.  
  21.  
  22. #Установим пакеты
  23. apt install python3-venv python3-pip python3-full -y
  24.  
  25. #Токен берем у @BotFather
  26. Проверка и консоли сервера
  27. curl https://api.telegram.org/bot1185235528:AAEEx5rfV8U68-PGBNZC-NOeYrN7e-Hs6pM/getUpdates
  28.  
  29. Зайти в бота
  30. @userinfobot
  31. Вам нужен Id: 14564564565528
  32.  
  33. Это в браузере тест вам придет сообщение ddddddddd
  34. https://api.telegram.org/bot1185235528:AAEEx5rfV8U68-PGBNZC-NOeYrN7e-Hs6pM/sendMessage?chat_id=14564564565528&text=ddddddddd
  35.  
  36.  
  37. #Создаем файл bot.py и вствляем код
  38. ########## mcedit /usr/src/bottgservce/bot.py ###########################
  39.  
  40. import config
  41. import subprocess
  42. import shlex
  43. from telegram import Update, ReplyKeyboardMarkup
  44. from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
  45.  
  46. # Функция для загрузки администраторов из файла
  47. def load_admins(filename):
  48. try:
  49. with open(filename, 'r') as f:
  50. return {int(line.strip()) for line in f if line.strip().isdigit()}
  51. except FileNotFoundError:
  52. return set()
  53.  
  54. # Загружаем список администраторов
  55. ADMIN_IDS = load_admins('admins.conf')
  56.  
  57. # Создаем экземпляр Application с токеном
  58. app = ApplicationBuilder().token(config.token).build()
  59.  
  60. # Функция для выполнения команд
  61. def run_command(command):
  62. process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  63. textoutput = ''
  64. while True:
  65. output = process.stdout.readline()
  66. output = output.decode('utf-8')
  67.  
  68. if output == '' and process.poll() is not None:
  69. break
  70. if output:
  71. textoutput += output.strip() + '\n'
  72. rc = process.poll() # Получаем код возврата процесса
  73. return rc, textoutput
  74.  
  75. # Обработчик команды /start
  76. async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
  77. await context.bot.send_message(
  78. chat_id=update.effective_chat.id,
  79. text="Привет, я бот, жду команды! Нажмите /help, чтобы получить список доступных команд."
  80. )
  81.  
  82. # Обработчик команды /help
  83. async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
  84. commands = [
  85. ["/start - Приветственное сообщение"],
  86. ["/run <command> - Выполнить системную команду"],
  87. ["/checkdisk - Проверить место на диске"],
  88. #####################################################################################################################################
  89. ["/ip - Проверить сеть"]
  90. ############################ При след команды добавить запятую ["/ip - Проверить сеть"] , #########################################################################################################
  91. ]
  92. reply_markup = ReplyKeyboardMarkup(commands, one_time_keyboard=True, resize_keyboard=True)
  93. await context.bot.send_message(
  94. chat_id=update.effective_chat.id,
  95. text="Доступные команды:",
  96. reply_markup=reply_markup
  97. )
  98.  
  99. # Обработчик команды /run
  100. async def run(update: Update, context: ContextTypes.DEFAULT_TYPE):
  101. if update.effective_user.id not in ADMIN_IDS:
  102. await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
  103. return
  104.  
  105. command = " ".join(context.args) # Собираем команду из аргументов
  106. if command:
  107. rc, output = run_command(command)
  108. await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
  109. else:
  110. await context.bot.send_message(chat_id=update.effective_chat.id, text="Пожалуйста, укажите команду для выполнения.")
  111.  
  112. # Обработчик команды /checkdisk
  113. async def check_disk(update: Update, context: ContextTypes.DEFAULT_TYPE):
  114. if update.effective_user.id not in ADMIN_IDS:
  115. await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
  116. return
  117.  
  118. command = "df -h" # Команда для проверки дискового пространства
  119. rc, output = run_command(command)
  120. await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
  121.  
  122.  
  123. #################################################################################################################################
  124. # Обработчик команды /ip
  125. async def check_ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
  126. if update.effective_user.id not in ADMIN_IDS:
  127. await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
  128. return
  129.  
  130. command = "ip a" # Команда для проверки ip
  131. rc, output = run_command(command)
  132. await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
  133. ##################################################################################################################################
  134.  
  135.  
  136.  
  137. # Регистрация обработчиков команд
  138. app.add_handler(CommandHandler("start", start))
  139. app.add_handler(CommandHandler("help", help_command))
  140. app.add_handler(CommandHandler("run", run))
  141. app.add_handler(CommandHandler("checkdisk", check_disk))
  142.  
  143. #####################################################################################################################################
  144. app.add_handler(CommandHandler("ip", check_ip))
  145. ######################################################################################################################################
  146.  
  147. # Запуск бота
  148. if __name__ == "__main__":
  149. app.run_polling()
  150.  
  151. ######################################################################################### Окончание кода
  152.  
  153.  
  154.  
  155.  
  156.  
  157.  
  158.  
  159.  
  160.  
  161.  
  162. ####################################################################################
  163.  
  164. #Создаем файл config.py и вствляем код
  165. ##################### mcedit /usr/src/bottgservce/config.py ######################################################
  166. token = '14564564565528:ABEEx5rfV8R68-PGBNZC-NOeYrN7e-Hs6pM'
  167. #####################################################################################
  168.  
  169. Права админа
  170. ################################# mcedit /usr/src/bottgservce/admins.conf ############################################
  171. 14564564565528
  172. #####################################################################################
  173.  
  174.  
  175. #Начальные настройки для бота
  176. chmod +x /usr/src/bottgservce/bot.py
  177.  
  178.  
  179. #Создаем Виртуальное окружения для выполнения кода
  180. python3 -m venv bottgservce
  181.  
  182. source /usr/src/bottgservce/bin/activate
  183. pip3 install python-telegram-bot telegram
  184.  
  185.  
  186. #source /usr/src/bottgservce/bin/activate && python3 /usr/src/bottgservce/bot.py
  187.  
  188.  
  189. ############### Создаем сервис ######################
  190. mcedit /etc/systemd/system/telegram-bot.service
  191.  
  192. [Unit]
  193. Description=Service for Telegram bot
  194. After=network.target
  195.  
  196. [Service]
  197. Type=simple
  198. ExecStart=/bin/bash -c 'source /usr/src/bottgservce/bin/activate && exec python3 /usr/src/bottgservce/bot.py'
  199. WorkingDirectory=/usr/src/bottgservce
  200. Restart=on-failure
  201.  
  202. [Install]
  203. WantedBy=multi-user.target
  204. ###########################################################
  205.  
  206.  
  207.  
  208. # Права на сервис
  209. chmod 664 /etc/systemd/system/telegram-bot.service
  210.  
  211.  
  212. systemctl daemon-reload
  213. systemctl enable telegram-bot.service
  214. systemctl start telegram-bot.service
  215. systemctl status telegram-bot.service
  216.  
  217.  
  218. ###########################################################
  219.  
  220.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement