Esempio n. 1
0
 def windows(self, title, text):
     try:
         from win10toast import ToastNotifier
         toaster = ToastNotifier()
         toaster.show_toast(title, text)
     except ImportError:
         raise Exception('win10toast not installed')
Esempio n. 2
0
def set_clipboard(md_url = "error"):
    OpenClipboard()
    EmptyClipboard()
#    SetClipboardData(win32con.CF_TEXT, md_url)
    SetClipboardText(md_url)
    CloseClipboard()
#     win32api.MessageBox(0, md_url, "Les1ie", 0x00001000)
    toaster = ToastNotifier()
    # toaster.show_toast(md_url, "Les1ie")
    toaster.show_toast(md_url, "mdzz", icon_path='1.ico', duration=3)
Esempio n. 3
0
def growl(text):
    """send native notifications where supported. Growl is gone."""
    if platform.system() == 'Darwin':
        import pync
        pync.Notifier.notify(text, title="Hitman")

    elif platform.system() == 'Linux':
        notified = False
        try:
            logger.debug("Trying to import pynotify")
            import pynotify
            pynotify.init("Hitman")
            n = pynotify.Notification("Hitman Status Report", text)
            n.set_timeout(pynotify.EXPIRES_DEFAULT)
            n.show()
            notified = True
        except ImportError:
            logger.debug("Trying notify-send")
            # print("trying to notify-send")
            if Popen(['which', 'notify-send'], stdout=PIPE).communicate()[0]:
                # Do an OSD-Notify
                # notify-send "Totem" "This is a superfluous notification"
                os.system("notify-send \"Hitman\" \"%r\" " % str(text))
                notified = True
        if not notified:
            try:
                logger.info("notificatons gnome gi???")
                import gi
                gi.require_version('Notify', '0.7')
                from gi.repository import Notify
                Notify.init("Hitman")
                # TODO have Icon as third argument.
                notification = Notify.Notification.new("Hitman", text)
                notification.show()
                Notify.uninit()
                notified = True
            except ImportError:
                logger.exception()
    elif platform.system() == 'Haiku':
        os.system("notify --type information --app Hitman --title 'Status Report' '%s'" % str(text))
    elif platform.system() == 'Windows':
        try:
            from win10toast import ToastNotifier
            toaster = ToastNotifier()
            toaster.show_toast(text, "Hitman")
            # gntplib.publish("Hitman", "Status Update", "Hitman", text=text)
        except Exception:
            logger.exception()
    def process(self, instance):

        # Skipping instance if ftrackData isn"t present.
        if not instance.context.has_data("ftrackData"):
            msg = "No ftrackData present. "
            msg += "Skipping this instance: \"%s\"" % instance
            self.log.info(msg)
            return

        infoStr = giveMeInfo()

        toaster = ToastNotifier()
        toaster.show_toast("Task {0} from shot {1}".format(infoStr[1], infoStr[0]),
                           "Pyblished Completed",
                           #icon_path= iconPath,
                           duration = 10,
                           threaded=True)
Esempio n. 5
0
for i in range(1, 7):
    add = sheet.row_values(i)
    list1.append(add)

print(list1)
datetime_obj = datetime.now().ctime()
day = datetime_obj[0:3].upper()
hrs = datetime_obj[11:13]
min = datetime_obj[14:16]
url= []
teacher = []
print(f"Today is {day} and You have classes of following teacher:")
for i in range(0,len(list1)):
    m = list(list1[i][3].split(","))
    if(day in m):
        n.show_toast(f"Today's Zoom Classes",list1[i][1]+ " @ " + list1[i][0]+":00 AM", duration = 10,icon_path ="zoom.ico")
        print(list1[i][1]+ " @ " + list1[i][0]+":00 AM" )
        teacher.append(list1[i][1])
        url.append(list1[i][2])

while True:
    datetime_obj = datetime.now().ctime()
    hrs = datetime_obj[11:13]
    min = datetime_obj[14:16]
    time = int(hrs)*100+int(min)
    if(time >= int(955) and time <= int(1040)):
        print(f"Opening of class {teacher[0]} ")
        webbrowser.open(url[0])
        sleep(60*61)
    elif(time >= int(1055) and time <= int(1140)):
        print(f"Opening of class {teacher[1]} ")
