Example #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')
Example #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)
Example #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)
Example #5
0
from win10toast import ToastNotifier
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager


def debug(msg):
    if len(sys.argv) > 1:
        if sys.argv[1] == '--debug':
            print(str(msg))
            return

clear=lambda: os.system('cls')
toaster = ToastNotifier()

options = webdriver.ChromeOptions()

options.add_argument('--headless')


consoletitle = gw.getActiveWindow().title #sniper.py
debug(consoletitle)
console = gw.getWindowsWithTitle(consoletitle)[0]


print(Fore.RED+"""
 ________  ________  ___   _________    ___    ___      ________  ________   ___  ________  _______   ________     
|\   ____\|\   __  \|\  \ |\___   ___\ |\  \  /  /|    |\   ____\|\   ___  \|\  \|\   __  \|\  ___ \ |\   __  \    
\ \  \___|\ \  \|\  \ \  \\|___ \  \_| \ \  \/  / /    \ \  \___|\ \  \\ \  \ \  \ \  \|\  \ \   __/|\ \  \|\  \   
Example #6
0
import praw
from win10toast import ToastNotifier
from config import myClientId, mClientSecret, myUserAgent, searchSub, searchFlairs

reddit = praw.Reddit(client_id=myClientId, client_secret=mClientSecret, user_agent=myUserAgent)
subreddit = reddit.subreddit(searchSub)
toaster = ToastNotifier()

for submission in subreddit.stream.submissions(skip_existing=True):
    if str(submission.link_flair_text) in searchFlairs:
        toaster.show_toast("Important Post on "+str(submission.subreddit)+": " + str(submission.title))
        continue
Example #7
0
def main():
    # Read ABA checklist
    aba_list = {}
    aba_list_file = open('aba_list.txt')
    for line in aba_list_file.readlines():
        species_elements = line.strip().split(',')
        aba_list[species_elements[0]] = int(species_elements[1])

    # Read exceptions
    exceptions_list = []
    exceptions_file = open('exceptions.txt')
    for species in exceptions_file.readlines():
        exceptions_list.append(species.strip())

    # Read config file
    config_data = json.load(open('config.json'))

    # Create web browser
    br = mechanize.Browser()
    bcj = cj.LWPCookieJar()
    br.set_cookiejar(bcj)

    # Browser options
    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
    br.addheaders = [('User-agent', 'Chrome')]

    # Open the eBird login page
    br.open(login_url)
    # Select the login form
    br.select_form(nr=0)
    # Set credentials
    br.form['username'] = config_data['credentials']['username']
    br.form['password'] = config_data['credentials']['password']
    # Submit the login form
    br.submit()

    # Scrape life list
    print('scraping life list')
    life_list = []
    life_list_html = BeautifulSoup(br.open(life_list_url).read(), 'html.parser')
    for a in life_list_html.find_all(attrs={'data-species-code': True}):
        life_list.append(str.strip(a.text))

    # Scrape eBird alerts
    print('scraping eBird alerts:', end=' ')
    observation_list = []
    alert_regions = config_data['regions']
    alert_regions.append('ABA' if int(config_data['aba_rare']) in [3, 4, 5] else None)
    for alert_region in alert_regions:
        print(alert_region, end=' ')
        alert_html = BeautifulSoup(br.open(alert_url_prefix + alert_sids[alert_region]).read(), 'html.parser')
        for tr in alert_html.find_all('tr', class_='has-details'):
            species_name = str.strip(tr.findChild(class_='species-name').findChild('a').text)
            # Filter out species from ABA RBA whose code is below the specified level
            if alert_region == 'ABA':
                if species_name not in aba_list.keys() or aba_list[species_name] < int(config_data['aba_rare']):
                    continue
            species_count = str.strip(tr.findChild(class_='count').text)
            date_str = str.strip(tr.findChild(class_='date').text)[:-10]  # truncate 'Checklist'
            date_month_str = date_str[0:3]
            date_month = month_dict[date_month_str]
            date_day = int(date_str[4:6])
            date_year = int(date_str[8:12])
            date_hour = 0 if len(date_str) < 13 else int(date_str[13:15])  # some reports don't have a time
            date_minute = 0 if len(date_str) < 13 else int(date_str[16:18])  # some reports don't have a time
            species_date = datetime.datetime(date_year, date_month, date_day, date_hour, date_minute)
            species_checklist_link = 'https://ebird.org' + str.strip(tr.findChild(class_='date').findChild('a')['href'])
            species_location = str.strip(tr.findChild(class_='location').text)[:-4]  # truncate 'Map'
            species_map_link = str.strip(tr.findChild(class_='location').findChild('a')['href'])
            species_county = str.strip(tr.findChild(class_='county').text)
            species_state = str.strip(tr.findChild(class_='state').text).split(',')[0]  # truncate ', United States'
            species_aba_rare = (alert_region == 'ABA')
            observation_list.append(Observation(species_name, species_count, species_date, species_checklist_link,
                                                species_location, species_map_link, species_county, species_state,
                                                species_aba_rare))

    # determine which species would be lifers
    print('\ncreating custom alert')
    observation_list.sort(key=lambda x: x.state, reverse=True)
    observation_list.sort(key=lambda x: x.species, reverse=False)
    lifer_needs = []
    for o in observation_list:
        if o.species not in life_list and o.species not in exceptions_list and (
                o.species in aba_list.keys() or o.aba_rare):
            lifer_needs.append(o)

    # Combine reports of the same species based on the config setting
    combined_needs_dict = {}
    if config_data['combine'] in ['county', 'state', 'all']:
        for obs in lifer_needs:
            key_location = 'all'
            if config_data['combine'] == 'county':
                key_location = obs.county
            elif config_data['combine'] == 'state':
                key_location = obs.state
            key = (obs.species, key_location)
            if key not in combined_needs_dict or obs.date > combined_needs_dict[key].date:
                combined_needs_dict[key] = obs

        lifer_needs = combined_needs_dict.values()

    # build output html file
    output = open('alert.html', 'w')
    output.write('<html><body><h1>eBird Lifer Alert</h1>')
    if len(lifer_needs) == 0:
        output.write('<p>No lifers reported.</p>')
    else:
        output.write('<table border=1 style=border-collapse:collapse cellpadding=3><tr><th>Species</th><th>Count</th>'
                     '<th>Date</th><th>Location</th><th>Map Link</th><th>State</th><th>County</th>'
                     '<th>Checklist Link</th></tr>')
        for l in lifer_needs:
            output.write('<tr>')
            for td in range(len(l.output())):
                output.write('<td>%s</td>' % l.output()[td])
            output.write('</tr>')
        output.write('</table>')
    output.write('</body></html>')
    output.close()

    # display the results in the browser
    if config_data['output'] == 'browser':
        subprocess.Popen('alert.html', shell=True)

    # load the previous alert for comparison
    previous_alert = []
    previous_alert_file = open('alert.txt')
    for raw_obs in previous_alert_file.readlines():
        obs = raw_obs.strip().split(',')
        species = obs[0]
        date_str = obs[2]
        date_month = month_dict[date_str[0:3]]
        date_year = datetime.datetime.today().year
        if datetime.datetime.today().month == 1 and date_month == 12:
            date_year -= 1
        date = datetime.datetime(date_year, date_month, int(date_str[4:6]), int(date_str[7:9]), int(date_str[10:12]))
        location = obs[3]
        previous_alert.append(Observation(species, 0, date, '', location, '', '', '', False))

    # display the results as desktop notifications
    if config_data['output'] == 'desktop':
        toaster = ToastNotifier()
        for obs in lifer_needs:
            if obs in previous_alert:
                continue
            toaster.show_toast(obs.species, obs.county + ', ' + obs.state + ' | ' + obs.date.strftime('%b %d %I:%M %p'),
                               icon_path='ebird_logo.ico', duration=5)
            while toaster.notification_active():
                time.sleep(0.1)

    # write the alert to a file for future reference
    save_data = open('alert.txt', 'w')
    for obs in lifer_needs:
        for item in obs.output():
            save_data.write(str(item) + ',')
        save_data.write('\n')
Example #8
0
                        action='store_true')
    parser.add_argument('--stochastic',
                        help='Use stochastic actions.',
                        action='store_true')
    parser.add_argument('--recurrent',
                        help='Use RNN for policy network.',
                        action='store_true')
    parser.add_argument(
        '--pilot',
        help=
        'If training in a controller environment, this is the pilot agent to control.',
    )
    parser.add_argument(
        '--testvals',
        help='Path to JSON file containing config values to test.',
    )
    parser.add_argument(
        '--save-snapshots',
        help='Save snapshots of the vessel trajectory on a fixed interval.',
    )
    args = parser.parse_args()

    from win10toast import ToastNotifier
    toaster = ToastNotifier()
    try:
        main(args)
        toaster.show_toast("run.py", "Program is done", duration=10)
    except Exception as e:
        toaster.show_toast("run.py", "Program has crashed", duration=10)
        raise e
Example #9
0
from win10toast import ToastNotifier

toaster = ToastNotifier()
toaster.show_toast("You have been HACKED!!!", "Python is awesome!!!", duration=15)
Example #10
0
from egsapi_transform import api_to_GasPrice
from win10toast import ToastNotifier
import time

toast = ToastNotifier()

user_low = input("Price for low: ")
if not user_low:
    user_low = 9999
else:
    try:
        user_low = float(user_low)
    except ValueError:
        print("ValueError")
        exit(1)

user_medium = input("Price for standard: ")
if not user_medium:
    user_medium = 9999
else:
    try:
        user_medium = float(user_medium)
    except ValueError:
        print("ValueError")
        exit(1)

user_high = input("Price for fast: ")
if not user_high:
    user_high = 9999
else:
    try:
Example #11
0
import bs4 as bs
from urllib2 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])
Example #12
0
 def __init__(self):
     if IS_WINDOWS_10:
         self.toaster = ToastNotifier()
from win10toast import ToastNotifier
from beem.account import Account
import time

if __name__ == "__main__":
    toaster = ToastNotifier()

    randowhale = Account("randowhale")
    randowhale.refresh()

    try:
        while True:
            time.sleep(15)
            randowhale.refresh()
            if randowhale.profile["name"] == "Rando Is Sleeping":
                # print(randowhale)
                print("still sleeping, awake in " +
                      randowhale.get_recharge_time_str(99))
            else:
                toaster.show_toast(randowhale.profile["name"],
                                   randowhale.profile["about"],
                                   icon_path=None,
                                   duration=5,
                                   threaded=True)
                # Wait for threaded notification to finish
                while toaster.notification_active():
                    time.sleep(0.1)

    except KeyboardInterrupt:
        pass
Example #14
0
import requests
from bs4 import BeautifulSoup as bs
from win10toast import ToastNotifier
from urllib.request import urlopen, Request
#importing required libs

header = {"User-agent": "George"}
res = Request('https://www.worldometers.info/coronavirus/country/india/',
              headers=header)
html = urlopen(res)

obj = bs(html)

new_cases_today = obj.find('li', {"class": "news_li"}).strong.text.split()[0]
#creating a variable for newcases

new_deaths_today = list(
    obj.find('li', {
        "class": "news_li"
    }).strong.next_siblings)[1].text.split()[0]
#creating a variable for newdeaths

new_deaths_today

notifier = ToastNotifier()
dis_msg = "New_Cases: " + new_cases_today + "\nDeaths: " + new_deaths_today

dis_msg

notifier.show_toast(title="Corona cases update", msg=dis_msg)
from win10toast import ToastNotifier

toast = ToastNotifier()

toast.show_toast("Notification", "This is notifier", duration=5)
Example #16
0
import time
from win10toast import ToastNotifier

toast = ToastNotifier()

toast.show_toast("Timer Started","Remember to take regular breaks!",duration=10,icon_path="eye.ico")
while True:
    time.sleep(20*60)
    toast.show_toast("Blink Break","Look 20 ft away for 20 s!",duration=10,icon_path="eye.ico")
    time.sleep(20)
    toast.show_toast("Break Over", "Back to work!", duration=10, icon_path="eye.ico")

'''
timer = 20*60
while 1:
    print("minutes left:", timer/60)
    time.sleep(60)
    timer -= 1
    if timer == 0:
        toast.show_toast("Blink Break","Look 20 ft away for 20 s!",duration=10,icon_path="eye.ico")
        timer = 20
        while timer >= 0:
            print("seconds left:", timer)
            time.sleep(1)
            timer -= 1
        toast.show_toast("Break Over", "Back to work!", duration=10, icon_path="eye.ico")
        timer = 20*60
'''
def getPercent():
    """
    :rtype: bool
    """
    SYSTEM_POWER_STATUS_P = ctypes.POINTER(SYSTEM_POWER_STATUS)
    GetSystemPowerStatus = ctypes.windll.kernel32.GetSystemPowerStatus
    GetSystemPowerStatus.argtypes = [SYSTEM_POWER_STATUS_P]
    GetSystemPowerStatus.restype = wintypes.BOOL

    toaster = ToastNotifier()
    status = SYSTEM_POWER_STATUS()
    if not GetSystemPowerStatus(ctypes.pointer(status)):
        raise ctypes.WinError()
        return False

    print 'current time: ', time.ctime(time.time())
    print 'current battery level: ', status.BatteryLifePercent

    # case 1: completely charged
    if status.ExternalPower == True and status.BatteryLifePercent == 100:
        return True

    # case 2: charging, but not completed
    elif status.ExternalPower == True and status.BatteryLifePercent < 100:

        # sub case #1: battery almost completely charged
        if status.BatteryLifePercent > 95:

            toaster.show_toast("Battery Level: " +
                               str(status.BatteryLifePercent) + "%",
                               "Battery ALMOST FULL!",
                               duration=60)
            time.sleep(30)

        # sub case #2: battery still has a lot to charge up before reaching completion
        else:

            toaster.show_toast("Battery Level: " +
                               str(status.BatteryLifePercent) + "%",
                               "Battery Charging, nothing critical",
                               duration=60)

            time.sleep(30)

        return False

    # case #3: charger not connected
    elif status.ExternalPower == False:

        #sub case #1: battery life critical and requires charging urgently
        if status.BatteryLifePercent > 5 and status.BatteryLifePercent < 20:

            toaster.show_toast("Battery Level: " +
                               str(status.BatteryLifePercent) + "%",
                               "Battery Low! Please plug in charger",
                               duration=60)
            time.sleep(10)

        #sub case #2: machine running on battery life, not charging
        else:

            toaster.show_toast("Battery Level: " +
                               str(status.BatteryLifePercent) + "%",
                               "Running on Battery Power!",
                               duration=60)
            time.sleep(300)

        return False

    # case #4: failed to retrieve battery info
    else:

        toaster.show_toast("No battery information found",
                           "Battery Percent and Status unknown")
        return False
# Testing connection to REST API
try:
    data = requests.get("http://corona-rest-api.herokuapp.com/Api/pakistan")
except:
    print(
        "You are not connected to a network. Please check internet connection."
    )
    data = None

if data is not None:
    getData = data.json()
    covidPK = getData["Success"]

    # Alert Title
    title = """Covid Pakistan / {}""".format(datetime.date.today())
    # Covid statistics
    message = """In Pakistan Covid-19 Cases: {}, Deaths: {}, Recovered: {}, Cases Today: {}""".format(
        covidPK["cases"], covidPK["deaths"], covidPK["recovered"],
        covidPK["todayCases"])

    # Assigning Win10Toast to var
    toaster = ToastNotifier()

    # Defining icon image path
    toaster.show_toast(
        title,
        message,
        icon_path="E:\Software\Python 3\Python Projects/covid-icon.ico",
        duration=10)
Example #19
0
from time import localtime, strftime
from utils import fight, get_current_node, click, sleep, uniform, sample, pathfinder, shortest, collection, app
from random import randint
from start import sniff, Raw, on_receive, on_msg, useful
from threading import Thread
from win10toast import ToastNotifier
notify, first_fight = ToastNotifier(), True


def get_closest(edge, pos, direction):
    ret, length = [], len(edge)
    for j in range(min(5, length)):
        m = 600
        for i in range(length):
            if (dist := abs(edge[i] % 14 - pos % 14 if direction in (
                    'n', 's') else edge[i] // 14 - pos // 14)) < m:
                if j and prev - dist > 5:
                    continue
                index, m = i, dist
        ret.append(edge[index])
        edge.pop(index)
        length -= 1
        if not j:
            prev = m
    print(ret, edge, pos, direction)
    return ret[randint(0, len(ret) - 1)]


def wrapper(func, *args, **kwargs):
    def wrapped():
        return func(*args, **kwargs)
Example #20
0
import os
from time import sleep
from win10toast import ToastNotifier

# Define dictionaries
directories = {
    "Folder0": "C:\\Users\\Adrian\\Desktop\\test",
    "Folder1": "C:\\Users\\Adrian\\Desktop\\test1"
    # .
    # .
    # .
    # Add more folders if desired
}

# Define toaster
toaster = ToastNotifier()

while True:
    for directory, path in directories.items():
        if os.path.exists(path):
            files = os.listdir(path)

            for file in files:
                toaster.show_toast(directory + " (" + path + ")",
                                   file,
                                   icon_path="python.ico",
                                   duration=10,
                                   threaded=True)

                while toaster.notification_active():
                    sleep(0.1)
Example #21
0
class HomeSchool:
    """
    Alarm when the lesson approaches and ends.
    """
    title = "Ev Okulu"
    notify_near_template = Template(
        "${ders} dersiniz yaklaşıyor. ${baslangic}\nKitaplarınızı hazırlayın.")
    notify_started_template = Template("${ders} dersiniz başladı.")
    notify_finished_template = Template("${ders} dersiniz bitti.")
    on_lesson_template = Template("${ders} (${hoca}) dersiniz devam ediyor.")
    off_lesson_template = Template(
        "Tenefüs vakti. Sonraki ders ${ders} (${hoca}). ${baslangic}")
    no_lesson_template = Template("Bugün başka dersiniz bulunmamaktadır.")
    syllabus_title_template = Template("${tarih} ${gun} ders programı:")
    syllabus_lesson_template = Template(
        "${sayi}. [${baslangic} - ${bitis}] ${ders} (${hoca})")

    def __init__(self, ders_programi_path, language="tr.UTF-8"):
        """
        Set language,
        Read syllabus from JSON file,
        Set day name,
        Set alarm times,
        Set lesson clocks,
        :param ders_programi_path: JSON file path of the syllabus
        """
        locale.setlocale(locale.LC_ALL, language)
        self.toaster = ToastNotifier()
        # self.executor = ThreadPoolExecutor()

        self.interval = 0.5
        self.notification_duration = 30

        self.today = datetime.datetime.today()
        self.day_name = self.today.strftime("%A")
        self.ders_programi = self.get_today_syllabus(ders_programi_path)
        self.last_lesson_time = max(
            [value['bitis'] for key, value in self.ders_programi.items()])

        self.last_lesson = {}

        self.set_last_lesson()

        self.show_syllabus()

    def show_syllabus(self):
        print(
            self.syllabus_title_template.substitute({
                'gun':
                self.day_name,
                'tarih':
                self.today.strftime("%d/%m/%Y")
            }))
        for sayi, lesson in self.ders_programi.items():
            data = {
                'sayi': sayi,
                'baslangic': lesson['baslangic'].strftime('%H:%M'),
                'bitis': lesson['bitis'].strftime('%H:%M'),
                'ders': lesson['ders'],
                'hoca': lesson['hoca'],
            }
            print(self.syllabus_lesson_template.substitute(data))
        print('-' * 40)

    def get_today_syllabus(self, ders_programi_path):
        syllabus = get_dict_from_json_file(ders_programi_path)[self.day_name]
        for key, value in syllabus.items():
            start = get_updated_now_by_given_date(value['baslangic'], '%H:%M')
            finish = get_updated_now_by_given_date(value['bitis'], '%H:%M')
            syllabus[key]['baslangic'] = start
            syllabus[key]['bitis'] = finish
            syllabus[key][
                'durum'] = 'pending'  # pending, near, started, finished
        return syllabus

    def set_last_lesson(self):
        """
        sets the last lesson data to individual variable
        :return:
        """
        for key, value in self.ders_programi.items():
            if value['baslangic'] < datetime.datetime.now() < value['bitis']:
                self.ders_programi[key]['durum'] = 'started'
                self.last_lesson = value
                break

    def get_next_lesson(self):
        """
        returns the next lesson data if exist
        :return:
        """
        for key, value in self.ders_programi.items():
            if datetime.datetime.now() < value['baslangic']:
                return value
        return None

    def run(self):
        """
        Loop until the last lesson is finished.
        :return:
        """
        if not datetime.datetime.now() > self.last_lesson_time:
            threading.Timer(self.interval, self.run).start()
            self.start()

    def start(self):
        """
        Logic processes
        :return:
        """
        self.notification_control()
        self.lesson_control()

    def notification_control(self):
        """
        Check alarm conditions
        :return:
        """
        for key, value in self.ders_programi.items():
            if value['durum'] == 'pending':
                before_start = value['baslangic'] - datetime.timedelta(
                    0, 0, 0, 0, 3)
                if before_start < datetime.datetime.now() < value['baslangic']:
                    self.ders_programi[key]['durum'] = 'near'
                    self.send_notification(value['durum'], lesson=value)
            elif value['durum'] == 'near':
                time_difference = abs((datetime.datetime.now() -
                                       value['baslangic']).total_seconds())
                if time_difference < 2:
                    self.ders_programi[key]['durum'] = 'started'
                    self.last_lesson = value
                    self.send_notification(value['durum'])
            elif value['durum'] == 'started':
                time_difference = abs(
                    (datetime.datetime.now() - value['bitis']).total_seconds())
                if time_difference < 2:
                    self.ders_programi[key]['durum'] = 'finished'
                    self.last_lesson = value
                    self.send_notification(value['durum'])

    def lesson_control(self):
        """
        Check lesson conditions
        :return:
        """
        if self.last_lesson:
            if self.last_lesson['baslangic'] < datetime.datetime.now(
            ) < self.last_lesson['bitis']:
                self.on_lesson()
                return
        self.off_lesson()
        return

    def send_notification(self, msg_type, lesson=None):
        """
        Sends notification
        :param lesson:
        :param msg_type: Alarm type
        :return:
        """
        if lesson:
            data = {
                'ders': lesson['ders'],
                'baslangic': lesson['baslangic'].strftime('%H:%M')
            }
        else:
            data = {
                'ders': self.last_lesson['ders'],
                'baslangic': self.last_lesson['baslangic'].strftime('%H:%M')
            }

        toast_messages = {
            'near': self.notify_near_template.substitute(data),
            'started': self.notify_started_template.substitute(data),
            'finished': self.notify_finished_template.substitute(data)
        }

        # we don't use built-in threaded parameter of toaster,
        # because it has protection to multi notification at in the same time
        # thus we create our own thread
        self.toaster._show_toast(title=self.title,
                                 msg=toast_messages[msg_type],
                                 duration=self.notification_duration,
                                 icon_path=None)

    def on_lesson(self):
        """
        Do something when the lesson is ongoing.
        :return:
        """
        trigger_process = 'CptHost.exe'  # Zoom meeting exe
        processes_to_kill = ['firefox.exe']

        if self.last_lesson:
            data = {
                'ders': self.last_lesson['ders'],
                'hoca': self.last_lesson['hoca']
            }
            print(self.on_lesson_template.safe_substitute(data))

        kill_process(processes_to_kill, trigger_process)

    def off_lesson(self):
        """
        Do something when no lesson.
        :return:
        """
        next_lesson = self.get_next_lesson()
        if next_lesson:
            data = {
                'ders': next_lesson['ders'],
                'hoca': next_lesson['hoca'],
                'baslangic': next_lesson['baslangic'].time()
            }
            print(self.off_lesson_template.safe_substitute(data))
        else:
            print(self.no_lesson_template.safe_substitute())
Example #22
0
import webbrowser
import pyautogui
from time import sleep
from win10toast import ToastNotifier

n = ToastNotifier()

while True:
    File = open("C:/Users/XXX/AppleShortcuts/action.txt", "r+")
    Action = File.readline(2).strip("\n")
    if Action == "yt":
        webbrowser.open("https://youtube.com/")
        File.truncate(0)
    elif Action == "mc":
        MinecraftVersion = File.read().strip("\n")
        pyautogui.moveTo(x=201, y=1066)
        pyautogui.click()
        sleep(5)
        pyautogui.moveTo(x=299, y=83)
        pyautogui.click()
        if MinecraftVersion == "1.15":
            pyautogui.moveTo(x=1417, y=201)
            pyautogui.click()
        else:
            n.show_toast("AppleShortcuts",
                         f"Version {MinecraftVersion} is unsuppurted!",
                         duration=10)
        File.truncate(0)
    else:
        pass
    File.close()
Example #23
0
from win10toast import ToastNotifier

if __name__ == "__main__":
    # Example
    toaster = ToastNotifier()
    #toaster.show_toast("Hello World!!!","Python is 10 seconds awsm!",duration=10)
    toaster.show_toast(
        "Example two",
        "Once you start coding in Python you'll hate other languages")
Example #24
0
import time
import winsound
from datetime import datetime
from win10toast import ToastNotifier

toaster = ToastNotifier()
counter = 0

# Input and setting values to use later on for time & counter
wait_time_input = int(input("Time interval (in seconds) between rests: "))
rest_time = int(input("Duration of rest time (in seconds): "))
super_time = int(
    input("Duration of super rest time (in seconds, happens every hour): "))
wait_time = wait_time_input - rest_time
wait_time_super = wait_time_input - super_time
counter_number_to_check = int(60 / (wait_time / 60))
overall_breaks = 0
normal_breaks = 0
super_breaks = 0
time_spent_on_breaks = 0
launched_time = datetime.now()


def data_presenter(overall_breaks_counter, normal_breaks, super_breaks,
                   time_spent_on_breaks, launched_time):
    print("\n")
    print("I was launched on: " + str(launched_time) + ".")
    print("So far, you've had {0} minute(s) and {1} seconds worth of breaks.".
          format(str((time_spent_on_breaks // 60)),
                 str((time_spent_on_breaks % 60))))
    print(
from win10toast import ToastNotifier
toaster = ToastNotifier()
for i in range(10):
    toaster.show_toast("Virus Warning",
                       "Stealing data",
                       icon_path="favicon.ico",
                       duration=2)

toaster.show_toast("Example two",
                   "This notification is in it's own thread!",
                   icon_path=None,
                   duration=2,
                   threaded=True)
from win10toast import ToastNotifier
import time

while True:
    current_time = time.strftime("%H:%M:%S")
    if current_time == "09:43:00":
        break
    else:
        pass

hr = ToastNotifier()
hr.show_toast("REMINDER", "hello")
Example #27
0
def show_toast(msg):
    toaster = ToastNotifier()
    toaster.show_toast(msg, msg, threaded=True)
Example #28
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jan  3 10:44:43 2018

@author: admin
"""

from win10toast import ToastNotifier
toaster = ToastNotifier()
from datetime import datetime

a = 1
while (True):
    print("Done", +a)
    print(datetime.now())
    toaster.show_toast("---------------Reminder---------------",
                       "Python is awsm by default! Drink Water Please",
                       duration=1800)
    a = a + 1
Example #29
0
def showToast(frm,msg):
    toast=ToastNotifier()
    toast.show_toast(frm,msg)
Example #30
0
from pathlib import Path
import sys
import os
import threading
import subprocess
from win10toast import ToastNotifier


PATH = sys.argv[1]

toast = ToastNotifier()

total_count = 0
total_lines = 0
html_count = 0
html_lines = 0
css_count = 0
css_lines = 0
js_count = 0
js_lines = 0
python_count = 0
python_lines = 0
csharp_count = 0
csharp_lines = 0
cpp_count = 0
cpp_lines = 0
c_count = 0
c_lines = 0
java_count = 0
java_lines = 0
batch_count = 0
Example #31
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])
#!/usr/bin/env python3
import requests
from win10toast import ToastNotifier
import time

