[英]Issue Running Python 3.7 in PyCharm to Execute Twitter Bot (via Tweepy)
I am attempting to run Python 3.7 code within PyCharm to execute a Twitter bot from Tweepy (Twitter's API).我试图在 PyCharm 中运行 Python 3.7 代码以从 Tweepy(Twitter 的 API)执行 Twitter 机器人。
-I have a developer account with Twitter, which has been approved. - 我在 Twitter 上有一个开发者帐户,已获得批准。 -I have my correct consumer keys and access tokens within the code (these are left blank in this ticket).
- 我在代码中有正确的消费者密钥和访问令牌(这些在这张票中留空)。 -I have my correct Twitter handle within the code as well (left blank in this ticket's code as well).
- 我在代码中也有我正确的 Twitter 句柄(在这张票的代码中也留空)。 -Tweepy has been added as a project interpreter to my bot project, and is using the same Python 3.7 interpreter.
-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()
Running the code should expect for the bot to search and follow/like Tweets based on the search term, but I'm not getting that far.运行代码应该期望机器人根据搜索词搜索和关注/喜欢推文,但我没有走那么远。 I am experiencing the following error(s):
我遇到以下错误:
/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
The code you provided doesn't seem to be properly formatted.您提供的代码似乎格式不正确。
However, a 429 response status code means that you're beingrate limited by Twitter's API.但是,429响应状态代码意味着您受到 Twitter API 的速率限制。
The rate limit for the favorites/create endpoint that API.create_favorite
uses is 1000 requests / 24-hour window. API.create_favorite
使用的收藏夹/创建端点的速率限制为 1000 个请求/24 小时窗口。
As for your handling of the resulting error, e.args[0]
is the reason for the error in the form of a string.至于你对由此产生的错误的处理,
e.args[0]
是以字符串的形式出现错误的原因。
See https://github.com/tweepy/tweepy/blob/master/tweepy/error.py .请参阅https://github.com/tweepy/tweepy/blob/master/tweepy/error.py 。
e.args[0][0]
is therefore the first character of that reason. e.args[0][0]
因此是该原因的第一个字符。
Hence, the error you're encountering is because you're attempting to access a string (a single character) with the index 'code'
.因此,您遇到的错误是因为您试图访问索引为
'code'
的字符串(单个字符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.