'Job' object has no attribute 'Wednesday' error when scheduling event - python

I tried to make it as easy as possible to understand, I have no backgound in IT, I am doing this auto login program to join my own classes. Can anyone tell me why its not working?
The error is this :
"Traceback (most recent call last):
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 79, in <module>
Wednesday()
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 56, in Wednesday
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
AttributeError: 'Job' object has no attribute 'Wednesday' "
Here is my code:
import datetime
import schedule
import subprocess
import pyautogui
import time
#Define join meeting
def join_meeting(meetingid):
# open Tencent Meeting windows 10
subprocess.call(["C:\Program Files (x86)\Tencent\WeMeet\wemeetapp.exe"])
# 5 secs wait for lag
time.sleep(5)
# Click join button
join_button = pyautogui.locateCenterOnScreen('Tencent_meeting_join_button.png')
pyautogui.moveTo(join_button)
pyautogui.click()
# Putting in the Meeting ID
Id_button = pyautogui.locateCenterOnScreen('Tencent_meeting_id.png')
pyautogui.moveTo(Id_button)
pyautogui.click()
pyautogui.write(meetingid)
# Disable mic
mic_button = pyautogui.locateCenterOnScreen('mic_button.png')
pyautogui.moveTo(mic_button)
pyautogui.click()
# time.sleep(4)
# Joining the meeting
Meeting_button = pyautogui.locateCenterOnScreen('Join_meeting.png')
pyautogui.moveTo(Meeting_button)
pyautogui.click()
time.sleep(4)
pyautogui.press('enter')
#Class times
Class = "10:00"
Class2= "14:00"
Class3= "16:00"
Class4= "19:00"
Test= "18:25"
#Define weekdays
def Monday():
schedule.every().Monday.at(Class2).do(join_meeting(6666666))
def Tuesday():
schedule.every().Tuesday.at(Class3).do(join_meeting(6666666))
def Wednesday():
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
schedule.every().Wednesday.at(Class2).do(join_meeting(66666666))
schedule.every().Wednesday.at(Test).do(join_meeting(6666666666))
def Thursday():
schedule.every().Thursday.at(Class4).do(join_meeting(666666666))
def Friday():
schedule.every().Friday.at(Class4).do(join_meeting(66666666))
def Saturday():
print("Its saturday")
Date = datetime.datetime.now()
Today = (Date.strftime("%a"))
if Today=="Mon":
Monday()
elif Today=="Tue":
Tuesday()
elif Today=="Wed":
Wednesday()
elif Today=="Thu":
Thursday()
elif Today=="Fri":
Friday()
elif Today=="Sat":
Saturday()
else:
print("Today is sunday")
while True:
schedule.run_pending()
time.sleep(60)

Check the capitalization for the days of the week per their documentation.
wednesday will get called now but will run into a type error associated with join_meeting(meetingID):
TypeError: the first argument must be callable
A quick resolution to the TypeError is to not pass the meetingid through the scheduler and define it else where, example:
schedule.every().wednesday.at(Class2).do(join_meeting)
Also, the while loop is indented too far and won't run.

Related

Calling a class method from a different file using Schedule Module in Python