Esempio n. 6
0
def sendWin10Notification(message: str):
    toaster = ToastNotifier()
    toaster.show_toast("ZF Vouchering Process Status:",
                       message,
                       icon_path=None,
                       duration=10)
import time
from brainyquote import pybrainyquote


def randomquote(
):  #Used to return a random quote from BrainyQuotes official website.
    random = (pybrainyquote.get_random_quote())
    print(random)
    string = ''.join(str(e) for e in random)
    string = string.replace('<img alt=', '').replace('"', '')
    word = string.split('.')
    #To return the value to the function.
    return (word[0])
    #To print on Command prompt instead of being pushed a notification
    #print(word[0])


from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Quote for the day",
                   randomquote(),
                   icon_path=None,
                   duration=10)
Esempio n. 8
0
import time
from english_words import english_words_set
from PyDictionary import PyDictionary
from win10toast import ToastNotifier
import json
if __name__ == '__main__':
    dictionary = PyDictionary()
    word_list = list(english_words_set)
    toast = ToastNotifier()
    for word in word_list:
        dictionary=PyDictionary(word)
        for value in dictionary.getMeanings().values():
           if value == None:
                continue
           m = list(value.values())
           k=list(value.keys())
           for i in range(len(m)):
              l=[]
              for j in range(len(m[i])):
                s = f"{k[i]} \n{j+1}:{m[i][j]}"
                l.append(s)
           toast.show_toast(word.title(),"\n"+("\n".join(l)).title(), duration=12,
                         icon_path="C:\web devlopment\project\word_Notifier\icon.ico")
        time.sleep(60*60)
#Create Toast Notification Using Python

#pip install win10toast
from win10toast import ToastNotifier
notify = ToastNotifier()
notify.show_toast("I am Titile", "Message Here", duration=3, threaded=True)
print("Another Process Some Code Here")

#To Learn More About This Code
#Checkout My Youtube Channel - https://www.youtube.com/channel/UCmOBuijDvNgUMlqpzrwEBcw
Esempio n. 10
0
def notify_win10toast():
    toaster = ToastNotifier()
    toaster.show_toast("Hello World!!!",
                       "Python is 10 seconds awsm!",
                       icon_path="custom.ico",
                       duration=10)
Esempio n. 11
0
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup as bs
from win10toast import ToastNotifier

header = {"User-Agent": "Mozilla"}
req = Request("https://www.worldometers.info/coronavirus/country/india/",
              headers=header)
html = urlopen(req)

html.status
obj = bs(html)
new_cases = obj.find("li", {"class": "news_li"}).strong.text.split()[0]
death = list(obj.find("li", {
    "class": "news_li"
}).strong.next_siblings)[1].text.split()[0]

#Notifier

notifier = ToastNotifier()
message = "New Cases - " + new_cases + "\nDeath - " + death
notifier.show_toast(title="COVID-19 Update - 'INDIA'",
                    msg=message,
                    duration=8,
                    icon_path=r"virus.ico")
    data = requests.get(
        "https://api.covid19india.org/data.json")  # covid19india database
except:
    print("Check your internet connection")
    data = None

if data is not None:
    getData = data.json()
    covid_India = getData["cases_time_series"]  # national level data
    covid_India1 = getData["statewise"]
    title = """Ashish's COVID-19 India Live  {}""".format(
        datetime.date.today())
    n = len(covid_India)
    a = covid_India[n - 1]  # yesterday data
    b = covid_India1[0]  # current data
    l1 = list(b.values())
    l = list(a.values())
    tconf = l1[3]  # today's confirmed
    conf = l1[1]
    active = l1[0]
    deaths = l1[2]
    recov = l1[7]
    m1 = "Total cases is: %s " % conf + "\n"
    m5 = "Active cases: %s " % active + " | "
    m2 = "Total Deaths: %s " % deaths + "\n"
    m3 = "Total Recovered: %s " % recov + "\n"
    m4 = "Today's confirmed cases: %s" % tconf
    message = m1 + m5 + m2 + m3 + m4
    toaster = ToastNotifier()
    toaster.show_toast(title, message, icon_path="Corona.ico", duration=100)
