I am trying to code a homework list script that sends the homework to a group chat every day but I keep getting a invalid time format error because of pywhatkit. The error message only disappears when I delete the +65 but another error message will pop up saying that there is no country code for the number. I'm not sure how to solve it since I am trying to send to a group chat and not a phone number.
import pywhatkit
import datetime
# Dictionary to store the homework assignments and their due dates
homework_dict = {}
# Function to add a homework assignment to the dictionary
def add_homework(assignment, due_date):
homework_dict\[assignment\] = due_date
# Function to delete homework assignments that are due one day before the actual due date
def delete_overdue_homework():
# Check the current date
now = datetime.datetime.now()
# Calculate the date one day before the current date
yesterday = now - datetime.timedelta(days=1)
# Delete any assignments that are due on the calculated date
for assignment, due_date in homework_dict.items():
if due_date == yesterday.date():
del homework_dict\[assignment\]
# Function to send the homework list to the WhatsApp group chat
def send_homework_list():
# Check the current date
now = datetime.datetime.now()
# Initialize the message with the current date
message = "Homework of the day (" + now.strftime("%B %d, %Y") + "):\\n"
# Add each homework assignment to the message
for assignment, due_date in homework_dict.items():
\# If the due date has not passed, add the assignment to the message
if due_date \>= now.date():
message += " - " + assignment + "\\n"
# Calculate the hour to send the message (current hour + 18)
send_hour = (now.hour + 18) % 24
# Send the message to the WhatsApp group chat
pywhatkit.sendwhatmsg("+65 Homework List", send_hour, 0, message)
# Add some homework assignments for testing
add_homework("Math worksheet", datetime.date(2023, 1, 10))
add_homework("Science reading", datetime.date(2023, 1, 11))
add_homework("English essay", datetime.date(2023, 1, 15))
# Send the homework list to the WhatsApp group chat at 6:00 PM every day
while True:
delete_overdue_homework()
send_homework_list()
# Wait for 24 hours before sending the list again
time.sleep(24*60*60)
When I used 18, 0, for 6PM so I tried a different solution but it still shows as an error.
Related
I'm trying to write code in Python to help with sending an email that I send about twice a week, with the same format every time and just a few elements that differ between emails, so I wrote the following code to help with this:
def visitor():
visitors = []
number_of = int(input("How many visitors are you signing in? "))
time = input("What time are they coming? ")
comments = """
Please type the name of the first visitor, and their nationality on the next line, the name of the second visitor
and their nationality on the next line, until you wrote down all the names and nationalities.
If you wanna stop the program and execute the code with the names & nationalities, just type quit
"""
print(comments)
name, i = "", 1
while name != "quit":
name = str(input("Ignore: "))
visitors.append(name)
visitors = visitors.pop(-1)
email = f"""
Hello,
I have {number_of} visitors coming today at {time}.
Name: {visitors[i]}
Nationality: {visitors[i + 1]}
"""
for i in range(len(visitors)):
to_add = f"""
Name: {visitors[i]}
Nationality: {visitors[i + 1]}
"""
email += to_add
ending = "Awaiting your approval\nThank you"
email += ending
return email
visitor()
However, upon running this code, I run into a problem in line 25, saying "Index out of range" ( line 25 is Nationality: {visitors[i + 1]} ). This normally shouldn't happen since the list has more than one element. Can someone help with this?
P.S. I have another, way longer code written for this that works, but I wanted to try and improve it by making it less sloppy.
The visitors list is acceeded at offset i+1, and i go up to len(visitors)-1 (upper limit specified for the loop through range()), so there is an access out of range when i = len(visitors) - 1
I have automated an outlook email with a python script. What I'd like to do now is enter next weeks date in the body of the email.
Is there any function that will allow me to do this?
For example I want to send an email and in the email I want the ask the recipient to respond by the 29th of April (Exactly a week from todays date). Is there a way I can read todays date and then print out a date that is 7 days later in the email?
Sample code:
import win32com.client as client
import pathlib
import pandas as pd
outlook = client.Dispatch('Outlook.Application')
#Mail item
message = outlook.CreateItem(0)
df = pd.read_excel(r'Desktop\Review.xlsx',index_col=False,sheet_name='Review', usecols = "A:H")
#Display message
body = df.to_html()
message.Display()
message.To = "Mick.callnan#something.com"
message.Subject = "Review"
message.HTMLBody = "Hi All, <br> <br>Please respond by this day next week **Enter date here**
#message.Send()
import datetime
# how many days allowance?
N = 7
# assign the deadline date
deadline = datetime.date.today() + datetime.timedelta(days=N)
# on its own, it already works...
print(f"Please respond by {deadline}.")
# prints out Please respond by 2021-04-29.
# but perhaps you want to format it
s = deadline.strftime("%d %b %Y")
print(f"Please respond by {s}.")
# prints out Please respond by 29 Apr 2021.
By the way, please check out https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior on your own for the format codes.
I am trying to use the restrict method to search for emails where the subject equals a certain string, however, this string changes slightly everyday since the sender adds the current date. I am trying to use a variable which would contain the current date and insert it into the restrict method.
I keep getting an invalid syntax error message specifically with regards to the Restrict line.
from datetime import datetime, timedelta
received_dt = datetime.now()
received_dt = received_dt.strftime('%Y-%m-%d')
subject_search_string = "Daily Statement" + recevied_dt
msg = msg.Restrict("[Subject] = " subject_search_string)
The subject value must be single-quoted:
msg = msg.Restrict("[Subject] = '" subject_search_string "'")
I am trying to send meeting invites from outlook using python. I also want to reflect that in the outlook calendar of the receiver. I am using the following code
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
def sendRecurringMeeting():
appt = outlook.CreateItem(1) # AppointmentItem
appt.Start = "2018-11-14 15:30" # yyyy-MM-dd hh:mm
appt.Subject = "Important"
appt.Duration = 60 # In minutes (60 Minutes)
appt.Location = "Floor 5"
appt.MeetingStatus = 1 # 1 - olMeeting; Changing the appointment to meeting. Only after changing the meeting status recipients can be added
appt.Recipients.Add("mabc#abc.com") # Don't end ; as delimiter
appt.Recipients.Add("xyz#xyz.com")
appt.ReminderSet = True
appt.ReminderMinutesBeforeStart = 15
# Set Pattern, to recur every day, for the next 5 days
pattern = appt.GetRecurrencePattern()
pattern.RecurrenceType = 0
pattern.Occurrences = "1"
appt.Save()
appt.Send()
sendRecurringMeeting()
Here I am trying to send meeting invites from outlook with Python. Generally when we send a meeting invite, It starts showing in their calendar that you have a meeting today at the mentioned time. By using the above code, I am able to send a meeting invite but it is not showing in their calendar i.e it is not giving reminders.
I am trying to read emails from Outlook using a specific date range as well as other criteria - sender, subject etc. However, I am unsure as to how to specify a date range within which Python can search for the emails. This is what I have so far which generates the type error below:
if subject in message.subject and date in message.senton.date():
TypeError: argument of type 'datetime.date' is not iterable
import win32com.client
import datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(18).Folders.Item("xxxxx")
messages = inbox.Items
date = datetime.date.today()
subject = "xxxxxxx"
for message in messages:
if subject in message.subject and date in message.senton.date():
print(message.senton.time())
I would like to search for emails within a specific date range, as well as be able to use more than one criteria to search. E.g specify the subject as well as sender etc. But I am not sure how, I am new to Python so please help!
Try this
if subject in message.subject and date == message.senton.date():
print(message.senton.time())
print(message.sender)
Edit:
if you want date range you can use datetime to define the date range
start = message.senton.date() - timedelta(days=10)
end = message.senton.date() + datetime.timedelta(days=10) # 20 days date range
if subject in message.subject and date > start and date < end:
print(message.senton.time())
print(message.sender)
instead of looping through every message, outlook provides an api to query the exact subject:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.Folders.Item(3).Folders['Inbox'].Folders['My Folder']
filt = "#SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" = '{0}'".format(subject)
messages=inbox.Items.Restrict(filt)