New AssemblyAI-STT-3.7: Next-generation transcription models. Learn more about AssemblyAI-STT-3.7
Insights & Use Cases

Auto-tweet your words with real-time speech recognition in Python

Build a Python app that transcribes your microphone live with AssemblyAI-STT-3.7-Realtime and posts to X when you say "post that". Full code and repo.

Abstract green cylinder illustration

Written by

Mısra Turp

Published on

23 November 2026

We say the funniest things when no one is listening. This app listens. It transcribes your microphone live, and when you say "post that", it posts what you just said to X.

You'll build it in Python with two pieces:

  • Live transcription: AssemblyAI-STT-3.7-Realtime through the AssemblyAI Python SDK. Your words show up on screen as you talk, and each finished turn comes back punctuated and formatted.
  • Posting: X's Create Post endpoint, POST https://api.x.com/2/tweets, signed with your account's OAuth 1.0a tokens.

The full code is in the companion repo, kelsey-aai/voice-to-x-post-python.

Why AssemblyAI-STT-3.7-Realtime

Short, spoken one-liners are the hardest case for an auto-poster: there's little context, and one wrong word changes the joke. AssemblyAI-STT-3.7-Realtime is built for live transcription (meetings, calls, captions and dictation-style input), and on short-form English it has a 3.23% word error rate, ahead of ElevenLabs Scribe v3 Live, AWS Transcribe Streaming and Deepgram Flux, per the launch post.

Two behaviors make it a good fit for a voice command app:

  • Partial transcripts arrive about once a second, so you see your words while you're still talking.
  • Turns close when there's enough to show, and each final turn is already punctuated and capitalized. You don't need to request formatting or tune turn detection.

For agents that talk back, use AssemblyAI-STT-3.7-Realtime-Agent instead. This app only listens, so the Realtime model is the right one.

How the app works

You say What gets posted
"I think tabs beat spaces. Post that." (one turn) "I think tabs beat spaces."
"Coffee is a vegetable." Then, as a new turn, "Post that." "Coffee is a vegetable."
"Okay, post that." after a turn The previous turn. A word or two of filler before the command isn't treated as the post.

"Tweet that" works too. The app never posts the same text twice in a row, and it trims anything over 280 characters, X's limit for accounts without X Premium.

Set up your credentials

AssemblyAI. Sign up and copy your API key from the dashboard. New accounts get $50 in free credits for the speech APIs.

X. In the X Developer Console, create an app and set its permissions to Read and write. Then generate the API Key and Secret and the Access Token and Secret for your own account. X shows credentials once, so save them right away. If you change the app's permissions after generating tokens, generate new ones; old tokens keep the old permissions.

The X API is pay-per-use. At the time of writing, X's pricing page lists $0.015 per created post and $0.200 for a post that contains a URL. Use --dry-run while you test.

Put all six values in a .env file:

ASSEMBLYAI_API_KEY=your_assemblyai_api_key
X_API_KEY=your_x_api_key
X_API_KEY_SECRET=your_x_api_key_secret
X_ACCESS_TOKEN=your_x_access_token
X_ACCESS_TOKEN_SECRET=your_x_access_token_secret

Install the dependencies

You need Python 3.9 or later and a microphone. PyAudio needs the PortAudio library: brew install portaudio on macOS or sudo apt install portaudio19-dev on Debian and Ubuntu.

python -m venv .venv && source .venv/bin/activate
pip install "assemblyai>=1.10.11" pyaudio requests-oauthlib python-dotenv

Imports and settings

Create voice_post.py. The streaming classes come from assemblyai.streaming.v3:

"""Say something, then say "post that", and it goes to X.

Live transcription: AssemblyAI-STT-3.7-Realtime through the AssemblyAI Python SDK.
Posting: POST https://api.x.com/2/tweets with OAuth 1.0a user context.
"""

import argparse
import os
import re
import threading

import pyaudio
from dotenv import load_dotenv
from requests_oauthlib import OAuth1Session
from assemblyai.streaming.v3 import (
    BeginEvent,
    RealTimeError,
    RealTimeEvents,
    RealTimeParameters,
    RealTimeTranscriber,
    RealTimeTranscriberOptions,
    TerminationEvent,
    TurnEvent,
)

load_dotenv()

SAMPLE_RATE = 16000
FRAMES_PER_BUFFER = 800  # 50 ms of 16-bit mono PCM at 16 kHz
X_POST_URL = "https://api.x.com/2/tweets"
MAX_POST_CHARS = 280  # X's limit for accounts without X Premium

