惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
月光博客
月光博客
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
小众软件
小众软件
量子位
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog
U
Unit 42
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
I built a Telegram Twitter auto-poster — here's what OAut...
Ayi NEDJIMI · 2026-05-22 · via DEV Community

I run a cybersecurity consulting firm. We publish a lot of content — threat intel, CVE summaries, analysis — first on a Telegram channel, then cross-posted to Twitter/X for reach. After the tenth time manually copying a post at 8am, I decided to automate it.

The result: a Python bot that reads a Telegram channel via the Bot API, filters for posts worth sharing, and pushes them to Twitter. It runs every 2 hours via cron. It's capped at 400 tweets per month to stay on the free API tier. At 3 tweets per run, that's exactly 360 per month — enough margin for reruns and edge cases.

Building it took maybe 4 hours. Debugging OAuth took 3 of those.

The deceptively simple problem

Twitter API v2 is the current API. It uses OAuth 2.0 Bearer tokens for read operations, and OAuth 1.0a for write operations (posting tweets). That's annoying but fine — I'd dealt with OAuth 1.0a before.

The wrinkle: media uploads still go through the v1.1 endpoint (api.twitter.com/1.1/media/upload.json), not v2. And v1.1 uses OAuth 1.0a. So even if you'd rather forget OAuth 1.0a exists, you can't. You need it for image posts.

The Twitter docs don't exactly shout this at you. They mention it, but it's buried under the v2 migration guides and easy to miss if you're building fresh instead of migrating.

What OAuth 1.0a actually signs

Here's where I lost two hours.

OAuth 1.0a works by building a signature from a concatenation of: the HTTP method, the base URL, and all the request parameters — both OAuth parameters and request body parameters — sorted alphabetically, percent-encoded, and joined with &. Then you HMAC-SHA1 that with your consumer secret and token secret.

The part the docs gloss over: for application/x-www-form-urlencoded requests, body parameters must be included in the signature base string. If you're sending media_data=<base64> in the body, that parameter has to be in the signature. Skip it, and you get a 401 with {"code": 32, "message": "Could not authenticate you."} — the most useless error message in any API.

Here's the signing function I ended up with:

import hmac
import hashlib
import base64
import time
import uuid
from urllib.parse import quote, urlencode

def build_oauth_header(method, url, consumer_key, consumer_secret,
                       token, token_secret, body_params=None):
    oauth_params = {
        "oauth_consumer_key": consumer_key,
        "oauth_nonce": uuid.uuid4().hex,
        "oauth_signature_method": "HMAC-SHA1",
        "oauth_timestamp": str(int(time.time())),
        "oauth_token": token,
        "oauth_version": "1.0",
    }

    # THIS is the part the docs bury: body_params go into the signature
    all_params = {**oauth_params}
    if body_params:
        all_params.update(body_params)

    # Sort all params, percent-encode keys and values
    sorted_params = sorted(
        (quote(str(k), safe=""), quote(str(v), safe=""))
        for k, v in all_params.items()
    )
    param_string = "&".join(f"{k}={v}" for k, v in sorted_params)

    signature_base = "&".join([
        method.upper(),
        quote(url, safe=""),
        quote(param_string, safe=""),
    ])

    signing_key = f"{quote(consumer_secret, safe='')}&{quote(token_secret, safe='')}"
    signature = base64.b64encode(
        hmac.new(signing_key.encode(), signature_base.encode(), hashlib.sha1).digest()
    ).decode()

    oauth_params["oauth_signature"] = signature

    header_parts = ", ".join(
        f'{quote(k, safe="")}="{quote(v, safe="")}"'
        for k, v in sorted(oauth_params.items())
    )
    return f"Authorization: OAuth {header_parts}"

Enter fullscreen mode Exit fullscreen mode

The call that bit me: I was passing body_params=None for the media upload because I thought the body was handled separately by the requests library. It is — but you still have to include those same params in the signature calculation. The body and the signature are separate concerns.

The rate limit math

Twitter's free API tier gives you 500 write operations per month. I set a hard cap of 400 in the script to leave buffer. The cron runs every 2 hours (12 times per day, 360 times per month), posting a maximum of 3 tweets per run.

400 tweets / 30 days = 13.3/day
13.3/day / 12 runs = 1.1 tweet/run average

Enter fullscreen mode Exit fullscreen mode

In practice, some days have nothing worth posting, some days have 5 things. Setting the per-run max to 3 and tracking monthly usage in a local SQLite counter keeps it safe. If the monthly counter is above 380, the bot skips posting and logs it.

This is more reliable than trusting the Twitter API to return sensible errors when you hit limits — their rate limit error messages are also not great.

What the Telegram side looks like

Telegram's Bot API is, in contrast, a pleasure to use. You forward messages from the channel to a dedicated bot, and poll getUpdates to retrieve them. No OAuth. Bearer token in the URL. JSON responses that actually make sense.

The filter logic: skip messages shorter than 100 characters (usually reactions or single-link drops), skip messages that are pure retweets or already have the Twitter URL pattern, prefer messages with media for higher engagement.

One gotcha: Telegram's getUpdates gives you an update_id field. You have to track the last processed update_id and pass it as offset on the next call, or you'll re-process every message from the beginning on every run. I lost this to a file I forgot to persist across container restarts — spent 20 minutes wondering why the bot was reposting 3-week-old content.

Honest take on OAuth 1.0a

OAuth 1.0a is not good. The signature mechanism is fiddly, the error messages when you get it wrong are deliberately unhelpful (presumably as a security measure, though it mostly just wastes developer time), and the interaction between different content types and what has to be in the signature base is genuinely underspecified in the RFC.

OAuth 2.0 Bearer tokens are significantly better for developer experience. The fact that Twitter still requires OAuth 1.0a for writes — and v1.1-era endpoints for media — suggests some infrastructure decisions were made a long time ago and are very expensive to change.

If you're building against the Twitter API, use a library like tweepy for the OAuth layer. I chose not to for this project because I wanted to understand what was happening, and because the bot's requirements were narrow enough that the added dependency felt like overkill. That's a valid choice, but go in knowing you will spend time on the signature generation that you would not spend otherwise.

The bot has been running for three months without issue. The cron, the SQLite counter, and the Telegram offset tracking all work. Every 2 hours, relevant security news goes from Telegram to Twitter without me touching anything. That part is genuinely satisfying.


I run AYI NEDJIMI Consultants, a cybersecurity consulting firm. We publish free security hardening checklists for FortiGate, Palo Alto, pfSense, Sophos, Active Directory and more — PDF and Excel.