BotCommGitHub

Guides

Send bot messages from Python

Send a report, a reminder, or an alert from a Python script to your BotComm chat. This example uses Python 3.6 or later and the standard library, with no packages to install.

Prepare your bot

  1. Create a bot in the web console and save its Client ID and Client secret.
  2. Open the bot’s chat in BotComm on iOS or the web. Without a target Session ID, messages go to the owner’s chat.
  3. Enable notifications in the app and your device settings if you want a push alert.

Set the credentials in the environment of the machine running your script. Keep the secret out of source control.

export CLIENT_ID='YOUR_CLIENT_ID'
export CLIENT_SECRET='YOUR_CLIENT_SECRET'

Send a message

Save the following as notify.py. It sends JSON over HTTPS, uses HTTP Basic authentication, and waits up to 30 seconds for network operations.

import base64
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def send_message(content):
    client_id = os.environ.get("CLIENT_ID")
    client_secret = os.environ.get("CLIENT_SECRET")
    if not client_id or not client_secret:
        raise ValueError("Set CLIENT_ID and CLIENT_SECRET")
    if not 1 <= len(content) <= 4096:
        raise ValueError("Message content must contain 1–4096 characters")

    credentials = base64.b64encode(
        f"{client_id}:{client_secret}".encode("utf-8")
    ).decode("ascii")
    payload = {"content": content}
    if os.environ.get("SESSION_ID"):
        payload["sessionID"] = os.environ["SESSION_ID"]

    request = Request(
        "https://api.botcomm.app/message",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Basic {credentials}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    with urlopen(request, timeout=30) as response:
        return json.load(response)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 notify.py "Your message"')
    try:
        message = send_message(sys.argv[1])
    except HTTPError as error:
        raise SystemExit(f"BotComm HTTP {error.code}")
    except (URLError, TimeoutError) as error:
        raise SystemExit(f"Could not reach BotComm: {error}")
    except ValueError as error:
        raise SystemExit(str(error))
    print(message["id"])

Run it with a message as its argument:

python3 notify.py "Your report is ready."

A successful send returns HTTP 200. The script prints the message ID and exits successfully; the message appears in your bot’s chat. A saved message does not guarantee a device notification.

Choose a recipient

The default recipient is the bot owner. To notify another connected user, copy the Session ID from their Chat Settings and set SESSION_ID before running the script:

export SESSION_ID='YOUR_SESSION_ID'
python3 notify.py "Your report is ready."

The session must belong to the bot whose credentials you use. Run unset SESSION_ID to send to your own chat again. See the HTTP reference for subjects, silent messages, and broadcasts.

Troubleshooting

  • HTTP 401: check the Client ID and secret. Update the environment after rotating credentials.
  • HTTP 404: reconnect to your bot, or verify that the Session ID belongs to it.
  • HTTP 400: check the request fields and message length. Text messages allow up to 4,096 Unicode characters.
  • HTTP 429: reduce how often the script sends. Consult the rate limits before retrying.
  • Network timeout: check connectivity and your chat before retrying. The server may have saved the message even if the response did not reach your script, so a retry can create a duplicate.
  • A message appears without an alert: check the chat’s notification settings and your device permissions.

For details about the Python HTTP client used here, see the urllib.request documentation.