# "post that" / "tweet that" at the end of a turn, with optional trailing punctuation.
COMMAND = re.compile(r"^(?P<before>.*?)[\s,]*\b(?:post|tweet) that[\s.!?]*$", re.IGNORECASE)

state = {"previous_turn": "", "last_posted": ""}
lock = threading.Lock()

The streaming API expects 16-bit mono PCM by default, and the docs recommend chunks of 50 to 100 ms. At 16 kHz, 800 frames is 50 ms.

Post to X

X's Create Post reference accepts OAuth 1.0a user context, which is what the four keys in your .env are for. OAuth1Session signs each request, and the body is a JSON object with a text field. A successful post returns 201 with the new post's id under data:

# ---------- X ----------

def make_x_session() -> OAuth1Session:
    return OAuth1Session(
        client_key=os.environ["X_API_KEY"],
        client_secret=os.environ["X_API_KEY_SECRET"],
        resource_owner_key=os.environ["X_ACCESS_TOKEN"],
        resource_owner_secret=os.environ["X_ACCESS_TOKEN_SECRET"],
    )


def post_to_x(session, text: str, dry_run: bool) -> None:
    text = text.strip()
    if len(text) > MAX_POST_CHARS:
        text = text[: MAX_POST_CHARS - 1] + "…"

    if dry_run:
        print(f"[dry run] would post: {text!r}")
        return

    response = session.post(X_POST_URL, json={"text": text})
    if response.status_code == 201:
        post_id = response.json()["data"]["id"]
        print(f"Posted to X (id {post_id}): {text}")
    else:
        print(f"X returned {response.status_code}: {response.text}")

If you get a 403, the app's permissions are probably still read-only, or the access token was generated before you switched them to Read and write.

Get a Free API Key

Stream your microphone to AssemblyAI-STT-3.7-Realtime with $50 in free credits for the speech APIs.

Get Free API Key

Detect the voice command

Every final turn goes through handle_final_turn. If the turn ends in "post that", the app posts the sentence before the command, or the previous turn when the command stands alone. Otherwise it remembers the turn in case the next one is the command:

# ---------- Commands ----------

def handle_final_turn(text: str, session, dry_run: bool) -> None:
    """Post the earlier part of this turn, or the previous turn, when it ends in 'post that'."""
    match = COMMAND.match(text)
    if not match:
        with lock:
            state["previous_turn"] = text
        return

    with lock:
        before = match.group("before").strip()
        # "Okay, post that" -> post the previous turn; a real sentence before the command -> post it.
        payload = before if len(before.split()) >= 3 else state["previous_turn"]
        if not payload:
            print("Heard the command, but there's nothing to post yet.")
            return
        if payload == state["last_posted"]:
            print("Skipping a duplicate post.")
            return
        state["last_posted"] = payload
        state["previous_turn"] = ""

    post_to_x(session, payload, dry_run)

Matching on the final turn, not on partials, matters. Partials change as you speak, and you don't want "post" in the middle of a sentence to fire the command.

Read the microphone

A generator reads 50 ms chunks from PyAudio until a stop event is set. The SDK's stream() method accepts any iterable of bytes and handles the WebSocket framing:

# ---------- Microphone ----------

def microphone_chunks(stop: threading.Event):
    audio = pyaudio.PyAudio()
    stream = audio.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=SAMPLE_RATE,
        input=True,
        frames_per_buffer=FRAMES_PER_BUFFER,
    )
    try:
        while not stop.is_set():
            yield stream.read(FRAMES_PER_BUFFER, exception_on_overflow=False)
    finally:
        stream.stop_stream()
        stream.close()
        audio.terminate()

Stream to AssemblyAI-STT-3.7-Realtime

main() registers four event handlers and connects with speech_model="assemblyai-stt-3-7-realtime". Each Turn event carries end_of_turn: False for partials, which overwrite the current console line, and True for the final text, which goes to the command handler. On Ctrl+C, disconnect(terminate=True) sends a terminate message so the last turn is finalized before the session closes:

# ---------- Main ----------

