2
3

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.

Tweepyを使ってみる[Python2.7]

Posted at

tweepyというPython向けTwitterクライアント見つけたのでいじってみました。
そもそもTwitterを普段使わないので私の場合は作ったところで使いみちが無いのですが。。。

まず、実装してみたものとしては
・トークン発行
・ツイート削除
・片思いである人をフォロー解除又は、フォロー
・特定のアカウントをフォローしているユーザーをフォロー
片思いの定義はここでは
1.自分がフォローしており、相手がフォローしていない状態。
2.相手がフォローしており、自分がフォローをしていない状態。
とします。

それぞれ関数名,処理を説明をします。
deletion(self, id, count=200)

  • id=アカウントid(@XXX)
  • count=件数
    この関数は引数idで指定されたidのツイートを引数countだけ取得し
    削除します。この関数はトークンがidのものと同一である場合動作します。
    当然他人のツイート削除などはできません。

destroy(self, id)

  • id=アカウントid(@XXX)
    この関数は引数idで指定されたidのユーザーが片思い(定義1)であるユーザーのフォローを解除します。

create(self, id)

  • id=アカウントid(@XXX)
    この関数は引数idで指定されたidのユーザーが片思い(定義2)であるユーザーのフォローします。

follow(self, id)

  • id=アカウントid(@XXX)
    この関数は引数idで指定されたidのユーザーをフォローしているユーザーをフォローします。

class Token:
	def __init__(self, consumer_key, consumer_secret):
		self.auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
	def GET(self):
		redirect_url = self.auth.get_authorization_url()
		print "URL: %s" % (str(redirect_url))
		self.auth.get_access_token(raw_input('code: ').strip())
		return [self.auth.access_token, self.auth.access_token_secret]

class Twitter_Class:
	def __init__(self, consumer_key, consumer_secret, access_token, access_secret):
		auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
		auth.set_access_token(access_token, access_secret)
		self.api = tweepy.API(auth)

	def deletion(self, id, count=200):
		try:
			map(self.api.destroy_status, [i.id for i in self.api.user_timeline(id, count=count)])
		except Exception, e:
			print e

	def destroy(self, id):
		try:
			friends_ids = self.api.friends_ids(id)
			followers_ids = self.api.followers_ids(id)
			list_ = []
			for i in friends_ids:
				if not i in followers_ids:
					list_.append(i)
			map(self.api.destroy_friendship, list_)
		except Exception, e:
			print e

	def create(self, id):
		try:
			followers_ids = self.api.followers_ids(id)
			friends_ids = self.api.friends_ids(id)
			list_ = []
			for i in followers_ids:
				if not i in friends_ids:
					list_.append(i)
			map(self.api.create_friendship, list_)
		except Exception, e:
			print e

	def follow(self, id):
		try:
			friends = self.api.friends_ids(id)
			count = 0
			for i in friends:
				if count < 50:
					self.api.create_friendship(i)
				else:
					[time.sleep(18) for i in range(100)]
					count = 0
		except Exception, e:
			print e
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?