I'm trying to call a method from a class that is in a different file. This is how my code looks:
main.py
###Imports
import funct as f
import schedule
import time
###More Imports
###Grabbing GPS data from user and assigning values
bboxsize = f.find(userLat, userLng, userRad)
if __name__ == '__main__':
r = f.find.radar(bboxsize) ### <---- Line 14
schedule.every(5).seconds.do(r)
while True:
schedule.run_pending()
time.sleep(1)
funct.py
###Imports
class find:
def __init__(self, userLat, userLng, userRad):
self.userLat = userLat
self.userLng = userLng
self.userRad = userRad
def bboxFormula(self):
### Lots of code that is not important to this
return bboxsize
def radar(self, bboxsize):
api = OpenSkyApi(username='###', password='###')
states = api.get_states(bbox=bboxsize)
print(f"vvvvvv| {time.ctime(time.time())} |vvvvvv")
print("------------------------------------------")
for s in states.states:
print("Callsign: %r, Latitude: %r, Longitude: %r, Altitude (meters): %r, Velocity %r)" % (s.callsign, s.latitude, s.longitude, s.geo_altitude, s.velocity))
print("------------------------------------------")
When running this I get:
Traceback (most recent call last):
File "/##/##/##/##/main.py", line 14, in <module>
r = f.find.radar(bboxsize)
TypeError: find.radar() missing 1 required positional argument: 'bboxsize'
I can run all of this in one file without classes, so I know it works. I have been messing with this for a while getting all sorts of errors with every change I make.
Is there something that I'm missing or is there no way for me to do this with the Schedule Module?
I’m just guessing here, but I think you had different code when it was all one file.
Now with two files I think you meant to write this:
find = f.find(userLat, userLng, userRad)
boxsize = find.bboxFormula()
if __name__ == '__main__':
r = lambda :find.radar(bboxsize) ### <---- Line 14
schedule.every(5).seconds.do(r)
while True:
schedule.run_pending()
time.sleep(1)

How to correctly use enterabs from scheduler

I'm trying to schedule something to run periodically, using the code below:
import sched
import time
from datetime import datetime, timedelta
def foo(s, t_end):
now = datetime.now()
print(now)
# Schedule the next run of this function, but only if it'll be before 't_end'
next_run = now + timedelta(seconds=1)
if next_run <= t_end:
s.enter(1, 1, foo, (s, t_end,))
# s.enterabs(next_run, 1, foo, (s, t_end,)) # <-- why doesn't this work?
if __name__ == '__main__':
s = sched.scheduler(time.time, time.sleep)
t_end = datetime.now() + timedelta(seconds=5)
foo(s, t_end)
s.run()
This runs exactly like it should... the script calls foo exactly 5 times and then exits (with 1 second delay between the calls).
But if I change the s.enter(...) to s.enterabs(...) and pass in the calculated time when foo should be called again, it throws the following error:
Traceback (most recent call last):
File "/tmp/test.py", line 18, in <module>
s.run()
File "/usr/lib/python3.9/sched.py", line 141, in run
if time > now:
TypeError: '>' not supported between instances of 'datetime.datetime' and 'float'
What am I doing wrong?
OK I figured this out. In the call to s.enterabs(...), I need to pass next_run.timestamp() as the first argument (not just next_run).

can't play mp3 files continuously inside a loop using pygame? [duplicate]

This question already has an answer here:
I've got an error when trying to create sound using pygame
(1 answer)
Closed 2 years ago.
Hi i want to play a mp3 but when the function recalled that is logCreater an error shows can load mp3.
First time it play audio correctly but when it's recalled then it cant load mp3.
error msg say's pygame.mixer.music.load cant load xxxxx.mp3 file
Actually this is lil project and this is just one module of it.
Please suggest me the code correction.
Error message is :
Traceback (most recent call last):
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 151, in
timCount()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 65, in timCount
EyeExcercise.logCreater()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\EyeExcercise.py", line 45, in logCreater
pygame.mixer.music.load("Eyesound.mp3")
pygame.error: Couldn't open 'Eyesound.mp3'
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from os.path import expanduser
import time as t
import getpass
usernm = getpass.getuser()
from datetime import datetime
import pygame
def userDirFinder():
from os.path import expanduser
usrpth = expanduser("~")
mainp = os.path.join(usrpth, "Documents")
return mainp
def checknSetdir():
mainp=userDirFinder()
target_path = os.path.join(mainp,"HealthManger","Eye_Excercise_log")
if os.path.exists(target_path):
os.chdir(target_path)
else:
os.makedirs(target_path)
os.chdir(target_path)
def getCurrentDateandTime():
Dat = datetime.now()
currentD = Dat.strftime("%d/%m/%Y")
currentT = Dat.strftime("%I:%M %p")
return currentD , currentT
def logCreater():
print("Countdown paused")
pygame.mixer.init()
pygame.mixer.music.load("Eyesound.mp3")
pygame.mixer.music.play(-1)
write_msg = f"Eye Excercise Done by {usernm}"
while 1:
try:
print("Time for a Eye Excercise Break , After the Eye Excercise")
usr_msg = input("Type \"Done\" to stop this alarm: ")
usr_msg = usr_msg.lower()
if usr_msg != "done":
raise ValueError("Invalid Answer")
elif "done" == usr_msg:
checknSetdir()
with open("eye_excercise_log.txt","a") as fi:
cdat , ctim = getCurrentDateandTime()
fi.write(f"Date: {cdat} Time: {ctim} Message: {write_msg}\n")
# print("Log Created")
pygame.mixer.music.stop()
break
except Exception as e:
print(e)
def logReader():
try:
checknSetdir()
with open("eye_excercise_log.txt","r") as fi:
lis = fi.readlines()
for i in lis:
print(i)
input("Press to contiue")
except FileNotFoundError:
print("File is not created Yet")
input("Press to contiue")
if __name__ =="__main__":
while True:
logCreater()
First time it play audio correctly but when it's recalled then it cant load mp3
After playing the music, the current working directory is changed in the function checknSetdir, by os.chdir(target_path).
Get the current working directory at the begin of the application:
import os
currentWorkDir = os.getcwd()
Use an absolut path to load the file "Eyesound.mp3":
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))

