From 70a21f5dec2744e8c6d9051630f6e8d4a50872d4 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:26:38 +0300 Subject: [PATCH 01/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D1=8B=D0=B9=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D1=80=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9=20=D1=8F=D0=B7=D1=8B?= =?UTF-8?q?=D0=BA.=20=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B2=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=D1=85=20=D0=B8=20=D0=BA=D0=BE=D0=B4=D0=B5.=20=D0=94=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=B8=D1=82=D0=B5=D0=BB=D1=8B=D0=B9=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- servstatsbot.py | 50 ++++++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/servstatsbot.py b/servstatsbot.py index 95c1ffc..95e3d65 100644 --- a/servstatsbot.py +++ b/servstatsbot.py @@ -1,3 +1,5 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- from tokens import * import matplotlib matplotlib.use("Agg") # has to be before any other matplotlibs imports to set a "headless" backend @@ -12,7 +14,7 @@ # import threading # import random import telepot -# from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardHide, ForceReply +from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton # from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton # from telepot.namedtuple import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent @@ -29,7 +31,8 @@ setpolling = [] graphstart = datetime.now() -stopmarkup = {'keyboard': [['Stop']]} +stopmarkup = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Stop")]],resize_keyboard=True) +# stopmarkup = {'keyboard': [['Stop']]} hide_keyboard = {'hide_keyboard': True} def clearall(chat_id): @@ -44,9 +47,9 @@ def plotmemgraph(memlist, xaxis, tmperiod): # print(memlist) # print(xaxis) plt.xlabel(tmperiod) - plt.ylabel('% Used') - plt.title('Memory Usage Graph') - plt.text(0.1*len(xaxis), memorythreshold+2, 'Threshold: '+str(memorythreshold)+ ' %') + plt.ylabel('% использовано') + plt.title('График использования ОЗУ') + plt.text(0.1*len(xaxis), memorythreshold+2, 'Порог: '+str(memorythreshold)+ ' %') memthresholdarr = [] for xas in xaxis: memthresholdarr.append(memorythreshold) @@ -74,13 +77,18 @@ def on_chat_message(self, msg): bot.sendChatAction(chat_id, 'typing') memory = psutil.virtual_memory() disk = psutil.disk_usage('/') + cpuget = psutil.getloadavg() + cpufr = psutil.cpu_freq(percpu=False) boottime = datetime.fromtimestamp(psutil.boot_time()) now = datetime.now() - timedif = "Online for: %.1f Hours" % (((now - boottime).total_seconds()) / 3600) - memtotal = "Total memory: %.2f GB " % (memory.total / 1000000000) - memavail = "Available memory: %.2f GB" % (memory.available / 1000000000) - memuseperc = "Used memory: " + str(memory.percent) + " %" - diskused = "Disk used: " + str(disk.percent) + " %" + cpuget = "Среднаяя нагрузка CPU: " + str(cpuget) + cpufr = "Текущая частота CPU: " + str(cpufr.current) + "Mhz" + timedif = "Сервер работает уже: %.1f часов" % (((now - boottime).total_seconds()) / 3600) + memtotal = "Всего ОЗУ: %.2f GB " % (memory.total / 1000000000) + memavail = "Свободно ОЗУ: %.2f GB" % (memory.available / 1000000000) + memuseperc = "Используется ОЗУ: " + str(memory.percent) + " %" + diskused = "Использовано HDD: " + str(disk.percent) + " %" + pids = psutil.pids() pidsreply = '' procs = {} @@ -99,19 +107,21 @@ def on_chat_message(self, msg): for proc in sortedprocs: pidsreply += proc[0] + " " + ("%.2f" % proc[1]) + " %\n" reply = timedif + "\n" + \ + cpuget + "\n" + \ + cpufr + "\n" + \ memtotal + "\n" + \ memavail + "\n" + \ memuseperc + "\n" + \ diskused + "\n\n" + \ pidsreply - bot.sendMessage(chat_id, reply, disable_web_page_preview=True) + bot.sendMessage(chat_id, reply, disable_web_page_preview=True, parse_mode='HTML') elif msg['text'] == "Stop": clearall(chat_id) - bot.sendMessage(chat_id, "All operations stopped.", reply_markup=hide_keyboard) + bot.sendMessage(chat_id, "Все операции остановлены", reply_markup=hide_keyboard) elif msg['text'] == '/setpoll' and chat_id not in setpolling: bot.sendChatAction(chat_id, 'typing') setpolling.append(chat_id) - bot.sendMessage(chat_id, "Send me a new polling interval in seconds? (higher than 10)", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Отправить мне новый интервал опроса в секундах? (выше 10)", reply_markup=stopmarkup) elif chat_id in setpolling: bot.sendChatAction(chat_id, 'typing') try: @@ -125,7 +135,7 @@ def on_chat_message(self, msg): except: bot.sendMessage(chat_id, "Please send a proper numeric value higher than 10.") elif msg['text'] == "/shell" and chat_id not in shellexecution: - bot.sendMessage(chat_id, "Send me a shell command to execute", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Отправь мне Shell-комманду", reply_markup=stopmarkup) shellexecution.append(chat_id) elif msg['text'] == "/setmem" and chat_id not in settingmemth: bot.sendChatAction(chat_id, 'typing') @@ -153,12 +163,10 @@ def on_chat_message(self, msg): else: bot.sendMessage(chat_id, "No output.", disable_web_page_preview=True) elif msg['text'] == '/memgraph': - bot.sendChatAction(chat_id, 'typing') - tmperiod = "Last %.2f hours" % ((datetime.now() - graphstart).total_seconds() / 3600) + bot.sendChatAction(chat_id, 'upload_photo') + tmperiod = "За %.2f часа" % ((datetime.now() - graphstart).total_seconds() / 3600) bot.sendPhoto(chat_id, plotmemgraph(memlist, xaxis, tmperiod)) - - TOKEN = telegrambot bot = YourBot(TOKEN) @@ -184,11 +192,11 @@ def on_chat_message(self, msg): memlist.append(mempercent) memfree = memck.available / 1000000 if mempercent > memorythreshold: - memavail = "Available memory: %.2f GB" % (memck.available / 1000000000) + memavail = "Доступно ОЗУ: %.2f GB" % (memck.available / 1000000000) graphend = datetime.now() - tmperiod = "Last %.2f hours" % ((graphend - graphstart).total_seconds() / 3600) + tmperiod = "За последние %.2f часов" % ((graphend - graphstart).total_seconds() / 3600) for adminid in adminchatid: - bot.sendMessage(adminid, "CRITICAL! LOW MEMORY!\n" + memavail) + bot.sendMessage(adminid, "ВНИМАНИЕ! МАЛО ОПЕРАТИВНОЙ ПАМЯТИ!\n" + memavail) bot.sendPhoto(adminid, plotmemgraph(memlist, xaxis, tmperiod)) time.sleep(10) # 10 seconds tr += 10 From e016eda73f9e3711347e090fefdb4461ed6f3388 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:30:36 +0300 Subject: [PATCH 02/19] =?UTF-8?q?=D0=9B=D0=BE=D0=BA=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tokens.py_example | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tokens.py_example b/tokens.py_example index c97a832..274fe1a 100644 --- a/tokens.py_example +++ b/tokens.py_example @@ -1,5 +1,4 @@ -# A token you get from the Telegram's botfather +# Токен бота telegrambot = '9999999:6666aaaaaa666666a6aaa' - -# A chat_id of your client -adminchatid = [99999999] \ No newline at end of file +# Введите chat_id канала/группы/пользователя +adminchatid = [99999999] From 7ad405f00b6180fc3182dc320b8c920c7131da63 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:37:18 +0300 Subject: [PATCH 03/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D1=8F=20=D0=BF=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=D0=BE=D0=B4=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 004d24a..a62534e 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ # Server Manager Bot -A Telegram Bot: +Этот Telegram бот умеет: -* Commands - * `/stats` - gives summed statistics about memory \ disk \ processes (will improve) - * `/shell` - goes into the mode of executing shell commands & sends you the output - * `/memgraph` - plots a graph of memory usage for a past period and sends you a picture of the graph - * `/setmem` - set memory threshold (%) to monitor and notify if memory usage goes above it - * `/setpoll` - set polling interval in seconds (higher than 10) -* Monitors memory usage and if it reaches above the set threshold = sends you warning message +* Комманды + * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. + * `/shell` - позволяет использовать бот в режиме Shell. + * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. + * `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. + * `/setpoll` - интервал опроса в секундах (выше 10). +* Отслеживает использование памяти и, если она превышает установленное пороговое значение =, отправляет вам предупреждение. -Example summary: [Gif](http://i.imgur.com/AhCvy9W.gifv) +Как это работает: [Gif](https://i.13.wf/2019/08/17/1566074720-2541.gif) -![Bot](http://i.imgur.com/hXT0drx.png) +![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) Example shell command output as a message from the bot: From defb7a902d85c6cd3121b7c0977761650265a264 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:46:13 +0300 Subject: [PATCH 04/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index a62534e..786ed77 100644 --- a/README.md +++ b/README.md @@ -16,31 +16,31 @@ ![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) -Example shell command output as a message from the bot: +Пример вывода команды shell от бота: ![Shell](https://i.imgur.com/PtvcaSD.png) -Example graph sent by bot: [Gif](http://i.imgur.com/anX7rJR.gifv) +Пример графика: [Gif](http://i.imgur.com/anX7rJR.gifv) ![Graph](http://i.imgur.com/K8mG3aM.jpg?1) -# Usage +# Использование -## Requirements +## Требования * Python 3+ * [Telepot](https://github.com/nickoala/telepot) * [Psutil](https://github.com/giampaolo/psutil) - * Make sure to install it for Python 3+ - * In order to make sure that `pip` installs packages for the 3+ version: + * Не забудьте установить его для Python 3+. + * Чтобы убедиться, что `pip`устанавливает пакеты для версии 3+: * `curl -O https://bootstrap.pypa.io/get-pip.py` * `sudo python3 get-pip.py` - * After that `pip install psutil` + * После этого установите `pip install psutil` * Also Stackoverflow question about that [here](http://stackoverflow.com/questions/11268501/how-to-use-pip-with-python-3-x-alongside-python-2-x) * [matplotlib](http://matplotlib.org/) * `sudo apt-get install python3-matplotlib` -* Bot key & `tokens.py` +* Токен бота & `tokens.py` * Hide all the keys and admin variables in `tokens.py`. Use it only for sensitive variables. Avoid creating functions not to clutter the namespaces through the import. * Get a key from the [Bot Father](https://telegram.me/BotFather) * Clone that repo @@ -49,11 +49,11 @@ Example graph sent by bot: [Gif](http://i.imgur.com/anX7rJR.gifv) * In that file put a string variable `telegrambot` which equals your key * For example: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` -## Running the bot +## Запуск `python3 servstatsbot.py` -## Running the bot as "daemon" +## Запуск в режиме "daemon" * See included file in the repo: `servstatsbot.conf` * Open it and edit the path as mentiond in the comments there @@ -63,7 +63,7 @@ Example graph sent by bot: [Gif](http://i.imgur.com/anX7rJR.gifv) * If bot crashes it'll be automatically restarted * It will also start after reboot -## Setting an admin +## Настройка администратора You have to set a variable `adminchatid` in `tokens.py` to be equal your chat_id or multiple chat_id (if more people will use your bot). For example: @@ -84,6 +84,5 @@ I will reimplement this differently later. ## Alfred [http://alfredthebot.com](http://alfredthebot.com) - - - GB +## vladios13 +[Blog vladios13](http://blog.vladios13.com) From dcd6971b0ff06bb94ed90e86edb5fc663d4137ac Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:47:45 +0300 Subject: [PATCH 05/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.1.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 786ed77..5a3ec90 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Этот Telegram бот умеет: -* Комманды +* Команды * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. * `/shell` - позволяет использовать бот в режиме Shell. * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. From d0f3b37fb64cbbc0a36cc6d27bd328f0ea69019c Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:53:57 +0300 Subject: [PATCH 06/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.1.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 5a3ec90..0f073a7 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,11 @@ Этот Telegram бот умеет: * Команды - * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. - * `/shell` - позволяет использовать бот в режиме Shell. - * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. - * `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. - * `/setpoll` - интервал опроса в секундах (выше 10). + `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. + `/shell` - позволяет использовать бот в режиме Shell. + `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. + `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. + `/setpoll` - интервал опроса в секундах (выше 10). * Отслеживает использование памяти и, если она превышает установленное пороговое значение =, отправляет вам предупреждение. @@ -15,14 +15,10 @@ ![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) - Пример вывода команды shell от бота: - ![Shell](https://i.imgur.com/PtvcaSD.png) - Пример графика: [Gif](http://i.imgur.com/anX7rJR.gifv) - ![Graph](http://i.imgur.com/K8mG3aM.jpg?1) # Использование @@ -48,20 +44,20 @@ * It's added to the `.gitignore` so you don't commit your own (and I don't commit mine:) * In that file put a string variable `telegrambot` which equals your key * For example: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` - + ## Запуск `python3 servstatsbot.py` ## Запуск в режиме "daemon" -* See included file in the repo: `servstatsbot.conf` - * Open it and edit the path as mentiond in the comments there -* Place that file in `/etc/init/` -* Start the "daemon" with: `start servstatsbot` - * You can start|stop|restart - * If bot crashes it'll be automatically restarted - * It will also start after reboot +* Смотрите файл который включен в этот репозиторий: `servstatsbot.conf` + * Откройте его и отредактируйте путь, как указано в комментариях к нему. +* Поместите файл в папку `/etc/init/` +* Запустите как "daemon" с: `start servstatsbot` + * Используйте start|stop|restart + * Если произойдет сбой ботов, он будет автоматически перезапущен. + * Он также заработает после перезагрузки. ## Настройка администратора @@ -72,17 +68,17 @@ For example: * `adminchatid = [443355, 55667788, 99884433]` I will reimplement this differently later. - - + + # PLEASE CONTRIBUTE :) I threw this code together within 10 minutes or so as a mockup to work on it later. But I think it's a nice bot idea and some of you guys might like this too. So please feel free to fork, pull, requests features! Can give contributors access! Would really love to see this bot grow some fat and brain:) - - + + # Other bot development - + ## Alfred [http://alfredthebot.com](http://alfredthebot.com) ## vladios13 -[Blog vladios13](http://blog.vladios13.com) +[Blog VLADIOS13](http://blog.vladios13.com) From 14137cba8770d48ae7a8be70dc90e682c5d3e661 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:54:55 +0300 Subject: [PATCH 07/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.1.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f073a7..387dfc5 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Этот Telegram бот умеет: * Команды - `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. + `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. `/shell` - позволяет использовать бот в режиме Shell. `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. From a7dc372a2dc7dce909dfb98961c24eab2b3f15b8 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sat, 17 Aug 2019 23:56:30 +0300 Subject: [PATCH 08/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.1.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 387dfc5..6315a0a 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ Этот Telegram бот умеет: * Команды + `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. `/shell` - позволяет использовать бот в режиме Shell. `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. @@ -16,11 +17,14 @@ ![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) Пример вывода команды shell от бота: + ![Shell](https://i.imgur.com/PtvcaSD.png) Пример графика: [Gif](http://i.imgur.com/anX7rJR.gifv) + ![Graph](http://i.imgur.com/K8mG3aM.jpg?1) + # Использование ## Требования From 6bde518130246a1c5f2326fa5b13cbc7138a28bf Mon Sep 17 00:00:00 2001 From: vladios13 Date: Sun, 18 Aug 2019 00:07:14 +0300 Subject: [PATCH 09/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 51 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 6315a0a..fa6d1c1 100644 --- a/README.md +++ b/README.md @@ -3,27 +3,32 @@ Этот Telegram бот умеет: * Команды + * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. + * `/shell` - позволяет использовать бот в режиме Shell. + * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. + * `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. + * `/setpoll` - интервал опроса в секундах (выше 10). +* Отслеживает использование памяти и, **если** она **превышает** установленное пороговое значение =, **отправляет вам предупреждение**. - `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. - `/shell` - позволяет использовать бот в режиме Shell. - `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. - `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. - `/setpoll` - интервал опроса в секундах (выше 10). -* Отслеживает использование памяти и, если она превышает установленное пороговое значение =, отправляет вам предупреждение. +------------ -Как это работает: [Gif](https://i.13.wf/2019/08/17/1566074720-2541.gif) + +**Как это работает**: [Gif](https://i.13.wf/2019/08/17/1566074720-2541.gif) ![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) -Пример вывода команды shell от бота: +**Пример вывода команды shell от бота:** ![Shell](https://i.imgur.com/PtvcaSD.png) -Пример графика: [Gif](http://i.imgur.com/anX7rJR.gifv) +**Пример графика**: [Gif](http://i.imgur.com/anX7rJR.gifv) ![Graph](http://i.imgur.com/K8mG3aM.jpg?1) +------------ + + # Использование @@ -49,9 +54,15 @@ * In that file put a string variable `telegrambot` which equals your key * For example: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` + +------------ + + ## Запуск -`python3 servstatsbot.py` +Выполните: `python3 servstatsbot.py` + +------------ ## Запуск в режиме "daemon" @@ -74,15 +85,19 @@ For example: I will reimplement this differently later. -# PLEASE CONTRIBUTE :) - I threw this code together within 10 minutes or so as a mockup to work on it later. But I think it's a nice bot idea and some of you guys might like this too. So please feel free to fork, pull, requests features! - Can give contributors access! - Would really love to see this bot grow some fat and brain:) +# Развите проекта :) + Я собрал этот код в течение 10 минут, чтобы он служил макетом для дальнейшей работы. +Но я думаю, что это хорошая идея, и некоторым из вас это тоже может понравится, и пригодится. + +------------ + + +------------ -# Other bot development +# Разработчики бота -## Alfred +### Alfred -- разрботчик [http://alfredthebot.com](http://alfredthebot.com) -## vladios13 -[Blog VLADIOS13](http://blog.vladios13.com) +### vladios13 -- локализация и доработка 🌚 +[Blog vladios13](http://blog.vladios13.com) From 1eabb6dc0248790d20f41e0d20e272d2b2df8720 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Mon, 19 Aug 2019 11:57:38 +0300 Subject: [PATCH 10/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 55 +++++++++++++++++++++++-------------------------------- 1 file changed, 23 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index fa6d1c1..946b907 100644 --- a/README.md +++ b/README.md @@ -3,20 +3,19 @@ Этот Telegram бот умеет: * Команды - * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах. + * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах, а также общую нагрузку за определнный период времени. * `/shell` - позволяет использовать бот в режиме Shell. * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. * `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. * `/setpoll` - интервал опроса в секундах (выше 10). -* Отслеживает использование памяти и, **если** она **превышает** установленное пороговое значение =, **отправляет вам предупреждение**. +* Отслеживает использование памяти и, **если** она **превышает** установленное пороговое значение то **отправляет вам предупреждение**. ------------ +**Как это работает**: [Смотреть GIF](https://i.13.wf/2019/08/17/1566074720-2541.gif) -**Как это работает**: [Gif](https://i.13.wf/2019/08/17/1566074720-2541.gif) - -![Bot](https://i.13.wf/2019/08/17/1566074746-9489.png) +![Вывод изображения ](https://i.13.wf/2019/08/17/1566074746-9489.png) **Пример вывода команды shell от бота:** @@ -24,35 +23,33 @@ **Пример графика**: [Gif](http://i.imgur.com/anX7rJR.gifv) -![Graph](http://i.imgur.com/K8mG3aM.jpg?1) +![Пример графика](http://i.imgur.com/K8mG3aM.jpg?1) ------------ +# Установка -# Использование - -## Требования +## Требования к системе: * Python 3+ * [Telepot](https://github.com/nickoala/telepot) * [Psutil](https://github.com/giampaolo/psutil) * Не забудьте установить его для Python 3+. - * Чтобы убедиться, что `pip`устанавливает пакеты для версии 3+: + * Чтобы убедиться, что `pip` устанавливает пакеты для версии 3+: * `curl -O https://bootstrap.pypa.io/get-pip.py` * `sudo python3 get-pip.py` - * После этого установите `pip install psutil` + * После этого установите: `pip install psutil` * Also Stackoverflow question about that [here](http://stackoverflow.com/questions/11268501/how-to-use-pip-with-python-3-x-alongside-python-2-x) * [matplotlib](http://matplotlib.org/) * `sudo apt-get install python3-matplotlib` * Токен бота & `tokens.py` - * Hide all the keys and admin variables in `tokens.py`. Use it only for sensitive variables. Avoid creating functions not to clutter the namespaces through the import. - * Get a key from the [Bot Father](https://telegram.me/BotFather) - * Clone that repo - * In the folder with the cloned repo create a file `tokens.py` - * It's added to the `.gitignore` so you don't commit your own (and I don't commit mine:) - * In that file put a string variable `telegrambot` which equals your key - * For example: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` + * Все ключи и токены сохраняйте в `tokens.py`. + * Получить токен для бота можно в [Bot Father](https://telegram.me/BotFather) + * Клонировать репозиторий командой: `https://github.com/vladios13/ServerStatsBot.git` + * В папке с клонированным репозиторием создайте файл `tokens.py` + * В этот файл поместите строковую переменную `telegrambot` токен вашего бота. + * *Пример*: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` ------------ @@ -66,38 +63,32 @@ ## Запуск в режиме "daemon" -* Смотрите файл который включен в этот репозиторий: `servstatsbot.conf` +* Вся нужная информация находится в: `servstatsbot.conf` * Откройте его и отредактируйте путь, как указано в комментариях к нему. * Поместите файл в папку `/etc/init/` * Запустите как "daemon" с: `start servstatsbot` - * Используйте start|stop|restart - * Если произойдет сбой ботов, он будет автоматически перезапущен. + * Используйте `start|stop|restart` + * Если произойдет сбой, он будет автоматически перезапущен. * Он также заработает после перезагрузки. ## Настройка администратора -You have to set a variable `adminchatid` in `tokens.py` to be equal your chat_id or multiple chat_id (if more people will use your bot). -For example: +Вы должны установить переменную. `adminchatid` в `tokens.py`. Вы так же можете указать несколько пользователей. + +**Пример**: * `adminchatid = [443355]` * `adminchatid = [443355, 55667788, 99884433]` -I will reimplement this differently later. - - # Развите проекта :) Я собрал этот код в течение 10 минут, чтобы он служил макетом для дальнейшей работы. Но я думаю, что это хорошая идея, и некоторым из вас это тоже может понравится, и пригодится. ------------ - ------------- - - # Разработчики бота -### Alfred -- разрботчик +### Alfred - разрботчик [http://alfredthebot.com](http://alfredthebot.com) -### vladios13 -- локализация и доработка 🌚 +### vladios13 - локализация и доработка 🌚 [Blog vladios13](http://blog.vladios13.com) From a0cc47b933046d5136523bed7b0bc1d181de3a7b Mon Sep 17 00:00:00 2001 From: vladios13 Date: Mon, 19 Aug 2019 12:05:45 +0300 Subject: [PATCH 11/19] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4:=201.2.2=20-=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=D0=BE=D0=B1=D1=80=D0=B0?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 946b907..3c55d40 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ **Как это работает**: [Смотреть GIF](https://i.13.wf/2019/08/17/1566074720-2541.gif) -![Вывод изображения ](https://i.13.wf/2019/08/17/1566074746-9489.png) +![Вывод изображения ](https://i.13.yt/2019/08/19/1566205847-6575.png) **Пример вывода команды shell от бота:** @@ -23,7 +23,7 @@ **Пример графика**: [Gif](http://i.imgur.com/anX7rJR.gifv) -![Пример графика](http://i.imgur.com/K8mG3aM.jpg?1) +![Пример графика](https://i.13.wf/2019/08/19/1566205949-2775.jpg) ------------ From cfbc5e16fc882ac117fbfe59e9887875f8d8b521 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Mon, 19 Aug 2019 12:14:29 +0300 Subject: [PATCH 12/19] =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=D1=8B,=20"=D0=B4=D0=BE=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B2=D0=BE=D0=B4"=20=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- servstatsbot.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/servstatsbot.py b/servstatsbot.py index 95e3d65..663c928 100644 --- a/servstatsbot.py +++ b/servstatsbot.py @@ -20,8 +20,8 @@ -memorythreshold = 85 # If memory usage more this % -poll = 300 # seconds +memorythreshold = 85 # Если потребляется больше памяти, то этот % равен: +poll = 300 # секунды shellexecution = [] timelist = [] @@ -57,7 +57,7 @@ def plotmemgraph(memlist, xaxis, tmperiod): plt.axis([0, len(xaxis)-1, 0, 100]) plt.savefig('/tmp/graph.png') plt.close() - f = open('/tmp/graph.png', 'rb') # some file on local disk + f = open('/tmp/graph.png', 'rb') # файл изображние на локальном диске return f @@ -70,8 +70,8 @@ def __init__(self, *args, **kwargs): def on_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) # Do your stuff according to `content_type` ... - print("Your chat_id:" + str(chat_id)) # this will tell you your chat_id - if chat_id in adminchatid: # Store adminchatid variable in tokens.py + print("Ваш chat_id:" + str(chat_id)) # узнать chat_id + if chat_id in adminchatid: # Переменная adminchatid хранится в tokens.py if content_type == 'text': if msg['text'] == '/stats' and chat_id not in shellexecution: bot.sendChatAction(chat_id, 'typing') @@ -133,26 +133,26 @@ def on_chat_message(self, msg): else: 1/0 except: - bot.sendMessage(chat_id, "Please send a proper numeric value higher than 10.") + bot.sendMessage(chat_id, "Пожалуйста, отправьте числовое значение выше 10.") elif msg['text'] == "/shell" and chat_id not in shellexecution: bot.sendMessage(chat_id, "Отправь мне Shell-комманду", reply_markup=stopmarkup) shellexecution.append(chat_id) elif msg['text'] == "/setmem" and chat_id not in settingmemth: bot.sendChatAction(chat_id, 'typing') settingmemth.append(chat_id) - bot.sendMessage(chat_id, "Send me a new memory threshold to monitor?", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Установи новый порог памяти для мониторинга", reply_markup=stopmarkup) elif chat_id in settingmemth: bot.sendChatAction(chat_id, 'typing') try: global memorythreshold memorythreshold = int(msg['text']) if memorythreshold < 100: - bot.sendMessage(chat_id, "All set!") + bot.sendMessage(chat_id, "Все получилось!") clearall(chat_id) else: 1/0 except: - bot.sendMessage(chat_id, "Please send a proper numeric value below 100.") + bot.sendMessage(chat_id, "Пожалуйста, отправь числовое значение ниже 100.") elif chat_id in shellexecution: bot.sendChatAction(chat_id, 'typing') @@ -161,7 +161,7 @@ def on_chat_message(self, msg): if output != b'': bot.sendMessage(chat_id, output, disable_web_page_preview=True) else: - bot.sendMessage(chat_id, "No output.", disable_web_page_preview=True) + bot.sendMessage(chat_id, "Упс.", disable_web_page_preview=True) elif msg['text'] == '/memgraph': bot.sendChatAction(chat_id, 'upload_photo') tmperiod = "За %.2f часа" % ((datetime.now() - graphstart).total_seconds() / 3600) From d2290e38e2e49089fe16504fe5754588a4904296 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Mon, 19 Aug 2019 12:15:33 +0300 Subject: [PATCH 13/19] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tokens.py_example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tokens.py_example b/tokens.py_example index 274fe1a..861f21b 100644 --- a/tokens.py_example +++ b/tokens.py_example @@ -1,4 +1,4 @@ # Токен бота telegrambot = '9999999:6666aaaaaa666666a6aaa' -# Введите chat_id канала/группы/пользователя +# Введите chat_id канала/группы/пользователя. Можно использовать несколько значений, подробнее в readme.md adminchatid = [99999999] From bc9723acfa0f7aab5d34772e2379ccdcacd2a585 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 20 Jan 2020 22:11:13 +0300 Subject: [PATCH 14/19] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5=20=D0=B7?= =?UTF-8?q?=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D1=8F,=20=D0=B8=20=D0=B8?= =?UTF-8?q?=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=BC?= =?UTF-8?q?=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D1=82=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- servstatsbot.py | 14 +++++++++++--- tokens.py_example | 2 +- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/servstatsbot.py b/servstatsbot.py index 663c928..4093118 100644 --- a/servstatsbot.py +++ b/servstatsbot.py @@ -21,7 +21,7 @@ memorythreshold = 85 # Если потребляется больше памяти, то этот % равен: -poll = 300 # секунды +poll = 300 # значения в секундах shellexecution = [] timelist = [] @@ -31,7 +31,7 @@ setpolling = [] graphstart = datetime.now() -stopmarkup = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Stop")]],resize_keyboard=True) +stopmarkup = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Stop Shell")]],resize_keyboard=True) # stopmarkup = {'keyboard': [['Stop']]} hide_keyboard = {'hide_keyboard': True} @@ -78,16 +78,21 @@ def on_chat_message(self, msg): memory = psutil.virtual_memory() disk = psutil.disk_usage('/') cpuget = psutil.getloadavg() + сpu_countF = psutil.cpu_count(logical=False) + сpu_countL = psutil.cpu_count(logical=True) cpufr = psutil.cpu_freq(percpu=False) boottime = datetime.fromtimestamp(psutil.boot_time()) now = datetime.now() - cpuget = "Среднаяя нагрузка CPU: " + str(cpuget) + cpuget = "Средняя нагрузка CPU: " + str(cpuget) cpufr = "Текущая частота CPU: " + str(cpufr.current) + "Mhz" + сpu_countF = "Физических ядер: " + str(сpu_countF) + сpu_countL = "Логических ядер: " + str(сpu_countL) timedif = "Сервер работает уже: %.1f часов" % (((now - boottime).total_seconds()) / 3600) memtotal = "Всего ОЗУ: %.2f GB " % (memory.total / 1000000000) memavail = "Свободно ОЗУ: %.2f GB" % (memory.available / 1000000000) memuseperc = "Используется ОЗУ: " + str(memory.percent) + " %" diskused = "Использовано HDD: " + str(disk.percent) + " %" + pidsinf = "Текущие процессы:" pids = psutil.pids() pidsreply = '' @@ -110,9 +115,12 @@ def on_chat_message(self, msg): cpuget + "\n" + \ cpufr + "\n" + \ memtotal + "\n" + \ + сpu_countF + "\n" + \ + сpu_countL + "\n" + \ memavail + "\n" + \ memuseperc + "\n" + \ diskused + "\n\n" + \ + pidsinf + "\n" + \ pidsreply bot.sendMessage(chat_id, reply, disable_web_page_preview=True, parse_mode='HTML') elif msg['text'] == "Stop": diff --git a/tokens.py_example b/tokens.py_example index 861f21b..da53b3a 100644 --- a/tokens.py_example +++ b/tokens.py_example @@ -1,4 +1,4 @@ # Токен бота telegrambot = '9999999:6666aaaaaa666666a6aaa' # Введите chat_id канала/группы/пользователя. Можно использовать несколько значений, подробнее в readme.md -adminchatid = [99999999] +adminchatid = [99999999] \ No newline at end of file From 2273350f1808733012dfb874e1b0d83f19a79104 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 20 Jan 2020 22:19:17 +0300 Subject: [PATCH 15/19] =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B2?= =?UTF-8?q?=20=D0=BF=D1=83=D0=BD=D0=BA=D1=82=D1=83=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- servstatsbot.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/servstatsbot.py b/servstatsbot.py index 4093118..c3226fa 100644 --- a/servstatsbot.py +++ b/servstatsbot.py @@ -107,7 +107,7 @@ def on_chat_message(self, msg): else: procs[p.name()] = pmem except: - print("Hm") + print("ХМ?") sortedprocs = sorted(procs.items(), key=operator.itemgetter(1), reverse=True) for proc in sortedprocs: pidsreply += proc[0] + " " + ("%.2f" % proc[1]) + " %\n" @@ -129,7 +129,7 @@ def on_chat_message(self, msg): elif msg['text'] == '/setpoll' and chat_id not in setpolling: bot.sendChatAction(chat_id, 'typing') setpolling.append(chat_id) - bot.sendMessage(chat_id, "Отправить мне новый интервал опроса в секундах? (выше 10)", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Отправьте мне новый интервал проверки в секундах? (выше 10)", reply_markup=stopmarkup) elif chat_id in setpolling: bot.sendChatAction(chat_id, 'typing') try: @@ -141,14 +141,14 @@ def on_chat_message(self, msg): else: 1/0 except: - bot.sendMessage(chat_id, "Пожалуйста, отправьте числовое значение выше 10.") + bot.sendMessage(chat_id, "Отправьте числовое значение выше 10.") elif msg['text'] == "/shell" and chat_id not in shellexecution: - bot.sendMessage(chat_id, "Отправь мне Shell-комманду", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Отправьте мне Shell-комманду", reply_markup=stopmarkup) shellexecution.append(chat_id) elif msg['text'] == "/setmem" and chat_id not in settingmemth: bot.sendChatAction(chat_id, 'typing') settingmemth.append(chat_id) - bot.sendMessage(chat_id, "Установи новый порог памяти для мониторинга", reply_markup=stopmarkup) + bot.sendMessage(chat_id, "Установите новый порог памяти для мониторинга", reply_markup=stopmarkup) elif chat_id in settingmemth: bot.sendChatAction(chat_id, 'typing') try: @@ -160,7 +160,7 @@ def on_chat_message(self, msg): else: 1/0 except: - bot.sendMessage(chat_id, "Пожалуйста, отправь числовое значение ниже 100.") + bot.sendMessage(chat_id, "Пожалуйста, отправьте числовое значение ниже 100.") elif chat_id in shellexecution: bot.sendChatAction(chat_id, 'typing') From 03a2cbca5a7623ed747d3323084c868f0820cb1b Mon Sep 17 00:00:00 2001 From: Vlad Date: Tue, 21 Jan 2020 16:16:54 +0300 Subject: [PATCH 16/19] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20requirements.txt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bc12e76 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +psutil +telepot +matplotlib \ No newline at end of file From 6d3abfe7de1f7d5522c32ab488e8fcedf6875aca Mon Sep 17 00:00:00 2001 From: vladios13 Date: Tue, 21 Jan 2020 16:18:37 +0300 Subject: [PATCH 17/19] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20README.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 83 +++++++++++++++++-------------------------------------- 1 file changed, 26 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 3c55d40..ffce86b 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,40 @@ -# Server Manager Bot +# SERVER MANAGER BOT +Команды и возможности бота: -Этот Telegram бот умеет: - -* Команды - * `/stats` - дает обобщенную статистику о памяти \ диске \ процессах, а также общую нагрузку за определнный период времени. - * `/shell` - позволяет использовать бот в режиме Shell. - * `/memgraph` - строит график использования памяти за прошедший период и отправляет вам изображение графика. - * `/setmem` - возможность установить порог оперативной памяти (%) для мониторинга. - * `/setpoll` - интервал опроса в секундах (выше 10). -* Отслеживает использование памяти и, **если** она **превышает** установленное пороговое значение то **отправляет вам предупреждение**. +| Команда | Описание | +| ------ | ------ | +| `/stats` | дает обобщенную статистику о памяти \ диске \ процессах, а также общую нагрузку за определнный период времени | +| `/shell` | позволяет использовать бот в режиме Shell | +| `/memgraph` | строит график использования памяти за прошедший период | +| `/setmem` | возможность установить порог оперативной памяти (%) для мониторинга | +| `/setpoll` | интервал опроса в секундах (выше 10) | ------------ - - **Как это работает**: [Смотреть GIF](https://i.13.wf/2019/08/17/1566074720-2541.gif) ![Вывод изображения ](https://i.13.yt/2019/08/19/1566205847-6575.png) -**Пример вывода команды shell от бота:** - -![Shell](https://i.imgur.com/PtvcaSD.png) - -**Пример графика**: [Gif](http://i.imgur.com/anX7rJR.gifv) - +**Пример графика**: ![Пример графика](https://i.13.wf/2019/08/19/1566205949-2775.jpg) ------------ +## Установка -# Установка - -## Требования к системе: - -* Python 3+ -* [Telepot](https://github.com/nickoala/telepot) -* [Psutil](https://github.com/giampaolo/psutil) - * Не забудьте установить его для Python 3+. - * Чтобы убедиться, что `pip` устанавливает пакеты для версии 3+: - * `curl -O https://bootstrap.pypa.io/get-pip.py` - * `sudo python3 get-pip.py` - * После этого установите: `pip install psutil` - * Also Stackoverflow question about that [here](http://stackoverflow.com/questions/11268501/how-to-use-pip-with-python-3-x-alongside-python-2-x) -* [matplotlib](http://matplotlib.org/) - * `sudo apt-get install python3-matplotlib` -* Токен бота & `tokens.py` - * Все ключи и токены сохраняйте в `tokens.py`. - * Получить токен для бота можно в [Bot Father](https://telegram.me/BotFather) - * Клонировать репозиторий командой: `https://github.com/vladios13/ServerStatsBot.git` - * В папке с клонированным репозиторием создайте файл `tokens.py` - * В этот файл поместите строковую переменную `telegrambot` токен вашего бота. - * *Пример*: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` +```sh +$ git https://github.com/vladios13/ServerStatsBot.git +$ cd ServerStatsBot +$ sudo pip3 install -r requirements.txt +``` +* Все ключи и токены сохраняйте в `tokens.py`. +* Получить токен для бота можно в [Bot Father](https://t.me/BotFather) +* В этот файл поместите строковую переменную `telegrambot` токен вашего бота. +* Пример: `telegrambot = "000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"` +Вы должны установить переменную. `adminchatid` в `tokens.py`. Вы так же можете указать несколько пользователей. +**Пример**: +* `adminchatid = [443355]` +* `adminchatid = [443355, 55667788, 99884433]` ------------ @@ -64,28 +48,13 @@ ## Запуск в режиме "daemon" * Вся нужная информация находится в: `servstatsbot.conf` - * Откройте его и отредактируйте путь, как указано в комментариях к нему. +* Откройте его и отредактируйте путь, как указано в комментариях к нему. * Поместите файл в папку `/etc/init/` -* Запустите как "daemon" с: `start servstatsbot` +* Запустите как "daemon" : `start servstatsbot` * Используйте `start|stop|restart` * Если произойдет сбой, он будет автоматически перезапущен. * Он также заработает после перезагрузки. - -## Настройка администратора - -Вы должны установить переменную. `adminchatid` в `tokens.py`. Вы так же можете указать несколько пользователей. - -**Пример**: - -* `adminchatid = [443355]` -* `adminchatid = [443355, 55667788, 99884433]` - -# Развите проекта :) - Я собрал этот код в течение 10 минут, чтобы он служил макетом для дальнейшей работы. -Но я думаю, что это хорошая идея, и некоторым из вас это тоже может понравится, и пригодится. - ------------ - # Разработчики бота ### Alfred - разрботчик From dc19938ba84add6d917ed7d05b7acdf6d2b894f0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 20 Jan 2020 22:11:13 +0300 Subject: [PATCH 18/19] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B2=20Readme.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bc12e76 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +psutil +telepot +matplotlib \ No newline at end of file From 0fd0aedbeee6f051d3d51bf3b9aa78138e006ed5 Mon Sep 17 00:00:00 2001 From: vladios13 Date: Tue, 21 Jan 2020 16:19:37 +0300 Subject: [PATCH 19/19] fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ffce86b..9c0233f 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ ![Вывод изображения ](https://i.13.yt/2019/08/19/1566205847-6575.png) **Пример графика**: + ![Пример графика](https://i.13.wf/2019/08/19/1566205949-2775.jpg) ------------ @@ -38,7 +39,6 @@ $ sudo pip3 install -r requirements.txt ------------ - ## Запуск Выполните: `python3 servstatsbot.py`