def main() -> None:
    parser = argparse.ArgumentParser(description="Post to X by voice.")
    parser.add_argument("--dry-run", action="store_true", help="print posts instead of sending them")
    args = parser.parse_args()

    session = None if args.dry_run else make_x_session()

    def on_begin(client: RealTimeTranscriber, event: BeginEvent):
        print(f"Session {event.id} started. Talk, then say 'post that'. Ctrl+C to stop.")

    def on_turn(client: RealTimeTranscriber, event: TurnEvent):
        if not event.transcript:
            return
        if event.end_of_turn:
            print(f"\r{event.transcript}")
            handle_final_turn(event.transcript, session, args.dry_run)
        else:
            print(f"\r{event.transcript}", end="", flush=True)

    def on_terminated(client: RealTimeTranscriber, event: TerminationEvent):
        print(f"\nSession ended after {event.audio_duration_seconds}s of audio.")

    def on_error(client: RealTimeTranscriber, error: RealTimeError):
        print(f"\nStreaming error: {error}")

    client = RealTimeTranscriber(
        RealTimeTranscriberOptions(),
        api_key=os.environ["ASSEMBLYAI_API_KEY"],
    )
    client.on(RealTimeEvents.Begin, on_begin)
    client.on(RealTimeEvents.Turn, on_turn)
    client.on(RealTimeEvents.Termination, on_terminated)
    client.on(RealTimeEvents.Error, on_error)

    client.connect(
        RealTimeParameters(
            speech_model="assemblyai-stt-3-7-realtime",
            sample_rate=SAMPLE_RATE,
        )
    )

    stop = threading.Event()
    try:
        client.stream(microphone_chunks(stop))
    except KeyboardInterrupt:
        pass
    finally:
        stop.set()
        client.disconnect(terminate=True)


if __name__ == "__main__":
    main()

Run it

# Practice without posting
python voice_post.py --dry-run

# Post for real
python voice_post.py

A session looks like this:

Session 7f3a9c2e-... started. Talk, then say 'post that'. Ctrl+C to stop.
I think tabs beat spaces. Post that.
[dry run] would post: 'I think tabs beat spaces.'
Hear AssemblyAI-STT-3.7-Realtime Live

Stream your microphone in the playground and watch partials and final turns arrive before you write any code.

Open the Playground

Make it yours

Change How
Spell names and handles right Add keyterms_prompt=["AssemblyAI", "Kubernetes"] to RealTimeParameters (the SDK takes a list; keyterms are included in the Realtime price)
Post in another language Nothing to change: AssemblyAI-STT-3.7-Realtime detects and code-switches across 32 languages. Translate the command words in COMMAND.
Confirm before posting Print the payload and wait for "yes" as the next final turn before calling post_to_x
Run it in a browser Mint a temporary streaming token on your server so the API key never reaches the client

If you go the keyterms route, keyterms prompting for streaming explains how many terms to add and which ones help. Keep the list short; when keyterm prompting backfires shows why.

What it costs

AssemblyAI-STT-3.7-Realtime is $0.30 per hour of streamed audio, with keyterms prompting included, per the pricing page. A half-hour of rambling into your microphone comes to 15 cents. X bills separately for each post, so practice with --dry-run.

Build Voice Commands Into Your App

Clone the repo, add your keys and post your first spoken thought in a few minutes.

Start Building Free

Frequently Asked Questions (FAQs)

How do I post to X (Twitter) from Python?

Send POST https://api.x.com/2/tweets with a JSON body like {"text": "hello"}, signed with your account's credentials. With OAuth 1.0a, create an app in the X Developer Console with Read and write permission, generate your access token and secret, and sign the request with requests_oauthlib.OAuth1Session. A successful request returns 201 with the new post's ID.

Can I tweet with my voice?

Yes. Stream your microphone to a real-time speech-to-text API, watch the final transcript for a command phrase such as "post that", and send the text before it to X's Create Post endpoint. This tutorial does exactly that in about 160 lines of Python.

Which AssemblyAI model should I use for live transcription in Python?

Use AssemblyAI-STT-3.7-Realtime (speech_model="assemblyai-stt-3-7-realtime") for live transcription, captions, meetings and voice commands. Use AssemblyAI-STT-3.7-Realtime-Agent for voice agents that respond to the speaker. Both support 32 languages.

How do I transcribe my microphone in real time with Python?

Read 16 kHz, 16-bit mono audio from PyAudio in 50 ms chunks and pass the chunks to RealTimeTranscriber.stream() from assemblyai.streaming.v3. Register a handler for RealTimeEvents.Turn: events with end_of_turn set to False are partials, and True marks the finished, formatted turn.

Does the X API cost money to post?

Yes. The X API is pay-per-use. At the time of writing, X lists $0.015 per created post and $0.200 for a post that contains a URL. Check X's pricing page before you post at volume.

Why does X return 403 Forbidden when I post?

A common cause is that the app's permissions are Read only, or the access token was generated before you changed them to Read and write. Update the permissions in the X Developer Console, then generate a new access token and secret.