Simple script with an error, variable is not defined

im trying to write a very basic sleep interval script and a starter script
but for some reason that I can't understand I get an error message
CODE:
def intervals():
while True:
try:
interval = input('[?] Intervals in seconds [default = 0s]:\t') or 0
interval = int(interval)
print(f'[+] Sleep for: {interval} seconds after each message Sent')
return interval
except:
print(f'[!] Error: {interval} Not a number')
def intervals_start(interval):
sleep(interval)
intervals()
intervals_start(interval)
ERROR:
[?] Intervals in seconds [default = 0s]: 5
[+] Sleep for: 5 seconds after each message Sent
Traceback (most recent call last):
File "***********/testing.py", line 49, in <module>
intervals_start(interval)
NameError: name 'interval' is not defined
Process finished with exit code 1
You are passing a variable interval into a function intervals_start(), but nowhere in the code did you assign interval a value.
You need to capture the result of intervals()
interval = intervals()
then you can safely pass the user selected interval into intervals_start()

func must be a callable or a textual reference to one

I am trying to run a function every 2 minutes, and I use apscheduler for this. However, when I run this I get the following error:
Traceback (most recent call last):
File "main_forecast.py", line 7, in <module>
scheduler.add_job(get_warnings(), 'interval', seconds = 120)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 434, in add_job
job = Job(self, **job_kwargs)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/job.py", line 49, in __init__
self._modify(id=id or uuid4().hex, **kwargs)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/job.py", line 170, in _modify
raise TypeError('func must be a callable or a textual reference to one')
TypeError: func must be a callable or a textual reference to one
And here's the code:
from apscheduler.schedulers.background import BackgroundScheduler
from enemies_info import get_warnings
import time
scheduler = BackgroundScheduler()
scheduler.add_job(get_warnings(), 'interval', seconds = 120)
scheduler.start()
while True:
time.sleep(120)
The function I want to run every 2 minutes is get_warnings.
def get_warnings():
print('get_warning has been run')
names = []
types = []
number_of_threats = 0
forecast_weather()
for i in range(0, number_of_enemies):
enemies = info["enemies"][i]
name = enemies["name"]
type = enemies["type"]
temperature = enemies["temperature"]
temperature = temperature.split("-")
min_temp = temperature[0]
max_temp = temperature[1]
for i in range(len(temperatures)):
if avg_temps[i] <= str(max_temp):
names.append(name)
types.append(type)
number_of_threats += 1
break
os.chdir('..')
write_data(number_of_threats, names, types)
move_to_github()
You are calling the function get_warnings, instead of providing it as a callable. Try:
scheduler.add_job(get_warnings, 'interval', seconds = 120)

Categories

Resources