toaster = ToastNotifier()
req = requests.session()

login_headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
    'Accept': '*/*',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': '74',
    'Origin': 'https://10.10.11.1:8090',
    'DNT': '1',
    'Connection': 'close',
    'Referer': 'https://10.10.11.1:8090/httpclient.html'
}

live_headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
    'Accept': '*/*',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'DNT': '1',
    'Connection': 'close',
    'Referer': 'https://10.10.11.1:8090/httpclient.html'
        html_page = requests.get(worldmetersLink)
    except requests.exceptions.RequestException as e: 
        print (e)
        continue
    bs = BeautifulSoup(html_page.content, 'html.parser')

    search = bs.select("div tbody tr td")
    start = -1
    for i in range(len(search)):
        if search[i].get_text().find(country) !=-1:
            start = i
            break
    data = []
    for i in range(1,8):
        try:
            data = data + [search[start+i].get_text()]
        except:
            data = data + ["0"]
    
    data= data_cleanup(data)
    message = "Total infected = {}, New Case = {}, Total Deaths = {}, New Deaths = {}, Recovred = {}, Active Case = {}, Serious Critical = {}".format(*data)

    
    if data_check != data:
        data_check = data
        toaster = ToastNotifier()
        toaster.show_toast("Coronavirus {}".format(country) , message, duration = notification_duration )
    else:
        # time.sleep(refresh_time*60)
        exit()
        
