我用tweepy自动发布了一个URL列表。然而,如果我的名单太长(它可以根据不同的推特),我是不允许的。当内容太长时,tweepy是否可以创建一个tweet线程?我的tweepy代码看起来如下:
import tweepy
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'],
cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'],
cfg['access_token_secret'])
return tweepy.API(auth)
def main():
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "VALUE",
"consumer_secret" : "VALUE",
"access_token" : "VALUE",
"access_token_secret" : "VALUE"
}
api = get_api(cfg)
tweet = "Hello, world!"
status = api.update_status(status=tweet)
# Yes, tweet is called 'status' rather confusing
if __name__ == "__main__":
main()发布于 2018-12-16 00:41:38
您的代码与您试图解决的问题无关。main()不仅似乎不接受任何争论(推特文本?)但你并没有显示出你目前是如何处理这件事的。考虑以下代码:
import random
TWEET_MAX_LENGTH = 280
# Sample Tweet Seed
tweet = """I'm using tweepy to automatically tweet a list of URLs. However if my list is too long (it can vary from tweet to tweet) I am not allowed."""
# Creates list of tweets of random length
tweets = []
for _ in range(10):
tweets.append(tweet * (random.randint(1, 10)))
# Print total initial tweet count and list of lengths for each tweet.
print("Initial Tweet Count:", len(tweets), [len(x) for x in tweets])
# Create a list for formatted tweet texts
to_tweet = []
for tweet in tweets:
while len(tweet) > TWEET_MAX_LENGTH:
# Take only first 280 chars
cut = tweet[:TWEET_MAX_LENGTH]
# Save as separate tweet to do later
to_tweet.append(cut)
# replace the existing 'tweet' variable with remaining chars
tweet = tweet[TWEET_MAX_LENGTH:]
# Gets last tweet or those < 280
to_tweet.append(tweet)
# Print total final tweet count and list of lengths for each tweet
print("Formatted Tweet Count:", len(to_tweet), [len(x) for x in to_tweet])为了便于解释,尽可能地把它分开。最重要的是,我们可以从一个文本列表开始,将其用作tweet。变量TWEET_MAX_LENGTH定义了每个tweet将被分割的位置,以允许多个tweet。
to_tweet列表将包含每个tweet,按照初始列表的顺序,扩展为多个<= TWEET_MAX_LENGTH长度字符串的tweet。
您可以使用该列表输入实际发布的tweepy函数。这种方法非常巧妙,不需要对维护分裂的tweet序列进行任何检查。这可能是一个问题,但也是一个单独的问题,这取决于你如何实现最后的推文功能。
https://stackoverflow.com/questions/53798094
复制相似问题