Compare commits

...

966 Commits

Author SHA1 Message Date
SpudGunMan
6f16fc6afb docs 2025-10-27 22:30:43 -07:00
SpudGunMan
fd971d8cc5 Update README.md
ffs
2025-10-27 22:23:05 -07:00
SpudGunMan
96193a22e8 LLM docs 2025-10-27 22:22:06 -07:00
SpudGunMan
02b0cde1c8 Update llm.py 2025-10-27 22:00:52 -07:00
SpudGunMan
40f4de02d9 Update system.py 2025-10-27 21:59:57 -07:00
SpudGunMan
0b1d626f09 refactor 2025-10-27 21:52:59 -07:00
SpudGunMan
964883cae9 Update system.py 2025-10-27 21:52:02 -07:00
SpudGunMan
6ab1102d07 Update wiki.py 2025-10-27 21:30:00 -07:00
SpudGunMan
c8d8880806 Update wiki.py 2025-10-27 21:25:12 -07:00
Kelly
21c2f7df18 Merge pull request #236 from SpudGunMan/copilot/link-llm-to-wiki-module
Add RAG support to LLM module with Wikipedia/Kiwix and OpenWebUI integration
2025-10-27 20:45:58 -07:00
SpudGunMan
cb51cf921b Update llm.py 2025-10-27 20:43:22 -07:00
SpudGunMan
908e84e155 Update README.md 2025-10-27 20:32:14 -07:00
SpudGunMan
b9eaf7deb0 Update wiki.py 2025-10-27 20:32:09 -07:00
SpudGunMan
128ac456eb Update wiki.py 2025-10-27 20:15:22 -07:00
SpudGunMan
1269214264 Update llm.py 2025-10-27 20:15:15 -07:00
SpudGunMan
4daf087fa5 Update llm.py 2025-10-27 20:03:14 -07:00
SpudGunMan
9282c63206 Update llm.md 2025-10-27 20:00:50 -07:00
SpudGunMan
710342447f Update llm.py 2025-10-27 19:26:53 -07:00
SpudGunMan
8e2c3a43fb refactor2 2025-10-27 18:50:58 -07:00
SpudGunMan
8d82823ccc refactor1 2025-10-27 17:31:47 -07:00
SpudGunMan
27789d7508 patch 2025-10-27 17:23:23 -07:00
SpudGunMan
680ba98a1c bumping version
thanks dependabot
2025-10-27 04:38:47 -07:00
SpudGunMan
4d71a64971 Update mesh_bot.py 2025-10-26 22:17:01 -07:00
SpudGunMan
d608754b5e dedupe 2025-10-26 21:51:02 -07:00
copilot-swe-agent[bot]
70ab741746 Update README with RAG and OpenWebUI documentation
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-27 03:35:36 +00:00
copilot-swe-agent[bot]
b0cf5914bf Add RAG support with Wikipedia/Kiwix and OpenWebUI integration
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-27 03:32:42 +00:00
copilot-swe-agent[bot]
434fbc3eef Initial plan 2025-10-27 03:26:02 +00:00
SpudGunMan
1186801d7e Update globalalert.py 2025-10-26 20:06:01 -07:00
SpudGunMan
902d764ca0 Update custom_scheduler.py 2025-10-26 19:41:48 -07:00
SpudGunMan
00fd29e679 Update custom_scheduler.py 2025-10-26 19:40:42 -07:00
SpudGunMan
163920b399 Update custom_scheduler.py 2025-10-26 19:36:44 -07:00
SpudGunMan
850ee2d291 Update wiki.py 2025-10-26 13:52:06 -07:00
SpudGunMan
cefbe93178 Update bbstools.md 2025-10-26 12:13:24 -07:00
SpudGunMan
44b2837ba0 fix typo for link command 2025-10-26 12:11:03 -07:00
SpudGunMan
1aa6a7a41a Update dxspot.py 2025-10-26 11:53:39 -07:00
SpudGunMan
7abd1fd704 Update dxspot.py
ffs
2025-10-26 11:51:31 -07:00
SpudGunMan
d35832caa8 Update dxspot.py 2025-10-26 11:49:56 -07:00
SpudGunMan
b4b0f2c561 Update dxspot.py 2025-10-26 11:40:50 -07:00
SpudGunMan
1e8ff95769 Update dxspot.py 2025-10-26 11:37:31 -07:00
SpudGunMan
41093be614 Update bbstools.md 2025-10-26 11:28:55 -07:00
SpudGunMan
6fe874e192 Update bbstools.md 2025-10-26 11:28:12 -07:00
SpudGunMan
3fa5d96073 Update bbstools.md 2025-10-26 11:25:03 -07:00
SpudGunMan
242c1c8741 Update README.md 2025-10-26 11:13:51 -07:00
SpudGunMan
c679cee66c dox 2025-10-26 11:06:48 -07:00
SpudGunMan
ca896c0f35 enhance 2025-10-26 10:19:52 -07:00
SpudGunMan
e3cd727cc3 enhance
filters
2025-10-26 10:11:22 -07:00
SpudGunMan
ded8470677 Update dxspot.py 2025-10-26 09:56:29 -07:00
SpudGunMan
f0b63b8b20 Update simulator.py 2025-10-26 09:54:25 -07:00
SpudGunMan
8a9c7a1147 changes to dx spotter
by is now of and xota is now ota
2025-10-26 09:42:02 -07:00
SpudGunMan
2d0e6b54b3 Update update.sh 2025-10-26 09:29:44 -07:00
SpudGunMan
0745847d3a Update update.sh 2025-10-26 09:28:54 -07:00
SpudGunMan
6c49c5c87f Update update.sh
https://github.com/SpudGunMan/meshing-around/issues/234
2025-10-26 09:24:14 -07:00
SpudGunMan
719fa95c1c Update README.md
thanks for this its been fun to help make this project for the community
2025-10-26 09:09:04 -07:00
SpudGunMan
b642961d26 Update README.md 2025-10-26 08:57:57 -07:00
SpudGunMan
f59d97f6ad Update mesh_bot.py 2025-10-26 08:48:29 -07:00
SpudGunMan
92d5f01ce5 allow days x for wx 2025-10-26 08:40:03 -07:00
SpudGunMan
39e53eb599 Update mesh_bot.py 2025-10-26 08:37:57 -07:00
SpudGunMan
9f6165503e Update locationdata.py 2025-10-26 08:28:41 -07:00
SpudGunMan
ec27ab65da Update custom_scheduler.py 2025-10-26 07:35:59 -07:00
SpudGunMan
f34eefb75a Update custom_scheduler.py 2025-10-26 07:34:21 -07:00
SpudGunMan
ce2ccb1455 Update scheduler.py 2025-10-26 07:31:16 -07:00
SpudGunMan
da144a2b89 scheduler enhancment
this brings scheduler into the 19th century
2025-10-26 07:26:54 -07:00
SpudGunMan
bbdccb382a Update dxspot.py 2025-10-26 06:02:07 -07:00
SpudGunMan
95f75b8e0a ... 2025-10-26 05:57:55 -07:00
SpudGunMan
0bf4915cd5 Update update.sh
https://github.com/SpudGunMan/meshing-around/issues/234
2025-10-26 05:51:59 -07:00
SpudGunMan
f83793acc9 Update README.md 2025-10-26 05:43:10 -07:00
SpudGunMan
abb2fa6b61 Update README.md 2025-10-26 05:42:51 -07:00
SpudGunMan
6d90d6f207 dx command 2025-10-26 05:37:04 -07:00
SpudGunMan
9c9e9a02e6 Update globalalert.py 2025-10-25 21:01:47 -07:00
SpudGunMan
80fc795f35 enhance 2025-10-25 18:50:12 -07:00
SpudGunMan
166c49854f Update config.template 2025-10-25 18:37:44 -07:00
SpudGunMan
a685fc3a9b Update config.template 2025-10-25 18:37:22 -07:00
SpudGunMan
91da1a4c58 Update update.sh 2025-10-25 18:34:06 -07:00
SpudGunMan
9889fd0da8 logs 2025-10-25 18:29:45 -07:00
Kelly
bebd9352ea Merge pull request #231 from SpudGunMan/copilot/add-mesh-bot-timer
Add systemd timer for daily mesh_bot_w3.service execution at 4:20 AM
2025-10-25 17:30:15 -07:00
SpudGunMan
fd1cd2a44c patch 2025-10-25 17:28:16 -07:00
SpudGunMan
ac55a51c87 # messages
https://github.com/SpudGunMan/meshing-around/issues/233
2025-10-25 16:01:54 -07:00
SpudGunMan
86144cd888 Update scheduler.py 2025-10-25 13:12:55 -07:00
SpudGunMan
d7a37ce9f1 haha 2025-10-25 12:59:59 -07:00
SpudGunMan
da7035dfed Update joke.py 2025-10-25 12:28:01 -07:00
SpudGunMan
da500981a2 Update mesh_bot.py 2025-10-25 12:23:48 -07:00
SpudGunMan
b4dc2207a6 refactor scheduler 2025-10-25 12:22:02 -07:00
SpudGunMan
b69a187466 Update mesh_bot.py 2025-10-25 12:10:57 -07:00
SpudGunMan
66d143d68e fix 2025-10-25 11:37:45 -07:00
SpudGunMan
49f2dcff88 Update test_bot.py 2025-10-25 10:59:46 -07:00
SpudGunMan
2c3c3fed10 Update INSTALL.md 2025-10-25 08:45:07 -07:00
SpudGunMan
2872fb040e refactor 2025-10-25 08:35:16 -07:00
copilot-swe-agent[bot]
6097ff899c Add explicit Unit directive to mesh_bot_w3.timer
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-25 14:02:49 +00:00
copilot-swe-agent[bot]
aec75d598a Add systemd timer to run mesh_bot_w3.service daily at 4:20 am
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-25 13:59:45 +00:00
copilot-swe-agent[bot]
0640fdbbae Initial plan 2025-10-25 13:55:40 +00:00
SpudGunMan
8312f4e683 Update system.py 2025-10-24 23:07:14 -07:00
SpudGunMan
990ea4f4e4 leaderboard fix messages 2025-10-24 21:57:16 -07:00
SpudGunMan
9acf9df3bb fix messages win 2025-10-24 21:47:32 -07:00
SpudGunMan
37942e950e fixLeaderboardLoading 2025-10-24 21:45:29 -07:00
SpudGunMan
8a0e1cba7c Update bbstools.py 2025-10-24 21:25:58 -07:00
SpudGunMan
8d0a53ec3e Update system.py 2025-10-24 21:24:18 -07:00
SpudGunMan
2ea3917eba Alllllllllll the rssssss'ssss
srsly I hope this time
2025-10-24 21:20:16 -07:00
SpudGunMan
75410c98e3 sweep 2025-10-24 20:40:23 -07:00
SpudGunMan
10171a712e moar cleanup 🧹
tighter memory control
2025-10-24 20:32:30 -07:00
SpudGunMan
fa76a76203 BIG OLD PATCH 🍠
pz days ... haha. I hope this works.
fancy potato
2025-10-24 19:54:46 -07:00
SpudGunMan
e0e275a49c Revert "scheduler memory issue"
This reverts commit bf39c2f088.
2025-10-24 18:30:08 -07:00
SpudGunMan
bf39c2f088 scheduler memory issue 2025-10-24 18:19:35 -07:00
SpudGunMan
34d36057c1 ATOM FEEDS
oh yea its 2003
2025-10-24 18:05:08 -07:00
SpudGunMan
4e1d1de883 Update adding_more.md 2025-10-24 17:52:24 -07:00
SpudGunMan
97f103dfd7 Update test_bot.py 2025-10-24 17:46:15 -07:00
SpudGunMan
47089871b1 Update test_bot.py 2025-10-24 17:45:16 -07:00
SpudGunMan
cc7ef129f6 Update test_bot.py 2025-10-24 17:42:50 -07:00
SpudGunMan
0fa5d06a3a Update test_bot.py 2025-10-24 17:12:06 -07:00
SpudGunMan
7fc44ec06e Update README.md 2025-10-24 17:12:00 -07:00
SpudGunMan
184760096e game test unit
🧩
2025-10-24 17:01:43 -07:00
SpudGunMan
8868d10388 Update hangman.py 2025-10-24 16:53:43 -07:00
SpudGunMan
1ce2ecd75c Update README.md 2025-10-24 16:50:04 -07:00
SpudGunMan
69e1c21488 enhance hangman.json
example JSON: [\"apple\",\"banana\",\"cherry\"]
2025-10-24 16:46:57 -07:00
SpudGunMan
97a2ffce7b gamepackFix
clean up globals
2025-10-24 15:46:11 -07:00
SpudGunMan
4c0d3a597e Update test_bot.py 2025-10-24 14:58:32 -07:00
SpudGunMan
094f7e61a0 Update wiki.py
fixed
2025-10-24 13:22:36 -07:00
SpudGunMan
a54ecaa5a1 Update mesh_bot.py 2025-10-24 13:21:49 -07:00
SpudGunMan
bd12392d69 Update system.py
doh
2025-10-24 13:05:40 -07:00
SpudGunMan
882bcf3f4b wiki wiki 2025-10-24 13:02:13 -07:00
SpudGunMan
c0d0ca3743 Update compose.yaml 2025-10-24 12:59:29 -07:00
SpudGunMan
d74d848646 Update compose.yaml 2025-10-24 12:58:16 -07:00
SpudGunMan
2afb915b56 Update test_bot.py 2025-10-24 12:50:58 -07:00
SpudGunMan
d5e48bead1 Update compose.yaml 2025-10-24 12:46:27 -07:00
SpudGunMan
3c80848f61 refactor wikipedia
also removed that old package!!!
2025-10-24 12:45:24 -07:00
SpudGunMan
64345fe47a Update wiki.py 2025-10-24 12:30:18 -07:00
SpudGunMan
32f734d69b Update wiki.py 2025-10-24 12:27:30 -07:00
SpudGunMan
aa6de00c5b Update wiki.py 2025-10-24 12:26:24 -07:00
SpudGunMan
6df4ba5756 Update test_bot.py
risky stuff lower
2025-10-24 12:13:50 -07:00
SpudGunMan
a11a2780db Update bbstools.py 2025-10-24 11:55:39 -07:00
SpudGunMan
980414f872 Update test_bot.py 2025-10-24 11:23:04 -07:00
SpudGunMan
f26334d625 Update wiki.py 2025-10-24 11:22:52 -07:00
SpudGunMan
24546b28d6 Create test_bot.py 2025-10-24 10:33:19 -07:00
SpudGunMan
f33da848cd cleanup 2025-10-24 10:32:28 -07:00
SpudGunMan
57ce15de4e Update radio.py 2025-10-24 10:19:05 -07:00
SpudGunMan
b8886e0662 Update qrz.py 2025-10-24 10:16:41 -07:00
SpudGunMan
9a1e86f25e Update qrz.py 2025-10-24 10:13:33 -07:00
SpudGunMan
fa8021ab5a Update checklist.py 2025-10-24 10:06:11 -07:00
SpudGunMan
f3917f1c3d Update locationdata.py 2025-10-24 10:00:35 -07:00
SpudGunMan
c1443048fd Update llm.py 2025-10-24 09:39:57 -07:00
SpudGunMan
da430557f3 Update filemon.py 2025-10-24 09:36:07 -07:00
SpudGunMan
84152bda65 Update checklist.py 2025-10-24 09:35:53 -07:00
SpudGunMan
b6e80ae576 Update bbstools.py 2025-10-24 09:18:31 -07:00
SpudGunMan
18ac26864c better resolution for gametracker
thanks pdx
2025-10-24 08:24:05 -07:00
SpudGunMan
b661fbc750 Revert "fix init of trackers"
This reverts commit 3049d18663.
2025-10-24 08:20:36 -07:00
SpudGunMan
3049d18663 fix init of trackers
thanks @pdxlocations
2025-10-24 08:12:24 -07:00
SpudGunMan
126f81fbd3 Update README.md 2025-10-23 23:38:26 -07:00
SpudGunMan
337d43a7af Update README.md 2025-10-23 23:32:53 -07:00
SpudGunMan
8c3121d5d6 Update entrypoint.sh 2025-10-23 23:29:26 -07:00
SpudGunMan
1d577c9ec5 Update compose.yaml 2025-10-23 23:12:28 -07:00
SpudGunMan
3540b8f110 Update entrypoint.sh 2025-10-23 23:10:15 -07:00
SpudGunMan
3fdebf3bf9 Update entrypoint.sh 2025-10-23 23:07:54 -07:00
SpudGunMan
430279809e Update entrypoint.sh 2025-10-23 23:06:02 -07:00
SpudGunMan
7ba3a78718 Update entrypoint.sh 2025-10-23 23:04:25 -07:00
SpudGunMan
c329391450 Update entrypoint.sh 2025-10-23 23:03:55 -07:00
SpudGunMan
6bc3c3e980 Update entrypoint.sh 2025-10-23 23:00:36 -07:00
SpudGunMan
48788ceda8 Update entrypoint.sh 2025-10-23 22:57:50 -07:00
SpudGunMan
8f5bae3b05 Update README.md 2025-10-23 22:55:18 -07:00
SpudGunMan
17c693c2f7 Update entrypoint.sh 2025-10-23 22:55:16 -07:00
SpudGunMan
ff91356c2a Update compose.yaml 2025-10-23 22:45:54 -07:00
SpudGunMan
180d9f4728 Update compose.yaml 2025-10-23 22:43:27 -07:00
SpudGunMan
1202a076d1 Update compose.yaml 2025-10-23 22:42:55 -07:00
SpudGunMan
9b62d7f4d8 Update compose.yaml 2025-10-23 22:42:00 -07:00
SpudGunMan
9451d23c09 Update compose.yaml 2025-10-23 22:40:48 -07:00
SpudGunMan
dcdef40e89 Update Dockerfile 2025-10-23 22:28:25 -07:00
SpudGunMan
817dde42f2 Update Dockerfile 2025-10-23 22:23:39 -07:00
SpudGunMan
b384d2d5b1 Update entrypoint.sh 2025-10-23 22:18:56 -07:00
SpudGunMan
4db46f16f2 Update compose.yaml 2025-10-23 22:15:12 -07:00
SpudGunMan
5590391f7e Update compose.yaml
i get no security!
2025-10-23 22:11:22 -07:00
SpudGunMan
ccb505f37f confounded 2025-10-23 22:09:34 -07:00
SpudGunMan
d883927572 enhance 2025-10-23 21:57:50 -07:00
SpudGunMan
b0109be3b0 Update README.md 2025-10-23 21:52:13 -07:00
SpudGunMan
98af757d93 enhance 2025-10-23 21:50:54 -07:00
SpudGunMan
f8746ff348 Create null 2025-10-23 21:46:59 -07:00
SpudGunMan
32fbfba3e9 config 2025-10-23 21:45:23 -07:00
SpudGunMan
d2501bf353 Update compose.yaml 2025-10-23 21:38:19 -07:00
SpudGunMan
db9d7d9790 Update README.md 2025-10-23 21:34:56 -07:00
SpudGunMan
c6b5a1c708 docker
i never enjoy docker
2025-10-23 21:26:32 -07:00
SpudGunMan
a36f1580b3 Update entrypoint.sh 2025-10-23 21:24:59 -07:00
SpudGunMan
f051e95986 Update entrypoint.sh 2025-10-23 21:24:45 -07:00
SpudGunMan
bafcfad190 Update entrypoint.sh 2025-10-23 21:21:43 -07:00
SpudGunMan
8b2059c444 Update compose.yaml 2025-10-23 21:07:43 -07:00
SpudGunMan
fd4b5607d7 Update compose.yaml 2025-10-23 21:02:42 -07:00
SpudGunMan
df30ee9cc4 Update compose.yaml 2025-10-23 20:53:26 -07:00
SpudGunMan
c1135ecadf cleanup 2025-10-23 20:40:00 -07:00
SpudGunMan
899702eecc Update compose.yaml 2025-10-23 20:26:55 -07:00
SpudGunMan
d4604d8cbd Update compose.yaml 2025-10-23 20:23:03 -07:00
SpudGunMan
c674b0a404 Update scheduler.py 2025-10-23 20:18:42 -07:00
SpudGunMan
d59ddfd517 fix for Malice
sorry this was so painfull
2025-10-23 20:15:15 -07:00
SpudGunMan
f68c533488 errorLoggin 2025-10-23 20:08:42 -07:00
SpudGunMan
6e47d71028 Update Dockerfile 2025-10-23 20:00:02 -07:00
SpudGunMan
f9af9b756d Update compose.yaml
how did I miss this
2025-10-23 19:57:18 -07:00
SpudGunMan
c19d442190 Update compose.yaml 2025-10-23 19:53:01 -07:00
SpudGunMan
4c2d0cdebb Update compose.yaml 2025-10-23 19:49:01 -07:00
SpudGunMan
612dbf01d3 Update compose.yaml 2025-10-23 19:47:40 -07:00
SpudGunMan
28846b24a6 Update compose.yaml 2025-10-23 19:40:43 -07:00
SpudGunMan
cd398375a2 Update compose.yaml 2025-10-23 19:33:40 -07:00
SpudGunMan
01372a0f2c Update compose.yaml 2025-10-23 19:30:08 -07:00
SpudGunMan
8254ec5baf Update compose.yaml 2025-10-23 19:23:25 -07:00
SpudGunMan
549e12ffc1 Update Dockerfile 2025-10-23 18:50:47 -07:00
SpudGunMan
d940cdf534 Update Dockerfile 2025-10-23 15:57:34 -07:00
SpudGunMan
54837884a7 Update locationdata.py 2025-10-23 15:48:08 -07:00
Kelly
91501d42db Merge pull request #158 from pcs3rd/create-docker-image
Create docker image and push to packages on new release
2025-10-23 15:44:57 -07:00
SpudGunMan
e0bcc31204 Update README.md 2025-10-23 15:37:43 -07:00
SpudGunMan
1cb56aa1b7 set bbslink via config.ini 2025-10-23 15:32:10 -07:00
SpudGunMan
8cf2db3b49 Update custom_scheduler.py 2025-10-23 15:22:05 -07:00
SpudGunMan
755fc4fac3 Update joke.py 2025-10-23 14:51:14 -07:00
SpudGunMan
7c341ed0e7 cleanup 2025-10-23 14:50:18 -07:00
SpudGunMan
c87db75f2f cleanupPartOne
I hope I didnt break a lot of things!
2025-10-23 13:46:36 -07:00
SpudGunMan
13875b7cf8 Update pong_bot.py 2025-10-23 13:33:17 -07:00
SpudGunMan
fd4925ee92 Update mesh_bot.py 2025-10-23 13:18:31 -07:00
SpudGunMan
eccc48ff3f whats all this 2025-10-23 13:15:51 -07:00
SpudGunMan
3a6d464398 Update bbstools.md 2025-10-23 12:52:54 -07:00
SpudGunMan
6c7e8558b0 Update bbstools.md 2025-10-23 12:51:01 -07:00
SpudGunMan
74a744c77e Update wiki.py 2025-10-23 12:45:12 -07:00
SpudGunMan
5225998c92 Update rss.py 2025-10-23 12:43:33 -07:00
SpudGunMan
97a0ff3112 enhance 2025-10-23 12:41:37 -07:00
SpudGunMan
1250479219 Update README.md 2025-10-23 12:33:17 -07:00
SpudGunMan
f8bcc4f495 Update README.md 2025-10-23 12:26:34 -07:00
SpudGunMan
5d1608f366 Update README.md 2025-10-23 12:25:16 -07:00
SpudGunMan
a19dc93350 Update locationdata.py 2025-10-23 12:13:25 -07:00
SpudGunMan
30d4e487c9 Update locationdata.py 2025-10-23 12:12:54 -07:00
SpudGunMan
5bf1ade2b0 enhance 2025-10-23 12:10:45 -07:00
SpudGunMan
13cefc2002 Update locationdata.py 2025-10-23 12:08:00 -07:00
SpudGunMan
640bead32c Update locationdata.py 2025-10-23 12:06:45 -07:00
SpudGunMan
49d9b58627 Update mesh_bot.py 2025-10-23 12:02:55 -07:00
SpudGunMan
ad1a8aa1ce Update locationdata.py 2025-10-23 12:01:56 -07:00
SpudGunMan
55567815ef map
to csv
2025-10-23 11:57:55 -07:00
SpudGunMan
346fb38bbd heasder csv 2025-10-23 11:40:24 -07:00
SpudGunMan
104e70c01c Update README.md 2025-10-23 11:33:55 -07:00
SpudGunMan
2111bb46ae bbs doc 2025-10-23 10:27:28 -07:00
Kelly
459dad4c32 Merge branch 'main' into create-docker-image 2025-10-23 09:43:52 -07:00
SpudGunMan
d9febeef0f cleanupX2 2025-10-23 09:39:21 -07:00
SpudGunMan
f8a94fca71 cleanup
yikes this was messy
2025-10-23 09:21:48 -07:00
SpudGunMan
a30b3dc2d2 Update dependabot.yml
https://github.com/SpudGunMan/meshing-around/pull/228
2025-10-23 08:38:09 -07:00
Kelly
b45254795d Merge pull request #228 from SpudGunMan/dependabot/docker/python-3.14-slim
Bump python from 3.13-slim to 3.14-slim
2025-10-23 08:37:41 -07:00
SpudGunMan
4a209e0c17 Update greetings.yml 2025-10-23 08:30:14 -07:00
dependabot[bot]
1aecb42186 Bump python from 3.13-slim to 3.14-slim
Bumps python from 3.13-slim to 3.14-slim.

---
updated-dependencies:
- dependency-name: python
  dependency-version: 3.14-slim
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-23 15:29:14 +00:00
SpudGunMan
6513e9f177 Update dependabot.yml 2025-10-23 08:28:22 -07:00
SpudGunMan
dd14034f3c Update update.sh 2025-10-23 00:20:45 -07:00
SpudGunMan
8308c2f98c Update README.md 2025-10-22 23:44:02 -07:00
SpudGunMan
5050f1c5eb Update install.sh 2025-10-22 23:43:20 -07:00
SpudGunMan
553137d228 Update install.sh 2025-10-22 23:41:43 -07:00
SpudGunMan
d3e7a4d5e4 Update install.sh 2025-10-22 23:25:11 -07:00
SpudGunMan
2e26819c2f Update install.sh 2025-10-22 22:40:14 -07:00
SpudGunMan
f03b85cebe typoFix
https://github.com/SpudGunMan/meshing-around/issues/227
thanks @mesb1
2025-10-22 22:32:53 -07:00
SpudGunMan
99f25345e8 Update README.md 2025-10-22 22:19:54 -07:00
SpudGunMan
4952bb3ecc documentation 2025-10-22 22:12:22 -07:00
SpudGunMan
f79f714317 enhance 2025-10-22 22:00:53 -07:00
SpudGunMan
a6db9bc878 Update README.md 2025-10-22 21:41:56 -07:00
SpudGunMan
774f76ecf1 Update README.md 2025-10-22 21:33:25 -07:00
SpudGunMan
3038d72996 Update README.md 2025-10-22 21:29:42 -07:00
SpudGunMan
33245e8443 Update README.md 2025-10-22 21:23:08 -07:00
SpudGunMan
54fb30d048 Update README.md 2025-10-22 21:20:27 -07:00
SpudGunMan
86c86d2f97 Update README.md 2025-10-22 21:18:23 -07:00
SpudGunMan
bb46981a85 Update README.md 2025-10-22 21:17:24 -07:00
SpudGunMan
e32cdf803c Update scheduler.py 2025-10-22 21:09:21 -07:00
SpudGunMan
c6e8feefd7 Update scheduler.py 2025-10-22 21:08:55 -07:00
SpudGunMan
1f48e9a4aa Create INSTALL.md 2025-10-22 21:03:55 -07:00
SpudGunMan
571c9c521f documentation 2025-10-22 21:02:12 -07:00
SpudGunMan
52b88ce16b documentation 2025-10-22 20:53:55 -07:00
SpudGunMan
6f38bff473 Update README.md 2025-10-22 20:31:20 -07:00
SpudGunMan
2b964390f8 Update README.md 2025-10-22 20:30:46 -07:00
SpudGunMan
a305acc492 Update README.md 2025-10-22 20:22:42 -07:00
SpudGunMan
cf66556fe6 enhance
fix bingo play
2025-10-22 20:21:17 -07:00
SpudGunMan
76e9bd8677 Update system.py 2025-10-22 18:56:49 -07:00
SpudGunMan
c8c3c0f80b Update wodt.py 2025-10-22 18:54:14 -07:00
SpudGunMan
3a9330d831 Update wodt.py 2025-10-22 18:47:16 -07:00
SpudGunMan
8d3b0ce4bf Update system.py
ahh
2025-10-22 18:46:50 -07:00
SpudGunMan
bb0a22c69b Update system.py 2025-10-22 18:45:45 -07:00
SpudGunMan
df369c3d29 Update system.py 2025-10-22 18:40:19 -07:00
SpudGunMan
db1ca48f0a Update system.py 2025-10-22 18:37:22 -07:00
SpudGunMan
a38d0a6ed7 Update system.py 2025-10-22 18:32:49 -07:00
SpudGunMan
ac8d308f58 Update system.py 2025-10-22 18:30:05 -07:00
SpudGunMan
08b54d9009 Update README.md 2025-10-22 18:25:49 -07:00
SpudGunMan
9da6416433 wordOfTheDay Games
Simple word fun, bingo and customizable word of the day lists via JSON files. Slot Machine for Emoji 🎰 shout out to pee-wee
2025-10-22 18:06:25 -07:00
SpudGunMan
efcfb749dc Update settings.py 2025-10-22 16:44:42 -07:00
SpudGunMan
493d2792d6 Update config.template 2025-10-22 16:44:31 -07:00
SpudGunMan
aa68ce120e Update scheduler.py 2025-10-22 16:17:27 -07:00
SpudGunMan
e3a9a00c92 better custom_ handling
thanks @pdxlocations for the idea
2025-10-22 14:54:06 -07:00
SpudGunMan
f1feb1be0d Update mesh_bot.py 2025-10-22 12:53:30 -07:00
SpudGunMan
290695327d enhance Ping with ping @NodeShortID
you should be able to now ping @ and if its a node ID it will send a BBS mail with a joke in it

@mesb1 thanks for idea
https://github.com/SpudGunMan/meshing-around/issues/224
2025-10-22 12:31:25 -07:00
SpudGunMan
c3ea07fde5 enhance
https://github.com/SpudGunMan/meshing-around/issues/225

https://github.com/SpudGunMan/meshing-around/issues/196

https://github.com/SpudGunMan/meshing-around/issues/224
2025-10-22 11:48:04 -07:00
SpudGunMan
e551f1252a Update injectDM.py 2025-10-22 08:39:24 -07:00
Raymond Dean
57093d09ef Merge branch 'SpudGunMan:main' into create-docker-image 2025-10-22 09:43:27 -04:00
SpudGunMan
a8b2aefa28 Update locationdata.py 2025-10-21 22:31:57 -07:00
SpudGunMan
849565cacb Update joke.py 2025-10-21 21:40:20 -07:00
SpudGunMan
fdec3a6754 Update README.md 2025-10-21 20:56:47 -07:00
SpudGunMan
f3a97bc567 Update README.md 2025-10-21 20:45:40 -07:00
SpudGunMan
02625ad0f2 Update install.sh 2025-10-21 20:18:55 -07:00
SpudGunMan
b4ba4b0daf Update locationdata.py 2025-10-21 18:52:40 -07:00
SpudGunMan
fd7f8a94f5 Update locationdata.py 2025-10-21 18:47:29 -07:00
SpudGunMan
d252250edd last_alert_time 🚀
throttle sending alerts for the same node more than once every 30 minutes
2025-10-21 16:42:36 -07:00
SpudGunMan
d6410e0461 Update joke.py 2025-10-21 15:47:06 -07:00
SpudGunMan
050b4ab3ce Update joke.py 2025-10-21 15:46:48 -07:00
SpudGunMan
8ac1a1eed7 Update joke.py 2025-10-21 15:45:30 -07:00
SpudGunMan
370a417ce6 Update config.template 2025-10-21 15:10:13 -07:00
SpudGunMan
378b05df35 PingRefactor
anyone notice this?
2025-10-21 14:50:06 -07:00
SpudGunMan
d002c5ede8 remove LastHop 2025-10-21 14:26:43 -07:00
SpudGunMan
cd03cc56b4 🐇 2025-10-21 14:24:24 -07:00
SpudGunMan
d4fd484706 sentry_alert.sh
this enhances the sentry to optionally run a shell command you would create in the script/directory which will fire every time the alert fires. sentry_alert_near.sh and sentry_alert_far.sh are the needed files. it will error and remind you it cant find them.
2025-10-21 14:21:09 -07:00
SpudGunMan
82d519279e servicePackAttack
enhance for armbian builds
2025-10-21 13:34:38 -07:00
SpudGunMan
09302e8c91 ntp 2025-10-21 13:17:15 -07:00
SpudGunMan
91fc4605ec enhance 2025-10-21 12:57:10 -07:00
SpudGunMan
abc6c07ee3 Update locationdata.py 2025-10-21 12:52:34 -07:00
SpudGunMan
bbf8b04bd3 Update locationdata.py 2025-10-21 12:45:29 -07:00
SpudGunMan
5fd293c990 only seen with soft nodes
## FIXME needs better like a default interface setting or hash lookup
2025-10-21 12:33:13 -07:00
SpudGunMan
a9a65a6c6d refactor rxInt 2025-10-21 11:00:26 -07:00
SpudGunMan
34e95c86d6 log IP if there 2025-10-21 10:52:28 -07:00
Kelly
80891090c3 Merge pull request #222 from pdxlocations/allow-port-numbers
Missed a Spot to support hostname:port
thanks!
2025-10-21 10:49:00 -07:00
SpudGunMan
1b098fbf7b Update pong_bot.py 2025-10-21 10:47:42 -07:00
SpudGunMan
165d76cf8d add IP 2025-10-21 10:45:44 -07:00
Kelly
045c9d433b Merge pull request #223 from SpudGunMan/copilot/add-pylint-disable-comment 2025-10-21 10:28:51 -07:00
SpudGunMan
fbe5e008de Revert "Update joke.py"
This reverts commit 004adc7d9a.
2025-10-21 10:28:02 -07:00
Kelly
004adc7d9a Update joke.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-21 10:23:12 -07:00
copilot-swe-agent[bot]
9a2033452f Add Pylint disable comment above variable on line 58
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-21 17:08:51 +00:00
copilot-swe-agent[bot]
5638204f82 Initial plan 2025-10-21 17:05:27 +00:00
pdxlocations
e5c3b0cceb refactor 2025-10-21 09:33:01 -07:00
pdxlocations
18ac53b230 Refactor TCP interface handling to support hostname:poert 2025-10-21 09:17:54 -07:00
SpudGunMan
4aa65dad6a Update mesh_bot.py
https://github.com/SpudGunMan/meshing-around/issues/220
2025-10-21 09:03:00 -07:00
SpudGunMan
f65a7b7934 refactorMwx 2025-10-21 06:56:03 -07:00
SpudGunMan
886293087a Update greetings.yml 2025-10-20 23:10:25 -07:00
SpudGunMan
e05e6f3451 Update greetings.yml 2025-10-20 23:07:31 -07:00
SpudGunMan
4b5dd934e9 enhance 2025-10-20 23:07:03 -07:00
Kelly
008ddfb5a2 Merge pull request #221 from SpudGunMan/lab
DependaBot
2025-10-20 23:02:13 -07:00
SpudGunMan
e1330b9b9e DependaBot
DependaBot
2025-10-20 22:56:34 -07:00
SpudGunMan
7b43213094 Update README.md 2025-10-20 21:57:46 -07:00
SpudGunMan
b17c2b17ee Update system.py 2025-10-20 20:20:25 -07:00
SpudGunMan
b6505ee577 Update system.py 2025-10-20 20:19:43 -07:00
SpudGunMan
f7379b7ca5 Update system.py 2025-10-20 20:19:30 -07:00
SpudGunMan
ec9a1d88db Update system.py 2025-10-20 20:15:29 -07:00
SpudGunMan
a339570afe Update system.py 2025-10-20 20:10:08 -07:00
SpudGunMan
f5af9f419a Update system.py 2025-10-20 20:06:39 -07:00
SpudGunMan
ad5c1c90da Update system.py 2025-10-20 19:55:57 -07:00
SpudGunMan
eb1e0c82ea enhance Sentinel
# list of watched nodes numbers
sentryWatchList =
monitors for INSIDE or OUTSIDE the zone
2025-10-20 19:50:06 -07:00
SpudGunMan
8d2277bc59 Update SECURITY.md 2025-10-20 17:46:57 -07:00
Kelly
dc9908a72c Revise security support information and reporting process
Updated the security support table and reporting guidelines.
2025-10-20 17:08:31 -07:00
SpudGunMan
21123d2993 sysinfo from a DM
now lets you see the IP addresses of the bot
2025-10-20 16:33:58 -07:00
SpudGunMan
7dc3134d0b Update system.py 2025-10-20 16:20:27 -07:00
SpudGunMan
b125178492 Update survey.py 2025-10-20 16:16:49 -07:00
SpudGunMan
2ad9e84c33 Update pong_bot.py 2025-10-20 15:55:30 -07:00
SpudGunMan
63bd288caa fixMOTD
theMOTD is how did this happen
2025-10-20 15:40:32 -07:00
SpudGunMan
5c7d199831 surveyReport
run survey report to see return data
2025-10-20 15:34:09 -07:00
SpudGunMan
f56a39eeb6 refactor 2025-10-20 13:07:30 -07:00
SpudGunMan
ae5991ee39 moreTime
to spare
2025-10-20 13:03:33 -07:00
SpudGunMan
1324f83f17 enhance schedule
allow basic Joke and Weather messages with out extra config
# value can also be joke (everyXmin) or weather (hour) for special scheduled messages
# custom for module/scheduler.py custom schedule examples
2025-10-20 12:07:22 -07:00
SpudGunMan
08ae8c31a0 enhance:fix
I added some things to help any future aarg, sorry I broke it again I also
2025-10-20 11:45:49 -07:00
SpudGunMan
957e803951 cleanup 2025-10-20 11:35:26 -07:00
SpudGunMan
2de3441d67 enhance
with time stamp and also better CSV answers for review
2025-10-20 09:54:44 -07:00
SpudGunMan
2b420022f9 timeFix
will be make year 2000
2025-10-20 09:54:25 -07:00
SpudGunMan
d01f143adf Update system.py 2025-10-20 09:24:18 -07:00
SpudGunMan
5f5aeeadac Update system.py 2025-10-20 09:22:45 -07:00
SpudGunMan
d57826613c moved
to slurp repo
2025-10-20 09:19:18 -07:00
SpudGunMan
af09dc0cf9 improveUse 2025-10-19 22:43:51 -07:00
SpudGunMan
011bac41f2 lower 2025-10-19 22:32:06 -07:00
SpudGunMan
20467ea886 enhance 2025-10-19 22:30:40 -07:00
SpudGunMan
bbfd71f011 "IP-Network" 2025-10-19 22:27:40 -07:00
SpudGunMan
e1ff87a197 enhance Ping 2025-10-19 22:26:09 -07:00
SpudGunMan
a859f830bb coreFix
Enhance Packet hop and MQTT detection
2025-10-19 22:16:19 -07:00
SpudGunMan
d99698e7f3 Update blackjack.py 2025-10-19 20:25:36 -07:00
SpudGunMan
5ecc563e96 newChunker 2025-10-19 20:18:08 -07:00
SpudGunMan
eeeb43cacc Update lemonade.py 2025-10-19 20:12:28 -07:00
SpudGunMan
9fdcea56fc Update lemonade.py 2025-10-19 20:10:26 -07:00
SpudGunMan
24a33fe882 Update lemonade.py 2025-10-19 20:08:34 -07:00
SpudGunMan
5710cebf39 Update mmind.py 2025-10-19 20:04:05 -07:00
SpudGunMan
b66487863d Update mmind.py 2025-10-19 19:35:41 -07:00
SpudGunMan
b3c4d208b7 Update mmind.py 2025-10-19 19:29:34 -07:00
SpudGunMan
f41ff2d5f7 Update mmind.py 2025-10-19 19:21:48 -07:00
SpudGunMan
48366bc595 Update mmind.py 2025-10-19 19:15:31 -07:00
SpudGunMan
02dd64382d Update mesh_bot.py 2025-10-19 19:05:23 -07:00
SpudGunMan
731b48ad65 Update mesh_bot.py 2025-10-19 19:04:34 -07:00
SpudGunMan
69a7082669 Update README.md 2025-10-19 18:57:56 -07:00
SpudGunMan
fafa7d8a51 Update config.template 2025-10-19 18:57:27 -07:00
Kelly
6e69b5f014 Merge pull request #219 from pdxlocations/allow-port-numbers
Enhance TCP interface initialization to support host:port format
2025-10-19 18:54:54 -07:00
SpudGunMan
03895248cd fixing
sorry if you saw the crashing I had dinner
2025-10-19 18:31:51 -07:00
SpudGunMan
a79de8a325 cleanupBadCode 2025-10-19 17:16:53 -07:00
SpudGunMan
740b53f02f Update system.py 2025-10-19 16:25:35 -07:00
SpudGunMan
76e75551c6 Update videopoker.py 2025-10-19 16:15:49 -07:00
SpudGunMan
51752ae896 Update videopoker.py 2025-10-19 16:15:37 -07:00
SpudGunMan
d81e773c0c Update blackjack.py 2025-10-19 16:02:24 -07:00
SpudGunMan
1f1ed1ca70 Update blackjack.py 2025-10-19 16:01:04 -07:00
pdxlocations
df9f3806a3 Enhance TCP interface initialization to support host:port format 2025-10-19 16:00:45 -07:00
SpudGunMan
081ccd9e2e Update blackjack.py 2025-10-19 15:55:46 -07:00
SpudGunMan
d9a7dafe6e Update blackjack.py 2025-10-19 15:54:41 -07:00
SpudGunMan
921225965b Update blackjack.py 2025-10-19 15:52:20 -07:00
SpudGunMan
3659254785 refactor suggestion 2025-10-19 15:42:49 -07:00
SpudGunMan
7c502608f6 remove deps install 2025-10-19 14:51:51 -07:00
SpudGunMan
427c25f80b noHoldsHeld 2025-10-19 14:26:45 -07:00
SpudGunMan
c3f15390ea Update system.py 2025-10-19 14:08:21 -07:00
SpudGunMan
e1476a44c6 enhance 2025-10-19 13:46:58 -07:00
SpudGunMan
72070fef3e backup data 2025-10-19 13:43:57 -07:00
SpudGunMan
b63ea677f6 Update blackjack.py 2025-10-19 13:35:00 -07:00
SpudGunMan
f8389500b8 Update mesh_bot.py 2025-10-19 13:28:32 -07:00
SpudGunMan
b257625a45 cleanupBlackJack 2025-10-19 13:23:40 -07:00
SpudGunMan
a233d8c7b3 Update mesh_bot.py 2025-10-19 12:57:37 -07:00
SpudGunMan
11c9742ebe cleanup 2025-10-19 12:55:16 -07:00
SpudGunMan
5af28c3dc2 Update system.py
kidding
2025-10-19 12:55:08 -07:00
SpudGunMan
aebb9e3c20 cleanup 2025-10-19 12:48:19 -07:00
SpudGunMan
d5916f4ccc 🐞🧩
thanks meshguy
2025-10-19 12:22:09 -07:00
SpudGunMan
056159a3f3 Update mesh_bot.py 2025-10-19 09:21:25 -07:00
SpudGunMan
2f6049d94b bugfix survey game 2025-10-18 19:20:36 -07:00
SpudGunMan
a2d7f664ab Update udp.py 2025-10-18 17:29:21 -07:00
SpudGunMan
b26491b646 Update udp.py 2025-10-18 17:26:39 -07:00
SpudGunMan
22e97b0eec Update udp.py 2025-10-18 16:54:26 -07:00
SpudGunMan
f540866d08 Update locationdata.py 2025-10-18 15:18:18 -07:00
SpudGunMan
c9729c8214 Update locationdata.py 2025-10-18 15:17:34 -07:00
SpudGunMan
49901cbbee Update locationdata.py 2025-10-18 15:14:23 -07:00
SpudGunMan
2aa2b80935 Update locationdata.py 2025-10-18 15:08:40 -07:00
SpudGunMan
95695f4f58 Update locationdata.py 2025-10-18 15:02:33 -07:00
SpudGunMan
b641d2b5e8 ok finslly
this looks better
2025-10-18 14:54:45 -07:00
SpudGunMan
51d8faab12 enhance 2025-10-18 14:49:26 -07:00
SpudGunMan
7a1396b99d Update locationdata.py 2025-10-18 14:40:39 -07:00
SpudGunMan
819bbbcaf4 enhance 2025-10-18 14:39:06 -07:00
SpudGunMan
0eeda96670 Update locationdata.py 2025-10-18 14:36:44 -07:00
SpudGunMan
18cca4ffdd Update locationdata.py 2025-10-18 14:35:28 -07:00
SpudGunMan
d169fe2dff Update locationdata.py 2025-10-18 14:33:42 -07:00
SpudGunMan
1c732dfe17 Update install.sh 2025-10-18 12:47:17 -07:00
SpudGunMan
bdad3927e5 enhance 2025-10-18 10:07:09 -07:00
SpudGunMan
0e0d6416d9 enhance config merge data 2025-10-18 09:38:00 -07:00
SpudGunMan
0da780371a enhance 2025-10-18 09:10:47 -07:00
SpudGunMan
37bf30cbc0 enhance 2025-10-18 09:05:17 -07:00
SpudGunMan
817a8601dd Update system.py 2025-10-18 08:53:30 -07:00
SpudGunMan
47cca409be lab work 2025-10-18 08:52:32 -07:00
SpudGunMan
e08a82ec39 Update system.py 2025-10-18 08:42:48 -07:00
SpudGunMan
345541dfb5 Update system.py 2025-10-18 08:41:22 -07:00
SpudGunMan
6e89762f1d bbsCompression
not enabled yet
2025-10-18 08:39:43 -07:00
SpudGunMan
0fb26bc16a Update mesh_bot.py 2025-10-17 19:50:47 -07:00
SpudGunMan
f1ad5966af send_raw_bytes 2025-10-17 19:50:41 -07:00
SpudGunMan
ac57d4683f Update udp.py 2025-10-17 17:48:24 -07:00
SpudGunMan
eab099e5ee channelID 2025-10-17 17:42:07 -07:00
SpudGunMan
685bd3491d Update udp.py 2025-10-17 17:10:44 -07:00
SpudGunMan
b8d64f3a9e Update system.py 2025-10-17 13:31:47 -07:00
SpudGunMan
852d491030 Update meshview.ino 2025-10-16 18:57:17 -07:00
SpudGunMan
76565c5546 Update meshview.ino 2025-10-16 18:55:03 -07:00
SpudGunMan
af1ec1630e Update udp.py 2025-10-16 16:04:06 -07:00
SpudGunMan
0c2b36a206 refactor handle_messages
@mesb1 give this one a test

https://github.com/SpudGunMan/meshing-around/issues/213
2025-10-16 15:55:12 -07:00
SpudGunMan
c0934096f0 Update meshview.ino 2025-10-16 12:07:58 -07:00
SpudGunMan
819bfaba90 Update meshview.ino 2025-10-16 11:52:03 -07:00
SpudGunMan
8041a1296b tinkering
@martinbogo
2025-10-15 20:32:46 -07:00
SpudGunMan
10d93b4fd3 keyFactor 2025-10-15 20:17:44 -07:00
SpudGunMan
19dedef1e6 meshview.ino
I could use help with this I am stuck at the moment
2025-10-15 19:25:21 -07:00
SpudGunMan
d4af0c7e8b Update udp.py 2025-10-15 15:58:02 -07:00
SpudGunMan
8730f0fd38 Update udp.py 2025-10-15 15:57:40 -07:00
SpudGunMan
9cda8daf65 Update udp.py 2025-10-15 15:57:24 -07:00
SpudGunMan
a9223f1613 Create udp.py 2025-10-15 15:51:30 -07:00
SpudGunMan
04ca4c99b8 Update scheduler.py
sorry for that
2025-10-15 08:24:02 -07:00
SpudGunMan
3072520e63 Merge branch 'main' of https://github.com/SpudGunMan/meshing-around 2025-10-15 08:23:16 -07:00
SpudGunMan
bd6603766b Update scheduler.py 2025-10-15 08:23:14 -07:00
Kelly
075a23bd2b LowerBits
https://github.com/SpudGunMan/meshing-around/issues/213
2025-10-14 22:21:21 -07:00
SpudGunMan
a8e4f653ed Update radio.py 2025-10-14 21:19:00 -07:00
SpudGunMan
374a44f4a9 Update radio.py 2025-10-14 21:17:36 -07:00
SpudGunMan
3c8d2e646e Update radio.py 2025-10-14 16:32:01 -07:00
SpudGunMan
e5df983244 Update mesh_bot.py 2025-10-14 16:23:27 -07:00
SpudGunMan
fa5f9250c4 Update llm.py 2025-10-14 16:14:59 -07:00
SpudGunMan
3f7a831690 Update llm.py 2025-10-14 16:12:14 -07:00
SpudGunMan
89aaaddae9 Update llm.py 2025-10-14 16:02:40 -07:00
SpudGunMan
e1919616c2 refactoring 2025-10-14 15:55:59 -07:00
SpudGunMan
8b9e637006 Update README.md 2025-10-14 15:08:07 -07:00
SpudGunMan
0df3e32901 Update README.md 2025-10-14 15:07:18 -07:00
SpudGunMan
1c2fa174ea Hey Chirpy
- **Voice/Command Triggers**: The following keywords can be used in messages or via voice (VOX) to trigger bot functions:
  - `joke`: Tells a joke
  - `weather`: Returns local weather forecast
  - `moon`: Returns moonrise/set and phase info
  - `daylight`: Returns sunrise/sunset times
  - `river`: Returns NOAA river flow info
  - `tide`: Returns NOAA tide information
  - `satellite`: Returns satellite pass info
2025-10-14 15:05:39 -07:00
SpudGunMan
c97aefcef1 Update radio.py 2025-10-14 14:59:10 -07:00
SpudGunMan
dfb94c3993 voxUse 2025-10-14 14:56:45 -07:00
SpudGunMan
7d62f69f12 ... 2025-10-14 14:24:42 -07:00
SpudGunMan
cf896767fb Update mesh_bot.py 2025-10-14 13:41:31 -07:00
SpudGunMan
1eb4cf71ed Update mesh_bot.py 2025-10-14 13:40:27 -07:00
SpudGunMan
e959124eac voxEnhance 2025-10-14 13:38:26 -07:00
SpudGunMan
d787c72812 Update radio.py 2025-10-14 13:32:22 -07:00
SpudGunMan
9f0dd56d43 Update mesh_bot.py 2025-10-14 13:26:37 -07:00
SpudGunMan
aa71e6045a Update radio.py
forgot to save a good
2025-10-14 12:45:41 -07:00
SpudGunMan
a140ad83cd Update radio.py 2025-10-14 12:34:44 -07:00
SpudGunMan
93c2d731e8 Update radio.py 2025-10-14 12:33:18 -07:00
SpudGunMan
d8da553af9 Update radio.py 2025-10-14 12:32:21 -07:00
SpudGunMan
9d9f070908 enhance 2025-10-14 12:24:42 -07:00
SpudGunMan
0f2061af55 chirpy make my lunch 2025-10-14 12:24:29 -07:00
SpudGunMan
d8423584d4 Update radio.py 2025-10-14 12:19:13 -07:00
SpudGunMan
843320d268 Update radio.py 2025-10-14 12:18:11 -07:00
SpudGunMan
216128b15a Update radio.py 2025-10-14 12:07:45 -07:00
SpudGunMan
f8bc574753 Update radio.py 2025-10-14 11:35:32 -07:00
SpudGunMan
6193c5933f Update radio.py 2025-10-14 11:32:34 -07:00
SpudGunMan
b668965bda bufferHandler
tracking https://github.com/SpudGunMan/meshing-around/issues/213
2025-10-14 11:13:40 -07:00
SpudGunMan
ae039b5baf Update radio.py 2025-10-14 11:01:24 -07:00
SpudGunMan
824d43f16e Update radio.py 2025-10-14 10:57:39 -07:00
SpudGunMan
2de76e6c5e Update radio.py 2025-10-14 10:56:14 -07:00
SpudGunMan
afb02602fd Update radio.py 2025-10-14 10:53:44 -07:00
SpudGunMan
99528c2bcf Update system.py 2025-10-14 10:52:35 -07:00
SpudGunMan
b53f5821f3 Update system.py 2025-10-14 10:51:34 -07:00
SpudGunMan
93fc6547b8 Update system.py 2025-10-14 10:46:30 -07:00
SpudGunMan
9a7e321dff Update scheduler.py 2025-10-14 10:25:32 -07:00
SpudGunMan
39257f2d39 Update scheduler.py 2025-10-14 10:25:16 -07:00
SpudGunMan
8c5abecac3 refactor
or custom for module/scheduler.py
2025-10-14 10:09:33 -07:00
SpudGunMan
16dcc96037 consolidate time to wait 2025-10-14 09:38:38 -07:00
SpudGunMan
b1d32a7745 refactor MOTD 2025-10-14 09:22:41 -07:00
SpudGunMan
631a2f53ea major refactor to schedule
major thanks to @FJRPiolt
2025-10-14 08:44:59 -07:00
SpudGunMan
32903c97e3 enhance 2025-10-14 08:13:35 -07:00
SpudGunMan
6e61e8122d Update system.py
no its not
2025-10-14 08:07:00 -07:00
SpudGunMan
d109803f9d Update system.py 2025-10-14 07:21:05 -07:00
SpudGunMan
09ed4f57cf Update system.py
enhance high fly with block list blocks
2025-10-14 07:18:10 -07:00
SpudGunMan
acfb8078a9 Update system.py
to much log
2025-10-14 07:06:46 -07:00
SpudGunMan
84f9693833 Update system.py 2025-10-13 23:50:32 -07:00
SpudGunMan
50fdcf486d Update system.py 2025-10-13 23:21:50 -07:00
SpudGunMan
eab5afccc8 Update system.py
helps to hit save
2025-10-13 21:31:10 -07:00
SpudGunMan
ea9db47c2d refactor sysinfo local telemetry 2025-10-13 21:29:45 -07:00
SpudGunMan
cf3a9c5b43 Update filemon.py 2025-10-13 19:49:43 -07:00
SpudGunMan
adedaa092c Update mesh_bot.py
fixLocaStats and sysinfo
2025-10-13 19:49:24 -07:00
SpudGunMan
f204237a63 Update mesh_bot.py 2025-10-13 19:27:58 -07:00
SpudGunMan
057a400041 Update mesh_bot.py 2025-10-13 19:26:53 -07:00
SpudGunMan
4cdf68f074 fixLocaStats and sysinfo 2025-10-13 19:24:37 -07:00
SpudGunMan
003a11c557 fixReportingEngine
This data is used by the webReporting engine
2025-10-13 17:57:20 -07:00
SpudGunMan
8d309fa579 Update README.md 2025-10-13 17:42:35 -07:00
SpudGunMan
232f9c24db aaahhhrrg 2025-10-13 17:27:51 -07:00
SpudGunMan
39dccd149b Update mesh_bot.py 2025-10-13 17:26:45 -07:00
SpudGunMan
b921c73fa7 Update mesh_bot.py 2025-10-13 17:26:08 -07:00
SpudGunMan
f3ec1cbe93 enhance 2025-10-13 17:23:49 -07:00
SpudGunMan
a6bcfda0ac enhance 2025-10-13 17:20:56 -07:00
SpudGunMan
51cd2002af Update system.py 2025-10-13 17:13:37 -07:00
SpudGunMan
b40f41f41c bannode
bad node! this isnt saving to .ini
2025-10-13 17:12:27 -07:00
SpudGunMan
4c33b30f14 addMessageData
Co-Authored-By: Martin Bogomolni <martinbogo@igotu.com>
2025-10-13 15:22:29 -07:00
SpudGunMan
b7490afb99 Update llm.py 2025-10-13 15:03:42 -07:00
SpudGunMan
8b57ed727c Update mesh_bot.py 2025-10-13 13:50:07 -07:00
SpudGunMan
fd5d64b9fb 🫖
enhance
2025-10-13 13:14:32 -07:00
SpudGunMan
00af152c2c Update system.py
slowing this a bit
2025-10-13 12:28:41 -07:00
SpudGunMan
31f0abc8c8 requestPosition
alsoRequesting feedback if this works well? you will need to edit the file find the `reqLocationEnabled` and set True. save and test it out
2025-10-13 12:00:36 -07:00
SpudGunMan
6b7d795a31 Update README.md 2025-10-13 10:04:13 -07:00
SpudGunMan
1f093c4bc2 Update system.py 2025-10-13 10:02:22 -07:00
SpudGunMan
fe1c4a1ad0 Update locationdata.py 2025-10-13 10:02:20 -07:00
SpudGunMan
11687cb7ba ‼️UPDATE LOCATION🗺️
this is a fail safe change to fuzzing the default location. This may change the way you use the bot today and should evaluate the change specifically test the auto alerts for proper data for emergency alerts etc.`fuzzConfigLocation = True`
2025-10-13 09:49:10 -07:00
SpudGunMan
b07a7fb0cc Update radio.py 2025-10-13 08:40:21 -07:00
SpudGunMan
b876d87ba9 enhance 2025-10-13 08:38:27 -07:00
SpudGunMan
0a63e89633 waitTooLong!
haha I well sorry
2025-10-13 08:23:07 -07:00
SpudGunMan
848f5609c2 Update README.md 2025-10-12 23:22:33 -07:00
SpudGunMan
0ccbed6165 fix Lemons 2025-10-12 23:19:08 -07:00
SpudGunMan
646517db71 Update mesh_bot.py 2025-10-12 21:27:14 -07:00
SpudGunMan
7d347bb80a enhance 2025-10-12 21:24:58 -07:00
SpudGunMan
e199d4f5eb Update mesh_bot.py 2025-10-12 20:03:03 -07:00
SpudGunMan
a9767b58c4 Update mesh_bot.py 2025-10-12 20:00:22 -07:00
SpudGunMan
69dfde047e Update lemonade.py 2025-10-12 20:00:20 -07:00
SpudGunMan
da33b6f1b9 Update dopewar.py 2025-10-12 19:55:43 -07:00
SpudGunMan
8a7125358b Update lemonade.py 2025-10-12 18:23:14 -07:00
SpudGunMan
ae558052f7 hey chirpy
vox trapping
2025-10-12 18:17:05 -07:00
SpudGunMan
5074d71eb7 defaults 2025-10-12 17:22:02 -07:00
SpudGunMan
632f42477a Update settings.py 2025-10-12 17:18:44 -07:00
SpudGunMan
b3df38d15e Update radio.py
aaarg
2025-10-12 17:17:31 -07:00
SpudGunMan
b76b8ca718 Update radio.py 2025-10-12 17:17:02 -07:00
SpudGunMan
d66a9e745b enhance 2025-10-12 17:13:41 -07:00
SpudGunMan
717bbccea3 Omg 2025-10-12 16:25:43 -07:00
SpudGunMan
50fd1c0410 Update tictactoe.py 2025-10-12 16:22:25 -07:00
SpudGunMan
ae89788ea4 Update settings.py 2025-10-12 15:33:02 -07:00
SpudGunMan
4220b095ee Update addFav.py 2025-10-12 15:27:30 -07:00
SpudGunMan
ef28341cdb Update addFav.py 2025-10-12 15:07:27 -07:00
SpudGunMan
b5d610728c Update addFav.py
ffs
2025-10-12 15:03:44 -07:00
SpudGunMan
bc238ef476 Update addFav.py 2025-10-12 14:38:20 -07:00
SpudGunMan
feb3544014 fixBug 2025-10-12 14:32:59 -07:00
SpudGunMan
31322dc0cd lessWait
remove some waits now that 2 seconds is needed by firmware
2025-10-12 14:26:23 -07:00
SpudGunMan
8c1cbaf442 fix game bugs 2025-10-12 13:05:54 -07:00
SpudGunMan
8d6a95b5da OMG
sorry to the fans
2025-10-12 11:00:09 -07:00
SpudGunMan
b4b2ef3d80 Update system.py
expand the timers for game play to 3 days for cleanup
2025-10-12 10:05:30 -07:00
SpudGunMan
13b1b90864 Update system.py 2025-10-12 10:00:09 -07:00
SpudGunMan
838bd3edce Update radio.py
oops
2025-10-12 09:55:55 -07:00
SpudGunMan
70bcf43b49 Update radio.py 2025-10-12 09:54:56 -07:00
SpudGunMan
0a02ae860e Update radio.py 2025-10-11 22:21:09 -07:00
SpudGunMan
a80575a381 Update radio.py 2025-10-11 22:20:52 -07:00
SpudGunMan
e57b65b447 Update system.py 2025-10-11 21:58:39 -07:00
SpudGunMan
1d18f0936c Update radio.py 2025-10-11 21:25:52 -07:00
SpudGunMan
b096716b96 enhance import note 2025-10-11 21:19:26 -07:00
SpudGunMan
f4734c5b87 vox detection 2025-10-11 20:44:03 -07:00
SpudGunMan
96447b166f Update README.md 2025-10-11 14:04:41 -07:00
SpudGunMan
2fc151bbbf leaderboard
I hope its all working now!
2025-10-11 12:55:56 -07:00
SpudGunMan
e66af5c068 bug in leaderboard fix 2025-10-11 12:47:24 -07:00
SpudGunMan
d3ce4d3905 Update addFav.py 2025-10-11 12:38:20 -07:00
SpudGunMan
a95cdeb086 -pickle
or print either way
2025-10-11 12:35:58 -07:00
SpudGunMan
27bf61a913 Update addFav.py 2025-10-11 12:21:00 -07:00
SpudGunMan
d62990b6db Update system.py
seriously open a window
2025-10-11 12:10:03 -07:00
SpudGunMan
0784aaebd9 enhance 2025-10-11 12:09:18 -07:00
SpudGunMan
e348854a50 cleanup 2025-10-11 11:46:09 -07:00
SpudGunMan
a71e5fa8f3 Update addFav.py 2025-10-11 11:22:21 -07:00
SpudGunMan
9600ea5e00 enhance with client_base 2025-10-11 11:20:00 -07:00
SpudGunMan
cc7461929e cleanup 2025-10-11 11:19:52 -07:00
SpudGunMan
0c8fb0c243 cleanup 2025-10-11 07:54:20 -07:00
SpudGunMan
311563320e enhance
rss sucks
2025-10-10 19:41:44 -07:00
SpudGunMan
78b6d660dd yakima works 2025-10-10 16:37:30 -07:00
SpudGunMan
77da966b9d Update mesh_bot.py 2025-10-10 16:22:59 -07:00
SpudGunMan
d844c123be refactor Rivers 2025-10-10 16:02:23 -07:00
SpudGunMan
d4d36c8a31 increase urlTimeout to 15 seconds 2025-10-10 15:30:36 -07:00
SpudGunMan
9acd57a420 log in the river
better logs for this API
2025-10-10 15:21:36 -07:00
SpudGunMan
bc06712b87 enhance rssread
enhance rssread
enhance rssread
enhance rssread
2025-10-10 12:50:07 -07:00
SpudGunMan
260e52fe81 Update system.py 2025-10-10 11:53:33 -07:00
SpudGunMan
6b548f82b2 Update mesh_bot.py 2025-10-10 11:40:30 -07:00
SpudGunMan
2273b481ad NEW CHUNKER
what day is it, chunker day!
2025-10-10 11:38:01 -07:00
SpudGunMan
95ee7779b4 Update mesh_bot.py
@mesb1 ahhh thanks!
2025-10-10 09:47:32 -07:00
SpudGunMan
ee1391f6e7 2fa.ini 2025-10-10 07:41:18 -07:00
SpudGunMan
b7a0d7cd8e Update system.py 2025-10-10 07:30:18 -07:00
SpudGunMan
a880236117 Update filemon.py 2025-10-10 07:24:42 -07:00
SpudGunMan
a67bdc3641 Update filemon.py 2025-10-10 07:16:02 -07:00
SpudGunMan
da8235adae Update filemon.py 2025-10-10 07:08:51 -07:00
SpudGunMan
22384463e2 are you human
or are you dancer, this was just fun to add. 2fa human check to x: commands
2025-10-10 07:03:10 -07:00
SpudGunMan
b48377de5f Update system.py 2025-10-10 00:42:31 -07:00
SpudGunMan
855c2e08cc Update system.py 2025-10-10 00:41:30 -07:00
SpudGunMan
d0aa07ed7d Update system.py
i should snooze
2025-10-10 00:39:43 -07:00
SpudGunMan
7328a92535 Update system.py 2025-10-10 00:36:34 -07:00
SpudGunMan
35c8dc6f70 resetLeaderboard 2025-10-10 00:36:22 -07:00
SpudGunMan
4b1123dcac Update mesh_bot.py 2025-10-10 00:06:19 -07:00
SpudGunMan
b74dc1ff25 not this or that 2025-10-09 23:31:21 -07:00
SpudGunMan
8c752dff3e Update system.py 2025-10-09 23:11:08 -07:00
SpudGunMan
b3b45a4335 Update system.py 2025-10-09 19:10:58 -07:00
SpudGunMan
fd86187798 Update mesh_bot.py 2025-10-09 19:09:20 -07:00
SpudGunMan
4da3e68c62 readrss
thanks FJRP you can now return an rss feed
2025-10-09 19:06:38 -07:00
SpudGunMan
e47907ebeb Update system.py 2025-10-09 18:38:35 -07:00
SpudGunMan
f63278ae8f Update system.py 2025-10-09 18:37:04 -07:00
SpudGunMan
0e0d2f11d7 Update system.py 2025-10-09 18:11:40 -07:00
SpudGunMan
6587ba61e2 Update system.py 2025-10-09 18:10:02 -07:00
SpudGunMan
b46697c0c4 enhance leaderboard 2025-10-09 18:08:38 -07:00
SpudGunMan
f5f8539924 segassem
reverse the order of the messages
2025-10-09 17:21:07 -07:00
SpudGunMan
e8063fcf3f Update system.py 2025-10-09 17:05:01 -07:00
SpudGunMan
169f9b27a5 Update system.py 2025-10-09 17:03:39 -07:00
SpudGunMan
4ceb23bcff Update system.py 2025-10-09 17:02:14 -07:00
SpudGunMan
315ae84bb6 enhance 2025-10-09 16:27:06 -07:00
SpudGunMan
fb12c11a7e Update mesh_bot.py 2025-10-09 15:39:32 -07:00
SpudGunMan
496c222cdc Update README.md 2025-10-09 15:34:56 -07:00
Kelly
cb55aba498 Merge pull request #203 from SpudGunMan/copilot/add-local-wiki-search-functionality
Add Kiwix local wiki server support for offline Wikipedia searches
2025-10-08 20:38:17 -07:00
SpudGunMan
1aac3d5ac2 failover 2025-10-08 20:37:21 -07:00
SpudGunMan
413f2a24d9 Kiwix in wiki
@NomDeTom its finally done
2025-10-08 20:29:52 -07:00
SpudGunMan
c75782d559 Update system.py 2025-10-08 20:03:05 -07:00
SpudGunMan
d38314a21c Update system.py 2025-10-08 19:31:30 -07:00
SpudGunMan
65dfe90edc Update system.py 2025-10-08 19:24:14 -07:00
SpudGunMan
3ce24fb7c9 Update system.py 2025-10-08 12:48:26 -07:00
SpudGunMan
8765e5a871 🥒
ahh pickles
2025-10-08 12:45:37 -07:00
SpudGunMan
b4f0421423 Update system.py 2025-10-08 12:37:52 -07:00
SpudGunMan
2b8906ae55 colon
KFC🍗
2025-10-08 11:11:14 -07:00
Kelly
5710b47a99 Merge pull request #208 from SpudGunMan/copilot/add-funny-data-facts-logging
Add mesh leaderboard feature to track extreme metrics and special packets
2025-10-08 11:02:42 -07:00
SpudGunMan
1f8bf5a700 bytes&bits 2025-10-08 11:01:21 -07:00
copilot-swe-agent[bot]
171480b704 Add leaderboard command documentation to README
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-08 16:53:07 +00:00
copilot-swe-agent[bot]
c74e4f99b2 Add mesh leaderboard feature to track extreme metrics
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-08 16:50:46 +00:00
copilot-swe-agent[bot]
cd5749521c Initial plan 2025-10-08 16:43:39 +00:00
Kelly
5ce7019dba Merge pull request #204 from SpudGunMan/copilot/fix-messages-bot-errors
Fix messages command error with Unicode characters (Cyrillic) I like this approach thanks GitHub
2025-10-08 09:21:22 -07:00
SpudGunMan
6c1e0cc2f9 bits&bytes 2025-10-08 09:20:09 -07:00
SpudGunMan
68b171f68e Update mesh_bot.py 2025-10-08 08:42:44 -07:00
SpudGunMan
7cfd5d0b0e Update mesh_bot.py 2025-10-08 08:39:24 -07:00
SpudGunMan
6dd4f0c4b6 Update joke.py 2025-10-08 08:37:03 -07:00
copilot-swe-agent[bot]
8ef0fa2ac0 Fix messages command to handle Unicode characters safely
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-08 15:18:30 +00:00
copilot-swe-agent[bot]
0c8d6b8fac Initial plan 2025-10-08 15:12:01 +00:00
copilot-swe-agent[bot]
1e4e5e6627 Add documentation and fix deprecated BeautifulSoup method
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-08 15:05:09 +00:00
copilot-swe-agent[bot]
c97004b410 Add Kiwix local wiki server support with configuration options
Co-authored-by: SpudGunMan <12676665+SpudGunMan@users.noreply.github.com>
2025-10-08 15:00:44 +00:00
copilot-swe-agent[bot]
2292fb2655 Initial plan 2025-10-08 14:54:32 +00:00
SpudGunMan
3ebf3ba374 Update config.template 2025-10-08 07:05:40 -07:00
SpudGunMan
b6087c926c news.template 2025-10-08 01:22:08 -07:00
SpudGunMan
2895e6c034 newNews🚨🚨
the location of news.txt changed FYI 🚨 now you can read more files
2025-10-08 01:14:10 -07:00
SpudGunMan
691bc8d701 Update README.md 2025-10-08 00:02:08 -07:00
SpudGunMan
bd50524e95 Update README.md 2025-10-07 23:53:22 -07:00
SpudGunMan
299b749f0e Update survey.py
I should sleep
2025-10-07 23:44:52 -07:00
SpudGunMan
9a060e3c6e Update quiz.py 2025-10-07 23:43:34 -07:00
SpudGunMan
a012ef17d0 Update survey.py 2025-10-07 23:41:22 -07:00
SpudGunMan
adbf78b740 enhance 2025-10-07 23:39:23 -07:00
SpudGunMan
3aad8d89cf Update survey.py 2025-10-07 23:34:36 -07:00
SpudGunMan
3370304249 Update survey.py 2025-10-07 23:30:35 -07:00
SpudGunMan
ef62a06db1 Update settings.py
disabled till configured and also uses io
2025-10-07 23:16:28 -07:00
SpudGunMan
8cc1d24b93 Update README.md 2025-10-07 23:15:23 -07:00
SpudGunMan
fca90cbee3 Update survey.py 2025-10-07 23:10:09 -07:00
SpudGunMan
d05c7bb6a5 Update survey.py 2025-10-07 23:05:12 -07:00
SpudGunMan
7774529fb4 bugfix 2025-10-07 23:02:52 -07:00
SpudGunMan
4c615af22d Update mesh_bot.py 2025-10-07 22:42:13 -07:00
SpudGunMan
6c078b4d17 Survey Says!
is this cool?
2025-10-07 22:39:08 -07:00
SpudGunMan
ddb9c8b4bf Update mesh_bot.py 2025-10-07 20:34:17 -07:00
SpudGunMan
73f3175705 Update mesh_bot.py 2025-10-07 20:18:12 -07:00
SpudGunMan
d2ee1bce1c Update quiz.py 2025-10-07 20:01:20 -07:00
SpudGunMan
b4a2149815 enhance 2025-10-07 20:00:22 -07:00
SpudGunMan
320f41e05a documentation 2025-10-07 17:58:19 -07:00
SpudGunMan
48a57e875f QuizMaster
let me know if this is cool
2025-10-07 17:48:22 -07:00
SpudGunMan
ce317d8bbe Update simulator.py 2025-10-07 16:35:03 -07:00
SpudGunMan
c2d2a8f7e4 Update simulator.py 2025-10-07 16:33:33 -07:00
SpudGunMan
00280e351c Update mesh_bot.py 2025-10-07 14:04:07 -07:00
SpudGunMan
0e8bb197a9 Update mesh_bot.py 2025-10-07 13:59:49 -07:00
SpudGunMan
d825c0fa15 Update mesh_bot.py
what happened here? I forget now but sheesh!
2025-10-07 13:57:00 -07:00
SpudGunMan
6abe73c1bc Update mesh_bot.py
ack
2025-10-07 13:54:32 -07:00
SpudGunMan
b8e9adb223 fixMessagesCommand
thanks @mesb1  https://github.com/SpudGunMan/meshing-around/issues/200
2025-10-07 13:48:23 -07:00
SpudGunMan
e621016e9a nom
nom
2025-10-07 06:06:21 -07:00
SpudGunMan
cfaf652852 Update mesh_bot.py 2025-10-06 20:02:36 -07:00
SpudGunMan
6c27b5d5de xoxo
enhance
2025-10-06 18:03:22 -07:00
SpudGunMan
a31fa90942 Update system.py 2025-10-06 14:57:40 -07:00
SpudGunMan
3cd347dff3 Update tictactoe.py 2025-10-06 14:46:24 -07:00
SpudGunMan
ea4ac1f9c1 whichonelooksbetter 2025-10-06 14:42:50 -07:00
SpudGunMan
a9da8336cc enhance 2025-10-06 14:40:08 -07:00
SpudGunMan
4ba60ed276 correctLogLevel 2025-10-06 14:25:13 -07:00
Kelly
42e07d44e6 Merge pull request #198 from martinbogo/feature/tictactoe-game
Feature/tictactoe game
2025-10-06 14:11:23 -07:00
SpudGunMan
11f5218c2e Merge branch 'feature/tictactoe-game' of https://github.com/martinbogo/meshing-around into pr/198 2025-10-06 14:08:49 -07:00
SpudGunMan
e137420138 patch-2 2025-10-06 14:08:07 -07:00
Kelly
80c0f698b6 Update modules/games/tictactoe.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-06 13:51:56 -07:00
SpudGunMan
2045bf98f7 🧩 2025-10-06 13:45:02 -07:00
SpudGunMan
c36ce2c3a6 Update mesh_bot.py 2025-10-06 13:09:47 -07:00
SpudGunMan
7ff36a3d5f Update mesh_bot.py 2025-10-06 13:05:32 -07:00
SpudGunMan
ae1a3040b5 patches
dont need no stinking patches. thanks again.
2025-10-06 12:54:41 -07:00
Martin Bogomolni
84b6b48d60 feat: Add tic-tac-toe game with compact messaging
🎮 New Tic-Tac-Toe Game Features:
- Compact 3x3 board display using ASCII art
- Smart AI opponent with win/block/random strategy
- All messages under 200-character meshtastic limit (tested: 10-50 chars)
- Player vs Bot gameplay with X (player) vs O (bot)
- Win detection for rows, columns, and diagonals
- Tie game detection when board is full
- Game statistics tracking (games played, won)

🔧 Integration Features:
- Follows established game patterns from hangman/hamtest
- Added to restrictedCommands (DM-only like other games)
- Integrated with game tracker system for memory cleanup
- Added configuration option in config.template
- Automatic cleanup of stale game sessions

🎯 Game Mechanics:
- Players pick positions 1-9 corresponding to board layout
- Simple input parsing (extracts first digit from message)
- Graceful error handling for invalid moves
- 'end' command to quit game
- Automatic game cleanup on completion

📊 Message Examples:
- New game: 39 chars
- Game moves: 50 chars
- Win/lose: 40 chars
- Invalid move: 23 chars
- All well under 200-char limit

Tested: Complete game scenarios, AI behavior, message lengths
Follows: Existing game implementation patterns and memory management
2025-10-06 00:08:56 -07:00
Martin Bogomolni
9f3446b605 feat: Implement comprehensive memory management and stability improvements
🔧 Memory Management Enhancements:
- Add memory cleanup constants (MAX_CMD_HISTORY=1000, MAX_SEEN_NODES=500, MAX_MSG_HISTORY=100)
- Implement cleanup_memory() function to prevent unbounded list growth
- Add periodic cleanup every hour via watchdog process
- Clean up stale game tracker entries automatically
- Limit cmdHistory and msg_history sizes to prevent memory bloat

🚀 Async Task Management Improvements:
- Fix async task management in both mesh_bot.py and pong_bot.py
- Implement proper task cleanup and cancellation on shutdown
- Add task names for better debugging and monitoring
- Use asyncio.gather() with return_exceptions=True for better error handling
- Prevent task hanging and resource leaks

🛡️ Enhanced Resource Management:
- Improve exit_handler() with proper interface cleanup
- Add atexit.register() for automatic graceful shutdown
- Ensure all meshtastic interfaces are properly closed
- Save persistent data (BBS, email, SMS, game scores) on exit
- Perform final memory cleanup during shutdown

🔍 Better Exception Handling:
- Replace bare except: blocks with specific exception handling
- Add proper error logging throughout the codebase
- Improve BBS database operations with better error recovery
- Add try/catch blocks for file operations and imports

📈 System Stability Improvements:
- Prevent memory leaks from growing lists and dictionaries
- Add automatic cleanup of stale player tracking data
- Improve error recovery in watchdog and async loops
- Better handling of interface connection failures

These changes address critical memory management issues that could cause
the bot to consume increasing memory over time, eventually leading to
system instability. The improvements ensure long-term reliability and
better resource utilization.

Fixes: Memory leaks, async task hanging, resource cleanup issues
Improves: System stability, error handling, resource management
Tested: Code analysis and review completed
2025-10-05 23:45:40 -07:00
SpudGunMan
10add3147d Update system.py 2025-10-05 23:10:23 -07:00
SpudGunMan
4e074a309f Update system.py 2025-10-05 23:05:55 -07:00
SpudGunMan
f394f58b9f paxCounter 2025-10-05 22:30:03 -07:00
SpudGunMan
30bcee498d Update config.template 2025-10-05 22:24:35 -07:00
SpudGunMan
5c54ce0b70 better waypoint data 2025-10-05 21:50:56 -07:00
SpudGunMan
b4684f49ff Update system.py 2025-10-05 21:38:19 -07:00
SpudGunMan
c6c1e9f637 refactor more consumeMetadata 2025-10-05 21:13:39 -07:00
SpudGunMan
54540b1656 cleanup 2025-10-05 20:26:48 -07:00
SpudGunMan
006c9f58c6 enhance bbsLink 2025-10-05 19:44:00 -07:00
SpudGunMan
3d582e9b77 enhance import of BBS
for ssh copy
2025-10-05 19:20:44 -07:00
SpudGunMan
0578c0b233 more enhancing metadata 2025-10-05 19:00:34 -07:00
SpudGunMan
98ccf8708f enhanceTelemetry
logging and handlers for telemetry
2025-10-05 17:47:19 -07:00
SpudGunMan
47280f4330 Update bbstools.py
comment from https://github.com/SpudGunMan/meshing-around/issues/194
2025-10-05 15:26:50 -07:00
SpudGunMan
4b0b074ba7 mathWasntMathn'
@mesb1 thanks
2025-10-05 09:08:47 -07:00
SpudGunMan
d8d79f46b5 Update README.md
@pdxlocations
2025-10-04 15:45:43 -07:00
SpudGunMan
1a49a81cf5 load_bbsdb with 'api'
allows for ssh file synch?
2025-10-04 12:54:20 -07:00
SpudGunMan
5c0b04f0b7 Update injectDM.py 2025-10-03 19:11:40 -07:00
SpudGunMan
8f1cb6265d Update injectDM.py 2025-10-03 19:07:25 -07:00
SpudGunMan
c51a4584ae enhance bbsAPI
switch for diskIO
2025-10-03 19:06:14 -07:00
SpudGunMan
13ee6d4fd6 enhance bbsDM
enable a new 'API' to inject into the pkl file for DM's also see 2d44faac98
2025-10-03 19:02:15 -07:00
SpudGunMan
2d44faac98 Create injectDM.py
Usage: python3 script/injectDM.py -s NODEID -d NODEID -m "message"
2025-10-03 18:15:57 -07:00
SpudGunMan
0a2daeac1f Update joke.py 2025-10-03 15:42:05 -07:00
SpudGunMan
da7ba256d8 Update joke.py 2025-10-03 15:41:40 -07:00
SpudGunMan
42e99a0dc1 Update joke.py 2025-10-03 15:40:54 -07:00
SpudGunMan
ca5896a015 Update locationdata.py 2025-10-03 15:35:04 -07:00
SpudGunMan
ebe2636104 refactor riverflow 2025-10-03 15:34:03 -07:00
SpudGunMan
971a421d01 riverflow refactor 2025-10-03 15:15:40 -07:00
SpudGunMan
9d080de8f3 Update locationdata.py 2025-10-03 15:01:41 -07:00
SpudGunMan
5209092928 better riverflow logic 2025-10-03 14:54:12 -07:00
SpudGunMan
6439f49fb1 Update filemon.py 2025-10-03 12:28:47 -07:00
SpudGunMan
c115cdf82f enhance x: with subprocess 2025-10-03 12:15:14 -07:00
SpudGunMan
63fccbdf3e Update config.template 2025-10-03 12:01:41 -07:00
SpudGunMan
c23564d8b5 Update system.py 2025-10-02 19:37:57 -07:00
SpudGunMan
0b9db28951 Update README.md 2025-10-02 19:18:39 -07:00
SpudGunMan
1aa4eddb3b Update filemon.py 2025-10-02 19:07:37 -07:00
SpudGunMan
a7de64b385 Update filemon.py 2025-10-02 19:03:15 -07:00
SpudGunMan
2e8206d4ec x:ShellCommands
this x: is a direct shell access from DM, to enable it needs the enable_runShellCmd, allowXcmd, xcmdChannel set. Make sure your secure.
2025-10-02 18:58:27 -07:00
SpudGunMan
b47c13503b Update filemon.py 2025-10-02 13:37:17 -07:00
SpudGunMan
a66dbd13fd Update config.template 2025-10-02 13:17:48 -07:00
SpudGunMan
02322cdf91 cleanup
fixes per https://github.com/SpudGunMan/meshing-around/issues/192
2025-10-02 04:51:40 -07:00
SpudGunMan
955d3681e9 Update joke.py 2025-10-01 11:41:59 -07:00
SpudGunMan
9d96c02870 catch em all 2025-09-29 16:59:13 -07:00
SpudGunMan
c87dba1e06 fixWikiErrors 2025-09-29 16:58:34 -07:00
SpudGunMan
1c3d2f7f18 Update mesh_bot.py 2025-09-29 16:16:33 -07:00
SpudGunMan
b53a7d3832 Update joke.py 2025-09-29 16:13:01 -07:00
SpudGunMan
99e74ae8c0 lower! 2025-09-28 18:22:56 -07:00
SpudGunMan
1bdfc3828f cleanup 2025-09-28 18:20:42 -07:00
SpudGunMan
26f39e76e6 somdays tabs killl me 2025-09-28 17:41:13 -07:00
SpudGunMan
c49dcfbfc8 aarg 2025-09-28 17:38:59 -07:00
SpudGunMan
1008ec6afa yarp 2025-09-28 17:36:57 -07:00
SpudGunMan
8c0a1bbd0d cleanup
need to fix this
2025-09-28 17:27:55 -07:00
SpudGunMan
30d8f00aeb Update update.sh 2025-09-28 17:25:31 -07:00
SpudGunMan
033b1bcd51 Update update.sh 2025-09-28 17:21:00 -07:00
SpudGunMan
d80b2da06a Update launch.sh 2025-09-28 17:18:56 -07:00
SpudGunMan
dc02464662 Update update.sh 2025-09-28 17:17:53 -07:00
SpudGunMan
b738881ff1 Update update.sh 2025-09-28 17:16:04 -07:00
SpudGunMan
b8f0601684 enhance 2025-09-28 17:11:09 -07:00
SpudGunMan
910c045b08 Update update.sh 2025-09-28 17:07:12 -07:00
SpudGunMan
35ba139577 enhance 2025-09-28 17:03:59 -07:00
SpudGunMan
eddd990cc5 Update README.md
ffs
2025-09-28 16:32:40 -07:00
SpudGunMan
6e3d83401f enhance echo
enhance echo
2025-09-28 16:28:31 -07:00
SpudGunMan
f9ab6a79d3 echo
echo command will just echo, off by default its handy for things like making a demo or node speak
2025-09-28 15:04:56 -07:00
SpudGunMan
4b2402c286 Update space.py 2025-09-27 17:24:21 -07:00
SpudGunMan
47e0276f0c howtall
returns height of something you give a shadow by using sun angle
2025-09-26 19:23:12 -07:00
SpudGunMan
6dc54abf43 enhance 2025-09-26 19:16:16 -07:00
SpudGunMan
53ff37c782 howtall
is this handy? I thought it might be for tree tower use
2025-09-26 19:02:02 -07:00
SpudGunMan
5c48e008ee Update checklist.py 2025-09-26 19:00:46 -07:00
SpudGunMan
ddac18bb13 Update README.md 2025-09-26 16:13:34 -07:00
SpudGunMan
507919bb4c aarg 2025-09-26 16:05:55 -07:00
SpudGunMan
b4f3f9887d OCD 2025-09-26 15:58:10 -07:00
SpudGunMan
aa051abbd4 better Logic for handler 2025-09-26 15:54:51 -07:00
SpudGunMan
8ba0c6f14c Update system.py 2025-09-26 15:47:51 -07:00
SpudGunMan
166b15463a Update launch.sh 2025-09-26 15:46:36 -07:00
SpudGunMan
d02924bfda Update launch.sh 2025-09-26 15:45:26 -07:00
SpudGunMan
0a123251f4 Update README.md 2025-09-26 15:44:23 -07:00
SpudGunMan
a80f926d08 Update launch.sh 2025-09-26 15:43:29 -07:00
SpudGunMan
b8318f8f3e Update README.md 2025-09-26 15:38:36 -07:00
SpudGunMan
adb6fa3b5a Update system.py 2025-09-26 15:36:49 -07:00
SpudGunMan
a9254c9c79 addFav
Helper Script to Add Favorite to the bot node for admin and other use
2025-09-26 15:32:24 -07:00
SpudGunMan
0ac642ac44 Update config.template 2025-09-24 15:21:02 -07:00
SpudGunMan
ec24a8b8dd typo 2025-09-24 15:19:57 -07:00
SpudGunMan
f79026a95f enhance
DEBUGpackets, debugMetadata hidden config.ini values
2025-09-24 15:16:37 -07:00
SpudGunMan
99acaf28a1 Update system.py 2025-09-24 15:14:17 -07:00
SpudGunMan
9c068c8d28 Update settings.py 2025-09-24 15:14:07 -07:00
SpudGunMan
d9ab1b88c1 Update system.py 2025-09-24 15:10:26 -07:00
SpudGunMan
8499b6c851 Update README.md 2025-09-19 09:36:28 -07:00
SpudGunMan
ea47bf9329 bugfix parser
thanks again Iris!
2025-09-19 09:32:53 -07:00
SpudGunMan
229043c32a fix config.ini bug
Thanks Iris for pointing out this long time bug
2025-09-19 09:05:37 -07:00
SpudGunMan
5dbd137f14 enhance 2025-09-19 08:51:43 -07:00
SpudGunMan
ca83117180 Update locationdata.py
fix polygone at 4+
2025-09-17 12:13:03 -07:00
SpudGunMan
fde37313f5 Update locationdata.py 2025-09-17 11:55:34 -07:00
Kelly
a39f588f9f Merge pull request #188 from SpudGunMan/lab
Noisy Telemetry
lost work on location data
2025-09-17 11:52:50 -07:00
SpudGunMan
39e348f701 Update locationdata.py
got lost somehow
2025-09-17 11:43:43 -07:00
SpudGunMan
4fdfa49b87 Revert "Update locationdata.py"
This reverts commit 8a64b8e7ad.
2025-09-17 11:43:22 -07:00
SpudGunMan
8a64b8e7ad Update locationdata.py
this got lost somewhere
2025-09-17 11:41:35 -07:00
SpudGunMan
c585f60882 Update README.md
think this was a typo
2025-09-17 10:55:38 -07:00
SpudGunMan
4e91801cb9 Update system.py
reset alerts
2025-09-17 10:55:30 -07:00
SpudGunMan
4e1d3e2b58 lower volume 2025-09-17 10:55:17 -07:00
SpudGunMan
38d5006236 Update system.py 2025-09-16 17:24:55 -07:00
SpudGunMan
642738e3b6 noisyNodeLogging
telemetry logger idea
2025-09-16 17:09:47 -07:00
SpudGunMan
5728d6b9e3 Update locationdata.py
didnt like this
2025-09-13 18:25:35 -07:00
SpudGunMan
82bec43f22 Update locationdata.py
move this and add miles
2025-09-13 18:21:09 -07:00
SpudGunMan
7ca8b6793a Update locationdata.py
limit noaa which just gave me a 11 digit richter ooof
2025-09-13 17:33:18 -07:00
SpudGunMan
d589d3e155 Update system.py 2025-09-11 18:00:42 -07:00
SpudGunMan
452c4aa520 Update locationdata.py 2025-09-11 17:50:19 -07:00
SpudGunMan
e5d2ea4bcb Update system.py 2025-09-10 19:24:44 -07:00
SpudGunMan
2596d133fd Update system.py 2025-09-10 19:23:08 -07:00
SpudGunMan
c3221d64a8 enhance 2025-09-10 19:03:44 -07:00
SpudGunMan
dcabfc0f50 Update system.py 2025-09-10 19:00:37 -07:00
SpudGunMan
2eca5f644a add aircraft lookup to highFlying info
@Cisien for the idea
2025-09-10 18:58:33 -07:00
SpudGunMan
3f90a7fc39 dedupe emergency alerts
double check we didnt already send the message here it could be duplicated elsewhere
2025-09-10 18:06:43 -07:00
SpudGunMan
9639c793d9 Update README.md
i can spell well
2025-09-10 13:09:54 -07:00
SpudGunMan
18294f4ca3 Update locationdata.py 2025-09-10 12:48:33 -07:00
SpudGunMan
14043dd950 Merge branch 'main' of https://github.com/SpudGunMan/meshing-around 2025-09-10 12:46:25 -07:00
SpudGunMan
fe1c264b19 Update locationdata.py 2025-09-10 12:46:01 -07:00
Kelly
8848d9b6fe Merge pull request #184 from ulab/patch-2
Add fileMon files to .gitignore
2025-09-10 09:49:28 -07:00
Kelly
daa6e85318 Merge pull request #185 from sodoku/dealert-fixes
fix: wrong variable use
2025-09-10 09:49:01 -07:00
sodoku
f7f127590d fix: wrong variable use 2025-09-10 18:41:45 +02:00
Balu
5b0fd65d31 Add fileMon files to .gitignore 2025-09-10 14:52:19 +02:00
SpudGunMan
fe12e1f107 enhance 2025-09-09 15:55:34 -07:00
SpudGunMan
11025f101f add QRN to hfcond 2025-09-09 15:19:46 -07:00
SpudGunMan
92a5fc2ed5 Update space.py 2025-09-09 15:03:37 -07:00
SpudGunMan
3f891d93d2 add space
same here to stop runaway commands
2025-09-09 15:03:22 -07:00
SpudGunMan
398c9ddb60 remove space
this happens to stop a multi-bot runaway
2025-09-09 15:02:37 -07:00
SpudGunMan
518eb25f0d Merge branch 'main' of https://github.com/SpudGunMan/meshing-around 2025-09-09 15:00:54 -07:00
SpudGunMan
0613cc7b3d Update README.md 2025-09-09 15:00:51 -07:00
Kelly
be2d1fbf72 Merge pull request #179 from ulab/space_spaces
Add some spaces around emojiis and after punctuation
2025-09-09 13:26:46 -07:00
Kelly
8595190ed1 Merge pull request #181 from SpudGunMan/lab
HowFar
2025-09-09 13:26:04 -07:00
SpudGunMan
5703cfb381 🗺️ howfar 2025-09-09 12:42:03 -07:00
SpudGunMan
ff9b76c966 Update locationdata.py 2025-09-09 12:08:59 -07:00
Balu
e41f692038 Add some spaces around emojiis and after punctuation 2025-09-09 14:06:27 +02:00
SpudGunMan
19935d9f08 howfar
initial idea goofin to see if this works
2025-09-07 19:12:57 -07:00
SpudGunMan
f0e8b2c057 🐛 2025-09-02 11:19:23 -07:00
SpudGunMan
eb2d809fe4 from: in bbs_read_message
Reading Messages has the last 4 of the HexID now "from"
2025-08-31 20:37:40 -07:00
SpudGunMan
b276bbb40a rlist command in help 2025-08-31 19:47:59 -07:00
SpudGunMan
35ea7cb505 fix HTML parsing for rlist getRepeaterBook
Thanks to rhinodods on discord for the alert
2025-08-31 18:02:21 -07:00
SpudGunMan
eb78c2e5e8 Update install.sh 2025-08-29 17:48:30 -07:00
SpudGunMan
3df16b7626 Update system.py 2025-08-29 17:25:51 -07:00
SpudGunMan
8c01433d14 🚨fixes/enhancments
better multi network control of alerts and 🪫 alert to mesh
2025-08-27 12:10:38 -07:00
SpudGunMan
a8dbef7e12 Update install.sh 2025-08-26 17:24:29 -07:00
SpudGunMan
23478812e0 Update install.sh 2025-08-26 16:51:33 -07:00
SpudGunMan
08c2c668f9 EarthQuake
from USGS data seismicportal.eu wont let me set a radius on lookups but looking into it
2025-08-26 14:21:10 -07:00
SpudGunMan
3b41e39ff5 Update system.py 2025-08-26 14:09:23 -07:00
SpudGunMan
78fa3209e6 Update install.sh
update gemma3:270m
2025-08-26 11:04:46 -07:00
Kelly
c5ba56a656 Merge pull request #178 from SpudGunMan/lab
Gemma3 LLM
2025-08-26 11:00:31 -07:00
SpudGunMan
50c3249edc explicitCmd
i think @NomDeTom mentioned this a long time ago and well .. here is a change to help the phases of the moon and tide.
2025-08-26 10:44:30 -07:00
SpudGunMan
80897f7a82 defaults to gemma3 raw input
this is a change as its looking to remove google lookups with the python module. if this changes is impacting please let me know in [general] add `rawLLMQuery = False` to reverse
2025-08-26 10:26:33 -07:00
SpudGunMan
d311832a92 truncation 2025-08-20 11:55:44 -07:00
SpudGunMan
56af59345d Update settings.py 2025-08-19 06:19:07 -07:00
SpudGunMan
c1adca7db0 Update mesh_bot.py 2025-08-18 18:55:23 -07:00
SpudGunMan
4c7fe55b43 hopFix 2025-08-18 18:54:02 -07:00
SpudGunMan
df6a1cfb66 Update pong_bot.py
better MQTT handler
2025-08-17 20:25:40 -07:00
SpudGunMan
9994446510 better MQTT handler 2025-08-17 20:24:09 -07:00
SpudGunMan
9272218815 Update system.py
i declare
2025-08-17 20:05:41 -07:00
SpudGunMan
388d862fc9 Update llm.py 2025-08-16 21:24:46 -07:00
SpudGunMan
ac33f8a02b Update llm.py 2025-08-16 21:16:44 -07:00
SpudGunMan
f04392a81c Update llm.py 2025-08-16 20:25:53 -07:00
SpudGunMan
d0097c092b Update llm.py 2025-08-16 17:48:04 -07:00
SpudGunMan
92ff166260 Update llm.py
adding these back, the token limit just has no bounds
2025-08-15 21:48:30 -07:00
Kelly
bfe0d219f9 Merge pull request #175 from SpudGunMan/main
fix daylight
2025-08-15 21:44:24 -07:00
SpudGunMan
85a2d90cff fix daylight 2025-08-15 21:42:45 -07:00
SpudGunMan
e15232875c token limit 2025-08-15 21:33:40 -07:00
SpudGunMan
d1a87f161b updateOllama
remember to update to latest ollama bin's
2025-08-15 21:17:58 -07:00
SpudGunMan
626ac59b4e gemma3
LLM rewrite, the removal of RAG to keep things clean.

This default changes as well as puts input direct to the LLM further testing is needed, new LLM prompting is different.
2025-08-15 21:11:09 -07:00
SpudGunMan
835a9e5f89 Update space.py 2025-08-15 06:52:55 -07:00
SpudGunMan
3ae928dd66 more light on the sun 2025-08-15 06:51:51 -07:00
SpudGunMan
3973406783 formatting of sun
trying this out vs the old way
2025-08-15 06:32:15 -07:00
SpudGunMan
4fbdd42837 Update space.py 2025-08-15 05:40:33 -07:00
SpudGunMan
04378efdd8 Update space.py 2025-08-14 20:33:21 -07:00
SpudGunMan
0d19a40ed6 Update space.py 2025-08-14 19:47:53 -07:00
SpudGunMan
75ac3c974a Update space.py 2025-08-14 19:47:25 -07:00
SpudGunMan
7e0eb348ae 🌝 2025-08-14 19:46:53 -07:00
SpudGunMan
af6ea2a512 Update space.py 2025-08-14 19:41:12 -07:00
SpudGunMan
6665ea7dcd moon refactor 2025-08-14 19:40:32 -07:00
SpudGunMan
3212661ee8 enhance sun and moon
add position data when visible
2025-08-14 19:35:13 -07:00
SpudGunMan
0675132171 up a river
without help
2025-08-13 20:41:42 -07:00
Kelly
fdb7897963 Merge pull request #173 from dludwig/typofix
typo fix deteted -> detected
2025-08-13 20:16:18 -07:00
dludwig
8ff7a0bf3c typo fix detetec -> detected 2025-08-13 15:18:34 -07:00
SpudGunMan
c210534543 Update README.md 2025-08-13 08:58:31 -07:00
SpudGunMan
ea7574a868 Update locationdata.py
remove the $$ end marker
2025-08-12 13:40:26 -07:00
SpudGunMan
8f69c4d93c Update mesh_bot.py
aarg
2025-08-12 12:03:43 -07:00
SpudGunMan
bc9ada91b4 Update mesh_bot.py 2025-08-12 11:54:17 -07:00
SpudGunMan
28f06f0a21 Update config.template 2025-08-12 11:50:05 -07:00
SpudGunMan
267fe392e3 tuypo 2025-08-12 11:42:13 -07:00
SpudGunMan
6c1f7940ca refactor coastal weather
changes to config.ini template if you use tide or mwx
2025-08-12 11:35:42 -07:00
Raymond Dean
29a26d5d14 Merge branch 'SpudGunMan:main' into create-docker-image 2025-08-08 19:29:53 -04:00
SpudGunMan
2fc9281394 Update system.py 2025-08-04 18:54:46 -07:00
SpudGunMan
b5bd1008c2 HowHigh? divideBy3
https://github.com/SpudGunMan/meshing-around/discussions/170
2025-08-03 17:43:10 -07:00
SpudGunMan
ee1db5b7be Update locationdata.py 2025-08-02 19:21:46 -07:00
SpudGunMan
7395b96337 Update locationdata.py 2025-07-30 10:16:33 -07:00
SpudGunMan
f3c6f77b23 Update mesh_bot.py 2025-07-30 10:13:14 -07:00
SpudGunMan
f6e04a42a0 Update system.py 2025-07-30 10:11:34 -07:00
SpudGunMan
3fcd588d02 bugs and docs
Consolidated Tide with MWX fixed up readme and cleaned up rlist in help
2025-07-30 10:05:04 -07:00
SpudGunMan
e1b47484f2 NOAA Coastal Marine Forcast data
using older but handy products with new mwx
2025-07-30 08:34:20 -07:00
SpudGunMan
14798cb992 alertDe 2025-07-22 09:28:08 -07:00
Kelly
41c8f0044b Merge pull request #163 from SudoRand/efficient-chunking
Allow chunker to consolidate lines when possible
2025-07-22 08:23:42 -07:00
SpudGunMan
45eefb24d8 enhance retry 2025-07-22 07:02:08 -07:00
SpudGunMan
410d32947c Update system.py 2025-07-21 20:13:07 -07:00
SpudGunMan
748652ac62 onDisconnect
correcting multiple issues adding config.ini feature for dont_retry_disconnect

https://github.com/SpudGunMan/meshing-around/issues/137
https://github.com/SpudGunMan/meshing-around/issues/156
2025-07-21 20:10:59 -07:00
SpudGunMan
d715cb6b4d Update system.py 2025-07-21 04:33:04 -07:00
SpudGunMan
1895a365ae fix retry and failure
correcting multiple issues with some bad code

https://github.com/SpudGunMan/meshing-around/issues/137

https://github.com/SpudGunMan/meshing-around/issues/156
2025-07-20 05:41:50 -07:00
SpudGunMan
cc58a38165 Update system.py 2025-07-18 21:24:55 -07:00
SpudGunMan
a8ccb05d56 Update system.py
bug of undefined for interface retry
2025-07-16 08:57:39 -07:00
SpudGunMan
a90a533a30 USGS Alerts
documented
2025-07-15 21:20:37 -07:00
SpudGunMan
57a4e5d68c Update README.md 2025-07-15 21:12:23 -07:00
SpudGunMan
7c99b684ad riverflow
never got documented well
2025-07-15 21:11:48 -07:00
SpudGunMan
b957c89d70 Update README.md 2025-07-15 20:32:51 -07:00
SpudGunMan
9b986dd57a Update locationdata.py
allow FIPS only
2025-07-15 20:30:43 -07:00
SpudGunMan
9e348332e5 SAME code back in iPAWS
the state only FIPS codes are too wide
2025-07-15 19:09:27 -07:00
SpudGunMan
0cfe759ef6 Update mesh_bot.py 2025-07-15 15:34:32 -07:00
SpudGunMan
e95902ef98 fix Excessive queries to FEMA
issue raised https://github.com/SpudGunMan/meshing-around/issues/165

Co-Authored-By: DEVAFRS <180097515+devafrs@users.noreply.github.com>
2025-07-15 15:22:53 -07:00
Raymond Dean
43e6349351 Update compose example. 2025-07-15 17:42:17 -04:00
SpudGunMan
c7df4d88d1 Update config.template
Co-Authored-By: Russell Schmidt <836646+rfschmid@users.noreply.github.com>
2025-07-15 14:28:25 -07:00
SpudGunMan
6d01c5a986 further adjustments for 2.7.2
https://github.com/SpudGunMan/meshing-around/pull/164#pullrequestreview-3021705851

and

https: //github.com/SpudGunMan/meshing-around/issues/162
Co-Authored-By: SudoRand <25190078+sudorand@users.noreply.github.com>
2025-07-15 11:14:29 -07:00
SpudGunMan
3f882dcfcd fix message.log
fixing issue for log in https://github.com/SpudGunMan/meshing-around/pull/161

Co-Authored-By: SudoRand <25190078+sudorand@users.noreply.github.com>
2025-07-15 09:41:34 -07:00
SpudGunMan
b146fd6f64 Revert "enhance sysinfo"
This reverts commit 8709e5aed5.
2025-07-14 22:55:41 -07:00
SpudGunMan
8709e5aed5 enhance sysinfo
ChUtil/Node value
2025-07-14 22:13:49 -07:00
SpudGunMan
caf8a2708b Update log.py
fix time display
2025-07-14 22:04:22 -07:00
SpudGunMan
9b4200c198 Update config.template
adjustments for 2.7.2 firmware might change again
2025-07-14 21:54:30 -07:00
SudoRand
097cae6e94 Allow chunker to consolidate lines when possible
This allows the chunker to consolidate lines into significantly
fewer messages in many cases without exceeding the max chunk size.

Without this change, the chunker will either emit all lines in
one message (if it fits in a single chunk) or else each line will be in
a separate message. This often creates a long series of short messages,
which doesn't transmit as quickly or display as compact.

Instead, this consolidates as many lines as possible into each
message, while being sure to stay within the chunk size limit.
This should reduce the load on the mesh, and it's also more readable.
2025-07-14 12:27:14 -06:00
Raymond Dean
628f66e4b7 Update compose.yaml to expose port 8420 2025-07-12 14:08:29 -04:00
Raymond Dean
29f97c62d0 add compose example 2025-07-12 11:50:21 -04:00
Raymond Dean
b805e6d428 Update docker-image.yml 2025-07-12 11:19:35 -04:00
Raymond Dean
6d5ded7df6 Create and publish a Docker image on new release 2025-07-12 11:18:05 -04:00
SpudGunMan
0a260b28b6 Update llm.py
last time?
2025-06-26 19:30:33 -07:00
SpudGunMan
3f5c6f2e9a Update llm.py 2025-06-26 19:03:13 -07:00
SpudGunMan
8a4f7a904a Update llm.py 2025-06-26 18:49:16 -07:00
SpudGunMan
0bc3d392cf fix Interface logic
a condition where TCP interfaces can fail leaving a none condition. this should resolve the errored interface better.
2025-06-25 07:30:46 -07:00
SpudGunMan
5eaef8b5b8 Update sysEnv.sh
enhance with git update check

Co-Authored-By: Johannes le Roux <dade@dade.co.za>
2025-06-25 07:25:04 -07:00
SpudGunMan
3a0007771d Update update.sh 2025-06-22 20:04:18 -07:00
SpudGunMan
67ba2b1fb5 Create update.sh 2025-06-22 19:59:31 -07:00
SpudGunMan
f2e7a9aa5c Update config.template 2025-06-18 12:15:44 -07:00
SpudGunMan
9d22270dde highfly_ignoreList
some nodes have bad altimeters
2025-06-18 12:14:14 -07:00
SpudGunMan
409d07436e Update settings.py 2025-06-10 11:22:32 -07:00
SpudGunMan
5ab0001f2b Update system.py
https://github.com/SpudGunMan/meshing-around/issues/154
2025-06-08 20:32:28 -07:00
SpudGunMan
5e34537af7 fix
reference https://github.com/SpudGunMan/meshing-around/issues/154
2025-06-08 19:26:51 -07:00
SpudGunMan
1764bdf4f3 enhance
the database page to include qrz.db
2025-06-07 21:05:49 -07:00
SpudGunMan
2290f07351 Update locationdata.py 2025-06-06 17:54:31 -07:00
SpudGunMan
ee01051cf7 Update config.template 2025-06-06 17:54:29 -07:00
Kelly
de50a52fa6 Merge pull request #153 from rfschmid/allow-dms-to-numeric-short-names 2025-06-05 19:38:44 -07:00
SpudGunMan
8eabfaa9c4 enhance ignore logic 2025-06-04 10:37:58 -07:00
Russell Schmidt
ca7114b058 Allow DMs to numeric short names 2025-06-04 11:55:30 -05:00
Kelly
8b94dc8111 Merge pull request #152 from SudoRand/main 2025-06-01 19:03:01 -07:00
SudoRand
5b26aabb00 Config for whether ollama responds to non-commands
The current behavior is that whenever ollama is enabled the LLM replies
to all non-command message. This setting allows limiting it the LLM to
run only in response to the "ask:" and "askai" commands.

Default is True to keep consistent with previous behavior.
2025-06-01 15:32:08 -06:00
SudoRand
67b3c67348 Fix bug that always enabled news_random_line_only
This looks like a simple typo that accidentally used read_news_enabled
for the news_random_line_only parameter. As a result, the
news_random_line_only setting was always treated as True (since this
line it only executed if read_news_enabled was True). Now it obeys the
configuration value.
2025-06-01 14:02:19 -06:00
SpudGunMan
860cceec59 Update locationdata.py 2025-05-28 15:20:33 -07:00
Kelly
53a0535e55 Merge pull request #149 from SpudGunMan/lab
High Altitude Alerts
2025-05-23 19:14:51 -07:00
SpudGunMan
621f4ad916 enhance 2025-05-23 19:10:15 -07:00
SpudGunMan
118857ec15 Update system.py 2025-05-21 16:52:01 -07:00
SpudGunMan
1be13be92a highfly enhancements 2025-05-21 16:43:56 -07:00
SpudGunMan
895fc3fd37 Update README.md 2025-05-21 16:36:55 -07:00
SpudGunMan
0e0bda60ad Update system.py 2025-05-21 16:36:52 -07:00
SpudGunMan
903767f4b3 Update settings.py 2025-05-21 16:36:46 -07:00
SpudGunMan
f54d362ea0 Update config.template 2025-05-21 16:36:43 -07:00
SpudGunMan
60bb68c6b5 Update system.py 2025-05-21 16:20:54 -07:00
SpudGunMan
feb9a1d9b3 FlightDetector
high alt detection
2025-05-21 16:18:46 -07:00
SpudGunMan
d055c35c96 Update install.sh 2025-05-11 13:07:52 -07:00
SpudGunMan
27820daaf4 Cron4W3 2025-05-10 15:34:33 -07:00
SpudGunMan
56e8e1c0d5 🐇🪵
config register set in config.ini for hop logs
2025-05-01 10:35:43 -07:00
SpudGunMan
4545b8f4a4 Update locationdata.py 2025-04-28 23:10:52 -07:00
SpudGunMan
6ed48d49ce Update videopoker.py
fix gameplay
2025-04-24 15:54:47 -07:00
SpudGunMan
a3a54b081d Update system.py 2025-04-23 19:34:13 -07:00
SpudGunMan
ab420af63e Update system.py 2025-04-23 09:24:51 -07:00
SpudGunMan
a55c61c47d Update web.py 2025-04-23 07:17:02 -07:00
SpudGunMan
7236f47eb7 Update README.md 2025-04-17 13:30:53 -07:00
SpudGunMan
05e11ae5f8 Update README.md 2025-04-13 10:04:15 -07:00
SpudGunMan
f8ffcc19b1 Update config.template 2025-04-13 10:04:13 -07:00
SpudGunMan
ea20eec604 Update README.md 2025-04-11 14:51:50 -07:00
SpudGunMan
d1204d2c26 ignoreEAS and USGS alert word
enhance with list to ignore words not wanted for broadcast
2025-04-11 14:32:51 -07:00
SpudGunMan
654d8b3ff7 Update README.md 2025-04-10 16:14:32 -07:00
SpudGunMan
3bf12d62b5 Update mesh_bot.py 2025-04-10 16:09:15 -07:00
SpudGunMan
0ec8613d27 Update install.sh
issues raised https://github.com/SpudGunMan/meshing-around/issues/139
2025-04-10 15:57:56 -07:00
SpudGunMan
10dd413ae7 Update config.template 2025-04-10 15:50:12 -07:00
SpudGunMan
09ac7525b3 Update mesh_bot.py 2025-04-10 15:48:47 -07:00
SpudGunMan
aac497dfa0 config.ini Scheduler enhancments
request from https://github.com/SpudGunMan/meshing-around/issues/141

enhances with a basic announcement from config.ini
2025-04-10 15:46:36 -07:00
88 changed files with 11317 additions and 2855 deletions

28
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,28 @@
---
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
assignees:
- "SpudGunMan"
labels:
- "dependencies"
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
assignees:
- "SpudGunMan"
labels:
- "dependencies"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
assignees:
- "SpudGunMan"
labels:
- "dependencies"

61
.github/workflows/docker-image.yml vendored Normal file
View File

@@ -0,0 +1,61 @@
#
name: Create and publish a Docker image on new release
# Configures this workflow to run every time a change is pushed to the branch called `release`.
on:
release:
types: [released]
workflow_dispatch:
# Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
# There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu.
jobs:
build-and-push-image:
runs-on: ubuntu-latest
# Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job.
permissions:
contents: read
packages: write
attestations: write
id-token: write
#
steps:
- name: Checkout repository
uses: actions/checkout@v5
# Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.
- name: Log in to the Container registry
uses: docker/login-action@28fdb31ff34708d19615a74d67103ddc2ea9725c
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels.
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@032a4b3bda1b716928481836ac5bfe36e1feaad6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
# This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages.
# It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see [Usage](https://github.com/docker/build-push-action#usage) in the README of the `docker/build-push-action` repository.
# It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step.
- name: Build and push Docker image
id: push
uses: docker/build-push-action@9e436ba9f2d7bcd1d038c8e55d039d37896ddc5d
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# This step generates an artifact attestation for the image, which is an unforgeable statement about where and how it was built. It increases supply chain security for people who consume the image. For more information, see [Using artifact attestations to establish provenance for builds](/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds).
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v3
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true

22
.github/workflows/greetings.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Greetings
on:
issues:
types: [opened]
pull_request:
types: [opened]
permissions:
issues: write
pull-requests: write
jobs:
greeting:
name: Greet first-time contributors
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue_message: "Dependabot's first issue"
pr_message: "Thank you for your pull request!"

12
.gitignore vendored
View File

@@ -1,5 +1,7 @@
# config
config.ini
config_new.ini
ini_merge_log.txt
# Pickle files
*.pkl
@@ -22,3 +24,13 @@ data/rag/*
# qrz db
data/qrz.db
# fileMonitor test file
bee.txt
# .csv files
*.csv
# modules/custom_scheduler.py
modules/custom_scheduler.py

View File

@@ -1,21 +1,43 @@
FROM python:3.13-slim
FROM python:3.14-slim
ENV PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y gettext tzdata locales nano && rm -rf /var/lib/apt/lists/*
ENV PYTHONUNBUFFERED=1 \
LANG=en_US.UTF-8 \
LANGUAGE=en_US:en \
LC_ALL=en_US.UTF-8 \
TZ=America/Los_Angeles
# Set the locale default to en_US.UTF-8
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \
dpkg-reconfigure --frontend=noninteractive locales && \
update-locale LANG=en_US.UTF-8
ENV LANG="en_US.UTF-8"
ENV TZ="America/Los_Angeles"
RUN apt-get update && \
apt-get install -y \
build-essential \
python3-dev \
gettext \
tzdata \
locales \
nano && \
sed -i 's/^# *\(en_US.UTF-8 UTF-8\)/\1/' /etc/locale.gen && \
locale-gen en_US.UTF-8 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install dependencies first for better caching
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r /app/requirements.txt
# Copy the rest of the application
COPY . /app
COPY config.template /app/config.ini
RUN pip install -r requirements.txt
RUN chmod +x /app/script/docker/entrypoint.sh
# Add a non-root user and switch to it
# RUN useradd -m appuser && usermod -a -G dialout appuser
# USER appuser
# Expose Meshtastic TCP API port from the host
#EXPOSE 4403
# Meshing Around Web Dashboard port
#EXPOSE 8420
ENTRYPOINT ["/bin/bash", "/app/script/docker/entrypoint.sh"]

199
INSTALL.md Normal file
View File

@@ -0,0 +1,199 @@
# INSTALL.md
## Table of Contents
- [Manual Install](#manual-install)
- [Docker Installation](#docker-installation)
- [Requirements](#requirements)
- [install.sh](#installsh)
- [Purpose](#purpose)
- [Usage](#usage)
- [What it does](#what-it-does)
- [When to use](#when-to-use)
- [Note](#note)
- [update.sh](#updatesh)
- [Purpose](#purpose-1)
- [Usage](#usage-1)
- [What it does](#what-it-does-1)
- [When to use](#when-to-use-1)
- [Note](#note-1)
- [launch.sh](#launchsh)
- [Purpose](#purpose-2)
- [How to Use](#how-to-use)
- [What it does](#what-it-does-2)
- [Note](#note-2)
---
## Manual Install
Install all required dependencies using pip:
```sh
pip install -r requirements.txt
```
Copy the configuration template and edit as needed:
```sh
cp config.template config.ini
```
---
## Docker Installation
See [script/docker/README.md](script/docker/README.md) for Docker-based setup instructions.
Docker is recommended for Windows or if you want an isolated environment.
---
## Requirements
- **Python 3.8 or later** (Python 3.13+ supported in Docker)
- All dependencies are listed in `requirements.txt` and can be installed with:
```sh
pip install -r requirements.txt
```
- To enable emoji in the Debian/Ubuntu console:
```sh
sudo apt-get install fonts-noto-color-emoji
```
- For Ollama LLM support, see the prompts during `install.sh` or visit [https://ollama.com](https://ollama.com).
---
## install.sh
### Purpose
`install.sh` automates installation, configuration, and service setup for the Meshing Around Bot project. It is designed for Linux systems (Debian/Ubuntu/Raspberry Pi and embedded devices).
### Usage
Run from the project root directory:
```sh
bash install.sh
```
To uninstall:
```sh
bash install.sh --nope
```
### What it does
- Checks for existing installations and permissions.
- Optionally moves the project to `/opt/meshing-around`.
- Installs Python and pip if missing (unless on embedded systems).
- Adds the current user (or a dedicated `meshbot` user) to necessary groups for serial and Bluetooth access.
- Copies and configures systemd service files for running the bot as a service.
- Sets up configuration files, updating latitude/longitude automatically.
- Offers to create and activate a Python virtual environment, or install dependencies system-wide.
- Installs optional components (emoji fonts, Ollama LLM) if desired.
- Sets permissions for log and data directories.
- Optionally installs and enables the bot as a systemd service.
- Provides post-installation notes and commands in `install_notes.txt`.
- Offers to reboot the system to complete setup.
### When to use
- For first-time installation of the Meshing Around Bot.
- When migrating to a new device or environment.
- After cloning or updating the repository to set up dependencies and services.
### Note
- You may be prompted for input during installation (e.g., for embedded mode, virtual environment, or optional features).
- Review and edit the script if you have custom requirements or are running on a non-standard system.
---
## update.sh
### Purpose
`update.sh` is an update and maintenance script for the Meshing Around Bot project. It automates the process of safely updating your codebase, backing up data, and merging configuration changes.
### Usage
Run from the project root directory:
```sh
bash update.sh
```
Or, after making it executable:
```sh
chmod +x update.sh
./update.sh
```
### What it does
- Stops running Mesh Bot services to prevent conflicts during update.
- Fetches and pulls the latest changes from the GitHub repository (using `git pull --rebase`).
- Handles git conflicts, offering to reset to the latest remote version if needed.
- Copies a custom scheduler template if not already present.
- Backs up the `data/` directory (and `custom_scheduler.py` if present) to a compressed archive.
- Merges your existing configuration with new defaults using `script/configMerge.py`, and logs the process.
- Restarts services if they were stopped for the update.
- Provides status messages and logs for troubleshooting.
### When to use
- To update your Mesh Bot installation to the latest version.
- Before making significant changes or troubleshooting, as it creates a backup of your data.
### Note
- Review `ini_merge_log.txt` and `config_new.ini` after running for any configuration changes or errors.
- You may be prompted if git conflicts are detected.
---
## launch.sh
### Purpose
`launch.sh` is a convenience script for starting the Mesh Bot, Pong Bot, or generating reports within the Python virtual environment. It ensures the correct environment is activated and the appropriate script is run.
### How to Use
From your project root, run one of the following commands:
- Launch Mesh Bot:
```sh
bash launch.sh mesh
```
- Launch Pong Bot:
```sh
bash launch.sh pong
```
- Generate HTML report:
```sh
bash launch.sh html
```
- Generate HTML5 report:
```sh
bash launch.sh html5
```
- Add a favorite (calls `script/addFav.py`):
```sh
bash launch.sh add
```
### What it does
- Ensures you are in the project directory.
- Copies `config.template` to `config.ini` if no config exists.
- Activates the Python virtual environment (`venv`).
- Runs the selected Python script based on your argument.
- Deactivates the virtual environment when done.
### Note
- The script requires a Python virtual environment (`venv`) to be present in the project directory.
- If `venv` is missing, the script will exit with an error message.
- Always provide an argument (`mesh`, `pong`, `html`, `html5`, or `add`) to specify what you want to launch.

529
README.md
View File

@@ -1,442 +1,144 @@
# Mesh Bot for Network Testing and BBS Activities
Welcome to the Mesh Bot project! This feature-rich bot is designed to enhance your [Meshtastic](https://meshtastic.org/docs/introduction/) network experience with a variety of powerful tools and fun features, connectivity and utility through text-based message delivery. Whether you're looking to perform network tests, send messages, or even play games, [mesh_bot.py](mesh_bot.py) has you covered.
Mesh Bot is a feature-rich Python bot designed to enhance your [Meshtastic](https://meshtastic.org/docs/introduction/) network experience. It provides powerful tools for network testing, messaging, games, and more—all via text-based message delivery. Whether you want to test your mesh, send messages, or play games, [mesh_bot.py](mesh_bot.py) has you covered.
* [Getting Started](#getting-started)
![Example Use](etc/pong-bot.jpg "Example Use")
#### TLDR
* [install.sh](INSTALL.md)
* [Configuration Guide](modules/README.md)
* [Games Help](modules/games/README.md)
## Key Features
![CodeQlBadge](https://github.com/SpudGunMan/meshing-around/actions/workflows/dynamic/github-code-scanning/codeql/badge.svg)
### Intelligent Keyword Responder
- **Automated Responses**: The bot detects keywords like "ping" and responds with "pong" in direct messages (DMs) or group channels.
- **Customizable Triggers**: Monitor group channels for specific keywords and set custom responses.
- **Emergency Response**: Monitor channels for keywords indicating emergencies and alert a wider audience.
- **New Node Hello**: Greet new nodes on the mesh with a hello message
- **Automated Responses**: Detects keywords like "ping" and replies with "pong" in direct messages (DMs) or group channels.
- **Customizable Triggers**: Monitors group channels for specific keywords and sends custom responses.
- **Emergency Detection**: Watches for emergency-related keywords and alerts a wider audience.
- **New Node Greetings**: Automatically welcomes new nodes joining the mesh.
### Network Tools
- **Build, Test Local Mesh**: Ping allow for message delivery testing with more realistic packets vs. telemetry
- **Test Node Hardware**: `test` will send incremental sized data into the radio buffer for overall length of message testing
- **Mesh Testing**: Use `ping` to test message delivery with realistic packets.
- **Hardware Testing**: The `test` command sends incrementally sized data to test radio buffer limits.
- **Network Monitoring**: Alerts for noisy nodes, tracks node locations, and suggests optimal relay placement.
### Multi Radio/Node Support
- **Simultaneous Monitoring**: Monitor up to nine networks at the same time.
- **Flexible Messaging**: send mail and messages, between networks.
- **Site Survey & Location Logging**: Use the `map` command to log your current GPS location with a custom description—ideal for site surveys, asset tracking, or mapping nodes locations. Entries are saved to a CSV file for later analysis or visualization.
### Multi-Radio/Node Support
- **Simultaneous Monitoring**: Observe up to nine networks at once.
- **Flexible Messaging**: Send mail and messages between networks.
### Advanced Messaging Capabilities
- **Mail Messaging**: Leave messages for other devices, which are sent as DMs when the device is seen.
- **Scheduler**: Schedule messages like weather updates or reminders for weekly VHF nets.
- **Store and Forward**: Replay messages with the `messages` command, and log messages locally to disk.
- **Send Mail**: Send mail to nodes using `bbspost @nodeNumber #message` or `bbspost @nodeShortName #message`.
- **BBS Linking**: Combine multiple bots to expand BBS reach.
- **E-Mail/SMS**: Send mesh-messages to E-Mail or SMS(Email) expanding visability.
- **New Node Hello**: Send a hello to any new node seen in text message.
- **Mail Messaging**: Leave messages for other devices; delivered as DMs when the device is next seen. Use `bbspost @nodeNumber #message` or `bbspost @nodeShortName #message`.
- **Message Scheduler**: Automate messages such as weather updates or net reminders.
- **Store and Forward**: Retrieve missed messages with the `messages` command; optionally log messages to disk.
- **BBS Linking**: Connect multiple bots to expand BBS coverage.
- **E-Mail/SMS Integration**: Send mesh messages to email or SMS for broader reach.
- **New Node Greetings**: Automatically greet new nodes via text.
### Interactive AI and Data Lookup
- **NOAA location Data**: Get localized weather(alerts), River Flow, and Tide information. Open-Meteo is used for wx only outside NOAA coverage.
- **Wiki Integration**: Look up data using Wikipedia results.
- **Ollama LLM AI**: Interact with the [Ollama](https://github.com/ollama/ollama/tree/main/docs) LLM AI for advanced queries and responses.
- **Satalite Pass Info**: Get passes for satalite at your location.
- **Weather, Earthquake, River, and Tide Data**: Get local alerts and info from NOAA/USGS; uses Open-Meteo for areas outside NOAA coverage.
- **Wikipedia Search**: Retrieve summaries from Wikipedia.
- **OpenWebUI, Ollama LLM Integration**: Query the [Ollama](https://github.com/ollama/ollama/tree/main/docs) AI for advanced responses. Supports RAG (Retrieval Augmented Generation) with Wikipedia/Kiwix context and [OpenWebUI](https://github.com/open-webui/open-webui) integration for enhanced AI capabilities. [LLM Readme](modules/llm.md)
- **Satellite Passes**: Find upcoming satellite passes for your location.
- **GeoMeasuring Tools**: Calculate distances and midpoints using collected GPS data; supports Fox & Hound direction finding.
### Proximity Alerts
- **Location-Based Alerts**: Get notified when members arrive back at a configured lat/long, perfect for remote locations like campsites.
- **Location-Based Alerts**: Get notified when members arrive at a configured latitude/longitude—ideal for campsites, geo-fences, or remote locations. Optionally, trigger scripts, send emails, or automate actions (e.g., change node config, turn on lights, or drop an `alert.txt` file to start a survey or game).
- **Customizable Triggers**: Use proximity events for creative applications like "king of the hill" or 🧭 geocache games by adjusting the alert cycle.
- **High Flying Alerts**: Receive notifications when nodes with high altitude are detected on the mesh.
- **Voice/Command Triggers**: Activate bot functions using keywords or voice commands (see [Voice Commands](#voice-commands-vox) for "Hey Chirpy!" support).
### CheckList / Check In Out
- **Asset Tracking**: Maintain a list of node/asset checkin and checkout. Usefull for accountability of people, assets. Radio-Net, FEMA, Trailhead.
#### Radio Frequency Monitoring
- **SNR RF Activity Alerts**: Monitor radio frequencies and receive alerts when high SNR (Signal-to-Noise Ratio) activity is detected.
- **Hamlib Integration**: Use Hamlib (rigctld) to monitor the S meter on a connected radio.
- **Speech-to-Text Broadcasting**: Convert received audio to text using [Vosk](https://alphacephei.com/vosk/models) and broadcast it to the mesh.
### Check-In / Check-Out & Asset Tracking
- **Asset Tracking**: Maintain a check-in/check-out list for nodes or assets—ideal for accountability of people and equipment (e.g., Radio-Net, FEMA, trailhead groups).
### Fun and Games
- **Built-in Games**: Enjoy games like DopeWars, Lemonade Stand, BlackJack, and VideoPoker.
- **FCC ARRL QuizBot**: The exam question pool quiz-bot.
- **Command-Based Gameplay**: Issue `games` to display help and start playing.
- **Built-in Games**: Play classic games like DopeWars, Lemonade Stand, BlackJack, and Video Poker directly via DM.
- **FCC ARRL QuizBot**: Practice for the ham radio exam with the integrated quiz bot.
- **Command-Based Gameplay**: Use the `games` command to view available games and start playing.
- **Telemetry Leaderboard**: Compete for fun stats like lowest battery or coldest temperature.
### Radio Frequency Monitoring
- **SNR RF Activity Alerts**: Monitor a radio frequency and get alerts when high SNR RF activity is detected.
- **Hamlib Integration**: Use Hamlib (rigctld) to watch the S meter on a connected radio.
#### QuizMaster
- **Group Quizzes**: Admins can start and stop quiz games for groups.
- **Player Participation**: Players join with `q: join`, leave with `q: leave`, and answer questions by prefixing their answer with `q:`, e.g., `q: 42`.
- **Scoring & Leaderboards**: Check your score with `q: score` and see the top performers with `q: top`.
- **Admin Controls**: QuizMasters (from `bbs_admin_list`) can use `q: start`, `q: stop`, and `q: broadcast <message>` to manage games.
#### Survey Module
- **Custom Surveys**: Create and manage surveys by editing JSON files in `data/survey`. Multiple surveys are supported (e.g., `survey snow`).
- **User Feedback**: Users participate via DM; responses are logged for review.
- **Reporting**: Retrieve survey results with `survey report` or `survey report <surveyname>`.
### EAS Alerts
- **FEMA iPAWS/EAS Alerts via API**: Use an internet-connected node to message Emergency Alerts from FEMA
- **NOAA EAS Alerts via API**: Use an internet-connected node to message Emergency Alerts from NOAA.
- **USGS Volcano Alerts via API**: Use an internet-connected node to message Emergency Alerts from USGS.
- **EAS Alerts over the air**: Utilizing external tools to report EAS alerts offline over mesh.
- **NINA alerts for Germany**: Emergency Alerts from xrepository.de feed
- **FEMA iPAWS/EAS Alerts**: Receive Emergency Alerts from FEMA via API on internet-connected nodes.
- **NOAA EAS Alerts**: Get Emergency Alerts from NOAA via API.
- **USGS Volcano Alerts**: Receive volcano alerts from USGS via API.
- **Offline EAS Alerts**: Report EAS alerts over the mesh using external tools, even without internet.
- **NINA Alerts (Germany)**: Receive emergency alerts from the xrepository.de feed for Germany.
### File Monitor Alerts
- **File Monitor**: Monitor a flat/text file for changes, broadcast the contents of the message to the mesh channel.
- **News File**: On request of news, the contents of the file are returned.
- **File Monitoring**: Watch a text file for changes and broadcast updates to the mesh channel.
- **News File Access**: Retrieve the contents of a news file on request; supports multiple news sources or files.
- **Shell Command Access**: Execute shell commands via DM with replay protection (admin only).
### Data Reporting
- **HTML Generator**: Visualize bot traffic and data flows with a built-in HTML generator for [data reporting](logs/README.md).
- **HTML Reports**: Visualize bot traffic and data flows with a built-in HTML generator. See [data reporting](logs/README.md) for details.
- **RSS & News Feeds**: Receive news and data from multiple sources directly on the mesh.
### Robust Message Handling
- **Message Chunking**: Automatically chunk messages over 160 characters to ensure higher delivery success across hops.
- **Automatic Message Chunking**: Messages over 160 characters are automatically split to ensure reliable delivery across multiple hops.
## Getting Started
This project is developed on Linux (specifically a Raspberry Pi) but should work on any platform where the [Meshtastic protobuf API](https://meshtastic.org/docs/software/python/cli/) modules are supported, and with any compatible [Meshtastic](https://meshtastic.org/docs/getting-started/) hardware. For pico or low-powered devices, see projects for embedding, [buildroot](https://github.com/buildroot-meshtastic/buildroot-meshtastic), also see [femtofox](https://github.com/noon92/femtofox). 🥔 Please use responsibly and follow local rulings for such equipment. This project captures packets, logs them, and handles over the air communications which can include PII such as GPS locations.
This project is developed on Linux (specifically a Raspberry Pi) but should work on any platform where the [Meshtastic protobuf API](https://meshtastic.org/docs/software/python/cli/) modules are supported, and with any compatible [Meshtastic](https://meshtastic.org/docs/getting-started/) hardware. For pico or low-powered devices, see projects for embedding, armbian or [buildroot](https://github.com/buildroot-meshtastic/buildroot-meshtastic), also see [femtofox](https://github.com/noon92/femtofox) for running on luckfox hardware. If you need a local console consider the [firefly](https://github.com/pdxlocations/firefly) project.
### Installation
🥔 Please use responsibly and follow local rulings for such equipment. This project captures packets, logs them, and handles over the air communications which can include PII such as GPS locations.
### Quick Setup
#### Clone the Repository
If you dont have git you will need it `sudo apt-get install git`
```sh
git clone https://github.com/spudgunman/meshing-around
```
The code is under active development, so make sure to pull the latest changes regularly!
- **Automated Installation**: [install.sh](INSTALL.md) will automate optional venv and requirements installation.
- **Launch Script**: [laynch.sh](INSTALL.md) only used in a venv install, to launch the bot and the report generator.
#### Quick setup
- **Automated Installation**: `install.sh` will automate optional venv and requirements installation.
- **Launch Script**: `launch.sh` only used in a venv install, to launch the bot and the report generator.
#### Docker Installation
### Docker Installation - Good for Windows!
See further info on the [docker.md](script/docker/README.md)
#### Manual Install
Install the required dependencies using pip:
```sh
pip install -r requirements.txt
```
## Full list of commands for the bot
[modules/README.md](modules/README.md)
Copy the configuration template to `config.ini` and edit it to suit your needs:
```sh
cp config.template config.ini
```
### Games (via DM only)
[modules/games/README.md](modules/games/README.md)
### Configuration Guide
The following is documentation for the config.ini file
### Firmware 2.6 DM Key, and 2.7 CLIENT_BASE Favorite Nodes
Firmware 2.6 introduced [PKC](https://meshtastic.org/blog/introducing-new-public-key-cryptography-in-v2_5/), enabling secure private messaging by adding necessary keys to each node. To fully utilize this feature, you should add favorite nodes—such as BBS admins—to your nodes favorites list to ensure their keys are retained. A helper script is provided to simplify this process:
- Run the helper script from the main program directory: `python3 script/addFav.py`
- By default, this script adds nodes from `bbs_admin_list` and `bbslink_whitelist`
- If using a virtual environment, run: `launch.sh addfav`
- The API will not work-fully today to set nodes this is a WIP
If you have not done so, or want to 'factory reset', copy the [config.template](config.template) to `config.ini` and set the appropriate interface for your method (serial/ble/tcp). While BLE and TCP will work, they are not as reliable as serial connections. There is a watchdog to reconnect TCP if possible. To get the BLE MAC address, use:
```sh
meshtastic --ble-scan
```
Additionally, you can just DM a bot to "auto favorite." If your node is set to not be messageable, DMs won't work—be advised.
**Note**: The code has been tested with a single BLE device and is written to support only one BLE port.
```ini
# config.ini
# type can be serial, tcp, or ble.
# port is the serial port to use; commented out will try to auto-detect
# hostname is the IP address of the device to connect to for TCP type
# mac is the MAC address of the device to connect to for BLE type
[interface]
type = serial
# port = '/dev/ttyUSB0'
# hostname = 192.168.0.1
# mac = 00:11:22:33:44:55
# Additional interface for dual radio support. See config.template for more.
[interface2]
enabled = False
```
### General Settings
The following settings determine how the bot responds. By default, the bot will not spam the default channel. Setting `respond_by_dm_only` to `True` will force all messages to be sent via DM, which may not be desired. Setting it to [`False`] will allow responses in the channel for all to see. If you have no default channel you can set this value to `-1` or any unused channel index. You can also have the bot ignore the defaultChannel for any commands, but still observe the channel.
```ini
To configure favorite nodes, add their numbers to your config file:
```conf
[general]
respond_by_dm_only = True
defaultChannel = 0
ignoreDefaultChannel = False # ignoreDefaultChannel, the bot will ignore the default channel set above
ignoreChannels = # ignoreChannels is a comma separated list of channels to ignore, e.g. 4,5
cmdBang = False # require ! to be the first character in a command
```
### Location Settings
The weather forecasting defaults to NOAA, for locations outside the USA, you can set `UseMeteoWxAPI` to `True`, to use a global weather API. The `lat` and `lon` are default values when a node has no location data, as well as the default for all NOAA, repeater lookup. It is also the center of radius for Sentry.
```ini
[location]
enabled = True
lat = 48.50
lon = -123.0
UseMeteoWxAPI = True
riverListDefault = # NOAA Hydrology data, unique identifiers, LID or USGS ID
```
### Module Settings
Modules can be enabled or disabled as needed. They are essentally larger functions of code which you may not want on your mesh or in memory space.
```ini
[bbs]
enabled = False
[general]
DadJokes = False
StoreForward = False
```
### History
The history command shows the last commands the user ran, and [`lheard`] reflects the last users on the bot.
```ini
enableCmdHistory = True # history command enabler
lheardCmdIgnoreNodes = # command history ignore list ex: 2813308004,4258675309
```
### Sentry Settings
Sentry Bot detects anyone coming close to the bot-node. uses the Location Lat/Lon value.
```ini
SentryEnabled = True # detect anyone close to the bot
emailSentryAlerts = True # if SMTP enabled send alert to sysop email list
SentryRadius = 100 # radius in meters to detect someone close to the bot
SentryChannel = 9 # holdoff time multiplied by seconds(20) of the watchdog
SentryHoldoff = 2 # channel to send a message to when the watchdog is triggered
sentryIgnoreList = # list of ignored nodes numbers ex: 2813308004,4258675309
```
### E-Mail / SMS Settings
To enable connectivity with SMTP allows messages from meshtastic into SMTP. The term SMS here is for connection via [carrier email](https://avtech.com/articles/138/list-of-email-to-sms-addresses/)
```ini
[smtp]
# enable or disable the SMTP module, minimum required for outbound notifications
enableSMTP = True # enable or disable the IMAP module for inbound email, not implimented yet
enableImap = False # list of Sysop Emails seperate with commas, used only in emergemcy responder currently
sysopEmails =
# See config.template for all the SMTP settings
SMTP_SERVER = smtp.gmail.com
SMTP_AUTH = True
EMAIL_SUBJECT = Meshtastic✉
```
### Emergency Response Handler
Traps the following ("emergency", "911", "112", "999", "police", "fire", "ambulance", "rescue") keywords. Responds to the user, and calls attention to the text message in logs and via another network or channel.
```ini
[emergencyHandler]
enabled = True # enable or disable the emergency response handler
alert_channel = 2 # channel to send a message to when the emergency handler is triggered
alert_interface = 1
```
### EAS Alerting
To Alert on Mesh with the EAS API you can set the channels and enable, checks every 20min.
#### FEMA iPAWS/EAS and NINA
This uses USA: SAME, FIPS, ZIP code to locate the alerts in the feed. By default ignoring Test messages.
```ini
eAlertBroadcastEnabled = False # Goverment IPAWS/CAP Alert Broadcast
eAlertBroadcastCh = 2,3 # Goverment Emergency IPAWS/CAP Alert Broadcast Channels
ignoreFEMAenable = True # Ignore any headline that includes followig word list
ignoreFEMAwords = test,exercise
# comma separated list of codes (e.g., SAME,FIPS,ZIP) trigger local alert.
# find your SAME https://www.weather.gov/nwr/counties
mySAME = 053029,053073
# To use other country services enable only a single optional serivce
enableDEalerts = False # Use DE Alert Broadcast Data see template for filters
```
#### NOAA EAS
This uses the defined lat-long of the bot for collecting of data from the API. see [File-Monitoring](#File-Monitoring) for ideas to collect EAS alerts from a RTL-SDR.
```ini
# EAS Alert Broadcast
wxAlertBroadcastEnabled = True
# EAS Alert Broadcast Channels
wxAlertBroadcastCh = 2,4
```
### Repeater Settings
A repeater function for two different nodes and cross-posting messages. The `repeater_channels` is a list of repeater channels that will be consumed and rebroadcast on the same number channel on the other device, node, or interface. Each node should have matching channel numbers. The channel names and PSK do not need to be the same on the nodes. Use this feature responsibly to avoid creating a feedback loop.
```ini
[repeater] # repeater module
enabled = True
repeater_channels = [2, 3]
```
### Ollama (LLM/AI) Settings
For Ollama to work, the command line `ollama run 'model'` needs to work properly. Ensure you have enough RAM and your GPU is working as expected. The default model for this project is set to `gemma2:2b`. Ollama can be remote [Ollama Server](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-do-i-configure-ollama-server) works on a pi58GB with 40 second or less response time.
```ini
# Enable ollama LLM see more at https://ollama.com
ollama = True # Ollama model to use (defaults to gemma2:2b)
ollamaModel = gemma2 #ollamaModel = llama3.1
ollamaHostName = http://localhost:11434 # server instance to use (defaults to local machine install)
```
Also see `llm.py` for changing the defaults of:
```ini
# LLM System Variables
llmEnableHistory = True # enable history for the LLM model to use in responses adds to compute time
llmContext_fromGoogle = True # enable context from google search results helps with responses accuracy
googleSearchResults = 3 # number of google search results to include in the context more results = more compute time
```
Note for LLM in docker with [NVIDIA](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/docker-specialized.html). Needed for the container with ollama running.
### Radio Monitoring
A module allowing a Hamlib compatible radio to connect to the bot. When functioning, it will message the configured channel with a message of in use. **Requires hamlib/rigctld to be running as a service.**
```ini
[radioMon]
enabled = True
rigControlServerAddress = localhost:4532
sigWatchBroadcastCh = 2 # channel to broadcast to can be 2,3
signalDetectionThreshold = -10 # minimum SNR as reported by radio via hamlib
signalHoldTime = 10 # hold time for high SNR
signalCooldown = 5 # the following are combined to reset the monitor
signalCycleLimit = 5
```
### File Monitoring
Some dev notes for ideas of use
```ini
[fileMon]
filemon_enabled = True
file_path = alert.txt
broadcastCh = 2,4
enable_read_news = False
news_file_path = news.txt
news_random_line = False # only return a single random line from the news file
enable_runShellCmd = False # enables running of bash commands runShell.sh demo for sysinfo
```
#### Offline EAS
To Monitor EAS with no internet connection see the following notes
- [samedec](https://crates.io/crates/samedec) rust decoder much like multimon-ng
- [sameold](https://crates.io/crates/sameold) rust SAME message translator much like EAS2Text and dsame3
no examples yet for these tools
- [EAS2Text](https://github.com/A-c0rN/EAS2Text)
- depends on [multimon-ng](https://github.com/EliasOenal/multimon-ng), [direwolf](https://github.com/wb2osz/direwolf), [samedec](https://crates.io/crates/samedec) rust decoder much like multimon-ng
- [dsame3](https://github.com/jamieden/dsame3)
- has a sample .ogg file for testing alerts
The following example shell command can pipe the data using [etc/eas_alert_parser.py](etc/eas_alert_parser.py) to alert.txt
```bash
sox -t ogg WXR-RWT.ogg -esigned-integer -b16 -r 22050 -t raw - | multimon-ng -a EAS -v 1 -t raw - | python eas_alert_parser.py
```
The following example shell command will pipe rtl_sdr to alert.txt
```bash
rtl_fm -f 162425000 -s 22050 | multimon-ng -t raw -a EAS /dev/stdin | python eas_alert_parser.py
```
#### Newspaper on mesh
a newspaper could be built by external scripts. could use Ollama to compile text via news web pages and write news.txt
### Greet new nodes QRZ module
This isnt QRZ.com this is Q code for who is calling me, this will track new nodes and say hello
```ini
[qrz]
enabled = True # QRZ Hello to new nodes
qrz_hello_string = "send CMD or DM me for more info." # will be sent to all heard nodes once
training = True # Training mode will not send the hello message to new nodes, use this to build up database
```
### Scheduler
In the config.ini enable the module
```ini
[scheduler]
# enable or disable the scheduler module
enabled = True
```
The actions are via code only at this time. See mesh_bot.py around line [1097](https://github.com/SpudGunMan/meshing-around/blob/e94581936530c76ea43500eebb43f32ba7ed5e19/mesh_bot.py#L1097) to edit the schedule. See [schedule documentation](https://schedule.readthedocs.io/en/stable/) for more. Recomend to backup changes so they dont get lost.
```python
#Send WX every Morning at 08:00 using handle_wxc function to channel 2 on device 1
schedule.every().day.at("08:00").do(lambda: send_message(handle_wxc(0, 1, 'wx'), 2, 0, 1))
#Send a Net Starting Now Message Every Wednesday at 19:00 using send_message function to channel 2 on device 1
schedule.every().wednesday.at("19:00").do(lambda: send_message("Net Starting Now", 2, 0, 1))
```
#### BBS Link
The scheduler also handles the BBS Link Brodcast message, this would be an esxample of a mesh-admin channel on 8 being used to pass BBS post traffic between two bots as the initator, one direction pull.
```python
# Send bbslink looking for peers every other day at 10:00 using send_message function to channel 8 on device 1
schedule.every(2).days.at("10:00").do(lambda: send_message("bbslink MeshBot looking for peers", 8, 0, 1))
```
```ini
bbslink_enabled = True
bbslink_whitelist = # list of whitelisted nodes numbers ex: 2813308004,4258675309 empty list allows all
favoriteNodeList = # list of favorite nodes numbers ex: 2813308004,4258675309 used by script/addFav.py
```
### MQTT Notes
There is no direct support for MQTT in the code, however, reports from Discord are that using [meshtasticd](https://meshtastic.org/docs/hardware/devices/linux-native-hardware/) with no radio and attaching the bot to the software node, which is MQTT-linked, allows routing. Tested working fully Firmware:2.5.15.79da236 with [mosquitto](https://meshtastic.org/docs/software/integrations/mqtt/mosquitto/).
There is no direct support for MQTT in the code, however, reports from Discord are that using [meshtasticd](https://meshtastic.org/docs/hardware/devices/linux-native-hardware/) with no radio and attaching the bot to the software node, which is MQTT-linked, allows routing. Tested working fully Firmware:2.6.11 with [mosquitto](https://meshtastic.org/docs/software/integrations/mqtt/mosquitto/).
~~There also seems to be a quicker way to enable MQTT by having your bot node with the enabled [serial](https://meshtastic.org/docs/configuration/module/serial/) module with echo enabled and MQTT uplink and downlink. These two~~
## Full list of commands for the bot
### Networking
| Command | Description | ✅ Works Off-Grid |
|---------|-------------|-
| `ping`, `ack` | Return data for signal. Example: `ping 15 #DrivingI5` (activates auto-ping every 20 seconds for count 15) | ✅ |
| `cmd` | Returns the list of commands (the help message) | ✅ |
| `history` | Returns the last commands run by user(s) | ✅ |
| `lheard` | Returns the last 5 heard nodes with SNR. Can also use `sitrep` | ✅ |
| `motd` | Displays the message of the day or sets it. Example: `motd $New Message Of the day` | ✅ |
| `sysinfo` | Returns the bot node telemetry info | ✅ |
| `test` | used to test the limits of data transfer `test 4` sends data to the maxBuffer limit (default 220) | ✅ |
| `whereami` | Returns the address of the sender's location if known |
| `whoami` | Returns details of the node asking, also returned when position exchanged 📍 | ✅ |
| `whois` | Returns details known about node, more data with bbsadmin node | ✅ |
### Radio Propagation & Weather Forcasting
| Command | Description | |
|---------|-------------|-------------------
| `ea` and `ealert` | Return FEMA iPAWS/EAS alerts in USA or DE Headline or expanded details for USA | |
| `hfcond` | Returns a table of HF solar conditions | |
| `rlist` | Returns a table of nearby repeaters from RepeaterBook | |
| `riverflow` | Return information from NOAA for river flow info. Example: `riverflow modules/settings.py`| |
| `solar` | Gives an idea of the x-ray flux | |
| `sun` and `moon` | Return info on rise and set local time | ✅ |
| `tide` | Returns the local tides (NOAA data source) | |
| `valert` | Returns USGS Volcano Data | |
| `wx` and `wxc` | Return local weather forecast (wxc is metric value), NOAA or Open Meteo for weather forecasting | |
| `wxa` and `wxalert` | Return NOAA alerts. Short title or expanded details | |
### Bulletin Board & Mail
| Command | Description | |
|---------|-------------|-
| `bbshelp` | Returns the following help message | ✅ |
| `bbslist` | Lists the messages by ID and subject | ✅ |
| `bbsread` | Reads a message. Example: `bbsread #1` | ✅ |
| `bbspost` | Posts a message to the public board or sends a DM(Mail) Examples: `bbspost $subject #message`, `bbspost @nodeNumber #message`, `bbspost @nodeShortName #message` | ✅ |
| `bbsdelete` | Deletes a message. Example: `bbsdelete #4` | ✅ |
| `bbsinfo` | Provides stats on BBS delivery and messages (sysop) | ✅ |
| `bbslink` | Links Bulletin Messages between BBS Systems | ✅ |
| `email:` | Sends email to address on file for the node or `email: bob@test.net # hello from mesh` | |
| `sms:` | Send sms-email to multiple address on file | |
| `setemail`| Sets the email for easy communciations | |
| `setsms` | Adds the SMS-Email for quick communications | |
| `clearsms` | Clears all SMS-Emails on file for node | |
### Data Lookup
| Command | Description | |
|---------|-------------|-
| `askai` and `ask:` | Ask Ollama LLM AI for a response. Example: `askai what temp do I cook chicken` | ✅ |
| `messages` | Replays the last messages heard, like Store and Forward | ✅ |
| `readnews` | returns the contents of a file (news.txt, by default) via the chunker on air | ✅ |
| `satpass` | returns the pass info from API for defined NORAD ID in config or Example: `satpass 25544,33591`| |
| `wiki:` | Searches Wikipedia and returns the first few sentences of the first result if a match. Example: `wiki: lora radio` |
### CheckList
| Command | Description | |
|---------|-------------|-
| `checkin` | Check in the node to the checklist database, you can add a note like `checkin ICO` or `checkin radio4` | ✅ |
| `checkout` | Checkout the node in the checklist database, checkout all from node | ✅ |
| `checklist` | Display the checklist database, with note | ✅ |
### Games (via DM)
| Command | Description | |
|---------|-------------|-
| `blackjack` | Plays Blackjack (Casino 21) | ✅ |
| `dopewars` | Plays the classic drug trader game | ✅ |
| `golfsim` | Plays a 9-hole Golf Simulator | ✅ |
| `hamtest` | FCC/ARRL Quiz `hamtest general` or `hamtest extra` and `score` | ✅ |
| `hangman` | Plays the classic word guess game | ✅ |
| `joke` | Tells a joke | ✅ |
| `lemonstand` | Plays the classic Lemonade Stand finance game | ✅ |
| `mastermind` | Plays the classic code-breaking game | ✅ |
| `videopoker` | Plays basic 5-card hold Video Poker | ✅ |
# Recognition
I used ideas and snippets from other responder bots and want to call them out!
@@ -456,53 +158,20 @@ I used ideas and snippets from other responder bots and want to call them out!
- ARRL Question Pool Data from https://github.com/russolsen/ham_radio_question_pool
### Special Thanks
- **xdep**: For the reporting tools.
- **Nestpebble**: For new ideas and enhancements.
- **mrpatrick1991**: For Docker configurations.
- **[https://github.com/A-c0rN](A-c0rN)**: Assistance with iPAWS and EAS
For testing and feature ideas on Discord and GitHub, if its stable its thanks to you all.
- **PiDiBi, Cisien, bitflip, nagu, Nestpebble, NomDeTom, Iris, Josh, GlockTuber, FJRPiolt, dj505, Woof, propstg, snydermesh, trs2982, F0X, Malice, mesb1, Hailo1999**
- **xdep**: For the reporting html. 📊
- **mrpatrick1991**: For OG Docker configurations. 💻
- **[https://github.com/A-c0rN](A-c0rN)**: Assistance with iPAWS and 🚨
- **Mike O'Connell/skrrt**: For [eas_alert_parser](etc/eas_alert_parser.py) enhanced by **sheer.cold**
- **PiDiBi**: For looking at test functions and other suggestions like wxc, CPU use, and alerting ideas.
- **WH6GXZ nurse dude**: For bashing on installer, Volcano Alerts 🌋
- **Josh**: For more bashing on installer!
- **dj505**: trying it on windows!
- **mikecarper**: ideas, and testing. hamtest
- **Cisien, bitflip, **Woof**, **propstg**, **trs2982**, **Josh** and Hailo1999**: For testing and feature ideas on Discord and GitHub.
- **Meshtastic Discord Community**: For tossing out ideas and testing code.
- **WH6GXZ nurse dude**: Volcano Alerts 🌋
- **mikecarper**: hamtest, leading to quiz etc.. 📋
- **c.merphy360**: high altitude alerts. 🚀
- **G7KSE**: DX Spotting idea. 📻
- **Growing List of GitHub Contributers**
- **Meshtastic Discord Community**: For putting up with 🥔
### Tools
- **Node Backup Management**: [Node Slurper](https://github.com/SpudGunMan/node-slurper)
### Requirements
Python 3.8? or later is needed (docker on 3.13). The following can be installed with `pip install -r requirements.txt` or using the [install.sh](install.sh) script for venv and automation:
```sh
pip install meshtastic
pip install pubsub
```
Mesh-bot enhancements:
```sh
pip install pyephem
pip install requests
pip install geopy
pip install maidenhead
pip install beautifulsoup4
pip install dadjokes
pip install schedule
pip install wikipedia
```
For the Ollama LLM:
```sh
pip install googlesearch-python
```
To enable emoji in the Debian console, install the fonts:
```sh
sudo apt-get install fonts-noto-color-emoji
```
Meshtastic® is a registered trademark of Meshtastic LLC. Meshtastic software components are released under various licenses, see GitHub for details. No warranty is provided - use at your own risk.

14
SECURITY.md Normal file
View File

@@ -0,0 +1,14 @@
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| git pull| :white_check_mark: |
## Reporting a Vulnerability
If its serious, its likley big. otherwise post issues, reachout on discord.

71
compose.yaml Normal file
View File

@@ -0,0 +1,71 @@
services:
meshing-around:
ports:
- 8420:8420
#devices:
#- /dev/ttyUSB0:/dev/tty #update your config.ini to /dev/tty
#- /dev/ttyACM0:/dev/tty #if using serial select proper port
volumes:
- .:/app:rw
image: ghcr.io/spudgunman/meshing-around:main
container_name: meshing-around
restart: unless-stopped
environment:
- OLLAMA_API_URL=http://ollama:11434
extra_hosts:
- "host.docker.internal:host-gateway"
#user: "1000:1000"
#user: "10999:10999"
networks:
- meshing-around-network
test-bot:
image: ghcr.io/spudgunman/meshing-around:main
container_name: test-bot
command: ["/bin/bash", "-c", "python3 modules/test_bot.py | tee /tmp/test_tmp.txt; if grep -E 'failures=|errors=' /tmp/test_tmp.txt; then cp /tmp/test_tmp.txt /app/test_results.txt; fi"]
volumes:
- .:/app:rw
networks:
- meshing-around-network
stdin_open: true
debug-console:
image: ghcr.io/spudgunman/meshing-around:main
container_name: debug-console
command: ["/bin/bash"]
stdin_open: true
tty: true
volumes:
- .:/app:rw
networks:
- meshing-around-network
meshtasticd:
ports:
- 4403:4403
- 443:443
volumes:
- ./script/docker:/etc/meshtasticd:rw
restart: unless-stopped
container_name: meshtasticd
image: meshtastic/meshtasticd:daily-debian
networks:
- meshing-around-network
ollama:
ports:
- 11434:11434
container_name: ollama
image: ollama/ollama:latest
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:11434/api/tags"]
interval: 30s
timeout: 10s
retries: 5
networks:
- meshing-around-network
networks:
meshing-around-network:
external: true

View File

@@ -1,7 +1,7 @@
#config.ini
# type can be serial, tcp, or ble
# port is the serial port to use, commented out will try to auto-detect
# hostname is the IP address of the device to connect to for tcp type
# hostname is the IP/DNS and port for tcp type default is host:4403
# mac is the MAC address of the device to connect to for ble type
[interface]
@@ -36,6 +36,10 @@ ignoreDefaultChannel = False
ignoreChannels =
# require ! to be the first character in a command
cmdBang = False
# require explicit command, the message will only be processed if it starts with a command word
explicitCmd = True
# list of favorite nodes numbers ex: 2813308004,4258675309 used by script/addFav.py
favoriteNodeList =
# motd is reset to this value on boot
motd = Thanks for using MeshBOT! Have a good day!
@@ -51,19 +55,53 @@ DadJokesEmoji = False
# enable or disable the Solar module
spaceWeather = True
# enable or disable the RSS module, and truncate the story
rssEnable = True
rssFeedURL = http://www.hackaday.com/rss.xml,http://rss.slashdot.org/Slashdot/slashdotMain,http://www.reddit.com/r/meshtastic/.rss
# RSS feed names must match the order of the URLs above, default is used if no match
rssFeedNames = default,slashdot,mesh
rssMaxItems = 3
rssTruncate = 100
# enable or disable the wikipedia search module
wikipedia = True
# Use local Kiwix server instead of online Wikipedia
# Set to False to use online Wikipedia, or provide Kiwix server URL
useKiwixServer = False
# Kiwix server URL (e.g., http://127.0.0.1:8080)
kiwixURL = http://127.0.0.1:8080
# Kiwix library name (e.g., wikipedia_en_100_nopic_2025-09)
kiwixLibraryName = wikipedia_en_100_nopic_2025-09
# Enable ollama LLM see more at https://ollama.com
ollama = False
# Ollama model to use (defaults to gemma2:2b)
# ollamaModel = llama3.1
# Ollama model to use (defaults to gemma3:270m) gemma2 is good for older SYSTEM prompt
# ollamaModel = gemma3:latest
# ollamaModel = gemma2:2b
# server instance to use (defaults to local machine install)
ollamaHostName = http://localhost:11434
# Produce LLM replies to messages that aren't commands?
# If False, the LLM only replies to the "ask:" and "askai" commands.
llmReplyToNonCommands = True
# if True, the input is sent raw to the LLM, if False uses SYSTEM prompt
rawLLMQuery = True
# Enable Wikipedia/Kiwix integration with LLM for RAG (Retrieval Augmented Generation)
# When enabled, LLM will automatically search Wikipedia/Kiwix and include context in responses
llmUseWikiContext = False
# Use OpenWebUI instead of direct Ollama API (enables advanced RAG features)
useOpenWebUI = False
# OpenWebUI server URL (e.g., http://localhost:3000)
openWebUIURL = http://localhost:3000
# OpenWebUI API key/token (required when useOpenWebUI is True)
openWebUIAPIKey =
# StoreForward Enabled and Limits
StoreForward = True
StoreLimit = 3
reverseSF = False
# history command
enableCmdHistory = True
@@ -73,7 +111,7 @@ lheardCmdIgnoreNodes =
# 24 hour clock
zuluTime = False
# wait time for URL requests
urlTimeout = 10
urlTimeout = 15
# logging to file of the non Bot messages
LogMessagesToFile = False
@@ -84,6 +122,14 @@ sysloglevel = DEBUG
# Number of log files to keep in days, 0 to keep all
log_backup_count = 32
#Do not retry enabling interface if it fails, just exit to let OS restart the bot
dont_retry_disconnect = False
#echo command, will echo back your message as the bot
enableEcho = False
# command will only echo 1:1 if sent on this channel, otherwise it will prepend @yourname
echoChannel = 9
[emergencyHandler]
# enable or disable the emergency response handler
enabled = False
@@ -94,15 +140,41 @@ alert_interface = 1
[sentry]
# detect anyone close to the bot
SentryEnabled = True
# device interface and channel to send the alert message to
SentryInterface = 1
SentryChannel = 2
emailSentryAlerts = False
# Enable detection sensor alert, requires external GPIO sensor connected to node
detectionSensorAlert = False
# list of ignored nodes numbers ex: 2813308004,4258675309
sentryIgnoreList =
# list of watched nodes numbers ex: 2813308004,4258675309
sentryWatchList =
# radius in meters to detect someone close to the bot
SentryRadius = 100
# channel to send a message to when the watchdog is triggered
SentryChannel = 2
# holdoff time multiplied by seconds(20) of the watchdog
SentryHoldoff = 9
# list of ignored nodes numbers ex: 2813308004,4258675309
sentryIgnoreList =
# Enable running external shell command when sentry alert is triggered
cmdShellSentryAlerts = False
# External shell command to run when sentry alert is triggered
sentryAlertNear = sentry_alert_near.sh
sentryAlertAway = sentry_alert_away.sh
# HighFlying Node alert
highFlyingAlert = True
# Altitude in meters to trigger the alert
highFlyingAlertAltitude = 2000
# check with OpenSkyNetwork if highfly detected for aircraft
highflyOpenskynetwork = True
# Channel to send Alert when the high flying node is detected
highFlyingAlertInterface = 1
# to disable OTA alert set to unused channel like 9
highFlyingAlertChannel = 2
# list of nodes numbers to ignore high flying alert ex: 2813308004,4258675309
highFlyingIgnoreList =
[bbs]
enabled = True
@@ -113,18 +185,22 @@ bbs_admin_list =
# enable bbs synchronization with other nodes
bbslink_enabled = False
# list of whitelisted nodes numbers ex: 2813308004,4258675309 empty list allows all
bbslink_whitelist =
bbslink_whitelist =
# enable API script access (increases disk i/o)
bbsAPI_enabled = False
# location module
[location]
enabled = True
lat = 48.50
lon = -123.0
fuzzConfigLocation = True
fuzzItAll = False
# Default to metric units rather than imperial
useMetric = False
# repeaterList lookup location (rbook / artsci)
# repeaterList lookup location (rbook / artsci / False)
repeaterLookup = rbook
# NOAA weather forecast days
@@ -135,11 +211,25 @@ NOAAalertCount = 2
# use Open-Meteo API for weather data not NOAA useful for non US locations
UseMeteoWxAPI = False
# NOAA Hydrology unique identifiers, LID or USGS ID
riverListDefault =
# NOAA Coastal Data Enable NOAA Coastal Waters Forecasts and Tide
coastalEnabled = False
# Find the correct costal weather directory at https://tgftp.nws.noaa.gov/data/forecasts/marine/coastal/
# pz = Puget Sound, ph = Honolulu HI, gm = Florida Keys, pk = Alaska
# this map can help https://www.weather.gov/marine select location and then look at the 'Forecast-by-Zone Map'
# myCoastalZone is the .txt file with the forecast data
myCoastalZone = https://tgftp.nws.noaa.gov/data/forecasts/marine/coastal/pz/pzz135.txt
# number of data points to return, default is 3
coastalForecastDays = 3
# NOAA USGS Hydrology river identifiers, LID or USGS ID https://waterdata.usgs.gov 12484500 Columbia River at The Dalles, OR
# for multiple rivers use comma separated list e.g. 12484500,14105700
riverList =
# NOAA EAS Alert Broadcast
wxAlertBroadcastEnabled = False
# Enable Ignore any message that includes following word list
ignoreEASenable = False
ignoreEASwords = test,advisory
# EAS Alert Broadcast Channels
wxAlertBroadcastCh = 2
# Add extra location to the weather alert
@@ -147,20 +237,22 @@ enableExtraLocationWx = False
# Goverment Alert Broadcast defaults to FEMA IPAWS
eAlertBroadcastEnabled = False
# comma separated list of FIPS codes to trigger local alert. find your FIPS codes at https://en.wikipedia.org/wiki/Federal_Information_Processing_Standard_state_code
myFIPSList = 57,58,53
# find your SAME https://www.weather.gov/nwr/counties comma separated list of SAME code to further refine local alert.
mySAMEList = 053029,053073
# Goverment Alert Broadcast Channels
eAlertBroadcastCh = 2
# FEMA Alert Broadcast Settings
# Enable Ignore any headline that includes followig word list
# Enable Ignore, headline that includes following word list
ignoreFEMAenable = True
ignoreFEMAwords = test,exercise
# comma separated list of codes (e.g., SAME,FIPS,ZIP) trigger local alert.
# find your SAME https://www.weather.gov/nwr/counties
mySAME = 053029,053073
# USGS Volcano alerts Enable USGS Volcano Alert Broadcast
volcanoAlertBroadcastEnabled = False
volcanoAlertBroadcastCh = 2
# Enable Ignore any message that includes following word list
ignoreUSGSEnable = False
ignoreUSGSWords = test,advisory
# Use DE Alert Broadcast Data
enableDEalerts = False
@@ -169,7 +261,7 @@ enableDEalerts = False
myRegionalKeysDE = 110000000000,120510000000
# Satalite Pass Prediction
# Register for free API https://www.n2yo.com/login/
# Register for free API https://www.n2yo.com/login/ personal data page at bottom 'Are you developer?'
n2yoAPIKey =
# NORAD list https://www.n2yo.com/satellites/
satList = 25544,7530
@@ -184,7 +276,7 @@ reverse_in_out = False
# QRZ Hello to new nodes with message
enabled = False
qrz_db = data/qrz.db
qrz_hello_string = "send CMD or DM me for more info."
qrz_hello_string = "MeshBot says Hello! DM for more info."
# Training mode will not send the hello message to new nodes
training = True
@@ -200,12 +292,30 @@ repeater_channels =
[scheduler]
# enable or disable the scheduler module
enabled = False
# interface to send the message to
interface = 1
# channel to send the message to
channel = 2
message = "MeshBot says Hello! DM for more info."
# enable overides the above and uses the motd as the message
schedulerMotd = False
# value can be min,hour,day,mon,tue,wed,thu,fri,sat,sun.
# value can also be 'joke' (min/interval) or 'weather' (time/day) or 'link' (hour/interval) for special auto messages
# 'custom' for module/scheduler.py custom schedule examples
value =
# interval to use when time is not set (e.g. every 2 days)
interval =
# time of day in 24:00 hour format when value is 'day' and interval is not set
time =
[radioMon]
# using Hamlib rig control will monitor and alert on channel use
enabled = False
rigControlServerAddress = localhost:4532
# broadcast to all nodes on the channel can also be = 2,3
dxspotter_enabled = True
# device interface to send the message to
sigWatchBroadcastInterface = 1
# broadcast channel can also be a comma separated list of channels
sigWatchBroadcastCh = 2
# minimum SNR as reported by radio via hamlib
signalDetectionThreshold = -10
@@ -214,17 +324,40 @@ signalHoldTime = 10
# the following are combined to reset the monitor
signalCooldown = 5
signalCycleLimit = 5
# enable VOX detection using default input
voxDetectionEnabled = False
# description to use in the alert message
voxDescription = VOX
useLocalVoxModel = False
voxLanguage = en-us
voxInputDevice = default
voxOnTrapList = True
voxTrapList = chirpy
voxEnableCmd = True
[fileMon]
filemon_enabled = False
# text file to monitor for changes
file_path = alert.txt
# channel to send the message to can be 2,3 multiple channels comma separated
broadcastCh = 2
# news command will return the contents of a text file
enable_read_news = False
news_file_path = news.txt
news_file_path = ../data/news.txt
# only return a single random line from the news file
news_random_line = False
# enable the use of exernal shell commands
# enable the use of exernal shell commands, this enables some data in `sysinfo`
enable_runShellCmd = False
# if runShellCmd and you think it is safe to allow the x: command to run
# direct shell command handler the x: command in DMs
allowXcmd = False
# Enable 2 factor authentication for x: commands
2factor_enabled = True
# time in seconds to wait for the correct 2FA answer
2factor_timeout = 100
[smtp]
# enable or disable the SMTP module
@@ -255,6 +388,7 @@ IMAP_FOLDER = inbox
[games]
# if hop limit for the user exceeds this value, the message will be dropped
game_hop_limit = 5
disable_emojis = False
# enable or disable the games module(s)
dopeWars = True
lemonade = True
@@ -264,17 +398,40 @@ mastermind = True
golfsim = True
hangman = True
hamtest = True
tictactoe = True
wordOfTheDay = True
# enable or disable the quiz game module questions are in data/quiz.json
quiz = False
# enable or disable the survey game module questions are in data/survey/*_survey.json
survey = False
# this is the default survey to use when command givcen, from data/survey/example_survey.json
defaultSurvey = example
# Whether to record user ID in responses
surveyRecordID=True
# Whether to record location on start of survey
surveyRecordLocation=True
[messagingSettings]
# delay in seconds for response to avoid message collision
responseDelay = 1.2
# delay in seconds for splits in messages to avoid message collision
splitDelay = 0.0
# message chunk size for sending at high success rate, chunkr allows exceeding by 3 characters
# delay in seconds for response to avoid message collision /throttling
responseDelay = 2.2
# delay in seconds for splits in messages to avoid message collision /throttling
splitDelay = 2.5
# message chunk size in charcters, chunkr allows exceeding by 3 characters
MESSAGE_CHUNK_SIZE = 160
# Request Acknowledgement of message OTA
wantAck = False
# Max limit buffer for radio testing. 233 is hard limit 2.5+ firmware
# Max limit buffer for radio testing in bytes
maxBuffer = 200
#Enable Extra logging of Hop count data
enableHopLogs = False
# Noisy Node Telemetry Logging and packet threshold
noisyNodeLogging = False
noisyTelemetryLimit = 5
logMetaStats = True
# Enable detailed packet logging all packets
DEBUGpacket = False
# metaPacket detailed logging, the filter negates the port ID
debugMetadata = False
metadataFilter = TELEMETRY_APP,POSITION_APP

1
data/mesh_news.txt Normal file
View File

@@ -0,0 +1 @@
Today in meshtastic you are looking at the coolest bot on the block.

16
data/quiz_questions.json Normal file
View File

@@ -0,0 +1,16 @@
[
{
"question": "Which RFband is commonly used by Meshtastic devices in US regions?",
"answers": ["2.4 GHz", "433 MHz", "900 MHz", "5.8 GHz"],
"correct": 2
},
{
"question": "Yogi the bear 🐻 likes what food?",
"answers": ["Picnic baskets", "Fish", "Burgers", "Hot dogs"],
"correct": 0
},
{
"question": "What is the password for the Meshtastic MQTT broker?",
"answer": "large4cats"
}
]

View File

@@ -0,0 +1,15 @@
[
{
"type": "multiple_choice",
"question": "How Did you hear about us?",
"options": ["Meshtastic", "Discord", "Friend", "Other"]
},
{
"type": "integer",
"question": "How many nodes do you own?"
},
{
"type": "text",
"question": "What feature would you like to see next?"
}
]

View File

@@ -0,0 +1,15 @@
[
{
"type": "multiple_choice",
"question": "How often do you experience snowfall in your area?",
"options": ["Never", "Rarely", "Sometimes", "Often", "Every winter"]
},
{
"type": "integer",
"question": "What was the deepest snowfall (in inches) you've measured at your location?"
},
{
"type": "text",
"question": "Describe any challenges you face during heavy snowfall."
}
]

75
etc/README.md Normal file
View File

@@ -0,0 +1,75 @@
# etc Directory
This folder contains supporting files and resources for the Mesh Bot project. Typical contents include:
- **Images**: Visual assets used in documentation (e.g., `pong-bot.jpg`).
- **Custom Scripts**: Example or utility scripts for advanced configuration (e.g., `custom_scheduler.py` for scheduled tasks).
- **tmp**: Temp files for install
## db_admin.py
**Purpose:**
`db_admin.py` is a simple administrative tool for viewing the contents of the Mesh Bots data and high score databases. It loads and prints out messages, direct messages, email/SMS records, and game high score tables stored in the `/data` directory.
**Usage:**
Run this script from the command line to display the current contents of the bots databases. This is useful for debugging, verifying data integrity, or reviewing stored messages and game scores.
```sh
python etc/db_admin.py
```
**What it does:**
- Attempts to load various `.pkl` and `.pickle` files from the `data` directory.
- Prints out the contents of BBS messages, direct messages, email and SMS databases.
- Displays high scores for supported games (Lemonade Stand, DopeWars, BlackJack, Video Poker, Mastermind, GolfSim).
- If a file is missing, it will print a message indicating so.
**Note:**
This tool is for administrative and debugging purposes only. It does not modify any data.
## eas_alert_parser.py
**Purpose:**
`eas_alert_parser.py` is a utility script for processing and cleaning up output from `multimon-ng` to extract and convert Emergency Alert System (EAS) messages for further use, such as with EAS2Text.
**Usage:**
This script is intended to be used with piped input, typically from `multimon-ng` decoding SAME/EAS messages. It filters and processes EAS lines, converts them to readable text using EAS2Text, and writes the results to `alert.txt`.
**Example usage:**
```sh
multimon-ng -a EAS ... | python etc/eas_alert_parser.py
```
**What it does:**
- Reads input line-by-line (supports piped or redirected input).
- Filters for lines starting with `EAS:` or `EAS (part):`.
- Avoids duplicate messages and only processes new alerts.
- Uses the EAS2Text library to convert EAS codes to human-readable messages.
- Writes completed alerts to `alert.txt` for further processing or notification.
**Note:**
This script is intended for experimental or hobbyist use and may require customization for your specific workflow.
## simulator.py
**Purpose:**
`simulator.py` is a development and testing tool that simulates the behavior of the Mesh Bot in a controlled environment. It allows you to prototype and test handler functions without needing real hardware or a live mesh network.
**Usage:**
Run this script from the command line to interactively test handler functions. You can input messages as if you were a mesh node, and see how your handler responds.
```sh
python etc/simulator.py
```
**What it does:**
- Simulates node IDs, device IDs, and random GPS locations.
- Lets you specify which handler function to test (by setting `projectName`).
- Prompts for user input, passes it to the handler, and displays the response.
- Logs simulated message sending and handler output for review.
- Useful for rapid prototyping and debugging new features or message handlers.
**Note:**
Edit the `projectName` variable to match the handler function you want to test. You can expand this script to test additional handlers or scenarios as needed.
Feel free to add or update resources here as needed for documentation, configuration, or project support.

69
etc/custom_scheduler.py Normal file
View File

@@ -0,0 +1,69 @@
import schedule
from modules.log import logger
from modules.settings import MOTD
from modules.system import send_message
def setup_custom_schedules(send_message, tell_joke, welcome_message, handle_wxc, MOTD, schedulerChannel, schedulerInterface):
"""
Set up custom schedules. Edit the example schedules as needed.
1. in config.ini set "value" under [scheduler] to: value = custom
2. edit this file to add/remove/modify schedules
3. restart mesh bot
4. verify schedules are working by checking the log file
5. Make sure to uncomment the example schedules below to enable them
"""
try:
# Example task functions, modify as needed the channel and interface parameters default to schedulerChannel and schedulerInterface
def send_joke(channel, interface):
# uses system.send_message to send the result of tell_joke()
send_message(tell_joke(), channel, 0, interface)
def send_good_morning(channel, interface):
# uses system.send_message to send "Good Morning"
send_message("Good Morning", channel, 0, interface)
def send_wx(channel, interface):
# uses system.send_message to send the result of handle_wxc(id,id,cmd,days_returned)
send_message(handle_wxc(0, 1, 'wx', days=1), channel, 0, interface)
def send_weather_alert(channel, interface):
# uses system.send_message to send string
send_message("Weather alerts available on 'Alerts' channel with default 'AQ==' key.", channel, 0, interface)
def send_config_url(channel, interface):
# uses system.send_message to send string
send_message("Join us on Medium Fast https://meshtastic.org/e/#CgcSAQE6AggNEg4IARAEOAFAA0gBUB5oAQ", channel, 0, interface)
def send_net_starting(channel, interface):
# uses system.send_message to send string, channel 2, interface 3
send_message("Net Starting Now", 2, 0, 3)
def send_welcome(channel, interface):
# uses system.send_message to send string, channel 2, interface 1
send_message("Welcome to the group", 2, 0, 1)
def send_motd(channel, interface):
send_message(MOTD, channel, 0, interface)
### Send a joke every 2 minutes
#schedule.every(2).minutes.do(lambda: send_joke(schedulerChannel, schedulerInterface))
### Send a good morning message every day at 9 AM
#schedule.every().day.at("09:00").do(lambda: send_good_morning(schedulerChannel, schedulerInterface))
### Send weather update every day at 8 AM
#schedule.every().day.at("08:00").do(lambda: send_wx(schedulerChannel, schedulerInterface))
### Send weather alerts every Wednesday at noon
#schedule.every().wednesday.at("12:00").do(lambda: send_weather_alert(schedulerChannel, schedulerInterface))
### Send configuration URL every 2 days at 10 AM
#schedule.every(2).days.at("10:00").do(lambda: send_config_url(schedulerChannel, schedulerInterface))
### Send net starting message every Wednesday at 7 PM
#schedule.every().wednesday.at("19:00").do(lambda: send_net_starting(schedulerChannel, schedulerInterface))
### Send welcome message every 2 days at 8 AM
#schedule.every(2).days.at("08:00").do(lambda: send_welcome(schedulerChannel, schedulerInterface))
### Send MOTD every day at 1 PM
#schedule.every().day.at("13:00").do(lambda: send_motd(schedulerChannel, schedulerInterface))
### Send bbslink message every 2 days at 10 AM
#schedule.every(2).days.at("10:00").do(lambda: send_message("bbslink MeshBot looking for peers", schedulerChannel, 0, schedulerInterface))
except Exception as e:
logger.error(f"Error setting up custom schedules: {e}")

View File

@@ -14,6 +14,8 @@ Group=pi
WorkingDirectory=/dir/
ExecStart=python3 mesh_bot.py
ExecStop=pkill -f mesh_bot.py
Environment=REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
Environment=SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs

View File

@@ -2,9 +2,11 @@
Description=MeshingAround-ReportingTask
[Timer]
OnUnitActiveSec=1h
OnbootSec=5min
OnCalendar=*-*-* 04:20:00
Persistent=true
Unit=mesh_bot_reporting.service
#OnUnitActiveSec=1h
#OnbootSec=5min
[Install]
WantedBy=timers.target

View File

@@ -14,6 +14,9 @@ Group=pi
WorkingDirectory=/dir/
ExecStart=python3 etc/report_generator5.py
ExecStop=pkill -f report_generator5.py
# ExecStart=python3 etc/report_generator.py
# ExecStop=pkill -f report_generator.py
# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs
@@ -23,4 +26,4 @@ Restart=on-failure
Type=notify #try simple if any problems
[Install]
WantedBy=default.target
WantedBy=timers.target

View File

@@ -1,23 +0,0 @@
# /etc/systemd/system/mesh_bot_w3.service
# sudo systemctl daemon-reload
# sudo systemctl enable mesh_bot_w3.service
# sudo systemctl start mesh_bot_w3.service
[Unit]
Description=MeshingAround-W3Server
After=network.target
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/dir/
ExecStart=python3 modules/web.py
ExecStop=pkill -f mesh_bot_w3.py
# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs
Environment=PYTHONUNBUFFERED=1
Restart=on-failure
Type=notify #try simple if any problems

View File

@@ -0,0 +1,21 @@
[Unit]
Description=MeshingAround-WebServer
After=network.target
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/dir/
ExecStart=python3 modules/web.py
ExecStop=pkill -f mesh_bot_w3.py
Environment=REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
Environment=SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
Environment=PYTHONUNBUFFERED=1
Restart=on-failure
[Install]
WantedBy=multi-user.target

View File

@@ -14,6 +14,8 @@ Group=pi
WorkingDirectory=/dir/
ExecStart=python3 pong_bot.py
ExecStop=pkill -f pong_bot.py
Environment=REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
Environment=SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
# Disable Python's buffering of STDOUT and STDERR, so that output from the
# service shows up immediately in systemd's logs

View File

@@ -350,7 +350,8 @@ def get_database_info():
os.path.join(base_dir, 'mmind_hs.pkl'),
os.path.join(base_dir, 'golfsim_hs.pkl'),
os.path.join(base_dir, 'bbsdb.pkl'),
os.path.join(base_dir, 'bbsdm.pkl')]
os.path.join(base_dir, 'bbsdm.pkl'),
os.path.join(base_dir, 'qrz.db')]
for file in databaseFiles:
try:
@@ -371,6 +372,16 @@ def get_database_info():
bbsdb = pickle.load(f)
elif 'bbsdm' in file:
bbsdm = pickle.load(f)
elif 'qrz.db' in file:
# open the qrz.db sqllite file
import sqlite3
conn = sqlite3.connect(file)
cursor = conn.cursor()
cursor.execute("SELECT * FROM qrz")
qrz_db = cursor.fetchall()
# convert to a list of strings
qrz_db = [f"{row[0]}: {row[1]} {row[2]}" for row in qrz_db]
conn.close()
except Exception as e:
print(f"Warning issue reading database file: {str(e)}")
if 'lemonstand' in file:
@@ -425,7 +436,8 @@ def get_database_info():
'golfsim_score': golfsim_score,
'banList': banList,
'adminList': adminList,
'sentryIgnoreList': sentryIgnoreList
'sentryIgnoreList': sentryIgnoreList,
'qrz_db': qrz_db if 'qrz_db' in locals() else "no data"
}
def generate_main_html(log_data, system_info):
@@ -913,6 +925,11 @@ def generate_database_html(database_info):
<tr><td>Mastermind</td><td>${mmind_score}</td></tr>
<tr><td>Golf Simulator</td><td>${golfsim_score}</td></tr>
</table>
<h1>QRZ Database</h1>
<p>QRZ Database holds heard nodeID and Shortname</p>
<table>
<tr><td>${qrz_db}</td></tr>
</table>
</body>
</html>
"""

View File

@@ -359,7 +359,8 @@ def get_database_info():
os.path.join(base_dir, 'mmind_hs.pkl'),
os.path.join(base_dir, 'golfsim_hs.pkl'),
os.path.join(base_dir, 'bbsdb.pkl'),
os.path.join(base_dir, 'bbsdm.pkl')]
os.path.join(base_dir, 'bbsdm.pkl'),
os.path.join(base_dir, 'qrz.db')]
for file in databaseFiles:
try:
@@ -380,6 +381,16 @@ def get_database_info():
bbsdb = pickle.load(f)
elif 'bbsdm' in file:
bbsdm = pickle.load(f)
elif 'qrz.db' in file:
#open the qrz.db sqllite file
import sqlite3
conn = sqlite3.connect(file)
cursor = conn.cursor()
cursor.execute("SELECT * FROM qrz")
qrz_db = cursor.fetchall()
# convert to a list of strings
qrz_db = [f"{row[0]}: {row[1]} {row[2]}" for row in qrz_db]
conn.close()
except Exception as e:
print(f"Warning issue reading database file: {str(e)}")
if 'lemonstand' in file:
@@ -434,7 +445,8 @@ def get_database_info():
'golfsim_score': golfsim_score,
'banList': banList,
'adminList': adminList,
'sentryIgnoreList': sentryIgnoreList
'sentryIgnoreList': sentryIgnoreList,
'qrz_db': qrz_db if 'qrz_db' in locals() else "no data"
}
def generate_main_html(log_data, system_info):
@@ -1207,6 +1219,11 @@ def generate_database_html(database_info):
<tr><td>Mastermind</td><td>${mmind_score}</td></tr>
<tr><td>Golf Simulator</td><td>${golfsim_score}</td></tr>
</table>
<h1>QRZ Database</h1>
<p>QRZ Database holds heard nodeID and Shortname</p>
<table>
<tr><td>${qrz_db}</td></tr>
</table>
</body>
</html>
"""

View File

@@ -1,7 +1,8 @@
#!/usr/bin/env python3
# # Simulate meshing-around de K7MHI 2024
from modules.log import * # Import the logger; ### --> If you are reading this put the script in the project root <-- ###
from modules.log import logger, getPrettyTime # Import the logger; ### --> If you are reading this put the script in the project root <-- ###
import time
import datetime
import random
# Initialize the tool
@@ -9,6 +10,7 @@ projectName = "example_handler" # name of _handler function to match the functio
randomNode = False # Set to True to use random node IDs
# bot.py Simulated functions
deviceID = 1 # represents the device/node number
def get_NodeID():
nodeList = [4258675309, 1212121212, 1234567890, 9876543210]
if randomNode:
@@ -16,22 +18,45 @@ def get_NodeID():
else:
nodeID = nodeList[0]
return nodeID
nodeID = get_NodeID() # assign a nodeID
def get_name_from_number(nodeID, length='short', interface=1):
# return random name for nodeID
names = ["Max","Molly","Jake","Kelly"]
return names[nodeID % len(names)]
def mesh_bot(message, nodeID, deviceID):
return "Meshing-Around Bot at your service!"
#simulate GPS locations for testing
locations = [
(48.200909, -123.25719),
(48.330283,-123.260703),
(48.342735,-122.987911),
(48.205591,-122.998448)
]
lat, lon = random.choice(locations) # pick a random location
location = f"{lat},{lon}"
# # end Initialization of the tool
# # Function to handle, or the project in test
#from modules.llm import * # Import the LLM module
# # Project handler function code here
# example handler function canada()
def example_handler(message, nodeID, deviceID):
readableTime = time.ctime(time.time())
msg = "Hello World! "
msg += f" You are Node ID: {nodeID} "
msg += f" Its: {readableTime} "
msg += f" You just sent: {message}"
return msg
if message != "":
# put code in test here
msg = f"Hello {get_name_from_number(nodeID)}, simulator ready for testing {projectName} project! on device {deviceID}"
msg += f" Your location is {location}"
msg += f" you said: {message}"
return msg
# # end of function test code
@@ -42,7 +67,7 @@ if __name__ == '__main__': # represents the bot's main loop
nodeInt = 1 # represents the device/node number
logger.info(f"System: Meshing-Around Simulator Starting for {projectName}")
nodeID = get_NodeID() # assign a nodeID
projectResponse = globals()[projectName]("", nodeID, nodeInt) # Call the project handler under test
projectResponse = globals()[projectName]("", nodeID, deviceID) # call the handler function once to start
while True: # represents the onReceive() loop in the bot.py
projectResponse = ""
responseLength = 0
@@ -51,7 +76,7 @@ if __name__ == '__main__': # represents the bot's main loop
packet = input(f"CLIENT {nodeID} INPUT: " ) # Emulate the client input
if packet != "":
#try:
projectResponse = globals()[projectName](message = packet, nodeID = nodeID, deviceID = nodeInt)
projectResponse = globals()[projectName](message = packet, nodeID = nodeID, deviceID = deviceID) # call the handler function
# except Exception as e:
# logger.error(f"System: Handler: {e}")
# projectResponse = "Error in handler"

View File

@@ -1,9 +1,71 @@
#!/bin/bash
# meshing-around install helper script
# to uninstall, run with --nope
# install.sh
NOPE=0
cd "$(dirname "$0")"
program_path=$(pwd)
for arg in "$@"; do
if [[ "$arg" == "--nope" ]]; then
NOPE=1
fi
done
if [[ $NOPE -eq 1 ]]; then
echo "Uninstalling Meshing Around and all related services..."
sudo systemctl stop mesh_bot || true
sudo systemctl disable mesh_bot || true
sudo systemctl stop pong_bot || true
sudo systemctl disable pong_bot || true
sudo systemctl stop mesh_bot_w3_server || true
sudo systemctl disable mesh_bot_w3_server || true
sudo systemctl stop mesh_bot_reporting || true
sudo systemctl disable mesh_bot_reporting || true
sudo rm -f /etc/systemd/system/mesh_bot.service
sudo rm -f /etc/systemd/system/mesh_bot_reporting
sudo rm -f /etc/systemd/system/pong_bot.service
sudo rm -f /etc/systemd/system/mesh_bot_w3_server.service
sudo rm -f /etc/systemd/system/mesh_bot_reporting.service
sudo rm -f /etc/systemd/system/mesh_bot_reporting.timer
sudo systemctl daemon-reload
sudo systemctl reset-failed
sudo gpasswd -d meshbot dialout || true
sudo gpasswd -d meshbot tty || true
sudo gpasswd -d meshbot bluetooth || true
sudo groupdel meshbot || true
sudo userdel meshbot || true
sudo rm -rf /opt/meshing-around/
# If Ollama was installed and you want to remove it:
if [[ -f /etc/systemd/system/ollama.service ]]; then
read -p "Ollama service detected. Do you want to remove Ollama and all its data? (y/n): " remove_ollama
if [[ "$remove_ollama" =~ ^[Yy] ]]; then
sudo systemctl stop ollama || true
sudo systemctl disable ollama || true
sudo rm -f /etc/systemd/system/ollama.service
sudo rm -rf /usr/local/bin/ollama
sudo rm -rf ~/.ollama
echo "Ollama removed."
else
echo "Ollama not removed."
fi
fi
echo "Uninstall complete. Hope to see you again! 73"
exit 0
fi
# install.sh, Meshing Around installer script
# Thanks for using Meshing Around!
printf "\n########################"
printf "\nMeshing Around Installer\n"
printf "########################\n"
@@ -12,13 +74,18 @@ printf "Installer works best in raspian/debian/ubuntu or foxbuntu embedded syste
printf "If there is a problem, try running the installer again.\n"
printf "\nChecking for dependencies...\n"
# fuse check for existing installation
if [[ -f config.ini ]]; then
printf "\nDetected existing installation, please backup and remove existing installation before proceeding\n"
exit 1
fi
# check if we are in /opt/meshing-around
if [ $program_path != "/opt/meshing-around" ]; then
if [[ "$program_path" != "/opt/meshing-around" ]]; then
printf "\nIt is suggested to project path to /opt/meshing-around\n"
printf "Do you want to move the project to /opt/meshing-around? (y/n)"
read move
if [[ $(echo "$move" | grep -i "^y") ]]; then
sudo mv $program_path /opt/meshing-around
sudo mv "$program_path" /opt/meshing-around
cd /opt/meshing-around
printf "\nProject moved to /opt/meshing-around. re-run the installer\n"
exit 0
@@ -70,17 +137,25 @@ else
printf "\nDependencies installed\n"
fi
# add user to groups for serial access
printf "\nAdding user to dialout, bluetooth, and tty groups for serial access\n"
sudo usermod -a -G dialout $USER
sudo usermod -a -G tty $USER
sudo usermod -a -G bluetooth $USER
# copy service files
cp etc/pong_bot.tmp etc/pong_bot.service
cp etc/mesh_bot.tmp etc/mesh_bot.service
cp etc/mesh_bot_reporting.tmp etc/mesh_bot_reporting.service
cp etc/mesh_bot_w3.tmp etc/mesh_bot_w3.service
cp etc/mesh_bot_w3_server.tmp etc/mesh_bot_w3_server.service
# set the correct path in the service file
replace="s|/dir/|$program_path/|g"
sed -i "$replace" etc/pong_bot.service
sed -i "$replace" etc/mesh_bot.service
sed -i "$replace" etc/mesh_bot_reporting.service
sed -i "$replace" etc/mesh_bot_w3_server.service
# copy modules/custom_scheduler.py template if it does not exist
if [[ ! -f modules/custom_scheduler.py ]]; then
cp etc/custom_scheduler.py modules/custom_scheduler.py
printf "\nCustom scheduler template copied to modules/custom_scheduler.py\n"
fi
# generate config file, check if it exists
if [[ -f config.ini ]]; then
@@ -172,15 +247,7 @@ else
read bot
fi
# set the correct path in the service file
replace="s|/dir/|$program_path/|g"
sed -i $replace etc/pong_bot.service
sed -i $replace etc/mesh_bot.service
sed -i $replace etc/mesh_bot_reporting.service
sed -i $replace etc/mesh_bot_w3.service
# set the correct user in the service file?
#ask if we should add a user for the bot
# ask if we should add a user for the bot
if [[ $(echo "${embedded}" | grep -i "^n") ]]; then
printf "\nDo you want to add a local user (meshbot) no login, for the bot? (y/n)"
read meshbotservice
@@ -193,30 +260,43 @@ if [[ $(echo "${meshbotservice}" | grep -i "^y") ]] || [[ $(echo "${embedded}" |
sudo usermod -a -G meshbot meshbot
whoami="meshbot"
echo "Added user meshbot with no home directory"
sudo usermod -a -G dialout $whoami
sudo usermod -a -G tty $whoami
sudo usermod -a -G bluetooth $whoami
echo "Added meshbot to dialout, tty, and bluetooth groups"
sudo chown -R $whoami:$whoami $program_path/logs
sudo chown -R $whoami:$whoami $program_path/data
echo "Permissions set for meshbot on logs and data directories"
else
whoami=$(whoami)
fi
# set the correct user in the service file
replace="s|User=pi|User=$whoami|g"
sed -i $replace etc/pong_bot.service
sed -i $replace etc/mesh_bot.service
sed -i $replace etc/mesh_bot_reporting.service
sed -i $replace etc/mesh_bot_w3.service
sed -i "$replace" etc/pong_bot.service
sed -i "$replace" etc/mesh_bot.service
sed -i "$replace" etc/mesh_bot_reporting.service
sed -i "$replace" etc/mesh_bot_reporting.timer
# set the correct group in the service file
replace="s|Group=pi|Group=$whoami|g"
sed -i $replace etc/pong_bot.service
sed -i $replace etc/mesh_bot.service
sed -i $replace etc/mesh_bot_reporting.service
sed -i $replace etc/mesh_bot_w3.service
sed -i "$replace" etc/pong_bot.service
sed -i "$replace" etc/mesh_bot.service
sed -i "$replace" etc/mesh_bot_reporting.service
sed -i "$replace" etc/mesh_bot_reporting.timer
printf "\n service files updated\n"
# add user to groups for serial access
printf "\nAdding user to dialout, bluetooth, and tty groups for serial access\n"
sudo usermod -a -G dialout "$whoami"
sudo usermod -a -G tty "$whoami"
sudo usermod -a -G bluetooth "$whoami"
echo "Added user $whoami to dialout, tty, and bluetooth groups"
sudo chown -R "$whoami:$whoami" "$program_path/logs"
sudo chown -R "$whoami:$whoami" "$program_path/data"
echo "Permissions set for meshbot on logs and data directories"
# check and see if some sort of NTP is running
if ! systemctl is-active --quiet ntp.service && \
! systemctl is-active --quiet systemd-timesyncd.service && \
! systemctl is-active --quiet chronyd.service; then
printf "\nNo NTP service detected, it is recommended to have NTP running for proper bot operation.\n"
fi
if [[ $(echo "${bot}" | grep -i "^p") ]]; then
# install service for pong bot
sudo cp etc/pong_bot.service /etc/systemd/system/
@@ -235,6 +315,29 @@ if [[ $(echo "${bot}" | grep -i "^m") ]]; then
service="mesh_bot"
fi
# install mesh_bot_reporting timer to run daily at 4:20 am
echo ""
echo "Installing mesh_bot_reporting.timer to run mesh_bot_reporting daily at 4:20 am..."
sudo cp etc/mesh_bot_reporting.service /etc/systemd/system/
sudo cp etc/mesh_bot_reporting.timer /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable mesh_bot_reporting.timer
sudo systemctl start mesh_bot_reporting.timer
echo "mesh_bot_reporting.timer installed and enabled"
echo "Check timer status with: systemctl status mesh_bot_reporting.timer"
echo "List all timers with: systemctl list-timers"
echo ""
# # install mesh_bot_w3_server service
# echo "Installing mesh_bot_w3_server.service to run the web3 server..."
# sudo cp etc/mesh_bot_w3_server.service /etc/systemd/system/
# sudo systemctl daemon-reload
# sudo systemctl enable mesh_bot_w3_server.service
# sudo systemctl start mesh_bot_w3_server.service
# echo "mesh_bot_w3_server.service installed and enabled"
# echo "Check service status with: systemctl status mesh_bot_w3_server.service"
# echo ""
# check if running on embedded for final steps
if [[ $(echo "${embedded}" | grep -i "^n") ]]; then
# ask if emoji font should be installed for linux
@@ -245,28 +348,46 @@ if [[ $(echo "${embedded}" | grep -i "^n") ]]; then
echo "Emoji font installed!, reboot to load the font"
fi
printf "\nOptionally if you want to install the multi gig LLM Ollama compnents we will execute the following commands\n"
printf "\nOptionally if you want to install the LLM Ollama compnents we will execute the following commands\n"
printf "\ncurl -fsSL https://ollama.com/install.sh | sh\n"
printf "ollama pull gemma2:2b\n"
printf "Total download is multi GB, recomend pi5/8GB or better for this\n"
printf "ollama pull gemma3:270m\n"
# ask if the user wants to install the LLM Ollama components
printf "\nDo you want to install the LLM Ollama components? (y/n)"
read ollama
if [[ $(echo "${ollama}" | grep -i "^y") ]]; then
curl -fsSL https://ollama.com/install.sh | sh
# ask if want to install gemma2:2b
printf "\n Ollama install done now we can install the Gemma2:2b components\n"
echo "Do you want to install the Gemma2:2b components? (y/n)"
# ask if want to install gemma3:latest
printf "\n Ollama install done now we can install the gemma3:270m components\n"
echo "Do you want to install the gemma3:270m components? (y/n)"
read gemma
if [[ $(echo "${gemma}" | grep -i "^y") ]]; then
ollama pull gemma2:2b
ollama pull gemma3:270m
fi
fi
# ask if the user wants to edit the ollama service for API access
if [[ -f /etc/systemd/system/ollama.service ]]; then
printf "\nEdit /etc/systemd/system/ollama.service and add Environment=OLLAMA_HOST=0.0.0.0 for API? (y/n)"
read editollama
if [[ $(echo "${editollama}" | grep -i "^y") ]]; then
replace="s|\[Service\]|\[Service\]\nEnvironment=\"OLLAMA_HOST=0.0.0.0\"|g"
sudo sed -i "$replace" /etc/systemd/system/ollama.service
sudo systemctl daemon-reload
sudo systemctl restart ollama.service
printf "\nOllama service updated and restarted\n"
fi
# assume we want to enable ollama in config.ini
if [[ -f config.ini ]]; then
replace="s|ollama = False|ollama = True|g"
sed -i "$replace" config.ini
printf "\nOllama enabled in config.ini\n"
fi
fi
# document the service install
printf "To install the %s service and keep notes, reference following commands:\n\n" "$service" > install_notes.txt
printf "sudo cp %s/etc/%s.service /etc/systemd/system/etc/%s.service\n" "$program_path" "$service" "$service" >> install_notes.txt
printf "sudo cp %s/etc/%s.service /etc/systemd/system/%s.service\n" "$program_path" "$service" "$service" >> install_notes.txt
printf "sudo systemctl daemon-reload\n" >> install_notes.txt
printf "sudo systemctl enable %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl start %s.service\n" "$service" >> install_notes.txt
@@ -276,6 +397,15 @@ if [[ $(echo "${embedded}" | grep -i "^n") ]]; then
printf "sudo journalctl -u %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl stop %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl disable %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl disable %s.service\n" "$service" >> install_notes.txt
printf "\n older chron statment to run the report generator hourly:\n" >> install_notes.txt
printf "0 * * * * /usr/bin/python3 $program_path/etc/report_generator5.py" >> install_notes.txt
printf " to edit crontab run 'crontab -e'\n" >> install_notes.txt
printf "\nmesh_bot_reporting.timer installed to run daily at 4:20 am\n" >> install_notes.txt
printf "Check timer status: systemctl status mesh_bot_reporting.timer\n" >> install_notes.txt
printf "List all timers: systemctl list-timers\n" >> install_notes.txt
printf "View timer logs: journalctl -u mesh_bot_reporting.timer\n" >> install_notes.txt
printf "*** Stay Up to date using 'bash update.sh' ***\n" >> install_notes.txt
if [[ $(echo "${venv}" | grep -i "^y") ]]; then
printf "\nFor running on venv, virtual launch bot with './launch.sh mesh' in path $program_path\n" >> install_notes.txt
@@ -305,7 +435,18 @@ else
sudo systemctl daemon-reload
sudo systemctl enable $service.service
sudo systemctl start $service.service
printf "Reference following commands:\n\n" "$service" > install_notes.txt
sudo systemctl daemon-reload
# # check if the cron job already exists
# if ! crontab -l | grep -q "$chronjob"; then
# # add the cron job to run the report_generator5.py script
# (crontab -l 2>/dev/null; echo "$chronjob") | crontab -
# printf "\nAdded cron job to run report_generator5.py\n"
# else
# printf "\nCron job already exists, skipping\n"
# fi
# document the service install
printf "Reference following commands:\n\n" > install_notes.txt
printf "sudo systemctl status %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl start %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl restart %s.service\n\n" "$service" >> install_notes.txt
@@ -313,9 +454,16 @@ else
printf "sudo journalctl -u %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl stop %s.service\n" "$service" >> install_notes.txt
printf "sudo systemctl disable %s.service\n" "$service" >> install_notes.txt
printf "older crontab to run the report generator hourly:" >> install_notes.txt
printf "0 * * * * /usr/bin/python3 $program_path/etc/report_generator5.py" >> install_notes.txt
printf " to edit crontab run 'crontab -e'" >> install_notes.txt
printf "\nmesh_bot_reporting.timer installed to run daily at 4:20 am\n" >> install_notes.txt
printf "Check timer status: systemctl status mesh_bot_reporting.timer\n" >> install_notes.txt
printf "List all timers: systemctl list-timers\n" >> install_notes.txt
printf "*** Stay Up to date using 'bash update.sh' ***\n" >> install_notes.txt
fi
printf "\nInstallation complete!\n"
printf "\nInstallation complete?\n"
exit 0
@@ -323,14 +471,23 @@ exit 0
# sudo systemctl stop mesh_bot
# sudo systemctl disable mesh_bot
# sudo systemctl stop pong_bot
# sudo systemctl disable pong_bot
# sudo systemctl stop mesh_bot_w3_server
# sudo systemctl disable mesh_bot_w3_server
# sudo systemctl stop mesh_bot_reporting
# sudo systemctl disable mesh_bot_reporting
# sudo rm /etc/systemd/system/mesh_bot.service
# sudo rm /etc/systemd/system/mesh_bot_reporting.service
# sudo rm /etc/systemd/system/mesh_bot_w3.service
# sudo rm /etc/systemd/system/mesh_bot_reporting
# sudo rm /etc/systemd/system/pong_bot.service
# sudo rm /etc/systemd/system/mesh_bot_w3_server.service
# sudo rm /etc/systemd/system/mesh_bot_reporting.service
# sudo rm /etc/systemd/system/mesh_bot_reporting.timer
# sudo systemctl daemon-reload
# sudo systemctl reset-failed
@@ -340,9 +497,16 @@ exit 0
# sudo groupdel meshbot
# sudo userdel meshbot
# sudo rm -rf /opt/meshing-around
# sudo rm -rf /opt/meshing-around/
# If Ollama was installed and you want to remove it:
# sudo systemctl stop ollama
# sudo systemctl disable ollama
# sudo rm /etc/systemd/system/ollama.service
# sudo rm -rf /usr/local/bin/ollama
# sudo rm -rf ~/.ollama
# after install shenannigans
# add 'bee = True' to config.ini General section. You will likley want to clean the txt up a bit
# wget https://courses.cs.washington.edu/courses/cse163/20wi/files/lectures/L04/bee-movie.txt -O bee.txt
# add 'bee = True' to config.ini General section.
# wget https://gist.github.com/MattIPv4/045239bc27b16b2bcf7a3a9a4648c08a -O bee.txt

View File

@@ -5,12 +5,12 @@
cd "$(dirname "$0")"
if [ ! -f "config.ini" ]; then
if [[ ! -f "config.ini" ]]; then
cp config.template config.ini
fi
# activate the virtual environment if it exists
if [ -d "venv" ]; then
if [[ -d "venv" ]]; then
source venv/bin/activate
else
echo "Virtual environment not found, this tool just launches the .py in venv"
@@ -22,12 +22,14 @@ if [[ "$1" == pong* ]]; then
python3 pong_bot.py
elif [[ "$1" == mesh* ]]; then
python3 mesh_bot.py
elif [ "$1" == "html" ]; then
elif [[ "$1" == "html" ]]; then
python3 etc/report_generator.py
elif [ "$1" == "html5" ]; then
elif [[ "$1" == "html5" ]]; then
python3 etc/report_generator5.py
elif [[ "$1" == add* ]]; then
python3 script/addFav.py
else
echo "Please provide a bot to launch (pong/mesh) or a report to generate (html/html5)"
echo "Please provide a bot to launch (pong/mesh) or a report to generate (html/html5) or addFav"
exit 1
fi

View File

@@ -1,10 +1,16 @@
# Logs and Reports
Logs will collect here. Give a day of logs or a bunch of messages to have good reports.
## Reporting Note
Reporting is via [../etc/report_generator5.py](../etc/report_generator5.py). The report_generator5 has newer feel and HTML5 coding. The index.html output is published in [../etc/www](../etc/www) there is a .cfg file created on first run for configuring values as needed (like moving web root)
- Make sure to have `SyslogToFile = True` and default of DEBUG log level to fully enable reporting! ‼️
- If you are in a venv and using launch.sh you can `launch.sh html5`
This directory stores log files generated by the Mesh Bot. To generate useful reports, ensure you have at least a day's worth of logs or a substantial number of messages.
## Reporting
Reports are generated using [`../etc/report_generator5.py`](../etc/report_generator5.py), which produces modern HTML5 reports. The output (`index.html`) is saved in [`../etc/www`](../etc/www) by default. A `.cfg` configuration file is created on first run, allowing you to customize settings such as the web root directory.
- Ensure `SyslogToFile = True` and `sysloglevel = DEBUG` in your configuration to enable full reporting.
- If using a virtual environment and `launch.sh`, you can run:
```sh
launch.sh html5
```
![reportView](../etc/reporting.jpg)
@@ -24,4 +30,18 @@ log_backup_count = 32
## Web Reporting WebServer
There is a web-server module. You can run `python3 modules/web.py` from the project root directory and it will serve up the web content.
find it at. http://localhost:8420
find it at. http://localhost:8420
If you have linux-native running and errors such as..
```bash
File "/usr/lib/python3.11/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.11/socketserver.py", line 472, in server_bind
self.socket.bind(self.server_address)
```
modify the modules/web.py to use a real IP address, meshtasticD-native is binding to 127.0.0.1
```python
# Set the desired IP address
server_ip = '127.0.0.1'
```

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,865 @@
# Modules and Adding stuff
# Meshtastic Mesh-Bot Modules
To help with code testing see `etc/simulator.py` to simulate a bot. I also enjoy meshtasticd(linux-native) in noradio with MQTT server and client to just emulate a mesh.
This document provides an overview of all modules available in the Mesh-Bot project, including their features, usage, and configuration.
## By following these steps, you can add a new bbs option to the bot.
---
## Table of Contents
1. **Define the Command Handler**:
Add a new function in mesh_bot.py to handle the new command. For example, if you want to add a command `newcommand`:
```python
def handle_newcommand(message, message_from_id, deviceID):
return "This is a response from the new command."
```
Additionally you can add a whole new module.py, I recommend doing this if you need to import more stuff, try and wedge it into similar spots if you can. You will need to import the file as well, look further at `modules/system.py` for more.
2. **Add the Command to the Auto Response**:
Update the auto_response function in mesh_bot.py to include the new command:
```python
def auto_response(message, snr, rssi, hop, pkiStatus, message_from_id, channel_number, deviceID, isDM):
#...
"newcommand": lambda: handle_newcommand(message, message_from_id, deviceID),
#...
```
3. **Update the Trap List and Help**:
A quick way to do this is to edit the line 16/17 in `modules/system.py` to include the new command:
```python
#...
trap_list = ("cmd", "cmd?", "newcommand") # default trap list, with the new command added
help_message = "Bot CMD?:newcommand, "
#...
```
- [Overview](#overview)
- [Networking](#networking)
- [Games](#games)
- [BBS (Bulletin Board System)](#bbs-bulletin-board-system)
- [Checklist](#checklist)
- [Location & Weather](#location--weather)
- [Map Command](#map-command)
- [EAS & Emergency Alerts](#eas--emergency-alerts)
- [File Monitoring & News](#file-monitoring--news)
- [Radio Monitoring](#radio-monitoring)
- [Voice Commands (VOX)](#voice-commands-vox)
- [Ollama LLM/AI](#ollama-llmai)
- [Wikipedia Search](#wikipedia-search)
- [DX Spotter Module](#dx-spotter-module)
- [Mesh Bot Scheduler User Guide](#mesh-bot-scheduler-user-guide)
- [Other Utilities](#other-utilities)
- [Messaging Settings](#messaging-settings)
- [Troubleshooting](#troubleshooting)
- [Configuration Guide](#configuration-guide)
---
**If looking to merge** the prefered way would be to update `modules/system.py` Adding this block below `ping` which ends around line 28:
```python
# newcommand Configuration
newcommand_enabled = True # settings.py handles the config.ini values; this is a placeholder
if newcommand_enabled:
trap_list_newcommand = ("newcommand",)
trap_list = trap_list + trap_list_newcommand
help_message = help_message + ", newcommand"
```
## Overview
5. **Test the New Command**:
Run MeshBot and test the new command by sending a message with the command `newcommand` to ensure it responds correctly.
Modules are Python files in the `modules/` directory that add features to the bot. Enable or disable them via `config.ini`.
See [modules/adding_more.md](adding_more.md) for developer notes.
---
## Networking
### ping / pinging / test / testing / ack
- **Usage:** `ping`, `pinging`, `test`, `testing`, `ack`, `ping @user`, `ping #tag`
- **Description:** Sends a ping to the bot. The bot responds with signal information such as SNR (Signal-to-Noise Ratio), RSSI (Received Signal Strength Indicator), and hop count. Used for making field report etc.
- **Targeted Ping:**
You can direct a ping to a specific user or group by mentioning their short name or tag:
- `ping @NODE` — Pings a Joke to specific node by its short name.
- **Example:**
```
ping
```
Response:
```
SNR: 12.5, RSSI: -80, Hops: 2
```
```
ping @Top of the hill
```
Response:
```
PING @Top of the hill SNR: 10.2, RSSI: -85, Hops: 1
```
- **Help:**
Send `ping?` in a Direct Message (DM) for usage instructions.
---
### Notes
- You can mention users or tags in your ping/test messages (e.g., `ping @user` or `ping #group`) to target specific nodes or groups.
- Some commands may only be available in Direct Messages, depending on configuration.
| Command | Description | ✅ Works Off-Grid |
|--------------|-------------|------------------|
| `ping`, `ack` | Return data for signal. Example: `ping 15 #DrivingI5` (activates auto-ping every 20 seconds for count 15 via DM only) you can also ping @NODE short name and if BBS DM enabled it will send them a joke | ✅ |
| `cmd` | Returns the list of commands (the help message) | ✅ |
| `history` | Returns the last commands run by user(s) | ✅ |
| `leaderboard` | Shows extreme mesh metrics like lowest battery 🪫 `leaderboard reset` allows admin reset | ✅ |
| `lheard` | Returns the last 5 heard nodes with SNR. Can also use `sitrep` | ✅ |
| `motd` | Displays the message of the day or sets it. Example: `motd $New Message Of the day` | ✅ |
| `sysinfo` | Returns the bot node telemetry info | ✅ |
| `test` | used to test the limits of data transfer (`test 4` sends data to the maxBuffer limit default 200 charcters) via DM only | ✅ |
| `whereami` | Returns the address of the sender's location if known |
| `whoami` | Returns details of the node asking, also returned when position exchanged 📍 | ✅ |
| `whois` | Returns details known about node, more data with bbsadmin node | ✅ |
| `echo` | Echo string back, disabled by default | ✅ |
| `bannode` | Admin option to prevent a node from using bot. `bannode list` will load and use the data/bbs_ban_list.txt db | ✅ |
---
## Games
All games are played via DM to the bot. See [modules/games/README.md](games/README.md) for detailed rules and examples.
| Command | Description |
|----------------|------------------------------------|
| `blackjack` | Play Blackjack (Casino 21) |
| `dopewars` | Classic trading game |
| `golfsim` | 9-hole Golf Simulator |
| `lemonstand` | Lemonade Stand business sim |
| `tictactoe` | Tic-Tac-Toe vs. the bot |
| `mastermind` | Code-breaking game |
| `videopoker` | Video Poker (five-card draw) |
| `joke` | Tells a dad joke |
| `hamtest` | FCC/ARRL QuizBot |
| `hangman` | Classic word guess game |
| `survey` | Take a custom survey |
| `quiz` | QuizMaster group quiz |
Enable/disable games in `[games]` section of `config.ini`.
---
## BBS (Bulletin Board System)
| Command | Description |
|--------------|-----------------------------------------------|
| `bbshelp` | Show BBS help |
| `bbslist` | List messages |
| `bbsread` | Read a message by ID |
| `bbspost` | Post a message or DM |
| `bbsdelete` | Delete a message |
| `bbsinfo` | BBS stats (sysop) |
| `bbslink` | Link messages between BBS systems |
Enable in `[bbs]` section of `config.ini`.
more at [meshBBS: How-To & API Documentation](bbstools.md)
---
## Checklist
| Command | Description |
|--------------|-----------------------------------------------|
| `checkin` | Check in a node/asset |
| `checkout` | Check out a node/asset |
| `checklist` | Show checklist database |
Enable in `[checklist]` section of `config.ini`.
---
## Location & Weather
| Command | Description |
|--------------|-----------------------------------------------|
| `wx` | Local weather forecast (NOAA/Open-Meteo) |
| `wxc` | Weather in metric/imperial |
| `wxa` | NOAA alerts |
| `wxalert` | NOAA alerts (expanded) |
| `mwx` | NOAA Coastal Marine Forecast |
| `tide` | NOAA tide info |
| `riverflow` | NOAA river flow info |
| `earthquake` | USGS earthquake info |
| `valert` | USGS volcano alerts |
| `rlist` | Nearby repeaters from RepeaterBook |
| `satpass` | Satellite pass info |
| `howfar` | Distance traveled since last check |
| `howtall` | Calculate height using sun angle |
| `whereami` | Show current location |
Configure in `[location]` section of `config.ini`.
Certainly! Heres a README help section for your `mapHandler` command, suitable for users of your meshbot:
---
## 📍 Map Command
The `map` command allows you to log your current GPS location with a custom description. This is useful for mapping mesh nodes, events, or points of interest.
### Usage
- **Show Help**
```
map help
```
Displays usage instructions for the map command.
- **Log a Location**
```
map <description>
```
Example:
```
map Found a new mesh node near the park
```
This will log your current location with the description "Found a new mesh node near the park".
### How It Works
- The bot records your user ID, latitude, longitude, and your description in a CSV file (`data/map_data.csv`).
- If your location data is missing or invalid, youll receive an error message.
- You can view or process the CSV file later for mapping or analysis.
**Tip:** Use `map help` at any time to see these instructions in the bot.
---
## EAS & Emergency Alerts
| Command | Description |
|--------------|-----------------------------------------------|
| `ea`/`ealert`| FEMA iPAWS/EAS alerts (USA/DE) |
Enable in `[eas]` section of `config.ini`.
---
## File Monitoring & News
| Command | Description |
|--------------|-----------------------------------------------|
| `readnews` | Read contents of a news file |
| `readrss` | Read RSS feed |
| `x:` | Run shell command (if enabled) |
Configure in `[fileMon]` section of `config.ini`.
---
## Radio Monitoring
| Command | Description |
|--------------|-----------------------------------------------|
| `radio` | Monitor radio SNR via Hamlib |
Configure in `[radioMon]` section of `config.ini`.
---
## Voice Commands (VOX)
You can trigger select bot functions using voice commands with the "Hey Chirpy!" wake word.
Just say "Hey Chirpy..." followed by one of the supported commands:
| Voice Command | Description |
|---------------|---------------------------------------------|
| `joke` | Tells a joke |
| `weather` | Returns local weather forecast |
| `moon` | Returns moonrise/set and phase info |
| `daylight` | Returns sunrise/sunset times |
| `river` | Returns NOAA river flow info |
| `tide` | Returns NOAA tide information |
| `satellite` | Returns satellite pass info |
Enable and configure VOX features in the `[vox]` section of `config.ini`.
---
## Ollama LLM/AI
| Command | Description |
|--------------|-----------------------------------------------|
| `askai` | Ask Ollama LLM AI |
| `ask:` | Ask Ollama LLM AI (raw) |
Configure in `[ollama]` section of `config.ini`.
More at [LLM Readme](llm.md)
---
## Wikipedia Search
| Command | Description |
|--------------|-----------------------------------------------|
| `wiki` | Search Wikipedia or local Kiwix server |
Configure in `[wikipedia]` section of `config.ini`.
---
## DX Spotter Module
The DX Spotter module allows you to fetch and display recent DX cluster spots from [spothole.app](https://spothole.app) directly in your mesh-bot.
### Command
| Command | Description |
|---------|------------------------------|
| `dx` | Show recent DX cluster spots |
###Usage
Send a message to the bot containing the `dx` command. You can add filters to narrow down the results:
- **Basic usage:**
```
dx
```
Returns the latest DX spots.
- **With filters:**
```
dx band=20m mode=SSB
dx xota=WWFF
dx by=K7MHI
```
- `band=`: Filter by band (e.g., 20m, 40m)
- `mode=`: Filter by mode (e.g., SSB, CW, FT8)
- `ota=`: Filter by source/group (e.g., WWFF, POTA, SOTA)
- `of=`: Filter by callsign of the spotted DX
### Example Output
```
K7ABC @14.074 MHz FT8 WWFF KFF-1234 by:N0CALL CN87 Some comment
W1XYZ @7.030 MHz CW SOTA W7W/WE-001 by:K7MHI CN88
```
- Each line shows:
`DX_CALL @FREQUENCY MODE GROUP GROUP_REF by:SPOTTER_CALL SPOTTER_GRID COMMENT`
### Notes
- Returns up to 4 of the most recent spots matching your filters.
- Data is fetched from [spothole.app](https://spothole.app/).
- If no spots are found, youll see:
`No DX spots found.`
### Configuration
```ini
[radioMon]
dxspotter_enabled = True
```
---
## 📅 Mesh Bot Scheduler User Guide
Automate messages and tasks using the scheduler module.
Configure in `[scheduler]` section of `config.ini`.
See modules/custom_scheduler.py for advanced scheduling using python
**Purpose:**
`scheduler.py` provides automated scheduling for Mesh Bot, allowing you to send messages, jokes, weather updates, and custom actions at specific times or intervals.
**How to Use:**
- The scheduler is configured via your bots settings or commands, specifying what to send, when, and on which channel/interface.
- Supports daily, weekly, hourly, and minutely schedules, as well as special jobs like jokes and weather.
- For advanced automation, you can define your own schedules in `etc/custom_scheduler.py` (copied to `modules/custom_scheduler.py` at install).
**Features:**
- **Basic Scheduling:** Send messages on a set schedule (e.g., every day at 09:00, every Monday at noon, every hour, etc.).
- **Joke Scheduler:** Automatically send jokes every x min
- **Weather Scheduler:** Send weather updates at time of day, daily.
- **Custom Scheduler:** run your own scheduled jobs by editing `custom_scheduler.py`.
- **Logging:** All scheduling actions are logged for debugging and monitoring.
**Example Configuration:**
To send a daily message at 09:00:
- `schedulerValue = 'day'`
- `schedulerTime = '09:00'`
- `schedulerMessage = 'Good morning, mesh!'`
**Custom Schedules:**
1. Edit `etc/custom_scheduler.py` to define your custom jobs.
2. On install, this file is copied to `modules/custom_scheduler.py`.
3. Set `schedulerValue = 'custom'` to activate your custom schedules.
**Note:**
- The scheduler uses the [schedule](https://schedule.readthedocs.io/en/stable/) Python library.
- All scheduled jobs run asynchronously as long as the bot is running.
- For troubleshooting, check the logs for scheduler activity and errors.
### Basic Scheduler Options
You can schedule messages or actions using the following options in your configuration:
- **day**: Run every day at a specific time or every N days.
- **mon, tue, wed, thu, fri, sat, sun**: Run on a specific day of the week at a specific time.
- **hour**: Run every N hours.
- **min**: Run every N minutes.
#### **Examples:**
| Option | Time/Interval | What it does |
|-------------|--------------|---------------------------------------------------|
| `day` | `08:00` | Runs every day at 8:00 AM |
| `day` | `2` | Runs every 2 days |
| `mon` | `09:30` | Runs every Monday at 9:30 AM |
| `hour` | `1` | Runs every hour |
| `min` | `30` | Runs every 30 minutes |
- If you specify a day (e.g., `mon`) and a time (e.g., `09:30`), the message will be sent at that time on that day.
- If you specify `hour` or `min`, set the interval (e.g., every 2 hours or every 15 minutes).
---
### Special Scheduler Options
#### **joke**
- Schedules the bot to send a random joke at the specified interval.
- **Example:**
- Option: `joke`
- Interval: `60`
- → Sends a joke every 60 minutes.
#### **link**
- Schedules the bot to send a satellite link message at the specified interval (in hours).
- **Example:**
- Option: `link`
- Interval: `2`
- → Sends a bbslink message every 2 hours.
#### **weather**
- Schedules the bot to send a weather update at the specified time of day, daily.
- **Example:**
- Option: `weather`
- Time: `08:00`
- → Sends a weather update daily at 8:00a.
---
### Days of the Week
You can use any of these options to schedule messages on specific days:
- `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun`
**Example:**
- Option: `fri`
- Time: `17:00`
- → Sends the message every Friday at 5:00 PM.
---
## Other Utilities
- `motd` — Message of the day
- `leaderboard` — Mesh telemetry stats
- `lheard` — Last heard nodes
- `history` — Command history
- `cmd`/`cmd?` — Show help message (the bot avoids the use of saying or using help)
---
## Configuration
- Edit `config.ini` to enable/disable modules and set options.
- See `config.template` for all available settings.
- Each module section in `config.ini` has an `enabled` flag.
---
## Troubleshooting
- Use the `logger` module for debug output.
- See [modules/README.md](modules/README.md) for developer help.
- Use `etc/simulator.py` for local testing.
- Check the logs in the `logs/` directory for errors.
### .ini Settings
If you encounter issues with modules or bot behavior, you can use the `.ini` configuration settings to help diagnose and resolve problems:
### Enable Debug Logging
Increase the logging level to capture more detailed information:
```ini
[general]
sysloglevel = DEBUG
SyslogToFile = True
```
This will log detailed system messages to disk, which you can review in the `logs/` directory.
### Module-Specific Troubleshooting
- **Games Not Working:**
Ensure the relevant game is enabled in the `[games]` section:
```ini
[games]
blackjack = True
dopeWars = True
# ...other games
```
- **Weather/Location Issues:**
Make sure `[location]` and weather modules are enabled and configured:
```ini
[location]
enabled = True
lat = 48.50
lon = -123.0
```
- **BBS Not Responding:**
Check that BBS is enabled and you are not on the ban list:
```ini
[bbs]
enabled = True
bbs_ban_list =
```
- **Scheduler Not Running:**
Confirm the scheduler is enabled and properly configured:
```ini
[scheduler]
enabled = True
value = day
time = 09:00
```
- **File Monitoring Not Working:**
Verify file monitoring is enabled and the correct file path is set:
```ini
[fileMon]
filemon_enabled = True
file_path = alert.txt
```
---
## Messaging Settings
The `[messagingSettings]` section in your `config.ini` controls how messages are handled, split, acknowledged, and logged by Mesh Bot. Adjust these settings to optimize performance, reliability, and debugging for your mesh network.
### Key Options
- **responseDelay**
*Default: 2.2*
Sets the delay (in seconds) before the bot responds to a message. Increase this if you experience message collisions or throttling on busy networks.
- **splitDelay**
*Default: 2.5*
Sets the delay (in seconds) between sending split message chunks. Useful for avoiding collisions when sending long messages that are broken into parts.
- **MESSAGE_CHUNK_SIZE**
*Default: 160*
The maximum number of characters per message chunk. Messages longer than this are automatically split. (The chunker may allow up to 3 extra characters.)
- **wantAck**
*Default: False*
If set to `True`, the bot will request over-the-air (OTA) acknowledgements for sent messages. Enable this for critical messages, but note it may increase network traffic.
- **maxBuffer**
*Default: 200*
Sets the maximum buffer size (in bytes) for radio testing. Increase or decrease based on your hardwares capabilities.
- **enableHopLogs**
*Default: False*
If `True`, enables extra logging of hop count data for each message. Useful for analyzing mesh performance.
- **noisyNodeLogging**
*Default: False*
Enables logging for nodes that generate excessive telemetry or noise. Helps identify problematic devices.
- **noisyTelemetryLimit**
*Default: 5*
The threshold for how many noisy packets trigger logging for a node.
- **logMetaStats**
*Default: True*
Enables logging of metadata statistics for analysis.
- **DEBUGpacket**
*Default: False*
If `True`, logs all packet details for advanced debugging. Only enable if you need deep diagnostics, as this can generate large log files.
- **debugMetadata**
*Default: False*
Enables detailed logging for metaPackets. Use the `metadataFilter` to control which packet types are logged.
- **metadataFilter**
*Default: TELEMETRY_APP,POSITION_APP*
Comma-separated list of packet types to include in metaPacket logging. Adjust to focus on specific data types.
### Troubleshooting Tips
- If you see message collisions or dropped messages, try increasing `responseDelay` and `splitDelay`.
- Enable `DEBUGpacket` and `enableHopLogs` for detailed diagnostics if youre troubleshooting delivery or routing issues.
- Use `noisyNodeLogging` to identify and address problematic nodes on your mesh.
---
**Tip:**
Refer to the comments in `config.template` for further guidance on each setting.
### General Tips
- After changing `.ini` settings, restart the bot to apply changes.
- Check the logs in the `logs/` directory for errors or warnings.
- Use `explicitCmd = True` in `[general]` to require explicit commands, which can help avoid accidental triggers.
- For advanced debugging, set `DEBUGpacket = True` in `[messagingSettings]` to log all packet details.
---
If you continue to have issues, review the logs for error messages and consult the comments in `config.template` for further guidance.
---
### Configuration Guide
The following is documentation for the config.ini file
If you have not done so, or want to 'factory reset', copy the [config.template](config.template) to `config.ini` and set the appropriate interface for your method (serial/ble/tcp). While BLE and TCP will work, they are not as reliable as serial connections. There is a watchdog to reconnect TCP if possible. To get the BLE MAC address, use:
```sh
meshtastic --ble-scan
```
**Note**: The code has been tested with a single BLE device and is written to support only one BLE port.
```ini
# config.ini
# type can be serial, tcp, or ble.
# port is the serial port to use; commented out will try to auto-detect
# hostname is the IP/DNS and port for tcp type default is host:4403
# mac is the MAC address of the device to connect to for BLE type
[interface]
type = serial
# port = '/dev/ttyUSB0'
# hostname = 192.168.0.1
# mac = 00:11:22:33:44:55
# Additional interface for dual radio support. See config.template for more.
[interface2]
enabled = False
```
### General Settings
The following settings determine how the bot responds. By default, the bot will not spam the default channel. Setting `respond_by_dm_only` to `True` will force all messages to be sent via DM, which may not be desired. Setting it to [`False`] will allow responses in the channel for all to see. If you have no default channel you can set this value to `-1` or any unused channel index. You can also have the bot ignore the defaultChannel for any commands, but still observe the channel.
```ini
[general]
respond_by_dm_only = True
defaultChannel = 0
ignoreDefaultChannel = False # ignoreDefaultChannel, the bot will ignore the default channel set above
ignoreChannels = # ignoreChannels is a comma separated list of channels to ignore, e.g. 4,5
cmdBang = False # require ! to be the first character in a command
explicitCmd = True # require explicit command, the message will only be processed if it starts with a command word disable to get more activity
```
### Location Settings
The weather forecasting defaults to NOAA, for locations outside the USA, you can set `UseMeteoWxAPI` to `True`, to use a global weather API. The `lat` and `lon` are default values when a node has no location data, as well as the default for all NOAA, repeater lookup. It is also the center of radius for Sentry.
```ini
[location]
enabled = True
lat = 48.50
lon = -123.0
# To fuzz the location of the above
fuzzConfigLocation = True
# Fuzz all values in all data
fuzzItAll = False
UseMeteoWxAPI = True
coastalEnabled = False # NOAA Coastal Data Enable NOAA Coastal Waters Forecasts and Tide
# Find the correct coastal weather directory at https://tgftp.nws.noaa.gov/data/forecasts/marine/coastal/
# this map can help https://www.weather.gov/marine select location and then look at the 'Forecast-by-Zone Map'
myCoastalZone = https://tgftp.nws.noaa.gov/data/forecasts/marine/coastal/pz/pzz135.txt # myCoastalZone is the .txt file with the forecast data
coastalForecastDays = 3 # number of data points to return, default is 3
```
### Module Settings
Modules can be enabled or disabled as needed. They are essentally larger functions of code which you may not want on your mesh or in memory space.
```ini
[bbs]
enabled = False
[general]
DadJokes = False
StoreForward = False
```
### History
The history command shows the last commands the user ran, and [`lheard`] reflects the last users on the bot.
```ini
enableCmdHistory = True # history command enabler
lheardCmdIgnoreNodes = # command history ignore list ex: 2813308004,4258675309
```
### Sentry Settings
Sentry Bot detects anyone coming close to the bot-node. uses the Location Lat/Lon value.
```ini
SentryEnabled = True # detect anyone close to the bot
emailSentryAlerts = True # if SMTP enabled send alert to sysop email list
SentryRadius = 100 # radius in meters to detect someone close to the bot
SentryChannel = 9 # holdoff time multiplied by seconds(20) of the watchdog
SentryHoldoff = 2 # channel to send a message to when the watchdog is triggered
sentryIgnoreList = # list of ignored nodes numbers ex: 2813308004,4258675309
highFlyingAlert = True # HighFlying Node alert
highFlyingAlertAltitude = 2000 # Altitude in meters to trigger the alert
highflyOpenskynetwork = True # check with OpenSkyNetwork if highfly detected for aircraft
```
### E-Mail / SMS Settings
To enable connectivity with SMTP allows messages from meshtastic into SMTP. The term SMS here is for connection via [carrier email](https://avtech.com/articles/138/list-of-email-to-sms-addresses/)
```ini
[smtp]
# enable or disable the SMTP module, minimum required for outbound notifications
enableSMTP = True # enable or disable the IMAP module for inbound email, not implemented yet
enableImap = False # list of Sysop Emails separate with commas, used only in emergency responder currently
sysopEmails =
# See config.template for all the SMTP settings
SMTP_SERVER = smtp.gmail.com
SMTP_AUTH = True
EMAIL_SUBJECT = Meshtastic✉
```
### Emergency Response Handler
Traps the following ("emergency", "911", "112", "999", "police", "fire", "ambulance", "rescue") keywords. Responds to the user, and calls attention to the text message in logs and via another network or channel.
```ini
[emergencyHandler]
enabled = True # enable or disable the emergency response handler
alert_channel = 2 # channel to send a message to when the emergency handler is triggered
alert_interface = 1
```
### EAS Alerting
To Alert on Mesh with the EAS API you can set the channels and enable, checks every 20min.
#### FEMA iPAWS/EAS and NINA
This uses USA: SAME, FIPS, to locate the alerts in the feed. By default ignoring Test messages.
```ini
eAlertBroadcastEnabled = False # Goverment IPAWS/CAP Alert Broadcast
eAlertBroadcastCh = 2,3 # Goverment Emergency IPAWS/CAP Alert Broadcast Channels
ignoreFEMAenable = True # Ignore any headline that includes followig word list
ignoreFEMAwords = test,exercise
# comma separated list of FIPS codes to trigger local alert. find your FIPS codes at https://en.wikipedia.org/wiki/Federal_Information_Processing_Standard_state_code
myFIPSList = 57,58,53
# find your SAME https://www.weather.gov/nwr/counties comma separated list of SAME code to further refine local alert.
mySAMEList = 053029,053073
# To use other country services enable only a single optional serivce
enableDEalerts = False # Use DE Alert Broadcast Data see template for filters
myRegionalKeysDE = 110000000000,120510000000
```
#### NOAA EAS
This uses the defined lat-long of the bot for collecting of data from the API. see [File-Monitoring](#File-Monitoring) for ideas to collect EAS alerts from a RTL-SDR.
```ini
wxAlertBroadcastEnabled = True # EAS Alert Broadcast
wxAlertBroadcastCh = 2,4 # EAS Alert Broadcast Channels
ignoreEASenable = True # Ignore any headline that includes followig word list
ignoreEASwords = test,advisory
```
#### USGS River flow data and Volcano alerts
Using the USGS water data page locate a water flow device, for example Columbia River at Vancouver, WA - USGS-14144700
Volcano Alerts use lat/long to determine ~1000km radius
```ini
[location]
# USGS Hydrology unique identifiers, LID or USGS ID https://waterdata.usgs.gov
riverList = 14144700 # example Mouth of Columbia River
# USGS Volcano alerts Enable USGS Volcano Alert Broadcast
volcanoAlertBroadcastEnabled = False
volcanoAlertBroadcastCh = 2
```
### Repeater Settings
A repeater function for two different nodes and cross-posting messages. The `repeater_channels` is a list of repeater channels that will be consumed and rebroadcast on the same number channel on the other device, node, or interface. Each node should have matching channel numbers. The channel names and PSK do not need to be the same on the nodes. Use this feature responsibly to avoid creating a feedback loop.
```ini
[repeater] # repeater module
enabled = True
repeater_channels = [2, 3]
```
### Wikipedia Search Settings
The Wikipedia search module can use either the online Wikipedia API or a local Kiwix server for offline wiki access. Kiwix is especially useful for mesh networks operating in remote or offline environments.
```ini
# Enable or disable the wikipedia search module
wikipedia = True
# Use local Kiwix server instead of online Wikipedia
# Set to False to use online Wikipedia (default)
useKiwixServer = False
# Kiwix server URL (only used if useKiwixServer is True)
kiwixURL = http://127.0.0.1:8080
# Kiwix library name (e.g., wikipedia_en_100_nopic_2024-06)
# Find available libraries at https://library.kiwix.org/
kiwixLibraryName = wikipedia_en_100_nopic_2024-06
```
To set up a local Kiwix server:
1. Install Kiwix tools: https://kiwix.org/en/ `sudo apt install kiwix-tools -y`
2. Download a Wikipedia ZIM file to `data/`: https://library.kiwix.org/ `wget https://download.kiwix.org/zim/wikipedia/wikipedia_en_100_nopic_2025-09.zim`
3. Run the server: `kiwix-serve --port 8080 wikipedia_en_100_nopic_2025-09.zim`
4. Set `useKiwixServer = True` in your config.ini with `wikipedia = True`
The bot will automatically extract and truncate content to fit Meshtastic's message size limits (~500 characters).
### Radio Monitoring
A module allowing a Hamlib compatible radio to connect to the bot. When functioning, it will message the configured channel with a message of in use. **Requires hamlib/rigctld to be running as a service.**
```ini
[radioMon]
enabled = True
rigControlServerAddress = localhost:4532
sigWatchBroadcastCh = 2 # channel to broadcast to can be 2,3
signalDetectionThreshold = -10 # minimum SNR as reported by radio via hamlib
signalHoldTime = 10 # hold time for high SNR
signalCooldown = 5 # the following are combined to reset the monitor
signalCycleLimit = 5
```
### File Monitoring
Some dev notes for ideas of use
```ini
[fileMon]
filemon_enabled = True
file_path = alert.txt # text file to monitor for changes
broadcastCh = 2 # channel to send the message to can be 2,3 multiple channels comma separated
enable_read_news = False # news command will return the contents of a text file
news_file_path = news.txt
news_random_line = False # only return a single random line from the news file
enable_runShellCmd = False # enable the use of exernal shell commands, this enables more data in `sysinfo` DM
# if runShellCmd and you think it is safe to allow the x: command to run
# direct shell command handler the x: command in DMs user must be in bbs_admin_list
allowXcmd = True
```
#### Offline EAS
To Monitor EAS with no internet connection see the following notes
- [samedec](https://crates.io/crates/samedec) rust decoder much like multimon-ng
- [sameold](https://crates.io/crates/sameold) rust SAME message translator much like EAS2Text and dsame3
no examples yet for these tools
- [EAS2Text](https://github.com/A-c0rN/EAS2Text)
- depends on [multimon-ng](https://github.com/EliasOenal/multimon-ng), [direwolf](https://github.com/wb2osz/direwolf), [samedec](https://crates.io/crates/samedec) rust decoder much like multimon-ng
- [dsame3](https://github.com/jamieden/dsame3)
- has a sample .ogg file for testing alerts
The following example shell command can pipe the data using [etc/eas_alert_parser.py](etc/eas_alert_parser.py) to alert.txt
```bash
sox -t ogg WXR-RWT.ogg -esigned-integer -b16 -r 22050 -t raw - | multimon-ng -a EAS -v 1 -t raw - | python eas_alert_parser.py
```
The following example shell command will pipe rtl_sdr to alert.txt
```bash
rtl_fm -f 162425000 -s 22050 | multimon-ng -t raw -a EAS /dev/stdin | python eas_alert_parser.py
```
#### Newspaper on mesh
Maintain multiple news sources. Each source should be a file named `{source}_news.txt` in the `data/` directory (for example, `data/mesh_news.txt`).
- To read the default news, use the `readnews` command (reads from `data/news.txt`.
- To read a specific source, use `readnews abc` to read from `data/abc_news.txt`.
This allows you to organize and access different news feeds or categories easily.
External scripts can update these files as needed, and the bot will serve the latest content on request.
### Greet new nodes QRZ module
This isnt QRZ.com this is Q code for who is calling me, this will track new nodes and say hello
```ini
[qrz]
enabled = True # QRZ Hello to new nodes
qrz_hello_string = "send CMD or DM me for more info." # will be sent to all heard nodes once
training = True # Training mode will not send the hello message to new nodes, use this to build up database
```
Happy meshing!

207
modules/adding_more.md Normal file
View File

@@ -0,0 +1,207 @@
# Modules and Adding Features
This document explains how to add new modules and commands to your Meshtastic mesh-bot project.
## Table of Contents
- [Overview](#overview)
- [Adding a New Command](#adding-a-new-command)
- [Running a Shell Command](#running-a-shell-command)
- [Best Practices](#best-practices)
- [Technical Assistance & Troubleshooting](#technical-assistance--troubleshooting)
---
## Overview
For code testing, see `etc/simulator.py` to simulate a bot.
You can also use `meshtasticd` (Linux-native) in `noradio` mode with MQTT server and client to emulate a mesh network.
---
## Adding a New Command
Follow these steps to add a new BBS option or command to the bot:
### 1. Define the Command Handler
Add a new function in `mesh_bot.py` to handle your command.
Example for a command called `newcommand`:
```python
def handle_newcommand(message, message_from_id, deviceID):
return "This is a response from the new command."
```
If your command is complex, consider creating a new module (e.g., `modules/newcommand.py`).
Import your new module where needed (see `modules/system.py` for examples).
---
### 2. Add the Command to the Auto Response
Update the `auto_response` function in `mesh_bot.py` to include your new command:
```python
def auto_response(message, snr, rssi, hop, pkiStatus, message_from_id, channel_number, deviceID, isDM):
#...
"newcommand": lambda: handle_newcommand(message, message_from_id, deviceID),
#...
```
---
### 3. Update the Trap List and Help
Edit `modules/system.py` to include your new command in the trap list and help message:
```python
#...
trap_list = ("cmd", "cmd?", "newcommand") # Add your command here
help_message = "Bot CMD?:newcommand, "
#...
```
**Preferred method:**
Add a configuration block below `ping` (around line 28):
```python
# newcommand Configuration
newcommand_enabled = True # settings.py handles config.ini values; this is a placeholder
if newcommand_enabled:
trap_list_newcommand = ("newcommand",)
trap_list = trap_list + trap_list_newcommand
help_message = help_message + ", newcommand"
```
---
### 4. Test the New Command
Run MeshBot and test your new command by sending a message with `newcommand` to ensure it responds correctly.
---
## Running a Shell Command
You can make a command that calls a bash script on the system (requires the `filemon` module):
```python
def auto_response(message, snr, rssi, hop, pkiStatus, message_from_id, channel_number, deviceID, isDM):
#...
"switchON": lambda: call_external_script(message)
```
This will call the default script located at `script/runShell.sh` and return its output.
---
## Best Practices
- **Modularize:** Place complex or reusable logic in its own module.
- **Document:** Add docstrings and comments to your functions.
- **Test:** Use the simulator or a test mesh to verify new features.
- **Update Help:** Keep the help message and trap list up to date for users.
- **Configuration:** Use `settings.py` and `config.ini` for feature toggles and settings.
---
## Technical Assistance & Troubleshooting
- **Debug Logging:**
Use the `logger` module for debug output. Check logs for errors or unexpected behavior.
- **Common Issues:**
- *Module Import Errors:* Ensure your new module is in the `modules/` directory and imported correctly.
- *Command Not Responding:* Verify your command is in the trap list and auto_response dictionary.
- *Configuration Problems:* Double-check `settings.py` and `config.ini` for typos or missing entries.
- **Testing:**
- Use `etc/simulator.py` for local testing without radio hardware.
- Use `meshtasticd` in `noradio` mode for network emulation.
- **Python Environment:**
- Use a virtual environment (`python3 -m venv venv`) to manage dependencies.
- Install requirements with `pip install -r requirements.txt`.
- **Updating Dependencies:**
- try not to I want to remove some.
- **Getting Help:**
- Check the project wiki or issues page for common questions.
- Use inline comments and docstrings for clarity.
- If youre stuck, ask for help on the projects GitHub Discussions or Issues tab.
---
## Overview Unit Tests
Your test_bot.py file contains a comprehensive suite of unit tests for the various modules the project. The tests are organized using Pythons `unittest` framework and cover both core utility modules and all major game modules.
---
## Structure
- **Imports & Setup:**
The script sets up the environment, imports all necessary modules, and suppresses certain warnings for clean test output.
- **TestBot Class:**
All tests are methods of the `TestBot` class, which inherits from `unittest.TestCase`.
---
## Core Module Tests
- **Database & Checklist:**
- `test_load_bbsdb`, `test_bbs_list_messages`, `test_initialize_checklist_database`
- **News & Alerts:**
- `test_init_news_sources`, `test_get_nina_alerts`
- **LLM & Wikipedia:**
- `test_llmTool_get_google`, `test_send_ollama_query`, `test_get_wikipedia_summary`, `test_get_kiwix_summary`
- **Space & Weather:**
- `test_get_moon_phase`, `test_get_sun_times`, `test_hf_band_conditions`
- **Radio & Location:**
- `test_get_hamlib`, `test_get_rss_feed`, `get_openskynetwork`, `test_initalize_qrz_database`
---
## Game Module Tests
Each game module has a dedicated test that simulates a typical user interaction:
- **Tic-Tac-Toe:**
Starts a game and makes one move.
- **Video Poker:**
Starts a session and places a bet.
- **Blackjack:**
Starts a game and places a bet.
- **Hangman:**
Starts a game and guesses a letter.
- **Lemonade Stand:**
Starts a game and buys a box of cups.
- **GolfSim:**
Starts a hole and takes a shot.
- **DopeWars:**
Starts a game, selects a city, and checks the list.
- **MasterMind:**
Starts a game and makes one guess.
- **Quiz:**
Starts a quiz, joins as a player, answers one question, and ends the quiz.
- **Survey:**
Starts a survey, answers one question, and ends the survey.
- **HamTest:**
Starts a ham radio test and answers one question.
---
## Extended API Tests
If the `.checkall` file is present, additional API and data-fetching tests are run for:
- RepeaterBook, ArtSciRepeaters, NOAA tides/weather, USGS earthquakes/volcanoes, satellite passes, and more.
## Notes
- Tests are designed to be **non-destructive** and **idempotent**.
- Some tests require specific data files (e.g., for quiz, survey, hamtest).
- The suite is intended to be run from the main program directory.
Happy hacking!

234
modules/bbstools.md Normal file
View File

@@ -0,0 +1,234 @@
---
# 📡 meshBBS: How-To & API Documentation
This document covers the Bulliten Board System or BBS componment of the meshing-around project.
## Table of Contents
1. [BBS Core Functions](#1-bbs-core-functions)
- [Central Message Store](#11-central-message-store)
- [Direct Mail (DM) Messages](#12-direct-mail-dm-messages)
- [BBS Commands](#bbs-commands)
2. [Synchronization bot2bot: Full Sync Workflow](#2-synchronization-bot2bot--full-sync-workflow)
- [BBS Database Sync: File-Based (Out-of-Band)](#21-bbs-database-sync-file-based-out-of-band)
- [BBS Over-the-Air (OTA) Sync: Linking](#22-bbs-over-the-air-ota-sync-linking)
- [Scheduling BBS Auto Sync](#23-scheduling-bbs-auto-sync)
3. [Troubleshooting](#4-troubleshooting)
4. [API Reference: BBS Sync](#5-api-reference-bbs-sync)
5. [Best Practices](#5-best-practices)
## 1. **BBS Core Functions**
The mesh-bot provides a basic message mail system for Meshtastic
## 1.1 Central Message Store
- **Shared public message space** for all nodes.
- Classic BBS list with a simple, one-level message tree.
- Messages are stored in `data/bbsdb.pkl`.
- Each entry typically includes:
`[id, subject, body, fromNode, timestamp, threadID, replytoID]`
### Posting to Public
To post a public message:
```sh
bbspost $Subject #Message
```
---
## 1.2 Direct Mail (DM) Messages
- **DMs are private messages** sent from one node to another.
- Stored separately from public posts in `data/bbsdm.pkl`.
- Each DM entry typically includes:
`[id, toNode, message, fromNode, timestamp, threadID, replytoID]`
- You can inject DMs directly for automation using the `script/injectDM.py` tool.
### DM Delivery
- To post a DM, use:
```sh
bbspost @USER #Message
```
- When a DM is posted, it is added to the DM database.
- When the bot detects the recipient node on the network, it delivers the DM and then removes it from local storage.
---
### BBS Commands
| Command | Description |
|--------------|-----------------------------------------------|
| `bbshelp` | Show BBS help |
| `bbslist` | List messages |
| `bbsread` | Read a message by ID |
| `bbspost` | Post a message or DM |
| `bbsdelete` | Delete a message |
| `bbsinfo` | BBS stats (sysop) |
| `bbslink` | Link messages between BBS systems |
---
## 2. **Synchronization bot2bot : Full Sync Workflow**
1. **Set up a dedicated sync channel** (e.g., channel bot-admin).
2. **Configure both nodes** with `bbs_link_enabled = True` and add each other to `bbs_link_whitelist`.
3. **Schedule sync** every hour:
- Node A sends `bbslink 0` to Node B on channel 99.
- Node B responds with messages and `bbsack`.
4. **Optionally, use SSH/scp** to copy `bbsdb.pkl` for full out-of-band backup.
## 2.1. **BBS Database Sync: File-Based (Out-of-Band)**
### **Manual/Automated File Sync (e.g., SSH/SCP)**
- **Purpose:** Sync BBS data between nodes by copying `bbsdb.pkl` and `bbsdm.pkl` files.
```ini
[bbs]
# The "api" needs enabled which enables file polling
bbsAPI_enabled = True
```
- **How-To:**
1. **Locate Files:**
- `data/bbsdb.pkl` (public posts)
- `data/bbsdm.pkl` (direct messages)
2. **Copy Files:**
Use `scp` or `rsync` to copy files between nodes:
```sh
scp user@remote:/path/to/meshing-around/data/bbsdb.pkl ./data/bbsdb.pkl
scp user@remote:/path/to/meshing-around/data/bbsdm.pkl ./data/bbsdm.pkl
```
3. **Reload Database:**
After copying, when the "API" is enabled the watchdog will look for changes and injest.
- **Automating with Cron/Scheduler:**
- Set up a cron job or use the bots scheduler to periodically pull/push files.
---
## 2.2. **BBS Over-the-Air (OTA) Sync: Linking**
### **How OTA Sync Works**
- Nodes can exchange BBS messages using special commands over the mesh network.
- Uses `bbslink` and `bbsack` commands for message exchange.
- Future supports compression for bandwidth efficiency.
### **Enabling BBS Linking**
- Set `bbs_link_enabled = True` in your config.
- Optionally, set `bbs_link_whitelist` to restrict which nodes can sync.
### **Manual Sync Command**
- To troubleshoot request sync from another node, send:
```
bbslink <messageID> $<subject> #<body>
```
- The receiving node will respond with `bbsack <messageID>`.
### **Out-of-Band Channel**
- For high-reliability sync, configure a dedicated channel (not used for chat).
---
## 2.3. **Scheduling BBS Auto Sync**
### **Using the Bots Scheduler**
- You can schedule periodic sync requests to a peer node.
- Example: Every hour, send a `bbslink` request to a peer.
see more at [Module Readme](README.md#scheduler)
---
#### BBS Link
The scheduler also handles the BBS Link Broadcast message, this would be an example of a mesh-admin channel on 8 being used to pass BBS post traffic between two bots as the initiator, one direction pull. The message just needs to have bbslink
```ini
[bbs]
bbslink_enabled = True
bbslink_whitelist = # list of whitelisted nodes numbers ex: 2813308004,4258675309 empty list allows all
[scheduler]
enabled = True
interface = 1
channel = 2
value = link
interval = 12 # 12 hours
```
```python
# Custom Schedule Example if using custom for [scheduler]
# Send bbslink looking for peers every 2 days at 10 AM
schedule.every(2).days.at("10:00").do(send_message("bbslink MeshBot looking for peers", schedulerChannel, 0, schedulerInterface))
```
---
---
## 4. **Troubleshooting**
- **Messages not syncing?**
- Check `bbs_link_enabled` and whitelist settings.
- Ensure both nodes are on the same sync channel.
- Check logs for errors.
- **File sync issues?**
- Verify file permissions and paths.
- Ensure the bot reloads the database after file copy.
- **Custom file problems?**
- remove the custom_scheduler.py and replace it with [etc/custom_scheduler.py](etc/custom_scheduler.py)
The bbs link command should include `bbslink`
`.do(send_message("bbslink MeshBot looking for peers", schedulerChannel, 0, schedulerInterface))`
```ini
[bbs]
# The "api" needs enabled which enables file polling and use of `script/injectDM.py`
bbsAPI_enabled = True
```
## 5. **API Reference: BBS Sync**
### **Key Functions in Python**
| Function | Purpose | Usage Example |
|-------------------------|-------------------------------------------|----------------------------------------------------|
| `bbs_post_message()` | Post a new public message | `bbs_post_message(subject, body, fromNode)` |
| `bbs_read_message()` | Read a message by ID | `bbs_read_message(messageID)` |
| `bbs_delete_message()` | Delete a message (admin/owner only) | `bbs_delete_message(messageID, fromNode)` |
| `bbs_list_messages()` | List all message subjects | `bbs_list_messages()` |
| `bbs_post_dm()` | Post a direct message | `bbs_post_dm(toNode, message, fromNode)` |
| `bbs_check_dm()` | Check for DMs for a node | `bbs_check_dm(toNode)` |
| `bbs_delete_dm()` | Delete a DM after reading | `bbs_delete_dm(toNode, message)` |
| `get_bbs_stats()` | Get stats on BBS and DMs | `get_bbs_stats()` |
| Function | Purpose |
|---------------------------|-------------------------------------------|
| `bbs_sync_posts()` | Handles incoming/outgoing sync requests |
| `bbs_receive_compressed()`| Handles compressed sync data |
| `compress_data()` | Compresses data for OTA transfer |
| `decompress_data()` | Decompresses received data |
### **Handle Incoming Sync**
- The bot automatically processes incoming `bbslink` and `bbsack` commands via `bbs_sync_posts()`.
### **Compressed Sync**
Future Use
- If `useSynchCompression` is enabled, use:
```python
compressed = compress_data(msg)
send_raw_bytes(peerNode, compressed)
```
- Receiving node uses `bbs_receive_compressed()`.
---
### 5. **Best Practices**
- **Backup:** Regularly back up `bbsdb.pkl` and `bbsdm.pkl`.
- **Security:** Use SSH keys for file transfer; restrict OTA sync to trusted nodes.
- **Reliability:** Use a dedicated channel for BBS sync to avoid chat congestion.
- **Automation:** Use the scheduler for regular syncs, both file-based and OTA.
---

View File

@@ -2,8 +2,16 @@
# K7MHI Kelly Keeton 2024
import pickle # pip install pickle
from modules.log import *
from modules.log import logger
from modules.settings import bbs_admin_list, bbs_ban_list, MESSAGE_CHUNK_SIZE, bbs_link_enabled, bbs_link_whitelist, responseDelay
import time
from datetime import datetime
useSynchCompression = False
if useSynchCompression:
import zlib
from modules.system import send_raw_bytes
trap_list_bbs = ("bbslist", "bbspost", "bbsread", "bbsdelete", "bbshelp", "bbsinfo", "bbslink", "bbsack")
@@ -11,24 +19,45 @@ trap_list_bbs = ("bbslist", "bbspost", "bbsread", "bbsdelete", "bbshelp", "bbsin
bbs_messages = []
bbs_dm = []
def load_bbsdb():
global bbs_messages
# load the bbs messages from the database file
try:
with open('data/bbsdb.pkl', 'rb') as f:
bbs_messages = pickle.load(f)
new_bbs_messages = pickle.load(f)
if isinstance(new_bbs_messages, list):
for msg in new_bbs_messages:
msgHash = hash(tuple(msg[1:3]))
if all(hash(tuple(existing_msg[1:3])) != msgHash for existing_msg in bbs_messages):
new_id = len(bbs_messages) + 1
bbs_messages.append([new_id, msg[1], msg[2], msg[3]])
return True # Loaded successfully, regardless of whether new messages were added
return False # File existed but did not contain a valid list of messages (possibly corrupted)
except FileNotFoundError:
# create a new bbsdb.pkl with a welcome message
# template ([messageID, subject, message, fromNode, now, thread, replyto])
bbs_messages = [[1, "Welcome to meshBBS", "Welcome to the BBS, please post a message!",0,time.strftime('%Y-%m-%d %H:%M:%S'),0,0]]
logger.debug("System: bbsdb.pkl not found, creating new one")
try:
with open('data/bbsdb.pkl', 'wb') as f:
pickle.dump(bbs_messages, f)
return True
except Exception as e:
logger.error(f"System: Error creating bbsdb.pkl: {e}")
return False
except Exception as e:
bbs_messages = [[1, "Welcome to meshBBS", "Welcome to the BBS, please post a message!",0]]
logger.debug("System: Creating new data/bbsdb.pkl")
with open('data/bbsdb.pkl', 'wb') as f:
pickle.dump(bbs_messages, f)
logger.error(f"System: Error loading bbsdb.pkl: {e}")
return False
def save_bbsdb():
global bbs_messages
# save the bbs messages to the database file
logger.debug("System: Saving data/bbsdb.pkl")
with open('data/bbsdb.pkl', 'wb') as f:
pickle.dump(bbs_messages, f)
try:
logger.debug("System: Saving data/bbsdb.pkl")
with open('data/bbsdb.pkl', 'wb') as f:
pickle.dump(bbs_messages, f)
except Exception as e:
logger.error(f"System: Error saving bbsdb: {e}")
def bbs_help():
# help message
@@ -40,7 +69,7 @@ def bbs_list_messages():
message_list = ""
for message in bbs_messages:
# message[0] is the messageID, message[1] is the subject
message_list += "Msg #" + str(message[0]) + " " + message[1] + "\n"
message_list += "[#" + str(message[0]) + "] " + message[1] + "\n"
# last newline removed
message_list = message_list[:-1]
@@ -70,7 +99,11 @@ def bbs_delete_message(messageID = 0, fromNode = 0):
else:
return "Please specify a message number to delete."
def bbs_post_message(subject, message, fromNode):
def bbs_post_message(subject, message, fromNode, threadID=0, replytoID=0):
# post a message to the bbsdb
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
thread = threadID
replyto = replytoID
# post a message to the bbsdb and assign a messageID
messageID = len(bbs_messages) + 1
@@ -78,15 +111,17 @@ def bbs_post_message(subject, message, fromNode):
if str(fromNode) in bbs_ban_list:
logger.warning(f"System: Naughty node {fromNode}, tried to post a message: {subject}, {message} and was dropped.")
return "Message posted. ID is: " + str(messageID)
# validate message length isnt three times the MESSAGE_CHUNK_SIZE
if len(message) > (3 * MESSAGE_CHUNK_SIZE):
return "Message too long, max length is " + str(3 * MESSAGE_CHUNK_SIZE) + " characters."
# validate not a duplicate message
for msg in bbs_messages:
if msg[1].strip().lower() == subject.strip().lower() and msg[2].strip().lower() == message.strip().lower():
messageID = msg[0]
return "Message posted. ID is: " + str(messageID)
# validate its not overlength by keeping in chunker limit
# append the message to the list
bbs_messages.append([messageID, subject, message, fromNode])
bbs_messages.append([messageID, subject, message, fromNode, now, thread, replyto])
logger.info(f"System: NEW Message Posted, subject: {subject}, message: {message} from {fromNode}")
# save the bbsdb
@@ -99,8 +134,10 @@ def bbs_read_message(messageID = 0):
if (messageID - 1) >= len(bbs_messages):
return "Message not found."
if messageID > 0:
fromNode = bbs_messages[messageID - 1][3]
fromNodeHex = hex(fromNode)[-4:]
message = bbs_messages[messageID - 1]
return f"Msg #{message[0]}\nMsg Body: {message[2]}"
return f"Msg #{message[0]}\nFrom:{fromNodeHex}\n{message[2]}"
else:
return "Please specify a message number to read."
@@ -116,7 +153,11 @@ def load_bbsdm():
# load the bbs messages from the database file
try:
with open('data/bbsdm.pkl', 'rb') as f:
bbs_dm = pickle.load(f)
new_bbs_dm = pickle.load(f)
if isinstance(new_bbs_dm, list):
for msg in new_bbs_dm:
if msg not in bbs_dm:
bbs_dm.append(msg)
except:
bbs_dm = [[1234567890, "Message", 1234567890]]
logger.debug("System: Creating new data/bbsdm.pkl")
@@ -129,6 +170,14 @@ def bbs_post_dm(toNode, message, fromNode):
if str(fromNode) in bbs_ban_list:
logger.warning(f"System: Naughty node {fromNode}, tried to post a message: {message} and was dropped.")
return "DM Posted for node " + str(toNode)
# validate message length isnt three times the MESSAGE_CHUNK_SIZE
if len(message) > (3 * MESSAGE_CHUNK_SIZE):
return "Message too long, max length is " + str(3 * MESSAGE_CHUNK_SIZE) + " characters."
# validate not a duplicate message
for msg in bbs_dm:
if msg[0] == int(toNode) and msg[1].strip().lower() == message.strip().lower():
return "DM Posted for node " + str(toNode)
# append the message to the list
bbs_dm.append([int(toNode), message, int(fromNode)])
@@ -163,6 +212,32 @@ def bbs_delete_dm(toNode, message):
return "System: cleared mail for" + str(toNode)
return "System: No DM found for node " + str(toNode)
def compress_data(data_to_compress):
# Prepare message as bytes
compressed = zlib.compress(data_to_compress.encode('utf-8'))
return compressed
def decompress_data(data_bytes):
try:
decompressed = zlib.decompress(data_bytes)
msg = decompressed.decode('utf-8')
return msg
except Exception as e:
logger.warning(f"Error decompressing data: {e}")
return False
def bbs_receive_compressed(data_bytes, fromNode, RxNode):
try:
decompressed = zlib.decompress(data_bytes)
msg = decompressed.decode('utf-8')
bbs_sync_posts(msg, fromNode, RxNode)
return msg
except Exception as e:
logger.error(f"Error decompressing BBS message: {e}")
return None
def bbs_sync_posts(input, peerNode, RxNode):
messageID = 0
@@ -180,7 +255,12 @@ def bbs_sync_posts(input, peerNode, RxNode):
#store the message
subject = input.split("$")[1].split("#")[0]
body = input.split("#")[1]
bbs_post_message(subject, body, peerNode)
fromNodeHex = input.split("@")[1]
try:
bbs_post_message(subject, body, int(fromNodeHex, 16))
except:
logger.error(f"System: Error parsing bbslink from node {peerNode}: {input}")
fromNodeHex = hex(peerNode)
messageID = input.split(" ")[1]
return f"bbsack {messageID}"
elif "bbsack" in input.lower():
@@ -195,12 +275,20 @@ def bbs_sync_posts(input, peerNode, RxNode):
# send message with delay to keep chutil happy
if messageID < len(bbs_messages):
logger.debug(f"System: Sending bbslink message {messageID} to peer " + str(peerNode))
logger.debug(f"System: wait to bbslink with peer " + str(peerNode))
fromNodeHex = hex(bbs_messages[messageID][3])
time.sleep(5 + responseDelay)
# every 5 messages add extra delay
if messageID % 5 == 0:
time.sleep(10 + responseDelay)
return f"bbslink {messageID} ${bbs_messages[messageID][1]} #{bbs_messages[messageID][2]}"
logger.debug(f"System: Sending bbslink message {messageID} of {len(bbs_messages)} to peer " + str(peerNode))
msg = f"bbslink {messageID} ${bbs_messages[messageID][1]} #{bbs_messages[messageID][2]} @{fromNodeHex}"
if useSynchCompression:
compressed = compress_data(msg)
send_raw_bytes(peerNode, compressed)
logger.debug("System: Sent compressed bbslink message to peer " + str(peerNode))
else:
return msg
else:
logger.debug("System: bbslink sync complete with peer " + str(peerNode))

View File

@@ -2,24 +2,28 @@
# K7MHI Kelly Keeton 2024
import sqlite3
from modules.log import *
from modules.log import logger
from modules.settings import checklist_db, reverse_in_out, bbs_ban_list
import time
trap_list_checklist = ("checkin", "checkout", "checklist", "purgein", "purgeout")
def initialize_checklist_database():
# create the database
conn = sqlite3.connect(checklist_db)
c = conn.cursor()
# Check if the checkin table exists, and create it if it doesn't
c.execute('''CREATE TABLE IF NOT EXISTS checkin
(checkin_id INTEGER PRIMARY KEY, checkin_name TEXT, checkin_date TEXT, checkin_time TEXT, location TEXT, checkin_notes TEXT)''')
# Check if the checkout table exists, and create it if it doesn't
c.execute('''CREATE TABLE IF NOT EXISTS checkout
(checkout_id INTEGER PRIMARY KEY, checkout_name TEXT, checkout_date TEXT, checkout_time TEXT, location TEXT, checkout_notes TEXT)''')
conn.commit()
conn.close()
logger.debug("System: Ensured data/checklist.db exists with required tables")
try:
conn = sqlite3.connect(checklist_db)
c = conn.cursor()
# Check if the checkin table exists, and create it if it doesn't
c.execute('''CREATE TABLE IF NOT EXISTS checkin
(checkin_id INTEGER PRIMARY KEY, checkin_name TEXT, checkin_date TEXT, checkin_time TEXT, location TEXT, checkin_notes TEXT)''')
# Check if the checkout table exists, and create it if it doesn't
c.execute('''CREATE TABLE IF NOT EXISTS checkout
(checkout_id INTEGER PRIMARY KEY, checkout_name TEXT, checkout_date TEXT, checkout_time TEXT, location TEXT, checkout_notes TEXT)''')
conn.commit()
conn.close()
return True
except Exception as e:
logger.error(f"Checklist: Failed to initialize database: {e}")
return False
def checkin(name, date, time, location, notes):
location = ", ".join(map(str, location))
@@ -122,8 +126,16 @@ def list_checkin():
timeCheckedIn = ""
checkin_list = ""
for row in rows:
#calculate length of time checked in
timeCheckedIn = time.strftime("%H:%M:%S", time.gmtime(time.time() - time.mktime(time.strptime(row[2] + " " + row[3], "%Y-%m-%d %H:%M:%S"))))
# Calculate length of time checked in, including days
total_seconds = time.time() - time.mktime(time.strptime(row[2] + " " + row[3], "%Y-%m-%d %H:%M:%S"))
days = int(total_seconds // 86400)
hours = int((total_seconds % 86400) // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
if days > 0:
timeCheckedIn = f"{days}d {hours:02}:{minutes:02}:{seconds:02}"
else:
timeCheckedIn = f"{hours:02}:{minutes:02}:{seconds:02}"
checkin_list += "ID: " + row[1] + " checked-In for " + timeCheckedIn
if row[5] != "":
checkin_list += "📝" + row[5]
@@ -154,6 +166,17 @@ def process_checklist_command(nodeID, message, name="none", location="none"):
return delete_checkin(nodeID)
elif "purgeout" in message.lower():
return delete_checkout(nodeID)
elif "?" in message.lower():
if not reverse_in_out:
return ("Command: checklist followed by\n"
"checkout to check out\n"
"purgeout to delete your checkout record\n"
"Example: checkin Arrived at park")
else:
return ("Command: checklist followed by\n"
"checkin to check out\n"
"purgeout to delete your checkin record\n"
"Example: checkout Leaving park")
elif "checklist" in message.lower():
return list_checkin()
else:

202
modules/dxspot.py Normal file
View File

@@ -0,0 +1,202 @@
# meshing-around modules/dxspot.py - Handles DX Spotter integration
# Fetches DX spots from Spothole API based on user commands
# 2025 K7MHI Kelly Keeton
import requests
import datetime
from modules.log import logger
from modules.settings import latitudeValue, longitudeValue
trap_list_dxspotter = ["dx"]
def handledxcluster(message, nodeID, deviceID):
from modules.dxspot import get_spothole_spots
if "DX" in message.upper():
logger.debug(f"System: DXSpotter: Device:{deviceID} Handler: DX Spot Request Received from Node {nodeID}")
band = None
mode = None
source = None
dx_call = None
parts = message.split()
for part in parts:
if part.lower().startswith("band="):
band = part.split("=")[1]
elif part.lower().startswith("mode="):
mode = part.split("=")[1]
elif part.lower().startswith("ota="):
source = part.split("=")[1]
elif part.lower().startswith("of="):
dx_call = part.split("=")[1]
# Build params dict
params = {}
if source:
params["source"] = source.upper()
if band:
params["band"] = band.lower()
if mode:
params["mode"] = mode.upper()
if dx_call:
params["dx_call"] = dx_call.upper()
# Fetch spots
spots = get_spothole_spots(**params)
if spots:
response_lines = []
for spot in spots[:5]:
callsign = spot.get('dx_call', spot.get('callsign', 'N/A'))
freq_hz = spot.get('freq', spot.get('frequency', None))
frequency = f"{float(freq_hz)/1e6:.3f} MHz" if freq_hz else "N/A"
mode_val = spot.get('mode', 'N/A')
comment = spot.get('comment', '')
if len(comment) > 111: # Truncate comment to 111 chars
comment = comment[:111] + '...'
sig = spot.get('sig', '')
de_grid = spot.get('de_grid', '')
de_call = spot.get('de_call', '')
sig_ref_name = spot.get('sig_refs_names', [''])[0] if spot.get('sig_refs_names') else ''
line = f"{callsign} @{frequency} {mode_val} {sig} {sig_ref_name} by:{de_call} {de_grid} {comment}"
response_lines.append(line)
response = "\n".join(response_lines)
else:
response = "No DX spots found."
return response
return "Error: No DX command found."
def get_spothole_spots(source=None, band=None, mode=None, date=None, dx_call=None, de_continent=None, de_location=None):
"""
Fetches spots from https://spothole.app/api/v1/spots with optional filters.
Returns a list of spot dicts.
"""
url = "https://spothole.app/api/v1/spots"
params = {}
fetched_count = 0
# Add administrative filters if provided
qrt = False # Always fetch active spots
needs_sig = False # Always need spots wth a group ike Xota
limit = 4
dedupe = True
params["dedupe"] = str(dedupe).lower()
params["limit"] = limit
params["qrt"] = str(qrt).lower()
params["needs_sig"] = str(needs_sig).lower()
params["needs_sig_ref"] = 'true'
# Only get spots from last 9 hours
received_since_dt = datetime.datetime.utcnow() - datetime.timedelta(hours=9)
received_since = int(received_since_dt.timestamp())
params["received_since"] = received_since
# Add spot filters if provided
if source:
params["source"] = source
if band:
params["band"] = band
if mode:
params["mode"] = mode
if date:
# date should be a string in YYYY-MM-DD or datetime.date
if isinstance(date, datetime.date):
params["date"] = date.isoformat()
else:
params["date"] = date
try:
headers = {"User-Agent": "meshing-around-dxspotter/1.0"}
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()
spots = response.json()
except Exception as e:
logger.debug(f"Error fetching spots: {e}")
spots = []
fetched_count = len(spots)
# Admin Filters done via config.ini
de_grid = None # e.g., "EM00"
de_dxcc_id = None # e.g., "291"
de_call = None # e.g., "K7MHI"
dx_itu_zone = None # e.g., "3"
dx_cq_zone = None # e.g., "4"
dx_dxcc_id = None # e.g., "291"
# spotter filters
# location filter
de_latitude = None # e.g., 34.05
de_longitude = None # e.g., -118.25
if de_location:
de_latitude, de_longitude = de_location
elif de_latitude is not None and de_longitude is not None:
de_latitude = latitudeValue
de_longitude = longitudeValue
if de_latitude and de_longitude:
lat_range = (de_latitude - 1.0, de_latitude + 1.0)
lon_range = (de_longitude - 1.0, de_longitude + 1.0)
spots = [spot for spot in spots if lat_range[0] <= spot.get('de_latitude', 0) <= lat_range[1] and
lon_range[0] <= spot.get('de_longitude', 0) <= lon_range[1]]
# grid filter
if de_grid:
spots = [spot for spot in spots if spot.get('de_grid', '').upper() == de_grid.upper()]
# DXCC Filters
if de_dxcc_id:
spots = [spot for spot in spots if str(spot.get('de_dxcc_id', '')) == str(de_dxcc_id)]
# By reporting callsign
if de_call:
spots = [spot for spot in spots if spot.get('de_call', '').upper() == de_call.upper()]
# DX spotted in zone
if dx_itu_zone:
spots = [spot for spot in spots if str(spot.get('dx_itu_zone', '')) == str(dx_itu_zone)]
if dx_cq_zone:
spots = [spot for spot in spots if str(spot.get('dx_cq_zone', '')) == str(dx_cq_zone)]
if dx_dxcc_id:
spots = [spot for spot in spots if str(spot.get('dx_dxcc_id', '')) == str(dx_dxcc_id)]
# User Runtime Filters
# Filter by dx_call if provided
if dx_call:
spots = [spot for spot in spots if spot.get('dx_call', '').upper() == dx_call.upper()]
# Filter by de_continent if provided
if de_continent:
spots = [spot for spot in spots if spot.get('de_continent', '').upper() == de_continent.upper()]
# Filter by de_location if provided
if de_location:
spots = [spot for spot in spots if spot.get('de_location', '').upper() == de_location.upper()]
logger.debug(f"System: Spothole Returning {len(spots)} spots after filtering (fetched {fetched_count})")
return spots
def handle_post_dxspot():
time = int(datetime.datetime.utcnow().timestamp())
freq = 14200000 # 14 MHz
comment = "Test spot please ignore"
de_spot = "N0CALL"
dx_spot = "N0CALL"
spot = {"dx_call": dx_spot, "time": time, "freq": freq, "comment": comment, "de_call": de_spot}
try:
success = post_spothole_spot(spot)
if success:
return "Spot posted successfully."
else:
return "Failed to post spot."
except Exception as e:
logger.debug(f"Error in handle_post_dxspot: {e}")
return "Error occurred while posting spot."
def post_spothole_spot(spot):
"""
Posts a new spot to https://spothole.app/api/v1/spot.
"""
url = "https://spothole.app/api/v1/spot"
headers = {"Content-Type": "application/json", "User-Agent": "meshing-around-dxspotter/1.0"}
try:
response = requests.post(url, json=spot, headers=headers, timeout=10)
response.raise_for_status()
logger.debug(f"Spot posted successfully: {response.json()}")
return True
except Exception as e:
logger.debug(f"Error posting spot: {e}")
return False

View File

@@ -1,18 +1,31 @@
# File monitor module for the meshing-around bot
# 2024 Kelly Keeton K7MHI
from modules.log import *
from modules.log import logger
from modules.settings import (
file_monitor_file_path,
news_file_path,
news_random_line_only,
allowXcmd,
bbs_admin_list,
xCmd2factorEnabled,
xCmd2factor_timeout,
enable_runShellCmd
)
import asyncio
import random
import os
import subprocess
from datetime import datetime, timedelta
trap_list_filemon = ("readnews",)
def read_file(file_monitor_file_path, random_line_only=False):
NEWS_DATA_DIR = os.path.join(os.path.dirname(__file__), '..', 'data')
newsSourcesList = []
def read_file(file_monitor_file_path, random_line_only=False):
try:
if not os.path.exists(file_monitor_file_path):
logger.warning(f"FileMon: File not found: {file_monitor_file_path}")
if file_monitor_file_path == "bee.txt":
return "🐝buzz 💐buzz buzz🍯"
if random_line_only:
@@ -28,25 +41,29 @@ def read_file(file_monitor_file_path, random_line_only=False):
except Exception as e:
logger.warning(f"FileMon: Error reading file: {file_monitor_file_path}")
return None
def read_news():
# read the news file on demand
return read_file(news_file_path, read_news_enabled)
def read_news(source=None):
# Reads the news file. If a source is provided, reads {source}_news.txt.
if source:
file_path = os.path.join(NEWS_DATA_DIR, f"{source}_news.txt")
else:
file_path = os.path.join(NEWS_DATA_DIR, news_file_path)
return read_file(file_path, news_random_line_only)
def write_news(content, append=False):
# write the news file on demand
try:
with open(news_file_path, 'a' if append else 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"FileMon: Updated {news_file_path}")
file_path = os.path.join(NEWS_DATA_DIR, news_file_path)
with open(file_path, 'a' if append else 'w', encoding='utf-8') as f:
#f.write(content)
logger.info(f"FileMon: Updated {file_path}")
return True
except Exception as e:
logger.warning(f"FileMon: Error writing file: {news_file_path}")
logger.warning(f"FileMon: Error writing file: {file_path}")
return False
async def watch_file():
# Watch the file for changes and return the new content when it changes
if not os.path.exists(file_monitor_file_path):
return None
else:
@@ -63,22 +80,117 @@ async def watch_file():
return content
await asyncio.sleep(1) # Check every
def call_external_script(message, script="script/runShell.sh"):
def call_external_script(message, script="runShell.sh"):
# If no path is given, assume script/ directory
if "/" not in script and "\\" not in script:
script = os.path.join("script", script)
try:
# Debugging: Print the current working directory and resolved script path
current_working_directory = os.getcwd()
script_path = os.path.join(current_working_directory, script)
if not os.path.exists(script_path):
# try the raw script name
# Try the raw script name
script_path = script
if not os.path.exists(script_path):
logger.warning(f"FileMon: Script not found: {script_path}")
return "sorry I can't do that"
output = os.popen(f"bash {script_path} {message}").read().encode('utf-8').decode('utf-8')
return output
result = subprocess.run(
["bash", script_path, message],
capture_output=True,
text=True,
timeout=10
)
if result.returncode != 0:
logger.error(f"FileMon: Script error: {result.stderr.strip()}")
return None
output = result.stdout.strip()
return output if output else None
except Exception as e:
logger.warning(f"FileMon: Error calling external script: {e}")
return None
waitingXroom = {} # {message_from_id: (expected_answer, original_command, timestamp)}
def handleShellCmd(message, message_from_id, channel_number, isDM, deviceID):
if not allowXcmd:
return "x: command is disabled"
if str(message_from_id) not in bbs_admin_list:
logger.warning(f"FileMon: Unauthorized x: command attempt from {message_from_id}")
return "x: command not authorized"
if not isDM:
return "x: command not authorized in group chat"
# 2FA logic
if xCmd2factorEnabled:
timeNOW = datetime.utcnow()
# If user is waiting for 2FA, treat message as answer
if message_from_id in waitingXroom:
answer = message[2:].strip() if message.lower().startswith("x:") else message.strip()
expected, orig_command, ts = waitingXroom[message_from_id]
if timeNOW - ts > timedelta(seconds=xCmd2factor_timeout):
del waitingXroom[message_from_id]
return "x2FA timed out, please try again"
if answer == str(expected):
del waitingXroom[message_from_id]
# Run the original command
try:
logger.info(f"FileMon: Running shell command from {message_from_id}: {orig_command}")
result = subprocess.run(orig_command, shell=True, capture_output=True, text=True, timeout=10, start_new_session=True)
output = result.stdout.strip()
return output if output else "✅ x: processed finished, no output"
except Exception as e:
logger.warning(f"FileMon: Error running shell command: {e}")
logger.debug(f"FileMon: This command is not good for use over the mesh network")
return "x: error running command"
else:
logger.warning(f"FileMon: 🚨Incorrect 2FA answer from {message_from_id}")
return "x2FA incorrect, try again"
# If not waiting, treat as new command and issue challenge
if message.lower().startswith("x:"):
command = message[2:].strip()
# Generate two random numbers, seed with message_from_id and time of day
seed = timeNOW.second + timeNOW.minute * 60 + timeNOW.hour * 3600 + int(message_from_id)
rnd = random.Random(seed)
a = rnd.randint(10, 99)
b = rnd.randint(10, 99)
expected = a + b
waitingXroom[message_from_id] = (expected, command, timeNOW)
return f"x2FA required.\nReply `x: answer`\nWhat is {a} + {b}? "
else:
return "invalid command format"
# If we reach here, 2FA is disabled or passed
if enable_runShellCmd:
if message.lower().startswith("x:"):
command = message[2:].strip()
else:
return "invalid command format"
try:
logger.info(f"FileMon: Running shell command from {message_from_id}: {command}")
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=10, start_new_session=True)
output = result.stdout.strip()
return output if output else "x: command executed with no output"
except Exception as e:
logger.warning(f"FileMon: Error running shell command: {e}")
logger.debug(f"FileMon: This command is not good for use over the mesh network")
return "error running command"
else:
logger.debug("FileMon: x: command is disabled by no enable_runShellCmd")
return "command is disabled"
def initNewsSources():
#check for the files _news.txt and add to the newsHeadlines list
global newsSourcesList
newsSourcesList = []
for file in os.listdir(NEWS_DATA_DIR):
if file.endswith('_news.txt'):
source = file[:-9] # remove _news.txt
newsSourcesList.append(source)
return True
logger.info("FileMon: No news sources found")
return False
#initialize the headlines on startup
initNewsSources()

721
modules/games/README.md Normal file
View File

@@ -0,0 +1,721 @@
# Meshtastic Mesh-Bot Games
## Game Index
- [Blackjack](#blackjack-game-module)
- [DopeWars](#dopewars-game-module)
- [GolfSim](#golfsim-game-module)
- [Lemonade Stand](#lemonade-stand-game-module)
- [Tic-Tac-Toe](#tic-tac-toe-game-module)
- [MasterMind](#mastermind-game-module)
- [Video Poker](#video-poker-game-module)
- [Hangman](#hangman-game-module)
- [Quiz](#quiz-game-module)
- [Survey](#survey--module-game)
- [Word of the Day Game](#word-of-the-day-game--rules--features)
---
# Blackjack Game Module
This module implements a classic game of Blackjack (Casino 21) for the Meshtastic mesh-bot.
## How to Play
- **Start the Game:**
Send the command `blackjack` via DM to the bot to start a new game session.
- **Place a Bet:**
When prompted, enter the amount you wish to wager (e.g., `5`). Minimum bet is 1 chip, maximum is your current chip total.
- **Gameplay Commands:**
After betting, you will be dealt two cards. The dealer will also have two cards (one face up).
- `h` or `hit` — Draw another card.
- `s` or `stand` — End your turn and let the dealer play.
- `d` or `double` — Double your bet and draw one more card (if you have enough chips).
- `f` or `forfit` — Forfeit half your bet and end the round.
- `r` or `resend` — Resend your current hand status.
- `l` or `leave` — Leave the table and end your session.
- **Winning:**
- Get as close to 21 as possible without going over.
- If your hand exceeds 21, you bust and lose your bet.
- If you beat the dealer without busting, you win your bet.
- If you get a Blackjack (21 with two cards), you win 1.5x your bet.
- If you tie the dealer, it's a push (no win/loss).
- **High Scores:**
The module tracks the highest chip total achieved. If you beat the high score, you'll be notified!
## Notes
- Each player starts with 100 chips.
- If you run out of chips, your balance will reset to 100.
- The game state is tracked per player using your node ID.
- Game progress and high scores are saved in `data/blackjack_hs.pkl`.
- Only one game session per player is supported at a time.
- For best results, play via DM to avoid interfering with other users' sessions.
## Example Session
```
You have 100 chips. Whats your bet?
> 10
Player[14] 8♠, 6♥
Dealer[10] 10♦
🧠Hit: 38% 👎, 62% 👍
(H)it,(S)tand,(F)orfit,(D)ouble,(R)esend,(L)eave table
> h
Player[18] 8♠, 6♥, 4♣
Dealer[10] 10♦
🧠Hit: 77% 👎, 23% 👍
[H,S,F,D]
> s
Player[18] 8♠, 6♥, 4♣
Dealer[20] 10♦, Q♠
👎DEALER WINS
📊🏆P:0,D:1,T:0
💰You have 90 chips
Bet or Leave?
```
## Credits
- Ported from [Himan10/BlackJack](https://github.com/Himan10/BlackJack)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# DopeWars Game Module
A text-based trading game inspired by the classic DopeWars/DrugWars, adapted for the Meshtastic mesh-bot.
## How to Play
- **Start the Game:**
Send the command `dopewars` via DM to the bot to begin a new session.
- **Objective:**
Travel between cities, buy and sell drugs, and try to maximize your cash in 7 days.
- **Game Flow:**
1. **Pick a Starting City:**
Youll be shown a list of cities. Enter the number to choose your starting location.
2. **Each Day:**
- Youll see drug prices, your inventory, and your cash.
- You can buy, sell, or fly to a new city.
- Random events may occur (police, market changes, or finding cash/drugs).
3. **Commands:**
- **Buy:** `b,drug#,qty#` (e.g., `b,1,10` buys 10 of drug 1)
- **Sell:** `s,drug#,qty#` (e.g., `s,2,5` sells 5 of drug 2)
- **Max:** Use `m` for max quantity (e.g., `b,1,m`)
- **Sell All:** Just `s` to sell everything you have.
- **Fly:** `f` to move to a new city (ends the day).
- **Price List:** `p` to view current prices and inventory.
- **End Game:** `e` to end your run early.
4. **Repeat:**
Each time you fly, a day passes. After 7 days, your final cash is your score.
- **Winning:**
- Try to finish with as much cash as possible.
- Beat the high score to be crowned the top dealer!
## Example Session
```
1. Red Deer 2. Edmonton 3. Calgary 4. Toronto 5. Vancouver 6. St. Johns Where do you want to 🛫?#
> 2
🗺Edmonton 📆1/7 🎒0/100 💵5,000
#1.Cocaine$15,000(0) #2.Heroin$2,500(0) #3.Weed$800(0) ...
Buy💸, Sell💰, (F)ly🛫? (P)riceList?
> b,2,10
Heroin: you have🎒 0 The going price is: $2,500
You bought 10 Heroin. Remaining cash: $47,500
Buy💸, Sell💰, Fly🛫?
> f
🗺Toronto 📆2/7 🎒10/100 💵47,500
...
```
## Notes
- You start with $5,000 and a 100-slot backpack.
- Each drug has a random price per city and day.
- Special events can spike or crash prices, or cause you to lose/gain cash or inventory.
- Police may confiscate your drugs or cash.
- High scores are saved in `data/dopewar_hs.pkl`.
- Only one game session per player at a time.
- Play via DM for best experience.
## Credits
- Ported from [Reconfirefly/drugwars](https://github.com/Reconfirefly/drugwars)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# GolfSim Game Module
A text-based golf simulator for the Meshtastic mesh-bot. Play a full 9-hole round, choose your clubs, and try to set a new course record!
## How to Play
- **Start the Game:**
Send the command `golf` via DM to the bot to begin a new round.
- **Objective:**
Complete 9 holes in as few strokes as possible.
- **Game Flow:**
1. **Each Hole:**
- The bot tells you the hole number, length, par, and any hazards or weather.
- Choose your club for each shot by typing its name or initial:
- `d` or `driver` — Longest club
- `l` or `low` — Low iron
- `m` or `mid` — Mid iron
- `h` or `high` — High iron
- `g` or `gap` — Gap wedge
- `w` or `wedge` — Lob wedge
- `c` or `caddy` — Get a caddy guess for club distances
- The bot will tell you how far you hit and how far remains.
- When youre within 20 yards, youll automatically putt to finish the hole.
2. **Scoring:**
- The bot tracks your strokes and score relative to par.
- After each hole, youll see your score for the hole and your running total.
3. **Hazards & Surprises:**
- Hazards (sand, water, trees, etc.) and random events may affect your shots.
- Critters or weather can cause unexpected results!
4. **End of Round:**
- After 9 holes, your total strokes and score to par are shown.
- If you set a new low score, youll be notified as the new club record holder!
## Example Session
```
⛳️#1 is a 410-yard Par 4.☀️
Choose your club.
> d
🏌Hit D 260yd.
You have 150yd. ⛳️
Club?[D, L, M, H, G, W]🏌️
> m
🏌Hit M Iron 170yd. Overshot the green!🚀
You have 20yd. ⛳️
Club?[D, L, M, H, G, W]🏌️
> w
🏌Hit L Wedge 30yd. You're on the green! After 2 putt(s), you're in for 5 strokes. +Bogey
You've hit a total of 5 strokes today, for +Bogey
...
🎉Finished 9-hole round⛳ 🏆New Club Record🏆
```
## Notes
- Play via DM for best experience.
- Hazards and weather are randomized for each hole.
- High scores are saved in `data/golfsim_hs.pkl`.
- Only one game session per player at a time.
- Commands are not case-sensitive; you can use full club names or initials.
## Credits
- Ported from [danfriedman30/pythongame](https://github.com/danfriedman30/pythongame)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# Lemonade Stand Game Module
A text-based business simulation where you run your own lemonade stand! Buy supplies, set prices, and try to maximize your profits over a summer season.
## How to Play
- **Start the Game:**
Send the command `lemonade` via DM to the bot to begin a new game.
- **Objective:**
Make as much money as possible in 7 weeks by managing your lemonade stand.
- **Game Flow:**
1. **Each Week:**
- The bot will show you the weather, temperature, and sales potential.
- Buy supplies: cups, lemons, and sugar. Enter the number of each to purchase, or `n` for none.
- Set your selling price per cup.
- The bot will simulate sales and show your results, profits, and remaining inventory.
- Repeat for each week.
2. **Commands:**
- Enter a number to buy supplies or set price.
- Use `n` to skip buying an item.
- Enter `g` during pricing to go back and buy more supplies.
- At the end of each week, choose to continue or end the game.
3. **Scoring:**
- Your score is based on your net profit and efficiency (profit vs. possible profit).
- High scores are tracked and displayed at the end of the game.
## Example Session
```
LemonStand🍋Week #1 of 7. 85ºF Sunny ☀️
SupplyCost $0.45 a cup.
Sales Potential: 60 cups.
Inventory: 🥤:0 🍋:0 🍚:0
Prices:
🥤:$2.50 📦 of 25.
🍋:$4.00 🧺 of 8.
🍚:$3.00 bag for 15🥤.
💵:$30.00
🥤 to buy?
Have 0 Cost $2.50 a 📦 of 25
> 2
Purchased 2 📦 50 🥤 in inventory. $25.00 remaining
🍋 to buy?
Have 0🥤 of 🍋 Cost $4.00 a 🧺 for 8🥤
> 1
Purchased 1 🧺 8 🍋 in inventory. $21.00 remaining
🍚 to buy?
You have 0🥤 of 🍚, Cost $3.00 a bag for 15🥤
> 1
Purchased 1 bag(s) of 🍚 for $3.00. 15🥤🍚 in inventory.
Cost of goods is $0.45 per 🥤 $18.00 💵 remaining.
Price to Sell? or (G)rocery to buy more 🥤🍋🍚
> 1.25
Results Week📊#1 of 7 Cost/Price:$0.45/$1.25 P.Margin:$0.80 T.Sales:16@$1.25 G.Profit: $20.00 N.Profit:$12.80
Remaining 🥤:34 🍋:0 🍚:0 💵:$38.00📊P&L📈$8.00
Weekly📊#1. 16 sold x $1.25ea.
Play another week🥤? or (E)nd Game
```
## Notes
- You start with $30.00 and must buy supplies each week.
- Weather and temperature affect sales potential.
- If you run out of any supply, you can't sell more lemonade that week.
- High scores are saved in `data/lemonstand.pkl`.
- Only one game session per player at a time.
- Play via DM for best experience.
## Credits
- Ported from [tigerpointe/Lemonade-Stand](https://github.com/tigerpointe/Lemonade-Stand)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# Tic-Tac-Toe Game Module
A classic Tic-Tac-Toe game for the Meshtastic mesh-bot. Play against the bot, track your stats, and see if you can beat the AI!
## How to Play
- **Start the Game:**
Send the command `tictactoe` via DM to the bot to begin a new game.
- **Objective:**
Get three of your marks in a row (horizontally, vertically, or diagonally) before the bot does.
- **Game Flow:**
1. **Board Layout:**
- The board is numbered 1-9, left to right, top to bottom.
- Example:
```
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
```
2. **Making Moves:**
- On your turn, type the number (1-9) where you want to place your mark.
- The bot will respond with the updated board and make its move.
3. **Commands:**
- `n` — Start a new game.
- `e` or `q` — End the current game.
- `b` — Show the current board.
- Enter a number (1-9) to make a move.
4. **Winning:**
- The first to get three in a row wins.
- If the board fills with no winner, its a tie.
## Example Session
```
❌ | 2 | 3
4 | ⭕️ | 6
7 | 8 | 9
Your turn! Pick 1-9:
> 3
❌ | 2 | ❌
4 | ⭕️ | 6
7 | 8 | 9
🤖Bot wins! (n)ew (e)nd
```
## Notes
- Emojis are used for X and O unless disabled in settings.
- Your win/loss stats are tracked across games.
- The bot will try to win, block you, or pick a random move.
- Play via DM for best experience.
- Only one game session per player at a time.
## Credits
- Written for Meshtastic mesh-bot by Martin
# MasterMind Game Module
A text-based version of the classic code-breaking game MasterMind for the Meshtastic mesh-bot. Try to guess the secret color code in as few turns as possible!
## How to Play
- **Start the Game:**
Send the command `mmind` via DM to the bot to begin a new game.
- **Objective:**
Guess the secret 4-color code in 10 turns or less.
- **Game Flow:**
1. **Choose Difficulty:**
- (N)ormal: 4 colors (R🔴, Y🟡, G🟢, B🔵)
- (H)ard: 6 colors (R🔴, Y🟡, G🟢, B🔵, O🟠, P🟣)
- e(X)pert: 8 colors (R🔴, Y🟡, G🟢, B🔵, O🟠, P🟣, W⚪, K⚫)
- Type `n`, `h`, or `x` to select.
2. **Guessing:**
- Enter a 4-letter code using the color initials (e.g., `RGBY`).
- The bot will respond with feedback:
- ✅ color ✅ position: correct color in the correct spot
- ✅ color 🚫 position: correct color, wrong spot
- 🚫No pins: none of your colors are in the code
- You have 10 turns to guess the code.
3. **Winning:**
- Guess the code exactly to win!
- Your number of turns is tracked for high scores.
- After a win or loss, you can play again by choosing a difficulty.
## Example Session
```
The colors to choose from are:
R🔴, Y🟡, G🟢, B🔵
Enter your guess (e.g., RGBY):
> RGYB
Turn 1:
Guess🔴🟢🟡🔵
✅ color ✅ position: 2
✅ color 🚫 position: 1
> RYGB
Turn 2:
🏆Correct🔴🟡🟢🔵
You are the master mind!🤯
🏆 High Score:2 turns, Difficulty:n
Would you like to play again? (N)ormal, (H)ard, or e(X)pert?
```
## Notes
- Only one game session per player at a time.
- High scores are saved in `data/mmind_hs.pkl`.
- Play via DM for best experience.
- Input is not case-sensitive, but guesses must be exactly 4 letters.
## Credits
- Ported from [pwdkramer/pythonMastermind](https://github.com/pwdkramer/pythonMastermind)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# Video Poker Game Module
A text-based Video Poker game for the Meshtastic mesh-bot. Play classic five-card draw poker, place your bets, and try to build your bankroll!
## How to Play
- **Start the Game:**
Send the command `videopoker` via DM to the bot to begin a new session.
- **Objective:**
Win as many coins as possible by making the best poker hands.
- **Game Flow:**
1. **Place Your Bet:**
- You start with 20 coins.
- Enter your bet (1-5 coins) to begin each hand.
2. **Draw Cards:**
- You are dealt 5 cards.
- The bot will show your hand and a hint about its strength.
3. **Redraw:**
- Choose which cards to replace:
- Enter numbers (e.g., `1,3,4`) to redraw those cards.
- Enter `a` to redraw all cards.
- Enter `n` to keep your current hand.
- Enter `h` to show your hand again.
- You can only redraw once per hand.
4. **Scoring:**
- After the redraw, your hand is scored and winnings are paid out based on the hand type.
- If you run out of coins, your balance resets to 20.
- High scores are tracked and announced.
5. **Continue:**
- Place another bet to play again, or enter `l` to leave the table.
## Example Session
```
You have 20 coins,
Whats your bet?
> 5
K♠ 7♦ 7♣ 2♥ 9♠
Showing:Pair👯
Deal new card?
ex: 1,3,4 or (N)o,(A)ll (H)and
> 1,4
7♦ 7♣ 9♠ 3♣ Q♥
Your hand, Pair👯. Your bankroll is now 22 coins.
Place your Bet, or (L)eave Table.
```
## Hand Rankings & Payouts
- 👑Royal Flush🚽 — 10x bet
- 🧻Straight Flush🚽 — 9x bet
- Flush🚽 — 8x bet
- Full House🏠 — 7x bet
- Four of a Kind👯👯 — 6x bet
- Three of a Kind☘ — 5x bet
- Two Pair👯👯 — 4x bet
- Straight📏 — 3x bet
- Pair👯 — 2x bet
- Bad Hand 🙈 — Lose bet
## Notes
- Only one game session per player at a time.
- High scores are saved in `data/videopoker_hs.pkl`.
- Play via DM for best experience.
- Bets must be between 1 and 5 coins and not exceed your bankroll.
## Credits
- Ported from [devtronvarma/Video-Poker-Terminal-Game](https://github.com/devtronvarma/Video-Poker-Terminal-Game)
- Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
# Word of the Day Game — Rules & Features
- **Word of the Day:**
Each day, a new word is chosen from `data/wotd.json` (or a default list if missing). Mention the word (or its leet/1337 variants) in chat to win and trigger a new word.
- **Bingo Mini-Game:**
A random 3x3 bingo card of words, drawn from `data/bingo.json` (or a default list if missing). Mention words from the card in chat. Complete a row, column, or diagonal to win BINGO and get a new card.
- **Emoji Mini-Game:**
Use emojis in chat to:
- Play a slot machine: send the same emoji several times in a row to hit the JACKPOT!
- **Data Files:**
- `data/wotd.json`: List of words and definitions for the Word of the Day.
[
{
"word": "serendipity",
"meta": "The occurrence of events by chance in a happy or beneficial way."
},
{
"word": "ephemeral",
"meta": "Lasting for a very short time."
},
{
"word": "sonder",
"meta": "The realization that each passerby has a life as vivid and complex as your own."
}
]
- `data/bingo.json`: List of words for bingo cards.
[
"dog",
"cat",
"fish",
"bird",
"hamster",
"rabbit",
"turtle",
"lizard",
"snake"
]
# Hangman Game Module
A classic word-guessing game for the Meshtastic mesh-bot. Try to guess the hidden word one letter at a time before you run out of chances!
## How to Play
- **Start the Game:**
Send the command `hangman` via DM to the bot to begin a new game.
- **Objective:**
Guess the secret word by suggesting letters, one at a time. Each incorrect guess brings you closer to losing!
- **Game Flow:**
1. **New Game:**
- The bot picks a random word and shows you its masked form (e.g., `_ _ _ _ _`).
- Youll see your total games played and games won.
2. **Guessing:**
- Type a single letter to guess.
- Correct guesses reveal all instances of that letter in the word.
- Incorrect guesses are tracked; you have 6 chances before the game ends.
- The bot shows your progress, wrong guesses, and a hangman emoji status.
3. **Winning & Losing:**
- Guess all letters before reaching 6 wrong guesses to win!
- If you lose, the bot reveals the word and starts a new game.
- **Commands:**
- Enter a single letter to guess.
- Start a new game by sending `hangman` again.
## Example Session
```
_ _ _ _ _ _ _
Guess a letter
🥳
Total Games: 1, Won: 1
M E S H T A S T I C
Guess a letter
```
## Notes
- The word list is loaded from `data/hangman.json` if available, or uses a built-in default list. [\"apple\",\"banana\",\"cherry\"]
- Game stats are tracked per player.
- Only one game session per player at a time.
- Play via DM for best experience.
## Data Files
- `data/hangman.json`: List of words for Hangman.
Example:
```
[
"apple",
"banana",
"cherry"
]
```
## Credits
- Written for Meshtastic mesh-bot by ZR1RF Johannes le Roux 2025
# Quiz Game Module
This module implements a multiplayer quiz game for the Meshtastic mesh-bot.
## How to Play
- **Start the Game:**
The quizmaster starts the quiz session (usually with `/quiz start` or similar command).
- **Join the Game:**
Players join by sending `/quiz join` or by answering a question while a quiz is active.
- **Answer Questions:**
- Use `Q: <answer>` to answer the current question.
- For multiple choice, answer with `A`, `B`, `C`, etc.
- For free-text, type the answer after `Q: `.
- Use `Q: ?` to request the next question.
- **Leave the Game:**
Players can leave at any time with `/quiz leave`.
- **Stop the Game:**
The quizmaster stops the quiz session (e.g., `/quiz stop`). Final scores and the top 3 players are announced.
## Rules & Features
- Only the quizmaster can start or stop the quiz.
- Players can join or leave at any time while the quiz is active.
- Questions are loaded from quiz_questions.json and can be multiple choice or free-text.
- Players earn 1 point for each correct answer.
- The first player to answer each question correctly is noted.
- The top 3 players are displayed at the end of the quiz.
- The quizmaster can broadcast messages to all players.
## Example Commands
- Start quiz:
`/quiz start`
- Join quiz:
`/quiz join`
- Answer a question:
`Q: B`
`Q: Paris`
- Next question:
`Q: ?`
- Leave quiz:
`/quiz leave`
- Stop quiz:
`/quiz stop`
## Notes
- Only one quiz can be active at a time.
- Players can only answer each question once.
- The quizmaster is defined by the `bbs_admin_list` variable.
- Questions must be formatted correctly in the JSON file for the game to function.
---
**Written for Meshtastic mesh-bot by K7MHI Kelly Keeton 2025**
Certainly! Heres documentation for the **Survey Game Module** in the same format as your other game modules:
---
# Survey Module "game"
This module implements a survey system for the Meshtastic mesh-bot.
## How to Play
- **Start the Survey:**
Users start a survey by specifying the survey name (e.g., `/survey start example`).
The survey will prompt the user with the first question.
- **Answer Questions:**
- For multiple choice: reply with a letter (A, B, C, ...).
- For integer: reply with a number.
- For text: reply with your answer as text.
After each answer, the next question is shown automatically.
- **End the Survey:**
The survey ends automatically after the last question, or the user can send `end` to finish early.
Responses are saved to a CSV file.
## Rules & Features
- Surveys are defined in JSON files in surveys (e.g., `example_survey.json`).
- Each survey can have multiple choice, integer, or text questions.
- User responses are saved to a CSV file named `<survey_name>_responses.csv` in the same directory.
- Users can only answer each question once per survey session.
- Survey results can be summarized and reported by the bot.
## Example Commands
- Start a survey:
`/survey start example`
- Answer a multiple choice question:
`A`
- Answer an integer question:
`42`
- Answer a text question:
`My favorite color is blue.`
- End the survey early:
`end`
- Get survey results (admin):
`/survey results example`
## Notes
- Only surveys listed in the surveys directory with the `_survey.json` suffix are available.
- Each users responses are tracked separately.
- Results are summarized and can be displayed by the bot.
---
**Written for Meshtastic mesh-bot by K7MHI Kelly Keeton 2025**

View File

@@ -2,13 +2,12 @@
# Adapted for Meshtastic mesh-bot by K7MHI Kelly Keeton 2024
from random import choices, shuffle
from modules.log import *
from modules.log import logger
from modules.settings import jackTracker
import time
import pickle
jack_starting_cash = 100 # Replace 100 with your desired starting cash value
jackTracker= [{'nodeID': 0, 'cmd': 'new', 'time': time.time(), 'cash': jack_starting_cash,\
'bet': 0, 'gameStats': {'p_win': 0, 'd_win': 0, 'draw': 0}, 'p_cards':[], 'd_cards':[], 'p_hand':[], 'd_hand':[], 'next_card':[]}]
SUITS = ("♥️", "♦️", "♠️", "♣️")
RANKS = (
@@ -114,22 +113,35 @@ class jackChips:
self.total -= self.bet
self.winnings -= 1
def success_rate(card, obj_h):
""" Calculate Success rate of 'HIT' new cards """
msg = ""
rate = 0
diff = 21 - obj_h.value
if diff != 0:
rate = (VALUES[card[0][1]] / diff) * 100
def success_rate(next_card, player_hand):
# Estimate the chance of a successful 'HIT' (not busting) in blackjack.
if rate < 100:
msg += f"If Hit, chance {int(rate)}% failure, {100-int(rate)}% success."
else:
l_rate = int(rate - (rate - 99)) # Round to 99
if card[0][1] == "A":
l_rate -= 99
msg += f"If Hit, chance {100-l_rate}% failure, and {l_rate}% success"
return msg
# If player already has 21 or more, hitting will always bust
if player_hand.value >= 21:
return "\n🧠 What do you think?"
# Calculate how much more the player can add without busting
max_safe = 21 - player_hand.value
safe_cards = 0
total_cards = 0
for rank in VALUES:
# 4 cards of each rank in a standard deck
count = 4
card_value = VALUES[rank]
# Ace can be 1 or 11, but here we treat it as 1 if 11 would bust
if rank == "A":
card_value = 1 if player_hand.value + 11 > 21 else 11
# Count as safe if it won't bust the player
if card_value <= max_safe:
safe_cards += count
total_cards += count
# Calculate probability
success_chance = int((safe_cards / total_cards) * 100)
fail_chance = 100 - success_chance
return f"\n🧠Hit: {fail_chance}% 👎, {success_chance}% 👍"
def hits(obj_de):
new_card = [obj_de.deal_cards()[0][0]]
@@ -147,12 +159,12 @@ def display_hand(hand):
def show_some(player_cards, dealer_cards, obj_h):
msg = f"Player[{obj_h.value}] {display_hand(player_cards)} "
msg += f"Dealer[{VALUES[dealer_cards[1][1]]}] {dealer_cards[1][1]}{dealer_cards[1][0]} "
msg += f"\nDealer[{VALUES[dealer_cards[1][1]]}] {dealer_cards[1][1]}{dealer_cards[1][0]} "
return msg
def show_all(player_cards, dealer_cards, obj_h, obj_d):
msg = f"Player[{obj_h.value}] {display_hand(player_cards)} "
msg += f"Dealer[{obj_d.value}] {display_hand(dealer_cards)}"
msg += f"\nDealer[{obj_d.value}] {display_hand(dealer_cards)}"
return msg
def player_bust(obj_h, obj_c):
@@ -229,7 +241,7 @@ def loadHSJack():
pickle.dump(highScore, file)
return 0
def playBlackJack(nodeID, message):
def playBlackJack(nodeID, message, last_cmd=None):
# Initalize the Game
msg, last_cmd = '', None
blackJack = False
@@ -267,10 +279,12 @@ def playBlackJack(nodeID, message):
if last_cmd is None:
# create new player if not in tracker
logger.debug(f"System: BlackJack: New Player {nodeID}")
jackTracker.append({'nodeID': nodeID, 'cmd': 'new', 'time': time.time(), 'cash': jack_starting_cash,\
'bet': 0, 'gameStats': {'p_win': p_win, 'd_win': d_win, 'draw': draw}, 'p_cards':p_cards, 'd_cards':d_cards, 'p_hand':p_hand.cards, 'd_hand':d_hand.cards, 'next_card':next_card})
return f"Welcome to ♠BlackJack♣ you have {p_chips.total} chips. Whats your bet?"
if nodeID != 0:
#logger.debug(f"System: BlackJack: New Player {nodeID}")
jackTracker.append({'nodeID': nodeID, 'cmd': 'new', 'last_played': time.time(), 'cash': jack_starting_cash,\
'bet': 0, 'gameStats': {'p_win': p_win, 'd_win': d_win, 'draw': draw}, 'p_cards':p_cards, 'd_cards':d_cards, 'p_hand':p_hand.cards, 'd_hand':d_hand.cards, 'next_card':next_card})
return f"You have {p_chips.total} chips. Whats your bet?"
return "Error: Player not found."
if getLastCmdJack(nodeID) == "new":
# Place Bet
@@ -283,24 +297,26 @@ def playBlackJack(nodeID, message):
#resend the hand
msg += show_some(p_cards, d_cards, p_hand)
return msg
elif "blackjack" in message.lower():
return f"\nTo place a bet, enter the amount you wish to wager."
else:
try:
bet_money = int(message)
except ValueError:
return "Invalid Bet, please enter a valid number."
return f"\nInvalid Bet, please enter a valid number."
if bet_money <= p_chips.total and bet_money >= 1:
p_chips.bet = bet_money
else:
return f"Invalid Bet, the maximum bet you can place is {p_chips.total} and the minimum bet is 1."
return f"\nInvalid Bet, the maximum bet you can place is {p_chips.total} and the minimum bet is 1."
except ValueError:
return f"Invalid Bet, the maximum bet, {p_chips.total}"
return f"\nInvalid Bet, the maximum bet, {p_chips.total}"
# Show the cards
msg += show_some(p_cards, d_cards, p_hand)
# check for blackjack 21 and only two cards
if p_hand.value == 21 and len(p_hand.cards) == 2:
msg += "Player 🎰 BLAAAACKJACKKKK 💰"
msg += f"\n🎰 BLAAAACKJACKKKK 💰"
p_chips.total += round(p_chips.bet * 1.5)
setLastCmdJack(nodeID, "dealerTurn")
blackJack = True
@@ -317,7 +333,7 @@ def playBlackJack(nodeID, message):
if getLastCmdJack(nodeID) == "betPlaced":
setLastCmdJack(nodeID, "playing")
msg += "(H)it,(S)tand,(F)orfit,(D)ouble,(R)esend,(L)eave table"
msg += f"\n(H)it,(S)tand,(F)orfit,(D)ouble,(R)esend,(L)eave table"
# save the game state
for i in range(len(jackTracker)):
@@ -367,7 +383,7 @@ def playBlackJack(nodeID, message):
# Check if player bust
if player_bust(p_hand, p_chips):
d_win += 1
msg += "💥PlayerBUST💥"
msg += f"\n💥PlayerBUST💥"
setLastCmdJack(nodeID, "dealerTurn")
if getLastCmdJack(nodeID) == "playing":
@@ -419,7 +435,7 @@ def playBlackJack(nodeID, message):
d_hand.add_cards(d_card)
if dealer_bust(d_hand, p_hand, p_chips):
p_win += 1
msg += "💰DealerBUST💥"
msg += f"\n💰DealerBUST💥"
break
# Show all cards
msg += show_all(p_hand.cards, d_hand.cards, p_hand, d_hand)
@@ -427,15 +443,15 @@ def playBlackJack(nodeID, message):
# Check who wins
if push(p_hand, d_hand):
draw += 1
msg += "👌PUSH"
msg += f"\n👌PUSH"
elif player_wins(p_hand, d_hand, p_chips):
p_win += 1
msg += "🎉PLAYER WINS🎰"
msg += f"\n🎉PLAYER WINS🎰"
elif dealer_wins(p_hand, d_hand, p_chips):
d_win += 1
msg += "👎DEALER WINS"
msg += f"\n👎DEALER WINS"
else:
msg += "👎DEALER WINS"
msg += f"\n👎DEALER WINS"
# Display the Game Stats
msg += gameStats(str(p_win), str(d_win), str(draw))
@@ -443,20 +459,20 @@ def playBlackJack(nodeID, message):
# Display the chips left
if p_chips.total < 1:
if p_chips.total > 0:
msg += "🪙Keep the change you filthy animal!"
msg += f"\n🪙Keep the change you filthy animal!"
else:
msg += "💸NO MORE CHIPS!🏧💳"
msg += f"\n💸NO MORE CHIPS!🏧💳"
p_chips.total = jack_starting_cash
else:
# check high score
highScore = loadHSJack()
if highScore != 0 and p_chips.total > highScore['highScore']:
msg += f"💰HighScore💰{p_chips.total} "
msg += f"\n💰HighScore💰{p_chips.total} "
saveHSJack(nodeID, p_chips.total)
else:
msg += f"💰You have {p_chips.total} chips "
msg += f"\n💰You have {p_chips.total} chips "
msg += " Bet or Leave?"
msg += f"\nBet or Leave?"
# Reset the game
setLastCmdJack(nodeID, "new")
@@ -468,6 +484,6 @@ def playBlackJack(nodeID, message):
jackTracker[i]['d_cards'] = []
jackTracker[i]['p_hand'] = []
jackTracker[i]['d_hand'] = []
jackTracker[i]['time'] = time.time()
jackTracker[i]['last_played'] = time.time()
return msg

View File

@@ -4,7 +4,7 @@
import random
import time
import pickle
from modules.log import *
from modules.log import logger
# Global variables
total_days = 7 # number of days or rotations the player has to play
@@ -14,7 +14,7 @@ dwInventoryDb = [{'userID': 1234567890, 'inventory': 0, 'priceList': [], 'amount
dwCashDb = [{'userID': 1234567890, 'cash': starting_cash},]
dwGameDayDb = [{'userID': 1234567890, 'day': 0},]
dwLocationDb = [{'userID': 1234567890, 'location': 'USA', 'loc_choice': 0},]
dwPlayerTracker = [{'userID': 1234567890, 'last_played': time.time(), 'cmd': 'start'},]
from modules.settings import dwPlayerTracker
# high score is saved in a pickle file
dwHighScore = {}
@@ -366,7 +366,8 @@ def get_location_table(nodeID, choice=0):
return loc_table_string
def endGameDw(nodeID):
global dwCashDb, dwInventoryDb, dwLocationDb, dwGameDayDb, dwHighScore
global dwCashDb, dwInventoryDb, dwLocationDb, dwGameDayDb, dwHighScore, dwPlayerTracker
cash = 0
msg = ''
dwHighScore = getHighScoreDw()
# Confirm the cash for the user
@@ -375,23 +376,6 @@ def endGameDw(nodeID):
cash = dwCashDb[i].get('cash')
logger.debug("System: DopeWars: Game Over for user: " + str(nodeID) + " with cash: " + str(cash))
# remove the player from the game databases
for i in range(0, len(dwCashDb)):
if dwCashDb[i].get('userID') == nodeID:
dwCashDb.pop(i)
for i in range(0, len(dwInventoryDb)):
if dwInventoryDb[i].get('userID') == nodeID:
dwInventoryDb.pop(i)
for i in range(0, len(dwLocationDb)):
if dwLocationDb[i].get('userID') == nodeID:
dwLocationDb.pop(i)
for i in range(0, len(dwGameDayDb)):
if dwGameDayDb[i].get('userID') == nodeID:
dwGameDayDb.pop(i)
for i in range(0, len(dwPlayerTracker)):
if dwPlayerTracker[i].get('userID') == nodeID:
dwPlayerTracker.pop(i)
# checks if the player's score is higher than the high score and writes a new high score if it is
if cash > dwHighScore.get('cash'):
dwHighScore = ({'userID': nodeID, 'cash': round(cash, 2)})
@@ -680,6 +664,7 @@ def playDopeWars(nodeID, cmd):
for i in range(0, len(dwPlayerTracker)):
if dwPlayerTracker[i].get('userID') == nodeID:
dwPlayerTracker[i]['cmd'] = 'ask_bsf'
dwPlayerTracker[i]['last_played'] = time.time()
# Game end
if game_day == total_days + 1:

View File

@@ -4,7 +4,7 @@
import random
import time
import pickle
from modules.log import *
from modules.log import logger
# Clubs setup
driver_distances = list(range(230, 280, 5))
@@ -26,7 +26,7 @@ par4_5_range = par4_range + par5_range
# Player setup
playingHole = False
golfTracker = [{'nodeID': 0, 'last_played': time.time(), 'cmd': '', 'hole': 0, 'distance_remaining': 0, 'hole_shots': 0, 'hole_strokes': 0, 'hole_to_par': 0, 'total_strokes': 0, 'total_to_par': 0, 'par': 0, 'hazard': ''}]
from modules.settings import golfTracker
# Club functions
def hit_driver():
@@ -122,9 +122,8 @@ def getHighScoreGolf(nodeID, strokes, par):
return 0
# Main game loop
def playGolf(nodeID, message, finishedHole=False):
def playGolf(nodeID, message, finishedHole=False, last_cmd=''):
msg = ''
global golfTracker
# Course setup
par3_count = 0
par4_count = 0
@@ -133,6 +132,7 @@ def playGolf(nodeID, message, finishedHole=False):
total_strokes = 0
total_to_par = 0
par = 0
hole = 1
# get player's last command from tracker if not new player
last_cmd = ""
@@ -145,8 +145,12 @@ def playGolf(nodeID, message, finishedHole=False):
par = golfTracker[i]['par']
total_strokes = golfTracker[i]['total_strokes']
total_to_par = golfTracker[i]['total_to_par']
if last_cmd == "" or last_cmd == "new":
#update last played time
for i in range(len(golfTracker)):
if golfTracker[i]['nodeID'] == nodeID:
golfTracker[i]['last_played'] = time.time()
if last_cmd == "new":
# Start a new hole
if hole <= 9:
# Set up hole count restrictions on par
@@ -193,17 +197,19 @@ def playGolf(nodeID, message, finishedHole=False):
# Set initial parameters before starting a hole
distance_remaining = hole_length
hole_shots = 0
last_cmd = 'stroking'
# save player's current game state
for i in range(len(golfTracker)):
if golfTracker[i]['nodeID'] == nodeID:
golfTracker[i]['cmd'] = last_cmd
golfTracker[i]['hole'] = hole
golfTracker[i]['distance_remaining'] = distance_remaining
golfTracker[i]['cmd'] = 'stroking'
golfTracker[i]['par'] = par
golfTracker[i]['total_strokes'] = total_strokes
golfTracker[i]['total_to_par'] = total_to_par
golfTracker[i]['hazard'] = hazard
golfTracker[i]['hole'] = hole
golfTracker[i]['last_played'] = time.time()
golfTracker[i]['hole_shots'] = hole_shots
@@ -320,8 +326,8 @@ def playGolf(nodeID, message, finishedHole=False):
else:
last_cmd = 'stroking'
else:
msg += "\nYou have " + str(distance_remaining) + "yd. ⛳️"
msg += "\nClub?[D, L, M, H, G, W]🏌️"
msg += f"\nYou have " + str(distance_remaining) + "yd. ⛳️"
msg += f"\nClub?[D, L, M, H, G, W]🏌️"
# save player's current game state, keep stroking
@@ -365,7 +371,7 @@ def playGolf(nodeID, message, finishedHole=False):
if hole not in [1, 10]:
# Show player total scoring info for the round, except hole 1 and 10
msg += "\nYou've hit a total of " + str(total_strokes) + " strokes today, for"
msg += f"\nYou've hit a total of " + str(total_strokes) + " strokes today, for"
msg += getScorecardGolf(total_to_par)
# Move to next hole
@@ -403,7 +409,7 @@ def playGolf(nodeID, message, finishedHole=False):
logger.debug("System: GolfSim: Player " + str(nodeID) + " has finished their round.")
else:
# Show player the next hole
msg += playGolf(nodeID, 'new', True)
msg += "\n🏌️[D, L, M, H, G, W, End]🏌️"
msg += playGolf(nodeID, '', True, last_cmd='new')
msg += f"\n🏌️[D, L, M, H, G, W, End]🏌️"
return msg

View File

@@ -9,7 +9,7 @@
import json
import random
import os
from modules.log import *
from modules.log import logger
class HamTest:
def __init__(self):

View File

@@ -1,4 +1,7 @@
# Written for Meshtastic mesh-bot by ZR1RF Johannes le Roux 2025
from modules.log import logger, getPrettyTime
import os
import json
import random
class Hangman:
@@ -118,6 +121,25 @@ class Hangman:
def __init__(self):
self.game = {}
self.DEFAULT_WORDS = self.WORDS
# Try to load hangman.json if it exists
hangman_json_path = os.path.join('data', 'hangman.json')
if os.path.exists(hangman_json_path):
try:
with open(hangman_json_path, 'r') as f:
words = json.load(f)
# Ensure it's a list of strings
if isinstance(words, list) and all(isinstance(w, str) for w in words):
self.WORDS = words
else:
self.WORDS = self.DEFAULT_WORDS
except (FileNotFoundError, json.JSONDecodeError):
logger.warning("Failed to load hangman.json, using default words. example JSON: [\"apple\",\"banana\",\"cherry\"]")
self.WORDS = self.DEFAULT_WORDS
else:
self.WORDS = self.DEFAULT_WORDS
def new_game(self, id):
games = won = 0

View File

@@ -2,7 +2,73 @@
# The emoji table of contents is used to replace words in the joke with emojis
# As a Ham, is this obsecuring the meaning of the joke? Or is it enhancing it?
from dadjokes import Dadjoke # pip install dadjokes
from modules.log import *
import random
from modules.log import logger, getPrettyTime
from modules.settings import dad_jokes_emojiJokes, dad_jokes_enabled
lameJokes = [
"Why don't scientists trust atoms? Because they make up everything!",
"Why did the scarecrow win an award? Because he was outstanding in his field!",
"Why don't skeletons fight each other? They don't have the guts.",
"What do you call fake spaghetti? An impasta!",
"Why did the bicycle fall over? Because it was two-tired!",
"Why did the math book look sad? Because it had too many problems.",
"Why did the golfer bring two pairs of pants? In case he got a hole in one.",
"Why did the coffee file a police report? It got mugged.",
"Why did the tomato turn red? Because it saw the salad dressing!",
"Why did the cookie go to the doctor? Because it felt crummy.",
"Why did the computer go to the doctor? Because it had a virus!",
"Why did the chicken join a band? Because it had the drumsticks!",
"Why did the banana go to the doctor? Because it wasn't peeling well.",
"Why did the cow go to space? To see the moooon!",
"Why did the fish blush? Because it saw the ocean's bottom!",
"Why did the elephant bring a suitcase to the zoo? Because it wanted to pack its trunk!",
"Why did the meshtastic node go to therapy? It had too many connections to handle!",
"Why did the meshtastic user bring a ladder to the meeting? To reach new heights in communication!",
"Why did the meshtastic device break up with Wi-Fi? It found a better connection!",
"Why did the meshtastic network throw a party? Because it wanted to mesh well with everyone!",
"Why did the meshtastic node get promoted? Because it was outstanding in its field!",
"Why did the meshtastic user bring a map? To navigate the mesh of possibilities!",
"Why did the meshtastic device go to school? To improve its signal strength!",
"How did the meshtastic node become a comedian? It uses mesh-bots to deliver punchlines!",
"Chuck Norris doesn't read books. He stares them down until he gets the information he wants.",
"When Chuck Norris enters a room, he doesn't turn the lights on. He turns the dark off.",
"Chuck Norris can divide by zero.",
"Chuck Norris counted to infinity. Twice.",
"Chuck Norris can slam a revolving door.",
"When Chuck Norris does a push-up, he isn't lifting himself up; he's pushing the Earth down.",
"Chuck Norris can hear sign language.",
"Death once had a near-Chuck Norris experience.",
"Chuck Norris can unscramble an egg.",
"Chuck Norris can win a game of Connect Four in only three moves.",
"Chuck Norris can make a snowman out of rain.",
"Chuck Norris can strangle you with a cordless phone.",
"Chuck Norris can do a wheelie on a unicycle.",
"Chuck Norris can kill two stones with one bird.",
"Chuck Norris can speak braille.",
"Chuck Norris can build a snowman out of rain.",
"This is a test. A test of the Joke Brodcast System. If this had been an actual joke, you would have been amused.",
"Chuck Norris doesn't join mesh networks. Mesh networks join Chuck's topology.",
"Every time Chuck Norris sends a packet, it arrives before he hits 'send'",
"Chuck Norris doesn't need LoRa. His roundhouse kick has a 15km range with zero latency.",
"When Chuck Norris uses a node, the bandwidth doubles out of fear.",
"Chuck Norris once pinged a device. It replied with an apology and a firmware update.",
"Chuck Norris doesn't use AES encryption. His packets are so secure, they punch hackers in the bits.",
"The Meshtastic protocol has a hidden mode: “Chuck Norris mode.” It only activates when he blinks.",
"Chuck Norris doesn't need a GPS fix. Satellites triangulate themselves around him.",
"Chuck Norris's mesh node doesn't sleep. It meditates while transmitting at full power.",
"Chuck Norris doesn't broadcast. He declares.",
"Chuck Norris once bridged two mesh networks using a shoelace.",
"Chuck Norris's packets don't hop. They teleport out of respect.",
"Chuck Norris doesn't need a repeater. Client_Mute is set to 'Always'.",
"Chuck Norris's mesh messages are entangled. When he sends one, it's already received.",
"Chuck Norris doesn't mesh with others. Others mesh with Chuck.",
"Chuck Norris's node doesn't need a case. The PCB is armored with his beard hair.",
"Chuck Norris once typed “Hello World” and the world replied 'Hello Chuck.'",
]
# pylint: disable=C0103, W0612
imtellingyourightnowiAmTellingYouRightNowThatMotherfErBackThereIsNotReal = ["🐦", "🦅", "🦆", "🦉", "🦜", "🐤", "🐥", "🐣", "🐔", "🐧", "🦚", "🦢", "🦩", "🦤", "🦃", "🐓"]
def tableOfContents():
wordToEmojiMap = {
@@ -35,8 +101,8 @@ def tableOfContents():
'plant': '🌱', 'tree': '🌳', 'flower': '🌸', 'leaf': '🍃', 'cactus': '🌵', 'mushroom': '🍄', 'herb': '🌿', 'bamboo': '🎍', 'rose': '🌹', 'tulip': '🌷', 'sunflower': '🌻',
'hibiscus': '🌺', 'cherry blossom': '🌸', 'bouquet': '💐', 'seedling': '🌱', 'palm tree': '🌴', 'evergreen tree': '🌲', 'deciduous tree': '🌳', 'fallen leaf': '🍂', 'maple leaf': '🍁',
'ear of rice': '🌾', 'shamrock': '☘️', 'four leaf clover': '🍀', 'grapes': '🍇', 'melon': '🍈', 'watermelon': '🍉', 'tangerine': '🍊', 'lemon': '🍋', 'banana': '🍌', 'pineapple': '🍍',
'mango': '🥭', 'apple': '🍎', 'green apple': '🍏', 'pear': '🍐', 'peach': '🍑', 'cherries': '🍒', 'strawberry': '🍓', 'kiwi': '🥝', 'tomato': '🍅', 'coconut': '🥥', 'avocado': '🥑',
'eggplant': '🍆', 'potato': '🥔', 'carrot': '🥕', 'corn': '🌽', 'hot pepper': '🌶️', 'cucumber': '🥒', 'leafy green': '🥬', 'broccoli': '🥦', 'garlic': '🧄', 'onion': '🧅',
'green apple': '🍏', 'pear': '🍐', 'peach': '🍑', 'cherries': '🍒', 'strawberry': '🍓', 'kiwi': '🥝', 'tomato': '🍅', 'coconut': '🥥', 'avocado': '🥑',
'hot pepper': '🌶️', 'cucumber': '🥒', 'leafy green': '🥬', 'broccoli': '🥦', 'garlic': '🧄', 'onion': '🧅',
'peanuts': '🥜', 'chestnut': '🌰', 'bread': '🍞', 'croissant': '🥐', 'baguette': '🥖', 'flatbread': '🥙', 'pretzel': '🥨', 'bagel': '🥯', 'pancakes': '🥞', 'waffle': '🧇', 'cheese': '🧀',
'meat': '🍖', 'poultry': '🍗', 'bacon': '🥓', 'hamburger': '🍔', 'fries': '🍟', 'pizza': '🍕', 'hot dog': '🌭', 'sandwich': '🥪', 'taco': '🌮', 'burrito': '🌯', 'tamale': '🫔',
'stuffed flatbread': '🥙', 'falafel': '🧆', 'egg': '🥚', 'fried egg': '🍳', 'shallow pan of food': '🥘', 'pot of food': '🍲', 'fondue': '🫕', 'bowl with spoon': '🥣', 'green salad': '🥗',
@@ -50,19 +116,19 @@ def tableOfContents():
'globe with meridians': '🌐', 'world map': '🗺️', 'mountain': '⛰️', 'volcano': '🌋', 'mount fuji': '🗻', 'camping': '🏕️', 'beach with umbrella': '🏖️', 'desert': '🏜️', 'desert island': '🏝️',
'national park': '🏞️', 'stadium': '🏟️', 'classical building': '🏛️', 'building construction': '🏗️', 'brick': '🧱', 'rock': '🪨', 'wood': '🪵', 'hut': '🛖', 'houses': '🏘️', 'derelict house': '🏚️',
'house with garden': '🏡', 'office building': '🏢', 'japanese post office': '🏣', 'post office': '🏤', 'hospital': '🏥', 'bank': '🏦', 'hotel': '🏨', 'love hotel': '🏩', 'convenience store': '🏪',
'school': '🏫', 'department store': '🏬', 'factory': '🏭', 'japanese castle': '🏯', 'castle': '🏰', 'wedding': '💒', 'tokyo tower': '🗼', 'statue of liberty': '🗽', 'church': '', 'mosque': '🕌',
'hindu temple': '🛕', 'synagogue': '🕍', 'shinto shrine': '⛩️', 'kaaba': '🕋', 'fountain': '', 'tent': '', 'foggy': '🌁', 'night with stars': '🌃', 'sunrise over mountains': '🌄', 'sunrise': '🌅',
'cityscape at dusk': '🌆', 'sunset': '🌇', 'cityscape': '🏙️', 'bridge at night': '🌉', 'hot springs': '♨️', 'carousel horse': '🎠', 'ferris wheel': '🎡', 'roller coaster': '🎢', 'barber pole': '💈',
'castle': '🏰', 'wedding': '💒', 'tokyo tower': '🗼', 'statue of liberty': '🗽', 'church': '', 'mosque': '🕌',
'fountain': '', 'tent': '', 'foggy': '🌁', 'night with stars': '🌃', 'sunrise over mountains': '🌄', 'sunrise': '🌅',
'cityscape at dusk': '🌆', 'sunset': '🌇', 'cityscape': '🏙️', 'bridge at night': '🌉', 'hot springs': '♨️', 'carousel horse': '🎠', 'barber pole': '💈',
'robot': '🤖', 'alien': '👽', 'ghost': '👻', 'skull': '💀', 'pumpkin': '🎃', 'clown': '🤡', 'wizard': '🧙', 'elf': '🧝', 'fairy': '🧚', 'mermaid': '🧜', 'vampire': '🧛',
'zombie': '🧟', 'genie': '🧞', 'superhero': '🦸', 'supervillain': '🦹', 'mage': '🧙', 'knight': '🛡️', 'ninja': '🥷', 'pirate': '🏴‍☠️', 'angel': '👼', 'devil': '😈', 'dragon': '🐉',
'unicorn': '🦄', 'phoenix': '🦅', 'griffin': '🦅', 'centaur': '🐎', 'minotaur': '🐂', 'cyclops': '👁️', 'medusa': '🐍', 'sphinx': '🦁', 'kraken': '🦑', 'yeti': '❄️', 'sasquatch': '🦧',
'loch ness monster': '🦕', 'chupacabra': '🐐', 'banshee': '👻', 'golem': '🗿', 'djinn': '🧞', 'basilisk': '🐍', 'hydra': '🐉', 'cerberus': '🐶', 'chimera': '🐐', 'manticore': '🦁', 'wyvern': '🐉',
'pegasus': '🦄', 'hippogriff': '🦅', 'kelpie': '🐎', 'selkie': '🦭', 'kitsune': '🦊', 'tanuki': '🦝', 'tengu': '🦅', 'oni': '👹', 'yokai': '👻', 'kappa': '🐢', 'yurei': '👻',
'kami': '👼', 'shinigami': '💀', 'bakemono': '👹', 'tsukumogami': '🧸', 'noppera-bo': '👤', 'rokurokubi': '🧛', 'yuki-onna': '❄️', 'jorogumo': '🕷️', 'nue': '🐍', 'ubume': '👼',
'atom': '⚛️', 'dna': '🧬', 'microscope': '🔬', 'telescope': '🔭', 'rocket': '🚀', 'satellite': '🛰️', 'spaceship': '🛸', 'planet': '🪐', 'black hole': '🕳️', 'galaxy': '🌌',
'comet': '☄️', 'constellation': '🌠', 'lightning': '', 'magnet': '🧲', 'battery': '🔋', 'computer': '💻', 'keyboard': '⌨️', 'mouse': '🖱️', 'printer': '🖨️', 'floppy disk': '💾',
'atom': '⚛️', 'dna': '🧬', 'microscope': '🔬', 'telescope': '🔭', 'satellite': '🛰️', 'spaceship': '🛸', 'planet': '🪐', 'black hole': '🕳️', 'galaxy': '🌌',
'constellation': '🌠', 'lightning': '', 'magnet': '🧲', 'computer': '💻', 'keyboard': '⌨️', 'mouse': '🖱️', 'printer': '🖨️', 'floppy disk': '💾',
'cd': '💿', 'dvd': '📀', 'smartphone': '📱', 'tablet': '📲', 'watch': '', 'camera': '📷', 'video camera': '📹', 'projector': '📽️', 'radio': '📻', 'television': '📺',
'satellite dish': '📡', 'game controller': '🎮', 'joystick': '🕹️', 'vr headset': '🕶️', 'headphones': '🎧', 'speaker': '🔊', 'flashlight': '🔦', 'circuit': '🔌', 'chip': '💻',
'satellite dish': '📡', 'game controller': '🎮', 'joystick': '🕹️', 'vr headset': '🕶️', 'headphones': '🎧', 'speaker': '🔊', 'circuit': '🔌', 'chip': '💻',
'server': '🖥️', 'database': '💾', 'cloud': '☁️', 'network': '🌐', 'code': '💻', 'bug': '🐛', 'virus': '🦠', 'bacteria': '🦠', 'lab coat': '🥼', 'safety goggles': '🥽',
'test tube': '🧪', 'petri dish': '🧫', 'beaker': '🧪', 'bunsen burner': '🔥', 'graduated cylinder': '🧪', 'pipette': '🧪', 'scalpel': '🔪', 'syringe': '💉', 'pill': '💊',
'stethoscope': '🩺', 'thermometer': '🌡️', 'x-ray': '🩻', 'brain': '🧠', 'heart': '❤️', 'lung': '🫁', 'bone': '🦴', 'muscle': '💪', 'robot arm': '🦾', 'robot leg': '🦿',
@@ -71,21 +137,18 @@ def tableOfContents():
'spider': '🕷️', 'scorpion': '🦂', 'turkey': '🦃', 'peacock': '🦚', 'parrot': '🦜', 'swan': '🦢', 'flamingo': '🦩', 'dodo': '🦤', 'sloth': '🦥', 'otter': '🦦',
'skunk': '🦨', 'kangaroo': '🦘', 'badger': '🦡', 'beaver': '🦫', 'bison': '🦬', 'mammoth': '🦣', 'raccoon': '🦝', 'hedgehog': '🦔', 'squirrel': '🐿️', 'chipmunk': '🐿️',
'porcupine': '🦔', 'llama': '🦙', 'giraffe': '🦒', 'zebra': '🦓', 'hippopotamus': '🦛', 'rhinoceros': '🦏', 'gorilla': '🦍', 'orangutan': '🦧', 'elephant': '🐘', 'camel': '🐫',
'llama': '🦙', 'alpaca': '🦙', 'buffalo': '🐃', 'ox': '🐂', 'deer': '🦌', 'moose': '🦌', 'reindeer': '🦌', 'goat': '🐐', 'sheep': '🐑', 'ram': '🐏', 'lamb': '🐑', 'horse': '🐴',
'unicorn': '🦄', 'zebra': '🦓', 'cow': '🐄', 'pig': '🐖', 'boar': '🐗', 'mouse': '🐁', 'rat': '🐀', 'hamster': '🐹', 'rabbit': '🐇', 'chipmunk': '🐿️', 'beaver': '🦫', 'hedgehog': '🦔',
'bat': '🦇', 'bear': '🐻', 'koala': '🐨', 'panda': '🐼', 'sloth': '🦥', 'otter': '🦦', 'skunk': '🦨', 'kangaroo': '🦘', 'badger': '🦡', 'turkey': '🦃', 'chicken': '🐔', 'rooster': '🐓',
'peacock': '🦚', 'parrot': '🦜', 'swan': '🦢', 'flamingo': '🦩', 'dodo': '🦤', 'crocodile': '🐊', 'turtle': '🐢', 'lizard': '🦎', 'snake': '🐍', 'dragon': '🐉', 'sauropod': '🦕', 't-rex': '🦖',
'whale': '🐋', 'dolphin': '🐬', 'fish': '🐟', 'blowfish': '🐡', 'shark': '🦈', 'octopus': '🐙', 'shell': '🐚', 'crab': '🦀', 'lobster': '🦞', 'shrimp': '🦐', 'squid': '🦑', 'snail': '🐌', 'butterfly': '🦋',
'bee': '🐝', 'beetle': '🐞', 'ant': '🐜', 'cricket': '🦗', 'spider': '🕷️', 'scorpion': '🦂', 'mosquito': '🦟', 'microbe': '🦠', 'locomotive': '🚂', 'arm': '💪', 'leg': '🦵', 'sponge': '🧽',
'toothbrush': '🪥', 'broom': '🧹', 'basket': '🧺', 'roll of paper': '🧻', 'bucket': '🪣', 'soap': '🧼', 'toilet paper': '🧻', 'shower': '🚿', 'bathtub': '🛁', 'razor': '🪒', 'lotion': '🧴',
'letter': '✉️', 'envelope': '✉️', 'mail': '📬', 'post': '📮', 'golf': '⛳️', 'golfing': '⛳️', 'office': '🏢', 'meeting': '📅', 'presentation': '📊', 'report': '📄', 'document': '📄',
'alpaca': '🦙', 'buffalo': '🐃', 'ox': '🐂', 'deer': '🦌', 'moose': '🦌', 'reindeer': '🦌', 'goat': '🐐', 'sheep': '🐑', 'ram': '🐏', 'lamb': '🐑', 'horse': '🐴',
'rat': '🐀', 'hedgehog': '🦔', 'chicken': '🐔', 'rooster': '🐓', 'crocodile': '🐊', 'turtle': '🐢', 'lizard': '🦎', 'dragon': '🐉', 'sauropod': '🦕', 't-rex': '🦖', 'butterfly': '🦋',
'mosquito': '🦟', 'microbe': '🦠', 'locomotive': '🚂', 'arm': '💪', 'leg': '🦵', 'sponge': '🧽',
'toothbrush': '🪥', 'roll of paper': '🧻', 'soap': '🧼', 'toilet paper': '🧻', 'shower': '🚿', 'bathtub': '🛁', 'razor': '🪒', 'lotion': '🧴',
'letter': '✉️', 'envelope': '✉️', 'mail': '📬', 'post': '📮', 'golf': '⛳️', 'golfing': '⛳️', 'meeting': '📅', 'presentation': '📊', 'report': '📄', 'document': '📄',
'file': '📁', 'folder': '📂', 'sports': '🏅', 'athlete': '🏃', 'competition': '🏆', 'race': '🏁', 'tournament': '🏆', 'champion': '🏆', 'medal': '🏅', 'victory': '🏆', 'win': '🏆', 'lose': '😞',
'draw': '🤝', 'team': '👥', 'player': '👤', 'coach': '👨‍🏫', 'referee': '🧑‍⚖️', 'stadium': '🏟️', 'arena': '🏟️', 'field': '🏟️', 'court': '🏟️', 'track': '🏟️', 'gym': '🏋️', 'fitness': '🏋️', 'exercise': '🏋️',
'workout': '🏋️', 'training': '🏋️', 'practice': '🏋️', 'game': '🎮', 'match': '🎮', 'score': '🏅', 'goal': '🥅', 'point': '🏅', 'basket': '🏀', 'home run': '⚾️', 'strike': '🎳', 'spare': '🎳', 'frame': '🎳',
'inning': '⚾️', 'quarter': '🏈', 'half': '🏈', 'overtime': '🏈', 'penalty': '⚽️', 'foul': '⚽️', 'timeout': '⏱️', 'substitute': '🔄', 'bench': '🪑', 'sideline': '🏟️', 'dugout': '⚾️', 'locker room': '🚪', 'shower': '🚿',
'uniform': '👕', 'jersey': '👕', 'cleats': '👟', 'helmet': '⛑️', 'pads': '🛡️', 'gloves': '🧤', 'bat': '⚾️', 'ball': '⚽️', 'puck': '🏒', 'stick': '🏒', 'net': '🥅', 'hoop': '🏀', 'goalpost': '🥅', 'whistle': '🔔',
'scoreboard': '📊', 'fans': '👥', 'crowd': '👥', 'cheer': '📣', 'boo': '😠', 'applause': '👏', 'celebration': '🎉', 'parade': '🎉', 'trophy': '🏆', 'medal': '🏅', 'ribbon': '🎀', 'cup': '🏆', 'championship': '🏆',
'league': '🏆', 'season': '🏆', 'playoffs': '🏆', 'finals': '🏆', 'champion': '🏆', 'runner-up': '🥈', 'third place': '🥉', 'snowman': '☃️', 'snowmen': '⛄️'
'league': '🏆', 'season': '🏆', 'playoffs': '🏆', 'finals': '🏆', 'runner-up': '🥈', 'third place': '🥉', 'snowman': '☃️', 'snowmen': '⛄️'
}
return wordToEmojiMap
@@ -115,12 +178,16 @@ def sendWithEmoji(message):
i += 1
return ' '.join(words)
def tell_joke(nodeID=0):
def tell_joke(nodeID=0, vox=False, test=False):
dadjoke = Dadjoke()
if dad_jokes_emojiJokes:
renderedLaugh = sendWithEmoji(dadjoke.joke)
else:
renderedLaugh = dadjoke.joke
return renderedLaugh
if test:
return sendWithEmoji(dadjoke.joke)
try:
if dad_jokes_emojiJokes:
renderedLaugh = sendWithEmoji(dadjoke.joke)
else:
renderedLaugh = dadjoke.joke
return renderedLaugh
except Exception as e:
return random.choice(lameJokes)

View File

@@ -6,8 +6,8 @@ from random import randrange, uniform # random numbers
from types import SimpleNamespace # namespaces support
import pickle # pickle file support
import time # time functions
from modules.log import * # mesh-bot logging
from modules.log import logger # mesh-bot logging
from modules.system import lemonadeTracker # player tracking
import locale # culture specific locale
import math # math functions
import re # regular expressions
@@ -18,7 +18,6 @@ locale.setlocale(locale.LC_ALL, '')
lemon_starting_cash = 30.00
lemon_total_weeks = 7
lemonadeTracker = [{'nodeID': 0, 'cups': 0, 'lemons': 0, 'sugar': 0, 'cash': lemon_starting_cash, 'start': lemon_starting_cash, 'cmd': 'new', 'time': time.time()}]
lemonadeCups = [{'nodeID': 0, 'cost': 2.50, 'count': 25, 'min': 0.99, 'unit': 0.00}]
lemonadeLemons = [{'nodeID': 0, 'cost': 4.00, 'count': 8, 'min': 2.00, 'unit': 0.00}]
lemonadeSugar = [{'nodeID': 0, 'cost': 3.00, 'count': 15, 'min': 1.50, 'unit': 0.00}]
@@ -50,12 +49,14 @@ def getHighScoreLemon():
pickle.dump(high_score, file)
return high_score
def start_lemonade(nodeID, message, celsius=False):
def playLemonstand(nodeID, message, celsius=False, newgame=False):
global lemonadeTracker, lemonadeCups, lemonadeLemons, lemonadeSugar, lemonadeWeeks, lemonadeScore
msg = ""
potential = 0
unit = 0.0
price = 0.0
total_sales = 0
lemonsLastCmd = ''
high_score = getHighScoreLemon()
@@ -94,33 +95,6 @@ def start_lemonade(nodeID, message, celsius=False):
lemonadeScore[i]['value'] = score.value
lemonadeScore[i]['total'] = score.total
def endGame(nodeID):
# remove the player from the tracker
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker.pop(i)
for i in range(len(lemonadeCups)):
if lemonadeCups[i]['nodeID'] == nodeID:
lemonadeCups.pop(i)
for i in range(len(lemonadeLemons)):
if lemonadeLemons[i]['nodeID'] == nodeID:
lemonadeLemons.pop(i)
for i in range(len(lemonadeSugar)):
if lemonadeSugar[i]['nodeID'] == nodeID:
lemonadeSugar.pop(i)
for i in range(len(lemonadeWeeks)):
if lemonadeWeeks[i]['nodeID'] == nodeID:
lemonadeWeeks.pop(i)
for i in range(len(lemonadeScore)):
if lemonadeScore[i]['nodeID'] == nodeID:
lemonadeScore.pop(i)
logger.debug("System: Lemonade: Game Over for " + str(nodeID))
# Check for end of game
if message.lower().startswith("e"):
endGame(nodeID)
return "Goodbye!👋"
title="LemonStand🍋"
# Define the temperature unit symbols
fahrenheit_unit = "ºF"
@@ -213,7 +187,7 @@ def start_lemonade(nodeID, message, celsius=False):
inventory.sugar = lemonadeTracker[i]['sugar']
inventory.cash = lemonadeTracker[i]['cash']
inventory.start = lemonadeTracker[i]['start']
last_cmd = lemonadeTracker[i]['cmd']
lemonsLastCmd = lemonadeTracker[i]['cmd']
for i in range(len(lemonadeCups)):
if lemonadeCups[i]['nodeID'] == nodeID:
cups.cost = lemonadeCups[i]['cost']
@@ -239,15 +213,35 @@ def start_lemonade(nodeID, message, celsius=False):
if lemonadeScore[i]['nodeID'] == nodeID:
score.value = lemonadeScore[i]['value']
score.total = lemonadeScore[i]['total']
if (newgame):
# reset the game values
inventory.cups = 0
inventory.lemons = 0
inventory.sugar = 0
inventory.cash = lemon_starting_cash
inventory.start = lemon_starting_cash
cups.cost = 2.50
cups.unit = round(cups.cost / cups.count, 2)
lemons.cost = 4.00
lemons.unit = round(lemons.cost / lemons.count, 2)
sugar.cost = 3.00
sugar.unit = round(sugar.cost / sugar.count, 2)
weeks.current = 1
weeks.total_sales = 0
weeks.summary = []
score.value = 0.00
score.total = 0.00
lemonsLastCmd = "cups"
# set the last command to new in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "cups"
lemonadeTracker[i]['last_played'] = time.time()
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
# Start the main loop
if (weeks.current <= weeks.total):
if "new" in last_cmd:
# set the last command to cups in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "cups"
if newgame or "new" in lemonsLastCmd:
logger.debug("System: Lemonade: New Game: " + str(nodeID))
# Create a new display buffer for the text messages
buffer= ""
@@ -264,7 +258,7 @@ def start_lemonade(nodeID, message, celsius=False):
buffer += ". " + \
formatted + temperature.units + " " + \
forecastd[list(forecastd)[temperature.forecast]][2] + \
" " + glyph
" " + glyph + f"\n"
# Calculate the potential sales as a percentage of the maximum value
# (lower temperature = fewer sales, severe weather = fewer sales)
@@ -292,44 +286,39 @@ def start_lemonade(nodeID, message, celsius=False):
sugar.unit = round(sugar.cost / sugar.count, 2)
# Calculate the unit cost and display the estimated sales from the forecast potential
unit = cups.unit + lemons.unit + sugar.unit
buffer += " SupplyCost" + locale.currency(unit, grouping=True) + " a cup."
buffer += " Sales Potential:" + str(potential) + " cups."
unit = max(0.01, min(cups.unit + lemons.unit + sugar.unit, 4.0)) # limit the unit cost between $0.01 and $4.00
buffer += f"\nSupplyCost" + locale.currency(round(unit, 2), grouping=True) + " a cup."
buffer += f"\nSales Potential:" + str(potential) + " cups."
# Display the current inventory
buffer += " Inventory:"
buffer += f"\nInventory:"
buffer += "🥤:" + str(inventory.cups)
buffer += "🍋:" + str(inventory.lemons)
buffer += "🍚:" + str(inventory.sugar)
# Display the updated item prices
buffer += f"\nPrices: "
buffer += "🥤:" + \
locale.currency(cups.cost, grouping=True) + " 📦 of " + str(cups.count) + "."
buffer += " 🍋:" + \
locale.currency(lemons.cost, grouping=True) + " 🧺 of " + str(lemons.count) + "."
buffer += " 🍚:" + \
locale.currency(sugar.cost, grouping=True) + " bag for " + str(sugar.count) + "🥤."
buffer += f"\nPrices:\n"
buffer += f"\n🥤:" + locale.currency(round(cups.cost, 2), grouping=True) + " 📦 of " + str(cups.count) + "."
buffer += f"\n🍋:" + locale.currency(round(lemons.cost, 2), grouping=True) + " 🧺 of " + str(lemons.count) + "."
buffer += f"\n🍚:" + locale.currency(round(sugar.cost, 2), grouping=True) + " bag for " + str(sugar.count) + "🥤."
# Display the current cash
gainloss = inventory.cash - inventory.start
buffer += " 💵:" + \
locale.currency(inventory.cash, grouping=True)
buffer += f"\n💵:" + locale.currency(round(inventory.cash, 2), grouping=True)
# if the player is in the red
pnl = locale.currency(gainloss, grouping=True)
pnl = locale.currency(round(gainloss, 2), grouping=True)
if "0.00" not in pnl:
if pnl.startswith("-"):
buffer += "📊P&L📉" + pnl
else:
buffer += "📊P&L📈" + pnl
buffer += f"\n🥤 to buy? Have {inventory.cups} Cost {locale.currency(cups.cost, grouping=True)} a 📦 of {str(cups.count)}"
buffer += f"\n🥤 to buy?\nHave {inventory.cups} Cost {locale.currency(cups.cost, grouping=True)} a 📦 of {str(cups.count)}"
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
return buffer
if "cups" in last_cmd:
if "cups" in lemonsLastCmd and not newgame:
# Read the number of cup boxes to purchase
newcups = -1
if "n" in message.lower():
@@ -343,22 +332,22 @@ def start_lemonade(nodeID, message, celsius=False):
inventory.cups += (newcups * cups.count)
inventory.cash -= cost
msg = "Purchased " + str(newcups) + " 📦 "
msg += str(inventory.cups) + " 🥤 in inventory. " + locale.currency(inventory.cash, grouping=True) + f" remaining"
msg += str(inventory.cups) + " 🥤 in inventory. " + locale.currency(round(inventory.cash, 2), grouping=True) + f" remaining"
else:
msg = "No 🥤 were purchased"
except Exception as e:
return "invalid input, enter the number of 🥤 to purchase or (N)one"
msg += f"\n 🍋 to buy?\nHave {inventory.lemons}🥤 of 🍋 Cost {locale.currency(lemons.cost, grouping=True)} a 🧺 for {str(lemons.count)}🥤"
# set the last command to lemons in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "lemons"
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
msg += f"\n 🍋 to buy? Have {inventory.lemons}🥤 of 🍋 Cost {locale.currency(lemons.cost, grouping=True)} a 🧺 for {str(lemons.count)}🥤"
return msg
if "lemons" in last_cmd:
if "lemons" in lemonsLastCmd and not newgame:
# Read the number of lemon bags to purchase
newlemons = -1
if "n" in message.lower():
@@ -379,15 +368,15 @@ def start_lemonade(nodeID, message, celsius=False):
newlemons = -1
return "invalid input, enter the number of 🍋 to purchase"
msg += f"\n 🍚 to buy?\nYou have {inventory.sugar}🥤 of 🍚, Cost {locale.currency(sugar.cost, grouping=True)} a bag for {str(sugar.count)}🥤"
# set the last command to sugar in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "sugar"
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
msg += f"\n 🍚 to buy? You have {inventory.sugar}🥤 of 🍚, Cost {locale.currency(sugar.cost, grouping=True)} a bag for {str(sugar.count)}🥤"
return msg
if "sugar" in last_cmd:
if "sugar" in lemonsLastCmd and not newgame:
# Read the number of sugar bags to purchase
newsugar = -1
if "n" in message.lower():
@@ -407,8 +396,8 @@ def start_lemonade(nodeID, message, celsius=False):
except Exception as e:
return "invalid input, enter the number of 🍚 bags to purchase"
msg += f"Cost of goods is {locale.currency(unit, grouping=True)}"
msg += f"per 🥤 {locale.currency(inventory.cash, grouping=True)} 💵 remaining."
msg += f"Cost of goods is {locale.currency(round(unit, 2), grouping=True)}"
msg += f"per 🥤 {locale.currency(round(inventory.cash, 2), grouping=True)} 💵 remaining."
msg += f"\nPrice to Sell? or (G)rocery to buy more 🥤🍋🍚"
# set the last command to price in the inventory db
@@ -418,17 +407,17 @@ def start_lemonade(nodeID, message, celsius=False):
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
return msg
if "price" in last_cmd:
if "price" in lemonsLastCmd and not newgame:
# set the last command to sales in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "sales"
if "g" in message.lower():
lemonadeTracker[i]['cmd'] = "cups"
msg = f"#of🥤 to buy? Have {inventory.cups} Cost {locale.currency(cups.cost, grouping=True)} a 📦 of {str(cups.count)}"
msg = f"#of🥤\nto buy? Have {inventory.cups} Cost {locale.currency(cups.cost, grouping=True)} a 📦 of {str(cups.count)}"
return msg
else:
last_cmd = "sales"
lemonsLastCmd = "sales"
# Read the actual price
price = 0.00
@@ -440,7 +429,7 @@ def start_lemonade(nodeID, message, celsius=False):
return "The price must be greater than zero."
except Exception as e:
price = 0.00
last_cmd = "price"
lemonsLastCmd = "price"
return "Invalid input, enter the price of the lemonade per 🥤"
# this isnt sent to the user, not needed
@@ -448,7 +437,7 @@ def start_lemonade(nodeID, message, celsius=False):
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
if "sales" in last_cmd:
if "sales" in lemonsLastCmd and not newgame:
# Calculate the weekly sales based on price and lowest inventory level
# (higher markup price = fewer sales, limited by the inventory on-hand)
sales = get_sales_amount(potential, unit, price)
@@ -478,7 +467,7 @@ def start_lemonade(nodeID, message, celsius=False):
msg += " N.Profit:" + locale.currency(net, grouping=True)
# Display the updated inventory levels
msg += "\nRemaining"
msg += f"\nRemaining"
msg += " 🥤:" + str(inventory.cups)
msg += " 🍋:" + str(inventory.lemons)
msg += " 🍚:" + str(inventory.sugar)
@@ -495,7 +484,7 @@ def start_lemonade(nodeID, message, celsius=False):
pad_week = len(str(weeks.total))
pad_sale = len(str(weeks.sales))
total = 0
msg += "\nWeekly📊"
msg += f"\nWeekly📊"
for i in range(len(weeks.summary)):
msg += "#" + str(weeks.current).rjust(pad_week) + ". " + str(weeks.summary[i]['sales']).rjust(pad_sale) + \
" sold x " + locale.currency(weeks.summary[i]['price'], grouping=True) + "ea. "
@@ -535,7 +524,7 @@ def start_lemonade(nodeID, message, celsius=False):
if (inventory.sugar <= 0):
msg += " You ran out of sugar.🍚"
else:
msg += "\nCongratulations 🍋🍋 your sales were perfect!🎉"
msg += f"\nCongratulations 🍋🍋 your sales were perfect!🎉"
# Increment the score counters
score.value = score.value + minnet
@@ -546,32 +535,32 @@ def start_lemonade(nodeID, message, celsius=False):
if (weeks.current == weeks.total):
# end of the game
success = round((score.value / score.total) * 100)
msg += "\nYou've made " + locale.currency(score.value, grouping=True) + " out of a possible " + \
msg += f"\nYou've made " + locale.currency(score.value, grouping=True) + " out of a possible " + \
locale.currency(score.total, grouping=True) + " for a score of " + str(success) + "% "
msg += "You've sold " + str(weeks.total_sales) + " total 🥤🍋"
msg += f"\nYou've sold " + str(weeks.total_sales) + " total 🥤🍋"
# check for high score
high_score = getHighScoreLemon()
if (inventory.cash > int(high_score['cash'])):
msg += "\nCongratulations! You've set a new high score!🎉💰🍋"
msg += f"\nCongratulations! You've set a new high score!🎉💰🍋"
high_score['cash'] = inventory.cash
high_score['success'] = success
high_score['userID'] = nodeID
with open('data/lemonstand.pkl', 'wb') as file:
pickle.dump(high_score, file)
endGame(nodeID)
else:
# keep playing
weeks.current = weeks.current + 1
msg += f"\nPlay another week🥤? or (E)nd Game"
# set the last command to new in the inventory db
for i in range(len(lemonadeTracker)):
if lemonadeTracker[i]['nodeID'] == nodeID:
lemonadeTracker[i]['cmd'] = "new"
lemonadeTracker[i]['time'] = time.time()
weeks.current = weeks.current + 1
msg += f"Play another week🥤? or (E)nd Game"
lemonadeTracker[i]['last_played'] = time.time()
saveValues(nodeID, inventory, cups, lemons, sugar, weeks, score)
return msg
else:
return "Game Over! Start a (N)ew Game or (E)xit"

View File

@@ -12,7 +12,7 @@ Game Rules:
"""
import pickle
from modules.log import *
from modules.log import logger, getPrettyTime
from datetime import datetime, timedelta
from geopy.distance import geodesic

View File

@@ -4,9 +4,8 @@
import random
import time
import pickle
from modules.log import *
mindTracker = [{'nodeID': 0, 'last_played': time.time(), 'cmd': '', 'secret_code': '', 'diff': 'n', 'turns': 1}]
from modules.log import logger
from modules.system import mindTracker
def chooseDifficultyMMind(message):
usrInput = message.lower()
@@ -62,98 +61,63 @@ def makeCodeMMind(diff):
return secret_code
#get guess from user
def getGuessMMind(diff, guess):
msg = ''
if diff == "n":
valid_colorsMMind = "RYGB"
elif diff == "h":
valid_colorsMMind = "RYGBOP"
elif diff == "x":
valid_colorsMMind = "RYGBOPWK"
user_guess = guess.upper()
valid_guess = True
if len(user_guess) != 4:
valid_guess = False
for i in range(len(user_guess)):
if user_guess[i] not in valid_colorsMMind:
valid_guess = False
if valid_guess == False:
user_guess = "XXXX"
def getGuessMMind(diff, guess, nodeID):
valid_colors = {
"n": "RYGB",
"h": "RYGBOP",
"x": "RYGBOPWK"
}
user_guess = guess.strip().upper()
if len(user_guess) != 4 or any(c not in valid_colors.get(diff, "RYGB") for c in user_guess):
return "XXXX"
#increase the turn count and store in tracker
for i in range(len(mindTracker)):
if mindTracker[i]['nodeID'] == nodeID:
mindTracker[i]['turns'] += 1
mindTracker[i]['last_played'] = time.time()
mindTracker[i]['diff'] = diff
return user_guess
def getHighScoreMMind(nodeID, turns, diff):
# check if player is in high score list and pick the lowest score
try:
with open('mmind_hs.pkl', 'rb') as f:
mindHighScore = pickle.load(f)
except:
logger.debug("System: MasterMind: High Score file not found.")
mindHighScore = [{'nodeID': nodeID, 'turns': turns, 'diff': diff}]
with open('mmind_hs.pkl', 'wb') as f:
pickle.dump(mindHighScore, f)
import os
hs_file = 'data/mmind_hs.pkl'
# Try to load existing high scores
if os.path.exists(hs_file):
try:
with open(hs_file, 'rb') as f:
mindHighScore = pickle.load(f)
except Exception as e:
logger.debug(f"System: MasterMind: Error loading high score file: {e}")
mindHighScore = []
else:
mindHighScore = []
# If nodeID==0, just return 0
if nodeID == 0:
# just return the high score
mindHighScore = [{'nodeID': 0, 'turns': 0, 'diff': 'n'}]
return mindHighScore
# calculate lowest score
lowest_score = mindHighScore[0]['turns']
# If no high score, add this one
if not mindHighScore:
mindHighScore = [{'nodeID': nodeID, 'turns': turns, 'diff': diff}]
with open(hs_file, 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
if mindHighScore[0]['diff'] == "n" and diff == "n":
if lowest_score > turns:
# update the high score for normal if new score is lower
mindHighScore[0]['nodeID'] = nodeID
mindHighScore[0]['turns'] = turns
mindHighScore[0]['diff'] = diff
# write new high score to file
with open('mmind_hs.pkl', 'wb') as f:
# If the diff matches, compare and update if better
if mindHighScore[0]['diff'] == diff:
if turns < mindHighScore[0]['turns']:
mindHighScore[0] = {'nodeID': nodeID, 'turns': turns, 'diff': diff}
with open(hs_file, 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
elif mindHighScore[0]['diff'] == "n" and diff == "h":
# update the high score for hard if normal is the only high score
mindHighScore[0]['nodeID'] = nodeID
mindHighScore[0]['turns'] = turns
mindHighScore[0]['diff'] = diff
# write new high score to file
with open('mmind_hs.pkl', 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
elif mindHighScore[0]['diff'] == "h" and diff == "h":
if lowest_score > turns:
# update the high score for hard if new score is lower
mindHighScore[0]['nodeID'] = nodeID
mindHighScore[0]['turns'] = turns
mindHighScore[0]['diff'] = diff
# write new high score to file
with open('mmind_hs.pkl', 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
elif mindHighScore[0]['diff'] == "n" or mindHighScore[0]['diff'] == "h" and diff == "x":
# update the high score for expert if normal or high is the only high score
mindHighScore[0]['nodeID'] = nodeID
mindHighScore[0]['turns'] = turns
mindHighScore[0]['diff'] = diff
# write new high score to file
with open('mmind_hs.pkl', 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
elif mindHighScore[0]['diff'] == "x" and diff == "x":
if lowest_score > turns:
# update the high score for expert if new score is lower
mindHighScore[0]['nodeID'] = nodeID
mindHighScore[0]['turns'] = turns
mindHighScore[0]['diff'] = diff
# write new high score to file
with open('mmind_hs.pkl', 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
return 0
# If the diff is different, replace with new high score for new diff
mindHighScore[0] = {'nodeID': nodeID, 'turns': turns, 'diff': diff}
with open(hs_file, 'wb') as f:
pickle.dump(mindHighScore, f)
return mindHighScore
def getEmojiMMind(secret_code):
@@ -182,7 +146,7 @@ def getEmojiMMind(secret_code):
return secret_code_emoji
#compare userGuess with secret code and provide feedback
def compareCodeMMind(secret_code, user_guess):
def compareCodeMMind(secret_code, user_guess, nodeID):
game_won = False
perfect_pins = 0
wrong_position = 0
@@ -210,9 +174,26 @@ def compareCodeMMind(secret_code, user_guess):
temp_code.remove(guess) # Remove the first occurrence of the matched color
# display feedback
if game_won:
msg += f"Correct{getEmojiMMind(user_guess)}\n"
msg += f"\n🏆Correct{getEmojiMMind(user_guess)}\nYou are the master mind!🤯"
# get turn count from tracker
for i in range(len(mindTracker)):
if mindTracker[i]['nodeID'] == nodeID:
turns = mindTracker[i]['turns'] - 2 # subtract 2 to account for increment after last guess and starting at 1
diff = mindTracker[i]['diff']
# get high score
high_score = getHighScoreMMind(nodeID, turns, diff)
if high_score[0]['turns'] != 0:
msg += f"\n🏆 High Score:{turns} turns, Difficulty:{diff}"
# reset turn count in tracker
msg += f"\nWould you like to play again? (N)ormal, (H)ard, or e(X)pert?"
# reset turn count in tracker
for i in range(len(mindTracker)):
if mindTracker[i]['nodeID'] == nodeID:
mindTracker[i]['turns'] = 0
mindTracker[i]['secret_code'] = ''
mindTracker[i]['cmd'] = 'new'
else:
msg += f"Guess{getEmojiMMind(user_guess)}\n"
msg += f"\nGuess{getEmojiMMind(user_guess)}\n"
if perfect_pins > 0 and game_won == False:
msg += "✅ color ✅ position: {}".format(perfect_pins)
@@ -231,11 +212,11 @@ def playGameMMind(diff, secret_code, turn_count, nodeID, message):
msg = ''
won = False
if turn_count <= 10:
user_guess = getGuessMMind(diff, message)
user_guess = getGuessMMind(diff, message, nodeID)
if user_guess == "XXXX":
msg += f"Invalid guess. Please enter 4 valid colors letters.\n🔴🟢🔵🔴 is RGBR"
return msg
check_guess = compareCodeMMind(secret_code, user_guess)
check_guess = compareCodeMMind(secret_code, user_guess, nodeID)
# display turn count and feedback
msg += "Turn {}:".format(turn_count)
@@ -245,18 +226,6 @@ def playGameMMind(diff, secret_code, turn_count, nodeID, message):
if won == True:
msg += f"\n🎉🧠 you win 🥷🤯"
# get high score
high_score = getHighScoreMMind(nodeID, turn_count, diff)
if high_score != 0:
msg += f"\n🏆 High Score:{high_score[0]['turns']} turns, Difficulty:{high_score[0]['diff'].upper()}"
msg += "\nWould you like to play again?\n(N)ormal, (H)ard, e(X)pert (E)nd?"
# reset turn count in tracker
for i in range(len(mindTracker)):
if mindTracker[i]['nodeID'] == nodeID:
mindTracker[i]['turns'] = 1
mindTracker[i]['secret_code'] = ''
mindTracker[i]['cmd'] = 'new'
else:
# increment turn count and keep playing
turn_count += 1
@@ -266,12 +235,12 @@ def playGameMMind(diff, secret_code, turn_count, nodeID, message):
mindTracker[i]['turns'] = turn_count
elif won == False:
msg += f"🙉Game Over🙈\nThe code was: {getEmojiMMind(secret_code)}"
msg += "\nYou have run out of turns.😿"
msg += "\nWould you like to play again? (N)ormal, (H)ard, or e(X)pert?"
msg += f"\nYou have run out of turns.😿"
msg += f"\nWould you like to play again? (N)ormal, (H)ard, or e(X)pert?"
# reset turn count in tracker
for i in range(len(mindTracker)):
if mindTracker[i]['nodeID'] == nodeID:
mindTracker[i]['turns'] = 1
mindTracker[i]['turns'] = 0
mindTracker[i]['secret_code'] = ''
mindTracker[i]['cmd'] = 'new'

166
modules/games/quiz.py Normal file
View File

@@ -0,0 +1,166 @@
# Quiz Module for meshbot 2025
# Provides a quiz game function with multiple choice and free-text questions
# Quizmaster can start/stop the quiz, players can join/leave, answer questions
# Scores are tracked, first correct answer is noted, top 3 players announced at end
# Questions are loaded from a JSON file in data/quiz_questions.json
# Questions can be multiple choice (with answers array) or free-text (with answer string)
# Players answer with "Q: <answer>" format, "Q: ?" for next question, locked to DM
# unlike a normal game, players can join/leave anytime during the quiz but the QuizMaster needs to start or open game
# Quizmaster can broadcast messages to all players
import json
import os
import random
from modules.log import logger
from modules.settings import bbs_admin_list
QUIZ_JSON = os.path.join(os.path.dirname(__file__), '../', '../', 'data', 'quiz_questions.json')
QUIZMASTER_ID = bbs_admin_list
trap_list_quiz = ("quiz", "q:")
help_text_quiz = "quiz",
class QuizGame:
def __init__(self):
self.quizmaster = QUIZMASTER_ID
self.active = False
self.players = {} # user_id: {'score': int, 'current_q': int, 'answered': set()}
self.questions = [] # Loaded from JSON
self.first_correct = {} # q_idx: user_id
self.load_questions()
def start_game(self, quizmaster_id):
if str(quizmaster_id) not in self.quizmaster:
return "Only the quizmaster can start the quiz."
if self.active:
return "Quiz already running."
self.active = True
logger.debug(f"QuizMaster: {quizmaster_id} started a new quiz round.")
self.players = {}
self.first_correct = {} # Reset on new game
self.load_questions()
return "Quiz started! Players can now join."
def load_questions(self):
try:
with open(QUIZ_JSON, 'r') as f:
self.questions = json.load(f)
# Shuffle questions to ensure randomness each game
#random.shuffle(self.questions)
except Exception as e:
logger.error(f"Failed to load quiz questions: {e}")
self.questions = []
def stop_game(self, quizmaster_id):
if not self.active or str(quizmaster_id) not in self.quizmaster:
return "Only the quizmaster can stop the quiz."
return_msg = "Quiz stopped! Final scores:\n" + self.top_three()
logger.debug(f"QuizMaster: {quizmaster_id} stopped the quiz.")
self.active = False
self.players = {}
return return_msg
def join(self, user_id):
if not self.active:
return "No quiz running. Wait for the quizmaster to start."
if user_id in self.players:
return "You are already in the quiz."
self.players[user_id] = {'score': 0, 'current_q': 0, 'answered': set()}
reminder = f"Joined!\n'Q: <Answer>' 'Q: ?' for more.\n"
logger.debug(f"QuizMaster: Player {user_id} joined the round.")
return reminder + self.next_question(user_id)
def leave(self, user_id):
if user_id in self.players:
del self.players[user_id]
logger.debug(f"QuizMaster: Player {user_id} left the round.")
return "You left the quiz."
return "You are not in the quiz."
def next_question(self, user_id):
if user_id not in self.players:
return "Join the quiz first."
player = self.players[user_id]
while player['current_q'] < len(self.questions) and player['current_q'] in player['answered']:
player['current_q'] += 1
if player['current_q'] >= len(self.questions):
return f"No more questions. Your final score: {player['score']}."
q = self.questions[player['current_q']]
msg = f"Q{player['current_q']+1}: {q['question']}\n"
if "answers" in q:
for i, opt in enumerate(q['answers']):
msg += f"{chr(65+i)}. {opt}\n"
msg = msg.strip()
return msg
def answer(self, user_id, answer):
if user_id not in self.players:
return "Join the quiz first."
player = self.players[user_id]
q_idx = player['current_q']
if q_idx >= len(self.questions):
return "No more questions."
if q_idx in player['answered']:
return "Already answered. Type 'next' for another question."
q = self.questions[q_idx]
# Check if it's multiple choice or free-text
if "answers" in q and "correct" in q:
try:
ans_idx = ord(answer.upper()) - 65
if ans_idx == q['correct']:
player['score'] += 1
# Track first correct answer
if q_idx not in self.first_correct:
self.first_correct[q_idx] = user_id
logger.info(f"QuizMaster: Question {q_idx+1} first user with correct answer by {user_id}")
result = "Correct! 🎉"
else:
result = f"Wrong. Correct answer: {chr(65+q['correct'])}"
player['answered'].add(q_idx)
player['current_q'] += 1
return f"{result}\n" + self.next_question(user_id)
except Exception:
return "Invalid answer. Use A, B, C, etc."
elif "answer" in q:
user_ans = answer.strip().lower()
correct_ans = str(q['answer']).strip().lower()
if user_ans == correct_ans:
player['score'] += 1
if q_idx not in self.first_correct:
self.first_correct[q_idx] = user_id
logger.info(f"QuizMaster: Question {q_idx+1} first user with correct answer by {user_id}")
result = "Correct! 🎉"
else:
result = f"Wrong. Correct answer: {q['answer']}"
player['answered'].add(q_idx)
player['current_q'] += 1
return f"{result}\n" + self.next_question(user_id)
else:
return "Invalid question format."
def top_three(self):
if not self.players:
return "No players in the quiz."
ranking = sorted(self.players.items(), key=lambda x: x[1]['score'], reverse=True)
count = min(3, len(ranking))
msg = f"🏆 Top {count} Player{'s' if count > 1 else ''}:\n"
for idx, (uid, pdata) in enumerate(iterable=ranking[:count], start=1):
msg += f"{idx}. {uid}: @{pdata['score']}\n"
return msg
def broadcast(self, quizmaster_id, message):
msgToAll = {}
if quizmaster_id and str(quizmaster_id) not in self.quizmaster:
return "Only the quizmaster can broadcast."
if not self.players:
return "No players to broadcast to."
# set up message
message_to_send = f"📢 From Quizmaster: {message}"
msgToAll['message'] = message_to_send
# setup players
for uid in self.players.keys():
msgToAll.setdefault('players', []).append(uid)
return msgToAll
# Initialize the quiz game
quizGamePlayer = QuizGame()

276
modules/games/tictactoe.py Normal file
View File

@@ -0,0 +1,276 @@
# Tic-Tac-Toe game for Meshtastic mesh-bot
# Board positions chosen by numbers 1-9
# 2025
import random
import time
import modules.settings as my_settings
# to (max), molly and jake, I miss you both so much.
if my_settings.disable_emojis_in_games:
X = "X"
O = "O"
else:
X = ""
O = "⭕️"
class TicTacToe:
def __init__(self):
self.game = {}
def new_game(self, id):
positiveThoughts = ["🚀I need to call NATO",
"🏅Going for the gold!",
"Mastering ❌TTT⭕",]
sorryNotGoinWell = ["😭Not your day, huh?",
"📉Results here dont define you.",
"🤖WOPR would be proud."]
"""Start a new game"""
games = won = 0
ret = ""
if id in self.game:
games = self.game[id]["games"]
won = self.game[id]["won"]
if games > 3:
if won / games >= 3.14159265358979323846: # win rate > pi
ret += random.choice(positiveThoughts) + "\n"
else:
ret += random.choice(sorryNotGoinWell) + "\n"
# Retain stats
ret += f"Games:{games} 🥇❌:{won}\n"
self.game[id] = {
"board": [" "] * 9, # 3x3 board as flat list
"player": X, # Human is X, bot is O
"games": games + 1,
"won": won,
"turn": "human" # whose turn it is
}
ret += self.show_board(id)
ret += "Pick 1-9:"
return ret
def rndTeaPrice(self, tea=42):
"""Return a random tea between 0 and tea."""
return random.uniform(0, tea)
def show_board(self, id):
"""Display compact board with move numbers"""
g = self.game[id]
b = g["board"]
# Show board with positions
board_str = ""
for i in range(3):
row = ""
for j in range(3):
pos = i * 3 + j
if my_settings.disable_emojis_in_games:
cell = b[pos] if b[pos] != " " else str(pos + 1)
else:
cell = b[pos] if b[pos] != " " else f" {str(pos + 1)} "
row += cell
if j < 2:
row += " | "
board_str += row
if i < 2:
board_str += "\n"
return board_str + "\n"
def make_move(self, id, position):
"""Make a move for the current player"""
g = self.game[id]
# Validate position
if position < 1 or position > 9:
return False
pos = position - 1
if g["board"][pos] != " ":
return False
# Make human move
g["board"][pos] = X
return True
def bot_move(self, id):
"""AI makes a move: tries to win, block, or pick random"""
g = self.game[id]
board = g["board"]
# Try to win
move = self.find_winning_move(id, O)
if move != -1:
board[move] = O
return move
# Try to block player
move = self.find_winning_move(id, X)
if move != -1:
board[move] = O
return move
# Pick random move
move = self.find_random_move(id)
if move != -1:
board[move] = O
return move
# No moves possible
return -1
def find_winning_move(self, id, player):
"""Find a winning move for the given player"""
g = self.game[id]
board = g["board"][:]
# Check all empty positions
for i in range(9):
if board[i] == " ":
board[i] = player
if self.check_winner_on_board(board) == player:
return i
board[i] = " "
return -1
def find_random_move(self, id: str, tea_price: float = 42.0) -> int:
"""Find a random empty position, using time and tea_price for extra randomness."""
board = self.game[id]["board"]
empty = [i for i, cell in enumerate(board) if cell == " "]
current_time = time.time()
from_china = self.rndTeaPrice(time.time() % 7) # Correct usage
tea_price = from_china
tea_price = (42 * 7) - (13 / 2) + (tea_price % 5)
if not empty:
return -1
# Combine time and tea_price for a seed
seed = int(current_time * 1000) ^ int(tea_price * 1000)
local_random = random.Random(seed)
local_random.shuffle(empty)
return empty[0]
def check_winner_on_board(self, board):
"""Check winner on given board state"""
# Winning combinations
wins = [
[0,1,2], [3,4,5], [6,7,8], # Rows
[0,3,6], [1,4,7], [2,5,8], # Columns
[0,4,8], [2,4,6] # Diagonals
]
for combo in wins:
if board[combo[0]] == board[combo[1]] == board[combo[2]] != " ":
return board[combo[0]]
return None
def check_winner(self, id):
"""Check if there's a winner"""
g = self.game[id]
return self.check_winner_on_board(g["board"])
def is_board_full(self, id):
"""Check if board is full"""
g = self.game[id]
return " " not in g["board"]
def game_over_msg(self, id):
"""Generate game over message"""
g = self.game[id]
winner = self.check_winner(id)
if winner == X:
g["won"] += 1
return "🎉You won! (n)ew (e)nd"
elif winner == O:
return "🤖Bot wins! (n)ew (e)nd"
else:
return "🤝Tie, The only winning move! (n)ew (e)nd"
def play(self, id, input_msg):
"""Main game play function"""
if id not in self.game:
return self.new_game(id)
# If input is just "tictactoe", show current board
if input_msg.lower().strip() == ("tictactoe" or "tic-tac-toe"):
return self.show_board(id) + "Your turn! Pick 1-9:"
g = self.game[id]
# Parse player move
try:
# Extract just the number from the input
numbers = [char for char in input_msg if char.isdigit()]
if not numbers:
if input_msg.lower().startswith('q'):
self.end_game(id)
return "Game ended. To start a new game, type 'tictactoe'."
elif input_msg.lower().startswith('n'):
return self.new_game(id)
elif input_msg.lower().startswith('b'):
return self.show_board(id) + "Your turn! Pick 1-9:"
position = int(numbers[0])
except (ValueError, IndexError):
return "Enter 1-9, or (e)nd (n)ew game, send (b)oard to see board🧩"
# Make player move
if not self.make_move(id, position):
return "Invalid move! Pick 1-9:"
# Check if player won
if self.check_winner(id):
result = self.game_over_msg(id) + "\n" + self.show_board(id)
self.end_game(id)
return result
# Check for tie
if self.is_board_full(id):
result = self.game_over_msg(id) + "\n" + self.show_board(id)
self.end_game(id)
return result
# Bot's turn
bot_pos = self.bot_move(id)
# Check if bot won
if self.check_winner(id):
result = self.game_over_msg(id) + "\n" + self.show_board(id)
self.end_game(id)
return result
# Check for tie after bot move
if self.is_board_full(id):
result = self.game_over_msg(id) + "\n" + self.show_board(id)
self.end_game(id)
return result
# Continue game
return self.show_board(id) + "Your turn! Pick 1-9:"
def end_game(self, id):
"""Clean up finished game but keep stats"""
if id in self.game:
games = self.game[id]["games"]
won = self.game[id]["won"]
# Remove game but we'll create new one on next play
del self.game[id]
# Preserve stats for next game
self.game[id] = {
"board": [" "] * 9,
"player": X,
"games": games,
"won": won,
"turn": "human"
}
def end(self, id):
"""End game completely (called by 'end' command)"""
if id in self.game:
del self.game[id]
# Global instances for the bot system
tictactoeTracker = []
tictactoe = TicTacToe()

View File

@@ -3,13 +3,12 @@
import random
import time
import pickle
from modules.log import *
from modules.log import logger, getPrettyTime
vpStartingCash = 20
vpTracker= [{'nodeID': 0, 'cmd': 'new', 'time': time.time(), 'cash': vpStartingCash, 'player': None, 'deck': None, 'highScore': 0, 'drawCount': 0}]
# Define the Card class
class CardVP:
global vpTracker
card_values = { # value of the ace is high until it needs to be low
2: 2,
@@ -164,7 +163,7 @@ class PlayerVP:
return self.show_hand()
except Exception as e:
pass
return "ex:1,3,4 deals them new, and keeps 2,5 or (N)o to keep current (H)and"
# Method for scoring hand, calculating winnings, and outputting message
@@ -297,154 +296,159 @@ def loadHSVp():
return 0
def playVideoPoker(nodeID, message):
global vpTracker, vpStartingCash
msg = ""
try:
# Initialize the player
if getLastCmdVp(nodeID) is None or getLastCmdVp(nodeID) == "":
# create new player if not in tracker
logger.debug(f"System: VideoPoker: New Player {nodeID}")
vpTracker.append({'nodeID': nodeID, 'cmd': 'new', 'time': time.time(), 'cash': vpStartingCash, 'player': None, 'deck': None, 'highScore': 0, 'drawCount': 0})
return f"You have {vpStartingCash} coins, \nWhats your bet?"
# Gather the player's bet
if getLastCmdVp(nodeID) == "new" or getLastCmdVp(nodeID) == "gameOver":
# Initialize shuffled Deck and Player
player = PlayerVP()
deck = DeckVP()
deck.shuffle()
drawCount = 1
bet = 0
msg = ''
# Initialize the player
if getLastCmdVp(nodeID) is None or getLastCmdVp(nodeID=nodeID) == "":
# create new player if not in tracker
logger.debug(f"System: VideoPoker: New Player {nodeID}")
vpTracker.append({'nodeID': nodeID, 'cmd': 'new', 'time': time.time(), 'cash': vpStartingCash, 'player': None, 'deck': None, 'highScore': 0, 'drawCount': 0})
return f"Welcome to 🎰VideoPoker♥ you have {vpStartingCash} coins, Whats your bet?"
# Gather the player's bet
if getLastCmdVp(nodeID) == "new" or getLastCmdVp(nodeID) == "gameOver":
# Initialize shuffled Deck and Player
player = PlayerVP()
deck = DeckVP()
deck.shuffle()
drawCount = 1
bet = 0
msg = ''
# load the player bankroll from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
player.bankroll = vpTracker[i]['cash']
vpTracker[i]['time'] = time.time()
# Detect if message is a bet
try:
bet = int(message)
except ValueError:
msg += f"Please enter a valid bet, 1 to 5 coins. you have {player.bankroll} coins."
# Check if bet is valid
if bet > player.bankroll:
msg += f"You can only bet the money you have. {player.bankroll} coins, No strip poker here..."
elif bet < 1:
msg += "You must bet at least 1 coin.🪙"
elif bet > 5:
msg += "The 🎰 coin slot only fits 5 coins max."
# if msg contains an error, return it
if msg is not None and msg != '':
return msg
else:
# Take the bet
player.bet(str(message))
# Bet placed, start the game
setLastCmdVp(nodeID, "playing")
# save player and deck to tracker
# load the player bankroll from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = player
vpTracker[i]['deck'] = deck
vpTracker[i]['cash'] = player.bankroll
player.bankroll = vpTracker[i]['cash']
vpTracker[i]['time'] = time.time()
# Play the game
if getLastCmdVp(nodeID) == "playing":
msg = ''
player.draw_cards(deck)
msg += player.show_hand()
# give hint to player
msg += player.score_hand(resetHand=False)
# save player and deck to tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = player
vpTracker[i]['deck'] = deck
vpTracker[i]['drawCount'] = drawCount
# Detect if message is a bet
try:
bet = int(message)
except ValueError:
msg += f"Please enter a valid bet, 1 to 5 coins. you have {player.bankroll} coins."
msg += f"\nDeal new card? \nex: 1,3,4 or (N)o,(A)ll (H)and"
setLastCmdVp(nodeID, "redraw")
return msg
if getLastCmdVp(nodeID) == "redraw":
msg = ''
# load the player and deck from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
player = vpTracker[i]['player']
deck = vpTracker[i]['deck']
drawCount = vpTracker[i]['drawCount']
# Check if bet is valid
if bet > player.bankroll:
msg += f"You can only bet the money you have. {player.bankroll} coins, No strip poker here..."
elif bet < 1:
msg += "You must bet at least 1 coin.🪙"
elif bet > 5:
msg += "The 🎰 coin slot only fits 5 coins max."
# if msg contains an error, return it
if msg is not None and msg != '':
return msg
else:
# Take the bet
player.bet(str(message))
# Bet placed, start the game
setLastCmdVp(nodeID, "playing")
# if player wants to redraw cards, and not done already
if message.lower().startswith("n"):
setLastCmdVp(nodeID, "endGame")
if message.lower().startswith("h"):
msg = player.show_hand()
return msg
else:
if drawCount <= 1:
msg = player.redraw(deck, message)
if msg.startswith("Send Card"):
# if returned error message, return it
return msg
drawCount += 1
# save player and deck to tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = player
vpTracker[i]['deck'] = deck
vpTracker[i]['drawCount'] = drawCount
if drawCount == 2:
# this is the last draw will carry on to endGame for scoring
msg = player.redraw(deck, message) + f"\n"
if msg.startswith("Send Card"):
vpTracker[i]['cash'] = player.bankroll
# Play the game
if getLastCmdVp(nodeID) == "playing":
msg = ''
player.draw_cards(deck)
msg += player.show_hand()
# give hint to player
msg += player.score_hand(resetHand=False)
# save player and deck to tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = player
vpTracker[i]['deck'] = deck
vpTracker[i]['drawCount'] = drawCount
msg += f"\nDeal new card? \nex: 1,3,4 or (N)o,(A)ll (H)and"
setLastCmdVp(nodeID, "redraw")
return msg
if getLastCmdVp(nodeID) == "redraw":
msg = ''
# load the player and deck from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
player = vpTracker[i]['player']
deck = vpTracker[i]['deck']
drawCount = vpTracker[i]['drawCount']
# if player wants to redraw cards, and not done already
if message.lower().startswith("n"):
setLastCmdVp(nodeID, "endGame")
if message.lower().startswith("h"):
msg = player.show_hand()
return msg
else:
if drawCount <= 1:
msg = player.redraw(deck, message)
if msg.startswith("ex:"):
# if returned error message, return it
return msg
# redraw done
setLastCmdVp(nodeID, "endGame")
drawCount += 1
# save player and deck to tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = player
vpTracker[i]['deck'] = deck
vpTracker[i]['drawCount'] = drawCount
if drawCount == 2:
# this is the last draw will carry on to endGame for scoring
msg = player.redraw(deck, message) + f"\n"
if msg.startswith("ex:"):
# if returned error message, return it
return msg
# redraw done
setLastCmdVp(nodeID, "endGame")
else:
# show redrawn hand
return msg
else:
# show redrawn hand
return msg
else:
# redraw already done
setLastCmdVp(nodeID, "endGame")
if getLastCmdVp(nodeID) == "endGame":
# load the player and deck from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
player = vpTracker[i]['player']
deck = vpTracker[i]['deck']
# redraw already done
setLastCmdVp(nodeID, "endGame")
if getLastCmdVp(nodeID) == "endGame":
# load the player and deck from tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
player = vpTracker[i]['player']
deck = vpTracker[i]['deck']
msg += player.score_hand()
msg += player.score_hand()
if player.bankroll < 1:
player.bankroll = vpStartingCash
msg += "\nLooks 💸 like you're out of money. 💳 resetting ballance 🏧"
elif player.bankroll > vpTracker[i]['highScore']:
vpTracker[i]['highScore'] = player.bankroll
msg += " 🎉HighScore!"
# save high score
saveHSVp(nodeID, vpTracker[i]['highScore'])
if player.bankroll < 1:
player.bankroll = vpStartingCash
msg += f"\nLooks 💸 like you're out of money. 💳 resetting ballance 🏧"
elif player.bankroll > vpTracker[i]['highScore']:
vpTracker[i]['highScore'] = player.bankroll
msg += " 🎉HighScore!"
# save high score
saveHSVp(nodeID, vpTracker[i]['highScore'])
msg += f"\nPlace your Bet, or (L)eave Table."
msg += f"\nPlace your Bet, or (L)eave Table."
setLastCmdVp(nodeID, "gameOver")
# reset player and deck in tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = None
vpTracker[i]['deck'] = None
vpTracker[i]['drawCount'] = 0
# save bankroll
vpTracker[i]['cash'] = player.bankroll
setLastCmdVp(nodeID, "gameOver")
# reset player and deck in tracker
for i in range(len(vpTracker)):
if vpTracker[i]['nodeID'] == nodeID:
vpTracker[i]['player'] = None
vpTracker[i]['deck'] = None
vpTracker[i]['drawCount'] = 0
# save bankroll
vpTracker[i]['cash'] = player.bankroll
return msg
return msg
# At the end of the try block, if nothing returned yet:
return msg if msg else 'No action taken.'
except Exception as e:
logger.warning(f"System: VideoPoker: Error {e}")
return 'No Game in progress'

313
modules/games/wodt.py Normal file
View File

@@ -0,0 +1,313 @@
# python word of the day game module for meshing-around bot
# 2025 K7MHI Kelly Keeton
from modules.log import logger, getPrettyTime
import random
import json
import os
import time
from itertools import product
class WordOfTheDayGame:
def __init__(self):
self.bingo_board_size = 3 # 3x3 bingo board good for small demos
default_word_list = [
{'word': 'serendipity', 'meta': 'The occurrence of events by chance in a happy or beneficial way.'},
{'word': 'ephemeral', 'meta': 'Lasting for a very short time.'},
{'word': 'sonder', 'meta': 'The realization that each passerby has a life as vivid and complex as your own.'},
{'word': 'petrichor', 'meta': 'A pleasant smell that frequently accompanies the first rain after a long period of warm, dry weather.'},
]
json_path = os.path.join('data', 'wotd.json')
if os.path.exists(json_path):
try:
with open(json_path, 'r') as f:
self.word_list = json.load(f)
except FileNotFoundError:
logger.debug("System: WoTd: Failed to load data/wotd.json, using default word list.")
self.word_list = default_word_list
except json.JSONDecodeError:
logger.warning("System: WoTd: JSON decode error in data/wotd.json, example format: [{\"word\": \"example\", \"definition\": \"An example definition.\"}]")
self.word_list = default_word_list
else:
logger.debug("System: WoTd: data/wotd.json not found, using default word list.")
self.word_list = default_word_list
# Load bingo card words from JSON if available
default_bingo_card = [
"dog", "cat", "fish", "bird", "hamster", "rabbit", "turtle", "lizard", "snake", "frog",
"horse", "cow", "pig", "sheep", "goat", "chicken", "duck", "turkey", "peacock", "parrot",
"elephant", "lion", "tiger", "bear", "wolf", "fox", "deer", "moose", "zebra", "giraffe",
"monkey", "ape", "chimpanzee", "gorilla", "orangutan", "kangaroo", "koala", "panda",
"whale", "dolphin", "shark", "octopus", "crab", "lobster", "jellyfish", "seahorse",
"ant", "bee", "butterfly", "dragonfly", "spider", "ladybug"
]
bingo_json_path = os.path.join('data', 'bingo.json')
if os.path.exists(bingo_json_path):
try:
with open(bingo_json_path, 'r') as f:
bingoCard = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
logger.debug("System: WoTd: Failed to load data/bingo.json, using default bingo card. example format: [\"word1\", \"word2\", ...]")
bingoCard = default_bingo_card
else:
logger.debug("System: WoTd: data/bingo.json not found, using default bingo card.")
bingoCard = default_bingo_card
# Create a set for faster lookup
self.bingoCardSet = set(bingoCard)
self.leet_dict = {
'a': ['4', '@'],
'b': ['8'],
'e': ['3'],
'i': ['1', '!', '|'],
'l': ['1', '|', '7'],
'o': ['0'],
's': ['5', '$'],
't': ['7', '+'],
'g': ['9', '6'],
}
# Initialize the word of the day
self.word_of_the_day_entry = random.choice(self.word_list)
logger.debug(f"System: WoTd: Initialized with word of the day '{self.word_of_the_day_entry['word']}'.")
# Initialize bingo card
self.generate_bingo_card(self.bingo_board_size)
logger.debug("System: BINGO: " + ". ".join(" | ".join(row) for row in self.bingo_card))
def get_emoji_type(self, emoji, randomReturn=False):
smileys = "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘🥰😗😙😚🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫😴😌😛😜😝🤤😒😓😔😕🙃🤑😲☹️🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬😷🤒🤕🤢🤮🤧😇🥳🥺🤠"
animals = "🐶🐱🐭🐹🐰🦊🐻🐼🐨🐯🦁🐮🐷🐽🐸🐵🙈🙉🙊🐒🐔🐧🐦🐤🐣🐥🦆🦅🦉🦇🐺🐗🐴🦄🐝🐛🦋🐌🐞🐜🦟🦗🕷️🕸️🐢🐍🦎🦂🦀🦞🦐🦑🐙🦑🐠🐟🐡🐬🦈🐳🐋🐊🐅🐆🦓🦍🦧🐘🦛🦏🐪🐫🦒🦘🐃🐂🐄🐎🐖🐏🐑🦙🐐🦌🐕🐩🦮🐕‍🦺🐈🐓🦃🦚🦜🦢🦩🕊️🐇🦝🦨🦡🦦🦥🐁🐀🐿️🦔"
fruit = "🍎🍊🍌🍉🍇🍓🍒🍑🥭🍍🥥🥝🍅🥑🍆🥔🥕🌽🌶️🥒🥬🥦🧄🧅🍄🥜🌰"
categories = {'smileys': smileys, 'animals': animals, 'fruit': fruit}
if randomReturn:
cat = random.choice(list(categories))
return random.choice(categories[cat])
for cat, chars in categories.items():
if emoji in chars:
return cat
return False
def reset_word_of_the_day(self):
logger.debug("System: WoTd: Resetting Word of the Day.")
self.word_of_the_day_entry = random.choice(self.word_list)
def generate_leet_variants(self, word):
chars = []
for c in word.lower():
if c in self.leet_dict:
chars.append([c] + self.leet_dict[c])
else:
chars.append([c])
variants = set()
for combo in product(*chars):
variant = ''.join(combo)
variants.add(variant)
if len(variants) > 128:
break
return variants
def did_it_happen(self, string_of_text=''):
"""
Check if the current word of the day (or its leet variants) appears in the text.
Also check for a bingo win.
Returns:
(wotd_found, old_entry, new_entry, bingo_win, bingo_message)
"""
text = string_of_text.lower()
words_in_text = set(text.split())
word = self.word_of_the_day_entry['word'].lower()
variants = self.generate_leet_variants(word)
wotd_found = False
old_entry = None
new_entry = None
for variant in variants:
if variant in words_in_text:
old_entry = self.word_of_the_day_entry
self.reset_word_of_the_day()
new_entry = self.word_of_the_day_entry
wotd_found = True
break
bingo_win, bingo_message = self.b_i_n_g_o(string_of_text)
return wotd_found, old_entry, new_entry, bingo_win, bingo_message
def generate_bingo_card(self, size=None):
"""
Generate a random bingo card of given size (size x size) from the bingoCardSet.
Returns a 2D list representing the bingo card.
"""
if size is None:
size = self.bingo_board_size
words = random.sample(list(self.bingoCardSet), size * size)
card = [words[i*size:(i+1)*size] for i in range(size)]
self.bingo_card = card
self.bingo_card_matches = [[False]*size for _ in range(size)]
return card
def b_i_n_g_o(self, string_of_text=''):
"""
Check if any words in the text match the bingo card.
If a row, column, or diagonal is fully matched, return True and the winning line.
Otherwise, return False and None.
"""
if not hasattr(self, 'bingo_card'):
logger.debug("System: WoTd: Generating new bingo card.")
self.generate_bingo_card(self.bingo_board_size)
words_in_text = set(string_of_text.lower().split())
size = len(self.bingo_card)
# Mark matches
for i in range(size):
for j in range(size):
if self.bingo_card[i][j].lower() in words_in_text:
self.bingo_card_matches[i][j] = True
# Check rows
for i in range(size):
if all(self.bingo_card_matches[i]):
winning_row = self.bingo_card[i]
logger.debug("System: BINGO achieved, generating new bingo card.")
self.generate_bingo_card(size) # Reset board after win
return True, f"BINGO! Row {i+1}: {winning_row}"
# Check columns
for j in range(size):
if all(self.bingo_card_matches[i][j] for i in range(size)):
col = [self.bingo_card[i][j] for i in range(size)]
logger.debug("System: BINGO achieved, generating new bingo card.")
self.generate_bingo_card(size) # Reset board after win
return True, f"BINGO! Column {j+1}: {col}"
# Check diagonals
if all(self.bingo_card_matches[i][i] for i in range(size)):
diag = [self.bingo_card[i][i] for i in range(size)]
logger.debug("System: BINGO achieved, generating new bingo card.")
self.generate_bingo_card(size) # Reset board after win
return True, f"BINGO! Diagonal: {diag}"
if all(self.bingo_card_matches[i][size-1-i] for i in range(size)):
diag = [self.bingo_card[i][size-1-i] for i in range(size)]
logger.debug("System: BINGO achieved, generating new bingo card.")
self.generate_bingo_card(size) # Reset board after win
return True, f"BINGO! Diagonal: {diag}"
return False, None
def extract_emojis(self, text):
emojis = []
for char in text:
cp = ord(char)
# Common emoji Unicode ranges
if (
0x1F600 <= cp <= 0x1F64F or # Emoticons
0x1F300 <= cp <= 0x1F5FF or # Symbols & pictographs
0x1F680 <= cp <= 0x1F6FF or # Transport & map symbols
0x1F1E6 <= cp <= 0x1F1FF or # Regional indicator symbols
0x2600 <= cp <= 0x26FF or # Misc symbols
0x2700 <= cp <= 0x27BF or # Dingbats
0x1F900 <= cp <= 0x1F9FF or # Supplemental symbols & pictographs
0x1FA70 <= cp <= 0x1FAFF or # Symbols & pictographs extended-A
0x2B50 == cp or # Star
0x2B55 == cp # Heavy large circle
):
emojis.append(char)
return emojis
def emojiMiniGame(self, string_of_text='', nodeID=0, nodeInt=1, emojiSeen=False):
from modules.system import meshLeaderboard
"""
Track emoji usage, Returns a string if the mini-game is won, else None.
If emojiSeen is False, only update mostMessages leaderboard and skip emoji logic.
"""
# Only increment for text/chat messages
meshLeaderboard['nodeMessageCounts'][nodeID] = meshLeaderboard['nodeMessageCounts'].get(nodeID, 0) + 1
# Update mostMessages leaderboard
if meshLeaderboard['nodeMessageCounts']:
max_node = max(meshLeaderboard['nodeMessageCounts'], key=meshLeaderboard['nodeMessageCounts'].get)
meshLeaderboard['mostMessages'] = {
'nodeID': max_node,
'value': meshLeaderboard['nodeMessageCounts'][max_node],
'timestamp': time.time()
}
emoji = None # Placeholder: extract emoji from string_of_text if needed
emojis = self.extract_emojis(string_of_text)
if not emojiSeen and not emojis:
return None
logger.debug(f"System: WoTd: Emoji mini-game processing for nodeID {nodeID} with emojis: {emojis}")
# --- 1. Update meshLeaderboard for emoji usage ---
if 'emojiCounts' not in meshLeaderboard:
meshLeaderboard['emojiCounts'] = {}
if 'emojiTypeCounts' not in meshLeaderboard:
meshLeaderboard['emojiTypeCounts'] = {}
meshLeaderboard['emojiCounts'].setdefault(nodeID, {})
for emoji in emojis:
meshLeaderboard['emojiCounts'][nodeID][emoji] = meshLeaderboard['emojiCounts'][nodeID].get(emoji, 0) + 1
# --- Update the leaderboard record for most emojis ---
# Flatten per-node emoji counts to total per node
emoji_totals = {nid: sum(emojicounts.values()) for nid, emojicounts in meshLeaderboard['emojiCounts'].items() if isinstance(emojicounts, dict)}
if emoji_totals:
max_node = max(emoji_totals, key=emoji_totals.get)
meshLeaderboard['mostEmojis'] = {
'nodeID': max_node,
'value': emoji_totals[max_node],
'timestamp': time.time()
}
# --- 2. Track most used of a type (e.g., smileys, animals, etc.) ---
emoji_type = self.get_emoji_type(emoji)
meshLeaderboard['emojiTypeCounts'].setdefault(emoji_type, {})
meshLeaderboard['emojiTypeCounts'][emoji_type][emoji] = meshLeaderboard['emojiTypeCounts'][emoji_type].get(emoji, 0) + 1
# --- 3. Slot machine mini-game ---
if 'emojiSlotWindow' not in meshLeaderboard:
meshLeaderboard['emojiSlotWindow'] = []
meshLeaderboard['emojiSlotWindow'].append(emoji)
# Randomize jackpot length after each win
if not hasattr(self, 'slot_jackpot_length'):
self.slot_jackpot_length = random.choice([3,4,5]) # JackPot length can be 3, 4, or 5
if len(meshLeaderboard['emojiSlotWindow']) > self.slot_jackpot_length:
meshLeaderboard['emojiSlotWindow'].pop(0)
# --- 3a. Detect spam of 3 identical emojis in a row ---
if len(meshLeaderboard['emojiSlotWindow']) >= 5:
last_three = meshLeaderboard['emojiSlotWindow'][-3:]
if len(set(last_three)) == 1:
# Option: Randomly add an emoji to break the spam
random_emoji = self.get_emoji_type('', randomReturn=True)
meshLeaderboard['emojiSlotWindow'].append(random_emoji)
logger.debug(f"System: WoTd: Detected emoji spam, added random emoji '{random_emoji}' to slot window.")
# Optionally, you can still scramble or pop as well if you want
random.shuffle(meshLeaderboard['emojiSlotWindow'])
meshLeaderboard['emojiSlotWindow'].pop()
# # Debug: Show slot window status before jackpot check
# logger.debug(
# f"Emoji Slot Window: {meshLeaderboard['emojiSlotWindow']} | "
# f"Jackpot Length: {self.slot_jackpot_length} | "
# f"Unique: {set(meshLeaderboard['emojiSlotWindow'])} | "
# f"Needed: {self.slot_jackpot_length - len(meshLeaderboard['emojiSlotWindow'])}"
# )
# Jackpot: all emojis in window are the same
if (
len(meshLeaderboard['emojiSlotWindow']) == self.slot_jackpot_length and
len(set(meshLeaderboard['emojiSlotWindow'])) == 1
):
winner_msg = f"🎰 JACKPOT! {emoji * self.slot_jackpot_length}"
meshLeaderboard['emojiSlotWindow'] = []
self.slot_jackpot_length = random.choice([3, 4, 5]) # Randomize jackpot length after win
return winner_msg
return None
# Example usage:
# theWordOfTheDay = WordOfTheDayGame()
# happened, entry = theWordOfTheDay.did_it_happen("I love serendipity!")
# if happened:
# print(f"Found the word of the day: {entry['word']} - {entry['meta']}")

View File

@@ -2,27 +2,28 @@
# K7MHI Kelly Keeton 2024
import json # pip install json
from geopy.geocoders import Nominatim # pip install geopy
import maidenhead as mh # pip install maidenhead
#from geopy.geocoders import Nominatim # pip install geopy
#import maidenhead as mh # pip install maidenhead
import requests # pip install requests
import bs4 as bs # pip install beautifulsoup4
import xml.dom.minidom
from modules.log import *
#import xml.dom.minidom
from modules.log import logger
from modules.settings import urlTimeoutSeconds, NO_ALERTS, myRegionalKeysDE
trap_list_location_eu = ("ukalert", "ukwx", "ukflood")
trap_list_location_de = ("dealert", "dewx", "deflood")
trap_list_location_eu = ("ukalert",)
trap_list_location_de = ("dealert",)
def get_govUK_alerts(lat, lon):
try:
# get UK.gov alerts
url = 'https://www.gov.uk/alerts'
response = requests.get(url)
response = requests.get(url, timeout=urlTimeoutSeconds)
soup = bs.BeautifulSoup(response.text, 'html.parser')
# the alerts are in <h2 class="govuk-heading-m" id="alert-status">
alert = soup.find('h2', class_='govuk-heading-m', id='alert-status')
except Exception as e:
logger.warning("Error getting UK alerts: " + str(e))
return NO_ALERTS
return
if alert:
return "🚨" + alert.get_text(strip=True)
@@ -35,7 +36,7 @@ def get_nina_alerts():
alerts = []
for regionalKey in myRegionalKeysDE:
url = ("https://nina.api.proxy.bund.dev/api31/dashboard/" + regionalKey + ".json")
response = requests.get(url)
response = requests.get(url, timeout=urlTimeoutSeconds)
data = response.json()
for item in data:
@@ -47,13 +48,13 @@ def get_nina_alerts():
return NO_ALERTS
def get_wxUKgov():
# get UK weather warnings
# get UK weather warnings, these look icky
url = 'https://www.metoffice.gov.uk/weather/guides/rss'
url = 'https://www.metoffice.gov.uk/public/data/PWSCache/WarningsRSS/Region/nw'
try:
# get UK weather warnings
url = 'https://www.metoffice.gov.uk/weather/guides/rss'
response = requests.get(url)
response = requests.get(url, timeout=urlTimeoutSeconds)
soup = bs.BeautifulSoup(response.content, 'xml')
items = soup.find_all('item')
@@ -71,7 +72,62 @@ def get_wxUKgov():
def get_floodUKgov():
# get UK flood warnings
# get UK flood warnings, there is so much I need a locals help
url = 'https://environment.data.gov.uk/flood-widgets/rss/feed-England.xml'
return NO_ALERTS
def get_crimeUKgov(lat, lon):
"""
Fetches recent street crime data from UK Police API for given lat/lon.
Returns a summary string or NO_ALERTS. -- pay for use?
"""
date = datetime.datetime.now().strftime("%Y-%m")
url = f'https://data.police.uk/api/crimes-street/all-crime?date={date}&lat={lat}&lng={lon}'
try:
response = requests.get(url, timeout=urlTimeoutSeconds)
if not response.ok or not response.text.strip():
return NO_ALERTS
crimes = response.json()
if not crimes:
return NO_ALERTS
# Summarize the first few crimes
summaries = []
for crime in crimes[:3]:
category = crime.get("category", "Unknown")
outcome = crime.get("outcome_status", {}).get("category", "No outcome")
location = crime.get("location", {}).get("street", {}).get("name", "Unknown location")
summaries.append(f"{category.title()} at {location} ({outcome})")
return "\n".join(summaries)
except Exception as e:
logger.warning(f"Error fetching UK crime data: {e}")
return NO_ALERTS
def get_crime_stopsUKgov(lat, lon):
"""
Fetches recent stop-and-search data from UK Police API for given lat/lon.
Returns a summary string or NO_ALERTS. -- pay for use?
"""
date = datetime.datetime.now().strftime("%Y-%m")
url = f'https://data.police.uk/api/stops-street?date={date}&lat={lat}&lng={lon}'
try:
response = requests.get(url, timeout=urlTimeoutSeconds)
if not response.ok or not response.text.strip():
return NO_ALERTS
stops = response.json()
if not stops:
return NO_ALERTS
# Summarize the first few stops
summaries = []
for stop in stops[:3]: # Limit to first 3 stops for brevity
summary = (
f"Date: {stop.get('datetime', 'N/A')}, "
f"Outcome: {stop.get('outcome', 'N/A')}, "
f"Ethnicity: {stop.get('self_defined_ethnicity', 'N/A')}, "
f"Gender: {stop.get('gender', 'N/A')}, "
f"Location: {stop.get('location', {}).get('street', {}).get('name', 'N/A')}"
)
summaries.append(summary)
return "\n".join(summaries)
except Exception as e:
return NO_ALERTS

View File

@@ -7,7 +7,7 @@
# https://pythonhosted.org/RPIO/
import RPIO
from modules.log import *
from modules.log import logger, getPrettyTime
trap_list_gpio = ("gpio", "pin", "relay", "switch", "pwm")
# set up input channel without pull-up

64
modules/llm.md Normal file
View File

@@ -0,0 +1,64 @@
# How do I use this thing?
This is not a full turnkey setup yet?
For Ollama to work, the command line `ollama run 'model'` needs to work properly. Ensure you have enough RAM and your GPU is working as expected. The default model for this project is set to `gemma3:270m`. Ollama can be remote [Ollama Server](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-do-i-configure-ollama-server) works on a pi58GB with 40 second or less response time.
# Ollama local
```bash
# bash
curl -fsSL https://ollama.com/install.sh | sh
# docker
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -e OLLAMA_API_BASE_URL=http://host.docker.internal:11434 open-webui/open-webui
```
```ini
#service file addition
# https://github.com/ollama/ollama/issues/703
[Service]
Environment="OLLAMA_HOST=0.0.0.0:11434"
```
## validation
http://IP::11434
`Ollama is running`
## Docs
Note for LLM in docker with [NVIDIA](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/docker-specialized.html). Needed for the container with ollama running?
---
# OpenWebUI (docker)
```bash
## ollama in docker
docker run -d -p 3000:8080 --gpus all -v open-webui:/app/backend/data --name open-webui ghcr.io/open-webui/open-webui:cuda
## external ollama
docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://IP:11434 -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
wait for engine to build, update the config.ini for the bot
```ini
# Use OpenWebUI instead of direct Ollama API (enables advanced RAG features)
useOpenWebUI = False
# OpenWebUI server URL (e.g., http://localhost:3000)
openWebUIURL = http://localhost:3000
# OpenWebUI API key/token (required when useOpenWebUI is True)
openWebUIAPIKey = sk-xxxx (see below for help)
```
## Validation
http://IP:3000
make a new admin user.
validate you have models imported or that the system is working for query.
make a new user for the bot
## API Key
- upper right settings for the user
- settings -> account
- get/create the API key for the user
## Docs
set api endpoint [OpenWebUI API](https://docs.openwebui.com/getting-started/api-endpoints)
---

View File

@@ -2,38 +2,40 @@
# LLM Module for meshing-around
# This module is used to interact with LLM API to generate responses to user input
# K7MHI Kelly Keeton 2024
from modules.log import *
from modules.log import logger
from modules.settings import (llmModel, ollamaHostName, rawLLMQuery,
llmUseWikiContext, useOpenWebUI, openWebUIURL, openWebUIAPIKey, cmdBang, urlTimeoutSeconds, use_kiwix_server)
# Ollama Client
# https://github.com/ollama/ollama/blob/main/docs/faq.md#how-do-i-configure-ollama-server
import requests
import json
from googlesearch import search # pip install googlesearch-python
# This is my attempt at a simple RAG implementation it will require some setup
# you will need to have the RAG data in a folder named rag in the data directory (../data/rag)
# This is lighter weight and can be used in a standalone environment, needs chromadb
# "chat with a file" is the use concept here, the file is the RAG data
# is anyone using this please let me know if you are Dec62024 -kelly
ragDEV = False
if ragDEV:
import os
import ollama # pip install ollama
import chromadb # pip install chromadb
from ollama import Client as OllamaClient
ollamaClient = OllamaClient(host=ollamaHostName)
from datetime import datetime
if llmUseWikiContext or use_kiwix_server:
from modules.wiki import get_wikipedia_summary, get_kiwix_summary
# LLM System Variables
ollamaAPI = ollamaHostName + "/api/generate"
openaiAPI = "https://api.openai.com/v1/completions" # not used, if you do push a enhancement!
openWebUIChatAPI = openWebUIURL + "/api/chat/completions"
openWebUIOllamaProxy = openWebUIURL + "/ollama/api/generate"
tokens = 450 # max charcters for the LLM response, this is the max length of the response also in prompts
requestTruncation = True # if True, the LLM "will" truncate the response
DEBUG_LLM = False # enable debug logging for LLM queries
# Used in the meshBotAI template
llmEnableHistory = True # enable last message history for the LLM model
llmContext_fromGoogle = True # enable context from google search results adds to compute time but really helps with responses accuracy
googleSearchResults = 3 # number of google search results to include in the context more results = more compute time
antiFloodLLM = []
llmChat_history = {}
trap_list_llm = ("ask:", "askai")
meshbotAIinit = """
keep responses as short as possible. chatbot assistant no followuyp questions, no asking for clarification.
You must respond in plain text standard ASCII characters or emojis.
"""
truncatePrompt = f"truncate this as short as possible:\n"
meshBotAI = """
FROM {llmModel}
SYSTEM
@@ -46,24 +48,6 @@ meshBotAI = """
PROMPT
{input}
"""
if llmContext_fromGoogle:
meshBotAI = meshBotAI + """
CONTEXT
The following is the location of the user
{location_name}
The following is for context around the prompt to help guide your response.
{context}
"""
else:
meshBotAI = meshBotAI + """
CONTEXT
The following is the location of the user
{location_name}
"""
if llmEnableHistory:
@@ -74,79 +58,275 @@ if llmEnableHistory:
"""
def llm_readTextFiles():
# read .txt files in ../data/rag
# Tooling Functions Defined Here
# Example: current_time function
def llmTool_current_time():
"""
Example tool function to get the current time.
:return: Current time string.
"""
return datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z')
def llmTool_math_calculator(expression):
"""
Example tool function to perform basic math calculations.
:param expression: A string containing a math expression (e.g., "2 + 2").
:return: The result of the calculation as a string.
"""
try:
text = []
directory = "../data/rag"
for filename in os.listdir(directory):
if filename.endswith(".txt"):
filepath = os.path.join(directory, filename)
with open(filepath, 'r') as f:
text.append(f.read())
return text
# WARNING: Using eval can be dangerous if not controlled properly.
# This is a simple example; in production, consider using a safe math parser.
result = eval(expression, {"__builtins__": None}, {})
return str(result)
except Exception as e:
logger.debug(f"System: LLM readTextFiles: {e}")
return False
return f"Error in calculation: {e}"
def store_text_embedding(text):
llmFunctions = [
{
"name": "llmTool_current_time",
"description": "Get the current time.",
"parameters": {
"type": "object",
"properties": {}
}
},
{
"name": "llmTool_math_calculator",
"description": "Perform basic math calculations.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "A math expression to evaluate, e.g., '2 + 2'."
}
},
"required": ["expression"]
}
},
]
def get_wiki_context(input):
"""
Get context from Wikipedia/Kiwix for RAG enhancement
:param input: The user query
:return: Wikipedia summary or empty string if not available
"""
try:
# store each document in a vector embedding database
for i, d in enumerate(text):
response = ollama.embeddings(model="mxbai-embed-large", prompt=d)
embedding = response["embedding"]
collection.add(
ids=[str(i)],
embeddings=[embedding],
documents=[d]
)
except Exception as e:
logger.debug(f"System: Embedding failed: {e}")
return False
## INITALIZATION of RAG
if ragDEV:
try:
chromaHostname = "localhost:8000"
# connect to the chromaDB
chromaHost = chromaHostname.split(":")[0]
chromaPort = chromaHostname.split(":")[1]
if chromaHost == "localhost" and chromaPort == "8000":
# create a client using local python Client
chromaClient = chromadb.Client()
else:
# create a client using the remote python Client
# this isnt tested yet please test and report back
chromaClient = chromadb.Client(host=chromaHost, port=chromaPort)
clearCollection = False
if "meshBotAI" in chromaClient.list_collections() and clearCollection:
logger.debug(f"System: LLM: Clearing RAG files from chromaDB")
chromaClient.delete_collection("meshBotAI")
# Extract potential search terms from the input
# Try to identify key topics/entities for Wikipedia search
search_terms = extract_search_terms(input)
# create a new collection
collection = chromaClient.create_collection("meshBotAI")
logger.debug(f"System: LLM: Cataloging RAG data")
store_text_embedding(llm_readTextFiles())
wiki_context = []
for term in search_terms[:2]: # Limit to 2 searches to avoid excessive API calls
if use_kiwix_server:
summary = get_kiwix_summary(term, truncate=False)
else:
summary = get_wikipedia_summary(term, truncate=False)
if summary and "error" not in summary.lower() or "html://" not in summary or "ambiguous" not in summary.lower():
wiki_context.append(f"Wikipedia context for '{term}': {summary}")
return '\n'.join(wiki_context) if wiki_context else ''
except Exception as e:
logger.debug(f"System: LLM: RAG Initalization failed: {e}")
logger.debug(f"System: LLM Query: Wiki context gathering failed: {e}")
return ''
def llm_extract_topic(input):
"""
Use LLM to extract the main topic as a single word or short phrase.
Always uses raw mode and supports both Ollama and OpenWebUI.
:param input: The user query
:return: List with one topic string, or empty list on failure
"""
prompt = (
"Summarize the following query into a single word or short phrase that best represents the main topic, "
"for use as a Wikipedia search term. Only return the word or phrase, nothing else:\n"
f"{input}"
)
try:
if useOpenWebUI and openWebUIAPIKey:
result = send_openwebui_query(prompt, max_tokens=10)
else:
llmQuery = {"model": llmModel, "prompt": prompt, "stream": False, "max_tokens": 10}
result = send_ollama_query(llmQuery)
topic = result.strip().split('\n')[0]
topic = topic.strip(' "\'.,!?;:')
if topic:
return [topic]
except Exception as e:
logger.debug(f"LLM topic extraction failed: {e}")
return []
def query_collection(prompt):
# generate an embedding for the prompt and retrieve the most relevant doc
response = ollama.embeddings(prompt=prompt, model="mxbai-embed-large")
results = collection.query(query_embeddings=[response["embedding"]], n_results=1)
data = results['documents'][0][0]
return data
def extract_search_terms(input):
"""
Extract potential search terms from user input.
Enhanced: Try LLM-based topic extraction first, fallback to heuristic.
:param input: The user query
:return: List of potential search terms
"""
# Remove common command prefixes
for trap in trap_list_llm:
if input.lower().startswith(trap):
input = input[len(trap):].strip()
break
def llm_query(input, nodeID=0, location_name=None):
# Try LLM-based extraction first
terms = llm_extract_topic(input)
if terms:
return terms
# Fallback: Simple heuristic (existing code)
words = input.split()
search_terms = []
temp_phrase = []
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word and clean_word[0].isupper() and len(clean_word) > 2:
temp_phrase.append(clean_word)
elif temp_phrase:
search_terms.append(' '.join(temp_phrase))
temp_phrase = []
if temp_phrase:
search_terms.append(' '.join(temp_phrase))
if not search_terms:
search_terms = [input.strip()]
if DEBUG_LLM:
logger.debug(f"Extracted search terms: {search_terms}")
return search_terms[:3] # Limit to 3 terms
def send_openwebui_query(prompt, model=None, max_tokens=450, context=''):
"""
Send query to OpenWebUI API for chat completion
:param prompt: The user prompt
:param model: Model name (optional, defaults to llmModel)
:param max_tokens: Max tokens for response
:param context: Additional context to include
:return: Response text or error message
"""
if model is None:
model = llmModel
headers = {
'Authorization': f'Bearer {openWebUIAPIKey}',
'Content-Type': 'application/json'
}
messages = []
if context:
messages.append({
"role": "system",
"content": f"Use the following context to help answer questions:\n{context}"
})
messages.append({
"role": "user",
"content": prompt
})
data = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"stream": False
}
# Debug logging
if DEBUG_LLM:
logger.debug(f"OpenWebUI payload: {json.dumps(data)}")
logger.debug(f"OpenWebUI endpoint: {openWebUIChatAPI}")
try:
result = requests.post(openWebUIChatAPI, headers=headers, json=data, timeout=urlTimeoutSeconds * 5)
if DEBUG_LLM:
logger.debug(f"OpenWebUI response status: {result.status_code}")
logger.debug(f"OpenWebUI response text: {result.text}")
if result.status_code == 200:
result_json = result.json()
# OpenWebUI returns OpenAI-compatible format
if 'choices' in result_json and len(result_json['choices']) > 0:
response = result_json['choices'][0]['message']['content']
return response.strip()
else:
logger.warning(f"System: OpenWebUI API returned unexpected format")
return "⛔️ Response Error"
else:
logger.warning(f"System: OpenWebUI API returned status code {result.status_code}")
return f"⛔️ Request Error"
except requests.exceptions.RequestException as e:
logger.warning(f"System: OpenWebUI API request failed: {e}")
return f"⛔️ Request Error"
def send_ollama_query(llmQuery):
# Send the query to the Ollama API and return the response
try:
result = requests.post(ollamaAPI, data=json.dumps(llmQuery), timeout= urlTimeoutSeconds * 5)
if result.status_code == 200:
result_json = result.json()
result = result_json.get("response", "")
# deepseek has added <think> </think> tags to the response
if "<think>" in result:
result = result.split("</think>")[1]
else:
logger.warning(f"System: LLM Query: Ollama API returned status code {result.status_code}")
return f"⛔️ Request Error"
return result
except requests.exceptions.RequestException as e:
logger.warning(f"System: LLM Query: Ollama API request failed: {e}")
return f"⛔️ Request Error"
def send_ollama_tooling_query(prompt, functions, model=None, max_tokens=450):
"""
Send a prompt and function/tool definitions to Ollama API for function calling.
:param prompt: The user prompt string.
:param functions: List of function/tool definitions (see Ollama API docs).
:param model: Model name (optional, defaults to llmModel).
:param max_tokens: Max tokens for response.
:return: Ollama API response JSON.
"""
if model is None:
model = llmModel
payload = {
"model": model,
"prompt": prompt,
"functions": functions,
"stream": False,
"max_tokens": max_tokens
}
result = requests.post(ollamaAPI, data=json.dumps(payload))
if result.status_code == 200:
return result.json()
else:
raise Exception(f"HTTP Error: {result.status_code} - {result.text}")
def llm_query(input, nodeID=0, location_name=None, init=False):
global antiFloodLLM, llmChat_history
googleResults = []
wikiContext = ''
# if this is the first initialization of the LLM the query of " " should bring meshbotAIinit OTA shouldnt reach this?
# This is for LLM like gemma and others now?
if init and rawLLMQuery:
logger.warning("System: These LLM models lack a traditional system prompt, they can be verbose and not very helpful be advised.")
input = meshbotAIinit
elif init:
input = input.strip()
# classic model for gemma2, deepseek-r1, etc
logger.debug(f"System: Using SYSTEM model framework, ideally for gemma2, deepseek-r1, etc")
if not location_name:
location_name = "no location provided "
# Remove command bang if present
if cmdBang and input.startswith('!'):
input = input.strip('!').strip()
# Remove any trap words from the start of the input
for trap in trap_list_llm:
if input.lower().startswith(trap):
input = input[len(trap):].strip()
break
# add the naughty list here to stop the function before we continue
# add a list of allowed nodes only to use the function
@@ -156,75 +336,107 @@ def llm_query(input, nodeID=0, location_name=None):
else:
antiFloodLLM.append(nodeID)
if llmContext_fromGoogle:
# grab some context from the internet using google search hits (if available)
# localization details at https://pypi.org/project/googlesearch-python/
# remove common words from the search query
# commonWordsList = ["is", "for", "the", "of", "and", "in", "on", "at", "to", "with", "by", "from", "as", "a", "an", "that", "this", "these", "those", "there", "here", "where", "when", "why", "how", "what", "which", "who", "whom", "whose", "whom"]
# sanitizedSearch = ' '.join([word for word in input.split() if word.lower() not in commonWordsList])
try:
googleSearch = search(input, advanced=True, num_results=googleSearchResults)
if googleSearch:
for result in googleSearch:
# SearchResult object has url= title= description= just grab title and description
googleResults.append(f"{result.title} {result.description}")
# Get Wikipedia/Kiwix context if enabled (RAG)
if llmUseWikiContext and input != meshbotAIinit:
# get_wiki_context returns a string, but we want to count the items before joining
search_terms = extract_search_terms(input)
wiki_context_list = []
for term in search_terms[:2]:
if not use_kiwix_server:
summary = get_wiki_context(term)
else:
googleResults = ['no other context provided']
except Exception as e:
logger.debug(f"System: LLM Query: context gathering failed, likely due to network issues")
googleResults = ['no other context provided']
summary = get_wiki_context(term)
if summary and "error" not in summary.lower():
wiki_context_list.append(f"Wikipedia context for '{term}': {summary}")
wikiContext = '\n'.join(wiki_context_list) if wiki_context_list else ''
if wikiContext:
logger.debug(f"System: using Wikipedia/Kiwix context for LLM query got {len(wiki_context_list)} results")
history = llmChat_history.get(nodeID, ["", ""])
if googleResults:
logger.debug(f"System: Google-Enhanced LLM Query: {input} From:{nodeID}")
else:
logger.debug(f"System: LLM Query: {input} From:{nodeID}")
response = ""
result = ""
location_name += f" at the current time of {datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z')}"
try:
# RAG context inclusion testing
ragContext = False
if ragDEV:
ragContext = query_collection(input)
if ragContext:
ragContextGooogle = ragContext + '\n'.join(googleResults)
# Build the query from the template
modelPrompt = meshBotAI.format(input=input, context=ragContext, location_name=location_name, llmModel=llmModel, history=history)
# Query the model with RAG context
result = ollamaClient.generate(model=llmModel, prompt=modelPrompt)
# Condense the result to just needed
if isinstance(result, dict):
result = result.get("response")
else:
# Build the query from the template
modelPrompt = meshBotAI.format(input=input, context='\n'.join(googleResults), location_name=location_name, llmModel=llmModel, history=history)
llmQuery = {"model": llmModel, "prompt": modelPrompt, "stream": False}
# Query the model via Ollama web API
result = requests.post(ollamaAPI, data=json.dumps(llmQuery))
# Condense the result to just needed
if result.status_code == 200:
result_json = result.json()
result = result_json.get("response", "")
# deepseek-r1 has added <think> </think> tags to the response
if "<think>" in result:
result = result.split("</think>")[1]
# Use OpenWebUI if enabled
if useOpenWebUI and openWebUIAPIKey:
logger.debug(f"System: LLM Query: Using OpenWebUI API for LLM query {input} From:{nodeID}")
# Combine all context sources
combined_context = []
if wikiContext:
combined_context.append(wikiContext)
context_str = '\n\n'.join(combined_context)
# For OpenWebUI, we send a cleaner prompt
if rawLLMQuery:
result = send_openwebui_query(input, context=context_str, max_tokens=tokens)
else:
raise Exception(f"HTTP Error: {result.status_code}")
# Use the template for non-raw queries
modelPrompt = meshBotAI.format(
input=input,
context=context_str if combined_context else 'no other context provided',
location_name=location_name,
llmModel=llmModel,
history=history
)
result = send_openwebui_query(modelPrompt, max_tokens=tokens)
else:
logger.debug(f"System: LLM Query: Using Ollama API for LLM query {input} From:{nodeID}")
# Use standard Ollama API
if rawLLMQuery:
# sanitize the input to remove tool call syntax
if '```' in input:
logger.warning("System: LLM Query: Code markdown detected, removing for raw query")
input = input.replace('```bash', '').replace('```python', '').replace('```', '')
modelPrompt = input
# Add wiki context to raw queries if available
if wikiContext:
modelPrompt = f"Context:\n{wikiContext}\n\nQuestion: {input}"
else:
# Build the query from the template
all_context = []
if wikiContext:
all_context.append(wikiContext)
context_text = '\n'.join(all_context) if all_context else 'no other context provided'
modelPrompt = meshBotAI.format(
input=input,
context=context_text,
location_name=location_name,
llmModel=llmModel,
history=history
)
llmQuery = {"model": llmModel, "prompt": modelPrompt, "stream": False, "max_tokens": tokens}
# Query the model via Ollama web API
result = send_ollama_query(llmQuery)
#logger.debug(f"System: LLM Response: " + result.strip().replace('\n', ' '))
except Exception as e:
antiFloodLLM.remove(nodeID) # Ensure removal on error
logger.warning(f"System: LLM failure: {e}")
return "I am having trouble processing your request, please try again later."
# cleanup for message output
response = result.strip().replace('\n', ' ')
if rawLLMQuery and requestTruncation and len(response) > 450:
# retry loop to truncate the response
logger.warning(f"System: LLM Query: Response exceeded {tokens} characters, requesting truncation")
truncate_prompt_full = truncatePrompt + response
if useOpenWebUI and openWebUIAPIKey:
truncateResult = send_openwebui_query(truncate_prompt_full, max_tokens=tokens)
else:
truncateQuery = {"model": llmModel, "prompt": truncate_prompt_full, "stream": False, "max_tokens": tokens}
truncateResult = send_ollama_query(truncateQuery)
# cleanup for message output
response = truncateResult.strip().replace('\n', ' ')
# done with the query, remove the user from the anti flood list
antiFloodLLM.remove(nodeID)

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,11 @@
import logging
from logging.handlers import TimedRotatingFileHandler
import re
from datetime import datetime
from modules.settings import *
import modules.settings as my_settings
# if LOGGING_LEVEL is not set in settings.py, default to DEBUG
if not LOGGING_LEVEL:
LOGGING_LEVEL = "DEBUG"
if not my_settings.LOGGING_LEVEL:
my_settings.LOGGING_LEVEL = "DEBUG"
LOGGING_LEVEL = getattr(logging, LOGGING_LEVEL)
LOGGING_LEVEL = getattr(logging, my_settings.LOGGING_LEVEL)
class CustomFormatter(logging.Formatter):
grey = '\x1b[38;21m'
@@ -38,11 +36,17 @@ class CustomFormatter(logging.Formatter):
return formatter.format(record)
class plainFormatter(logging.Formatter):
ansi_escape = re.compile(r'\x1b\[([0-9]+)(;[0-9]+)*m')
ansi_codes = [
'\x1b[38;21m', '\x1b[38;5;231m', '\x1b[38;5;39m', '\x1b[38;5;226m',
'\x1b[38;5;196m', '\x1b[38;5;46m', '\x1b[38;5;129m', '\x1b[31;1m',
'\x1b[37;1m', '\x1b[0m'
]
def format(self, record):
message = super().format(record)
return self.ansi_escape.sub('', message)
for code in self.ansi_codes:
message = message.replace(code, '')
return message
# Create logger
logger = logging.getLogger("MeshBot System Logger")
@@ -56,7 +60,6 @@ msgLogger.propagate = False
# Define format for logs
logFormat = '%(asctime)s | %(levelname)8s | %(message)s'
msgLogFormat = '%(asctime)s | %(message)s'
today = datetime.now()
# Create stdout handler for logging to the console
stdout_handler = logging.StreamHandler()
@@ -67,34 +70,30 @@ stdout_handler.setFormatter(CustomFormatter(logFormat))
# Add handlers to the logger
logger.addHandler(stdout_handler)
if syslog_to_file:
if my_settings.syslog_to_file:
# Create file handler for logging to a file
file_handler_sys = TimedRotatingFileHandler('logs/meshbot.log', when='midnight', backupCount=log_backup_count, encoding='utf-8')
file_handler_sys = TimedRotatingFileHandler('logs/meshbot.log', when='midnight', backupCount=my_settings.log_backup_count, encoding='utf-8')
file_handler_sys.setLevel(LOGGING_LEVEL) # DEBUG used by default for system logs to disk
file_handler_sys.setFormatter(plainFormatter(logFormat))
logger.addHandler(file_handler_sys)
if log_messages_to_file:
if my_settings.log_messages_to_file:
# Create file handler for logging to a file
file_handler = TimedRotatingFileHandler('logs/messages.log', when='midnight', backupCount=log_backup_count, encoding='utf-8')
file_handler = TimedRotatingFileHandler('logs/messages.log', when='midnight', backupCount=my_settings.log_backup_count, encoding='utf-8')
file_handler.setLevel(logging.INFO) # INFO used for messages to disk
file_handler.setFormatter(logging.Formatter(msgLogFormat))
msgLogger.addHandler(file_handler)
# Pretty Timestamp
def getPrettyTime(seconds):
# convert unix time to minutes, hours, or days, or years for simple display
designator = "s"
if seconds > 0:
seconds = round(seconds / 60)
designator = "m"
if seconds > 60:
seconds = round(seconds / 60)
designator = "h"
if seconds > 24:
seconds = round(seconds / 24)
designator = "d"
if seconds > 365:
seconds = round(seconds / 365)
designator = "y"
return str(seconds) + designator
# convert unix time to minutes, hours, days, or years for simple display
if seconds < 60:
return f"{int(seconds)}s"
elif seconds < 3600:
return f"{int(round(seconds / 60))}m"
elif seconds < 86400:
return f"{int(round(seconds / 3600))}h"
elif seconds < 31536000:
return f"{int(round(seconds / 86400))}d"
else:
return f"{int(round(seconds / 31536000))}y"

View File

@@ -1,18 +1,29 @@
# Module to respomnd to new nodes we havent seen before with a hello message
# K7MHI Kelly Keeton 2024
import os
import sqlite3
from modules.log import *
from modules.log import logger
from modules.settings import qrz_db
def initalize_qrz_database():
# create the database
conn = sqlite3.connect(qrz_db)
c = conn.cursor()
# Check if the qrz table exists, and create it if it doesn't
c.execute('''CREATE TABLE IF NOT EXISTS qrz
(qrz_id INTEGER PRIMARY KEY, qrz_call TEXT, qrz_name TEXT, qrz_qth TEXT, qrz_notes TEXT)''')
conn.commit()
conn.close()
try:
# If the database file doesn't exist, it will be created by sqlite3.connect
if not os.path.exists(qrz_db):
logger.info(f"QRZ database file '{qrz_db}' not found. Creating new database.")
conn = sqlite3.connect(qrz_db)
c = conn.cursor()
# Create the table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS qrz
(qrz_id INTEGER PRIMARY KEY, qrz_call TEXT, qrz_name TEXT, qrz_qth TEXT, qrz_notes TEXT)''')
conn.commit()
return True
except sqlite3.Error as e:
logger.error(f"Error initializing QRZ database: {e}")
return False
finally:
if 'conn' in locals():
conn.close()
def never_seen_before(nodeID):
# check if we have seen this node before and sent a hello message

View File

@@ -1,13 +1,125 @@
# meshing around with hamlib as a source for info to send to mesh network
# detect signal strength and frequency of active channel if appears to be in use send to mesh network
# depends on rigctld running externally as a network service
# also can use VOX detection with a microphone and vosk speech to text to send voice messages to mesh network
# requires vosk and sounddevice python modules. will auto download needed. more from https://alphacephei.com/vosk/models and unpack
# 2024 Kelly Keeton K7MHI
import socket
from modules.log import logger
import asyncio
from modules.log import *
from modules.settings import (
radio_detection_enabled,
rigControlServerAddress,
signalDetectionThreshold,
signalHoldTime,
signalCooldown,
signalCycleLimit,
voxDetectionEnabled,
useLocalVoxModel,
localVoxModelPath,
voxLanguage,
voxInputDevice,
voxTrapList,
voxOnTrapList,
voxEnableCmd,
ERROR_FETCHING_DATA
)
# verbose debug logging for trap words function
debugVoxTmsg = False
if radio_detection_enabled:
# used by hamlib detection
import socket
if voxDetectionEnabled:
# methods available for trap word processing, these can be called by VOX detection when trap words are detected
from mesh_bot import tell_joke, handle_wxc, handle_moon, handle_sun, handle_riverFlow, handle_tide, handle_satpass
botMethods = {
"joke": tell_joke,
"weather": handle_wxc,
"moon": handle_moon,
"daylight": handle_sun,
"river": handle_riverFlow,
"tide": handle_tide,
"satellite": handle_satpass}
# module global variables
previousVoxState = False
voxHoldTime = signalHoldTime
try:
import sounddevice as sd # pip install sounddevice sudo apt install portaudio19-dev
from vosk import Model, KaldiRecognizer # pip install vosk
import json
q = asyncio.Queue(maxsize=32) # queue for audio data
if useLocalVoxModel:
voxModel = Model(lang=localVoxModelPath) # use built in model for specified language
else:
voxModel = Model(lang=voxLanguage) # use built in model for specified language
except Exception as e:
print(f"RadioMon: Error importing VOX dependencies: {e}")
print(f"To use VOX detection please install the vosk and sounddevice python modules")
print(f"pip install vosk sounddevice")
print(f"sounddevice needs pulseaudio, apt-get install portaudio19-dev")
voxDetectionEnabled = False
logger.error(f"RadioMon: VOX detection disabled due to import error")
FREQ_NAME_MAP = {
462562500: "GRMS CH1",
462587500: "GRMS CH2",
462612500: "GRMS CH3",
462637500: "GRMS CH4",
462662500: "GRMS CH5",
462687500: "GRMS CH6",
462712500: "GRMS CH7",
467562500: "GRMS CH8",
467587500: "GRMS CH9",
467612500: "GRMS CH10",
467637500: "GRMS CH11",
467662500: "GRMS CH12",
467687500: "GRMS CH13",
467712500: "GRMS CH14",
467737500: "GRMS CH15",
462550000: "GRMS CH16",
462575000: "GMRS CH17",
462600000: "GMRS CH18",
462625000: "GMRS CH19",
462675000: "GMRS CH20",
462670000: "GMRS CH21",
462725000: "GMRS CH22",
462725500: "GMRS CH23",
467575000: "GMRS CH24",
467600000: "GMRS CH25",
467625000: "GMRS CH26",
467650000: "GMRS CH27",
467675000: "GMRS CH28",
467700000: "FRS CH1",
462650000: "FRS CH5",
462700000: "FRS CH7",
462737500: "FRS CH16",
146520000: "2M Simplex Calling",
446000000: "70cm Simplex Calling",
156800000: "Marine CH16",
# Add more as needed
}
def get_freq_common_name(freq):
freq = int(freq)
name = FREQ_NAME_MAP.get(freq)
if name:
return name
else:
# Return MHz if not found
return f"{freq/1000000} Mhz"
def get_hamlib(msg="f"):
# get data from rigctld server
if "socket" not in globals():
logger.warning("RadioMon: 'socket' module not imported. Hamlib disabled.")
return ERROR_FETCHING_DATA
try:
rigControlSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
rigControlSocket.settimeout(2)
@@ -29,110 +141,47 @@ def get_hamlib(msg="f"):
except Exception as e:
logger.error(f"RadioMon: Error fetching data from rigctld: {e}")
return ERROR_FETCHING_DATA
def get_freq_common_name(freq):
freq = int(freq)
if freq == 462562500:
return "GRMS CH1"
elif freq == 462587500:
return "GRMS CH2"
elif freq == 462612500:
return "GRMS CH3"
elif freq == 462637500:
return "GRMS CH4"
elif freq == 462662500:
return "GRMS CH5"
elif freq == 462687500:
return "GRMS CH6"
elif freq == 462712500:
return "GRMS CH7"
elif freq == 467562500:
return "GRMS CH8"
elif freq == 467587500:
return "GRMS CH9"
elif freq == 467612500:
return "GRMS CH10"
elif freq == 467637500:
return "GRMS CH11"
elif freq == 467662500:
return "GRMS CH12"
elif freq == 467687500:
return "GRMS CH13"
elif freq == 467712500:
return "GRMS CH14"
elif freq == 467737500:
return "GRMS CH15"
elif freq == 462550000:
return "GRMS CH16"
elif freq == 462575000:
return "GMRS CH17"
elif freq == 462600000:
return "GMRS CH18"
elif freq == 462625000:
return "GMRS CH19"
elif freq == 462675000:
return "GMRS CH20"
elif freq == 462670000:
return "GMRS CH21"
elif freq == 462725000:
return "GMRS CH22"
elif freq == 462725500:
return "GMRS CH23"
elif freq == 467575000:
return "GMRS CH24"
elif freq == 467600000:
return "GMRS CH25"
elif freq == 467625000:
return "GMRS CH26"
elif freq == 467650000:
return "GMRS CH27"
elif freq == 467675000:
return "GMRS CH28"
elif freq == 467700000:
return "FRS CH1"
elif freq == 462575000:
return "FRS CH2"
elif freq == 462600000:
return "FRS CH3"
elif freq == 462650000:
return "FRS CH5"
elif freq == 462675000:
return "FRS CH6"
elif freq == 462700000:
return "FRS CH7"
elif freq == 462725000:
return "FRS CH8"
elif freq == 462562500:
return "FRS CH9"
elif freq == 462587500:
return "FRS CH10"
elif freq == 462612500:
return "FRS CH11"
elif freq == 462637500:
return "FRS CH12"
elif freq == 462662500:
return "FRS CH13"
elif freq == 462687500:
return "FRS CH14"
elif freq == 462712500:
return "FRS CH15"
elif freq == 462737500:
return "FRS CH16"
elif freq == 146520000:
return "2M Simplex Calling"
elif freq == 446000000:
return "70cm Simplex Calling"
elif freq == 156800000:
return "Marine CH16"
else:
#return Mhz
freq = freq/1000000
return f"{freq} Mhz"
def get_sig_strength():
strength = get_hamlib('l STRENGTH')
return strength
def checkVoxTrapWords(text):
try:
if not voxOnTrapList:
logger.debug(f"RadioMon: VOX detected: {text}")
return text
if text:
traps = [voxTrapList] if isinstance(voxTrapList, str) else voxTrapList
text_lower = text.lower()
for trap in traps:
trap_clean = trap.strip()
trap_lower = trap_clean.lower()
idx = text_lower.find(trap_lower)
if debugVoxTmsg:
logger.debug(f"RadioMon: VOX checking for trap word '{trap_lower}' in: '{text}' (index: {idx})")
if idx != -1:
new_text = text[idx + len(trap_clean):].strip()
if debugVoxTmsg:
logger.debug(f"RadioMon: VOX detected trap word '{trap_lower}' in: '{text}' (remaining: '{new_text}')")
new_words = new_text.split()
if voxEnableCmd:
for word in new_words:
if word in botMethods:
logger.info(f"RadioMon: VOX action '{word}' with '{new_text}'")
if word == "joke":
return botMethods[word](vox=True)
else:
return botMethods[word](None, None, None, vox=True)
logger.debug(f"RadioMon: VOX returning text after trap word '{trap_lower}': '{new_text}'")
return new_text
if debugVoxTmsg:
logger.debug(f"RadioMon: VOX no trap word found in: '{text}'")
return None
except Exception as e:
logger.debug(f"RadioMon: Error in checkVoxTrapWords: {e}")
return None
async def signalWatcher():
global previousStrength
global signalCycle
@@ -157,4 +206,61 @@ async def signalWatcher():
signalCycle = 0
previousStrength = -40
# end of file
async def make_vox_callback(loop, q):
def vox_callback(indata, frames, time, status):
if status:
logger.warning(f"RadioMon: VOX input status: {status}")
try:
loop.call_soon_threadsafe(q.put_nowait, bytes(indata))
except asyncio.QueueFull:
# Drop the oldest item and add the new one
try:
q.get_nowait() # Remove oldest
except asyncio.QueueEmpty:
pass
try:
loop.call_soon_threadsafe(q.put_nowait, bytes(indata))
except asyncio.QueueFull:
# If still full, just drop this frame
logger.debug("RadioMon: VOX queue full, dropping audio frame")
except RuntimeError:
# Loop may be closed
pass
return vox_callback
async def voxMonitor():
global previousVoxState, voxMsgQueue
try:
model = voxModel
device_info = sd.query_devices(voxInputDevice, 'input')
samplerate = 16000
logger.debug(f"RadioMon: VOX monitor started on device {device_info['name']} with samplerate {samplerate} using trap words: {voxTrapList if voxOnTrapList else 'none'}")
rec = KaldiRecognizer(model, samplerate)
loop = asyncio.get_running_loop()
callback = await make_vox_callback(loop, q)
with sd.RawInputStream(
device=voxInputDevice,
samplerate=samplerate,
blocksize=4000,
dtype='int16',
channels=1,
callback=callback
):
while True:
data = await q.get()
if rec.AcceptWaveform(data):
result = rec.Result()
text = json.loads(result).get("text", "")
# process text
if text and text != 'huh':
result = checkVoxTrapWords(text)
if result:
# If result is a function return, handle it (send to mesh, log, etc.)
# If it's just text, handle as a normal message
voxMsgQueue.append(result)
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"RadioMon: Error in VOX monitor: {e}")
# end of file

138
modules/rss.py Normal file
View File

@@ -0,0 +1,138 @@
# rss feed module for meshing-around 2025
from modules.log import logger
from modules.settings import rssFeedURL, rssFeedNames, rssMaxItems, rssTruncate, urlTimeoutSeconds, ERROR_FETCHING_DATA
import urllib.request
import xml.etree.ElementTree as ET
import html
from html.parser import HTMLParser
import bs4 as bs
# Common User-Agent for all RSS requests
COMMON_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html_text):
# use BeautifulSoup to strip HTML tags
if not html_text:
return ""
soup = bs.BeautifulSoup(html_text, "html.parser")
text = soup.get_text(separator=" ", strip=True)
return ' '.join(text.split())
RSS_FEED_URLS = rssFeedURL
RSS_FEED_NAMES = rssFeedNames
RSS_RETURN_COUNT = rssMaxItems
RSS_TRIM_LENGTH = rssTruncate
def get_rss_feed(msg):
# Determine which feed to use
feed_name = ""
msg_lower = msg.lower() if msg else ""
if msg_lower and any(name.lower() in msg_lower for name in RSS_FEED_NAMES):
for name in RSS_FEED_NAMES:
if name.lower() in msg_lower:
feed_name = name
break
else:
logger.debug(f"RSS: No feed name found in message '{msg}'. Using default feed.")
feed_name = RSS_FEED_NAMES[0] if RSS_FEED_NAMES else "default"
try:
idx = RSS_FEED_NAMES.index(feed_name)
feed_url = RSS_FEED_URLS[idx]
except (ValueError, IndexError):
logger.warning(f"RSS: Feed '{feed_name}' not found in RSS_FEED_URLS ({RSS_FEED_URLS}).")
return f"Feed '{feed_name}' not found."
if "?" in msg_lower:
return f"Fetches the latest {RSS_RETURN_COUNT} entries RSS feeds. Available feeds are: {', '.join(RSS_FEED_NAMES)}. To fetch a specific feed, include its name in your request."
# Fetch and parse the RSS feed
try:
logger.debug(f"Fetching RSS feed from {feed_url} from message '{msg}'")
agent = {'User-Agent': COMMON_USER_AGENT}
request = urllib.request.Request(feed_url, headers=agent)
with urllib.request.urlopen(request, timeout=urlTimeoutSeconds) as response:
xml_data = response.read()
root = ET.fromstring(xml_data)
# Find all <item> (RSS) and <entry> (Atom) elements, regardless of namespace
items = []
for elem in root.iter():
if elem.tag.endswith('item') or elem.tag.endswith('entry'):
items.append(elem)
items = items[:RSS_RETURN_COUNT]
if not items:
logger.debug(f"No RSS or Atom feed entries found in feed xml_data: {xml_data[:500]}...")
return "No RSS or Atom feed entries found."
formatted_entries = []
seen_first3 = set() # Track first 3 words (lowercased) to avoid duplicates
for item in items:
# Helper to try multiple tag names
def find_any(item, tags):
for tag in tags:
val = item.findtext(tag)
if val:
return val
return None
title = find_any(item, [
'title',
'{http://purl.org/rss/1.0/}title',
'{http://www.w3.org/2005/Atom}title'
])
# Atom links are often attributes, not text
link = find_any(item, [
'link',
'{http://purl.org/rss/1.0/}link',
'{http://www.w3.org/2005/Atom}link'
])
if not link:
link_elem = item.find('{http://www.w3.org/2005/Atom}link')
if link_elem is not None and 'href' in link_elem.attrib:
link = link_elem.attrib['href']
description = find_any(item, [
'description',
'{http://purl.org/rss/1.0/}description',
'{http://purl.org/rss/1.0/modules/content/}encoded',
'{http://www.w3.org/2005/Atom}summary',
'{http://www.w3.org/2005/Atom}content'
])
pub_date = find_any(item, [
'pubDate',
'{http://purl.org/dc/elements/1.1/}date',
'{http://www.w3.org/2005/Atom}updated'
])
# Unescape HTML entities and strip tags
description = html.unescape(description) if description else ""
description = strip_tags(description)
if len(description) > RSS_TRIM_LENGTH:
description = description[:RSS_TRIM_LENGTH - 3] + "..."
# Duplicate check: use first 3 words of description (or title if description is empty)
text_for_dupe = description if description else (title or "")
first3 = " ".join(text_for_dupe.lower().split()[:3])
if first3 in seen_first3:
continue
seen_first3.add(first3)
formatted_entries.append(f"{title}\n{description}\n")
return "\n".join(formatted_entries)
except Exception as e:
logger.error(f"Error fetching RSS feed from {feed_url}: {e}")
return ERROR_FETCHING_DATA

157
modules/scheduler.py Normal file
View File

@@ -0,0 +1,157 @@
# modules/scheduler.py 2025 meshing-around
# Scheduler setup for Mesh Bot
import asyncio
import schedule
from datetime import datetime
from functools import partial
from modules.log import logger
from modules.settings import MOTD
from modules.system import send_message
async def run_scheduler_loop(interval=1):
logger.debug(f"System: Scheduler loop started Tasks: {len(schedule.jobs)}, Details:{extract_schedule_fields(schedule.get_jobs())}")
try:
last_logged_minute = -1
while True:
try:
# Log scheduled jobs every 20 minutes
now = datetime.now()
if now.minute % 20 == 0 and now.minute != last_logged_minute:
logger.debug(f"System: Scheduled Tasks {len(schedule.jobs)}, Details:{extract_schedule_fields(schedule.get_jobs())}")
last_logged_minute = now.minute
schedule.run_pending()
except Exception as e:
logger.error(f"System: Scheduler loop exception: {e}")
await asyncio.sleep(interval)
except asyncio.CancelledError:
logger.debug("System: Scheduler loop cancelled, shutting down.")
def safe_int(val, default=0, type=""):
try:
return int(val)
except (ValueError, TypeError):
logger.debug(f"System: Scheduler config {type} error '{val}' to int, using default {default}")
return default
def extract_schedule_fields(jobs):
"""
Extracts 'Every ... (last run: [...], next run: ...)' from schedule.get_jobs() output without regex.
"""
jobs_str = str(jobs)
results = []
# Split by '), ' to separate jobs, then add ')' back except last
parts = jobs_str.split('), ')
for i, part in enumerate(parts):
if not part.endswith(')'):
part += ')'
# Find the start of 'Every'
start = part.find('Every')
if start != -1:
# Find the start of 'do <lambda>()'
do_idx = part.find('do ')
if do_idx != -1:
summary = part[start:do_idx].strip()
# Find the (last run: ... next run: ...) part
paren_idx = part.find('(', do_idx)
if paren_idx != -1:
summary += ' ' + part[paren_idx:].strip()
while '<function ' in summary:
f_start = summary.find('<function ')
f_end = summary.find('>', f_start)
if f_end == -1:
break
func_str = summary[f_start+10:f_end]
func_name = func_str.split(' ')[0]
summary = summary[:f_start] + func_name + summary[f_end+1:]
results.append(summary)
return results
def setup_scheduler(
schedulerMotd, MOTD, schedulerMessage, schedulerChannel, schedulerInterface,
schedulerValue, schedulerTime, schedulerInterval):
try:
# Methods imported from mesh_bot for scheduling tasks
from mesh_bot import (
tell_joke,
welcome_message,
handle_wxc,
handle_moon,
handle_sun,
handle_riverFlow,
handle_tide,
handle_satpass,
)
except ImportError as e:
logger.warning(f"Some mesh_bot schedule features are unavailable by option disable in config.ini: {e} comment out the use of these methods in your custom_scheduler.py")
# Setup the scheduler based on configuration
schedulerValue = schedulerValue.lower().strip()
schedulerTime = schedulerTime.strip()
schedulerInterval = schedulerInterval.strip()
schedulerChannel = safe_int(schedulerChannel, 0, type="channel")
schedulerInterface = safe_int(schedulerInterface, 1, type="interface")
schedulerIntervalInt = safe_int(schedulerInterval, 5, type="interval")
try:
scheduler_message = MOTD if schedulerMotd else schedulerMessage
def send_sched_msg():
send_message(scheduler_message, schedulerChannel, 0, schedulerInterface)
# Basic Scheduler Options
basicOptions = ['day', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'hour', 'min']
if any(option in schedulerValue for option in basicOptions):
if schedulerValue == 'day':
if schedulerTime:
schedule.every().day.at(schedulerTime).do(send_sched_msg)
else:
schedule.every(schedulerIntervalInt).days.do(send_sched_msg)
elif 'mon' in schedulerValue and schedulerTime:
schedule.every().monday.at(schedulerTime).do(send_sched_msg)
elif 'tue' in schedulerValue and schedulerTime:
schedule.every().tuesday.at(schedulerTime).do(send_sched_msg)
elif 'wed' in schedulerValue and schedulerTime:
schedule.every().wednesday.at(schedulerTime).do(send_sched_msg)
elif 'thu' in schedulerValue and schedulerTime:
schedule.every().thursday.at(schedulerTime).do(send_sched_msg)
elif 'fri' in schedulerValue and schedulerTime:
schedule.every().friday.at(schedulerTime).do(send_sched_msg)
elif 'sat' in schedulerValue and schedulerTime:
schedule.every().saturday.at(schedulerTime).do(send_sched_msg)
elif 'sun' in schedulerValue and schedulerTime:
schedule.every().sunday.at(schedulerTime).do(send_sched_msg)
elif 'hour' in schedulerValue:
schedule.every(schedulerIntervalInt).hours.do(send_sched_msg)
elif 'min' in schedulerValue:
schedule.every(schedulerIntervalInt).minutes.do(send_sched_msg)
logger.debug(f"System: Starting the basic scheduler to send '{scheduler_message}' on schedule '{schedulerValue}' every {schedulerIntervalInt} interval at time '{schedulerTime}' on Device:{schedulerInterface} Channel:{schedulerChannel}")
elif 'joke' in schedulerValue:
schedule.every(schedulerIntervalInt).minutes.do(
partial(send_message, tell_joke(), schedulerChannel, 0, schedulerInterface)
)
logger.debug(f"System: Starting the joke scheduler to send a joke every {schedulerIntervalInt} minutes on Device:{schedulerInterface} Channel:{schedulerChannel}")
elif 'link' in schedulerValue:
schedule.every(schedulerIntervalInt).hours.do(
send_message("bbslink MeshBot looking for peers", schedulerChannel, 0, schedulerInterface)
)
logger.debug(f"System: Starting the link scheduler to send link messages every {schedulerIntervalInt} hours on Device:{schedulerInterface} Channel:{schedulerChannel}")
elif 'weather' in schedulerValue:
schedule.every().day.at(schedulerTime).do(
partial(send_message, handle_wxc(0, schedulerInterface, 'wx', days=1), schedulerChannel, 0, schedulerInterface)
)
logger.debug(f"System: Starting the weather scheduler to send weather updates every {schedulerIntervalInt} hours on Device:{schedulerInterface} Channel:{schedulerChannel}")
elif 'custom' in schedulerValue:
try:
from modules.custom_scheduler import setup_custom_schedules # type: ignore
setup_custom_schedules(
send_message, tell_joke, welcome_message, handle_wxc, MOTD,
schedulerChannel, schedulerInterface)
logger.debug(f"System: Starting the custom_scheduler.py ")
schedule.every().monday.at("12:00").do(
lambda: logger.info("System: Scheduled Broadcast Enabled Reminder")
)
except Exception as e:
logger.warning("Custom scheduler file not found or failed to import. cp etc/custom_scheduler.py modules/custom_scheduler.py")
except Exception as e:
logger.error(f"System: Scheduler Error {e}")
return True

View File

@@ -21,14 +21,37 @@ ping_enabled = True # ping feature to respond to pings, ack's etc.
sitrep_enabled = True # sitrep feature to respond to sitreps
lastHamLibAlert = 0 # last alert from hamlib
lastFileAlert = 0 # last alert from file monitor
max_retry_count1 = 4 # max retry count for interface 1
max_retry_count2 = 4 # max retry count for interface 2
max_retry_count1 = max_retry_count2 = max_retry_count3 = max_retry_count4 = max_retry_count5 = max_retry_count6 = max_retry_count7 = max_retry_count8 = max_retry_count9 = 4 # default retry count for interfaces
retry_int1 = False
retry_int2 = False
wiki_return_limit = 3 # limit the number of sentences returned off the first paragraph first hit
GAMEDELAY = 28800 # 8 hours in seconds for game mode holdoff
cmdHistory = [] # list to hold the last commands
seenNodes = [] # list to hold the last seen nodes
cmdHistory = [] # list to hold the command history for lheard and history commands
msg_history = [] # list to hold the message history for the messages command
max_bytes = 200 # Meshtastic has ~237 byte limit, use conservative 200 bytes for message content
voxMsgQueue = [] # queue for VOX detected messages
# Game trackers
surveyTracker = [] # Survey game tracker
tictactoeTracker = [] # TicTacToe game tracker
hamtestTracker = [] # Ham radio test tracker
hangmanTracker = [] # Hangman game tracker
golfTracker = [] # GolfSim game tracker
mastermindTracker = [] # Mastermind game tracker
vpTracker = [] # Video Poker game tracker
jackTracker = [] # Blackjack game tracker
lemonadeTracker = [] # Lemonade Stand game tracker
dwPlayerTracker = [] # DopeWars player tracker
jackTracker = [] # Jack game tracker
mindTracker = [] # Mastermind (mmind) game tracker
# Memory Management Constants
MAX_MSG_HISTORY = 250
MAX_CMD_HISTORY = 250
MAX_SEEN_NODES = 1000
CLEANUP_INTERVAL = 86400 # 24 hours in seconds
GAMEDELAY = 3 * CLEANUP_INTERVAL # 3 days in seconds
# Read the config file, if it does not exist, create basic config file
config = configparser.ConfigParser()
@@ -38,6 +61,10 @@ try:
config.read(config_file, encoding='utf-8')
except Exception as e:
print(f"System: Error reading config file: {e}")
# exit if we can't read the config file
print(f"System: Check the config.ini against config.template file for missing sections or values.")
print(f"System: Exiting...")
exit(1)
if config.sections() == []:
print(f"System: Error reading config file: {config_file} is empty or does not exist.")
@@ -198,14 +225,16 @@ try:
ignoreChannels = config['general'].get('ignoreChannels', '').split(',') # ignore these channels
ignoreDefaultChannel = config['general'].getboolean('ignoreDefaultChannel', False)
cmdBang = config['general'].getboolean('cmdBang', False) # default off
explicitCmd = config['general'].getboolean('explicitCmd', True) # default on
zuluTime = config['general'].getboolean('zuluTime', False) # aka 24 hour time
log_messages_to_file = config['general'].getboolean('LogMessagesToFile', False) # default off
log_backup_count = config['general'].getint('LogBackupCount', 32) # default 32 days
syslog_to_file = config['general'].getboolean('SyslogToFile', True) # default on
LOGGING_LEVEL = config['general'].get('sysloglevel', 'DEBUG') # default DEBUG
urlTimeoutSeconds = config['general'].getint('urlTimeout', 10) # default 10 seconds
urlTimeoutSeconds = config['general'].getint('urlTimeout', 15) # default 15 seconds for URL fetch timeout
store_forward_enabled = config['general'].getboolean('StoreForward', True)
storeFlimit = config['general'].getint('StoreLimit', 3) # default 3 messages for S&F
reverseSF = config['general'].getboolean('reverseSF', False) # default False, send oldest first
welcome_message = config['general'].get('welcome_message', WELCOME_MSG)
welcome_message = (f"{welcome_message}").replace('\\n', '\n') # allow for newlines in the welcome message
motd_enabled = config['general'].getboolean('motdEnabled', True)
@@ -219,9 +248,28 @@ try:
bee_enabled = config['general'].getboolean('bee', False) # 🐝 off by default undocumented
solar_conditions_enabled = config['general'].getboolean('spaceWeather', True)
wikipedia_enabled = config['general'].getboolean('wikipedia', False)
use_kiwix_server = config['general'].getboolean('useKiwixServer', False)
kiwix_url = config['general'].get('kiwixURL', 'http://127.0.0.1:8080')
kiwix_library_name = config['general'].get('kiwixLibraryName', 'wikipedia_en_100_nopic_2024-06')
llm_enabled = config['general'].getboolean('ollama', False) # https://ollama.com
llmModel = config['general'].get('ollamaModel', 'gemma2:2b') # default gemma2:2b
ollamaHostName = config['general'].get('ollamaHostName', 'http://localhost:11434') # default localhost
llmModel = config['general'].get('ollamaModel', 'gemma3:270m') # default gemma3:270m
rawLLMQuery = config['general'].getboolean('rawLLMQuery', True) #default True
llmReplyToNonCommands = config['general'].getboolean('llmReplyToNonCommands', True) # default True
llmUseWikiContext = config['general'].getboolean('llmUseWikiContext', False) # default False
useOpenWebUI = config['general'].getboolean('useOpenWebUI', False) # default False
openWebUIURL = config['general'].get('openWebUIURL', 'http://localhost:3000') # default localhost:3000
openWebUIAPIKey = config['general'].get('openWebUIAPIKey', '') # default empty
dont_retry_disconnect = config['general'].getboolean('dont_retry_disconnect', False) # default False, retry on disconnect
favoriteNodeList = config['general'].get('favoriteNodeList', '').split(',')
enableEcho = config['general'].getboolean('enableEcho', False) # default False
echoChannel = config['general'].getint('echoChannel', '9') # default 9, empty string to ignore
rssEnable = config['general'].getboolean('rssEnable', True) # default True
rssFeedURL = config['general'].get('rssFeedURL', 'http://www.hackaday.com/rss.xml,https://www.arrl.org/rss/arrl.rss').split(',')
rssMaxItems = config['general'].getint('rssMaxItems', 3) # default 3 items
rssTruncate = config['general'].getint('rssTruncate', 100) # default 100 characters
rssFeedNames = config['general'].get('rssFeedNames', 'default,arrl').split(',')
# emergency response
emergency_responder_enabled = config['emergencyHandler'].getboolean('enabled', False)
emergency_responder_alert_channel = config['emergencyHandler'].getint('alert_channel', 2) # default 2
@@ -231,39 +279,62 @@ try:
# sentry
sentry_enabled = config['sentry'].getboolean('SentryEnabled', False) # default False
secure_channel = config['sentry'].getint('SentryChannel', 2) # default 2
secure_interface = config['sentry'].getint('SentryInterface', 1) # default 1
sentry_holdoff = config['sentry'].getint('SentryHoldoff', 9) # default 9
sentryIgnoreList = config['sentry'].get('sentryIgnoreList', '').split(',')
sentryWatchList = config['sentry'].get('sentryWatchList', '').split(',')
sentry_radius = config['sentry'].getint('SentryRadius', 100) # default 100 meters
email_sentry_alerts = config['sentry'].getboolean('emailSentryAlerts', False) # default False
highfly_enabled = config['sentry'].getboolean('highFlyingAlert', True) # default True
highfly_altitude = config['sentry'].getint('highFlyingAlertAltitude', 2000) # default 2000 meters
highfly_channel = config['sentry'].getint('highFlyingAlertChannel', 2) # default 2
highfly_interface = config['sentry'].getint('highFlyingAlertInterface', 1) # default 1
highfly_ignoreList = config['sentry'].get('highFlyingIgnoreList', '').split(',') # default empty
highfly_check_openskynetwork = config['sentry'].getboolean('highflyOpenskynetwork', True) # default True check with OpenSkyNetwork if highfly detected
detctionSensorAlert = config['sentry'].getboolean('detectionSensorAlert', False) # default False
reqLocationEnabled = config['sentry'].getboolean('reqLocationEnabled', False) # default False
cmdShellSentryAlerts = config['sentry'].getboolean('cmdShellSentryAlerts', False) # default False
sentryAlertNear = config['sentry'].get('sentryAlertNear', 'sentry_alert_near.sh') # default sentry_alert_near.sh
sentryAlertFar = config['sentry'].get('sentryAlertFar', 'sentry_alert_far.sh') # default sentry_alert_far.sh
# location
location_enabled = config['location'].getboolean('enabled', True)
latitudeValue = config['location'].getfloat('lat', 48.50)
longitudeValue = config['location'].getfloat('lon', -123.0)
fuzz_config_location = config['location'].getboolean('fuzzConfigLocation', True) # default True
fuzzItAll = config['location'].getboolean('fuzzAllLocations', False) # default False, only fuzz config location
use_meteo_wxApi = config['location'].getboolean('UseMeteoWxAPI', False) # default False use NOAA
use_metric = config['location'].getboolean('useMetric', False) # default Imperial units
repeater_lookup = config['location'].get('repeaterLookup', 'rbook') # default repeater lookup source
n2yoAPIKey = config['location'].get('n2yoAPIKey', '') # default empty
satListConfig = config['location'].get('satList', '25544').split(',') # default 25544 ISS
riverListDefault = config['location'].get('riverList', '').split(',') # default 12061500 Skagit River
riverListDefault = config['location'].get('riverList', '').split(',') # default None
coastalEnabled = config['location'].getboolean('coastalEnabled', False) # default False
myCoastalZone = config['location'].get('myCoastalZone', None) # default None
coastalForecastDays = config['location'].getint('coastalForecastDays', 3) # default 3 days
# location alerts
emergencyAlertBrodcastEnabled = config['location'].getboolean('eAlertBroadcastEnabled', False) # default False
wxAlertBroadcastEnabled = config['location'].getboolean('wxAlertBroadcastEnabled', False) # default False
enableGBalerts = config['location'].getboolean('enableGBalerts', False) # default False
enableDEalerts = config['location'].getboolean('enableDEalerts', False) # default False
wxAlertsEnabled = config['location'].getboolean('NOAAalertsEnabled', True) # default True
mySAME = config['location'].get('mySAME', '').split(',') # default empty
ignoreEASenable = config['location'].getboolean('ignoreEASenable', False) # default False
ignoreEASwords = config['location'].get('ignoreEASwords', 'test,advisory').split(',') # default test,advisory
myRegionalKeysDE = config['location'].get('myRegionalKeysDE', '110000000000').split(',') # default city Berlin
forecastDuration = config['location'].getint('NOAAforecastDuration', 4) # NOAA forcast days
numWxAlerts = config['location'].getint('NOAAalertCount', 2) # default 2 alerts
enableExtraLocationWx = config['location'].getboolean('enableExtraLocationWx', False) # default False
ipawsPIN = config['location'].get('ipawsPIN', '000000') # default 000000
myStateFIPSList = config['location'].get('myFIPSList', '').split(',') # default empty
mySAMEList = config['location'].get('mySAMEList', '').split(',') # default empty
ignoreFEMAenable = config['location'].getboolean('ignoreFEMAenable', True) # default True
ignoreFEMAwords = config['location'].get('ignoreFEMAwords', 'test,exercise').split(',') # default test,exercise
wxAlertBroadcastChannel = config['location'].get('wxAlertBroadcastCh', '2').split(',') # default Channel 2
emergencyAlertBroadcastCh = config['location'].get('eAlertBroadcastCh', '2').split(',') # default Channel 2
volcanoAlertBroadcastEnabled = config['location'].getboolean('volcanoAlertBroadcastEnabled', False) # default False
volcanoAlertBroadcastChannel = config['location'].get('volcanoAlertBroadcastCh', '2').split(',') # default Channel 2
ignoreUSGSEnable = config['location'].getboolean('ignoreVolcanoEnable', False) # default False
ignoreUSGSWords = config['location'].get('ignoreVolcanoWords', 'test,advisory').split(',') # default test,advisory
# bbs
bbs_enabled = config['bbs'].getboolean('enabled', False)
@@ -272,6 +343,7 @@ try:
bbs_admin_list = config['bbs'].get('bbs_admin_list', '').split(',')
bbs_link_enabled = config['bbs'].getboolean('bbslink_enabled', False)
bbs_link_whitelist = config['bbs'].get('bbslink_whitelist', '').split(',')
bbsAPI_enabled = config['bbs'].getboolean('bbsAPI_enabled', False)
# checklist
checklist_enabled = config['checklist'].getboolean('enabled', False)
@@ -281,7 +353,7 @@ try:
# qrz hello
qrz_hello_enabled = config['qrz'].getboolean('enabled', False)
qrz_db = config['qrz'].get('qrz_db', 'data/qrz.db')
qrz_hello_string = config['qrz'].get('qrz_hello_string', 'send CMD or DM me for more info.')
qrz_hello_string = config['qrz'].get('qrz_hello_string', 'MeshBot says Hello! DM for more info.')
train_qrz = config['qrz'].getboolean('training', True)
# E-Mail Settings
@@ -307,27 +379,49 @@ try:
# scheduler
scheduler_enabled = config['scheduler'].getboolean('enabled', False)
schedulerInterface = config['scheduler'].getint('interface', 1) # default interface 1
schedulerChannel = config['scheduler'].getint('channel', 2) # default channel 2
schedulerMessage = config['scheduler'].get('message', 'Scheduled message') # default message
schedulerInterval = config['scheduler'].get('interval', '') # default empty
schedulerTime = config['scheduler'].get('time', '') # default empty
schedulerValue = config['scheduler'].get('value', '') # default empty
schedulerMotd = config['scheduler'].getboolean('schedulerMotd', False) # default False
# radio monitoring
radio_detection_enabled = config['radioMon'].getboolean('enabled', False)
dxspotter_enabled = config['radioMon'].getboolean('dxspotter_enabled', True) # default True
rigControlServerAddress = config['radioMon'].get('rigControlServerAddress', 'localhost:4532') # default localhost:4532
sigWatchBroadcastCh = config['radioMon'].get('sigWatchBroadcastCh', '2').split(',') # default Channel 2
sigWatchBroadcastInterface = config['radioMon'].getint('sigWatchBroadcastInterface', 1) # default interface 1
signalDetectionThreshold = config['radioMon'].getint('signalDetectionThreshold', -10) # default -10 dBm
signalHoldTime = config['radioMon'].getint('signalHoldTime', 10) # default 10 seconds
signalCooldown = config['radioMon'].getint('signalCooldown', 5) # default 1 second
signalCycleLimit = config['radioMon'].getint('signalCycleLimit', 5) # default 5 cycles, used with SIGNAL_COOLDOWN
voxDetectionEnabled = config['radioMon'].getboolean('voxDetectionEnabled', False) # default VOX detection disabled
voxDescription = config['radioMon'].get('voxDescription', 'VOX') # default VOX detected audio message
useLocalVoxModel = config['radioMon'].getboolean('useLocalVoxModel', False) # default False
localVoxModelPath = config['radioMon'].get('localVoxModelPath', 'no') # default models/vox.tflite
voxLanguage = config['radioMon'].get('voxLanguage', 'en-US') # default en-US
voxInputDevice = config['radioMon'].get('voxInputDevice', 'default') # default default
voxOnTrapList = config['radioMon'].getboolean('voxOnTrapList', False) # default False
voxTrapList = config['radioMon'].get('voxTrapList', 'chirpy').split(',') # default chirpy
voxEnableCmd = config['radioMon'].getboolean('voxEnableCmd', True) # default True
# file monitor
file_monitor_enabled = config['fileMon'].getboolean('filemon_enabled', False)
file_monitor_file_path = config['fileMon'].get('file_path', 'alert.txt') # default alert.txt
file_monitor_broadcastCh = config['fileMon'].getint('broadcastCh', 2) # default 2
file_monitor_broadcastCh = config['fileMon'].get('broadcastCh', '2').split(',') # default Channel 2
read_news_enabled = config['fileMon'].getboolean('enable_read_news', False) # default disabled
news_file_path = config['fileMon'].get('news_file_path', 'news.txt') # default news.txt
news_file_path = config['fileMon'].get('news_file_path', '../data/news.txt') # default ../data/news.txt
news_random_line_only = config['fileMon'].getboolean('news_random_line', False) # default False
enable_runShellCmd = config['fileMon'].getboolean('enable_runShellCmd', False) # default False
allowXcmd = config['fileMon'].getboolean('allowXcmd', False) # default False
xCmd2factorEnabled = config['fileMon'].getboolean('2factor_enabled', True) # default True
xCmd2factor_timeout = config['fileMon'].getint('2factor_timeout', 100) # default 100 seconds
# games
game_hop_limit = config['messagingSettings'].getint('game_hop_limit', 5) # default 3 hops
game_hop_limit = config['games'].getint('game_hop_limit', 5) # default 5 hops
disable_emojis_in_games = config['games'].getboolean('disable_emojis', False) # default False
dopewars_enabled = config['games'].getboolean('dopeWars', True)
lemonade_enabled = config['games'].getboolean('lemonade', True)
blackjack_enabled = config['games'].getboolean('blackjack', True)
@@ -336,16 +430,29 @@ try:
golfSim_enabled = config['games'].getboolean('golfSim', True)
hangman_enabled = config['games'].getboolean('hangman', True)
hamtest_enabled = config['games'].getboolean('hamtest', True)
tictactoe_enabled = config['games'].getboolean('tictactoe', True)
quiz_enabled = config['games'].getboolean('quiz', False)
survey_enabled = config['games'].getboolean('survey', False)
default_survey = config['games'].get('defaultSurvey', 'example') # default example
surveyRecordID = config['games'].getboolean('surveyRecordID', True)
surveyRecordLocation = config['games'].getboolean('surveyRecordLocation', True)
wordOfTheDay = config['games'].getboolean('wordOfTheDay', True)
# messaging settings
responseDelay = config['messagingSettings'].getfloat('responseDelay', 0.7) # default 0.7
splitDelay = config['messagingSettings'].getfloat('splitDelay', 0) # default 0
MESSAGE_CHUNK_SIZE = config['messagingSettings'].getint('MESSAGE_CHUNK_SIZE', 160) # default 160
MESSAGE_CHUNK_SIZE = config['messagingSettings'].getint('MESSAGE_CHUNK_SIZE', 160) # default 160 chars
wantAck = config['messagingSettings'].getboolean('wantAck', False) # default False
maxBuffer = config['messagingSettings'].getint('maxBuffer', 220) # default 220
except KeyError as e:
maxBuffer = config['messagingSettings'].getint('maxBuffer', 200) # default 200 bytes
enableHopLogs = config['messagingSettings'].getboolean('enableHopLogs', False) # default False
debugMetadata = config['messagingSettings'].getboolean('debugMetadata', False) # default False
metadataFilter = config['messagingSettings'].get('metadataFilter', '').split(',') # default empty
DEBUGpacket = config['messagingSettings'].getboolean('DEBUGpacket', False) # default False
noisyNodeLogging = config['messagingSettings'].getboolean('noisyNodeLogging', False) # default False
logMetaStats = config['messagingSettings'].getboolean('logMetaStats', True) # default True
noisyTelemetryLimit = config['messagingSettings'].getint('noisyTelemetryLimit', 5) # default 5 packets
except Exception as e:
print(f"System: Error reading config file: {e}")
print(f"System: Check the config.ini against config.template file for missing sections or values.")
print(f"System: Exiting...")
print("System: Check the config.ini against config.template file for missing sections or values.")
print("System: Exiting...")
exit(1)

View File

@@ -3,7 +3,12 @@
# https://avtech.com/articles/138/list-of-email-to-sms-addresses/
# 2024 Kelly Keeton K7MHI
from modules.log import *
from modules.log import logger
from modules.settings import (
SMTP_SERVER, SMTP_PORT, SMTP_AUTH, SMTP_USERNAME, SMTP_PASSWORD,
FROM_EMAIL, EMAIL_SUBJECT, enableImap, IMAP_SERVER, IMAP_PORT,
IMAP_USERNAME, IMAP_PASSWORD, IMAP_FOLDER, sysopEmails, bbs_ban_list
)
import pickle
import time
import smtplib
@@ -152,6 +157,12 @@ def store_sms(nodeID, sms):
global sms_db
try:
logger.debug("System: Setting SMS for " + str(nodeID))
# if the nodeID has over 5 sms addresses warn and return
for item in sms_db:
if item['nodeID'] == nodeID:
if len(item['sms']) >= 5:
logger.warning("System: 📵SMS limit reached for " + str(nodeID))
return False
# if not in db, add it
if nodeID not in sms_db:
sms_db.append({'nodeID': nodeID, 'sms': sms})

View File

@@ -6,20 +6,28 @@ import requests # pip install requests
import xml.dom.minidom
from datetime import datetime
import ephem # pip install pyephem
from datetime import timedelta
from modules.log import *
from datetime import timezone
from modules.log import logger, getPrettyTime
from modules.settings import (latitudeValue, longitudeValue, zuluTime,
n2yoAPIKey, urlTimeoutSeconds, use_metric,
ERROR_FETCHING_DATA, NO_DATA_NOGPS, NO_ALERTS)
import math
trap_list_solarconditions = ("sun", "moon", "solar", "hfcond", "satpass")
trap_list_solarconditions = ("sun", "moon", "solar", "hfcond", "satpass", "howtall")
def hf_band_conditions():
# ham radio HF band conditions
hf_cond = ""
signalnoise = ""
band_cond = requests.get("https://www.hamqsl.com/solarxml.php", timeout=urlTimeoutSeconds)
if(band_cond.ok):
solarxml = xml.dom.minidom.parseString(band_cond.text)
for i in solarxml.getElementsByTagName("band"):
hf_cond += i.getAttribute("time")[0]+i.getAttribute("name") +"="+str(i.childNodes[0].data)+"\n"
hf_cond = hf_cond[:-1] # remove the last newline
for i in solarxml.getElementsByTagName("solardata"):
signalnoise = i.getElementsByTagName("signalnoise")[0].childNodes[0].data
hf_cond += "\nQRN:" + signalnoise
else:
logger.error("Solar: Error fetching HF band conditions")
hf_cond = ERROR_FETCHING_DATA
@@ -63,7 +71,7 @@ def drap_xray_conditions():
def get_sun(lat=0, lon=0):
# get sunrise and sunset times using callers location or default
obs = ephem.Observer()
obs.date = datetime.now()
obs.date = datetime.now(timezone.utc)
sun = ephem.Sun()
if lat != 0 and lon != 0:
obs.lat = str(lat)
@@ -74,9 +82,17 @@ def get_sun(lat=0, lon=0):
sun.compute(obs)
sun_table = {}
# get the sun azimuth and altitude
sun_table['azimuth'] = sun.az
sun_table['altitude'] = sun.alt
# sun is up include altitude
if sun_table['altitude'] > 0:
sun_table['altitude'] = sun.alt
else:
sun_table['altitude'] = 0
# get the next rise and set times
local_sunrise = ephem.localtime(obs.next_rising(sun))
local_sunset = ephem.localtime(obs.next_setting(sun))
@@ -86,19 +102,25 @@ def get_sun(lat=0, lon=0):
else:
sun_table['rise_time'] = local_sunrise.strftime('%a %d %I:%M%p')
sun_table['set_time'] = local_sunset.strftime('%a %d %I:%M%p')
# if sunset is before sunrise, then it's tomorrow
# if sunset is before sunrise, then data will be for tomorrow format sunset first and sunrise second
if local_sunset < local_sunrise:
local_sunset = ephem.localtime(obs.next_setting(sun)) + timedelta(1)
if zuluTime:
sun_table['set_time'] = local_sunset.strftime('%a %d %H:%M')
else:
sun_table['set_time'] = local_sunset.strftime('%a %d %I:%M%p')
sun_data = "SunRise: " + sun_table['rise_time'] + "\nSet: " + sun_table['set_time']
sun_data = "SunSet: " + sun_table['set_time'] + "\nRise: " + sun_table['rise_time']
else:
sun_data = "SunRise: " + sun_table['rise_time'] + "\nSet: " + sun_table['set_time']
sun_data += "\nDaylight: " + str((local_sunset - local_sunrise).seconds // 3600) + "h " + str(((local_sunset - local_sunrise).seconds // 60) % 60) + "m"
if sun_table['altitude'] > 0:
sun_data += "\nRemaining: " + str((local_sunset - datetime.now()).seconds // 3600) + "h " + str(((local_sunset - datetime.now()).seconds // 60) % 60) + "m"
sun_data += "\nAzimuth: " + str('{0:.2f}'.format(sun_table['azimuth'] * 180 / ephem.pi)) + "°"
if sun_table['altitude'] > 0:
sun_data += "\nAltitude: " + str('{0:.2f}'.format(sun_table['altitude'] * 180 / ephem.pi)) + "°"
return sun_data
def get_moon(lat=0, lon=0):
# get moon phase and rise/set times using callers location or default
# the phase calculation mght not be accurate (followup later)
obs = ephem.Observer()
moon = ephem.Moon()
if lat != 0 and lon != 0:
@@ -108,10 +130,28 @@ def get_moon(lat=0, lon=0):
obs.lat = str(latitudeValue)
obs.lon = str(longitudeValue)
obs.date = datetime.now()
obs.date = datetime.now(timezone.utc)
moon.compute(obs)
moon_table = {}
moon_phase = ['NewMoon', 'Waxing Crescent', 'First Quarter', 'Waxing Gibbous', 'FullMoon', 'Waning Gibbous', 'Last Quarter', 'Waning Crescent'][round(moon.phase / (2 * ephem.pi) * 8) % 8]
illum = moon.phase # 0 = new, 50 = first/last quarter, 100 = full
if illum < 1.0:
moon_phase = 'New Moon🌑'
elif illum < 49:
moon_phase = 'Waxing Crescent 🌒'
elif 49 <= illum < 51:
moon_phase = 'First Quarter 🌓'
elif illum < 99:
moon_phase = 'Waxing Gibbous 🌔'
elif illum >= 99:
moon_phase = 'Full Moon🌕'
elif illum > 51:
moon_phase = 'Waning Gibbous 🌖'
elif 51 >= illum > 49:
moon_phase = 'Last Quarter 🌗'
else:
moon_phase = 'Waning Crescent 🌘'
moon_table['phase'] = moon_phase
moon_table['illumination'] = moon.phase
moon_table['azimuth'] = moon.az
@@ -135,9 +175,14 @@ def get_moon(lat=0, lon=0):
moon_table['next_full_moon'] = local_next_full_moon.strftime('%a %b %d %I:%M%p')
moon_table['next_new_moon'] = local_next_new_moon.strftime('%a %b %d %I:%M%p')
moon_data = "MoonRise:" + moon_table['rise_time'] + "\nSet:" + moon_table['set_time'] + \
"\nPhase:" + moon_table['phase'] + " @:" + str('{0:.2f}'.format(moon_table['illumination'])) + "%" \
+ "\nFullMoon:" + moon_table['next_full_moon'] + "\nNewMoon:" + moon_table['next_new_moon']
moon_data = "MoonRise: " + moon_table['rise_time'] + "\nSet: " + moon_table['set_time'] + \
"\nPhase: " + moon_table['phase'] + " @: " + str('{0:.2f}'.format(moon_table['illumination'])) + "%" \
+ "\nFullMoon: " + moon_table['next_full_moon'] + "\nNewMoon: " + moon_table['next_new_moon']
# if moon is in the sky, add azimuth and altitude
if moon_table['altitude'] > 0:
moon_data += "\nAz: " + str('{0:.2f}'.format(moon_table['azimuth'] * 180 / ephem.pi)) + "°" + \
"\nAlt: " + str('{0:.2f}'.format(moon_table['altitude'] * 180 / ephem.pi)) + "°"
return moon_data
@@ -169,7 +214,7 @@ def getNextSatellitePass(satellite, lat=0, lon=0):
pass_startAzCompass = pass_json['passes'][0]['startAzCompass']
pass_set_time = datetime.fromtimestamp(pass_time + pass_duration).strftime('%a %d %I:%M%p')
pass__endAzCompass = pass_json['passes'][0]['endAzCompass']
pass_data = f"{satname} @{pass_rise_time} Az:{pass_startAzCompass} for{getPrettyTime(pass_duration)}, MaxEl:{pass_maxEl}° Set@{pass_set_time} Az:{pass__endAzCompass}"
pass_data = f"{satname} @{pass_rise_time} Az: {pass_startAzCompass} for{getPrettyTime(pass_duration)}, MaxEl: {pass_maxEl}° Set @{pass_set_time} Az: {pass__endAzCompass}"
elif pass_json['info']['passescount'] == 0:
satname = pass_json['info']['satname']
pass_data = f"{satname} has no upcoming passes"
@@ -178,5 +223,33 @@ def getNextSatellitePass(satellite, lat=0, lon=0):
pass_data = ERROR_FETCHING_DATA
except Exception as e:
logger.warning(f"System: User supplied value {satellite} unknown or invalid")
pass_data = "Provide NORAD# example use:🛰satpass 25544,33591"
pass_data = "Provide NORAD# example use: 🛰satpass 25544,33591"
return pass_data
def measureHeight(lat=0, lon=0, shadow=0):
# measure height of a given location using sun angle and shadow length
if lat == 0 and lon == 0:
return NO_DATA_NOGPS
if shadow == 0:
return NO_ALERTS
obs = ephem.Observer()
obs.lat = str(lat)
obs.lon = str(lon)
obs.date = datetime.now(timezone.utc)
sun = ephem.Sun()
sun.compute(obs)
sun_altitude = sun.alt * 180 / ephem.pi
if sun_altitude <= 0:
return "Sun is below horizon, I dont belive your shadow measurement"
try:
if use_metric:
height = float(shadow) * math.tan(sun.alt)
return f"📏Object Height: {height:.2f} m (Shadow: {shadow} m, 📐Sun Alt: {sun_altitude:.2f}°)"
else:
# Assume shadow is in feet if imperial, otherwise convert from meters to feet
shadow_ft = float(shadow)
height_ft = shadow_ft * math.tan(sun.alt)
return f"📏Object Height: {height_ft:.2f} ft (Shadow: {shadow_ft} ft, 📐Sun Alt: {sun_altitude:.2f}°)"
except Exception as e:
logger.error(f"Space: Error calculating height: {e}")
return NO_ALERTS

280
modules/survey.py Normal file
View File

@@ -0,0 +1,280 @@
# Survey Module for meshbot 2025
# Provides a survey function to collect responses and put into a CSV file
# this module reads survey definitions from JSON files in the data/surveys directory
# Each survey is defined in a separate JSON file named <survey_name>_survey.json
# Example survey file: example_survey.json
# Example survey response file: example_responses.csv
# Each survey consists of multiple questions, which can be multiple choice, integer, or text
# Users can start a survey, answer questions, and end the survey
# Module acts like a game locking DM until the survey is complete or ended
import json
import os # For file operations
import csv
from datetime import datetime
from collections import Counter
from modules.log import logger
from modules.settings import surveyRecordLocation, surveyRecordID
allowedSurveys = [] # List of allowed survey names
trap_list_survey = ("survey",)
class SurveyModule:
def __init__(self):
self.base_dir = os.path.dirname(__file__)
self.survey_dir = os.path.join(self.base_dir, '..', 'data', 'surveys') # Directory for survey JSON files
self.response_dir = os.path.join(self.base_dir, '..', 'data', 'surveys') # Directory for survey response CSV files
self.surveys = {}
self.responses = {}
self.load_surveys()
def load_surveys(self):
"""Load all surveys from the surveys directory with _survey.json suffix."""
global allowedSurveys
allowedSurveys.clear()
try:
for filename in os.listdir(self.survey_dir):
if filename.endswith('_survey.json'):
survey_name = filename[:-12] # Remove '_survey.json'
allowedSurveys.append(survey_name)
path = os.path.join(self.survey_dir, filename)
try:
with open(path, encoding='utf-8') as f:
self.surveys[survey_name] = json.load(f)
except FileNotFoundError:
logger.error(f"File not found: {path}")
self.surveys[survey_name] = []
except json.JSONDecodeError:
logger.error(f"Error decoding JSON from file: {path}")
self.surveys[survey_name] = []
except Exception as e:
logger.error(f"Survey: Error loading surveys: {e}")
def start_survey(self, user_id, survey_name='example', location=None):
try:
"""Begin a new survey session for a user."""
if not survey_name:
survey_name = default_survey
if survey_name not in allowedSurveys:
return f"error: survey '{survey_name}' is not allowed."
self.responses[user_id] = {
'survey_name': survey_name,
'current_question': 0,
'answers': [],
'location': location if surveyRecordLocation and location is not None else 'N/A'
}
msg = f"'{survey_name}'📝survey\n"
msg += self.show_question(user_id)
msg += f"\nSend answer' or 'end'"
return msg
except Exception as e:
logger.error(f"Error starting survey for user {user_id}: {e}")
return "An error occurred while starting the survey. Please try again later."
def show_question(self, user_id):
"""Show the current question for the user, or end the survey."""
survey_name = self.responses[user_id]['survey_name']
current = self.responses[user_id]['current_question']
questions = self.surveys.get(survey_name, [])
if current >= len(questions):
return self.end_survey(user_id)
question = questions[current]
msg = f"{question['question']}\n"
if question.get('type', 'multiple_choice') == 'multiple_choice':
for i, option in enumerate(question['options']):
msg += f"{chr(65+i)}. {option}\n"
elif question['type'] == 'integer':
msg += "(Please enter a number)\n"
elif question['type'] == 'text':
msg += "(Please enter your response)\n"
msg = msg.rstrip('\n')
return msg
def save_responses(self, user_id):
"""Save user responses to a CSV file."""
survey_name = self.responses[user_id]['survey_name']
if survey_name not in self.surveys:
logger.warning(f"Survey '{survey_name}' not loaded. Responses not saved.")
return
filename = os.path.join(self.response_dir, f'{survey_name}_responses.csv')
try:
# Check if file exists and if it has a header
write_header = not os.path.isfile(filename) or os.path.getsize(filename) == 0
with open(filename, 'a', encoding='utf-8') as f:
# Write header if needed
if write_header:
header = ['timestamp', 'user_id', 'location'] + [f'Q{i+1}' for i in range(len(self.responses[user_id]['answers']))]
f.write(','.join(header) + '\n')
# Always write: timestamp, userID, position, answers...
timestamp = datetime.now().strftime('%d%m%Y%H%M%S')
user_id_str = str(user_id)
location = self.responses[user_id].get('location', "N/A")
answers = list(map(str, self.responses[user_id]['answers']))
row = [timestamp, user_id_str, str(location)] + answers
f.write(','.join(row) + '\n')
logger.info(f"Survey: Responses for user {user_id} saved for survey '{survey_name}' to {filename}.")
except Exception as e:
logger.error(f"Error saving responses to {filename}: {e}")
def format_survey_results(self, results):
if isinstance(results, dict) and "error" in results:
return results["error"]
if not results:
return "No results found."
msg = "📊Survey Results:\n"
for idx, q in enumerate(results):
msg += f"\nQ{idx+1}: {q['question']}\n"
if q['type'] == 'multiple_choice':
for opt, count in q['summary'].items():
msg += f" {opt}: {count}\n"
elif q['type'] == 'integer':
s = q['summary']
msg += f" Count: {s['count']}, Avg: {s['average']:.2f}, Min: {s['min']}, Max: {s['max']}\n"
elif q['type'] == 'text':
msg += f" Responses: {q['summary']['responses_count']}\n"
return msg
def get_survey_results(self, survey_name='example'):
if survey_name not in self.surveys:
return {"error": f"Survey '{survey_name}' not found."}
filename = os.path.join(self.response_dir, f'{survey_name}_responses.csv')
questions = self.surveys[survey_name]
results = []
try:
with open(filename, encoding='utf-8') as f:
reader = csv.reader(f)
lines = []
for row in reader:
if not row or len(row) < 4:
continue
# If location field is split due to comma, join columns 2 and 3
if row[2].startswith('[') and not row[2].endswith(']') and len(row) > 4:
location = row[2] + ',' + row[3]
answers = row[4:]
else:
location = row[2]
answers = row[3:]
lines.append(answers)
for q_idx, question in enumerate(questions):
qtype = question.get('type', 'multiple_choice')
answers = [row[q_idx] for row in lines if len(row) > q_idx]
summary = {}
if qtype == 'multiple_choice':
counts = Counter(answers)
summary = {chr(65+i): counts.get(chr(65+i), 0) for i in range(len(question.get('options', [])))}
elif qtype == 'integer':
ints = [int(a) for a in answers if a.isdigit()]
summary = {
"count": len(ints),
"average": sum(ints)/len(ints) if ints else 0,
"min": min(ints) if ints else None,
"max": max(ints) if ints else None
}
elif qtype == 'text':
summary = {"responses_count": len([a for a in answers if a.strip()])}
results.append({
"question": question['question'],
"type": qtype,
"summary": summary
})
return results
except FileNotFoundError:
return {"error": f"No responses recorded yet for '{survey_name}'."}
except Exception as e:
logger.error(f"Error summarizing survey results: {e}")
return NO_ALERTS
def answer(self, user_id, answer, location=None):
try:
"""Record an answer and return the next question or end message."""
if user_id not in self.responses:
return self.start_survey(user_id, location=location)
question_index = self.responses[user_id]['current_question']
survey_name = self.responses[user_id]['survey_name']
questions = self.surveys.get(survey_name, [])
if question_index < 0 or question_index >= len(questions):
return "No current question to answer."
question = questions[question_index]
qtype = question.get('type', 'multiple_choice')
if qtype == 'multiple_choice':
answer_char = answer.strip().upper()[:1]
if len(answer_char) != 1 or not answer_char.isalpha():
return "Please answer with a letter (A, B, C, ...)."
option_index = ord(answer_char) - 65
if 0 <= option_index < len(question['options']):
# Valid answer record letter, not index
self.responses[user_id]['answers'].append(answer_char)
self.responses[user_id]['current_question'] += 1
return f"Recorded..\n" + self.show_question(user_id)
else:
print(f"Invalid option index {option_index} for question with {len(question['options'])} options. user entered '{answer}'")
return "Invalid answer option. Please try again."
elif qtype == 'integer':
try:
int_answer = int(answer)
self.responses[user_id]['answers'].append(str(int_answer))
self.responses[user_id]['current_question'] += 1
return f"Recorded..\n" + self.show_question(user_id)
except ValueError:
return "Please enter a valid integer."
elif qtype == 'text':
self.responses[user_id]['answers'].append(answer.strip())
self.responses[user_id]['current_question'] += 1
return f"Recorded..\n" + self.show_question(user_id)
else:
return f"error: unknown question type '{qtype}' and cannot record answer '{answer}'"
except Exception as e:
logger.error(f"Error recording answer for user {user_id}: {e}")
return "An error occurred while recording your answer. Please try again."
def end_survey(self, user_id):
"""End the survey for the user and save responses."""
if user_id not in self.responses:
return "No active survey session to end."
self.save_responses(user_id)
self.responses.pop(user_id, None)
return "✅ Survey complete. Thank you for your responses!"
def quiz_report(self, survey_name='example'):
"""
Generate a quick poll report: counts of each answer per question.
Returns a string summary.
"""
filename = os.path.join(self.response_dir, f'{survey_name}_responses.csv')
questions = self.surveys.get(survey_name, [])
if not questions:
logger.warning(f"No survey found for '{survey_name}'.")
return f"No survey found for '{survey_name}'."
all_answers = []
try:
with open(filename, encoding='utf-8') as f:
for line in f:
parts = line.strip().split(',')
if surveyRecordID:
answers = [int(x) for x in parts[1:] if x.strip().isdigit()]
else:
answers = [int(x) for x in parts if x.strip().isdigit()]
all_answers.append(answers)
except FileNotFoundError:
logger.info(f"No responses recorded yet for '{survey_name}'.")
return "No responses recorded yet."
report = f"📊 Poll Report for '{survey_name}':\n"
for q_idx, question in enumerate(questions):
counts = Counter(ans[q_idx] for ans in all_answers if len(ans) > q_idx)
report += f"\nQ{q_idx+1}: {question['question']}\n"
for opt_idx, option in enumerate(question.get('options', [])):
count = counts.get(opt_idx, 0)
report += f" {chr(65+opt_idx)}. {option}: {count}\n"
return report
# Initialize the survey module
survey_module = SurveyModule()

File diff suppressed because it is too large Load Diff

430
modules/test_bot.py Normal file
View File

@@ -0,0 +1,430 @@
# test_bot.py
# Unit tests for various modules in the meshing-around project
import os
import sys
# Add the parent directory to sys.path to allow module imports
parent_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_path)
import unittest
import importlib
import pkgutil
import warnings
from modules.log import logger
from modules.settings import latitudeValue, longitudeValue
# Suppress ResourceWarning warnings for asyncio unclosed event here
warnings.filterwarnings("ignore", category=ResourceWarning)
modules_path = os.path.join(parent_path, 'modules')
# Limits API calls during testing
CHECKALL = False
# Check for a file named .checkall in the parent directory
checkall_path = os.path.join(parent_path, '.checkall')
if os.path.isfile(checkall_path):
CHECKALL = True
# List of module names to exclude
exclude = ['test_bot','udp', 'system', 'log', 'gpio', 'web',]
available_modules = [
m.name for m in pkgutil.iter_modules([modules_path])
if m.name not in exclude]
try:
print("\nImporting Core Modules:")
from modules.log import logger, getPrettyTime
print(" ✔ Imported 'log'")
# Set location default
lat = latitudeValue
lon = longitudeValue
print(f" ✔ Location set to Latitude: {lat}, Longitude: {lon}")
from modules.system import *
print(" ✔ Imported 'system'")
print("\nImporting non-excluded modules:")
for module_name in [m.name for m in pkgutil.iter_modules([modules_path])]:
if module_name not in exclude:
importlib.import_module(module_name)
print(f" ✔ Imported '{module_name}'")
except Exception as e:
print(f"\nError importing modules: {e}")
print("Run this program from the main program directory: python3 script/test_bot.py")
exit(1)
class TestBot(unittest.TestCase):
def test_example(self):
# Example test case
self.assertEqual(1 + 1, 2)
def test_load_bbsdb(self):
from bbstools import load_bbsdb
test_load = load_bbsdb()
self.assertTrue(test_load)
def test_bbs_list_messages(self):
from bbstools import bbs_list_messages
messages = bbs_list_messages()
print("list_messages() returned:", messages)
self.assertIsInstance(messages, str)
def test_initialize_checklist_database(self):
from checklist import initialize_checklist_database, process_checklist_command
result = initialize_checklist_database()
result1 = process_checklist_command(0, 'checklist', name="none", location="none")
self.assertTrue(result)
self.assertIsInstance(result1, str)
def test_init_news_sources(self):
from filemon import initNewsSources
result = initNewsSources()
self.assertTrue(result)
def test_get_nina_alerts(self):
from globalalert import get_nina_alerts
alerts = get_nina_alerts()
self.assertIsInstance(alerts, str)
def test_llmTool_get_google(self):
from llm import llmTool_get_google
result = llmTool_get_google("What is 2+2?", 1)
self.assertIsInstance(result, list)
def test_send_ollama_query(self):
from llm import send_ollama_query
response = send_ollama_query("Hello, Ollama!")
self.assertIsInstance(response, str)
def test_extract_search_terms(self):
from llm import extract_search_terms
# Test with capitalized terms
terms = extract_search_terms("What is Python programming?")
self.assertIsInstance(terms, list)
self.assertTrue(len(terms) > 0)
# Test with multiple capitalized words
terms2 = extract_search_terms("Tell me about Albert Einstein and Marie Curie")
self.assertIsInstance(terms2, list)
self.assertTrue(len(terms2) > 0)
def test_get_wiki_context(self):
from llm import get_wiki_context
# Test with a well-known topic
context = get_wiki_context("Python programming language")
self.assertIsInstance(context, str)
# Context might be empty if wiki is disabled or fails, that's ok
def test_get_moon_phase(self):
from space import get_moon
phase = get_moon(lat, lon)
self.assertIsInstance(phase, str)
def test_get_sun_times(self):
from space import get_sun
sun_times = get_sun(lat, lon)
self.assertIsInstance(sun_times, str)
def test_hf_band_conditions(self):
from space import hf_band_conditions
conditions = hf_band_conditions()
self.assertIsInstance(conditions, str)
def test_get_wikipedia_summary(self):
from wiki import get_wikipedia_summary
summary = get_wikipedia_summary("Python", location=(lat, lon))
self.assertIsInstance(summary, str)
def test_get_kiwix_summary(self):
from wiki import get_kiwix_summary
summary = get_kiwix_summary("Python")
self.assertIsInstance(summary, str)
def get_openskynetwork(self):
from locationdata import get_openskynetwork
flights = get_openskynetwork(lat, lon)
self.assertIsInstance(flights, str)
def test_initalize_qrz_database(self):
from qrz import initalize_qrz_database
result = initalize_qrz_database()
self.assertTrue(result)
def test_get_hamlib(self):
from radio import get_hamlib
frequency = get_hamlib('f')
self.assertIsInstance(frequency, str)
def test_get_rss_feed(self):
from rss import get_rss_feed
result = get_rss_feed('')
self.assertIsInstance(result, str)
##### GAMES Tests #####
def test_jokes(self):
from modules.games.joke import tell_joke
haha = tell_joke(nodeID=0, test=True)
print("Joke response:", haha)
self.assertIsInstance(haha, str)
def test_tictactoe_initial_and_move(self):
from games.tictactoe import tictactoe
user_id = "testuser"
# Start a new game (no move yet)
initial = tictactoe.play(user_id, "")
print("Initial response:", initial)
# Make a move, e.g., '1'
second = tictactoe.play(user_id, "1")
print("After move '1':", second)
self.assertIsInstance(initial, str)
self.assertIsInstance(second, str)
def test_playVideoPoker(self):
from games.videopoker import playVideoPoker
user_id = "testuser"
# Start a new game/session
initial = playVideoPoker(user_id, 'deal')
print("Initial response:", initial)
# Place a 5-coin bet
after_bet = playVideoPoker(user_id, '5')
print("After placing 5-coin bet:", after_bet)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_bet, str)
def test_play_blackjack(self):
from games.blackjack import playBlackJack
user_id = "testuser"
# Start a new game/session
initial = playBlackJack(user_id, 'deal')
print("Initial response:", initial)
# Place a 5-chip bet
after_bet = playBlackJack(user_id, '5')
print("After placing 5-chip bet:", after_bet)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_bet, str)
def test_hangman_initial_and_guess(self):
from games.hangman import hangman
user_id = "testuser"
# Start a new game (no guess yet)
initial = hangman.play(user_id, "")
print("Initial response:", initial)
# Guess a letter, e.g., 'e'
second = hangman.play(user_id, "e")
print("After guessing 'e':", second)
self.assertIsInstance(initial, str)
self.assertIsInstance(second, str)
def test_play_lemonade_stand(self):
from games.lemonade import playLemonstand, lemonadeTracker
user_id = "testuser"
# Ensure user is in tracker
if not any(u['nodeID'] == user_id for u in lemonadeTracker):
lemonadeTracker.append({'nodeID': user_id, 'cups': 0, 'lemons': 0, 'sugar': 0, 'cash': 30.0, 'start': 30.0, 'cmd': 'new', 'last_played': 0})
# Start a new game
initial = playLemonstand(user_id, "", newgame=True)
print("Initial response:", initial)
# Buy 1 box of cups
after_cups = playLemonstand(user_id, "1")
print("After buying 1 box of cups:", after_cups)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_cups, str)
def test_play_golfsim_one_hole(self):
from games.golfsim import playGolf
user_id = "testuser"
# Start a new game/hole
initial = playGolf(user_id, "", last_cmd="new")
print("Initial hole info:", initial)
# Take first shot with driver
after_shot = playGolf(user_id, "driver")
print("After hitting driver:", after_shot)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_shot, str)
def test_play_dopewar_choose_city_and_list(self):
from games.dopewar import playDopeWars
user_id = 1234567899 # Use a unique test user ID
# Start a new game, get city selection prompt
initial = playDopeWars(user_id, "")
print("Initial city selection:", initial)
# Choose city 1
after_city = playDopeWars(user_id, "1")
print("After choosing city 1 (main game list):", after_city)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_city, str)
def test_play_mastermind_one_guess(self):
from games.mmind import start_mMind
user_id = 1234567899 # Use a unique test user ID
# Start a new game (should prompt for difficulty/colors)
initial = start_mMind(user_id, "n")
print("Initial response (difficulty/colors):", initial)
# Make a guess (e.g., "RGBY" - valid for normal)
after_guess = start_mMind(user_id, "RGBY")
print("After guessing RGBY:", after_guess)
self.assertIsInstance(initial, str)
self.assertIsInstance(after_guess, str)
def test_quiz_game_answer_one_and_end(self):
from games.quiz import quizGamePlayer
quizmaster_id = "admin" # Use a valid quizmaster ID from bbs_admin_list
user_id = "testuser"
# Start the quiz as quizmaster
start_msg = quizGamePlayer.start_game(quizmaster_id)
print("Quiz start:", start_msg)
# User joins the quiz
join_msg = quizGamePlayer.join(user_id)
print("User joined:", join_msg)
# Get the first question (should be included in join_msg, but call explicitly for clarity)
question_msg = quizGamePlayer.next_question(user_id)
print("First question:", question_msg)
# Simulate answering with 'A' (adjust if your first question expects a different answer)
answer_msg = quizGamePlayer.answer(user_id, "A")
print("Answer response:", answer_msg)
# End the quiz as quizmaster
end_msg = quizGamePlayer.stop_game(quizmaster_id)
print("Quiz end:", end_msg)
self.assertIsInstance(start_msg, str)
self.assertIsInstance(join_msg, str)
self.assertIsInstance(question_msg, str)
self.assertIsInstance(answer_msg, str)
self.assertIsInstance(end_msg, str)
def test_survey_answer_one_and_end(self):
from survey import survey_module
user_id = "testuser"
survey_name = "example" # Make sure this survey exists in your data/surveys directory
# Start the survey
start_msg = survey_module.start_survey(user_id, survey_name)
print("Survey start:", start_msg)
# Answer the first question with 'A' (adjust if your survey expects a different type)
answer_msg = survey_module.answer(user_id, "A")
print("Answer response:", answer_msg)
# End the survey
end_msg = survey_module.end_survey(user_id)
print("Survey end:", end_msg)
self.assertIsInstance(start_msg, str)
self.assertIsInstance(answer_msg, str)
self.assertIsInstance(end_msg, str)
def test_hamtest_answer_one(self):
from games.hamtest import hamtest
user_id = "testuser"
# Start a new ham test game (default level: technician)
initial = hamtest.newGame(user_id)
print("Initial question:", initial)
# Answer the first question with 'A'
answer_msg = hamtest.answer(user_id, "A")
print("Answer response:", answer_msg)
self.assertIsInstance(initial, str)
self.assertIsInstance(answer_msg, str)
##### API Tests - Extended tests run only if CHECKALL is True #####
if CHECKALL:
logger.info("Running extended API tests as CHECKALL is enabled.")
def test_handledxcluster(self):
from modules.dxspot import handledxcluster
test_message = "DX band=20m mode=SSB of=K7MHI"
response = handledxcluster(test_message, nodeID=0, deviceID='testdevice')
print("DX Spotter response:", response)
self.assertIsInstance(response, str)
def test_getRepeaterBook(self):
from locationdata import getRepeaterBook
repeaters = getRepeaterBook(lat, lon)
self.assertIsInstance(repeaters, str)
def test_getArtSciRepeaters(self):
from locationdata import getArtSciRepeaters
repeaters = getArtSciRepeaters(lat, lon)
self.assertIsInstance(repeaters, str)
def test_get_NOAAtides(self):
from locationdata import get_NOAAtide
tides = get_NOAAtide(lat, lon)
self.assertIsInstance(tides, str)
def test_get_NOAAweather(self):
from locationdata import get_NOAAweather
weather = get_NOAAweather(lat, lon)
self.assertIsInstance(weather, str)
def test_where_am_i(self):
from locationdata import where_am_i
location = where_am_i(lat, lon)
self.assertIsInstance(location, str)
def test_getWeatherAlertsNOAA(self):
from locationdata import getWeatherAlertsNOAA
alerts = getWeatherAlertsNOAA(lat, lon)
if isinstance(alerts, tuple):
self.assertIsInstance(alerts[0], str)
else:
self.assertIsInstance(alerts, str)
def test_getActiveWeatherAlertsDetailNOAA(self):
from locationdata import getActiveWeatherAlertsDetailNOAA
alerts_detail = getActiveWeatherAlertsDetailNOAA(lat, lon)
self.assertIsInstance(alerts_detail, str)
def test_getIpawsAlerts(self):
from locationdata import getIpawsAlert
alerts = getIpawsAlert(lat, lon)
self.assertIsInstance(alerts, str)
def test_get_flood_noaa(self):
from locationdata import get_flood_noaa
flood_info = get_flood_noaa(lat, lon, 12484500) # Example gauge UID
self.assertIsInstance(flood_info, str)
def test_get_volcano_usgs(self):
from locationdata import get_volcano_usgs
volcano_info = get_volcano_usgs(lat, lon)
self.assertIsInstance(volcano_info, str)
def test_get_nws_marine_alerts(self):
from locationdata import get_nws_marine
marine_alerts = get_nws_marine('https://tgftp.nws.noaa.gov/data/forecasts/marine/coastal/pz/pzz135.txt',1) # Example zone
self.assertIsInstance(marine_alerts, str)
def test_checkUSGSEarthQuakes(self):
from locationdata import checkUSGSEarthQuake
earthquakes = checkUSGSEarthQuake(lat, lon)
self.assertIsInstance(earthquakes, str)
def test_getNextSatellitePass(self):
from space import getNextSatellitePass
pass_info = getNextSatellitePass('25544', lat, lon)
self.assertIsInstance(pass_info, str)
def test_get_wx_meteo(self):
from wx_meteo import get_wx_meteo
weather_report = get_wx_meteo(lat, lon)
self.assertIsInstance(weather_report, str)
def test_get_flood_openmeteo(self):
from wx_meteo import get_flood_openmeteo
flood_report = get_flood_openmeteo(lat, lon)
self.assertIsInstance(flood_report, str)
if __name__ == '__main__':
if not CHECKALL:
print("\nNote: Extended API tests are skipped. To enable them, create a file named '.checkall' in the parent directory.\n")
unittest.main()

126
modules/udp.py Normal file
View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# UDP Interface Listener
# credit to pdxlocations for all of this core work https://github.com/pdxlocations/
# depends on: pip install meshtastic protobuf zeroconf pubsub
# 2025 Kelly Keeton K7MHI
from pubsub import pub
from meshtastic.protobuf import mesh_pb2, portnums_pb2
from mudp import UDPPacketStream, node, conn, send_text_message, send_nodeinfo, send_device_telemetry, send_position, send_environment_metrics, send_power_metrics, send_waypoint, send_data
from mudp.encryption import generate_hash
import time
from zeroconf import Zeroconf, ServiceBrowser
import socket
MCAST_GRP, MCAST_PORT, CHANNEL_ID, KEY = "224.0.0.69", 4403, "LongFast", "1PG7OiApB1nwvP+rz05pAQ=="
PUBLIC_CHANNEL_IDS = ["LongFast", "ShortSlow", "MediumFast", "MediumSlow", "ShortFast", "ShortTurbo"]
mudpEnabled, mudpInterface = True, None
messages = []
class ZeroconfListner:
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
if info:
txt = info.properties
ip = None
if info.addresses:
ip = socket.inet_ntoa(info.addresses[0])
print(f"Found Meshtastic node: id={txt.get(b'id', b'').decode()} shortname={txt.get(b'shortname', b'').decode()} longname={txt.get(b'longname', b'').decode()} ip={ip}")
def update_service(self, zeroconf, type, name):
# This method is required by zeroconf, but you can leave it empty if you don't need updates.
pass
def initalize_mudp():
global mudpInterface
if mudpEnabled and mudpInterface is None:
mudpInterface = UDPPacketStream(MCAST_GRP, MCAST_PORT, key=KEY)
print(f"MUDP Interface initialized with multicast group", MCAST_GRP, "port", MCAST_PORT)
node.node_id, node.long_name, node.short_name = "!deadbeef", "UDP Test", "UDP"
node.channel, node.key = "LongFast", KEY
conn.setup_multicast(MCAST_GRP, MCAST_PORT)
def on_recieve(packet: mesh_pb2.MeshPacket, addr=None):
print(f"\n[RECV] Packet received from {addr}")
print("from:", getattr(packet, "from", None))
print("to:", packet.to)
# Check against all public channels
matched_channel = None
for channel_name in PUBLIC_CHANNEL_IDS:
channel_hash = generate_hash(channel_name, KEY)
if packet.channel == channel_hash:
matched_channel = channel_name
break
if matched_channel:
channel_status = f"Match ({matched_channel})"
else:
channel_status = f"Hash: {packet.channel}"
print("channel:", channel_status)
if packet.HasField("decoded"):
port_name = portnums_pb2.PortNum.Name(packet.decoded.portnum) if packet.decoded.portnum else "N/A"
try:
payload_decoded = True
packet_payload = packet.decoded.payload.decode("utf-8", "ignore")
except Exception:
print(" payload (raw bytes):", packet.decoded.payload)
else:
print(f"encrypted: { {packet.encrypted} }")
print("id:", packet.id or None)
print("rx_time:", packet.rx_time or None)
print("rx_snr:", packet.rx_snr or None)
print("hop_limit:", packet.hop_limit or None)
priority_name = mesh_pb2.MeshPacket.Priority.Name(packet.priority) if packet.priority else "N/A"
print("priority:", priority_name or None)
print("rx_rssi:", packet.rx_rssi or None)
print("hop_start:", packet.hop_start or None)
print("next_hop:", packet.next_hop or None)
print("relay_node:", packet.relay_node or None)
print(f"decoded {{portnum: {port_name}, payload: {packet_payload if payload_decoded else 'N/A'}, bitfield: {packet.decoded.bitfield or None}}}" if packet.HasField("decoded") else "No decoded field")
pub.subscribe(on_recieve, "mesh.rx.packet")
# pub.subscribe(on_text_message, "mesh.rx.port.1")
# pub.subscribe(on_nodeinfo, "mesh.rx.port.4") # NODEINFO_APP
zeroconf = Zeroconf()
listener = ZeroconfListner()
browser = ServiceBrowser(zeroconf, "_meshtastic._tcp.local.", listener)
def main():
initalize_mudp()
mudpInterface.start()
try:
while True: time.sleep(0.05)
except KeyboardInterrupt: pass
finally: mudpInterface.stop()
if __name__ == "__main__":
main()
# Meshtastic Port Numbers Reference:
# | Port Number | Name | Purpose |
# |-------------|------------------------|--------------------------------|
# | 1 | TEXT_MESSAGE_APP | Text messages |
# | 2 | POSITION_APP | Position updates (GPS) |
# | 3 | ROUTING_APP | Routing info |
# | 4 | NODEINFO_APP | Node info (name, id, etc) |
# | 5 | TELEMETRY_APP | Telemetry (battery, sensors) |
# | 6 | SERIAL_APP | Serial data |
# | 7 | ENVIRONMENTAL_APP | Environmental sensors |
# | 8 | REMOTE_HARDWARE_APP | Remote hardware control |
# | 9 | STORE_FORWARD_APP | Store and forward |
# | 10 | RANGE_TEST_APP | Range test |
# | 11 | ADMIN_APP | Admin/config |
# | 12 | WAYPOINT_APP | Waypoints |
# | 13 | CHANNEL_NODEINFO_APP | Channel node info |
# | 256 | PRIVATE_APP | Private app (custom use) |
# See: https://github.com/meshtastic/protobufs/blob/main/meshtastic/protobuf/portnums.proto

View File

@@ -40,8 +40,8 @@ class QuietHandler(http.server.SimpleHTTPRequestHandler):
# Change the current working directory to webRoot
os.chdir(webRoot)
# boot up simple HTTP server
httpd = http.server.HTTPServer(('127.0.0.1', PORT), QuietHandler)
# Create the HTTP server instance with the desired IP address
httpd = http.server.HTTPServer((server_ip, PORT), QuietHandler)
if SSL:
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
@@ -51,12 +51,9 @@ if SSL:
print("SSL certificate file not found. Please generate it using the command provided in the comments.")
exit(1)
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
# Create the HTTP server instance with the desired IP address
httpd = http.server.HTTPServer((server_ip, PORT), QuietHandler)
# Print out the URL using the IP address stored in server_ip
print(f"Serving reports at http://{server_ip}:{PORT} Press ^C to quit.\n\n")
print(f"Serving reports at https://{server_ip}:{PORT} Press ^C to quit.\n\n")
else:
print(f"Serving reports at http://{server_ip}:{PORT} Press ^C to quit.\n\n")
if not webServerLogs:
print("Server Logs are disabled")

135
modules/wiki.py Normal file
View File

@@ -0,0 +1,135 @@
# meshbot wiki module
from modules.log import logger
from modules.settings import (use_kiwix_server, kiwix_url, kiwix_library_name,
urlTimeoutSeconds, wiki_return_limit, ERROR_FETCHING_DATA, wikipedia_enabled)
#import wikipedia # pip install wikipedia
import requests
import bs4 as bs
from urllib.parse import quote
def tag_visible(element):
"""Filter visible text from HTML elements for Kiwix"""
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, bs.element.Comment):
return False
return True
def text_from_html(body):
"""Extract main article text from HTML content"""
soup = bs.BeautifulSoup(body, 'html.parser')
# Try to find the main content div (works for both Kiwix and Wikipedia HTML)
main = soup.find('div', class_='mw-parser-output')
if not main:
# Fallback: just use the body if main content div not found
main = soup.body
if not main:
return ""
texts = main.find_all(string=True)
visible_texts = filter(tag_visible, texts)
return " ".join(t.strip() for t in visible_texts if t.strip())
def get_kiwix_summary(search_term, truncate=True):
"""Query local Kiwix server for Wikipedia article using only search results."""
if search_term is None or search_term.strip() == "":
return ERROR_FETCHING_DATA
try:
search_encoded = quote(search_term)
search_url = f"{kiwix_url}/search?content={kiwix_library_name}&pattern={search_encoded}"
response = requests.get(search_url, timeout=urlTimeoutSeconds)
if response.status_code == 200 and "No results were found" not in response.text:
soup = bs.BeautifulSoup(response.text, 'html.parser')
results = soup.select('div.results ul li')
logger.debug(f"Kiwix: Found {len(results)} results in search results for:{search_term}")
for li in results[:3]:
a = li.find('a', href=True)
if not a:
continue
article_url = f"{kiwix_url}{a['href']}"
article_response = requests.get(article_url, timeout=urlTimeoutSeconds)
if article_response.status_code == 200:
text = text_from_html(article_response.text)
# Remove navigation and search jump text
# text = text.split("Jump to navigation", 1)[-1]
# text = text.split("Jump to search", 1)[-1]
sentences = text.split('. ')
summary = '. '.join(sentences[:wiki_return_limit])
if summary and not summary.endswith('.'):
summary += '.'
if truncate:
return summary.strip()[:500]
else:
return summary.strip()
logger.debug(f"System: No Kiwix Results for:{search_term}")
if wikipedia_enabled:
logger.debug("Kiwix: Falling back to Wikipedia API.")
return get_wikipedia_summary(search_term, force=True)
return ERROR_FETCHING_DATA
except Exception as e:
logger.warning(f"System: Error with Kiwix for:{search_term} URL:{search_url} {e}")
return ERROR_FETCHING_DATA
def get_wikipedia_summary(search_term, location=None, force=False, truncate=True):
if use_kiwix_server and not force:
return get_kiwix_summary(search_term)
if not search_term or not search_term.strip():
return ERROR_FETCHING_DATA
api_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{requests.utils.quote(search_term)}"
headers = {
"User-Agent": "MeshBot/1.0 (https://github.com/kkeeton/meshing-around; contact: youremail@example.com)"
}
try:
response = requests.get(api_url, timeout=5, headers=headers)
if response.status_code == 404:
logger.warning(f"System: No Wikipedia Results for:{search_term}")
return ERROR_FETCHING_DATA
response.raise_for_status()
data = response.json()
logger.debug(f"Wikipedia API response for '{search_term}': {len(data)} keys")
if "extract" not in data or not data.get("extract"):
#logger.debug(f"System: Wikipedia API returned no extract for:{search_term} (data: {data})")
return ERROR_FETCHING_DATA
if data.get("type") == "disambiguation" or "may refer to:" in data.get("extract", ""):
#logger.warning(f"System: Disambiguation page for:{search_term} (data: {data})")
# Fetch and parse the HTML disambiguation page
html_url = f"https://en.wikipedia.org/wiki/{requests.utils.quote(search_term)}"
html_resp = requests.get(html_url, timeout=5, headers=headers)
if html_resp.status_code == 200:
soup = bs.BeautifulSoup(html_resp.text, 'html.parser')
items = soup.select('div.mw-parser-output ul li a[href^="/wiki/"]')
choices = []
for a in items:
title = a.get('title')
href = a.get('href')
# Filter out non-article links
if title and href and ':' not in href:
choices.append(f"{title} (https://en.wikipedia.org{href})")
if len(choices) >= 5:
break
if choices:
return f"'{search_term}' is ambiguous. Did you mean:\n- " + "\n- ".join(choices)
return f"'{search_term}' is ambiguous. Please be more specific. See: {html_url}"
summary = data.get("extract")
if not summary or not isinstance(summary, str) or not summary.strip():
#logger.debug(f"System: No summary found for:{search_term} (data: {data})")
return ERROR_FETCHING_DATA
sentences = [s for s in summary.split('. ') if s.strip()]
if not sentences:
return ERROR_FETCHING_DATA
summary = '. '.join(sentences[:wiki_return_limit])
if summary and not summary.endswith('.'):
summary += '.'
if truncate:
# Truncate to 500 characters
return summary.strip()[:500]
else:
return summary.strip()
except Exception as e:
logger.warning(f"System: Wikipedia API error for:{search_term} {e}")
return ERROR_FETCHING_DATA

View File

@@ -3,7 +3,8 @@
import requests
import json
from modules.log import *
from modules.log import logger
from modules.settings import ERROR_FETCHING_DATA
def get_weather_data(api_url, params):
response = requests.get(api_url, params=params)

View File

@@ -10,8 +10,10 @@ except ImportError:
import asyncio
import time # for sleep, get some when you can :)
from datetime import datetime
import random
from modules.log import *
from modules.log import logger, CustomFormatter, msgLogger
import modules.settings as my_settings
from modules.system import *
# Global Variables
@@ -29,6 +31,7 @@ def auto_response(message, snr, rssi, hop, pkiStatus, message_from_id, channel_n
"cq": lambda: handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, channel_number),
"cqcq": lambda: handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, channel_number),
"cqcqcq": lambda: handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, channel_number),
"echo": lambda: handle_echo(message, message_from_id, deviceID, isDM, channel_number),
"lheard": lambda: handle_lheard(message, message_from_id, deviceID, isDM),
"motd": lambda: handle_motd(message, MOTD),
"ping": lambda: handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, channel_number),
@@ -49,9 +52,6 @@ def auto_response(message, snr, rssi, hop, pkiStatus, message_from_id, channel_n
logger.debug(f"System: Bot detected Commands:{cmds}")
# run the first command after sorting
bot_response = command_handler[cmds[0]['cmd']]()
# wait a responseDelay to avoid message collision from lora-ack
time.sleep(responseDelay)
return bot_response
@@ -71,30 +71,41 @@ def handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, chann
type = ''
if "ping" in message.lower():
msg = "🏓PONG\n"
msg = "🏓PONG"
type = "🏓PING"
elif "test" in message.lower() or "testing" in message.lower():
msg = random.choice(["🎙Testing 1,2,3\n", "🎙Testing\n",\
"🎙Testing, testing\n",\
"🎙Ah-wun, ah-two...\n", "🎙Is this thing on?\n",\
"🎙Roger that!\n",])
msg = random.choice(["🎙Testing 1,2,3", "🎙Testing",\
"🎙Testing, testing",\
"🎙Ah-wun, ah-two...", "🎙Is this thing on?",\
"🎙Roger that!",])
type = "🎙TEST"
elif "ack" in message.lower():
msg = random.choice(["✋ACK-ACK!\n", "✋Ack to you!\n"])
type = "✋ACK"
elif "cqcq" in message.lower() or "cq" in message.lower() or "cqcqcq" in message.lower():
if deviceID == 1:
myname = get_name_from_number(myNodeNum1, 'short', 1)
myname = get_name_from_number(deviceID, 'short', 1)
elif deviceID == 2:
myname = get_name_from_number(myNodeNum2, 'short', 2)
myname = get_name_from_number(deviceID, 'short', 2)
msg = f"QSP QSL OM DE {myname} K\n"
else:
msg = "🔊 Can you hear me now?"
if hop == "Direct":
msg = msg + f"SNR:{snr} RSSI:{rssi}"
# append SNR/RSSI or hop info
if hop.startswith("Gateway") or hop.startswith("MQTT"):
msg += " [GW]"
elif hop.startswith("Direct"):
msg += " [RF]"
else:
msg = msg + hop
#flood
msg += " [F]"
if (float(snr) != 0 or float(rssi) != 0) and "Hops" not in hop:
msg += f"\nSNR:{snr} RSSI:{rssi}"
elif "Hops" in hop:
msg += f"\n{hop}🐇 "
else:
msg += "\nflood route"
if "@" in message:
msg = msg + " @" + message.split("@")[1]
@@ -124,13 +135,13 @@ def handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, chann
pingCount = int(message.split(" ")[1])
if pingCount == 123 or pingCount == 1234:
pingCount = 1
elif not autoPingInChannel and not isDM:
elif not my_settings.autoPingInChannel and not isDM:
# no autoping in channels
pingCount = 1
if pingCount > 51:
pingCount = 50
except:
except ValueError:
pingCount = -1
if pingCount > 1:
@@ -141,19 +152,53 @@ def handle_ping(message_from_id, deviceID, message, hop, snr, rssi, isDM, chann
msg = f"🚦Initalizing {pingCount} auto-ping"
# if not a DM add the username to the beginning of msg
if not useDMForResponse and not isDM:
if not my_settings.useDMForResponse and not isDM:
msg = "@" + get_name_from_number(message_from_id, 'short', deviceID) + " " + msg
return msg
def handle_motd(message):
def handle_motd(message, message_from_id, isDM):
global MOTD
if "$" in message:
isAdmin = False
msg = MOTD
# check if the message_from_id is in the bbs_admin_list
if my_settings.bbs_admin_list != ['']:
for admin in my_settings.bbs_admin_list:
if str(message_from_id) == admin:
isAdmin = True
break
else:
isAdmin = True
# admin help via DM
if "?" in message and isDM and isAdmin:
msg = "Message of the day, set with 'motd $ HelloWorld!'"
elif "?" in message and isDM and not isAdmin:
# non-admin help via DM
msg = "Message of the day"
elif "$" in message and isAdmin:
motd = message.split("$")[1]
MOTD = motd.rstrip()
return "MOTD Set to: " + MOTD
logger.debug(f"System: {message_from_id} changed MOTD: {MOTD}")
msg = "MOTD changed to: " + MOTD
else:
return MOTD
msg = "MOTD: " + MOTD
return msg
def handle_echo(message, message_from_id, deviceID, isDM, channel_number):
if "?" in message.lower():
return "echo command returns your message back to you. Example:echo Hello World"
elif "echo " in message.lower():
parts = message.lower().split("echo ", 1)
if len(parts) > 1 and parts[1].strip() != "":
echo_msg = parts[1]
if channel_number != my_settings.echoChannel:
echo_msg = "@" + get_name_from_number(message_from_id, 'short', deviceID) + " " + echo_msg
return echo_msg
else:
return "Please provide a message to echo back to you. Example:echo Hello World"
else:
return "Please provide a message to echo back to you. Example:echo Hello World"
def sysinfo(message, message_from_id, deviceID):
if "?" in message:
@@ -169,14 +214,6 @@ def handle_lheard(message, nodeid, deviceID, isDM):
bot_response = "Last Heard\n"
bot_response += str(get_node_list(1))
# show last users of the bot with the cmdHistory list
history = handle_history(message, nodeid, deviceID, isDM, lheard=True)
if history:
bot_response += f'LastSeen\n{history}'
else:
# trim the last \n
bot_response = bot_response[:-1]
# bot_response += getNodeTelemetry(deviceID)
return bot_response
@@ -189,58 +226,79 @@ def onReceive(packet, interface):
rxType = type(interface).__name__
# Valies assinged to the packet
rxNode, message_from_id, snr, rssi, hop, hop_away, channel_number = 0, 0, 0, 0, 0, 0, 0
rxNode = message_from_id = snr = rssi = hop = hop_away = channel_number = hop_start = hop_count = hop_limit = 0
pkiStatus = (False, 'ABC')
replyIDset = False
rxNodeHostName = None
emojiSeen = False
simulator_flag = False
isDM = False
channel_name = "unknown"
session_passkey = None
playingGame = False
if DEBUGpacket:
# Debug print the interface object
for item in interface.__dict__.items(): intDebug = f"{item}\n"
for item in interface.__dict__.items():
intDebug = f"{item}\n"
logger.debug(f"System: Packet Received on {rxType} Interface\n {intDebug} \n END of interface \n")
# Debug print the packet for debugging
logger.debug(f"Packet Received\n {packet} \n END of packet \n")
# set the value for the incomming interface
if rxType == 'SerialInterface':
rxInterface = interface.__dict__.get('devPath', 'unknown')
if port1 in rxInterface: rxNode = 1
elif multiple_interface and port2 in rxInterface: rxNode = 2
elif multiple_interface and port3 in rxInterface: rxNode = 3
elif multiple_interface and port4 in rxInterface: rxNode = 4
elif multiple_interface and port5 in rxInterface: rxNode = 5
elif multiple_interface and port6 in rxInterface: rxNode = 6
elif multiple_interface and port7 in rxInterface: rxNode = 7
elif multiple_interface and port8 in rxInterface: rxNode = 8
elif multiple_interface and port9 in rxInterface: rxNode = 9
# determine the rxNode based on the interface type
if rxType == 'TCPInterface':
rxHost = interface.__dict__.get('hostname', 'unknown')
if hostname1 in rxHost and interface1_type == 'tcp': rxNode = 1
elif multiple_interface and hostname2 in rxHost and interface2_type == 'tcp': rxNode = 2
elif multiple_interface and hostname3 in rxHost and interface3_type == 'tcp': rxNode = 3
elif multiple_interface and hostname4 in rxHost and interface4_type == 'tcp': rxNode = 4
elif multiple_interface and hostname5 in rxHost and interface5_type == 'tcp': rxNode = 5
elif multiple_interface and hostname6 in rxHost and interface6_type == 'tcp': rxNode = 6
elif multiple_interface and hostname7 in rxHost and interface7_type == 'tcp': rxNode = 7
elif multiple_interface and hostname8 in rxHost and interface8_type == 'tcp': rxNode = 8
elif multiple_interface and hostname9 in rxHost and interface9_type == 'tcp': rxNode = 9
rxNodeHostName = interface.__dict__.get('ip', None)
rxNode = next(
(i for i in range(1, 10)
if multiple_interface and rxHost and
globals().get(f'hostname{i}', '').split(':', 1)[0] in rxHost and
globals().get(f'interface{i}_type', '') == 'tcp'),None)
if rxType == 'BLEInterface':
if interface1_type == 'ble': rxNode = 1
elif multiple_interface and interface2_type == 'ble': rxNode = 2
elif multiple_interface and interface3_type == 'ble': rxNode = 3
elif multiple_interface and interface4_type == 'ble': rxNode = 4
elif multiple_interface and interface5_type == 'ble': rxNode = 5
elif multiple_interface and interface6_type == 'ble': rxNode = 6
elif multiple_interface and interface7_type == 'ble': rxNode = 7
elif multiple_interface and interface8_type == 'ble': rxNode = 8
elif multiple_interface and interface9_type == 'ble': rxNode = 9
if rxType == 'SerialInterface':
rxInterface = interface.__dict__.get('devPath', 'unknown')
rxNode = next(
(i for i in range(1, 10)
if globals().get(f'port{i}', '') in rxInterface),None)
# check if the packet has a channel flag use it
if rxType == 'BLEInterface':
rxNode = next(
(i for i in range(1, 10)
if globals().get(f'interface{i}_type', '') == 'ble'),0)
if rxNode is None:
# default to interface 1 ## FIXME needs better like a default interface setting or hash lookup
if 'decoded' in packet and packet['decoded']['portnum'] in ['ADMIN_APP', 'SIMULATOR_APP']:
session_passkey = packet.get('decoded', {}).get('admin', {}).get('sessionPasskey', None)
rxNode = 1
# check if the packet has a channel flag use it ## FIXME needs to be channel hash lookup
if packet.get('channel'):
channel_number = packet.get('channel', 0)
channel_number = packet.get('channel')
# get channel name from channel number from connected devices
for device in channel_list:
if device["interface_id"] == rxNode:
device_channels = device['channels']
for chan_name, info in device_channels.items():
if info['number'] == channel_number:
channel_name = chan_name
break
# get channel hashes for the interface
device = next((d for d in channel_list if d["interface_id"] == rxNode), None)
if device:
# Find the channel name whose hash matches channel_number
for chan_name, info in device['channels'].items():
if info['hash'] == channel_number:
print(f"Matched channel hash {info['hash']} to channel name {chan_name}")
channel_name = chan_name
break
# check if the packet has a simulator flag
simulator_flag = packet.get('decoded', {}).get('simulator', False)
if isinstance(simulator_flag, dict):
# assume Software Simulator
simulator_flag = True
# set the message_from_id
message_from_id = packet['from']
@@ -254,10 +312,12 @@ def onReceive(packet, interface):
if 'decoded' in packet and packet['decoded']['portnum'] == 'TEXT_MESSAGE_APP':
message_bytes = packet['decoded']['payload']
message_string = message_bytes.decode('utf-8')
via_mqtt = packet['decoded'].get('viaMqtt', False)
transport_mechanism = packet['decoded'].get('transport_mechanism', 'unknown')
# check if the packet is from us
if message_from_id == myNodeNum1 or message_from_id == myNodeNum2:
logger.warning(f"System: Packet from self {message_from_id} loop or traffic replay deteted")
if message_from_id in [myNodeNum1, myNodeNum2, myNodeNum3, myNodeNum4, myNodeNum5, myNodeNum6, myNodeNum7, myNodeNum8, myNodeNum9]:
logger.warning(f"System: Packet from self {message_from_id} loop or traffic replay detected")
# get the signal strength and snr if available
if packet.get('rxSnr') or packet.get('rxRssi'):
@@ -266,51 +326,74 @@ def onReceive(packet, interface):
# check if the packet has a publicKey flag use it
if packet.get('publicKey'):
pkiStatus = (packet.get('pkiEncrypted', False), packet.get('publicKey', 'ABC'))
pkiStatus = packet.get('pkiEncrypted', False), packet.get('publicKey', 'ABC')
# check if the packet has replyId flag // currently unused in the code
if packet.get('replyId'):
replyIDset = packet.get('replyId', False)
# check if the packet has emoji flag set it // currently unused in the code
if packet.get('emoji'):
emojiSeen = packet.get('emoji', False)
# check if the packet has a hop count flag use it
if packet.get('hopsAway'):
hop_away = packet.get('hopsAway', 0)
else:
# if the packet does not have a hop count try other methods
if packet.get('hopLimit'):
hop_limit = packet.get('hopLimit', 0)
else:
hop_limit = 0
if packet.get('hopStart'):
hop_start = packet.get('hopStart', 0)
else:
hop_start = 0
if hop_start == hop_limit:
hop = "Direct"
hop_count = 0
elif hop_start == 0 and hop_limit > 0:
hop = "MQTT"
hop_count = 0
else:
# set hop to Direct if the message was sent directly otherwise set the hop count
if hop_away > 0:
hop_count = hop_away
else:
hop_count = hop_start - hop_limit
#print (f"calculated hop count: {hop_start} - {hop_limit} = {hop_count}")
if packet.get('hopStart'):
hop_start = packet.get('hopStart', 0)
hop = f"{hop_count} hops"
if packet.get('hopLimit'):
hop_limit = packet.get('hopLimit', 0)
# calculate hop count
hop = ""
if hop_limit > 0 and hop_start >= hop_limit:
hop_count = hop_away + (hop_start - hop_limit)
elif hop_limit > 0 and hop_start < hop_limit:
hop_count = hop_away + (hop_limit - hop_start)
else:
hop_count = hop_away
if hop == "" and hop_count > 0:
# set hop string from calculated hop count
hop = f"{hop_count} Hop" if hop_count == 1 else f"{hop_count} Hops"
if hop_start == hop_limit and "lora" in str(transport_mechanism).lower() and (snr != 0 or rssi != 0):
# 2.7+ firmware direct hop over LoRa
hop = "Direct"
if ((hop_start == 0 and hop_limit >= 0) or via_mqtt or ("mqtt" in str(transport_mechanism).lower())):
hop = "MQTT"
elif hop == "" and hop_count == 0 and (snr != 0 or rssi != 0):
# this came from a UDP but we had signal info so gateway is used
hop = "Gateway"
elif "unknown" in str(transport_mechanism).lower() and (snr == 0 and rssi == 0):
# we for sure detected this sourced from a UDP like host
hop = "Gateway"
if hop in ("MQTT", "Gateway") and hop_count > 0:
hop = f"{hop_count} Hops"
if my_settings.enableHopLogs:
logger.debug(f"System: Packet HopDebugger: hop_away:{hop_away} hop_limit:{hop_limit} hop_start:{hop_start} calculated_hop_count:{hop_count} final_hop_value:{hop} via_mqtt:{via_mqtt} transport_mechanism:{transport_mechanism} Hostname:{rxNodeHostName}")
# check with stringSafeChecker if the message is safe
if stringSafeCheck(message_string) is False:
logger.warning(f"System: Possibly Unsafe Message from {get_name_from_number(message_from_id, 'long', rxNode)}")
if help_message in message_string or welcome_message in message_string or "CMD?:" in message_string:
# ignore help and welcome messages
logger.warning(f"Got Own Welcome/Help header. From: {get_name_from_number(message_from_id, 'long', rxNode)}")
return
# If the packet is a DM (Direct Message) respond to it, otherwise validate its a message for us on the channel
if packet['to'] == myNodeNum1 or packet['to'] == myNodeNum2:
if packet['to'] in [myNodeNum1, myNodeNum2, myNodeNum3, myNodeNum4, myNodeNum5, myNodeNum6, myNodeNum7, myNodeNum8, myNodeNum9]:
# message is DM to us
isDM = True
# check if the message contains a trap word, DMs are always responded to
if (messageTrap(message_string) and not llm_enabled) or messageTrap(message_string.split()[0]):
# log the message to the message log
# log the message to stdout
logger.info(f"Device:{rxNode} Channel: {channel_number} " + CustomFormatter.green + f"Received DM: " + CustomFormatter.white + f"{message_string} " + CustomFormatter.purple +\
"From: " + CustomFormatter.white + f"{get_name_from_number(message_from_id, 'long', rxNode)}")
# respond with DM
@@ -318,10 +401,10 @@ def onReceive(packet, interface):
else:
logger.warning(f"Device:{rxNode} Ignoring DM: {message_string} From: {get_name_from_number(message_from_id, 'long', rxNode)}")
send_message(welcome_message, channel_number, message_from_id, rxNode)
time.sleep(responseDelay)
# log the message to the message log
msgLogger.info(f"Device:{rxNode} Channel:{channel_number} | {get_name_from_number(message_from_id, 'long', rxNode)} | " + message_string.replace('\n', '-nl-'))
if log_messages_to_file:
msgLogger.info(f"Device:{rxNode} Channel:{channel_number} | {get_name_from_number(message_from_id, 'long', rxNode)} | DM | " + message_string.replace('\n', '-nl-'))
else:
# message is on a channel
if messageTrap(message_string):
@@ -336,7 +419,7 @@ def onReceive(packet, interface):
send_message(auto_response(message_string, snr, rssi, hop, pkiStatus, message_from_id, channel_number, rxNode, isDM), channel_number, message_from_id, rxNode)
else:
# or respond to channel message on the channel itself
if channel_number == publicChannel and antiSpam:
if channel_number == my_settings.publicChannel and my_settings.antiSpam:
# warning user spamming default channel
logger.warning(f"System: AntiSpam protection, sending DM to: {get_name_from_number(message_from_id, 'long', rxNode)}")
@@ -349,7 +432,7 @@ def onReceive(packet, interface):
else:
# message is not for bot to respond to
# ignore the message but add it to the message history list
if zuluTime:
if my_settings.zuluTime:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
else:
timestamp = datetime.now().strftime("%Y-%m-%d %I:%M:%S%p")
@@ -367,86 +450,236 @@ def onReceive(packet, interface):
msgLogger.info(f"Device:{rxNode} Channel:{channel_number} | {get_name_from_number(message_from_id, 'long', rxNode)} | " + message_string.replace('\n', '-nl-'))
# repeat the message on the other device
if repeater_enabled and multiple_interface:
if my_settings.repeater_enabled and multiple_interface:
# wait a responseDelay to avoid message collision from lora-ack.
time.sleep(responseDelay)
time.sleep(my_settings.responseDelay)
rMsg = (f"{message_string} From:{get_name_from_number(message_from_id, 'short', rxNode)}")
# if channel found in the repeater list repeat the message
if str(channel_number) in repeater_channels:
if str(channel_number) in my_settings.repeater_channels:
for i in range(1, 10):
if globals().get(f'interface{i}_enabled', False) and i != rxNode:
logger.debug(f"Repeating message on Device{i} Channel:{channel_number}")
send_message(rMsg, channel_number, 0, i)
time.sleep(responseDelay)
time.sleep(my_settings.responseDelay)
else:
# Evaluate non TEXT_MESSAGE_APP packets
consumeMetadata(packet, rxNode)
consumeMetadata(packet, rxNode, channel_number)
except KeyError as e:
logger.critical(f"System: Error processing packet: {e} Device:{rxNode}")
logger.debug(f"System: Error Packet = {packet}")
async def start_rx():
print (CustomFormatter.bold_white + f"\nMeshtastic Autoresponder Bot CTL+C to exit\n" + CustomFormatter.reset)
# Start the receive subscriber using pubsub via meshtastic library
pub.subscribe(onReceive, 'meshtastic.receive')
pub.subscribe(onDisconnect, 'meshtastic.connection.lost')
for i in range(1, 10):
if globals().get(f'interface{i}_enabled', False):
myNodeNum = globals().get(f'myNodeNum{i}', 0)
logger.info(f"System: Autoresponder Started for Device{i} {get_name_from_number(myNodeNum, 'long', i)},"
f"{get_name_from_number(myNodeNum, 'short', i)}. NodeID: {myNodeNum}, {decimal_to_hex(myNodeNum)}")
if log_messages_to_file:
logger.debug("System: Logging Messages to disk")
if syslog_to_file:
logger.debug("System: Logging System Logs to disk")
if solar_conditions_enabled:
logger.debug("System: Celestial Telemetry Enabled")
if motd_enabled:
logger.debug(f"System: MOTD Enabled using {MOTD}")
if sentry_enabled:
logger.debug(f"System: Sentry Mode Enabled {sentry_radius}m radius reporting to channel:{secure_channel}")
if store_forward_enabled:
logger.debug(f"System: Store and Forward Enabled using limit: {storeFlimit}")
if useDMForResponse:
logger.debug(f"System: Respond by DM only")
if repeater_enabled and multiple_interface:
logger.debug(f"System: Repeater Enabled for Channels: {repeater_channels}")
if file_monitor_enabled:
logger.debug(f"System: File Monitor Enabled for {file_monitor_file_path}, broadcasting to channels: {file_monitor_broadcastCh}")
if read_news_enabled:
logger.debug(f"System: File Monitor News Reader Enabled for {news_file_path}")
if scheduler_enabled:
# Examples of using the scheduler, Times here are in 24hr format
# https://schedule.readthedocs.io/en/stable/
# Reminder Scheduler is enabled every Monday at noon send a log message
schedule.every().monday.at("12:00").do(lambda: logger.info("System: Scheduled Broadcast Reminder"))
logger.debug("System: Starting the broadcast scheduler")
await BroadcastScheduler()
logger.debug("System: RX Subscriber started")
# here we go loopty loo
while True:
await asyncio.sleep(0.5)
pass
def handle_boot(mesh=True):
try:
print (CustomFormatter.bold_white + f"\nMeshtastic Autoresponder Bot CTL+C to exit\n" + CustomFormatter.reset)
if mesh:
for i in range(1, 10):
if globals().get(f'interface{i}_enabled', False):
myNodeNum = globals().get(f'myNodeNum{i}', 0)
logger.info(f"System: Autoresponder Started for Device{i} {get_name_from_number(myNodeNum, 'long', i)},"
f"{get_name_from_number(myNodeNum, 'short', i)}. NodeID: {myNodeNum}, {decimal_to_hex(myNodeNum)}")
if llm_enabled:
logger.debug(f"System: Ollama LLM Enabled, loading model {my_settings.llmModel} please wait")
llmLoad = llm_query(" ")
if "trouble" not in llmLoad:
logger.debug(f"System: LLM Model {my_settings.llmModel} loaded")
if my_settings.bbs_enabled:
logger.debug(f"System: BBS Enabled, {bbsdb} has {len(bbs_messages)} messages. Direct Mail Messages waiting: {(len(bbs_dm) - 1)}")
if my_settings.bbs_link_enabled:
if len(bbs_link_whitelist) > 0:
logger.debug(f"System: BBS Link Enabled with {len(bbs_link_whitelist)} peers")
else:
logger.debug(f"System: BBS Link Enabled allowing all")
if my_settings.solar_conditions_enabled:
logger.debug("System: Celestial Telemetry Enabled")
if my_settings.location_enabled:
if my_settings.use_meteo_wxApi:
logger.debug("System: Location Telemetry Enabled using Open-Meteo API")
else:
logger.debug("System: Location Telemetry Enabled using NOAA API")
print("debug my_settings.scheduler_enabled:", my_settings.scheduler_enabled)
if my_settings.dad_jokes_enabled:
logger.debug("System: Dad Jokes Enabled!")
if my_settings.coastalEnabled:
logger.debug("System: Coastal Forecast and Tide Enabled!")
if games_enabled:
logger.debug("System: Games Enabled!")
if my_settings.wikipedia_enabled:
if my_settings.use_kiwix_server:
logger.debug(f"System: Wikipedia search Enabled using Kiwix server at {kiwix_url}")
else:
logger.debug("System: Wikipedia search Enabled")
if my_settings.rssEnable:
logger.debug(f"System: RSS Feed Reader Enabled for feeds: {rssFeedNames}")
if my_settings.radio_detection_enabled:
logger.debug(f"System: Radio Detection Enabled using rigctld at {my_settings.rigControlServerAddress} broadcasting to channels: {my_settings.sigWatchBroadcastCh} for {get_freq_common_name(get_hamlib('f'))}")
if my_settings.file_monitor_enabled:
logger.warning(f"System: File Monitor Enabled for {my_settings.file_monitor_file_path}, broadcasting to channels: {my_settings.file_monitor_broadcastCh}")
if my_settings.enable_runShellCmd:
logger.debug("System: Shell Command monitor enabled")
if my_settings.allowXcmd:
logger.warning("System: File Monitor shell XCMD Enabled")
if my_settings.read_news_enabled:
logger.debug(f"System: File Monitor News Reader Enabled for {my_settings.news_file_path}")
if my_settings.bee_enabled:
logger.debug("System: File Monitor Bee Monitor Enabled for bee.txt")
if my_settings.wxAlertBroadcastEnabled:
logger.debug(f"System: Weather Alert Broadcast Enabled on channels {my_settings.wxAlertBroadcastChannel}")
if my_settings.emergencyAlertBrodcastEnabled:
logger.debug(f"System: Emergency Alert Broadcast Enabled on channels {my_settings.emergencyAlertBroadcastCh} for FIPS codes {my_settings.myStateFIPSList}")
if my_settings.myStateFIPSList == ['']:
logger.warning("System: No FIPS codes set for iPAWS Alerts")
if my_settings.emergency_responder_enabled:
logger.debug(f"System: Emergency Responder Enabled on channels {my_settings.emergency_responder_alert_channel} for interface {my_settings.emergency_responder_alert_interface}")
if my_settings.volcanoAlertBroadcastEnabled:
logger.debug(f"System: Volcano Alert Broadcast Enabled on channels {my_settings.volcanoAlertBroadcastChannel}")
if my_settings.qrz_hello_enabled:
if my_settings.train_qrz:
logger.debug("System: QRZ Welcome/Hello Enabled with training mode")
else:
logger.debug("System: QRZ Welcome/Hello Enabled")
if my_settings.enableSMTP:
if my_settings.enableImap:
logger.debug("System: SMTP Email Alerting Enabled using IMAP")
else:
logger.warning("System: SMTP Email Alerting Enabled")
# Default Options
if my_settings.useDMForResponse:
logger.debug("System: Respond by DM only")
if my_settings.log_messages_to_file:
logger.debug("System: Logging Messages to disk")
if my_settings.syslog_to_file:
logger.debug("System: Logging System Logs to disk")
if my_settings.motd_enabled:
logger.debug(f"System: MOTD Enabled using {my_settings.MOTD} scheduler:{my_settings.schedulerMotd}")
if my_settings.sentry_enabled:
logger.debug(f"System: Sentry Mode Enabled {my_settings.sentry_radius}m radius reporting to channel:{my_settings.secure_channel} requestLOC:{reqLocationEnabled}")
if my_settings.sentryIgnoreList:
logger.debug(f"System: Sentry BlockList Enabled for nodes: {my_settings.sentryIgnoreList}")
if my_settings.sentryWatchList:
logger.debug(f"System: Sentry WatchList Enabled for nodes: {my_settings.sentryWatchList}")
if my_settings.highfly_enabled:
logger.debug(f"System: HighFly Enabled using {my_settings.highfly_altitude}m limit reporting to channel:{my_settings.highfly_channel}")
if my_settings.store_forward_enabled:
logger.debug(f"System: S&F(messages command) Enabled using limit: {storeFlimit} and reverse queue:{my_settings.reverseSF}")
if my_settings.enableEcho:
logger.debug("System: Echo command Enabled")
if my_settings.repeater_enabled and multiple_interface:
logger.debug(f"System: Repeater Enabled for Channels: {my_settings.repeater_channels}")
if my_settings.checklist_enabled:
logger.debug("System: CheckList Module Enabled")
if my_settings.ignoreChannels:
logger.debug(f"System: Ignoring Channels: {my_settings.ignoreChannels}")
if my_settings.noisyNodeLogging:
logger.debug("System: Noisy Node Logging Enabled")
if my_settings.logMetaStats:
logger.debug("System: Logging Metadata Stats Enabled, leaderboard")
if my_settings.scheduler_enabled:
logger.debug("System: Scheduler Enabled")
except Exception as e:
logger.error(f"System: Error during boot: {e}")
# Hello World
async def main():
meshRxTask = asyncio.create_task(start_rx())
watchdogTask = asyncio.create_task(watchdog())
if file_monitor_enabled:
fileMonTask: asyncio.Task = asyncio.create_task(handleFileWatcher())
tasks = []
try:
handle_boot(mesh=False) # pong bot
# Create core tasks
tasks.append(asyncio.create_task(start_rx(), name="mesh_rx"))
tasks.append(asyncio.create_task(watchdog(), name="watchdog"))
# Add optional tasks
if my_settings.file_monitor_enabled:
tasks.append(asyncio.create_task(handleFileWatcher(), name="file_monitor"))
if my_settings.radio_detection_enabled:
tasks.append(asyncio.create_task(handleSignalWatcher(), name="hamlib"))
await asyncio.gather(meshRxTask, watchdogTask)
if file_monitor_enabled:
await asyncio.gather(fileMonTask)
if my_settings.voxDetectionEnabled:
tasks.append(asyncio.create_task(voxMonitor(), name="vox_detection"))
if my_settings.scheduler_enabled:
from modules.scheduler import run_scheduler_loop, setup_scheduler
setup_scheduler(schedulerMotd, MOTD, schedulerMessage, schedulerChannel, schedulerInterface,
schedulerValue, schedulerTime, schedulerInterval)
tasks.append(asyncio.create_task(run_scheduler_loop(), name="scheduler"))
logger.debug(f"System: Starting {len(tasks)} async tasks")
# Wait for all tasks with proper exception handling
results = await asyncio.gather(*tasks, return_exceptions=True)
# Check for exceptions in results
for i, result in enumerate(results):
if isinstance(result, Exception):
logger.error(f"Task {tasks[i].get_name()} failed with: {result}")
except Exception as e:
logger.error(f"Main loop error: {e}")
finally:
# Cleanup tasks
logger.debug("System: Cleaning up async tasks")
for task in tasks:
if not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
logger.debug(f"Task {task.get_name()} cancelled successfully")
except Exception as e:
logger.warning(f"Error cancelling task {task.get_name()}: {e}")
await asyncio.sleep(0.01)
try:
if __name__ == "__main__":
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
exit_handler()
pass
except KeyboardInterrupt:
exit_handler()
except SystemExit:
pass
# EOF

View File

@@ -7,6 +7,4 @@ maidenhead
beautifulsoup4
dadjokes
geopy
schedule
wikipedia
googlesearch-python
schedule

60
script/README.md Normal file
View File

@@ -0,0 +1,60 @@
## script/runShell.sh
**Purpose:**
`runShell.sh` is a simple demo shell script for the Mesh Bot project. It demonstrates how to execute shell commands within the projects scripting environment.
**Usage:**
Run this script from the terminal to see a basic example of shell scripting in the project context.
```sh
bash script/runShell.sh
```
**What it does:**
- Changes the working directory to the scripts location.
- Prints the current directory path and a message indicating the script is running.
- Serves as a template for creating additional shell scripts or automating tasks related to the project.
**Note:**
You can modify this script to add more shell commands or automation steps as needed for your workflow.
## script/runShell.sh
**Purpose:**
`runShell.sh` is a demonstration shell script for the Mesh Bot project, showing how to execute shell commands in the project environment.
**Usage:**
Run this script from the terminal to see a basic shell scripting example:
```sh
bash script/runShell.sh
```
**What it does:**
- Changes to the scripts directory.
- Prints the current directory path.
- Displays a message indicating the script is running.
**Note:**
You can use this as a template for your own shell scripts or to automate project-related tasks.
## script/sysEnv.sh
**Purpose:**
`sysEnv.sh` is a shell script that collects and displays system telemetry and environment information, especially useful for monitoring a Raspberry Pi or similar device running the Mesh Bot.
**Usage:**
Run this script from the terminal to view system stats and network info:
```sh
bash script/sysEnv.sh
```
**What it does:**
- Reports disk space, RAM usage, CPU usage, and CPU temperature (in °C and °F).
- Checks for available Git updates if the project is a Git repository.
- Displays the devices public and local IP addresses.
- Designed to work on Linux systems, with special handling for Raspberry Pi hardware.
**Note:**
You can expand or modify this script to include additional telemetry or environment checks as needed for your deployment.

132
script/addFav.py Normal file
View File

@@ -0,0 +1,132 @@
#!/usr/bin/env python3
# Add a favorite node to all interfaces from config.ini data
# meshing-around - helper script
import sys
import os
import pickle
import argparse
favList = []
roofNodeList = []
roof_node = False
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Add favorite nodes or print pickle contents.")
parser.add_argument('-pickle', '-p', action='store_true', help="Print the contents of roofNodeList.pkl and exit")
args = parser.parse_args()
if args.pickle:
try:
with open('roofNodeList.pkl', 'rb') as f:
data = pickle.load(f)
#print a simple list of nodeID:x\n
for item in data:
print(f"{item.get('nodeID', 'N/A')}")
except Exception as e:
print(f"Error reading roofNodeList.pkl: {e}")
exit(0)
# welcome header
print("meshing-around: addFav - Auto-Add favorite nodes to all interfaces from config.ini data")
print("This script may need API improvments still in progress")
print("---------------------------------------------------------------")
try:
# set the path to import the modules and config.ini
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from modules.log import logger, getPrettyTime
from modules.system import handleFavoriteNode
from modules.settings import LOGGING_LEVEL
from modules.system import compileFavoriteList
except Exception as e:
print(f"Error importing modules run this program from the main repo directory 'python3 script/addFav.py'")
print(f"if you forgot the rest of it.. git clone https://github.com/spudgunman/meshing-around")
print(f"Import Error: {e}")
exit(1)
try:
# ask if we are running on a roof node
print("This script can be run on a client_base or on the bot under a roof node.")
print("The purpose of this script is to add favorite nodes to the bot to retain DM keys.")
print("If you are running this script on a roof (base) node, stop and rerun it on the bot first to collect all node ID's.")
roof_node = input("Are you running this script on a client_base node which has no BOT? (y/n): ").strip().lower()
if roof_node not in ['y', 'n']:
raise ValueError("Invalid input. Please enter 'y' or 'n'.")
roof_node = (roof_node == 'y')
except Exception as e:
print(f"Error: {e}")
exit(1)
try:
if roof_node:
# load roofNodeList from pickle file
try:
with open('roofNodeList.pkl', 'rb') as f:
roofNodeList = pickle.load(f)
logger.info(f"addFav: Loaded {len(roofNodeList)} connected nodes from roofNodeList.pkl for use on roof client_base only")
print(f"Loaded {len(roofNodeList)} connected nodes from roofNodeList.pkl for use on roof client_base only")
except Exception as e:
logger.error(f"addFav: Error loading roofNodeList.pkl: {e} - run this program from the main program directory 'python3 script/addFav.py'")
exit(1)
favList = roofNodeList
else:
# compile the favorite list wich returns node,interface tuples
roofNodeList = compileFavoriteList(True)
favList = compileFavoriteList(False)
#combine favList and roofNodeList to save for next step
for node in roofNodeList:
if node not in favList:
favList.append(node)
#save roofNodeList to a pickle file for running on the roof node
with open('roofNodeList.pkl', 'wb') as f:
pickle.dump(roofNodeList, f)
logger.info(f"addFav: Saved {len(roofNodeList)} connected nodes to roofNodeList.pkl for use on roof client_base only")
print(f"Saved {len(roofNodeList)} connected nodes to roofNodeList.pkl for use on roof client_base only")
except Exception as e:
logger.error(f"addFav: Error compiling favorite list: {e} - run this program from the main program directory 'python3 script/addFav.py'")
exit(1)
#confirm you want all these added
try:
if favList:
print(f"The following {len(favList)} favorite nodes will be added to the device(s):")
count_devices = set([fav['deviceID'] for fav in favList])
count_nodes = set([fav['nodeID'] for fav in favList])
for fav in favList:
print(f"addFav: adding nodeID {fav['nodeID']} meshtastic --set-favorite-node {fav['nodeID']}")
confirm = input(f"Are you sure you want to add these {len(count_nodes)} favorite nodes to {len(count_devices)} device(s)? (y/n): ").strip().lower()
if confirm != 'y':
print("Operation cancelled by user.")
exit(0)
else:
print("No favorite nodes to add to device(s). Exiting.")
exit(0)
except Exception as e:
logger.error(f"addFav: Error during confirmation: {e}")
exit(1)
if favList:
# for each node,interface tuple add the favorite node
for fav in favList:
try:
handleFavoriteNode(fav['deviceID'], fav['nodeID'], True)
logger.info(f"addFav: waiting 15 seconds to avoid API rate limits")
time.sleep(15) # wait to avoid API rate limits
except Exception as e:
logger.error(f"addFav: Error adding favorite node {fav['nodeID']} to device {fav['deviceID']}: {e}")
else:
logger.info("addFav: No favorite nodes to add to device(s)")
exit(0)
count_devices = set([fav['deviceID'] for fav in favList])
count_nodes = set([fav['nodeID'] for fav in favList])
logger.info(f"addFav: Finished adding {len(count_nodes)} favorite nodes to {len(count_devices)} device(s)")
logger.info("addFav: You may need to restart the mesh service on the device(s)")
print(f"Finished adding {len(count_nodes)} favorite nodes to {len(count_devices)} device(s)")
print(f"Data file for roof client_base has been saved to roofNodeList.pkl")
if not roof_node:
logger.info(f"addFav: You can now run this repo+script & roofNodeList.pkl on the roof node to add the favorite nodes to the roof client_base")
exit(0)

104
script/configMerge.py Normal file
View File

@@ -0,0 +1,104 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Configuration Merge Script
# Merges user configuration with default settings
# 2025 Kelly Keeton K7MHI mesh-around and its meshtastic
import shutil
import configparser
import os
def merge_configs(default_config_path, user_config_path, output_config_path):
# Load default configuration (INI)
default_config = configparser.ConfigParser()
default_config.read(default_config_path)
# Load user configuration (INI)
user_config = configparser.ConfigParser()
user_config.read(user_config_path)
# Merge configurations
for section in user_config.sections():
if not default_config.has_section(section):
default_config.add_section(section)
for key, value in user_config.items(section):
default_config.set(section, key, value)
# Save merged configuration as INI
with open(output_config_path, 'w', encoding='utf-8') as f:
default_config.write(f)
def backup_config(config_path, backup_path):
shutil.copyfile(config_path, backup_path)
def show_config_changes(user_config_path, merged_config_path):
if not os.path.exists(merged_config_path) or os.path.getsize(merged_config_path) == 0:
print(f"Error: {merged_config_path} is empty or missing!")
return
# Load user config (as dict)
user_config = configparser.ConfigParser()
user_config.read(user_config_path)
user_dict = {s: dict(user_config.items(s)) for s in user_config.sections()}
# Load merged config (as dict)
merged_config = configparser.ConfigParser()
merged_config.read(merged_config_path)
merged_dict = {s: dict(merged_config.items(s)) for s in merged_config.sections()}
print("\n--- Changes in merged configuration ---")
for section in merged_dict:
if section not in user_dict:
print(f"[{section}] (new section)")
for k, v in merged_dict[section].items():
print(f" {k} = {v} (added)")
else:
for k, v in merged_dict[section].items():
if k not in user_dict[section]:
print(f"[{section}] {k} = {v} (added)")
elif user_dict[section][k] != v:
print(f"[{section}] {k}: {user_dict[section][k]} -> {v} (changed)")
print("--- End of changes ---\n")
if __name__ == "__main__":
print("MESHING-AROUND: Configuration Merge Script for config.ini checking updates from config.template")
print("---------------------------------------------------------------")
master_config_path = 'config.template'
user_config_path = 'config.ini'
output_config = 'config_new.ini'
backup_config_path = 'config.bak'
# Step 1: Check master config
try:
if not os.path.exists(master_config_path) or os.path.getsize(master_config_path) == 0:
raise FileNotFoundError(f"Master configuration file {master_config_path} is missing or empty.")
except Exception as e:
print(f"Error: {e}")
print("Run the tool from the meshing-around/script/ directory where the config.template is located.")
print(" python3 script/configMerge.py")
exit(1)
# Step 2: Backup user config
try:
backup_config(user_config_path, backup_config_path)
print(f"Backup of user config created at {backup_config_path}")
except Exception as e:
print(f"Error backing up user config: {e}")
exit(1)
# Step 3: Merge configs
try:
merge_configs(master_config_path, user_config_path, output_config)
print(f"Merged configuration saved to {output_config}")
except Exception as e:
print(f"Error merging configuration: {e}")
exit(1)
# Step 4: Show changes
try:
show_config_changes(user_config_path, output_config)
print("Please review the new configuration and replace your existing config.ini if needed.")
print(" cp config_new.ini config.ini")
except Exception as e:
print(f"Error showing configuration changes: {e}")
exit(1)

View File

@@ -1,25 +1,17 @@
# How do I use this thing?
This is not a full turnkey setup for Docker yet but gets you most of the way there!
This is not a full turnkey setup for Docker yet?
## Setup New Image
`docker build -t meshing-around .`
`docker pull ghcr.io/spudgunman/meshing-around:main`
there is also [script/docker/docker-install.bat](script/docker/docker-install.bat) which will automate this.
`docker network create meshing-around-network`
## Ollama Image with compose
still a WIP
`docker compose up -d`
`docker compose run meshtasticd`
## Edit the config.ini in the docker
To edit the config.ini in the docker you can
`docker run -it --entrypoint /bin/bash meshing-around -c "nano /app/config.ini"`
`docker compose run meshing-around`
there is also [script/docker/docker-terminal.bat](script/docker/docker-terminal.bat) which will open nano to edit.
ctl+o to write out and exit editor in shell
`docker compose run ollama`
## other info
1. Ensure your serial port is properly shared.
2. Run the Docker container:
```sh
docker run --rm -it --device=/dev/ttyUSB0 meshing-around
```
`docker compose run debug-console`

View File

@@ -1,52 +0,0 @@
services:
meshing-around:
build:
context: ../..
depends_on:
ollama:
condition: service_healthy
devices:
- /dev/ttyAMA10 # Replace this with your actual device!
configs:
- source: me_config
target: /app/config.ini
extra_hosts:
- "host.docker.internal:host-gateway" # Used to access a local linux meshtasticd device via tcp
ollama:
image: ollama/ollama:0.5.1
volumes:
- ./ollama:/root/.ollama
- ./ollama-entrypoint.sh:./entrypoint.sh
container_name: ollama
pull_policy: always
tty: true
restart: always
entrypoint:
- /usr/bin/bash
- /script/docker/entrypoint.sh
expose:
- 11434
healthcheck:
test: "apt update && apt install curl -y && curl -f http://localhost:11434/api/tags | grep -q llama3.2:3b"
interval: 30s
timeout: 10s
retries: 20
node-exporter:
image: quay.io/prometheus/node-exporter:latest
volumes:
- /proc:/host/proc:ro
- /sys:/host/sys:ro
- /:/rootfs:ro
command:
- --path.procfs=/host/proc
- --path.rootfs=/rootfs
- --path.sysfs=/host/sys
- --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)
restart: unless-stopped
expose:
- 9100
network_mode: host
pid: host
configs:
me_config:
file: ./config.ini

View File

24
script/docker/config.yaml Normal file
View File

@@ -0,0 +1,24 @@
### Template config.yaml
---
Lora:
GPIO:
GPS:
I2C:
Display:
Touchscreen:
Input:
Logging:
LogLevel: info # debug, info, warn, error
# TraceFile: /var/log/meshtasticd.json
# AsciiLogs: true # default if not specified is !isatty() on stdout
Webserver:
Port: 443 # Port for Webserver & Webservices
RootPath: /usr/share/meshtasticd/web # Root Dir of WebServer
# SSLKey: /etc/meshtasticd/ssl/private_key.pem # Path to SSL Key, generated if not present
# SSLCert: /etc/meshtasticd/ssl/certificate.pem # Path to SSL Certificate, generated if not present
General:
MaxNodes: 200
MaxMessageQueue: 100
ConfigDirectory: /etc/meshtasticd/config.d/
# MACAddress: AA:BB:CC:DD:EE:FF
MACAddressSource: eth0

View File

@@ -1,6 +0,0 @@
REM batch file to install docker on windows
REM docker compose up -d
cd ../../
docker build -t meshing-around .
REM docker-compose up -d
docker run -it --entrypoint /bin/bash meshing-around -c "nano /app/config.ini"

View File

@@ -1,2 +0,0 @@
REM launch meshing-around container with a terminal
docker run -it --entrypoint /bin/bash meshing-around

View File

@@ -1,6 +1,16 @@
#!/bin/bash
# instruction set the meshing-around docker container entrypoint
# Substitute environment variables in the config file (what is the purpose of this?)
# envsubst < /app/config.ini > /app/config.tmp && mv /app/config.tmp /app/config.ini
# Run the bot
exec python /app/mesh_bot.py
# if no config.ini exists, copy the default one
if [ ! -f /app/config.ini ]; then
cp /app/config.template /app/config.ini
ls -l /app/config.ini
# Set type = tcp in [interface]
sed -i '/^\[interface\]/,/^[^[]/ s/^type = .*/type = tcp/' /app/config.ini
# Remove any commented or uncommented hostname lines in [interface]
sed -i '/^\[interface\]/,/^[^[]/ s/^#\? *hostname = .*$//' /app/config.ini
# Add hostname = meshtasticd:4403 after [interface]
sed -i '/^\[interface\]/a hostname = UPDATE-DOCKER-IP' /app/config.ini
fi
# Run the bot as appuser (if you want to drop privileges)
exec python /app/mesh_bot.py

View File

@@ -1,16 +0,0 @@
#!/bin/bash
# Start Ollama in the background.
/bin/ollama serve &
# Record Process ID.
pid=$!
# Pause for Ollama to start.
sleep 5
echo "🔴 Retrieve llama3.2:3b model..."
ollama pull llama3.2:3b
echo "🟢 Done!"
# Wait for Ollama process to finish.
wait $pid

55
script/injectDM.py Normal file
View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
# Usage: python3 script/injectDM.py -s NODEID -d NODEID -m "message"
# meshing-around - helper script - enable the bbsAPI in config.ini first
import sys
import os
import argparse
# welcome header
print("meshing-around: injectDM.py -s NODEID -d NODEID -m 'Hello World'")
print("Auto-Inject DM messages to data/bbsdm.pkl")
print(" needs config.ini [bbs] bbsAPI_enabled = True ")
print("---------------------------------------------------------------")
try:
# set the path to import the modules and config.ini
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from modules.log import logger
from modules.bbstools import bbs_post_dm, bbs_dm, get_bbs_stats
from modules.settings import LOGGING_LEVEL, vpTracker, MOTD
logger.setLevel(LOGGING_LEVEL)
except Exception as e:
print(f"Error importing modules run this program from the main program directory 'python3 script/injectDM.py'")
exit(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Inject DM messages to data/bbsdm.pkl')
parser.add_argument('-s', '--src', type=str, required=True, help='Source NODEID')
parser.add_argument('-d', '--dst', type=str, required=True, help='Destination NODEID')
parser.add_argument('-m', '--msg', type=str, required=True, help="'Message to send'")
args = parser.parse_args()
dst = args.dst
src = args.src
message = args.msg
if not message:
logger.error("Message cannot be empty")
exit(1)
if dst == src:
logger.error("Source and Destination cannot be the same")
exit(1)
if not isinstance(bbs_dm, list):
logger.error("bbs_dm is corrupt, something is wrong")
exit(1)
# inject the message
if bbs_post_dm(dst, message, src):
logger.info(f"Injected message from {src} to {dst}: {message}")
else:
logger.error("Failed to inject message")
exit(1)
# show stats get_bbs_stats
stats = get_bbs_stats()
stats = stats.replace("\n", " | ")
logger.info(f"BBS Stats: {stats}")

View File

@@ -24,4 +24,33 @@ else
fi
# print telemetry data rounded to 2 decimal places
printf "Disk:%s RAM:%.2f%% CPU:%.2f%% CPU-T:%.2f°C (%.2f°F)\n" "$free_space" "$ram_usage" "$cpu_usage" "$temp" "$tempf"
printf "Disk:%s RAM:%.2f%% CPU:%.2f%% CPU-T:%.2f°C (%.2f°F)\n" "$free_space" "$ram_usage" "$cpu_usage" "$temp" "$tempf"
# attempt check for updates
if command -v git &> /dev/null
then
if [ -d ../.git ]; then
# check for updates
git fetch --quiet
local_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$local_branch" != "HEAD" ] && git show-ref --verify --quiet "refs/remotes/origin/$local_branch"; then
local_commit=$(git rev-parse "$local_branch")
remote_commit=$(git rev-parse "origin/$local_branch")
if [ "$local_commit" != "$remote_commit" ]; then
echo "Bot Update Available!"
fi
fi
fi
fi
# Get public and local IP addresses
public_ip=$(curl -s https://ifconfig.me 2>/dev/null)
public_ip=${public_ip:-""}
local_ip=$(hostname -I 2>/dev/null | awk '{print $1}')
local_ip=${local_ip:-""}
if [ -n "$public_ip" ]; then
echo "Public IP: $public_ip"
fi
if [ -n "$local_ip" ]; then
echo "Local IP: $local_ip"
fi

100
update.sh Normal file
View File

@@ -0,0 +1,100 @@
#!/bin/bash
# MeshBot Update Script
# Usage: bash update.sh or ./update.sh after making it executable with chmod +x update.sh
# Check if the mesh_bot.service or pong_bot.service
service_stopped=false
if systemctl is-active --quiet mesh_bot.service; then
echo "Stopping mesh_bot.service..."
systemctl stop mesh_bot.service
service_stopped=true
fi
if systemctl is-active --quiet pong_bot.service; then
echo "Stopping pong_bot.service..."
systemctl stop pong_bot.service
service_stopped=true
fi
if systemctl is-active --quiet mesh_bot_reporting.service; then
echo "Stopping mesh_bot_reporting.service..."
systemctl stop mesh_bot_reporting.service
service_stopped=true
fi
if systemctl is-active --quiet mesh_bot_w3.service; then
echo "Stopping mesh_bot_w3.service..."
systemctl stop mesh_bot_w3.service
service_stopped=true
fi
# Fetch latest changes from GitHub
echo "Fetching latest changes from GitHub..."
if ! git fetch origin; then
echo "Error: Failed to fetch from GitHub, check your network connection."
exit 1
fi
# git pull with rebase to avoid unnecessary merge commits
echo "Pulling latest changes from GitHub..."
if ! git pull origin main --rebase; then
read -p "Git pull resulted in conflicts. Do you want to reset hard to origin/main? This will discard local changes. (y/n): " choice
if [[ "$choice" == "y" || "$choice" == "Y" ]]; then
git fetch --all
git reset --hard origin/main
echo "Local repository updated."
else
echo "Update aborted due to git conflicts."
fi
fi
# copy modules/custom_scheduler.py template if it does not exist
if [[ ! -f modules/custom_scheduler.py ]]; then
cp -n etc/custom_scheduler.py modules/
printf "\nCustom scheduler template copied to modules/custom_scheduler.py\n"
elif ! cmp -s modules/custom_scheduler.py etc/custom_scheduler.py; then
echo "custom_scheduler.py is set. To check changes run: diff etc/custom_scheduler.py modules/custom_scheduler.py"
fi
# Backup the data/ directory
echo "Backing up data/ directory..."
#backup_file="backup_$(date +%Y%m%d_%H%M%S).tar.gz"
backup_file="data_backup.tar.gz"
path2backup="data/"
#copy custom_scheduler.py if it exists
if [[ -f "modules/custom_scheduler.py" ]]; then
echo "Including custom_scheduler.py in backup..."
cp modules/custom_scheduler.py data/
fi
tar -czf "$backup_file" "$path2backup"
if [ $? -ne 0 ]; then
echo "Error: Backup failed."
else
echo "Backup of ${path2backup} completed: ${backup_file}"
fi
# Build a config_new.ini file merging user config with new defaults
echo "Merging configuration files..."
python3 script/configMerge.py > ini_merge_log.txt 2>&1
if [[ -f ini_merge_log.txt ]]; then
if grep -q "Error during configuration merge" ini_merge_log.txt; then
echo "Configuration merge encountered errors. Please check ini_merge_log.txt for details."
else
echo "Configuration merge completed. Please review config_new.ini and ini_merge_log.txt."
fi
else
echo "Configuration merge log (ini_merge_log.txt) not found. check out the script/configMerge.py tool!"
fi
if [[ "$service_stopped" = true ]]; then
echo "Restarting services..."
for svc in mesh_bot.service pong_bot.service mesh_bot_reporting.service mesh_bot_w3.service; do
if systemctl list-unit-files | grep -q "^$svc"; then
systemctl start "$svc"
echo "$svc restarted."
fi
done
fi
# Print completion message
echo "Update completed successfully?"
exit 0
# End of script