I want to loop a bot in python - python

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

Related

Why am I unable stop this program using the VSCode terminal command: ctrl + c, or ctrl + z?

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.

How to exclude a keyword or make a blacklist for some keywords when retweeting using tweepy

I know how to make a bot that retweets the tweets containing certain tag or keywords:
tag = 'My_keyword'
# Looping through tweets
for tweet in tweepy.Cursor(api.search, q=tag,
).items():
try:
print('\nTweet by: #' + tweet.user.screen_name)
# Retweet tweets as they are found
tweet.retweet()
print('Retweeted the tweet')
sleep(randint(1,2))
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
But how can I make a blacklist of keywords that checks if it is in the tweet skip the tweet and go to the next one... ?
Do check the documentation for a more detailed guide. You can get the tweets text with tweet.full_text, then using string comparison, you can check whether a certain word is in the tweet's text.
if 'bad_word' in tweet.full_text:
continue
If you have a list of words, you can do something like
If any([bw in tweet.full_text for bw in bad_word_list]):

Python How to Program to be Closed After a Certain Time

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

Tweepy targeting a user for following

I find myself in need of a bot for following users on twitter.
When I say user I don't refer to a follower but to a random user that I will find with "Cursor". I'm trying to modify my twitter bot for liking on the timeline for a specific search into one that follows the users for that search. What I don't know how to implement is how do I exactly target a user from the timeline to "create_friendship()"? I'm not targeting a specific user so I don't want to have to specify the 'Id' or the "screen_name" etc.
Looking in Tweepy documentation I wasn't able to find a solution, maybe is under my nose but I'm a newbie and I could use some help.
This is the code for the twitter bot I use for liking tweets.
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)
search = "The searc"
nrTweets = 100
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
try:
print('User succesfully followed')
tweet.favorite() #in here i should be able to create a friendship as i like
time.sleep(60)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
How can I turn this bot in one that follow people in the same fashion in which I like tweets? (for a search with a specific keyword)
This is how I resolved if anyone cares.
# Write a function named collatz() that has one parameter named number. If
# number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1
# Then write a program that lets the user type in an integer and that keeps
# calling collatz() on that number until the function returns the value 1.
# Add try and except statements to the previous project to detect whether the
# user types in a noninteger string. Normally, the int() function will raise a
# ValueError error if it is passed a noninteger string, as in int('puppy'). In the
# except clause, print a message to the user saying they must enter an integer.
try:
number = int(input(("Enter an integer number ")))
def collatz():
global number
if number % 2 == 0:
print(int(number/2))
number = (number/2)
elif number % 2 == 1:
print(int(3*number+1))
number = (3*number+1)
else:
return
while number != 1:
collatz()
except:
print("man, an integer number please! ")

Tweepy retweet bot keeps looping

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.

Categories

Resources