6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Whileで繰り返し。ターミナルからTweetしたり検索するスクリプト

6
Posted at

OAuth1Sessionを使ってターミナルからツイートしたり検索したりというスクリプト。

words = raw_input(u"input-tweet: ")
search_words = raw_input(u"Keyword?: ")

両方の要素が空である場合にループを抜けます。

ターミナルからツイートするのは意外と便利なのかもしれません。

twform.py

# !/user/bin/env python
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
import json
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)


while True:
	
	words = raw_input(u"input-tweet: ")
	search_words = raw_input(u"Keyword?: ")

	C_KEY = "************************************"
	C_SECRET = "************************************"
	A_KEY = "************************************"
	A_SECRET = "************************************"


	def Post_msg():
		url = "https://api.twitter.com/1.1/statuses/update.json"
		params = {"status": words,"lang": "ja"}
		tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
		req = tw.post(url, params = params)
		if req.status_code == 200:
			print "Success! Your Tweet: ", unicode(words, "utf-8")
		else:
			print req.status_code
		return Post_msg

	def Limit_Status():
		url = "https://api.twitter.com/1.1/application/rate_limit_status.json"
		params = {}
		tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
		req = tw.get(url, params = params)
		if req.status_code == 200:
			limit = req.headers["x-rate-limit-remaining"]
			print ("API remain: " + limit)
		return Limit_Status
	
	def Search_words():
		url = "https://api.twitter.com/1.1/search/tweets.json?"
		params = {
				"q": unicode(search_words, "utf-8"),
				"lang": "ja",
				"result_type": "recent",
				"count": "20"
				}
		tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
		req = tw.get(url, params = params)
		tweets = json.loads(req.text)
		for tweet in tweets["statuses"]:
			print (tweet["created_at"])
			print (tweet["user"]["screen_name"]), (tweet["user"]["name"])
			print (tweet["text"])
			print "=" * 60
			
		return Search_words
		
	if words:
		Post_msg()
		Limit_Status()
	elif search_words:
		Search_words()
		Limit_Status()
	else:
		break
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?