Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đăng tweet với Python (tweepy)

Sử dụng thư viện tweepy để tương tác Twitter API. Cần tài khoản developer và các key/token.

Chuẩn bị (5 bước)

  1. Tài khoản Twitter + xác thực số điện thoại.
  2. Tạo App tại developer.twitter.com.
  3. Cấp quyền Read and Write (Permissions tab).
  4. Tạo Access Token & Secret (Keys and Tokens tab).
  5. Cài đặt: pip install tweepy

Đăng tweet văn bản

import tweepy

consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

api.update_status(status="Hi All Of My Friends !!!!")

Đăng tweet kèm hình ảnh

tweet_msg = "Hello with image!"
image_path = "path/to/image.jpg"

status = api.update_with_media(image_path, tweet_msg)
# hoặc API v2:
# media = api.media_upload(image_path)
# api.update_status(status=tweet_msg, media_ids=[media.media_id])

Lưu ý quan trọng

  • Twitter API v2 đã thay đổi nhiều so với v1.1 (code trên dùng v1.1).
  • Cần申请 Elevated/Elevated+ access để đăng tweet.
  • Rate limits áp dụng (300 tweets/3h cho user).
  • Bảo mật: không hardcode key, dùng biến môi trường.