twitter全自动发推_我如何在5分钟内自动创建FreeCodeCampers的Twitter列表

twitter全自动发推

by Monica Powell

莫妮卡·鲍威尔(Monica Powell)

我如何在5分钟内自动创建FreeCodeCampers的Twitter列表 (How I automatically created a Twitter List of FreeCodeCampers in 5 minutes)

使用Twython Twitter API包装器将用户添加到Twitter列表 (Using Twython Twitter API wrapper to add users to a Twitter List)

We are going to create a Python script that will automatically search Twitter for individuals who use the #freeCodeCamp hashtag and add them to a Twitter list of “FreeCodeCampers”. Twitter lists are a way to curate a group of individuals on Twitter and collect all of their tweets in a stream, without having to follow each individual accounts. Twitter lists can contain up to 5,000 individual Twitter accounts.

我们将创建一个Python脚本,该脚本将自动在Twitter上搜索使用#freeCodeCamp标签的个人,并将其添加到“ FreeCodeCampers”的Twitter列表中。 Twitter列表是一种在Twitter上策划一组个人并在流中收集其所有tweet的方式,而不必关注每个个人帐户。 Twitter列表最多可以包含5,000个单独的Twitter帐户。

We can accomplish this by doing the following:

我们可以通过执行以下操作来完成此任务:

  • Installing the necessary Python packages

    安装必要的Python软件包
  • Registering an application with Twitter

    在Twitter上注册应用程序
  • Generating and accessing our Twitter credentials

    生成和访问我们的Twitter凭证
  • Making Twitter Search and List API calls

    进行Twitter 搜索列出 API调用

So lets get started.

因此,让我们开始吧。

1.安装必要的Python软件包 (1. Installing the necessary Python packages)

Create a file named addToFreeCodeCampList.py, that will contain our main script and then import two Python modules into this file:

创建一个名为addToFreeCodeCampList.py的文件,该文件将包含我们的主脚本,然后将两个Python模块导入该文件:

  • Import Config:In the same directory as ouraddToFreeCodeCampList.py script, create a file named config.py that stores our confidential Twitter API credentials. We are going to import our API credentials from that file into our addToFreeCodeCampList.py script by including the line import config. Twitter requires a valid API key, API secret, access token and token secret for all API requests.

    导入配置:在与addToFreeCodeCampList.py脚本相同的目录中,创建一个名为config.py的文件,该文件存储我们的机密Twitter API凭据。 我们将通过包含行import config将API凭据从该文件导入到addToFreeCodeCampList.py脚本中。 Twitter需要为所有API请求提供有效的API密钥,API密码,访问令牌和令牌密码。

  • Import Twython:Twython is a Python wrapper for the Twitter API that makes it easier to programmatically access and manipulate data from Twitter using Python. We can import Twython with the following line from twython import Twython, TwythonError.

    导入Twython: Twython是Twitter API的Python包装器,可以更轻松地使用Python以编程方式访问和操作Twitter的数据。 我们可以from twython import Twython, TwythonError的以下行from twython import Twython, TwythonError

Your addToFreeCodeCampList.py script should now look like this.

您的addToFreeCodeCampList.py脚本现在应如下所示。

import configfrom twython import Twython, TwythonError

2.在Twitter上注册应用程序 (2. Registering an application with Twitter)

We need to authenticate our application in order to access the Twitter API. You need to have a Twitter account in order to access Twitter’s Application Management site. The Application Management site is where you can view/edit/create API keys, API secrets, access tokens and token secrets.

我们需要对我们的应用程序进行身份验证才能访问Twitter API。 您需要具有Twitter帐户才能访问Twitter的Application Management网站 。 您可以在“应用程序管理”站点上查看/编辑/创建API密钥,API机密,访问令牌和令牌机密。

  1. In order to create these credentials, we need to create a Twitter application. Go to the Application Management site and click on “Create New App”. This should direct you to a page that looks similar to the one below.

    为了创建这些凭据,我们需要创建一个Twitter应用程序。 转到应用程序管理站点,然后单击“创建新应用程序”。 这应该将您定向到与以下页面相似的页面。

2. Fill out of the required fields and click on “Create your Twitter application”. You will then be redirected to a page with details about your application.

2.填写必填字段,然后单击“创建您的Twitter应用程序”。 然后,您将被重定向到包含有关您的应用程序详细信息的页面。

3.生成和访问我们的Twitter凭证 (3. Generating and accessing our Twitter credentials)

  1. Click on the tab that says “Keys and Access Tokens” and copy the “Consumer Key (API Key)” and “Consumer Secret (API Secret)” into the config.py file

    单击显示“密钥和访问令牌”的选项卡,然后将“用户密钥(API密钥)”和“用户密钥(API密钥)”复制到config.py文件中

  2. Scroll down to the bottom of the page and click on “Create my access token”. Copy the generated “Access Token” and “Access Token Secret” into the config.py file.

    向下滚动到页面底部,然后单击“创建我的访问令牌”。 将生成的“访问令牌”和“访问令牌密钥”复制到config.py文件中。

For reference, I recommend formatting your config.py similar to the file below:

作为参考,我建议将config.py格式化为类似于以下文件的格式:

3. Currently, all of our Twitter credentials live inside our config.py file and we’ve imported config into our addToFreeCodeCampList.py file. However, we have not actually passed any information between the files.

3.当前,我们所有的Twitter凭据都位于config.py文件中,并且我们已将config导入到addToFreeCodeCampList.py文件中。 但是,我们实际上并未在文件之间传递任何信息。

Let’s change that by creating a Twython object and passing in the necessary API key, API secrets and API token from our config.py file with the following:

让我们通过创建一个Twython对象并使用以下内容从config.py文件中传入必要的API密钥,API机密和API令牌来更改此设置:

twitter = Twython(config.api_key, config.api_secret, config.access_token, config.token_secret)`

The addToFreeCodeCampList.py file should now look similar to this:

现在, addToFreeCodeCampList.py文件应类似于以下内容:

import config
from twython import Twython, TwythonError
# create a Twython object by passing the necessary secret passwordstwitter = Twython(config.api_key, config.api_secret, config.access_token, config.token_secret)

4.进行Twitter搜索和列出API调用 (4. Making Twitter Search and List API calls)

  1. Let’s make an API call to search Twitter and return the 100 most recent tweets (excluding retweets) that contain “#freeCodeCamp”:

    让我们进行API调用来搜索Twitter,并返回包含“ #freeCodeCamp”的100条最新推文(不包括推文):
# return tweets containing #FreeCodeCampresponse = twitter.search(q=’”#FreeCodeCamp” -filter:retweets’, result_type=”recent”, count=100)

2. Look at the tweets returned from our search

2.查看我们的搜索返回的推文

# for each tweet returned from search of #FreeCodeCampfor tweet in response[‘statuses’]: # print tweet info if needed for debugging print(tweet) print(tweet[‘user’][‘screen_name’])

A single tweet returned by this API call looks like this in JSON:

此API调用返回的一条推文在JSON中如下所示:

{'created_at': 'Sun Dec 24 00:23:05 +0000 2017', 'id': 944725078763298816, 'id_str': '944725078763298816', 'text': 'Why is it so hard to wrap my head around node/express. Diving in just seems so overwhelming. Templates, forms, post… https://t.co/ae52rro63i', 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/ae52rro63i', 'expanded_url': 'https://twitter.com/i/web/status/944725078763298816', 'display_url': 'twitter.com/i/web/status/9…', 'indices': [117, 140]}]}, 'metadata': {'iso_language_code': 'en', 'result_type': 'recent'}, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 48602981, 'id_str': '48602981', 'name': 'Matt Huberty', 'screen_name': 'MattHuberty', 'location': 'Oxford, MS', 'description': "I'm a science and video game loving eagle scout with a Microbio degree from UF. Nowadays I'm working on growing my tutoring business at Ole Miss. Link below!", 'url': 'https://t.co/dfuqNNoBYZ', 'entities': {'url': {'urls': [{'url': 'https://t.co/dfuqNNoBYZ', 'expanded_url': 'http://www.thetutorcrew.com', 'display_url': 'thetutorcrew.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 42, 'friends_count': 121, 'listed_count': 4, 'created_at': 'Fri Jun 19 04:00:44 +0000 2009', 'favourites_count': 991, 'utc_offset': -28800, 'time_zone': 'Pacific Time (US & Canada)', 'geo_enabled': False, 'verified': False, 'statuses_count': 199, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/777294001598758912/FVOIrnb4_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/777294001598758912/FVOIrnb4_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/48602981/1431670621', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'lang': 'en'}MattHuberty

and like this on Twitter.com:

并在Twitter.com上这样:

3. Add Tweet-ers to our Twitter list

3.将推特添加到我们的Twitter列表

In order to add the author of the tweet to our Twitter list we need the username associated with the tweet tweet['user']['screen_name']

为了将推文的作者添加到我们的Twitter列表中,我们需要与推tweet['user']['screen_name']相关联的用户名

Let’s try to add the users from these tweets to our Twitter list “FreeCodeCampers”. I created my Twitter list at https://twitter.com/waterproofheart/lists/freecodecampers which means for my script the slug is freecodecampers and the owner_screen_name is mine, waterproofheart.

让我们尝试将这些推文中的用户添加到我们的Twitter列表“ FreeCodeCampers”中。 我在https://twitter.com/waterproofheart/lists/freecodecampers上创建了我的Twitter列表,这意味着对于我的脚本而言, owner_screen_namefreecodecampers ,而owner_screen_name是我的防水心。

for tweet in response['statuses']:
# try to add each user who has tweeted the hashtag to the list try: twitter.add_list_member(slug=’YOUR_LIST_SLUG’, owner_screen_name=’YOUR_USERNAME’, screen_name= tweet[‘user’][‘screen_name’])
#if for some reason Twython can't add user to the list print exception messageexcept TwythonError as e: print(e)

You can create your own Twitter list by navigating to your Twitter profile, clicking on “Lists” on desktop and clicking on the right hand side to “Create new list”. View the official Twitter List documentation for more information.

您可以导航到您的Twitter个人资料,单击桌面上的“列表”,然后单击右侧的“创建新列表”来创建自己的Twitter列表。 查看官方的Twitter List文档以获取更多信息。

You can test your script by running python addToFreeCodeCampList.py in the terminal.

您可以通过在终端中运行python addToFreeCodeCampList.py来测试脚本。

My final script looks like this:

我的最终脚本如下所示:

This script can be set to automatically run locally or remotely via a cron job which allows tasks to be performed at a set schedule.

可以将此脚本设置为通过cron作业自动在本地或远程运行,从而可以按设定的时间表执行任务。

Feel free to comment below or tweet at me if you have any questions, suggestions or want to share how you modified this script!

如果您有任何疑问,建议或想分享您如何修改此脚本,请下面发表评论或向我发送推特

If you enjoyed reading this article consider tapping the clap button ?. Wanna see more of my work? Check out my GitHubto view my code and learn more about my development experience at http://aboutmonica.com.

如果您喜欢阅读本文,请考虑点击拍手按钮?。 想看我更多的作品吗? GitHub上查看我的代码,并在h ttp://aboutmonica.com上了解有关我的开发经验的更多信息

翻译自: https://www.freecodecamp.org/news/how-i-automatically-created-a-twitter-list-of-freecodecampers-in-5-minutes-425f0b922118/

twitter全自动发推