python - 问题在 PyCharm 中运行 Python 3.7 以执行 Twitter Bot(通过 Tweepy)
问题描述
我正在尝试在 PyCharm 中运行 Python 3.7 代码以从 Tweepy(Twitter 的 API)执行 Twitter 机器人。
-我有一个 Twitter 的开发者帐户,该帐户已获得批准。- 我在代码中有正确的消费者密钥和访问令牌(在这张票中这些是空白的)。- 我在代码中也有正确的 Twitter 句柄(在这张票的代码中也留空)。-Tweepy 已作为项目解释器添加到我的机器人项目中,并使用相同的 Python 3.7 解释器。
#!/usr/bin/python
import tweepy
import random
import time
#Do not Touch Lists
followed = []
friends = []
liked = []
time_start = time.time()
first_run = 0
# 1. Log onto twitter
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
handle = '@MyHandle'
delay_between_search = 30
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def findtweets():
# Find 'new' tweets (under hashtags/search terms)
terms = ["test"]
query = random.choice(terms)
search = tweepy.Cursor(api.search, q=query, result_type="recent", lang="en").items(35) #Change the amount of tweets being searched for 50-75
print("Searching under term..." + query)
# Like 'new' tweets (only if the user has more than 10 followers & less than 15000 tweets)
for tweet in search:
if (tweet.user.followers_count < 10 and tweet.user.statuses_count < 15000):
print("Ignoring user " + tweet.user.screen_name)
continue
try:
api.create_favorite(id=tweet.id)
print("Following user " + tweet.user.screen_name)
# Follow the user, and then mute them.
time.sleep(6)
api.create_friendship(id=tweet.user.id)
time.sleep(3)
api.create_mute(id=tweet.user.id)
# Store their name in a file to be reviewed later.
followed.append(tweet.user.id)
liked.append(tweet.id)
except tweepy.TweepError as e:
#Catching errors
if (e.args[0][0]['code'] == 139):
print ("Error with tweet " + str(tweet.id) + ", already liked!")
liked.append(tweet.id)
continue
if (e.args[0][0]['code'] == 88):
print ("Rate limited..")
time.sleep(60*15)
continue
print ("Error with tweet " + str(tweet.id))
# Unfollow() provides a method for unfollowing users that have not
followed you back. Unfollow() also
# adds users that have followed you back to your "friends" list to
be unfollowed at a later time.
def unfollow():
print(" ~ Starting unfollow process ~ ")
for user in followed:
try:
status = api.show_friendship(source_screen_name=handle,
target_id=user)
except:
print ("Rate Limit Exceeded")
time.sleep(900)
# If the user is not following me back:
if (str(status[1].following) == "False"):
try:
# Unfollow them
api.destroy_friendship(id=user)
time.sleep(10)
print("Unfollowed: " + str(user))
followed.remove(user)
continue
except:
print("Could not Unfollow: " + str(user))
# Save the names of those who followed us back.
friends.append(user)
print("Friended: " + str(user))
followed.remove(user)
# Unfollow_friends(): Unfollows users that DO follow you back.
def unfollow_friends():
print(" ~ Starting unfollow_friends process ~ ")
for user in friends:
try:
api.destroy_friendship(id=user)
print("Unfollowed: " + str(user))
friends.remove(user)
except:
print("Could not Unfollow: " + str(user))
# Unlike statuses liked with the bot
def unlike():
for tweet in liked:
try:
api.destroy_favorite(id=tweet)
print("Unliked: " + str(tweet))
liked.remove(tweet)
except tweepy.TweepError as e:
if(e.args[0][0]['code'] == 144):
print("This status no longer exists... removing..")
liked.remove(tweet)
continue
print("An unknown error occured")
# Write our actions to separate files in case of a error
def write_to_file(filename, list):
for item in list:
filename.write(str(item) + "\n")
# Read from our files on first run.
if (first_run == 0):
try:
with open('followed_users.txt') as f:
followed = f.read().splitlines()
if (len(followed) > 100):
unfollow()
with open('liked_tweets.txt') as f:
liked = f.read().splitlines()
if (len(liked) > 100):
unlike()
with open('friend_users.txt') as f:
friends = f.read().splitlines()
if (len(friends) > 100):
unfollow_friends()
except:
print("Files not found...waiting for first run.")
first_run = 1
while (1 > 0):
since_launch = int(time.time() - time_start)
print ("Running Twitter Bot... " + str(since_launch/60) + " minutes since last mass-action..")
# Tweeting
if (time.time() > time_start+(3600*3)):
time_start = time.time()
unfollow_friends()
if (time.time() > time_start+3600 and len(followed) > 100):
unfollow()
unlike()
findtweets()
time.sleep(delay_between_search)
# Logging
print("Logging our files...")
liked_tweets = open("liked_tweets.txt", "w")
write_to_file(liked_tweets, liked)
liked_tweets.close()
followed_users = open("followed_users.txt", "w")
write_to_file(followed_users, followed)
followed_users.close()
friend_users = open("friend_users.txt", "w")
write_to_file(friend_users, friends)
friend_users.close()
运行代码应该期望机器人根据搜索词搜索和关注/喜欢推文,但我还没有走那么远。我遇到以下错误:
/usr/local/bin/python3.7 /Users/myname/Downloads/yt-python-twitter-master/twitter_bot.py
Files not found...waiting for first run.
Running Twitter Bot... 0.0 minutes since last mass-action..
Searching under term...test
Traceback (most recent call last):
File "/Users/myname/Downloads/yt-python-twitter-master/twitter_bot.py", line 48, in findtweets
api.create_favorite(id=tweet.id)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/binder.py", line 250, in _call
return method.execute()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/binder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: Twitter error response: status code = 429
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/myname/Downloads/yt-python-twitter-master/twitter_bot.py", line 158, in <module>
findtweets()
File "/Users/myname/Downloads/yt-python-twitter-master/twitter_bot.py", line 60, in findtweets
if (e.args[0][0]['code'] == 139):
TypeError: string indices must be integers
Process finished with exit code 1
解决方案
您提供的代码格式似乎不正确。
但是,429响应状态代码意味着您受到 Twitter API 的速率限制。使用的收藏夹/创建端点的
速率限制是 1000 个请求/24 小时窗口。API.create_favorite
至于你对产生的错误的处理,e.args[0]
是以字符串的形式出现错误的原因。
请参阅https://github.com/tweepy/tweepy/blob/master/tweepy/error.py。
e.args[0][0]
因此是那个原因的第一个特征。
因此,您遇到的错误是因为您尝试使用 index 访问字符串(单个字符)'code'
。
推荐阅读
- python - 在 azure blob 存储中重命名 spark 输出 csv
- python-3.x - Python 3 替换 nan 值
- python - WSL: /usr/bin/env: ‘python’: No such file or directory
- c# - 在标记 aspx 页面上的 ASP.NET 错误中创建母版页
- c# - 我可以将这个旧的 csproj 迁移到 VS2017 csproj 吗?
- pandas - 在python中根据字符串值创建单独的列
- spring - Spring 休息 API:saveAll
- c++ - 如何用像'X'这样的常量字符替换字符串的子字符串
- arrays - 如何在 Hibernate 中使用 Postgres 数组“包含”条件?
- javascript - 在 d3.js 中搜索使用 d3.csv 函数生成的 html 表