Put ChatGPT on your Meshtastic Node

Started by branx86, July 25, 2026, 12:24:09 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

branx86

Use the TXT document to install Meshtastic Ai -Bot
Worked on Raspberry Pi 3b+ with 64 Bit OS

Install dependencies: pip install meshtastic openai pubsub

Python Script

import meshtastic
import meshtastic.serial_interface
from pubsub import pub
from openai import OpenAI
import time

# ==== CONFIG ====
OPENAI_API_KEY = "your_openai_api_key_here"
MODEL = "gpt-4o-mini"  # fast + cheap model
CHANNEL_INDEX = 0      # default Meshtastic channel

# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)

# Connect to Meshtastic (USB)
interface = meshtastic.serial_interface.SerialInterface()

print("Connected to Meshtastic!")

# ==== CHATGPT FUNCTION ====
def ask_chatgpt(prompt):
    try:
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": "You are a helpful assistant. Keep responses short (under 200 characters)."},
                {"role": "user", "content": prompt}
            ]
        )
        return response.choices
  • .message.content.strip()
    except Exception as e:
        return f"Error: {str(e)}"

# ==== MESSAGE HANDLER ====
def on_receive(packet, interface):
    try:
        if 'decoded' not in packet:
            return

        text = packet['decoded'].get('text', '')
        sender = packet.get('fromId', 'unknown')

        if not text:
            return

        print(f"Received: {text} from {sender}")

        # Check for "/" command
        if text.startswith("/"):
            query = text[1:].strip()

            if not query:
                return

            print(f"Querying ChatGPT: {query}")

            reply = ask_chatgpt(query)

            print(f"Reply: {reply}")

            # Send back to mesh
            interface.sendText(
                text=reply,
                channelIndex=CHANNEL_INDEX
            )

    except Exception as e:
        print(f"Error handling message: {e}")

# Subscribe to Meshtastic receive events
pub.subscribe(on_receive, "meshtastic.receive")

# ==== KEEP RUNNING ====
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    interface.close()
    print("Disconnected.")




Optional Improvements:
if packet.get('fromId') == interface.myInfo.my_node_num:
    return


Limit response length (important for LoRa)
Meshtastic payloads are small (~200 chars), so trim:

reply = reply[:200]


Add command types:
/weather Dallas
/help
/status