Skip to content

Instantly share code, notes, and snippets.

@hapo31
Created December 14, 2015 16:04
Show Gist options
  • Save hapo31/fb6e1db05c8bfba1a7e6 to your computer and use it in GitHub Desktop.
Save hapo31/fb6e1db05c8bfba1a7e6 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import re
import datetime
import tweepy
#自分で作って
import config
class MyStreamListener(tweepy.StreamListener):
def __init__(self, auth):
super(MyStreamListener, self).__init__(api=tweepy.API(auth))
self.repatter = re.compile(config.updatename_regex)
self.user_history = { "": UsesCount()}
def on_status(self, status):
if(self.repatter.match(status.text)):
try:
if(self.rec_tweet.id == status.id):
return False
except AttributeError:
pass
#ツイートのID
tweetid = status.id
#ツイートしたユーザーのScreenName
tweetuser_screenname = status.author.screen_name
newname = ""
tweetstr = ""
if (tweetuser_screenname not in self.user_history or self.user_history[tweetuser_screenname].Use()):
#新しく設定する名前
newname = status.text
#成功時のツイート本文
tweetstr = "@%s 我が名は%sである!" % (tweetuser_screenname, newname)
if tweetuser_screenname not in self.user_history:
self.user_history[tweetuser_screenname] = UsesCount()
else:
#使いすぎマンにはおしおき
tweetstr = "@%s 使いすぎじゃボケ" % (tweetuser_screenname)
newname = ""
try:
if newname != "":
print("@%s: %s => %s" % (tweetuser_screenname, self.api.me().name, newname))
self.api.update_profile(name=newname)
self.rec_tweet = self.api.update_status(status = tweetstr, in_reply_to_status_id = tweetid)
except TweepError as e:
print(e.message[0]['code'] + ":" + e.message[0])
return False
return True
def on_error(self, status):
print(status)
class UsesCount(object):
def __init__(self):
self.first_time = datetime.datetime.now()
self.last_time = datetime.datetime.now()
self.use_count = 1
def Use(self):
self.use_count += 1
self.last_time = datetime.datetime.now()
#10分以内の5回以上の使用を禁ずる
if (self.last_time - self.first_time).seconds <= 10 * 60:
if self.use_count > 5:
return False
else:
self.first_time = datetime.datetime.now()
self.use_count = 0
return True
def Reset(self):
self.__init__()
if __name__ == '__main__':
auth = tweepy.OAuthHandler(
consumer_key = config.consumer_key,
consumer_secret = config.consumer_secret)
auth.set_access_token(config.access_token, config.access_secret)
mystream = MyStreamListener(auth=auth)
stream = tweepy.Stream(auth=auth, listener=mystream)
stream.userstream()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment