Twitter API

提供: socialakiba wiki
移動: 案内検索
# -*- coding:utf-8 -*-                                                                                                                                            

from requests_oauthlib import OAuth1Session
import json
from datetime import datetime
now = datetime.now()

user = "xxxxxxxxxxxxxxxxxxxxxxxxx"

oauth = OAuth1Session(
	'xxxxxxxxxxxxxxxxxxxxxxxxx',# consumer key
	'xxxxxxxxxxxxxxxxxxxxxxxxx',# consumer key secret
	'xxxxxxxxxxxxxxxxxxxxxxxxx',# access token
	'xxxxxxxxxxxxxxxxxxxxxxxxx',# access token secret
)

def check_error(response):
	if response.status_code != 200:
		print("Error code: %d" %(response.status_code))
		return True
	return False

def get_ids(req):
	response = oauth.get("https://api.twitter.com/1.1/" + req + "/ids.json?", params = {
		"screen_name": user,
		"count": "5000",
	})
	if(check_error(response)):
		return
	return set(json.loads(response.text)['ids'])

def show_user(id):
	response = oauth.get("https://api.twitter.com/1.1/users/show.json?", params = {
		"user_id": id,
		"include_entities": "false",
	})
	if(check_error(response)):
		return
	parsed = json.loads(response.text)
	print('<li><img src="' + parsed['profile_image_url'] + '">')
	print(parsed['name'])
	print('(<a href="' + 'http://twitter.com/' + parsed['screen_name'] + '">' + parsed['screen_name'] + "</a>) ")
	if(parsed['protected']):
		print('<font color="green">鍵</font>')
	if(parsed['statuses_count'] == 0):
		print('<font color="magenta">零</font>')
	elif(parsed['statuses_count'] < 100):
		print('<font color="cyan">少</font>')
	followers = parsed['followers_count']
	friends = parsed['friends_count']
	red = 0
	blue = 0
	val = 40 * followers /(friends + 1)
	if(val > 0):
		red = val
		if(red > 255):
			red = 255
	elif(val < 0):
		blue = - val
		if(blue > 255):
			blue = 255
	print('<span style="color: rgb(' + str(int(red)) + ',0,' + str(int(blue)) + ')">' + str(friends) + '/' + str(followers) + '</span> ')
	
	created_at = datetime.strptime(parsed['created_at'], '%a %b %d %H:%M:%S %z %Y')
	color = "black"
	if(now.year == created_at.year):
		color = "#005500"
	print('<font color="' + color + '">' + parsed['created_at'] + "</font> ")
	print(parsed['location'] + " ")
	print(parsed['description'])
	print('<br clear="all">')

followers = get_ids('followers')
friends = get_ids('friends')
following_but_not_followed = list(friends - followers)
not_following_but_followed = list(followers - friends)

print("<html><head><style>")
print("img { vertical-align: text-top; width: 64px; float: left; }")
print("</style></head><body>")

print("<h1>" + user + " following but not followed by</h1><ol>")
for id in following_but_not_followed:
	show_user(id)

print("</ol><h1>" + user + " not following but followed by</h1><ol>")
for id in not_following_but_followed:
	show_user(id)

print("</ol></body></html>")