Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://www.youtube.com/watch?v=Bj_6xBqvCrw
- #Если нужно обновим систему
- apt-get update && apt-get upgrade -y
- # Уствновим mc мне так удобней
- apt install mc -y
- # Установим client URL
- apt install curl -y
- #Создаем папку
- mkdir /usr/src/bottgservce
- cd /usr/src/
- #Установим пакеты
- apt install python3-venv python3-pip python3-full -y
- #Токен берем у @BotFather
- Проверка и консоли сервера
- curl https://api.telegram.org/bot1185235528:AAEEx5rfV8U68-PGBNZC-NOeYrN7e-Hs6pM/getUpdates
- Зайти в бота
- @userinfobot
- Вам нужен Id: 14564564565528
- Это в браузере тест вам придет сообщение ddddddddd
- https://api.telegram.org/bot1185235528:AAEEx5rfV8U68-PGBNZC-NOeYrN7e-Hs6pM/sendMessage?chat_id=14564564565528&text=ddddddddd
- #Создаем файл bot.py и вствляем код
- ########## mcedit /usr/src/bottgservce/bot.py ###########################
- import config
- import subprocess
- import shlex
- from telegram import Update, ReplyKeyboardMarkup
- from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
- # Функция для загрузки администраторов из файла
- def load_admins(filename):
- try:
- with open(filename, 'r') as f:
- return {int(line.strip()) for line in f if line.strip().isdigit()}
- except FileNotFoundError:
- return set()
- # Загружаем список администраторов
- ADMIN_IDS = load_admins('admins.conf')
- # Создаем экземпляр Application с токеном
- app = ApplicationBuilder().token(config.token).build()
- # Функция для выполнения команд
- def run_command(command):
- process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- textoutput = ''
- while True:
- output = process.stdout.readline()
- output = output.decode('utf-8')
- if output == '' and process.poll() is not None:
- break
- if output:
- textoutput += output.strip() + '\n'
- rc = process.poll() # Получаем код возврата процесса
- return rc, textoutput
- # Обработчик команды /start
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
- await context.bot.send_message(
- chat_id=update.effective_chat.id,
- text="Привет, я бот, жду команды! Нажмите /help, чтобы получить список доступных команд."
- )
- # Обработчик команды /help
- async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
- commands = [
- ["/start - Приветственное сообщение"],
- ["/run <command> - Выполнить системную команду"],
- ["/checkdisk - Проверить место на диске"],
- #####################################################################################################################################
- ["/ip - Проверить сеть"]
- ############################ При след команды добавить запятую ["/ip - Проверить сеть"] , #########################################################################################################
- ]
- reply_markup = ReplyKeyboardMarkup(commands, one_time_keyboard=True, resize_keyboard=True)
- await context.bot.send_message(
- chat_id=update.effective_chat.id,
- text="Доступные команды:",
- reply_markup=reply_markup
- )
- # Обработчик команды /run
- async def run(update: Update, context: ContextTypes.DEFAULT_TYPE):
- if update.effective_user.id not in ADMIN_IDS:
- await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
- return
- command = " ".join(context.args) # Собираем команду из аргументов
- if command:
- rc, output = run_command(command)
- await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
- else:
- await context.bot.send_message(chat_id=update.effective_chat.id, text="Пожалуйста, укажите команду для выполнения.")
- # Обработчик команды /checkdisk
- async def check_disk(update: Update, context: ContextTypes.DEFAULT_TYPE):
- if update.effective_user.id not in ADMIN_IDS:
- await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
- return
- command = "df -h" # Команда для проверки дискового пространства
- rc, output = run_command(command)
- await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
- #################################################################################################################################
- # Обработчик команды /ip
- async def check_ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
- if update.effective_user.id not in ADMIN_IDS:
- await context.bot.send_message(chat_id=update.effective_chat.id, text="У вас нет прав для выполнения этой команды.")
- return
- command = "ip a" # Команда для проверки ip
- rc, output = run_command(command)
- await context.bot.send_message(chat_id=update.effective_chat.id, text=f"Код возврата: {rc}\nВывод:\n{output}")
- ##################################################################################################################################
- # Регистрация обработчиков команд
- app.add_handler(CommandHandler("start", start))
- app.add_handler(CommandHandler("help", help_command))
- app.add_handler(CommandHandler("run", run))
- app.add_handler(CommandHandler("checkdisk", check_disk))
- #####################################################################################################################################
- app.add_handler(CommandHandler("ip", check_ip))
- ######################################################################################################################################
- # Запуск бота
- if __name__ == "__main__":
- app.run_polling()
- ######################################################################################### Окончание кода
- ####################################################################################
- #Создаем файл config.py и вствляем код
- ##################### mcedit /usr/src/bottgservce/config.py ######################################################
- token = '14564564565528:ABEEx5rfV8R68-PGBNZC-NOeYrN7e-Hs6pM'
- #####################################################################################
- Права админа
- ################################# mcedit /usr/src/bottgservce/admins.conf ############################################
- 14564564565528
- #####################################################################################
- #Начальные настройки для бота
- chmod +x /usr/src/bottgservce/bot.py
- #Создаем Виртуальное окружения для выполнения кода
- python3 -m venv bottgservce
- source /usr/src/bottgservce/bin/activate
- pip3 install python-telegram-bot telegram
- #source /usr/src/bottgservce/bin/activate && python3 /usr/src/bottgservce/bot.py
- ############### Создаем сервис ######################
- mcedit /etc/systemd/system/telegram-bot.service
- [Unit]
- Description=Service for Telegram bot
- After=network.target
- [Service]
- Type=simple
- ExecStart=/bin/bash -c 'source /usr/src/bottgservce/bin/activate && exec python3 /usr/src/bottgservce/bot.py'
- WorkingDirectory=/usr/src/bottgservce
- Restart=on-failure
- [Install]
- WantedBy=multi-user.target
- ###########################################################
- # Права на сервис
- chmod 664 /etc/systemd/system/telegram-bot.service
- systemctl daemon-reload
- systemctl enable telegram-bot.service
- systemctl start telegram-bot.service
- systemctl status telegram-bot.service
- ###########################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement