本文整理汇总了Python中twython.Twython.upload_media方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.upload_media方法的具体用法?Python Twython.upload_media怎么用?Python Twython.upload_media使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.upload_media方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def tweet():
with open(file_name) as file:
accounts = file.readlines()
if len(accounts) == 0:
print 'no accounts. Please add an account before tweeting'
else:
has_media = raw_input('Does the tweet you want to post contains any media file?\ny: yes\nn: no\n')
media_path = None
if has_media is 'y':
media_path = raw_input('Paste the path to your media file here\n').rstrip(' \r\n')
for account in accounts:
screen_name = account.split(',')[0]
oauth_token = account.split(',')[1]
oauth_token_secret = account.split(',')[2].rstrip('\n')
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
tweet_text = raw_input('Type in the text of tweet for account ' + screen_name + '\n')
if media_path is not None:
media = open(media_path, 'rb')
response = twitter.upload_media(media = media)
try:
twitter.update_status(status = tweet_text, media_ids=[response['media_id']])
print ('tweet for account ' + screen_name + ' posted')
except TwythonError as error:
print (error)
else:
try:
twitter.update_status(status = tweet_text)
print ('tweet for account ' + screen_name + ' posted')
except TwythonError as error:
print (error)
示例2: send
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def send(message, picture):
# Build Twython API
api = Twython(settings.CONSUMER_KEY,
settings.CONSUMER_SECRET,
settings.ACCESS_KEY,
settings.ACCESS_SECRET)
#time_now = time.strftime("%H:%M:%S") # get current time
#date_now = time.strftime("%d/%m/%Y") # get current date
#tweet_txt = "Photo captured by @twybot at " + time_now + " on " + date_now
try:
# Send text message with picture
if picture is not None:
media_status = api.upload_media(media=picture)
api.update_status(media_ids=[media_status['media_id']], status=message)
# Send text message
else:
api.update_status(status=message)
except TwythonError, error:
print error
示例3: Uploader
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
class Uploader(object):
def __init__(self, folder="."):
self.folder = folder
self.already_uploaded_file = "uploaded.txt"
self.already_uploaded = []
self.image_format_extension = ".jpg"
# Uncomment and fill with your details
# app_key = "your key"
# app_secret = "your secret"
# oauth_token = "your otoken"
# oauth_token_secret = "your osecret"
self.twitter = Twython(app_key=app_key,
app_secret=app_secret,
oauth_token=oauth_token,
oauth_token_secret=oauth_token_secret)
self.load_already_uploaded()
def upload(self, new_file):
if not self.is_already_uploaded(new_file):
with open(new_file, "rb") as image:
image_ids = self.twitter.upload_media(media=image)
self.twitter.update_status(status="hello this is a status #testing_smth",
media_ids=[image_ids["media_id"]])
self.write_to_uploaded(new_file=new_file)
return True
else:
print "Already uploaded!"
return False
def load_already_uploaded(self):
try:
with open(self.already_uploaded_file, "r") as log_file:
con = log_file.read()
self.already_uploaded = [x.strip() for x in con.split("\n")]
except IOError as err:
pass
def write_to_uploaded(self, new_file):
with open(self.already_uploaded_file, "a+") as log_file:
log_file.write("{0}\n".format(new_file))
self.load_already_uploaded()
def is_already_uploaded(self, new_file):
self.load_already_uploaded()
if new_file.strip() in self.already_uploaded:
return True
return False
def run_watcher(self):
try:
while "pigs" != "fly":
all_files = os.listdir(self.folder)
for f in all_files:
if f.endswith(self.image_format_extension):
if self.upload(new_file=os.path.join(self.folder, f)):
print "Uploaded '{0}'".format(f)
time.sleep(1)
except KeyboardInterrupt as err:
print "Thank you Exiting..."
示例4: tweet_string
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def tweet_string(message, log, media=None):
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
retries = 0
while retries < 5:
log.setLevel(logging.ERROR)
try:
if media:
photo = open(media, 'rb')
media_ids = twitter.upload_media(media=photo)
twitter.update_status(status=message.encode('utf-8').strip(), media_ids=media_ids['media_id'])
else:
twitter.update_status(status=message.encode('utf-8').strip())
break
except TwythonAuthError, e:
log.setLevel(old_level)
log.exception(" Problem trying to tweet string")
twitter_auth_issue(e)
return
except:
示例5: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def main():
APP_KEY, APP_SECRET = read_keys()
OAUTH_TOKEN, OAUTH_TOKEN_SECRET = read_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
commonsurl = 'https://commons.wikimedia.org/wiki/User:Emijrp/Realismo_socialista?action=raw'
raw = getURL(url=commonsurl)
works = re.findall(r'(?im)File:([^\|\n]+?)\|([^\n]+?)\n', raw)
random.shuffle(works)
selectedwork = works[0]
print(selectedwork)
imagename = selectedwork[0]
desc = selectedwork[1]
x, xx = getCommonsMD5(imagename)
imgurl = 'https://commons.wikimedia.org/wiki/File:%s' % (re.sub(' ', '_', imagename))
imgurl2 = 'https://upload.wikimedia.org/wikipedia/commons/%s/%s/%s' % (x, xx, urllib.parse.quote(re.sub(' ', '_', imagename)))
urllib.request.urlretrieve(imgurl2, 'realismosocialista-tempimage.jpg')
img = open('realismosocialista-tempimage.jpg', 'rb')
status = '#RealismoSocialista\n\n%s\n\n%s' % (desc, imgurl)
print(status)
response = twitter.upload_media(media=img)
raw = twitter.update_status(status=status, media_ids=[response['media_id']])
tweetid = raw['id_str']
print('Status:',status)
print('Returned ID:',tweetid)
示例6: post_neuralga
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def post_neuralga(cf, img, text):
"""Post a Neuralga image and text to the twitter account.
Args:
cf (dict): config file
img (str): image file
text (str): text part of tweet
Returns:
status (bool): True if the post was successful
"""
app_key = cf["app_key"]
app_secret = cf["app_secret"]
oauth_token = cf["oauth_token"]
oauth_token_secret = cf["oauth_token_secret"]
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
imgfile = os.path.join(cf["images"], img)
print("Posting %s" % imgfile)
if len(text) > 130:
text = text[:129]
with open(imgfile, "rb") as ih:
response = twitter.upload_media(media=ih)
out = twitter.update_status(status=text, media_ids=response["media_id"])
print("Posted")
return True
return False
示例7: xTwitter
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
class xTwitter(object):
def __init__(self):
self.configuration = ConfigParser.ConfigParser()
self.directorycurrent = os.path.dirname(os.path.realpath(__file__))
self.configuration.read(self.directorycurrent + '/configuration/credentials.config')
self.consumer_key = self.configuration.get('twitter','consumer_key')
self.consumer_secret = self.configuration.get('twitter','consumer_secret')
self.access_token = self.configuration.get('twitter','access_token')
self.access_token_secret = self.configuration.get('twitter','access_token_secret')
self.twythonid = Twython(self.consumer_key, \
self.consumer_secret, \
self.access_token, \
self.access_token_secret)
def tweet(self, status=""):
self.twythonid.update_status(status=status)
def pweet(self, status="", media=None):
photo = open(media,'rb')
response = self.twythonid.upload_media(media=photo)
self.twythonid.update_status(status=status, media_ids=[response['media_id']])
def vweet(self, status="", media=None):
video = open(media, 'rb')
response = self.twythonid.upload_video(media=video, media_type='video/mp4')
self.twythonid.update_status(status=status, media_ids=[response['media_id']])
示例8: generate_graphs
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def generate_graphs():
for pair_config in KEYS:
media_ids = []
tweet = ''
for interval in ['day', 'week', 'month', 'year']:
text = output_graph(interval, pair_config)
if not text:
continue
tweet += text
if args.tweeting and pair_config['APP_KEY']:
twitter = Twython(pair_config['APP_KEY'], pair_config['APP_SECRET'],
pair_config['OAUTH_TOKEN'], pair_config['OAUTH_TOKEN_SECRET'])
photo = open('{0}-{1}.png'.format(interval, pair_config['screen_name']), 'rb')
try:
response = twitter.upload_media(media=photo)
except TwythonError:
client.captureException()
return True
media_ids += [response['media_id']]
time.sleep(10)
if args.tweeting and pair_config['APP_KEY']:
twitter = Twython(pair_config['APP_KEY'], pair_config['APP_SECRET'],
pair_config['OAUTH_TOKEN'], pair_config['OAUTH_TOKEN_SECRET'])
try:
for status in twitter.get_user_timeline(screen_name=pair_config['screen_name']):
twitter.destroy_status(id=status['id_str'])
twitter.update_status(status=tweet, media_ids=media_ids)
except TwythonError:
client.captureException()
示例9: post_tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def post_tweet(status, media_fn):
"""Post media and an associated status message to Twitter."""
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
upload_response = twitter.upload_media(media=open(media_fn, 'rb'))
response = twitter.update_status(status=status,
media_ids=upload_response['media_id'])
log.info(response)
return twitter, response
示例10: tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def tweet(temp, lux):
twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
toTweet = 'Current condition: ' + str(int(float(temp))) + u'\N{DEGREE SIGN}' + 'C ' \
+ str(int(float(lux))) + ' lux'
photo = open('image.jpg','rb')
#twitter.update_status_with_media(media=photo, status=toTweet)
response = twitter.upload_media(media=photo)
twitter.update_status(status=toTweet, media_ids=[response['media_id']])
示例11: image_Tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def image_Tweet(status_update): #this function uploads a photo to twitter
photo = open(filename, 'rb')
twitter = Twython(config["app_key"],config["app_secret"],config["oauth_token"],config["oauth_token_secret"])
response = twitter.upload_media(media = photo)
toTweet = tweetList[random.randint(0,len(tweetList))-1]
print toTweet
try:
twitter.update_status(status = toTweet, media_ids=[response['media_id']])
except TwythonError as e:
print e
示例12: PublicarTwitter
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def PublicarTwitter(uri):
try:
twitter = Twython(settings.TW_KEY, settings.TW_SECRET, settings.TW_TOKEN, settings.TW_TOKEN_SECRET)
image_from_url = cStringIO.StringIO(urllib.urlopen(uri).read())
image_id = twitter.upload_media(media=image_from_url)
twitter.update_status(status=descripcion, media_ids=image_id['media_id'])
except Exception, e:
logging.error(e)
示例13: tweet
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def tweet(odict, creature):
logger = logging.getLogger()
logger.info("Posting %s as %s..." % (creature.getImagePath(), creature.getFullPageURL()))
creds = Location.getJsonModule().load(open(Location.getInstance().toAbsolutePath(".twitter.json")))
twitter = Twython(creds["app"], creds["app_secret"], creds["token"], creds["token_secret"])
photo = open(creature.getImagePath(), 'rb')
if (not odict.get("no-op", False)):
response = twitter.upload_media(media=photo)
response = twitter.update_status(status=creature.getFullPageURL(), media_ids=[response['media_id']])
logger.info("Posted as %s." % (response["id_str"]))
示例14: twitter_post
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def twitter_post(consumer_key, consumer_secret, access_token_key, access_token_secret, title, description, siteurl, picture_path):
encoding = "utf-8"
# message = title + " " + description + " " + siteurl
message = title
twitter = Twython(app_key=consumer_key, app_secret=consumer_secret, oauth_token=access_token_key, oauth_token_secret=access_token_secret)
image_open = open(picture_path, 'rb')
image_ids = twitter.upload_media(media=image_open)
result = twitter.update_status(status=message,media_ids=[image_ids['media_id']])
image_open.close()
return result
示例15: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import upload_media [as 别名]
def main():
APP_KEY, APP_SECRET = read_keys()
OAUTH_TOKEN, OAUTH_TOKEN_SECRET = read_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
month2name = {'01': 'enero', '02': 'febrero', '03': 'marzo', '04': 'abril', '05': 'mayo', '06': 'junio',
'07': 'julio', '08': 'agosto', '09': 'septiembre', '10': 'octubre', '11': 'noviembre', '12': 'diciembre' }
d = datetime.datetime.now()
today = '%s de %s' % (int(d.strftime('%d')), month2name[d.strftime('%m')])
today_ = re.sub(' ', '_', today)
raw = urllib.request.urlopen('https://15mpedia.org/w/index.php?title=Especial:Ask&q=[[persona+represaliada%%3A%%3A%%2B]]+[[represor%%3A%%3AFranquismo]]+[[represi%%C3%%B3n%%3A%%3AFusilamiento]]+[[fecha+string%%3A%%3A~*%%2F%s%%2F%s]]&p=format%%3Dbroadtable%%2Flink%%3Dall%%2Fheaders%%3Dshow%%2Fsearchlabel%%3D-26hellip%%3B-20siguientes-20resultados%%2Fclass%%3Dsortable-20wikitable-20smwtable&po=%%3FFecha+string%%0A&limit=500&eq=no' % (d.strftime('%m'), d.strftime('%d'))).read().decode('utf-8')
m = re.findall(r'(?im)<td><a href="[^<>]*?" title="[^<>]*?">([^<>]*?)</a></td>\s*<td class="Fecha-string">(\d\d\d\d)[^<>]+?</td>', raw)
fusilados = []
for i in m:
fusilados.append([i[1],i[0]])
fusilados.sort()
if not fusilados:
sys.exit()
#generar imagen
fusiladosnum = len(fusilados)
high = 25
img = Image.new('RGB', (500, fusiladosnum*high+220), (255, 255, 200))
fonttitle = ImageFont.truetype("OpenSans-Regular.ttf", 25)
fonttext = ImageFont.truetype("OpenSans-Regular.ttf", 18)
fontfooter = ImageFont.truetype("OpenSans-Regular.ttf", 15)
d = ImageDraw.Draw(img)
d.text((20, high), 'Represión franquista', fill=(255, 0, 0), font=fonttitle)
d.text((20, high*3), 'Estas personas fueron fusiladas un %s:' % (today), fill=(0, 0, 0), font=fonttext)
c = 0
for year, name in fusilados:
d.text((30, high*c+110), '%d) %s (%s)' % (c+1, name, year), fill=(0, 0, 0), font=fonttext)
c += 1
d.text((20, high*c+90+high), 'Que sus nombres no caigan en el olvido.', fill=(0, 0, 255), font=fonttext)
d.text((260, high*c+130+high), 'Fuente: Memoria y Libertad', fill=(0, 0, 0), font=fontfooter)
d.text((260, high*c+150+high), 'Elaboración gráfica: 15Mpedia', fill=(0, 0, 0), font=fontfooter)
img.save(imagename)
#tuitear imagen
img = open(imagename, 'rb')
status = 'Un %s el franquismo los fusiló https://15mpedia.org/wiki/%s Que sus nombres no caigan en el olvido #memoria' % (today, today_)
print(status)
response = twitter.upload_media(media=img)
raw = twitter.update_status(status=status, media_ids=[response['media_id']])
tweetid = raw['id_str']
print('Status:',status)
print('Returned ID:',tweetid)