Skip to content

Commit

Permalink
1. 国际化
Browse files Browse the repository at this point in the history
  • Loading branch information
bboysoulcn committed Jul 30, 2024
2 parents 7a8b5ad + 7eb3274 commit ef50291
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 74 deletions.
61 changes: 32 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,68 +1,71 @@
[中文](README_CN.md) | [English](README.md)

# TeleMonitor

TeleMonitor 是一个使用 Python 编写的系统监控工具,它可以监控 CPU、内存和磁盘的使用情况,并通过 Telegram 发送警告。
TeleMonitor is a system monitoring tool written in Python that can monitor CPU, memory, and disk usage and send alerts via Telegram.

## 使用
## Usage

首先,你需要创建一个 Telegram bot,然后获取 API token。你可以参考 [Telegram 官方文档](https://core.telegram.org/bots/features#botfather) 来创建一个 Telegram bot
First, you need to create a Telegram bot and get the API token. You can refer to the [Telegram official documentation](https://core.telegram.org/bots/features#botfather) to create a Telegram bot.

然后,你需要获取你希望接收警告的 Telegram chat ID。你可以使用 [@userinfobot](https://t.me/userinfobot) 来获取你的 chat ID
Then, you need to get the Telegram chat ID where you want to receive alerts. You can use [@userinfobot](https://t.me/userinfobot) to get your chat ID.

接下来 clone 这个项目:
Next, clone this project:

```bash
git clone https://github.com/bboysoulcn/telemonitor.git
```

你可以使用docker compose 来运行 Telemonitor:
You can use docker compose to run TeleMonitor:

```bash
docker-compose up -d
```

或者你可以使用 k8s 来运行 Telemonitor:
Or you can use k8s to run TeleMonitor:

```bash
kubectl apply -f deployment.yaml
```

下面是 Telemonitor 的环境变量:
Here are the environment variables for TeleMonitor:

- `TG_API_TOKEN`: 你的 Telegram bot 的 API token。
- `TG_CHAT_ID`: 你希望接收警告的 Telegram chat ID。
- `TG_API_BASE_URL`: Telegram API 的基础 URL,默认值为 `https://api.telegram.org`.
- `CPU_PERCENT`: CPU 使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `MEMORY_PERCENT`: 内存使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `DISK_PERCENT`: 磁盘使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `MONITOR_INTERVAL`: 监控的间隔时间(秒),默认值为 60。
- `DISK_PATH`: 磁盘的路径,默认值为 `/host`
- `URL_LIST`: 需要监控的 URL 列表,用逗号分隔,默认值为空。
- `TG_API_TOKEN`: The API token of your Telegram bot.
- `TG_CHAT_ID`: The Telegram chat ID where you want to receive alerts.
- `TG_API_BASE_URL`: The base URL of the Telegram API, default is `https://api.telegram.org`.
- `CPU_PERCENT`: The threshold for CPU usage. TeleMonitor will send an alert if the usage exceeds this value. Default is 80.
- `MEMORY_PERCENT`: The threshold for memory usage. TeleMonitor will send an alert if the usage exceeds this value. Default is 80.
- `DISK_PERCENT`: The threshold for disk usage. TeleMonitor will send an alert if the usage exceeds this value. Default is 80.
- `MONITOR_INTERVAL`: The interval time (in seconds) for monitoring. Default is 60.
- `DISK_PATH`: The path of the disk. Default is `/host`.
- `URL_LIST`: The list of URLs to monitor, separated by commas. Default is empty.
- `LANGUAGE`: The language. Default is `en`. Options are `en` and `cn`.

下面是机器人的命令:
Here are the commands for the bot:

- /start - 获取帮助
- /help - 获取帮助
- /status - 获取系统状态
- /start - Get help
- /help - Get help
- /status - Get system status

### 如果你不能访问Telegram API
### If you cannot access the Telegram API

你可以使用下面项目创建一个 api 代理,并且修改环境变量 TG_API_BASE_URL
You can use the following project to create an API proxy and modify the environment variable `TG_API_BASE_URL`:

[teleproxy](https://github.com/bboysoulcn/teleproxy)

### 效果展示
### Demo

![](./images/img1.webp)
![](./images/img2.webp)

## 贡献者
## Contributors

- [SimonGino](https://github.com/SimonGino)

## 广告位
## Telegram Channel

我的tg频道 [https://t.me/bboyapp](https://t.me/bboyapp)
My telegram channel: [https://t.me/bboysoulcn](https://t.me/bboysoulcn)

## 许可证
## License

这个项目使用 MIT 许可证,详情请见 [LICENSE](LICENSE) 文件。
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
71 changes: 71 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
[中文](README_CN.md) | [English](README.md)

# TeleMonitor

TeleMonitor 是一个使用 Python 编写的系统监控工具,它可以监控 CPU、内存和磁盘的使用情况,并通过 Telegram 发送警告。

## 使用

首先,你需要创建一个 Telegram bot,然后获取 API token。你可以参考 [Telegram 官方文档](https://core.telegram.org/bots/features#botfather) 来创建一个 Telegram bot。

然后,你需要获取你希望接收警告的 Telegram chat ID。你可以使用 [@userinfobot](https://t.me/userinfobot) 来获取你的 chat ID。

接下来 clone 这个项目:

```bash
git clone https://github.com/bboysoulcn/telemonitor.git
```

你可以使用docker compose 来运行 Telemonitor:

```bash
docker-compose up -d
```

或者你可以使用 k8s 来运行 Telemonitor:

```bash
kubectl apply -f deployment.yaml
```

下面是 Telemonitor 的环境变量:

- `TG_API_TOKEN`: 你的 Telegram bot 的 API token。
- `TG_CHAT_ID`: 你希望接收警告的 Telegram chat ID。
- `TG_API_BASE_URL`: Telegram API 的基础 URL,默认值为 `https://api.telegram.org`.
- `CPU_PERCENT`: CPU 使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `MEMORY_PERCENT`: 内存使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `DISK_PERCENT`: 磁盘使用率的阈值,超过这个阈值时,Telemonitor 会发送警告,默认值为 80。
- `MONITOR_INTERVAL`: 监控的间隔时间(秒),默认值为 60。
- `DISK_PATH`: 磁盘的路径,默认值为 `/host`
- `URL_LIST`: 需要监控的 URL 列表,用逗号分隔,默认值为空。
- `LANGUAGE`: 语言,默认值为 `en`。可选值为 `en``cn`

下面是机器人的命令:

- /start - 获取帮助
- /help - 获取帮助
- /status - 获取系统状态

### 如果你不能访问Telegram API

你可以使用下面项目创建一个 api 代理,并且修改环境变量 TG_API_BASE_URL

[teleproxy](https://github.com/bboysoulcn/teleproxy)

### 效果展示

![](./images/img1.webp)
![](./images/img2.webp)

## 贡献者

- [SimonGino](https://github.com/SimonGino)

## Telegram 频道

我的 Telegram 频道: [https://t.me/bboysoulcn](https://t.me/bboysoulcn)

## 许可证

这个项目使用 MIT 许可证,详情请见 [LICENSE](LICENSE) 文件。
2 changes: 2 additions & 0 deletions deploymet.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ spec:
value: "/host"
- name: URL_LIST
value: "https://www.baidu.com,https://www.google.com,https://www.bing.com"
- name: LANGUAGE
value: "cn"
volumeMounts:
- name: localtime
mountPath: /etc/localtime
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ services:
- TG_API_BASE_URL=https://api.telegram.org/bot
- DISK_PATH=/host
- URL_LIST=https://www.baidu.com,https://www.google.com,https://www.bing.com
- LANGUAGE=cn
network_mode: host
pid: host
volumes:
Expand Down
143 changes: 98 additions & 45 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import datetime
import time
import platform
import psutil
from telegram import Update
Expand All @@ -9,14 +8,72 @@
import httpx


def get_language():
return os.environ.get('LANGUAGE', 'en')


def get_message(key, **kwargs):
messages = {
'en': {
'help': "👋 Use /status to get system information",
'boot': "🎮 *Genshin Impact started\!*",
'cpu_warning': "⚠️ *Warning*: CPU usage has reached *{usage}%*\! Threshold set to *{threshold}%*\.",
'url_warning': "⚠️ *Warning*: {url} status code is *{status_code}*",
'url_access_failed': "⚠️ *Warning*: {url} access failed",
'memory_warning': "⚠️ *Warning*: Memory usage has reached *{usage}%*\! Threshold set to *{threshold}%*\.",
'disk_warning': "⚠️ *Warning*: Disk usage has reached *{usage}%*\! Threshold set to *{threshold}%*\.",
'system_info': """
📊 **System Information**\n
🌍 *System Name:* {system_name}
📌 *Hostname:* {hostname}
🖥️ *CPU Usage:* {cpu_usage}%
🧠 *Memory Usage:* {memory_usage}%
💽 *Disk Usage:* {disk_usage}%
👾 *Process Count:* {process_count}
🕰️ *Uptime:* {uptime}
🌐 *Network Info:*
📤 Bytes Sent: {bytes_sent} GB
📥 Bytes Recv: {bytes_recv} GB
🔗 *Monitor URL:*
{urls_info}
"""
},
'cn': {
'help': "👋 使用 /status 来获取系统信息",
'boot': "🎮 *原神启动\!*",
'cpu_warning': "⚠️ *警告*: CPU 使用率已经达到 *{usage}%*\! 阈值设置为 *{threshold}%*\.",
'url_warning': "⚠️ *警告*: {url} 状态码为 *{status_code}*",
'url_access_failed': "⚠️ *警告*: {url} 访问失败",
'memory_warning': "⚠️ *警告*: 内存使用率已经达到 *{usage}%*\! 阈值设置为 *{threshold}%*\.",
'disk_warning': "⚠️ *警告*: 磁盘使用率已经达到 *{usage}%*\! 阈值设置为 *{threshold}%*\.",
'system_info': """
📊 **系统信息**\n
🌍 *系统名称:* {system_name}
📌 *主机名:* {hostname}
🖥️ *CPU使用率:* {cpu_usage}%
🧠 *内存使用率:* {memory_usage}%
💽 *磁盘使用率:* {disk_usage}%
👾 *进程数量:* {process_count}
🕰️ *开机时间:* {uptime}
🌐 *网络信息:*
📤 已发送: {bytes_sent} GB
📥 已接收: {bytes_recv} GB
🔗 *监控URL:*
{urls_info}
"""
}
}
language = get_language()
return messages[language].get(key, '').format(**kwargs)


async def monitor_cpu_usage(context: ContextTypes.DEFAULT_TYPE):
cpu_percent = int(context.job.data)
cpu_usage = int(psutil.cpu_percent(interval=1))
if cpu_usage >= cpu_percent:
# 使用中文发送并且美化发送格式而且要添加emoji
await context.bot.send_message(chat_id=context.job.chat_id,
text=f"⚠️ *警告*: CPU 使用率已经达到 *{cpu_usage}%*\! 阈值设置为 *{cpu_percent}%*\.",
parse_mode="MarkdownV2")
message = get_message('cpu_warning', usage=cpu_usage,
threshold=cpu_percent)
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2")


async def monitor_url(context: ContextTypes.DEFAULT_TYPE):
Expand All @@ -26,23 +83,24 @@ async def monitor_url(context: ContextTypes.DEFAULT_TYPE):
response = httpx.get(url)
url = escape_markdown(url, version=2)
if response.status_code != 200:
await context.bot.send_message(chat_id=context.job.chat_id,
text=f"⚠️ *警告*: {url} 状态码为 *{response.status_code}*",
parse_mode="MarkdownV2", disable_web_page_preview=True)
message = get_message('url_warning', url=url,
status_code=response.status_code)
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2",
disable_web_page_preview=True)
except Exception as e:
await context.bot.send_message(chat_id=context.job.chat_id,
text=f"⚠️ *警告*: {url} 访问失败",
parse_mode="MarkdownV2",disable_web_page_preview=True)
message = get_message('url_access_failed', url=url)
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2",
disable_web_page_preview=True)


async def monitor_memory_usage(context: ContextTypes.DEFAULT_TYPE):
memory_percent = int(context.job.data)
memory_info = psutil.virtual_memory()
memory_usage = int(memory_info.percent)
if memory_usage >= memory_percent:
await context.bot.send_message(chat_id=context.job.chat_id,
text=f"⚠️ *警告*: 内存使用率已经达到 *{memory_usage}%*\! 阈值设置为 *{memory_percent}%*\.",
parse_mode="MarkdownV2")
message = get_message('memory_warning', usage=memory_usage,
threshold=memory_percent)
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2")


async def monitor_disk_usage(context: ContextTypes.DEFAULT_TYPE):
Expand All @@ -51,9 +109,9 @@ async def monitor_disk_usage(context: ContextTypes.DEFAULT_TYPE):
disk_info = psutil.disk_usage(disk_path)
disk_usage = int(disk_info.percent)
if disk_usage >= disk_percent:
await context.bot.send_message(chat_id=context.job.chat_id,
text=f"⚠️ *警告*: 磁盘使用率已经达到 *{disk_usage}%*\! 阈值设置为 *{disk_percent}%*\.",
parse_mode="MarkdownV2")
message = get_message('disk_warning', usage=disk_usage,
threshold=disk_percent)
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2")


def get_systeminfo():
Expand Down Expand Up @@ -95,36 +153,31 @@ async def reply_systeminfo(update: Update, context: ContextTypes.DEFAULT_TYPE) -
cpu_usage, memory_usage, disk_usage, bytes_sent, bytes_recv, process_count, uptime, system_name, hostname = get_systeminfo()
system_name = escape_markdown(system_name, version=2)
hostname = escape_markdown(hostname, version=2)
# Format the system information into a string
system_info = f"""
📊 **系统信息**\n
🌍 *系统名称:* {system_name}
📌 *主机名:* {hostname}
🖥️ *CPU使用率:* {int(cpu_usage)}%
🧠 *内存使用率:* {int(memory_usage)}%
💽 *磁盘使用率:* {int(disk_usage)}%
👾 *进程数量:* {process_count}
🕰️ *开机时间:* {uptime}
🌐 *网络信息:*
📤 已发送: {int(bytes_sent)} GB
📥 已接收: {int(bytes_recv)} GB
"""
# Send the system information to the user
await update.message.reply_text(system_info, parse_mode="MarkdownV2")
cpu_usage = int(cpu_usage)
memory_usage = int(memory_usage)
disk_usage = int(disk_usage)
bytes_sent = int(bytes_sent)
bytes_recv = int(bytes_recv)
url_list = os.environ.get('URL_LIST', 'https://www.baidu.com').split(',')
urls_info = ""
for url in url_list:
url = escape_markdown(url, version=2)
urls_info = urls_info + f"\- {url}\n"
message = get_message( 'system_info',
cpu_usage=cpu_usage, memory_usage=memory_usage, disk_usage=disk_usage,
bytes_sent=bytes_sent, bytes_recv=bytes_recv, process_count=process_count,
uptime=uptime, system_name=system_name, hostname=hostname, urls_info=urls_info)
await update.message.reply_text(message, parse_mode="MarkdownV2", disable_web_page_preview=True)


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Sends explanation on how to use the bot."""
await update.message.reply_text("👋 使用 `/status` 来获取系统信息",
parse_mode="MarkdownV2")
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = get_message( 'help')
await update.message.reply_text(message, parse_mode="MarkdownV2")


async def start_boot(context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=context.job.chat_id, text="🚀 *原神启动中\.\.\.*",
parse_mode="MarkdownV2")
time.sleep(1)
await context.bot.send_message(chat_id=context.job.chat_id, text="🎮 *原神启动完成\!*",
parse_mode="MarkdownV2")
async def boot(context: ContextTypes.DEFAULT_TYPE):
message = get_message('boot')
await context.bot.send_message(chat_id=context.job.chat_id, text=message, parse_mode="MarkdownV2")


def main() -> None:
Expand All @@ -148,9 +201,9 @@ def main() -> None:
job_queue.run_repeating(monitor_memory_usage, interval=monitor_interval, first=10, chat_id=tg_chat_id,
data=disk_percent)
job_queue.run_repeating(monitor_url, interval=monitor_interval, first=10, chat_id=tg_chat_id, data=url_list)
job_queue.run_once(start_boot, chat_id=tg_chat_id, when=2)
job_queue.run_once(boot, chat_id=tg_chat_id, when=2)
# on different commands - answer in Telegram
application.add_handler(CommandHandler(["start", "help"], start))
application.add_handler(CommandHandler(["start", "help"], help))
application.add_handler(CommandHandler("status", reply_systeminfo))
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
Expand Down

0 comments on commit ef50291

Please sign in to comment.