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/
Related
I've written a short code to download and rename files from a specific folder in my outlook account. The code works great, the only problem is that I typically need to run the code several times to actually download all of the messages. It seems the code is just failing to acknowledge some of the messages, there are no errors when I run through it.
I've tried a few things like walking through each line step by step in the python window, running the code with outlook closed or opened, and trying to print the files after they're successfully saved to see if there are specific messages that are causing the problem.
Here's my code
#! python3
# downloadAttachments.py - Downloads all of the weight tickets from Bucky
# Currently saves to desktop due to instability of I: drive connection
import win32com.client, os, re
#This line opens the outlook application
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#Not exactly sure why the inbox is default folder 6 but it works
inbox = outlook.GetDefaultFolder(6)
#box where the messages are to save
TicketSave = inbox.Folders('WDE').Folders('SAVE').Folders('TicketSave')
#box where the messages are moved to
done = inbox.Folders('WDE').Folders('CHES').Folders('Weight Tickets')
ticketMessages = TicketSave.Items
#Key is used to verify the subject line is correct. This script only works if the person sends
# their emails with a consistent subject line (can be altered for other cases)
key = re.compile(r'wde load \d{3}') #requires regulars expressions (i.e. 'import re')
for message in ticketMessages:
#will skip any message that does not match the correct subject line format (non-case sensitive)
check = str(message.Subject).lower()
if key.search(check) == None:
continue
attachments = message.Attachments
tic = attachments.item(1)
ticnum = str(message.Subject).split()[2]
name = str(tic).split()[0] + ' ticket ' + ticnum + '.pdf' #changes the filename
tic.SaveAsFile('C:\\Users\\bhalvorson\\Desktop\\Attachments' + os.sep + str(name))
if message.UnRead == True:
message.UnRead = False
message.Move(done)
print('Ticket pdf: ' + name + ' save successfully')
Alright I found the answer to my own question. I'll post it here in case any other youngster runs into the same problem as me.
The main problem is the "message.Move(done)" second from the bottom.
Apparently the move function alters the current folder thus altering the number of loops that the for loop will go through. So, the way it's written above, the code only ever processes half of the items in the folder.
An easy work around is to switch the main line of the for loop to "for message in list(ticketMessages):" the list is not affected by the Move function and therefore you'll be able to loop through every message.
Hope this helps someone.
My Script downloads a zipfile, exctracts the relevant parts replaced files and folders etc. It used to work flawlessly, for some reason its has now decided to stop working and only partly downloads the zipfile, and of course, as the zipfile is incomplete I get an error, saying the downloaded file is not a zipfile. my script is as follows.
def downloadupdate():
xbmcgui.Dialog().ok(
"[B][COLOR white]Daily Updater[/B][/COLOR]",
"Favourites and some software will now update",
"Elements of your system will be cleaned",
"Daily Update will take at most 2 minutes")
#ONLY HAVE THE SUPER FAVOURITES FOLDER IN THE ZIPFILE!!
url = 'http://x.com/x/x/Super Favourites.zip'
destination = xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip')
favzip = urllib.urlopen(url)
xbmc.executebuiltin("Notification(Downloading new updates, PLEASE WAIT,()")
with open(xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip'), "wb") as zipFile:
zipFile.write(favzip.read())
xbmc.executebuiltin("Notification(Download Complete, Please wait,()")
time.sleep(5)
xbmc.executebuiltin("Notification(Updating Click and Play channels, Please wait,()")
updatezip = xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip')
extractupdate = xbmc.translatePath('special://home/userdata/addon_data/plugin.program.super.favourites/')
oldfav = xbmc.translatePath('special://home/userdata/addon_data/plugin.program.super.favourites/Super Favourites')
yeszip = os.path.exists(updatezip)
time.sleep(5)
if yeszip:
xbmc.executebuiltin("Notification(Removing previous, Please wait,()")
shutil.rmtree(oldfav, ignore_errors=False)
xbmc.executebuiltin("Notification(Updating, now,()")
gh = open(updatezip, 'rb')
zp = zipfile.ZipFile(gh)
zp.extractall(extractupdate)
gh.close()
time.sleep(3)
xbmc.executebuiltin("Notification(updated, Now Checking sd,()")
# put this command at the end of whole script --->>>os.remove(updatezip)
else:
xbmc.executebuiltin("Notification(Update file Corrupt, Please try again,()")
The problem has been solved, It was not the code. It was the hosting service, I had to reset the File permissions on the server and after that all works perfectly again.
So I have a simple reddit bot set up which I wrote using the praw framework. The code is as follows:
import praw
import time
import numpy
import pickle
r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()
words_to_match = ['sdfghm']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("test")
print("Grabbing thread titles...")
threads = subreddit.get_hot(limit=10)
for submission in threads:
thread_title = submission.title.lower()
isMatch = any(string in thread_title for string in words_to_match)
if submission.id not in cache and isMatch:
print("Match found! Thread ID is " + submission.id)
r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
print("Message sent!")
cache.append(submission.id)
print("Comment loop finished. Restarting...")
# Run the script
while True:
run_bot()
time.sleep(20)
I want to create a file (text file or xml, or something else) using which the user can change the fields for the various information being queried. For example I want a file with lines such as :
Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot
I want the info to be input from fields, so that it takes the value after Words to Search for = instead of the whole line. After the information has been input into the file and it has been saved. I want my script to pull the information from the file, store it in a variable, and use that variable in the appropriate functions, such as:
words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....
So basically like a config file for the script. How do I go about making it so that my script can take input from a .txt or another appropriate file and implement it into my code?
Yes, that's just a plain old Python config, which you can implement in an ASCII file, or else YAML or JSON.
Create a subdirectory ./config, put your settings in ./config/__init__.py
Then import config.
Using PEP-18 compliant names, the file ./config/__init__.py would look like:
search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']
If you want more complicated config, just read the many other posts on that.
I have a report that I run everyday that I'm trying to send to a distribution list but am having one minor issue that is causing a big problem since it's not being sent to the appropriate people. It appears that if I try to send the report to a distribution list with periods in the address, the report won't send. Otherwise, it sends fine.
If I send the report to a single email such as "myname#domain.com" it works.
If I send the report to a distribution list such as "ME-EXAMPLE-EAMPLE2#domain.com" it also works.
However, the distribution list I am sending it to has periods in it. I.E "ME.EXAMPLE.EXAMPLE2#domain.com" and this will not work
The only thing I can think of is that python is having a issue parsing the periods. Has anyone else ran into this problem or found a solution to it?
def sendEmail(parser):
email = 'ME.EXAMPLE.EXAMPLE2.ME#gmail.com'
dailyReportLocation = parser.get('FileLocations','dailyReport')
yearlyReportLocation = parser.get('FileLocations','yearlyReport')
blankFile = parser.get('FileLocations','blankEmailContentFile')
fh = open(blankFile, 'w+')
fh.close()
linuxCMD = 'mutt -s "Daily & Yearly Hang Report" -a %s -a %s "%s" < %s ' % (dailyReportLocation,yearlyReportLocation,email,blankFile)
#print(linuxCMD)
os.system(linuxCMD)
if __name__ == '__main__':
c = ConfigurationPreCheck()
parser = c.run()
scrubbedFile = scrubPreviousDayReport(parser,getPreviousDayReportName(parser))
runReport(parser,DAILY_REPORT)
runReport(parser,YEARLY_REPORT)
sendEmail(parser)
I have found this code sample to make a query in ebay from here and also downloaded ebay-sdk for Python. How can I install the sdk and integrate this code with it?
from ebaysdk import finding, nodeText
f = finding()
f.execute('findItemsAdvanced', {'keywords': 'shoes'})
dom = f.response_dom()
mydict = f.response_dict()
myobj = f.response_obj()
print myobj.itemSearchURL
# process the response via DOM
items = dom.getElementsByTagName('item')
for item in items:
print nodeText(item.getElementsByTagName('title')[0])
It is quite a simple process
1) Go to http://developer.ebay.com/, register over there, and get
the app id key.
2) You can simply do a 'pip install ebaysdk' to
install the ebaysdk
3) Copy this file in the same directory
https://github.com/timotheus/ebaysdk-python/blob/master/ebay.yaml In
this file replace appid with what you generated in step 1
4) Execute the example, this time it will work :)