Skip to content

Commit

Permalink
chore(templ): update templates and methods
Browse files Browse the repository at this point in the history
  • Loading branch information
orenlab committed Jan 14, 2025
1 parent fd9f9f5 commit e795f34
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 72 deletions.
4 changes: 4 additions & 0 deletions pytmbot/adapters/psutil/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,7 @@ def _get_top_processes():
return sorted_processes[:count]

return self._safe_execute("top processes", _get_top_processes, [])

def get_cpu_count(self) -> int:
"""Get the number of CPU cores."""
return self._psutil.cpu_count()
5 changes: 2 additions & 3 deletions pytmbot/handlers/server_handlers/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
@logger.session_decorator
def handle_network(message: Message, bot: TeleBot):
emojis = {
"up_left_arrow": em.get_emoji("up-left_arrow"),
"up_right_arrow": em.get_emoji("up-right_arrow"),
"thought_balloon": em.get_emoji("thought_balloon"),
"globe_showing_europe_africa": em.get_emoji("globe_showing_Europe-Africa"),
"hugging_face": em.get_emoji("smiling_face_with_open_hands"),
}
Expand All @@ -46,7 +45,7 @@ def handle_network(message: Message, bot: TeleBot):
message_text = compiler.compile()

return bot.send_message(
message.chat.id, text=message_text, parse_mode="Markdown"
message.chat.id, text=message_text, parse_mode="HTML"
)

except Exception as error:
Expand Down
15 changes: 4 additions & 11 deletions pytmbot/handlers/server_handlers/quickview.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,6 @@ def _get_processes() -> Optional[Dict]:
return None


def _get_cpu() -> Optional[Dict]:
"""Get CPU usage."""
try:
return psutil_adapter.get_cpu_usage()
except Exception as e:
logger.error(f"Failed to get CPU usage: {e}")
return None


def _get_docker() -> Optional[Dict]:
"""Get Docker statistics."""
try:
Expand All @@ -89,11 +80,13 @@ def _collect_metrics() -> Dict[str, Any]:
'load_average': _get_load,
'memory': _get_memory,
'processes': _get_processes,
'cpu': _get_cpu,
'docker': _get_docker
}

with ThreadPoolExecutor(max_workers=len(tasks)) as executor:
# Calculate optimal number of workers
optimal_workers = min(len(tasks), (psutil_adapter.get_cpu_count() or 2) + 1)