Example #34
0
import requests, os, bs4, win10toast
from win10toast import ToastNotifier
url = 'https://www.cricbuzz.com/cricket-match/live-scores'
import time
toaster = ToastNotifier()
while (True):
    try:

        res = requests.get(url)
        ans = bs4.BeautifulSoup(res.text, "html5lib")
        req = ans.select('.cb-lv-scrs-col')
        req = req[0].getText()
        print(req)
        #print(res.text[1:250])
        toaster.show_toast(str(req))
        time.sleep(10)
    except ConnectionError:
        time.sleep(10)
Example #35
0
 def showMeToast(self):
     toaster = ToastNotifier()
     toaster.show_toast("Get Back to Work", "Just Checking, do not procrastinate, work on shit")
Example #36
0
share_id = config.get('auth', 'app_id')
share_token = config.get('auth', 'app_secret')
last_exe = config.get('metrics', 'last_exe')
last_total = int(config.get('metrics', 'last_total'))


# ------------ Real start ----------------
# instanciating Isogeo class
isogeo = Isogeo(client_id=share_id,
                client_secret=share_token,
                lang="fr")

token = isogeo.connect()

# Windows 10 notifications class
notif = ToastNotifier()

# ------------ REAL START ----------------------------
latest_data_modified = isogeo.search(token,
                                     page_size=10,
                                     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')
Example #37
0
class Window(webdriver.Chrome):

    buttonAddAnotherClass = 'DERIVED_REGFRM1_SSR_LINK_STARTOVER'
    buttonEnroll = 'DERIVED_SSS_SCR_SSS_LINK_ANCHOR3'
    buttonEnter = 'DERIVED_REGFRM1_SSR_PB_ADDTOLIST2$9$'
    buttonFinishEnrolling = 'DERIVED_REGFRM1_SSR_PB_SUBMIT'
    buttonStep2of3 = 'DERIVED_REGFRM1_LINK_ADD_ENRL$82$'

    textClass = 'SSR_REGFORM_VW$srt6$0'
    textSelectTerm = 'win0divSSR_DUMMY_RECV1GP$0'
    textAddClasses = 'DERIVED_REGFRM1_SS_TRANSACT_TITLE'
    textError = 'DERIVED_SASSMSG_ERROR_TEXT$0'

    def __init__(self):
        super(Window, self).__init__()
        self.timeout = 400
        self.timeoutUser = 86400
        self.timeoutLag = .5
        self.timeout0 = .025
        self.startTime = '09:00:00'  # 9 am EST
        self.isSuccessful = 'notYet'
        self.toaster = ToastNotifier()
        self.login()
        self.term()
        self.checkTime()
        self.waitEnrOpen()
        self.enrCheck()
        self.notify()

    def login(self):
        """Opens Student Center webpage and wait for user to log in."""
        self.get('https://studentcenter.cornell.edu')
        actions = ActionChains(self)
        actions.send_keys(config.un + Keys.TAB + config.pw + Keys.ENTER)
        actions.perform()
        """
        self.toaster.show_toast('Login',
                                   'Please log in through the opened Chrome window.',
                                   icon_path='images\logo.ico',
                                   duration=10)
        """
        while True:
            try:
                self.switch_to_frame('ptifrmtgtframe')
                break
            except:
                continue
        self.click(Window.buttonEnroll, self.timeout)

    def term(self):
        """Pauses program while user selects term."""
        if self.elementPresent(Window.textSelectTerm):
            self.toaster.show_toast(
                'Select Term',
                'Please select the term in the opened Chrome window, then click "Continue".',
                icon_path='images\logo.ico',
                duration=10)
            while not self.elementPresent(Window.buttonEnter):
                continue

    def checkTime(self):
        """Pauses program until start time."""
        now = datetime.now()
        while (now.strftime("%H:%M:%S") != self.startTime):
            now = datetime.now()
            print(now.strftime("%H:%M:%S"))

    def waitEnrOpen(self):
        """Checks cart is not empty, then begin enroll cycle."""
        self.loadPage()
        self.elementPresentWait(Window.textClass, self.timeout)
        while True:
            try:
                self.loadPage()
                self.click(Window.buttonStep2of3, 0)
                continue
            except:
                self.loadPage()
                self.click(Window.buttonFinishEnrolling, self.timeout)
                self.loadPage()
                self.click(Window.buttonAddAnotherClass, self.timeout)
                break

    def enroll(self):
        """Checks that cart is not empty, then continue through enrollment screens."""
        self.loadPage()
        self.elementPresentWait(Window.buttonEnter, self.timeout)

        try:
            self.click(Window.buttonStep2of3, self.timeout)
        except TimeoutException:
            self.quit()
            return 'no'
        except:
            self.quit()
            return 'yes'

        try:
            self.loadPage()
            self.click(Window.buttonFinishEnrolling, self.timeout)
            self.loadPage()
            self.click(Window.buttonAddAnotherClass, self.timeout)
            return 'notYet'
        except:
            self.quit()
            return 'no'

    def enrCheck(self):
        """Loop through enrollment screens until cart is empty."""
        try:
            while self.isSuccessful == 'notYet':
                self.enroll()
        except:
            self.isSuccessful = 'no'

    def notify(self):
        """Notify user that the program is finished."""
        self.root = Tk()
        if self.isSuccessful == 'yes':
            self.root.title('Congratulations!')
            logo = ImageTk.PhotoImage(Image.open('images\logo_success.jpg'))
        else:
            self.root.title('Error')
            logo = ImageTk.PhotoImage(Image.open('images\logo_failed.jpg'))
        panel = Label(self.root, image=logo)
        panel.pack(side="bottom", fill="both", expand="yes")
        self.root.eval('tk::PlaceWindow . center')
        self.root.lift()
        self.root.attributes('-topmost', True)
        self.root.after_idle(self.root.attributes, '-topmost', False)
        self.root.mainloop()

    def click(self, id, timeout):
        """Waits for element to load then click it."""
        try:
            WebDriverWait(self, timeout).until(
                EC.presence_of_element_located((By.ID, id)))
            self.find_element_by_id(id).click()
        except:
            WebDriverWait(self, timeout).until(
                EC.presence_of_element_located((By.ID, id)))
            self.find_element_by_id(id).click()

    def elementPresent(self, id):
        """Returns boolean saying whether an element exists on a page."""
        try:
            WebDriverWait(self, self.timeout).until(
                EC.presence_of_element_located((By.ID, id)))
            return True
        except:
            return False

    def elementPresentWait(self, id, wait):
        """elementPresent with a given timeout in seconds."""
        try:
            WebDriverWait(self, wait).until(
                EC.presence_of_element_located((By.ID, id)))
            return True
        except:
            return False

    def loadPage(self):
        """Waits for loading image to disappear."""
        try:
            while True:
                time.sleep(self.timeout0)
                self.find_element_by_xpath(
                    '//*[@style="display: none; \position: absolute;\
                right: -205px; z-index: 99991; visibility: visible; top: 196.5px;"]'
                )
        except:
            return

    def windowOpen(self):
        """Returns boolean to check if window is stil open."""
        DISCONNECTED_MSG = 'Unable to evaluate script: disconnected: not connected to DevTools\n'
        if self.get_log('browser')[-1]['message'] == DISCONNECTED_MSG:
            return False
        return True