148 Commits
Author SHA1 Message Date
rich fe26d9e2ed update link at top 2026-07-02 13:06:24 +00:00
rich 831ee9cbae printstat now shows status for both printers, old printstat function preserved as octostat. updated info command and readme as well 2026-02-28 16:39:05 -05:00
rich 545958b474 changing default bot status flip to 7 seconds 2026-02-28 16:24:19 -05:00
rich 367ef5b7af reworking the bot status display when two print jobs are running 2026-02-28 16:01:54 -05:00
rich 2a156b3a3c terminating ffpmeg caputre in event of timeout reached 2026-02-27 16:37:51 -05:00
rich 8ac70c645b updating "3D Print" to OctoPi Print 2026-02-27 14:28:08 -05:00
rich 4bdf61a018 matrix bot will auto join upgraded rooms 2026-02-22 12:13:27 -05:00
rich cd6955a567 readme update 2026-02-21 18:59:14 -05:00
rich eb922b4271 formatting 2026-02-21 17:55:28 -05:00
rich f51025d5f7 prettifying 2026-02-21 17:50:07 -05:00
rich 1f06251ca4 cant send raw 2026-02-21 17:46:17 -05:00
rich 70ea6508e2 fix for printer images 2026-02-21 17:44:32 -05:00
rich e79abf7715 fixing crash after bambustat call in matrix 2026-02-21 17:40:23 -05:00
rich 945e2464f7 what a buggy mess 2026-02-21 17:34:49 -05:00
rich 93b6995554 verify sessions 2026-02-21 17:32:36 -05:00
rich b45f617c73 more fixes 2026-02-21 17:22:22 -05:00
rich d872725af0 change to direct login 2026-02-21 17:18:27 -05:00
rich c18c89ac41 update for e2e 2026-02-21 17:06:20 -05:00
rich 787b0a2fb1 reworking to support e2e rooms 2026-02-21 17:03:44 -05:00
rich 31270db12b debugging 2026-02-21 16:56:17 -05:00
rich a2e1a42fe6 more matrix debugging 2026-02-21 16:45:57 -05:00
rich 1572eabac5 more matrix debugging 2026-02-21 16:41:24 -05:00
rich baf4905beb adding debugging 2026-02-21 16:38:58 -05:00
rich 123aa22abf trying to fix matrix 2026-02-21 16:32:28 -05:00
rich c2490d2159 adding safe handling of sync error 2026-02-21 16:25:32 -05:00
rich 36b8eccb6c initial add of matrix compatibility 2026-02-21 15:15:10 -05:00
rich e104538b5f removing ds_store 2026-02-20 18:20:14 -05:00
rich 516ba09548 mor minor removals for cleanup 2026-02-20 18:19:34 -05:00
rich 6f984b3d4e adding .gitignore 2026-02-20 18:16:07 -05:00
rich bc4854e6f4 updating readme 2026-02-20 18:01:13 -05:00
rich 6362f2558e removing tls_verify option 2026-02-20 17:38:21 -05:00
rich a750628097 adding code to capture ffmpeg errors 2026-02-20 17:35:56 -05:00
rich ce31a2e5df reworking bambu image to get from rtsp stream 2026-02-20 17:27:37 -05:00
rich 570e9d14a6 added option to enable bambu camera retrieval 2026-02-20 16:44:19 -05:00
rich 23fe33e3ad added camera 2026-02-20 16:38:19 -05:00
rich 54c16d81dc fixing the fix for the unconfirmed bug 2026-02-20 16:29:56 -05:00
rich 04d7d5c37f working around unconfirmed bug 2026-02-20 16:27:33 -05:00
rich fbc3ceb3c4 update requirements 2026-02-20 16:23:30 -05:00
rich e1703ae326 adding requirements 2026-02-20 16:19:54 -05:00
rich 65a1fe413d inital commit for adding $bambustat 2026-02-20 16:15:03 -05:00
rich 451938772a more clean up 2026-02-20 15:57:01 -05:00
rich 591d44904e fixing up some issues 2026-02-20 15:48:53 -05:00
rich 84dda24e9d adding discord.py version to $info 2026-02-20 15:00:54 -05:00
rich ebb9865109 reworking 2026-02-20 14:52:12 -05:00
rich e6cf3c6984 fix hanging if octopi is unavailable 2026-02-20 14:47:09 -05:00
rich 01e102af17 clearing voice session before joining channel 2026-02-20 14:42:28 -05:00
rich 790c224dcc using await for 1 second delay 2026-02-20 14:36:51 -05:00
rich 14104b4f39 Discord API now requires INTENTS 2024-03-20 13:29:36 -04:00
rich 1184102860 Added livestream URL to printstat output 2023-02-16 20:13:19 +00:00
rich 4e3d735b1d forgot to replace output variable 2023-02-12 15:47:11 +00:00
rich b074306696 ugh, need ==, not = 2023-02-11 23:13:45 +00:00
rich 0d5fd6c0cf rework time remaining for status 2023-02-11 23:12:34 +00:00
rich 8647451b24 setting to 999 2023-02-11 23:07:41 +00:00
rich c89bfaeff1 retrying leading zero 2023-02-11 19:38:00 +00:00
rich 74f6e0a32c adding leading zero (hopefully) 2023-02-11 19:35:49 +00:00
rich be9173a7ff adding time left to logging output 2023-02-11 19:26:31 +00:00
rich 1666e8fbf9 changeup wording 2023-02-11 19:23:30 +00:00
rich b950886c2d adding time remaining to status 2023-02-11 19:22:10 +00:00
rich 9a627c8a83 remove unused library 2023-02-10 22:51:44 +00:00
rich 9f11775db8 Fix missing paren, add comment explaining need for unknowns 2023-02-10 22:42:44 +00:00
rich d994b9f8fe forgot the f in the f-string 2023-02-10 20:50:50 +00:00
rich a7e5b3bea2 meh, round to tenth place 2023-02-10 20:14:15 +00:00
rich ed2e00ac3c change rounding to whole number 2023-02-10 20:12:53 +00:00
rich 0fd568fd87 minor logging message changes 2023-02-10 20:07:42 +00:00
rich 2801e1559f commenting out few lines that are updating bot status when $printstat is called. No longer need to do this. 2023-02-10 19:56:17 +00:00
rich 3007aa56f5 add message if print job is present but at 100% complete 2023-02-10 19:19:43 +00:00
rich 669333e2c7 dont want to watch print job if it's already at 100% 2023-02-10 19:14:46 +00:00
rich bf88d3d7c1 change location of last_error assignment 2023-02-10 14:48:49 +00:00
rich 3751a29dfb updating logging output 2023-02-10 14:21:23 +00:00
rich 2aae88ed22 forgot await async 2023-02-10 14:19:18 +00:00
rich dc2ea9a7e3 fixing loop 2023-02-10 14:16:43 +00:00
rich 7285c4da85 Adding loop to autodetect 3D printer jobs 2023-02-10 14:09:51 +00:00
rich e0c34659a2 removing references to StatPing and MMR 2023-02-08 23:27:15 +00:00
rich 32bb958ac0 Remove all StatPing and MMR_Checker code 2023-02-08 23:22:36 +00:00
rich a80f62f8d4 fixing some minor bugs 2022-12-10 00:22:15 +00:00
rich a9efb888bd some cleanup and re-org of help command 2022-12-10 00:15:27 +00:00
rich 59fdac5803 added $nice 2022-05-14 00:33:09 +00:00
rich 64173df84d Adding We butter the bread with butter - N!CE 2022-05-14 00:30:00 +00:00
rich 5859bbdac8 updating emote 2022-03-25 01:50:52 +00:00
rich 5b6555b8da adding ascii emote 2022-03-25 01:48:48 +00:00
rich 0e287c369d Added $breee command 2022-03-25 01:36:00 +00:00
rich 98f7ced3bf Adding BREEEEEEEEEEEE 2022-03-25 01:33:06 +00:00
rich dce4303ca1 Merge branch 'testing' into 'dev'
Fixing some stuff & things