with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
# Start all tasks
future_to_task = {
executor.submit(func): name
Expand Down
2 changes: 1 addition & 1 deletion pytmbot/plugins/monitor/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@


class SystemMonitorPlugin(PluginCore):
"""Optimized plugin for monitoring system resources."""
"""Plugin for monitoring system resources."""

__slots__ = (
'bot', 'monitor_settings', 'event_threshold_duration',
Expand Down
61 changes: 36 additions & 25 deletions pytmbot/templates/base_templates/b_index.jinja2
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
{# templates/index.jinja2 #}

Hi *{{ first_name }}*,

I'm a bot for server monitoring, here to help you keep an eye on your server. I'm still learning, but today I can provide you with some useful information.

Here's what I can tell you:

🐳 *A large section on Docker*

- Information about containers (even those that have finished work)
- The ability to view container logs
- Information about images
- Management of containers (start, stop, remove, and more)

💡 *Features*

- Load average information
- Summary memory usage information (with swap)
- Sensors information
- Summary process information
- Uptime information
- File system base information
- Basic information about the network connection
- Support for plugins, allowing you to extend my capabilities

My knowledge is still growing, so I recommend checking back periodically to see what I've learned. If there is anything else that I can help you with, please let me know. You can find me on [GitHub](https://github.com/orenlab/pytmbot/)
Hello, *{{ first_name }}*! 👋

I’m *pyTMbot*, a versatile Telegram bot designed for Docker management, server monitoring, and extending functionality through plugins. I support both polling and webhook modes and can be deployed on your host machine or inside a Docker container.

Here’s what I can do:

🐳 *Docker Management*
- Start, stop, restart, and manage containers
- Monitor real-time status of running/stopped containers
- Access and search detailed container logs
- Inspect and manage Docker images (tags, metadata)
- *NEW*: Check for Docker image updates (compare local tags with Docker Hub)

🖥️ *Server Monitoring*
- Load average and system uptime
- Memory and swap usage
- Real-time sensor data
- Process summary and control
- Network and file system information
- *NEW*: Quick system and Docker summary

🔌 *Plugin System*
- Extend my functionality with custom plugins:
- *Monitor Plugin*: Track CPU, memory, disk usage, and Docker changes.
- *2FA Plugin*: Two-factor authentication via QR codes and TOTP.
- *Outline VPN Plugin*: Monitor your Outline VPN server.

🔖 *Additional Features*
- Check for bot updates: `/check_bot_updates`
- Emoji support for better interaction 😎
- Templated responses powered by Jinja2
- Extensive logging via Docker log aggregators

I’m constantly improving, so check back often for updates! If you have questions or suggestions, let me know. You can find me on [GitHub](https://github.com/orenlab/pytmbot/).

Happy monitoring! 🚀
30 changes: 21 additions & 9 deletions pytmbot/templates/base_templates/b_net_io.jinja2
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
{# templates/fs.jinja2 #}

{{ thought_balloon }} Here is:
{{ thought_balloon }} Network stats:

<pre language="bash">
{% for value in context %}
{{ up_left_arrow }} **Bytes sent:** {{ value['bytes_sent'] }}
{{ up_right_arrow }} **Bytes received:** {{ value['bytes_recv'] }}
{{ up_left_arrow }} **Packets sent:** {{ value['packets_sent'] }}
{{ up_right_arrow }} **Packets received:** {{ value['packets_recv'] }}
{{ up_right_arrow }} **Input errors:** {{ value['err_in'] }}
{{ up_left_arrow }} **Output errors:** {{ value['err_out'] }}
{{ up_right_arrow }} **Input dropped packets:** {{ value['drop_in'] }}
{{ up_left_arrow }} **Output dropped packets:** {{ value['drop_out'] }}
{% set sent_bytes = value['bytes_sent'] | string %}
{% set recv_bytes = value['bytes_recv'] | string %}
{% set sent_packets = value['packets_sent'] | string %}
{% set recv_packets = value['packets_recv'] | string %}
{% set sent_errors = value['err_out'] | string %}
{% set recv_errors = value['err_in'] | string %}
{% set sent_dropped = value['drop_out'] | string %}
{% set recv_dropped = value['drop_in'] | string %}

{% set max_sent_len = [sent_bytes | length, sent_packets | length, sent_errors | length, sent_dropped | length] | max %}
{% set max_recv_len = [recv_bytes | length, recv_packets | length, recv_errors | length, recv_dropped | length] | max %}

| Parameter | Sent{{ ' ' * (max_sent_len - 4) }} | Received{{ ' ' * (max_recv_len - 8) }} |
|------------|{{ '-' * (max_sent_len + 2) }}|{{ '-' * (max_recv_len + 2) }}|
| Bytes | {{ "{:>{width}}".format(value['bytes_sent'], width=max_sent_len) }} | {{ "{:>{width}}".format(value['bytes_recv'], width=max_recv_len) }} |
| Packets | {{ "{:>{width}}".format(value['packets_sent'], width=max_sent_len) }} | {{ "{:>{width}}".format(value['packets_recv'], width=max_recv_len) }} |
| Errors | {{ "{:>{width}}".format(value['err_out'], width=max_sent_len) }} | {{ "{:>{width}}".format(value['err_in'], width=max_recv_len) }} |
| Dropped | {{ "{:>{width}}".format(value['drop_out'], width=max_sent_len) }} | {{ "{:>{width}}".format(value['drop_in'], width=max_recv_len) }} |
{% endfor %}
</pre>

{{ globe_showing_europe_africa }} Bytes unite us! {{ hugging_face }}
2 changes: 1 addition & 1 deletion pytmbot/templates/base_templates/b_plugins.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Here, you can explore various plugins that enhance the functionality of the bot. Please choose a plugin from the list below to view its details and capabilities:

{% for plugin_name, plugin_description in plugins.items() %}- **{{ plugin_name }}**: {{ plugin_description }}
{% for plugin_name, plugin_description in plugins.items() %}- *{{ plugin_name }}*: {{ plugin_description }}
{% endfor %}

Select a plugin to learn more about what it can do and how you can utilize it for your needs. If you need assistance, just let me know!
48 changes: 26 additions & 22 deletions pytmbot/templates/base_templates/b_quick_view.jinja2
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
{# templates/b_quick_view.jinja2 #}
🖥️ *System Quick View*
📊 *System Status Overview*

```bash
{% if context.system %}
🖥️
├─ ⏱️ Uptime: {{ "{:>10}".format(context.system.uptime if context.system.uptime else 'N/A') }}
├─ 📊 Load Average:
│ ├─ 1 min: {{ "{:>10.2f}".format(context.system.load_average[0] if context.system.load_average and context.system.load_average[0] is defined else 'N/A') }}
│ ├─ 5 min: {{ "{:>10.2f}".format(context.system.load_average[1] if context.system.load_average and context.system.load_average[1] is defined else 'N/A') }}
│ └─ 15 min: {{ "{:>10.2f}".format(context.system.load_average[2] if context.system.load_average and context.system.load_average[2] is defined else 'N/A') }}
├─ 🧠 Memory:
│ ├─ Used: {{ "{:>10}".format(context.system.memory.used if context.system.memory and context.system.memory.used else 'N/A') }}
│ ├─ Free: {{ "{:>10}".format(context.system.memory.free if context.system.memory and context.system.memory.free else 'N/A') }}
│ └─ Usage: {{ "{:>10}".format((context.system.memory.percent | string + '%') if context.system.memory and context.system.memory.percent is not none else 'N/A') }}
├─ ⚡ CPU Usage:
│ └─ {{ "{:>10}".format((context.system.cpu.cpu_percent | string + '%') if context.system.cpu and context.system.cpu.cpu_percent is not none else 'N/A') }}
└─ ⚙️ Processes:
├─ Running: {{ "{:>10}".format(context.system.processes.running if context.system.processes and context.system.processes.running else 'N/A') }}
└─ Total: {{ "{:>10}".format(context.system.processes.total if context.system.processes and context.system.processes.total else 'N/A') }}
```bash
🖥️ System Resources
├─ ⏱️ Uptime
│ └─ {{ "{:>12}".format(context.system.uptime if context.system.uptime is not none else 'N/A') }}
├─ 📈 Load Average
│ ├─ 1 min: {{ "{:>8.2f}".format(context.system.load_average[0]) if context.system.load_average and context.system.load_average[0] is not none else '{:>8}'.format('N/A') }}
│ ├─ 5 min: {{ "{:>8.2f}".format(context.system.load_average[1]) if context.system.load_average and context.system.load_average[1] is not none else '{:>8}'.format('N/A') }}
│ └─ 15 min: {{ "{:>8.2f}".format(context.system.load_average[2]) if context.system.load_average and context.system.load_average[2] is not none else '{:>8}'.format('N/A') }}
├─ 🧠 Memory Usage
│ ├─ Used: {{ "{:>8}".format(context.system.memory.used) if context.system.memory and context.system.memory.used is not none else '{:>8}'.format('N/A') }} GB
│ ├─ Free: {{ "{:>8}".format(context.system.memory.free) if context.system.memory and context.system.memory.free is not none else '{:>8}'.format('N/A') }} GB
│ └─ Usage: {{ "{:>7}%".format(context.system.memory.percent) if context.system.memory and context.system.memory.percent is not none else '{:>8}'.format('N/A') }}
└─ ⚙️ Process Stats
├─ Running: {{ "{:>8}".format(context.system.processes.running if context.system.processes and context.system.processes.running is not none else 'N/A') }}
├─ Sleeping: {{ "{:>8}".format(context.system.processes.sleeping if context.system.processes and context.system.processes.sleeping is not none else 'N/A') }}
├─ Idle: {{ "{:>8}".format(context.system.processes.idle if context.system.processes and context.system.processes.idle is not none else 'N/A') }}
└─ Total: {{ "{:>8}".format(context.system.processes.total if context.system.processes and context.system.processes.total is not none else 'N/A') }}
{% else %}
⚠️ System data is not available.
⚠️ System monitoring data is currently unavailable
{% endif %}

{% if context.docker %}
🐳
└─ 🐳 Docker Status
├─ Containers: {{ "{:>10}".format(context.docker.containers_count if context.docker.containers_count else 'N/A') }}
└─ Images: {{ "{:>10}".format(context.docker.images_count if context.docker.images_count else 'N/A') }}
🐳 Docker Environment
├─ Active Containers: {{ "{:>8}".format(context.docker.containers_count if context.docker.containers_count is not none else 'N/A') }}
└─ Available Images: {{ "{:>8}".format(context.docker.images_count if context.docker.images_count is not none else 'N/A') }}
{% endif %}
```
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ psutil==6.1.0
pydantic==2.10.3
pydantic-settings==2.6.1
pygal==3.0.5
pyoutlineapi==0.1.3
pyotp==2.9.0
pyTelegramBotAPI==4.25.0
PyYAML==6.0.2
Expand Down

0 comments on commit e795f34

Please sign in to comment.