Skip to main content
 首页 » 编程设计

python之Tweepy:来自文件夹的自动推文图片

2024年12月31日7yjmyzz

新来的,也是第一次发帖。

我目前正在尝试使用 Tweepy。到目前为止,我已经成功地设置了它,并且能够在推特上发布单张图片。所以代码运行正常。

这样做的目的是因为我运行的帐户只发布图片,没有实际的文本推文。

我有一个包含 100 张图像的文件夹,我每天都会浏览这些图像来发推文并发现了 tweepy,是否可以告诉 Tweepy 进入图像文件夹并随机选择 1 个或任意 1 个?我进行了广泛的搜索,但根本找不到任何东西。

非常感谢所有帮助!

这是我目前获得的代码 (python-2)。

import tweepy 
from time import sleep 
 
consumer_key = 'Removed' 
consumer_secret = 'Removed' 
access_token = 'Removed' 
access_token_secret = 'Removed' 
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
 
api = tweepy.API(auth) 
 
api.update_with_media('Image') 
sleep(900) 
 
print 'Tweeted!' 

请您参考如下方法:

鉴于您的目录中有 100 张照片,我假设您要迭代 100 次。我希望你不介意,我冒昧地将你的 twitter api 实例化/auth 放在一个函数中(为了可重用性:))。对于 getPathsFromDir() 函数,我从 processing.org 中改编了 GoToLoop 的解决方案。 .您可能想查看链接引用/链接以获取更多详细信息。此外,练习将 api.update[_with_media,_status]() 放在 try - except block 中。您永远不会知道 api 会引发奇怪的异常。我希望我的实现对你有用!

import tweepy 
from time import sleep 
 
folderpath = "/path/to/your/directory/" 
def tweepy_creds(): 
    consumer_key = 'Removed' 
    consumer_secret = 'Removed' 
    access_token = 'Removed' 
    access_token_secret = 'Removed' 
 
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 
 
    return tweepy.API(auth) 
 
def getPathsFromDir(dir, EXTS="extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp"): 
    return this.listPaths(folder, EXTS) 
 
def tweet_photos(api): 
    imagePaths = getPathsFromDir(this.dataPath(folderpath)) 
    for x in imagePaths: 
        status = "tweet text here" 
        try: 
            api.update_with_media(filename=x,status=status) 
            print "Tweeted!" 
            sleep(900) 
        except Exception as e: 
            print "encountered error! error deets: %s"%str(e) 
            break 
 
if __name__ == "__main__": 
    tweet_photos(tweepy_creds()) 

/组织