원격 URL을 지정하면 #Twitter #API를 두드려 이미지가 트윗되는 #python 스크립트 예제

6829 단어 트위터파이썬api

구성 g. py


CONSUMER_KEY=''
CONSUMER_SECRET=''
ACCESS_TOKEN=''
ACCESS_TOKEN_SECRET=''


티는 라우 th. py


#!/usr/bin/env python3

import os, config
from requests_oauthlib import OAuth1Session

if os.environ.get('TWITTER_CONSUMER_KEY'):
  CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY')
  CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET')
  ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN')
  ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
else:
  CONSUMER_KEY = config.CONSUMER_KEY
  CONSUMER_SECRET = config.CONSUMER_SECRET
  ACCESS_TOKEN = config.ACCESS_TOKEN
  ACCESS_TOKEN_SECRET = config.ACCESS_TOKEN_SECRET

def twitter():
  return  OAuth1Session(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)


sc pt. py


#!/usr/bin/env python3

import json, config, os, twitterauth, sys, base64

url = 'https://dummyimage.com/600x400/000/fff'

twitter = twitterauth.twitter()

image_bytes = base64.b64encode(requests.get(url).content)
image_base64_str = image_bytes.decode('utf-8')

media_api_params = {
  "media_data": image_base64_str
}

media_api_url = 'https://upload.twitter.com/1.1/media/upload.json'
media_api_res = twitter.post(media_api_url, params = media_api_params)

media_id_string = media_api_res.json().get('media_id_string')



update_api_params = {
  "status" : "test message",
  "media_ids" : media_id_string,
}

update_api_url = 'https://api.twitter.com/1.1/statuses/update.json'

update_api_res = twitter.post(update_api_url, params = update_api_params)


print(json.dumps(media_api_res.json()))

#result



Original by Github issue

좋은 웹페이지 즐겨찾기