Skip to content

Instantly share code, notes, and snippets.

@kdmgs110
Last active October 2, 2022 11:58
Show Gist options
  • Save kdmgs110/fc7e65c643ee8224b04279468942c12c to your computer and use it in GitHub Desktop.
Save kdmgs110/fc7e65c643ee8224b04279468942c12c to your computer and use it in GitHub Desktop.
Twitterでエッチな投稿するプログラム
import urllib.request
from requests_oauthlib import OAuth1Session # ライブラリ(1)
from bs4 import BeautifulSoup
from TwitterAPI import TwitterAPI
import requests
import tweepy
import os
# 各種キーをセット
CONSUMER_KEY = '[CONSUMER_KEY]'
CONSUMER_SECRET = '[CONSUMER_SECRET]'
ACCESS_TOKEN = '[ACCESS_TOKEN]'
ACCESS_SECRET = '[ACCESS_SECRET]'
#apiを取得
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)
# ツイート投稿用のURL
url = "https://api.twitter.com/1.1/statuses/update_with_media.json"
# DMMのAPP ID, AFFILIATE ID, 検索キーワードをセット
APPID = "[APPID]"
AFFILIATEID = "[AFFILIATEID]"
KEYWORD = "your keyword here"
#DMMのAPIを取得し、XMLをBeautifulsoupで取得
html = urllib.request.urlopen("https://api.dmm.com/affiliate/v3/ItemList?api_id=" + APPID + "&affiliate_id=" + AFFILIATEID + "%20&site=DMM.R18&service=digital&floor=videoa&hits=2&sort=date&keyword=" + KEYWORD + "&output=xml")
soup = BeautifulSoup(html,"html5lib")
#取得したXMLを整理して表示する
print("取得したデータを表示します")
print(soup.prettify())
#タイトル・女優・画像URL・動画URLを追加
items = soup.items #1つ1つのitemオブジェクトを取得
print("取得したitems数:{}".format(len(items.item)))
for item in items:
print("--------------")
title = item.title.string #動画タイトル
title = (title[:40] + "..動画はこちら→") if len(title) > 75 else title #タイトルが40字過ぎたら省略
print("title:{}".format(title))
photoURL = item.imageurl.large.string #画像URL
print("photoURL:{}".format(photoURL))
#動画によってはサンプル動画がない。ない場合エラーになるので、tryで囲む
try:
videoURL = item.samplemovieurl.size_476_306.string
print("videoURL:{}".format(videoURL))
#ツイート内容
content = title + "|" + videoURL
print("ツイート内容:{}".format(content))
#DMMから取得した画像を一度ローカルに保存
request = requests.get(photoURL, stream=True)
filename = "temp.jpg"
if request.status_code == 200:
print("status_code == 200")
with open(filename, 'wb') as image:
for chunk in request:
image.write(chunk)
api.update_with_media(filename, status = content)
print("ツイートに成功しました")
os.remove(filename)
else:
print("画像をダウンロードできませんでした")
except Exception as e:
print(e)
print("プログラムを終了しました")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment