本文整理匯總了Python中twitter.Api方法的典型用法代碼示例。如果您正苦於以下問題:Python twitter.Api方法的具體用法?Python twitter.Api怎麽用?Python twitter.Api使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twitter
的用法示例。
在下文中一共展示了twitter.Api方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: plugin
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def plugin(srv, item):
srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)
twitter_keys = item.addrs
twapi = twitter.Api(
consumer_key=twitter_keys[0],
consumer_secret=twitter_keys[1],
access_token_key=twitter_keys[2],
access_token_secret=twitter_keys[3]
)
text = item.message[0:138]
try:
srv.logging.debug("Sending tweet to %s..." % (item.target))
res = twapi.PostUpdate(text, trim_user=False)
srv.logging.debug("Successfully sent tweet")
except twitter.TwitterError as e:
srv.logging.error("TwitterError: %s" % e)
return False
except Exception as e:
srv.logging.error("Error sending tweet to %s: %s" % (item.target, e))
return False
return True
示例2: tokenize_random_tweet
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def tokenize_random_tweet(self):
"""
If the twitter library is installed and a twitter connection
can be established, then tokenize a random tweet.
"""
try:
import twitter
except ImportError:
print("Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/")
from random import shuffle
api = twitter.Api()
tweets = api.GetPublicTimeline()
if tweets:
for tweet in tweets:
if tweet.user.lang == 'en':
return self.tokenize(tweet.text)
else:
raise Exception("Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again")
示例3: getLotsOfTweets
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def getLotsOfTweets(searchStr):
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN_KEY = ''
ACCESS_TOKEN_SECRET = ''
api = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET,
access_token_key=ACCESS_TOKEN_KEY,
access_token_secret=ACCESS_TOKEN_SECRET)
#you can get 1500 results 15 pages * 100 per page
resultsPages = []
for i in range(1,15):
print "fetching page %d" % i
searchResults = api.GetSearch(searchStr, per_page=100, page=i)
resultsPages.append(searchResults)
sleep(6)
return resultsPages
示例4: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def __init__(self, slackbot=None):
self.logger = Logger().get_logger()
self.data_handler = DataHandler()
self.api = twitter.Api(
consumer_key=Config.open_api.twitter.CONSUMER_KEY,
consumer_secret=Config.open_api.twitter.CONSUMER_SECRET,
access_token_key=Config.open_api.twitter.ACCESS_TOKEN_KEY,
access_token_secret=Config.open_api.twitter.ACCESS_TOKEN_SECRET,
)
if slackbot is None:
self.slackbot = SlackerAdapter(
channel=Config.slack.channel.get("SNS", "#general")
)
else:
self.slackbot = slackbot
示例5: handle
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def handle(self, *args, **options):
api = twitter.Api(consumer_key=settings.TWITTER_CONSUMER_KEY,
consumer_secret=settings.TWITTER_CONSUMER_SECRET,
access_token_key=settings.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret=settings.TWITTER_ACCESS_TOKEN_SECRET)
for currency_symbol in settings.SOCIAL_NETWORK_SENTIMENT_CONFIG['twitter']:
print(currency_symbol)
results = api.GetSearch("$" + currency_symbol, count=200)
for tweet in results:
if SocialNetworkMention.objects.filter(network_name='twitter', network_id=tweet.id).count() == 0:
snm = SocialNetworkMention.objects.create(
network_name='twitter',
network_id=tweet.id,
network_username=tweet.user.screen_name,
network_created_on=datetime.datetime.fromtimestamp(tweet.GetCreatedAtInSeconds()),
text=tweet.text,
symbol=currency_symbol,
)
snm.set_sentiment()
snm.save()
示例6: catch_up_twitter
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def catch_up_twitter(bridge):
if bridge.twitter_last_id == 0 and bridge.twitter_oauth_token:
# get twitter ID
twitter_api = twitter.Api(
consumer_key=app.config['TWITTER_CONSUMER_KEY'],
consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
access_token_key=bridge.twitter_oauth_token,
access_token_secret=bridge.twitter_oauth_secret,
tweet_mode='extended' # Allow tweets longer than 140 raw characters
)
try:
tl = twitter_api.GetUserTimeline()
except TwitterError as e:
flash(f"Twitter error: {e}")
else:
if len(tl) > 0:
bridge.twitter_last_id = tl[0].id
d = datetime.strptime(tl[0].created_at, '%a %b %d %H:%M:%S %z %Y')
bridge.md.last_tweet = d
else:
bridge.twitter_last_id = 0
bridge.updated = datetime.now()
db.session.commit()
示例7: setUp
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def setUp(self):
moa_config = os.environ.get('MOA_CONFIG', 'TestingConfig')
self.c = getattr(importlib.import_module('config'), moa_config)
self.settings = TSettings()
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
self.l = logging.getLogger()
self.l.setLevel(logging.INFO)
self.api = twitter.Api(
consumer_key=self.c.TWITTER_CONSUMER_KEY,
consumer_secret=self.c.TWITTER_CONSUMER_SECRET,
tweet_mode='extended', # Allow tweets longer than 140 raw characters
# Get these 2 from the bridge
access_token_key=self.c.TWITTER_OAUTH_TOKEN,
access_token_secret=self.c.TWITTER_OAUTH_SECRET,
)
示例8: delete
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def delete(tweetjs_path, since_date, until_date, filters, s, min_l, min_r, dry_run=False):
with io.open(tweetjs_path, mode="r", encoding="utf-8") as tweetjs_file:
count = 0
api = twitter.Api(consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
consumer_secret=os.environ["TWITTER_CONSUMER_SECRET"],
access_token_key=os.environ["TWITTER_ACCESS_TOKEN"],
access_token_secret=os.environ["TWITTER_ACCESS_TOKEN_SECRET"])
destroyer = TweetDestroyer(api, dry_run)
tweets = json.loads(tweetjs_file.read()[25:])
for row in TweetReader(tweets, since_date, until_date, filters, s, min_l, min_r).read():
destroyer.destroy(row["tweet"]["id_str"])
count += 1
print("Number of deleted tweets: %s\n" % count)
sys.exit()
示例9: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def __init__(
self,
consumer_key=None,
consumer_secret=None,
access_token_key=None,
access_token_secret=None,
template=None,
):
super().__init__()
self.logger = logging.getLogger(__name__)
self.twitter_api = twitter.Api(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token_key=access_token_key,
access_token_secret=access_token_secret,
)
self.template = template
示例10: _send_tweet
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def _send_tweet(self, message=None, attachment=None):
consumer_key = self.config['consumer_key']
consumer_secret = self.config['consumer_secret']
access_token = self.config['access_token']
access_token_secret = self.config['access_token_secret']
# logger.info("Tautulli Notifiers :: Sending tweet: " + message)
api = twitter.Api(consumer_key, consumer_secret, access_token, access_token_secret)
try:
api.PostUpdate(message, media=attachment)
logger.info("Tautulli Notifiers :: {name} notification sent.".format(name=self.NAME))
return True
except Exception as e:
logger.error("Tautulli Notifiers :: {name} notification failed: {e}".format(name=self.NAME, e=e))
return False
示例11: load
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def load(self):
filelocation = os.path.join(self.config['basedir'], "tweet.conf")
rc = TweetRc(filelocation)
consumer_key = rc.GetConsumerKey()
consumer_secret = rc.GetConsumerSecret()
access_key = rc.GetAccessKey()
access_secret = rc.GetAccessSecret()
encoding = None
if not consumer_key or not consumer_secret or not access_key or not access_secret:
raise Exception("Could not load twitter config in: " + filelocation)
self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
access_token_key=access_key, access_token_secret=access_secret,
input_encoding=encoding)
示例12: tweet
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def tweet(txt):
if debug:
print "Tweet:", txt
api = twitter.Api(consumer_key='key',
consumer_secret='key',
access_token_key='key',
access_token_secret='key')
if debug:
print "Twitter:", twitter
user_timeline = api.PostUpdate(txt.encode("utf-8"))
if debug:
print "Timeline:", user_timeline
示例13: getTwitterApi
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def getTwitterApi(root_path):
global gloabl_api
if gloabl_api is None:
import twitter
config = configparser.ConfigParser()
config.read(root_path + "/" + "config.ini")
api_key = config.get('Twitter', 'KEY')
api_secret = config.get('Twitter', 'SECRET')
access_token_key = config.get('Twitter', 'TOKEN_KEY')
access_token_secret = config.get('Twitter', 'TOKEN_SECRET')
http = config.get('Proxy', 'HTTP')
https = config.get('Proxy', 'HTTPS')
proxies = {'http': http, 'https': https}
gloabl_api = twitter.Api(api_key, api_secret, access_token_key, access_token_secret, timeout = 15, proxies=proxies)
return gloabl_api
示例14: send_tweet
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def send_tweet(event, context):
"""Post tweet
"""
with open("twitter_credentials.json", "r") as f:
credentials = json.load(f)
t = tw.Api(**credentials)
try:
status = tweet_content()
t.PostUpdate(status=status)
return "Tweeted {}".format(status)
except Exception as e:
return e.message
示例15: get_api
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Api [as 別名]
def get_api(consumer_key, consumer_secret, access_key, access_secret):
api = twitter.Api(consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token_key=access_key,
access_token_secret=access_secret,
sleep_on_rate_limit=True)
return api