See merge request Bots/r0b3BOT!64
2021-04-27 22:36:37 +00:00
rich 1153d1919c fixing indents 2021-04-04 15:01:48 -04:00
rich 499d86459b Merge branch 'testing' of https://gitlab.rickelobe.com/Bots/r0b3BOT into testing 2021-04-04 14:54:55 -04:00
rich c053b58733 not properly handling non jason response 2021-04-04 14:54:38 -04:00
rich e018cfa05b Merge branch 'master' of https://gitlab.rickelobe.com/Bots/r0b3BOT into testing 2021-03-23 19:11:00 -04:00
rich 9f58177559 Merge branch 'dev' into 'master'
Bring in fix for displaying correct version number

See merge request Bots/r0b3BOT!63
2021-03-22 14:40:18 +00:00
rich 58e1781397 correctly fixing the version now (wish the documentation was better) 2021-03-22 00:10:35 +00:00
rich f08eb06db4 Fixing the version information displayed for the info command 2021-03-22 00:06:43 +00:00
rich fa38734869 Merge branch 'testing' into 'dev'
Merge MMR Checker into Dev

See merge request Bots/r0b3BOT!61
2021-03-21 23:29:08 +00:00
rich 66ed4fd4d1 Merge MMR Checker into Dev 2021-03-21 23:29:07 +00:00
rich c528e0f638 Added new feature 2021-03-21 17:19:27 +00:00
rich 41b1c73ff3 adding back bot.remove_command entry 2021-03-21 13:10:16 -04:00
rich b1d1a7b1cc Cleanup of code 2021-03-21 13:07:25 -04:00
rich 8bb132be24 Organizing 2021-03-21 12:44:49 -04:00
rich 15d0a01dcb typo 2021-03-21 12:37:56 -04:00
rich ad05b2f427 updating help command details 2021-03-21 12:37:20 -04:00
rich 2cbaef99c0 working on mmrstatus 2021-03-21 12:26:25 -04:00
rich a53cab8343 working on mmrstatus 2021-03-21 12:24:03 -04:00
rich e00da20870 Cleaning up output text 2021-03-21 12:17:00 -04:00
rich 45d8d5702c found typo 2021-03-21 12:11:24 -04:00
rich 86e7944837 editing output for clarity 2021-03-21 12:05:31 -04:00
rich e9a2165f78 found some issues 2021-03-21 11:41:45 -04:00
rich 9421b22cff was using wrong varibale... missed ong 2021-03-21 07:54:10 -04:00
rich 5767d2d606 was using wrong varibale 2021-03-21 07:53:06 -04:00
rich 3b5ecf4b6b more debug 2021-03-21 07:46:56 -04:00
rich d961698d40 typo 2021-03-21 07:45:15 -04:00
rich 37e9512d82 troubleshooting -list command 2021-03-21 07:44:27 -04:00
rich 5e1164d98c typo 2021-03-20 19:25:50 -04:00
rich 1e64e992dd let's try it this way 2021-03-20 19:25:05 -04:00
rich 667126c916 dunno 2021-03-20 19:18:31 -04:00
rich 5ada6cfb36 troubleshooting response check: welp, had that backwards 2021-03-20 19:13:08 -04:00
rich b6d5ce6836 troubleshooting response check: fixing syntax 2021-03-20 19:11:16 -04:00
rich 0077f1a80b troubleshooting response check 2021-03-20 19:09:34 -04:00
rich dfa82dbe96 correcting variable being used 2021-03-20 19:06:59 -04:00
rich ba014f4c98 fixing... 2021-03-20 19:05:27 -04:00
rich 6823161897 fixing... 2021-03-20 19:03:52 -04:00
rich fcb0051c87 fixing 2021-03-20 19:03:15 -04:00
rich 403aa9a362 check if handle was actually found 2021-03-20 19:00:42 -04:00
rich 8d91336b43 Added mmrstatus command 2021-03-20 18:31:41 -04:00
rich 25abfb2a59 updating info command 2021-03-20 18:23:30 -04:00
rich 3f9a976742 clarifying alert text 2021-03-20 17:17:49 -04:00
rich 8f41991a3d fixing assignment again... hopefully for the last time, again 2021-03-20 16:31:09 -04:00
rich 1785162cea fixing assignment again... hopefully for the last time 2021-03-20 16:30:15 -04:00
rich 0207424d32 fixing assignment again 2021-03-20 16:28:50 -04:00
rich ab7009e43f fixing assignment 2021-03-20 16:25:36 -04:00
rich 5c0e61d466 adding newlines 2021-03-20 12:51:43 -04:00
rich 2cabbbf6f1 more tweaks to output 2021-03-20 12:49:19 -04:00
rich 803e8d552d more tweaks to output 2021-03-20 12:48:19 -04:00
rich 0950092f6d more tweaks to output 2021-03-20 12:46:47 -04:00
rich f6e15d9c35 output formatting 2021-03-20 12:38:21 -04:00
rich 5b917e032f fixing minor typo 2021-03-20 12:16:36 -04:00
rich 7628f8d1ae setting variable to int 2021-03-20 12:14:52 -04:00
rich 1e496efbee added interval option for mmr checker, cleaned up some output 2021-03-20 12:11:30 -04:00
rich 0cf348570b tweaks 2021-03-20 11:39:17 -04:00
rich 55419dbafb correcting syntax error 2021-03-20 10:03:45 -04:00
rich cf3757ce11 added enable/disable check before starting mmr checker and statping monitor 2021-03-20 10:02:08 -04:00
rich 4cf45b2684 added enable/disable options for mmr checker and statping monitor 2021-03-20 10:01:34 -04:00
rich 544f7b5833 I think all of the necessary changes have been made to add the mmr checker... needs to test now? 2021-03-19 22:43:02 -04:00
rich fa2a34c951 adding mmr api variable 2021-03-19 22:24:04 -04:00
rich affbf366a1 adding base code for mmr_checker 2021-02-14 21:37:17 -05:00
rich 4056f60cd8 duplicated statping functions for mmr monitor 2021-01-20 21:55:42 -05:00
rich a7a36f123c Merge branch 'dev' of https://gitlab.rickelobe.com/Bots/r0b3BOT into mmr_checker 2021-01-20 21:27:43 -05:00
rich 6865041707 Added missing playtime value for rs command 2020-09-02 09:47:06 -04:00
rich 520758e2f2 Added Wiz Khalifa clip $big 2020-07-01 09:10:58 -04:00
rich cd74624747 added iran sound clip 2020-07-01 08:58:15 -04:00
rich ccb260c3f9 Merge branch 'master' into 'testing'
Make testing master again!

See merge request Bots/r0b3BOT!59
2020-04-15 15:27:09 -04:00
10 changed files with 1115 additions and 787 deletions

No files matched your search

Vendored
BIN
View File
Binary file not shown.
+4
View File
@@ -1 +1,5 @@
.DS_Store
.vscode/launch.json
__pycache__
bot_config.conf
.claude
-9
View File
@@ -1,9 +0,0 @@
stages:
- deploy
deploy:
stage: deploy
script: /var/lib/gitlab-runner/deploy_r0b3bot.sh
only:
- dev
- master
+74 -16
View File
@@ -1,28 +1,86 @@
*** This project lives @ https://gitlab.rickelobe.com/Bots/R0b3BOT ***
[![pipeline status](http://gitlab.rickelobe.com/Bots/r0b3BOT/badges/master/pipeline.svg)](http://gitlab.rickelobe.com/Bots/r0b3BOT/commits/master)
*** This project lives @ https://git.rickelobe.com/rich/R0b3BOT ***
# Description
This is R0b3's Discord Bot. It's creation was basically a challenge posed a coworker who said "Hey, you can write Discord Bots in Python... Make one to display your 3D printer status!". But as time went on, a few more features were added. Aside from being able to query and monitor your 3D printer, it can also fetch the current status of a service monitroed by your [StatPing](https://github.com/statping/statping) instance. In addition to just fetching the current status of a service, you can subscribe to receive alerts for any StatPing service state change. All subscriptions are persistent and will remain even after the bot is restarted.
This is R0b3's bot, originally built as a Discord bot to display 3D printer status. It now also runs as a Matrix bot, both operating simultaneously in the same process.
# Features
* Query & Monitor 3D Printer Status using `$printstat` command(Requires that your printer is connected to [Octoprint](https://octoprint.org/))<br>
* Query & Monitor OctoPrint 3D Printer Status using the `$octostat` command (Requires that your printer is connected to [Octoprint](https://octoprint.org/))<br>
![](images/Discord_Printstat_Command.png)
* Query serivces states on StatPing using the `$spstatus`
* Use `$spsub` to "Subscribe" to service change alerts for StatPing services. Subscribed alerts are persistent and are not lost on bot restart.<br>
![Example service alert](images/Service_alert.png)
* Use `$mmrsub` to "Subscribe" to a League of Legends handle's Ranked Average. As with the StatPing feature, the subscriptions are persistent.
* Play a selection of sound clips to voice channel members using the various commands (`$torololo`, `$oops`, `$promoted`, etc)
* Query & Monitor Bambu Lab Printer Status using the `$bambustat` command (Requires a Bambu Lab printer accessible on the local network via MQTT)
* Displays print state, progress percentage, time remaining, current layer, bed temp, nozzle temp, and chamber temp
* Optionally captures and attaches a camera snapshot from the printer's RTSPS stream (requires [ffmpeg](https://ffmpeg.org/) on the host)
* Updates the bot's Discord status to show live print progress; alternates between OctoPi and Bambu status every 30 seconds when both printers are running simultaneously
* Query both printers at once using the `$printstat` command
* Play a selection of sound clips to voice channel members using the various commands (`$trololo`, `$oops`, `$promoted`, etc) — Discord only
* **Matrix support** — the bot can connect to a self-hosted Matrix homeserver (Synapse/Dendrite) and respond to the same text commands in E2E-encrypted rooms
# Commands
![Screenshot of $help](images/command_list.png)
All text commands are available on both Discord and Matrix. Sound/voice commands are Discord-only.
# Requirements
1. discord.py version 1.2.4 or greater<br>
<code> pip install discord.py </code>
Install all Python dependencies using the provided `requirements.txt`:
```
pip install -r requirements.txt
```
Dependencies:
- `discord.py[voice]` >= 2.6.4 — Discord bot framework (voice support included)
- `requests` >= 2.32.3 — HTTP client for HomeAssistant REST API calls
- `bambu-connect` >= 0.3.1 — Bambu Lab printer integration via local MQTT
- `paho-mqtt` >= 2.0 — MQTT client library (required by bambu-connect)
- `matrix-nio[e2e]` >= 0.21 — Matrix bot client with E2E encryption support (optional, only needed if using Matrix)
**Optional: Camera snapshot support**
To enable camera snapshots with `$bambustat`, [ffmpeg](https://ffmpeg.org/) must be installed on the host running the bot. Set `bambu_camera_enable = true` in `bot_config.conf` once ffmpeg is available.
**Optional: Matrix E2E encryption**
Matrix support with E2E encryption requires the `libolm` system library:
```
apt-get install libolm3 # Debian/Ubuntu
```
# Configuration
1. Create a Discord Bot via Developer tools<br>
2. Enter configuration parameters in bot_config.conf.example<br>
3. Enter OctoPrint config parameters in octoapi.conf.example<br>
4. Rename *.example files as *.conf and setup your config<br>
1. Create a Discord Bot via the [Discord Developer Portal](https://discord.com/developers/applications)
2. Copy `bot_config.conf.example` to `bot_config.conf` and fill in your values (see below)
3. Rename `octoapi.conf.example` to `octoapi.conf` and configure OctoPrint settings (if using OctoPrint)
## bot_config.conf Keys
### [bot-config]
| Key | Description |
|-----|-------------|
| `discord_auth_token` | Bot token from the Discord Developer Console |
| `bot_command_prefix` | Command prefix (e.g. `$`, `!`, `/`) |
| `hass_url` | URL to your Home Assistant instance |
| `hass_token` | Long-lived access token for Home Assistant REST API |
| `hass_light` | Entity ID of the light at your printer |
| `octoprint_ip_address` | IP address of your OctoPrint/OctoPi host |
| `bambu_ip_address` | IP address of your Bambu Lab printer on the local network |
| `bambu_access_code` | Access code shown on the printer screen (Settings > WLAN) |
| `bambu_serial_number` | Serial number of your Bambu Lab printer |
| `bambu_camera_enable` | Set to `true` to capture camera snapshots with `$bambustat` (requires ffmpeg) |
| `statping_enable` | Set to `true` to enable StatPing service status integration |
| `statping_url` | URL of your StatPing instance |
| `statping_api_key` | API key for StatPing |
| `mmr_checker_enable` | Set to `true` to enable MMR checker |
| `mmr_checker_interval` | Seconds between MMR checks |
| `mmr_api_url` | MMR API URL |
### [matrix-config] (optional)
Adding this section enables the Matrix bot. All five keys are required to activate it.
| Key | Description |
|-----|-------------|
| `matrix_homeserver` | Full URL of your Matrix homeserver (e.g. `https://matrix.example.org`) |
| `matrix_user_id` | Full Matrix user ID for the bot account (e.g. `@r0b3bot:example.org`) |
| `matrix_password` | Password for the bot account. Used on first run to register the device; credentials are then saved to `matrix_store_path` and reused on subsequent restarts |
| `matrix_room_ids` | Comma-separated list of room IDs to listen in (e.g. `!abc123:example.org,!def456:example.org`) — use room IDs, not aliases |
| `matrix_store_path` | Directory for the E2E crypto store (Olm sessions, device keys). Default: `./matrix_store/` |
+32 -1
View File
@@ -7,7 +7,12 @@
# hass_url - URL to your home assistant instance. This is used to turn on the light by your 3d printer
# hass_token - Long Lived Access Token used to authenticate with the REST API for your Home assistant instance
# hass_light - Entity name of the light you want to control
# octoprint_ip_address - IP Address of you OctoPrint (or OctoPi) host. Used to get 3D printer stats.
# octoprint_ip_address - IP Address of you OctoPrint (or OctoPi) host. Used to get 3D printer stats.
# bambu_ip_address - IP Address of your Bambu Lab printer on the local network
# bambu_access_code - Access code displayed on the printer's screen (Settings > WLAN)
# bambu_serial_number - Serial number of your Bambu Lab printer
# bambu_camera_enable - Set to true to capture a camera snapshot with $bambustat via ffmpeg RTSPS stream.
# Requires ffmpeg to be installed on the bot host.
# statping_url - Server hostname of the StatPing instance we will be querying w/ the REST API
# statping_api_key - API Key for Statping to query for service status
#
@@ -17,9 +22,35 @@ hass_url = <URL to HomeAssistant>
hass_token = <HomeAssistant Long Lived Access Token>
hass_light = <Entity_ID of the light @ your printer>
octoprint_ip_address = <OctoPrint IP Address>
bambu_ip_address = <Bambu Lab Printer IP Address>
bambu_access_code = <Bambu Lab Access Code>
bambu_serial_number = <Bambu Lab Serial Number>
bambu_camera_enable = false
statping_enable = <trues/false>
statping_url = <Statping URL>
statping_api_key = <Statping API Key>
mmr_checker_enable = <true/false>
mmr_checker_interval = <number of seconds between checks>
mmr_api_url = <MMR API URL>
[matrix-config]
#
# Optional Matrix bot support. All four keys must be present to enable the Matrix bot.
# The bot will join the specified rooms and respond to the same command prefix as Discord.
# Voice/sound commands are Discord-only and will return a friendly message on Matrix.
#
# matrix_homeserver - Full URL of your Matrix homeserver (e.g. https://matrix.example.org)
# matrix_user_id - Full Matrix user ID for the bot account (e.g. @r0b3bot:example.org)
# matrix_password - Password for the bot account. The bot logs in via matrix-nio on first
# start and saves the access token + device ID to matrix_store_path so
# the same Matrix device is reused across restarts (required for E2E).
# matrix_room_ids - Comma-separated list of Matrix room IDs the bot should listen in.
# Use room IDs (!abc123:example.org), not aliases — IDs are stable.
# matrix_store_path - Directory for the E2E crypto store (Olm sessions, device keys).
# Default: ./matrix_store/
#
matrix_homeserver = https://matrix.example.org
matrix_user_id = @r0b3bot:example.org
matrix_password = <Matrix account password>
matrix_room_ids = !abc123:example.org,!def456:example.org
matrix_store_path = ./matrix_store/
+589
View File
@@ -0,0 +1,589 @@
#!/usr/bin/python3
"""
Matrix bot support for r0b3BOT.
Runs alongside the Discord bot in the same asyncio event loop (via asyncio.gather).
Enabled by adding a [matrix-config] section to bot_config.conf.
Supported commands (same prefix as Discord):
greetings, cat, explain, holyshit, smudge, printstat, bambustat, info, help, last_error
Voice/sound commands respond with a friendly Discord-only message.
Discord embeds are rendered as formatted HTML (org.matrix.custom.html).
"""
import asyncio
import io
import json
import os
import random
import sys
import time
import urllib.request
import octoapi
import requests
from nio import AsyncClient, AsyncClientConfig, JoinError, LoginError, MatrixRoom, MegolmEvent, RoomMessage, RoomMessageText, RoomUpgradeEvent, SyncError, UploadResponse
class MatrixBot:
def __init__(
self,
homeserver,
user_id,
password,
command_prefix,
room_ids,
get_bambu_status,
get_last_error,
hass_url,
hass_token,
hass_light,
octoprint_ip,
bambu_ip,
bambu_access_code,
bambu_camera_enable,
capture_bambu_frame=None,
store_path="./matrix_store/",
):
# Create the crypto store directory if it doesn't exist.
# matrix-nio[e2e] uses this to persist Olm/Megolm sessions and device keys
# across restarts so the bot can decrypt messages in E2E-encrypted rooms.
os.makedirs(store_path, exist_ok=True)
nio_config = AsyncClientConfig(store_sync_tokens=True)
self.client = AsyncClient(homeserver, user_id, store_path=store_path, config=nio_config)
self.prefix = command_prefix
self.room_ids = set(room_ids)
self.password = password
# Credentials file — persists access_token + device_id across restarts so we
# reuse the same Matrix device (and its Olm keys) rather than registering a new
# one on every bot startup.
self.credentials_file = os.path.join(store_path, "r0b3bot_credentials.json")
# Shared state — lambdas that read from r0b3bot.py module-level globals
self._get_bambu_status = get_bambu_status
self._get_last_error = get_last_error
# Configuration
self.hass_url = hass_url
self.hass_token = hass_token
self.hass_light = hass_light
self.octoprint_ip = octoprint_ip
self.bambu_ip = bambu_ip
self.bambu_access_code = bambu_access_code
self.bambu_camera_enable = bambu_camera_enable
self._capture_bambu_frame = capture_bambu_frame
self._start_time = time.time()
async def _login(self):
"""Authenticate with the homeserver.
Tries to restore a previously saved session first (same device_id, same Olm
keys). Falls back to a fresh password login if no credentials are saved or if
the saved token has expired. On a fresh login the credentials are persisted to
disk so the same device is reused on subsequent restarts — this is essential for
E2E encryption: the homeserver and other clients must be able to establish a
stable Olm session with a consistent device.
"""
if os.path.exists(self.credentials_file):
try:
with open(self.credentials_file) as f:
creds = json.load(f)
self.client.access_token = creds["access_token"]
self.client.user_id = creds["user_id"]
self.client.device_id = creds["device_id"]
self.client.load_store()
print(f">> [Matrix] Restored session: {creds['user_id']} / device {creds['device_id']}")
return True
except Exception as e:
print(f" ! [Matrix] Could not restore session ({e}), doing fresh login")
# Remove the stale credentials so we don't retry a broken session
try:
os.remove(self.credentials_file)
except OSError:
pass
# Fresh password login — matrix-nio registers a new device and uploads Olm keys
resp = await self.client.login(self.password, device_name="r0b3bot")
if isinstance(resp, LoginError):
print(f" !! [Matrix] Login failed: {resp.message}")
print(f" !! [Matrix] Check matrix_password in bot_config.conf")
return False
print(f">> [Matrix] Logged in as {self.client.user_id} / device {self.client.device_id}")
self.client.load_store()
# Persist credentials for next restart
with open(self.credentials_file, "w") as f:
json.dump({
"access_token": self.client.access_token,
"user_id": self.client.user_id,
"device_id": self.client.device_id,
}, f, indent=2)
print(f">> [Matrix] Credentials saved to {self.credentials_file}")
return True
async def start(self):
print(">> [Matrix] Starting Matrix bot client")
if not await self._login():
print(" !! [Matrix] Matrix bot will NOT start.")
return
# Upload Olm one-time keys if this is the first run with a fresh Olm account.
# On subsequent restarts with a restored session this is a no-op.
if self.client.should_upload_keys:
print(">> [Matrix] Uploading Olm keys to homeserver")
await self.client.keys_upload()
# Initial sync with no timeout to consume backlog before registering callbacks,
# so we don't replay old messages on startup.
try:
resp = await self.client.sync(timeout=0)
if isinstance(resp, SyncError):
print(f" ! [Matrix] Initial sync error: {resp.message}")
else:
print(f">> [Matrix] Initial sync OK, next_batch={self.client.next_batch!r}")
except Exception as e:
print(f" ! [Matrix] Initial sync exception: {e}")
# Join all configured rooms. The bot account must be a member of a room
# to receive its events in the sync stream — having the room ID in config
# alone is not sufficient.
for room_id in self.room_ids:
resp = await self.client.join(room_id)
if isinstance(resp, JoinError):
print(f" ! [Matrix] Failed to join {room_id}: {resp.message}")
else:
print(f">> [Matrix] Joined (or already in) room {room_id}")
self.client.add_event_callback(self._on_message, RoomMessageText)
self.client.add_event_callback(self._on_any_message, RoomMessage)
self.client.add_event_callback(self._on_encrypted, MegolmEvent)
self.client.add_event_callback(self._on_room_upgrade, RoomUpgradeEvent)
print(">> [Matrix] Listening for commands")
# Use a short poll timeout (5 s) to stay well under any reverse-proxy
# idle timeout. A 30 s long-poll through nginx/caddy will often get a
# 504 which matrix-nio can't parse, causing the "next_batch required"
# loop and silencing all callbacks. 5 s is safe for all common setups.
await self.client.sync_forever(timeout=5000)
# -------------------------------------------------------------------------
# Event handler
# -------------------------------------------------------------------------
async def _on_any_message(self, room: MatrixRoom, event: RoomMessage):
"""DEBUG — fires for any m.room.message msgtype, not just m.text."""
print(f" [Matrix DEBUG RoomMessage] type={type(event).__name__} from {event.sender} in {room.room_id!r}")
async def _on_encrypted(self, room: MatrixRoom, event: MegolmEvent):
"""Fires for encrypted messages the bot can't yet decrypt (missing session key).
Normal on first run — the sender's client needs to establish an Olm session with
the bot's device and share the room key. Sending another message from Element
triggers this automatically. We also send a key request to speed it up."""
print(f" ! [Matrix] Could not decrypt message from {event.sender} in {room.room_id!r} "
f"(session {event.session_id!r} not yet received — send another message to trigger key sharing)")
try:
await self.client.request_room_key(event)
except Exception as e:
print(f" ! [Matrix] Key request failed: {e}")
async def _on_room_upgrade(self, room: MatrixRoom, event: RoomUpgradeEvent):
"""Handle a room upgrade (tombstone). Join the replacement room and swap
the room ID in the active set so commands keep working without a restart.
The old room ID is left in bot_config.conf — update it to the new one."""
new_room_id = event.replacement_room
print(f">> [Matrix] Room {room.room_id} upgraded → {new_room_id}, joining replacement")
resp = await self.client.join(new_room_id)
if isinstance(resp, JoinError):
print(f" ! [Matrix] Failed to join upgraded room {new_room_id}: {resp.message}")
return
self.room_ids.discard(room.room_id)
self.room_ids.add(new_room_id)
print(f">> [Matrix] Now listening in {new_room_id}")
print(f" ! [Matrix] Update matrix_room_ids in bot_config.conf: replace {room.room_id} with {new_room_id}")
async def _on_message(self, room: MatrixRoom, event: RoomMessageText):
# DEBUG — remove once commands are confirmed working
print(f" [Matrix DEBUG] event from {event.sender} in {room.room_id!r} body={event.body!r}")
print(f" [Matrix DEBUG] configured room_ids={self.room_ids}")
# Ignore own messages
if event.sender == self.client.user_id:
print(" [Matrix DEBUG] ignored: own message")
return
# Only respond in configured rooms
if room.room_id not in self.room_ids:
print(f" [Matrix DEBUG] ignored: room_id not in configured list")
return
# Only respond to messages that start with the command prefix
if not event.body.startswith(self.prefix):
print(f" [Matrix DEBUG] ignored: no command prefix {self.prefix!r}")
return
body = event.body[len(self.prefix):]
parts = body.split()
if not parts:
return
command = parts[0].lower()
print(f">> [Matrix] {event.sender} in {room.room_id} called {self.prefix}{command}")
await self._dispatch(room.room_id, command)
# -------------------------------------------------------------------------
# Command dispatcher
# -------------------------------------------------------------------------
_SOUND_COMMANDS = {
"aww", "bitch", "big", "boom", "breee", "cowbell", "eia", "heavy",
"iran", "leeroy", "nice", "oops", "promoted", "rs", "trololo",
"wow", "yaw",
}
async def _dispatch(self, room_id, command):
handlers = {
"greetings": self._cmd_greetings,
"cat": self._cmd_cat,
"explain": self._cmd_explain,
"holyshit": self._cmd_holyshit,
"smudge": self._cmd_smudge,
"printstat": self._cmd_printstat,
"bambustat": self._cmd_bambustat,
"info": self._cmd_info,
"help": self._cmd_help,
"last_error": self._cmd_last_error,
}
if command in handlers:
await handlers[command](room_id)
elif command in self._SOUND_COMMANDS:
await self._send_text(
room_id,
"Sound commands are only available on Discord (voice channels)."
)
# -------------------------------------------------------------------------
# Helpers
# -------------------------------------------------------------------------
async def _share_session(self, room_id):
"""Share the Megolm outbound group session with all current room members.
Must be called before every room_send() in encrypted rooms. This establishes
Olm sessions with each member's devices (claiming one-time keys as needed) and
sends them the Megolm session key so they can decrypt our messages.
ignore_unverified_devices=True lets the bot still send even when some devices
have unverifiable keys (e.g. stale bot devices with mismatched Olm keys).
"""
try:
await self.client.share_group_session(room_id, ignore_unverified_devices=True)
except Exception as e:
print(f" ! [Matrix] share_group_session for {room_id}: {e}")
async def _send_text(self, room_id, text, html=None):
await self._share_session(room_id)
content = {"msgtype": "m.text", "body": text}
if html:
content["format"] = "org.matrix.custom.html"
content["formatted_body"] = html
await self.client.room_send(room_id, "m.room.message", content)
async def _send_image(self, room_id, file_path):
await self._share_session(room_id)
with open(file_path, "rb") as f:
data = f.read()
# Encrypted rooms require the attachment itself to be encrypted before upload.
# matrix-nio handles this via encrypt=True on upload(), which returns the key
# info needed to build the m.image "file" field so clients can decrypt it.
room = self.client.rooms.get(room_id)
encrypt = room is not None and room.encrypted
resp, keys = await self.client.upload(
io.BytesIO(data),
content_type="image/jpeg",
filename=os.path.basename(file_path),
encrypt=encrypt,
)
if not isinstance(resp, UploadResponse):
print(f" ! [Matrix] Image upload failed: {resp}")
return
if encrypt and keys:
content = {
"msgtype": "m.image",
"body": os.path.basename(file_path),
"file": {"url": resp.content_uri, **keys},
}
else:
content = {
"msgtype": "m.image",
"url": resp.content_uri,
"body": os.path.basename(file_path),
"info": {"mimetype": "image/jpeg"},
}
await self.client.room_send(room_id, "m.room.message", content)
def _format_html(self, title, description, fields):
"""Render a status block as a heading + two-column table."""
rows = "".join(
f"<tr><td><strong>{name}</strong></td><td>{value}</td></tr>"
for name, value in fields
)
desc_html = f"<p>{description}</p>" if description else ""
return f"<h4>{title}</h4>{desc_html}<table>{rows}</table>"
def _format_text(self, title, description, fields):
"""Plain-text fallback — pad label column for alignment."""
max_len = max((len(name) for name, _ in fields), default=0)
parts = [title]
if description:
parts.append(description)
for name, value in fields:
parts.append(f" {name:<{max_len}} {value}")
return "\n".join(parts)
# -------------------------------------------------------------------------
# Command implementations
# -------------------------------------------------------------------------
async def _cmd_greetings(self, room_id):
await self._send_text(room_id, "Hello there!")
async def _cmd_cat(self, room_id):
await self._send_text(room_id, "https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif")
async def _cmd_explain(self, room_id):
await self._send_text(room_id, "https://media.giphy.com/media/A8NNZlVuA1LoY/giphy.gif")
async def _cmd_holyshit(self, room_id):
await self._send_text(room_id, "https://media.giphy.com/media/QcGTswMKyBNgA/giphy.gif")
async def _cmd_smudge(self, room_id):
print(" - [Matrix] Uploading Smudge to Matrix room")
await self._send_image(room_id, "./images/smudge.png")
async def _cmd_last_error(self, room_id):
await self._send_text(room_id, f"Last error recorded: {self._get_last_error()}")
async def _cmd_info(self, room_id):
# Uptime
elapsed = time.time() - self._start_time
m, s = divmod(int(elapsed), 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
w, d = divmod(d, 7)
uptime = f"{w:02d}:{d:02d}:{h:02d}:{m:02d}:{s:02d}"
# Git version tag
try:
proc = await asyncio.create_subprocess_exec(
"git", "describe", "--tags",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=5)
bot_version = stdout.decode().strip() or "unknown"
except Exception:
bot_version = "unknown"
source_url = "https://gitlab.rickelobe.com/Bots/r0b3BOT"
fields = [
("Author", "R0b3"),
("Uptime [WW:DD:HH:MM:SS]", uptime),
("Version", bot_version),
("Python", sys.version.split()[0]),
("Source", f'<a href="{source_url}">{source_url}</a>'),
]
await self._send_text(
room_id,
self._format_text("r0b3BOT — Derpy Derp of a Bot", None, fields),
html=self._format_html("r0b3BOT — Derpy Derp of a Bot", None, fields),
)
async def _cmd_help(self, room_id):
p = self.prefix
commands = [
(f"{p}greetings", "Hello!"),
(f"{p}cat", "GIF"),
(f"{p}explain", "GIF"),
(f"{p}holyshit", "GIF"),
(f"{p}smudge", "Sends the Smudge image"),
(f"{p}printstat", "OctoPrint status + snapshot"),
(f"{p}bambustat", "Bambu Lab printer status + camera"),
(f"{p}info", "Bot info"),
(f"{p}last_error", "Last recorded error"),
]
rows = "".join(
f"<tr><td><code>{cmd}</code></td><td>{desc}</td></tr>"
for cmd, desc in commands
)
html = (
f"<h4>r0b3BOT Commands</h4>"
f"<table>{rows}</table>"
f"<p><em>Sound commands are Discord-only.</em></p>"
)
text_lines = [f" {cmd:<18} {desc}" for cmd, desc in commands]
text = "r0b3BOT Commands\n" + "\n".join(text_lines) + "\n (Sound commands are Discord-only)"
await self._send_text(room_id, text, html=html)
async def _cmd_printstat(self, room_id):
loop = asyncio.get_running_loop()
hass_headers = {
"Authorization": f"Bearer {self.hass_token}",
"content-type": "application/json",
}
hass_state_url = self.hass_url + "/api/states/" + self.hass_light
# Light control — same logic as the Discord version
turned_on_light = False
try:
resp = await loop.run_in_executor(
None, lambda: requests.get(hass_state_url, headers=hass_headers)
)
lights = resp.json()
if lights.get("state") == "off":
turned_on_light = True
await self._send_text(room_id, "Turning on a light, give me a moment...")
hass_on_url = self.hass_url + "/api/services/switch/turn_on"
payload = f'{{"entity_id": "{self.hass_light}"}}'
await loop.run_in_executor(
None, lambda: requests.post(hass_on_url, headers=hass_headers, data=payload)
)
await asyncio.sleep(3)
except Exception as e:
print(f" ! [Matrix] Hass light check failed: {e}")
await self._send_text(room_id, "Hmm, I can't tell if the light is on... oh well [Hass API error]")
# Capture webcam snapshot
file_name = str(random.randrange(1, 10000)) + ".jpg"
try:
print(" - [Matrix] Getting image from Webcam")
await loop.run_in_executor(
None,
lambda: urllib.request.urlretrieve(
f"http://{self.octoprint_ip}:8080/?action=snapshot", file_name
),
)
await self._send_image(room_id, file_name)
os.remove(file_name)
except Exception as e:
print(f" ! [Matrix] Webcam capture failed: {e}")
await self._send_text(room_id, f"Unable to capture snapshot: {e}")
# Turn the light back off if we turned it on
if turned_on_light:
try:
hass_off_url = self.hass_url + "/api/services/switch/turn_off"
payload = f'{{"entity_id": "{self.hass_light}"}}'
await loop.run_in_executor(
None, lambda: requests.post(hass_off_url, headers=hass_headers, data=payload)
)
except Exception as e:
print(f" ! [Matrix] Unable to turn off light: {e}")
# Fetch printer stats from OctoPrint
try:
operational = await loop.run_in_executor(None, octoapi.get_printer_dict)
except Exception:
operational = False
if operational:
try:
print_filename = await loop.run_in_executor(None, octoapi.get_printFileName)
except Exception:
print_filename = ""
try:
print_completion = round(
await loop.run_in_executor(None, octoapi.get_completion), 2
)
except Exception:
print_completion = "Unknown"
try:
print_seconds = await loop.run_in_executor(None, octoapi.get_printTime)
print_secondsleft = await loop.run_in_executor(None, octoapi.get_printTimeLeft)
print_hours = int(print_seconds / 3600)
print_min = int((print_seconds / 60) - (print_hours * 60))
print_hoursleft = int(print_secondsleft / 3600)
print_minleft = int((print_secondsleft / 60) - (print_hoursleft * 60))
time_elapsed = f"{print_hours}h {print_min}m"
time_remaining = f"{print_hoursleft}h {print_minleft}m"
except Exception:
time_elapsed = time_remaining = "Unknown"
printer_bed = f"{operational['temperature']['bed']['actual']}°C"
printer_hotend = f"{operational['temperature']['tool0']['actual']}°C"
fields = [
("Progress", f"{print_completion}%"),
("Elapsed", time_elapsed),
("Remaining", time_remaining),
("Bed Temp", printer_bed),
("Hotend", printer_hotend),
]
await self._send_text(
room_id,
self._format_text("R0b3's 3D Printer Status", f"Current Job: {print_filename}", fields),
html=self._format_html("R0b3's 3D Printer Status", f"Current Job: {print_filename}", fields),
)
else:
await self._send_text(room_id, "Printer is Offline")
async def _cmd_bambustat(self, room_id):
status = self._get_bambu_status()
if status is None:
await self._send_text(
room_id,
"Bambu printer status is not available yet. The printer may be offline or still connecting.",
)
return
gcode_state = status.gcode_state or "Unknown"
gcode_file = status.gcode_file or "Unknown"
mc_percent = status.mc_percent if status.mc_percent is not None else "Unknown"
remaining_mins = status.mc_remaining_time or 0
time_remaining = f"{remaining_mins // 60}h {remaining_mins % 60:02d}m"
nozzle_temp = (
f"{status.nozzle_temper:.1f}°C" if status.nozzle_temper is not None else "Unknown"
)
bed_temp = (
f"{status.bed_temper:.1f}°C" if status.bed_temper is not None else "Unknown"
)
chamber_temp = (
f"{status.chamber_temper:.1f}°C" if status.chamber_temper is not None else "Unknown"
)
layer_info = "Unknown"
if status.layer_num is not None and status.total_layer_num is not None:
layer_info = f"{status.layer_num} / {status.total_layer_num}"
fields = [
("State", gcode_state),
("Progress", f"{mc_percent}%"),
("Remaining", time_remaining),
("Layer", layer_info),
("Nozzle", nozzle_temp),
("Bed", bed_temp),
("Chamber", chamber_temp),
]
await self._send_text(
room_id,
self._format_text("Bambu Lab Printer Status", f"File: {gcode_file}", fields),
html=self._format_html("Bambu Lab Printer Status", f"File: {gcode_file}", fields),
)
# Optional camera snapshot via ffmpeg RTSPS
if self.bambu_camera_enable and self._capture_bambu_frame:
image_filename = f"bambu_{random.randrange(1, 10000)}.jpg"
try:
print(" - [Matrix] Capturing Bambu camera frame via RTSPS")
success = await self._capture_bambu_frame(image_filename)
if success:
await self._send_image(room_id, image_filename)
os.remove(image_filename)
else:
print(" ! [Matrix] ffmpeg exited with non-zero code, skipping image")
except asyncio.TimeoutError:
print(" ! [Matrix] ffmpeg timed out capturing Bambu camera frame")
except Exception as e:
print(f" ! [Matrix] Unable to capture Bambu camera frame: {e}")
+398 -761
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
# r0b3BOT Python dependencies
# Install with: pip install -r requirements.txt
# Discord bot framework — [voice] pulls in PyNaCl for voice channel encryption
discord.py[voice]>=2.6.4
# HTTP client — used for HomeAssistant REST API calls
requests>=2.32.3
# Bambu Lab printer integration via local MQTT
# bambu-connect 0.3.1 uses mqtt.CallbackAPIVersion.VERSION1, which requires paho-mqtt 2.x
bambu-connect>=0.3.1
paho-mqtt>=2.0
# Matrix bot support (optional — only needed if matrix-config section is present in bot_config.conf)
# [e2e] extra adds Olm/Megolm encryption support for encrypted rooms.
# Requires the libolm system library: apt-get install libolm3 (Debian/Ubuntu)
matrix-nio[e2e]>=0.21
Binary file not shown.
Binary file not shown.