Esempio n. 13
0
def low_battery():
    if percent < 20:
        notify = ToastNotifier()
        notify.show_toast("CONNECT CHARGER", "20% Charge remaining",
                          icon_path="C:/Windows/SystemApps/Microsoft.Windows.SecHealthUI_cw5n1h2txyewy/Assets/Device.contrast-white.ico",
                          duration=10)
Esempio n. 14
0
import time
import pyautogui
import codecs
import datetime
import sys
import os
import ctypes
from win10toast import ToastNotifier

SLEEPTIME = 180

if __name__ == '__main__':
    i = 0
    toaster = ToastNotifier()
    today = datetime.datetime.now()
    toaster.show_toast("INFO", f"{today}: PyRecorder started... ", duration=10)
    print(f"{today}: PyRecorder started...")
    f = None
    path = os.environ['HOMEPATH'] + "\\Documents\\_pyrecordings\\"
    while True:
        today = datetime.datetime.now()
        try:
            fw = pyautogui.getActiveWindow()
            d = '{:02d}'.format(today.day)
            m = '{:02d}'.format(today.month)
            y = '{:02d}'.format(today.year)

            filename = path+y+'-'+m+'-pyrecorder.csv'

            with codecs.open(filename, 'a+', 'UTF-8') as f:
                f.write(str(today)+',|'+fw.title+'\n')
Esempio n. 15
0
def low_level_notification(model, percent):
    notifer = ToastNotifier()
    notifer.show_toast(model,
                       "Your battery is going low ({}%)".format(percent),
                       "./icons/low_n.ico", 5, True)
Esempio n. 16
0
                print("In how many minutes?")
                speak("In how many minutes?\n")
                time_min = takeCommand()
                time_min = float(time_min)
            except:
                header = input("Title of reminder\n")
                text = input("Message of remindar\n")
                time_min = float(input("In how many minutes?\n"))
            time_min = time_min * 60
            print("Setting up reminder..")
            time.sleep(2)
            print("all set!")
            time.sleep(time_min)
            toaster.show_toast(
                f"{header}",
                f"{text}",
                icon_path="C:\\Users\\abhay\\Desktop\\ChatBot\\profile.ico",
                duration=10,
                threaded=True)
            while toaster.notification_active():
                time.sleep(0.005)
        elif 'calculation' in query:

            def add(x, y):
                return x + y

            def subtract(x, y):
                return x - y

            def multiply(x, y):
                return x * y
Esempio n. 17
0
def notification(name):
    from win10toast import ToastNotifier
    toaster = ToastNotifier()
    toaster.show_toast("Pink Scrape", "New Listing: {}".format(name))
Esempio n. 18
0
torch.save(cont, out_path)

end_t = default_timer()

total_t = end_t - start_t

writer.add_scalar('Total training time', total_t, epoch * len(trainloader) + i)

print('Training Complete')
images, labels = next(iter(testloader))
images = images.to(cont.device).cuda(cont.device)
labels = labels.to(cont.device).cuda(cont.device)
with torch.no_grad():
    output = cont(images)

fig = plt.figure()
for i in range(len(images)):
    plt.subplot(batch_size / 4, 4, i + 1)
    plt.tight_layout()
    plt.imshow(images[i][0].cpu(), cmap='gray', interpolation='none')
    plt.title("Prediction: {}".format(
        output.data.max(1, keepdim=True)[1][i].item()))
    plt.xticks([])
    plt.yticks([])

fig.savefig(out_dir / 'predict.png')

plt.show()

notify.show_toast(f"Training complete",
                  "Your training has finished. Total time: {total_t}")
Esempio n. 19
0
import requests
import json
from win10toast import ToastNotifier
from time import sleep

r = requests.get('https://coronavirus-19-api.herokuapp.com/all')

data = r.json()
text = f'Confirmed Cases : {data["cases"]} \nDeaths : {data["deaths"]} \nRecovered : {data["recovered"]}'

