This question would be a little silly, but I'm very very new to coding. I could not add the solutions I found on the internet to my codes. I would be so glad if you help.
When I open the .py file, the program does not stop automatically. And it running until I close the command window. After I open this file, I want it to run for 5 minutes and then turn itself off. How can I set a time limit for close the program?
import tweepy
import time
auth = tweepy.OAuthHandler('*','*')
auth.set_access_token('*','*')
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.me()
search = 'books'
nrTweets = 500
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
try:
print('Tweet Liked')
tweet.favorite()
time.sleep(10)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
You can monitor the running time of your program, and break the for-loop after the time limit.
import time
time_limit_sec = 5 * 60
start_time = time.time()
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
if (time.time()-start_time) > time_limit_sec:
break
... # your code here
Related
Background:
This was not an issue until I added the try/except. I added this because at times I feel there was a deeper issue, perhaps rooted in the function I call from kucoin.helpers. (I call a while loop, while inside of a while loop in my code.)
Specifically I would find myself unable to consistently finish the cycle of purchase and then sale of asset: This failure would stem from between a successful purchase of asset and the sale.
The try/except loop was the only way to "flawlessly execute my code".
I know the try/except loop was not utilized properly, I am inexperienced and will delve into it.
import kucoin_helpers
import time
import random
from twilio.rest import Client as TwilioClient
import twiliodata
####Set API Credentials for Twilio
text_client = TwilioClient(twiliodata.account_sid, twiliodata.auth_token)
#This is going to be Lumiere himself. The man, the bot, the first iteration and legend.
########IMMEDIATELY BEGIN KEEPING rounds of data.
#Leave room for INFO: in database to allow comment made to first and last entry in database for round
##This will allow for easy diefin tin
#look forward to using minimax
take_profit = 0
stop_loss = 0
keep_testing = True
while keep_testing:
try:
starting_account_balance = kucoin_helpers.doge_musk_check_balance()
print(f"BEGINNING BALANCE: {starting_account_balance}")
list_of_winLOSS = []
####Start keeping this data
total_times_to_run = random.randrange(start=20, stop=50)
total_times_to_run = int(total_times_to_run)
#####We need to run this loop repetitively until we reach an output ratio where Success to Failure is near (0.7/0.3)==2.63
#Add Each trials results (tp to sl limits/)
##Consider using limits that are proportionate to the "confidence" in current trend in timeframe
for i in range(total_times_to_run):
input_tp = random.uniform(1.001, 1.009)
take_profit=input_tp
print(input_tp)
input_sl = random.uniform(0.991, 0.99989)
take_profit=input_sl
print(input_sl)
answer = kucoin_helpers.execute_doge_musktrade(input_tp=input_tp, input_sl=input_sl)
list_of_winLOSS.append(answer)
time.sleep(0.5)
failure = 0
success = 0
for outcome in list_of_winLOSS:
if outcome == "Failure":
failure += 1
if outcome == "Success":
success += 1
ending_account_balance = kucoin_helpers.doge_musk_check_balance()
total_PNL = ending_account_balance - starting_account_balance
print(f"SUCCESS: {success}\nFailure: {failure}")
print(f"BEGINNING BALANCE: {starting_account_balance}")
print(f"ENDING BALANCE: {ending_account_balance}")
print(f"PNL : {total_PNL}")
body = f"SUCCESS: {success}\nFAILURE: {failure}\nBEGINNING BALANCE: {starting_account_balance}\nENDING BALANCE: {ending_account_balance}\nPNL: {total_PNL}"
text_client.messages.create(to="7177295751", from_=twiliodata.phone_number, body=body)
except:
print("Unable to perform Action")
As you already mentioned, a good use of try-except clauses would capture your specific exceptions and not all. What is happening right now is that you are throwing a KeyboardInterrupt exception by pressing Ctrl+c, which is caught by your except statement and results in printing "Unable to perform Action".
You could add an exception handler for the KeyboardInterrupt exception with exit() to end the program, ones you hit Ctrl+c:
try:
...
except KeyboardInterrupt:
exit()
except:
print("Unable to perform Action")
Is the code block exactly as it is being run? Because if not, you might have some indentation issues. From what I can tell, from starting_account_balance = kucoin_helpers.doge_musk_check_balance() to except: print("Unable to perform Action") should be one indent further in.
the code of my bot written in python
can someone tell me how to loop because I want to host on https://www.evennode.com/
#import modules
import tweepy
import time
auth = tweepy.OAuthHandler('','') #key
auth.set_access_token('', '') #token
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.me()
search = '#Evangelion' #code
numeroDeTweets = 40 #code
for tweet in tweepy.Cursor(api.search, search).items(numeroDeTweets): #code
try:
print('') #code
tweet.retweet() #code
tweet.favorite() #code
time.sleep(45) #code
except tweepy.TweepError as e: #code
print(e.reason) #code
except StopIteration: #code
break #code
Oh, Evangelion is mentioned here, good. Really good. But jokes aside, as far as i understood you want to infinitely loop through twitter search result. If so, there are two methods which will do it but with the key difference.
If you want to itereate through:
I. Every result possible before updating search queue
If you wan to do so, you just have to remove numeroDeTweets variable from the items() argument and let it iterate:
for tweet in tweepy.Cursor(api.search, search).items(): # No more limits!
try:
# your stuff here
except:
# and here
II. First numeroDeTweets results and then search again
In that case you have to put for cycle into the while True loop to make it infinite and add a time.sleep() to add some cooldown.
So it will look something like that:
while True: # Doing it infinite amount of times
for tweet in tweepy.Cursor(api.search, search).items(numeroDeTweets): #There ARE limits!
try:
# your stuff here
except:
# and here
finally:
time.sleep(45) # Taking rest for search to update
I'm a beginner with coding.
I'm trying to scrape tweets from a Twitter account.
I'm getting the following error when I run my code: CRITICAL:root:twint.get:User:
Here is the code that I'm running:
import twint
config = twint.Config()
# Search tweets tweeted by user 'BarackObama'
config.Username = "BarackObama"
# Limit search results to 20
config.Limit = 20
# Return tweets that were published after Jan 1st, 2020
config.Since = "2020-01-1 20:30:15"
# Formatting the tweets
config.Format = "Tweet Id {id}, tweeted at {time}, {date}, by {username} says: {tweet}"
# Storing tweets in a csv file
config.Store_csv = True
config.Output = "Barack Obama"
twint.run.Search(config)
Does this error mean it's a problem with Twint, or is there a mistake in my code?
Thank you!
I'm a beginner as well, trying to learn python as a tool for Digital History in Brazil.
I was getting the same problem (only when using c.Username parameter).
I solved running pip3 install --upgrade -e git+https://github.com/twintproject/twint.git#origin/master#egg=twint
I hope it works for you.
The solution is in modifying user.py in the twint source, and replace lines with a try and except statement.
try:
_usr.name = ur['data']['user']['legacy']['name']
except:
_usr.name = ''
try:
_usr.username = ur['data']['user']['legacy']['screen_name']
except:
_usr.username = ''
try:
_usr.bio = ur['data']['user']['legacy']['description']
except:
_usr.bio = ''
try:
_usr.location = ur['data']['user']['legacy']['location']
except:
_usr.location = ''
try:
_usr.url = ur['data']['user']['legacy']['url']
except:
_usr.url = ''
This question already has answers here:
How to make this script loop every hour
(4 answers)
Closed 2 years ago.
I am making a script wich post every hour on twitter every case of coronavirus. I have it finish but idk how to make that it posts every hour. any idea? (if you could post the following script with the solution in would be perfect)
import sys
CONSUMER_KEY = 'XXXX'
CONSUMER_SECRET = 'XXXX'
ACCESS_TOKEN = 'XXXX'
ACCESS_TOKEN_SECRET = 'XXXX'
import tweepy
import requests
from lxml import html
def create_tweet():
response = requests.get('https://www.worldometers.info/coronavirus/')
doc = html.fromstring(response.content)
total, deaths, recovered = doc.xpath('//div[#class="maincounter-number"]/span/text()')
tweet = f'''Coronavirus Latest Updates
Total cases: {total}
Recovered: {recovered}
Deaths: {deaths}
Source: https://www.worldometers.info/coronavirus/
#coronavirus #covid19 #coronavirusnews #coronavirusupdates #COVID19
'''
return tweet
if __name__ == '__main__':
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# Create API object
api = tweepy.API(auth)
try:
api.verify_credentials()
print('Authentication Successful')
except:
print('Error while authenticating API')
sys.exit(5)
tweet = create_tweet()
api.update_status(tweet)
print('Tweet successful')
Best way is to Schedule Python Script using Windows Scheduler on Windows & Cron Jobs on Linux. Following are the steps for Scheduling your python script on windows.
Prepare the Python Script
Save the Python Script
Create Batch File to Run the Python Script with extension .Bat
Content should be as follows
"Path where your Python exe is stored\python.exe" "Path where your Python script
is stored\script name.py"
pause
This batch file will run the Python script when double-clicking on it
In the final step below, you’ll see how to schedule that batch file
to execute the Python Script using the Windows Scheduler.
First, open the Control Panel and then click on the Administrative
Tools: Next, double-click on the Task Scheduler, and then choose the
option to ‘Create Basic Task…’
Type a name for your task (you can also type a description if needed), and then press Next.
Next, I chose to start the task ‘Daily’ since we wish to run the Python script daily at 6am:
The action will then recur everyday at 6am, staring from start date. You can adjust those timing parameters to suit your needs.
Select, Start a program, and then press Next:
Next, use the Browse button to find the batch file that runs the Python script.
click on Finish,
We go to the ‘Triggers’ tab and select the ‘Edit’ option:
An ‘Edit Trigger’ screen will appear. To set the script to run hourly, we select the ‘Repeat task…’ option and enable it. We select the ‘1 hour’ option, indicating that we wish for the task to execute on an hourly basis, and select the duration as indefinite under the duration option.
We then press the ‘OK’ button and exit the popup. Our batch script is enabled to run hourly at the :00 mark!
you should be good to go.
Above shared information is enough to do your job, But for more information, Feel free to use the link as below: https://datatofish.com/python-script-windows-scheduler/ and https://techrando.com/2019/06/22/how-to-execute-a-task-hourly-in-task-scheduler/
So I have been working on a twitter bot for a while now, and I am running into a problem with it. Every time I include the api.retweet() function it runs my function twice. To stop it all I have to do is comment it out. Every time it runs twice it causes an error and kills my program.
I fixed that part with a try except setup, but still it replies twice, and tries to like it twice. I don't understand why it would do it. If I take it out it fixes it completely.
I put print tags to tell me how the loop happens, and it enters the on_data function (Provided by tweepy to check if data has been received), then it enters my check_data (My function to check the data for phrases and tags I wish to filter out) then it goes to my retweet and like function. After it does those it continues back up to the end of my on_data. If there is no retweet, it ends there. If there is one, then it does it all once more before ending.
Streamer class:
class LEDStreamListener(tweepy.StreamListener):
def on_data(self, raw_data):
# with open("tweets.json", "w") as write_file:
# write_file.write(raw_data)
print('at the top boi')
data = json.loads(raw_data)
usr = data['user']['screen_name']
tweet_id = data['id']
if len(data['entities']['hashtags']) != 0:
tag = data['entities']['hashtags'][0]['text']
else:
tag = ''
data_check(usr, tweet_id, tag, counter)
print('here in on_data now')
Data check function:
def data_check(twitter_user, tweet, tag, count):
print('Entering data_check')
if tag == 'HUNTER_LED_OFF':
requests.get('http://192.168.1.172/off')
retweet_tweet(tweet)
api.update_status('I turned the led off for you', tweet)
print('off')
return
elif tag == 'HUNTER_LED_ON':
requests.get('http://192.168.1.172/on')
retweet_tweet(tweet)
api.update_status('I turned the led on for you', tweet)
print('on')
return
elif tag == 'led_test':
retweet_tweet(tweet)
api.update_status('Nice test bro *highfives* keep up the good work', tweet)
print('tested')
return
elif twitter_user == 'realDonaldTrump':
print('Make America Great Again!')
return
else:
return
Retweet function:
def retweet_tweet(tweet_id):
try:
print('re-tweeting')
api.retweet(tweet_id)
api.create_favorite(tweet_id)
print('done re-tweeting')
except tweepy.TweepError as e:
print(e)
Console output of a received tweet with retweets enabled
at the top boi
Entering data_check
re-tweeting
done re-tweeting
off
here in on_data now
at the top boi
Entering data_check
re-tweeting
[{'code': 327, 'message': 'You have already retweeted this Tweet.'}]
off(this is me editing this just says the state of the command it did to my robot)
here in on_data now
Console log of with out the retweet line in the retweet function
at the top boi
Entering data_check
re-tweeting
done re-tweeting
off(this is me editing this just says the state of the command it did to my robot)
here in on_data now
Ok so let's start this off by saying I'm mad at myself, and and currently not on speaking terms with my brain for this. Not sure I'll ever forgive the guy. Basically if you run into this error its because when you re tweet the tweet based on it hashtag, you make a post on your page with the hashtag on it. Tripping the bot to do things. To fix it I just set a variable
text = data['text']
Then in my if statements I checked if the text part of my json file that is now stored in the variable I just made starts with 'RT'. By saying
if tag = '(your hashtag)' and not text.startswith('RT')
I noticed while looking at the json files after I figured it out that they all do it.