while True:
    toast = ToastNotifier()
    toast.show_toast("Covid-19 Notification", text, duration=20)
    sleep(60)
            bat1 = main['batting']['batsman'][0]
            bat2 = main['batting']['batsman'][1]
            #print(bat1['name'])
            message = i['srs'] + "      " + "Format: " + i[
                'type'] + "\n" + "Score: " + main['batting'][
                    'team'] + " " + ms['runs'] + '/' + ms[
                        'wickets'] + " (" + ms['overs'] + ")" + "\n" + bat1[
                            'name'] + ":" + bat1['runs'] + "(" + bat1[
                                'balls'] + ")   " + bat2['name'] + ":" + bat1[
                                    'runs'] + "(" + bat2['balls'] + ")"

toaster = ToastNotifier()
prev_time = time.time()
while (True):
    if (time.time() - prev_time > 2):
        toaster.show_toast("Sample Notification", message)
        prev_time = time.time()
'''
import pyautogui as p
import time
import webbrowser as w
#Declaring the variables.
x = input("Type the name of receiver: ").strip()
y = input("Type message: ").strip()
s = int(input("Enter HOUR: "))
c = int(input("Enter MINUTE: "))
print("The message will be sent at the given time")
if (s == 00):
    s = 24
if (c == 00):
    c = 60
Esempio n. 21
0
 def get(self, todo_str):
     toaster = ToastNotifier()
     toaster.show_toast(todo_str, todo_str, 'favicon.ico')
Esempio n. 22
0
import os
from win10toast import ToastNotifier

# Generate a list of the srt and vid files in the directory
srtlist = []  #To store the list of .srt files in the directory
vidlist = []
for file in os.listdir():
    if '.srt' in file:
        srtlist.append(file)
    if '.avi' in file or '.mkv' in file or '.mp4' in file:
        vidlist.append(file)

# Now rename the files based on the filename (without extension) of the video
# also keep count of the changes made
changeCount = 0
for srt, vid in zip(srtlist, vidlist):
    vid = os.path.splitext(vid)[0]  # Strips the filename from the file
    os.rename(srt, vid + '.srt')  # renames the file with an appended '.srt'
    changeCount += 1

# Display a tost notification to let the user know what happened
toaster = ToastNotifier()
toaster.show_toast("Enjoy the binge!",
                   str(changeCount) + " subtitle files were renamed",
                   duration=1.5)

# More comments here cause why not
Esempio n. 23
0
                    int_yesterday_price[number] * 100, 2))
            print(company_name[number] + " : " + present_price[number] +
                  u"  수익률 : " + str(revenue_rate[number]) + "%")
            if before_pirce[number] != present_price[number]:
                if before_pirce[number] > present_price[number]:
                    # print(company_name[number]+u" 이전주가 : "+yesterday_price[number]+"\n"+u" 주가 : "+present_price[number]+ u" ▼"+str(revenue_rate[number])+"%\n" )
                    story += (company_name[number] + u" 어제주가 : " +
                              yesterday_price[number] + "\n" + u" 현주가 : " +
                              present_price[number] + u" ▼" +
                              str(revenue_rate[number]) + "%\n")
                else:
                    story += (company_name[number] + u" 어제주가 : " +
                              yesterday_price[number] + "\n" + u" 현주가 : " +
                              present_price[number] + u" ▲" +
                              str(revenue_rate[number]) + "%\n")
                    # print(company_name[number]+u" 이전주가 : "+yesterday_price[number]+"\n"+u" 주가 : "+present_price[number]+ u" ▲"+str(revenue_rate[number])+"%\n" )
                before_pirce[number] = present_price[number]
        print("-------------------------------")

        if story:
            toaster.show_toast(u"주가 분석", story, duration=10)
    #날짜 변환시 자동으로 금일 종가/날짜 저장  and before_date[0]!=now.strftime("%Y-%m-%d")
        if int(now.strftime("%H%M")) > 1530 or int(now.strftime("%H%M")) < 900:
            # print("test")
            for number in range(line_num):
                update_date(now.strftime("%Y-%m-%d"), present_price[number],
                            company_codes[number])
            before_date[0] = now_date

    story = ""
    time.sleep(30)
Esempio n. 24
0
def notify_desktop(value):
    toaster = ToastNotifier()
    toaster.show_toast("Ipl 2018 Update", value, duration=10)
Esempio n. 25
0
#python -m pip install win10toast
from win10toast import ToastNotifier

#one time initialization
toaster = ToastNotifier()

#Show notification whenever needed

toaster.show_toast("Notification!",
                   "Alert! Yes",
                   threaded=True,
                   icon_path=None,
                   duration=3)
#for 3 seconds

#To check any notifiacrtion are active
#use "toaster.notification_active()"
'''
import time
while toaster.notification_active():
    time.sleep(0.1)
'''
Esempio n. 26
0
        mainFrame.show()

    def exit(self):
        mainFrame.close()


if __name__ == '__main__':

    camera_width = 640
    camera_height = 480
    args = arg()
    EYE_AR_THRESH = args['threshold']

    toaster = ToastNotifier()
    toaster.show_toast("Twinkle",
                       "Running...",
                       icon_path='img/eye-tracking.ico',
                       threaded=True)
    th = CameraThread()
    th.start()
    time.sleep(4.0)

    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    mainFrame = Frame()

    # check Camera!
    mainFrame.buildPopup()

    trayIcon = SysetmTrayIcon(QIcon('img/program_icon.png'))
    trayIcon.show()
Esempio n. 27
0
 def showMeToast(self):
     toaster = ToastNotifier()
     toaster.show_toast("Get Back to Work", "Just Checking, do not procrastinate, work on shit")
Esempio n. 28
0
files = output.split("\r\n")

del files[-1]  #deletes the last entry "" from the list

notification = ToastNotifier()

removed = False
try:
    for file in files:
        if "Ground.exe" in file:
            os.remove(file)
            removed = True
except PermissionError:  #In case prompted for administrator password and one gets it wrong
    removed = None

if removed == True:
    notification.show_toast(title='Notification',
                            msg='Successfully removed Ground.exe',
                            duration=5,
                            threaded=False)
elif removed == False:
    notification.show_toast(title='Notification',
                            msg='Ground.exe was not found in your computer',
                            duration=5,
                            threaded=False)
elif removed == None:
    notification.show_toast(title='Notification',
                            msg='Permission denied - can\'t remove ground.exe',
                            duration=5,
                            threaded=False)
Esempio n. 29
0
import bs4 as bs            # bs4 library run as bs
from urllib import request
from win10toast import ToastNotifier

toaster = ToastNotifier()

url = "http://www.cricbuzz.com/cricket-match/live-scores"

sauce = request.urlopen(url).read()
soup = bs.BeautifulSoup(sauce, "lxml")
# print(soup)
score = []
results = []
# for live_matches in soup.find_all('div',attrs={"class":"cb-mtch-lst cb-col cb-col-100 cb-tms-itm"}):
for div_tags in soup.find_all('div', attrs={"class": "cb-lv-scrs-col text-black"}):
    score.append(div_tags.text)
for result in soup.find_all('div', attrs={"class": "cb-lv-scrs-col cb-text-complete"}):
    results.append(result.text)

print(score[0], results[0])
toaster.show_toast(title=score[0], msg=results[0])
Esempio n. 30
0
from win10toast import ToastNotifier
import time


toaster = ToastNotifier()
while True:
    toaster.show_toast("!!!!!", "#####")
    time.sleep(25*60)
Esempio n. 31
0
class DownloadHandler(FileSystemEventHandler):
    def __init__(self, item, destination):
        self.folder = item["folder"]
        self.moveFolders = item["moveFolders"]
        self.destination_folder = destination
        self.i = 0
        self.running = False
        self.notifier = ToastNotifier()

    def map_extension(self, ext):
        word_exts = [".docx", ".doc"]
        ppt_exts = [".pptx", ".ppt"]
        music_exts = [".mp3", ".iff", ".mpa", ".wav", ".m4a"]
        exe_and_installers = [".exe", ".msi", ".jar", ".bat"]
        photos = [".jpg", ".jpeg", ".png"]
        videos = [".mp4", ".mkv", ".m4p", ".avi", ".wmv"]
        code = [".c", ".java", ".class", ".cpp", ".cs", ".h", ".lua", ".m", ".py",
                ".sh", ".swift", ".vb", ".vcxproj", ".sql", ".ts", ".tsx", ".jsx"]
        fonts = [".otf", ".woff", ".woff2", ".ttf"]

        if ext == ".pdf":
            return "PDF_DOCS"
        elif ext in word_exts:
            return "WORDS_DOCS"
        elif ext in ppt_exts:
            return "PPTX_DOCS"
        elif ext in music_exts:
            return "MUSICAS"
        elif ext in exe_and_installers:
            return "EXECUTAVEIS"
        elif ext in photos:
            return "FOTOS"
        elif ext in videos:
            return "VIDEOS"
        elif ext in code:
            return "DEV_CODES"
        elif ext == ".txt":
            return "TEXTOS"
        elif ext == ".gif":
            return "GIFS"
        elif ext in fonts:
            return "FONTS"
        else:
            return ""

    def on_modified(self, event):
        if self.running:
            return
        self.running = True
        for filename in os.listdir(self.folder):
            self.i = 0
            base_name, extension = os.path.splitext(filename)

            if extension and self.map_extension(extension.lower()) != "":
                sub_folder = self.map_extension(extension.lower()) + "/"
                if not os.path.exists(self.destination_folder + "/" + sub_folder):
                    os.mkdir(self.destination_folder + "/" + sub_folder)
                new_name = sub_folder + filename
                file_exists = os.path.isfile(
                    self.destination_folder + "/" + new_name)
                while file_exists:
                    self.i += 1
                    new_name = "{} ({}){}".format(
                        sub_folder + base_name, self.i, extension)
                    file_exists = os.path.isfile(
                        "{}/{}".format(self.destination_folder, new_name))
                source = self.folder + "/" + filename
                new_destination = self.destination_folder + "/" + new_name
                self.notifier.show_toast("Python", "Movendo arquivo {} para {}".format(
                    filename, self.destination_folder + '/' + sub_folder), duration=8)
                shutil.move(source, new_destination)
            elif not extension and self.moveFolders:  # folders
                new_destination = self.destination_folder + "/Folders/" + filename
                folder_exists = os.path.exists(new_destination)
                while folder_exists:
                    self.i += 1
                    new_name = "{} ({})".format(filename, self.i)
                    new_destination = self.destination_folder + "/Folders/" + new_name
                    folder_exists = os.path.exists(new_destination)
                source = self.folder + "/" + filename
                self.notifier.show_toast("Python", "Movendo pasta {} para {}".format(
                    filename, self.destination_folder + '/Folders'), duration=8)
                shutil.move(source, new_destination)
        self.running = False
Esempio n. 32
0
elif 'my personal details' in query:   #tells me few small personal details
    speak("Your  name  is  Rishabh  Kamlesh  Jain.  Your  age  is  18  years  and  you  are  a  sophomore  at  VIT  Bhopal  University.  You  currently  are  studying  CSE   with  Artificial  Intelligence  and  Machine  Learning. Cant  disclose  more information  as  it  is  against  my  rules!")
elif 'alarm' in query:    #sets an alarm according to the time you want and shows a notification on windowss\
    speak("What hour do you want the alarm")
    hours = int(input())
    speak("What minute do you want the alarm")
    minutes = int(input())
    speak("Is it morning or evening")
    AmPm = takecommand()
    if 'evening' in AmPm:
        hours = hours + 12
    while True:
        if (hours == datetime.datetime.now().hour) and (minutes == datetime.datetime.now().minute):
            speak("SIR WAKE UP! ITS TIME !")
            toaster=ToastNotifier()
            toaster.show_toast("ALert!",'The timer is over ',threaded=True,icon_path=None,duration=10)
            wishme()
            break
elif 'time' in query:  # tells the present time
    strTime = datetime.datetime.now().strftime("%H:%M:%S")
    speak(f"Sir the time is {strTime}")
elif 'open Dev C plus plus' in query:  # opens Devc++
    codepath = 'C:\\Program Files (x86)\\Dev-Cpp\\devcpp.exe'
    os.startfile(codepath)
elif 'open dev c++' in query:  # opens Devc++
    codepath = 'C:\\Program Files (x86)\\Dev-Cpp\\devcpp.exe'
    os.startfile(codepath)
elif 'email' in query:  # pseudo email sender
    try:
        speak('What should I send')
        content = takecommand()
Esempio n. 33
0
class CourseSearcher():
    def __init__(self):
        self.cookies = dict()
        self.cookies_file = 'cookies.txt'
        self.search_urls = {
            '学位基础课':
            'http://yjsxk.fudan.edu.cn/yjsxkapp/sys/xsxkappfudan/xsxkCourse/loadXwzykCourseInfo.do?_=1599458690255',
            # '学位专业课': 'http://yjsxk.fudan.edu.cn/yjsxkapp/sys/xsxkappfudan/xsxkCourse/loadXwzykCourseInfo.do?_=1599458706907',
            # '专业选修课': 'http://yjsxk.fudan.edu.cn/yjsxkapp/sys/xsxkappfudan/xsxkCourse/loadXwzykCourseInfo.do?_=1599458740795',
        }
        self.toaster = ToastNotifier()
        self.blacklist = ['软件定义网络', '智能视频监控技术', '计算理论', '知识图谱', '高级数据库']
        self.whitelist = ['机器学习理论']

    def read_cookies(self):
        with open(self.cookies_file, 'r', encoding='utf-8') as f:
            cookies_txt = f.read().strip(';')  # 读取文本内容
            # 由于requests只保持 cookiejar 类型的cookie,而我们手动复制的cookie是字符串需先将其转为dict类型后利用requests.utils.cookiejar_from_dict转为cookiejar 类型
            # 手动复制的cookie是字符串转为字典:
            for cookie in cookies_txt.split(';'):
                name, value = cookie.strip().split('=', 1)  # 用=号分割,分割1次
                self.cookies[name] = value  # 为字典cookies添加内容
        # 将字典转为CookieJar:
        cookiesJar = requests.utils.cookiejar_from_dict(self.cookies,
                                                        cookiejar=None,
                                                        overwrite=True)
        return cookiesJar

    def available_hints(self, course):
        self.toaster.show_toast("有余量了",
                                "{}: {}".format(course['KCLBMC'],
                                                course['KCMC']),
                                icon_path=None,
                                duration=5,
                                threaded=False)

    def is_course_available(self, course_type_resp):
        print('=============================================')
        for index, course in enumerate(course_type_resp['datas']):
            print("{} {} {}".format(course['KCMC'], course['KXRS'],
                                    course['DQRS']))

            if course['KXRS'] != course['DQRS']:
                if course['KCMC'] in self.whitelist:
                    if course['RKJS'] == '池明旻':
                        continue
                    self.available_hints(course)
                else:
                    if course['IS_CONFLICT'] == 0 and course[
                            'KCMC'] not in self.blacklist:
                        self.available_hints(course)

    # 刷课
    def search(self):
        self.session = requests.session()
        self.session.cookies = self.read_cookies()
        while True:
            time.sleep(1.5)
            for course_type, url in self.search_urls.items():
                try:
                    response = self.session.get(url, timeout=5)
                    response = response.content.decode()
                    response = json.loads(response)
                    self.is_course_available(response)
                except:
                    continue

    # 抢课(捡漏)
    def frequent_course_request(self):
        self.session_choose = requests.session()
        self.session_choose.cookies = self.read_cookies()

        form_data = {
            'bjdm': '2020202101COMP630036.01',
            'lx': '8',
            'csrfToken': None
        }

        while True:
            new_token = self._refresh_csrfToken(self.session_choose)
            form_data['csrfToken'] = new_token

            while True:
                time.sleep(1.5)
                response = self._request_course(self.session_choose, form_data)

                if response['code'] == 0:
                    if '过期' in response['msg']:
                        break
                else:
                    return

    def _request_course(self, session, form_data):
        try:
            response = session.post(
                url=
                'http://yjsxk.fudan.edu.cn/yjsxkapp/sys/xsxkappfudan/xsxkCourse/choiceCourse.do?_=1600059897179',
                data=form_data,
                timeout=5)
            response = response.content.decode()
            response = json.loads(response)

            print(response)
        except:
            response = None

        return response

    def _refresh_csrfToken(self, session):
        try:
            response = self.session_choose.get(
                'http://yjsxk.fudan.edu.cn/yjsxkapp/sys/xsxkappfudan/xsxkHome/gotoChooseCourse.do',
                timeout=5)
            response = response.content.decode()
            new_token = re.findall(r"csrfToken\" value='(.*)'", response)[0]
        except:
            new_token = None

        return new_token
Esempio n. 34
0
import os, json, lib
from win10toast import ToastNotifier

toaster = ToastNotifier()
checker = lib.WebChecker()

file_list = os.listdir("./websites")
toaster.show_toast("Website checker",
                   "Adding following websites:\n" + '\n'.join(file_list),
                   "resources/internet.ico",
                   duration=3)
for file_name in file_list:
    with open("./websites/" + file_name, "r", encoding="utf-8") as file:
        raw_data = json.load(file)
        checker.add_target(
            lib.Website(raw_data['host'], raw_data['interval'],
                        raw_data['condition']))

toaster.show_toast("Website checker",
                   "Ready!",
                   "resources/success.ico",
                   duration=3)
checker.start()
# while True:
#     pass
Esempio n. 35
0
valores = valores.split(',')

# if valores is not list:
#     x = valores
#     valores = []
#     valores.append(x)

easygui.msgbox("COMEÇAR?")
time.sleep(5)

for i in valores:
    kb.write(i)
    kb.send('enter')
    time.sleep(5)
    kb.send('f8')
    time.sleep(1)
    kb.send('tab')
    for i in range(10):
        kb.send('right')
    kb.send('enter')

    # easygui.msgbox("Continuar?")
    if easygui.ynbox() == True:
        kb.send('ctrl+s')
        time.sleep(3)
    else:
        toaster.show_toast("", "Finalizado - break", duration=2)
        break

toaster.show_toast("", "Finalizado", duration=2)
Esempio n. 36
0
                                     order_by="modified",
                                     whole_share=0,
                                     sub_resources=["events"]
                                     )

# parsing the previous date
last_exe = dtparse(last_exe).strftime("%a %d %B %Y (%H:%M)")
# last_exe = last_exe.decode("Latin1")

# comparing total of metadats shared since last time
now_total = latest_data_modified.get('total')

if now_total > last_total:
    notif.show_toast("Isogeo - Total partage",
                     "{} données ajoutées\ndepuis le {}"
                     .format(now_total - last_total, last_exe),
                     icon_path=r"img/favicon.ico",
                     duration=10)
elif now_total < last_total:
    notif.show_toast("Isogeo - Total partage",
                     "{} données retirées\ndepuis le {}"
                     .format(last_total - now_total, last_exe),
                     icon_path=r"img/favicon.ico",
                     duration=10)
elif now_total == last_total:
    notif.show_toast("Isogeo - Total partage",
                     "Pas de changement \ndepuis le {}"
                     .format(last_exe),
                     icon_path=r"img/favicon.ico",
                     duration=10)
else:
Esempio n. 37
0
                time.sleep(0.999)
                last_time = LongStopInter + 1 - i
                print(
                    '\rNo Seat in ' + Libname +
                    ' library for a long time, temporarily stop detection for %s seconds.'
                    % last_time,
                    end="")
            failCount = 0
        drive.refresh()


if __name__ == '__main__':
    VarValue = ''
    toaster.show_toast("Python Script Running",
                       "Script screening library seat is running",
                       icon_path=None,
                       duration=20,
                       threaded=True)
    while toaster.notification_active():
        time.sleep(0.1)
    username = input("请输入读者证号码:")
    password = input("请输入密码:")
    print(username)
    print(password)
    date0 = datetime.datetime.today()
    hh = date0.hour
    [mm, dd] = [date0.month, date0.day]
    date1 = date0 + datetime.timedelta(days=1)
    [tmm, tdd] = [date1.month, date1.day]
    flagdate = int(input("Select date:\n1.today\n2.tomorrow\n"))
    listOfLib = [