async def get_prayertimes_local(self, location, calculation_method): async def get_information(location): url = "http://api.aladhan.com/v1/hijriCalendarByAddress" params = {"address": location} async with self.session.get(url, headers=headers, params=params) as resp: data = await resp.json() meta = data['data'][0]['meta'] coordinates = (meta['latitude'], meta['longitude']) timezone_name = meta['timezone'] time = dt.datetime.now(gettz(timezone_name)) timezone_offset = time.utcoffset() / timedelta(hours=1) return coordinates, time, timezone_offset def get_method_name(method_id): id_to_name = { 3: 'MWL', 2: 'ISNA', 5: 'Egypt', 4: 'Makkah', 1: 'Karachi', 7: 'Tehran', 0: 'Jafari', 8: 'Gulf', #TODO add this method to praytimes.py 9: 'Kuwait', #TODO add this method to praytimes.py 10: 'Qatar', #TODO add this method to praytimes.py 11: 'Singapore', #TODO add this method to praytimes.py 12: 'France', #TODO add this method to praytimes.py 13: 'Turkey', #TODO add this method to praytimes.py 14: 'Russia', #TODO add this method to praytimes.py # didn't include method 'MOONSIGHTING' because it uses 'shafaq' parameter, # which isn't used in praytimes.py } return id_to_name[method_id] coordinates, time, time_offset = await get_information(location) date = (time.year, time.month, time.day) method_name = get_method_name(calculation_method) prayTimes = PrayTimes() prayTimes.setMethod(method_name) prayTimes.adjust({"highLats": "AngleBased"}) prayTimes.adjust({"asr": "Standard"}) times = prayTimes.getTimes(date, coordinates, time_offset) prayTimes.adjust({"asr": "Hanafi"}) timesWithHanafiAsr = prayTimes.getTimes(date, coordinates, time_offset) fajr = times['fajr'] sunrise = times['sunrise'] dhuhr = times['dhuhr'] asr = times['asr'] hanafi_asr = timesWithHanafiAsr['asr'] maghrib = times['maghrib'] isha = times['isha'] imsak = times['imsak'] midnight = times['midnight'] sunrise = times['sunrise'] readable_date = time.strftime('%d %B, %Y') return fajr, sunrise, dhuhr, asr, hanafi_asr, maghrib, isha, imsak, midnight, readable_date
def getTimes(for_date): prayTimes = PrayTimes() prayTimes.setMethod('test') new_settings = { "imsak": '10 min', "dhuhr": '0 min', "asr": 'Standard', "highLats": 'AngleBased', "maghrib": '-6 min' } offset = { "fajr": -2, "dhuhr": +5, "asr": +5, "maghrib": 0, "isha": -3 } prayTimes.adjust(new_settings) prayTimes.tune(offset) isSummerTime = 1 times = prayTimes.getTimes(for_date, places['berlin'], 1, dst=isSummerTime) return times
def Resolve(cls, method, config, location, date): def buildCacheKey(loc, date): return "%s:%s:%s" % (method, resolver.CacheKey( loc, date), date.strftime("%Y-%m-%d")) if method in TimetableResolver._resolvers: # Dedicated resolver, vs. calculation. # We assume this lookup is costly (calling a remote API, and cache it). resolver = TimetableResolver._resolvers[method] query_cache_key = buildCacheKey(location, date) if query_cache_key in TimetableResolver._cache: return TimetableResolver._cache[query_cache_key] try: cache_obj = TimetableCachedTimes.objects.get( key=query_cache_key) TimetableResolver._cache[query_cache_key] = ( cache_obj.location_geoname, cache_obj.times) except TimetableCachedTimes.DoesNotExist: multi_day_times = resolver.Times(location, date) # The resolver returns a list of (location, date, timedict) tuples. # Obviously the location shouldn't ever change over a range, but oh well, we're storing it discretely anyway. for location_geoname, date, times in multi_day_times: day_cache_key = buildCacheKey(location, date) TimetableResolver._cache[day_cache_key] = ( location_geoname, times) TimetableCachedTimes.objects(key=day_cache_key).update( key=day_cache_key, location_geoname=location_geoname, times=times, upsert=True) return TimetableResolver._cache[query_cache_key] else: pt = PrayTimes() pt.setMethod(method) pt.adjust({"asr": config["asr"]}) return None, pt.getTimes(date, location, 0, format="Float")
from praytimes import PrayTimes #Get Prayer Times #If located in southern hemisphere, use a negative latitude value #-------------------- #User location lat = 51.5171 long = 0.1062 #System time and date now = datetime.datetime.now() #Prayer time calculation #Additional options available in praytimes.py PT = PrayTimes('ISNA') times = PT.getTimes((now.year, now.month, now.day), (lat, long), 0, 1) print times['fajr'] print times['dhuhr'] print times['asr'] print times['maghrib'] print times['isha'] #Update Crontab with Prayer Times #--------------------------------- from crontab import CronTab #Function to add azaan time to cron
def tanggap(updates): for update in updates["result"]: text = update["message"]["text"] chat = update["message"]["chat"]["id"] if text.startswith("halo") : send_message("<i>halo juga kak</i>",chat,'HTML') elif text.startswith("kernelbot") : msg = os.uname()[1]+" "+os.uname()[2]+" "+os.uname()[4] send_message(msg,chat,None) elif text.startswith("boot") : p = terminal.Popen(['systemd-analyze'],stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) msg,err = p.communicate() send_message('`'+msg.decode()+'`',chat,'Markdown') elif text.startswith("modaro"): send_message("shutting down now...",chat,None) text_split = text.split(' ',1) passwd = text_split[1] if 'raspberry' in passwd: send_message("matiin raspberry pi 3b sekarang", chat,None) command = 'poweroff' p = terminal.Popen(['sudo', '-S', command], stdin=terminal.PIPE, stderr=terminal.PIPE, universal_newlines=True) sudo_prompt = p.communicate(passwd + '\n')[1] #msg = p.returncode #send_message(msg, chat) else: send_message("sorry bro kamu ngga punya akses", chat,None) elif text.startswith("suhu"): # command ini disesuaikan dengan letak path file ceklamalogindantemp.sh bash script berada command= '/home/pi/ceklamalogindantemp.sh'.split() p = terminal.Popen(command,stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) msg,error = p.communicate() send_message('`'+msg.decode()+'`',chat,'Markdown') elif text.startswith("humidity"): msg = "suhu dan humidity ruangan server bot: \n" msg += read_filesuhu('/home/pi/suhuruangan.txt') send_message(msg, chat,None) elif text.startswith("benchmark"): command = 'sysbench --num-threads=4 --test=cpu --cpu-max-prime=20000 --validate run'.split() p = terminal.Popen(command,stdout=terminal.PIPE, stderr=terminal.PIPE, stdin=terminal.PIPE) msg,error = p.communicate(); print(msg.decode()) send_message("`"+msg.decode()+"`",chat,'Markdown') elif text.startswith('chmod'): textsplit = text.split(' ', 2) command = 'chmod {} /home/pi/{}'.format(textsplit[1], textsplit[2]).split() p = terminal.Popen(command, stdout=terminal.PIPE, stderr=terminal.PIPE, stdin=terminal.PIPE) msg,err = p.communicate() if err.decode() is not "": send_message('galat maaf bray belajar chmod dulu sono', chat,None) else: if msg.decode() is not "": send_message(msg, chat,None) else: send_message('sukses chmod', chat,None) elif text.startswith("sholat"): textsplit = text.split(' ',1) kota = textsplit[1]; urlkota = "https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty" latdanlng = get_news(urlkota) if latdanlng is None: send_message("latlon belum ketemu",chat,None) return j = PrayTimes() times = j.getTimes(date.today(), latdanlng , 7) string_reply = "Jadwal Sholat untuk kota {} dalam wib sekarang jam {} wib \n".format(kota, datetime.now().time()) for u in ['Imsak','Fajr','Sunrise','Dhuhr','Asr','Maghrib','Isha']: string_reply += (u + ': '+times[u.lower()])+'\n' send_message('<b>'+string_reply+'</b>', chat,'HTML') elif text.startswith("cocok"): textsplit = text.split(' ',2) unitext = textsplit[1]+textsplit[2] lentext = len(unitext) alentext = lentext + 20 kalitext = lentext + alentext string_replay = "kecocokan {} dan {} sekitar {}%".format(textsplit[1], textsplit[2], kalitext) send_message(string_replay, chat,None) elif text.startswith("write_code"): textsplit = text.split(' ', 3) if os.path.isfile("/home/pi/"+textsplit[1]+"."+textsplit[2]): send_message("file telah dibuat", chat, None) else: send_message('creating source code {}.{}'.format(textsplit[1], textsplit[2]), chat,None) create_source(textsplit[1], textsplit[2], textsplit[3]) send_document(chat,"file yang terbentuk", open('{}.{}'.format(textsplit[1],textsplit[2]),'rb')) elif text.startswith("compile_code"): textsplit = text.split(' ', 2) if os.path.isfile('/home/pi/{}'.format(textsplit[1])): if textsplit[1].endswith('go'): command = 'go build /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('ts'): command ='tsc /home/pi/{}'.format(textsplit[1]).split() else: command = 'gcc -std=gnu99 -o {} /home/pi/{}'.format(textsplit[2], textsplit[1]).split() p = terminal.Popen(command,stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) msg,error = p.communicate() #print "{} and {}".format(msg, error) if error.decode() is not "": print("{}".format(error)) if "error" in error.decode(): send_message("galat waktu ngompile %s"%(error.decode()), chat,None) else: send_message("sukses %s"%(error.decode()), chat, None) else: send_message('sukses compile', chat,None) else: send_message('source code tidak ditemukan', chat,None) elif text.startswith("read_code"): textsplit = text.split(' ') if os.path.isfile('/home/pi/{}'.format(textsplit[1])): msg= "your source code is:\n`" msg += read_source(textsplit[1]) msg += "`" print(msg) send_message(msg.encode(), chat, "json|Markdown"); else: send_message('source code dengan nama file {} belum dibuat'.format(textsplit[1]), chat,None) elif text.startswith("run_code"): textsplit = text.split(' ', 1) if os.path.isfile('/home/pi/{}'.format(textsplit[1])): if textsplit[1].endswith('py'): command = 'python /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('go'): command = 'go run /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('sh'): command = 'sh /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('js'): command = 'node /home/pi/{}'.format(textsplit[1]).split() else: command = '/home/pi/{}'.format(textsplit[1]).split() p = terminal.Popen(command,stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) msg,error = p.communicate() psn="" if error.decode() is not "": psn = "galat `" psn += error.decode() psn += "`" else: psn = "`" psn += msg.decode() psn += "`" send_message(psn, chat ,'Markdown') else: send_message("program {} tidak ditemukan".format(textsplit[1]), chat,None) elif text.startswith("play"): send_message('<b><i> putar lagu free software song </i></b>',chat, 'HTML') command = 'mpv --no-video /media/pi/data/Lagu-Lagu/freeSWSong.ogg'.split() p=terminal.Popen(command,stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) p.communicate() elif text.startswith("run_gpio"): textsplit = text.split(' ', 1) if os.path.isfile('/home/pi/{}'.format(textsplit[1])): if textsplit[1].endswith('py'): command = 'sudo python /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('go'): command = 'sudo go run /home/pi/{}'.format(textsplit[1]).split() elif textsplit[1].endswith('sh'): command = 'sudo sh /home/pi/{}'.format(textsplit[1]).split() else: command = 'sudo /home/pi/{}'.format(textsplit[1]).split() p = terminal.Popen(command,stdout=terminal.PIPE,stderr=terminal.PIPE,stdin=terminal.PIPE) msg,error = p.communicate() psn="" if error.decode('utf-8') is not "": psn = "galat `" psn += error.decode('utf-8') psn += "`" else: psn = "`" psn += msg.decode('utf-8') psn += "`" send_message(psn, chat,'Markdown') else: send_message('program {} tidak ditemukan'.format(textsplit[1]), chat,None) elif text.startswith("wakeup"): textsplit= text.split(' ') bunyi = Bunyi(textsplit[1]) send_message('<b>set alarm jam {}</b>'.format(bunyi.read_file()),chat,'HTML') elif text.startswith("/start"): msg=""" silahkan pilih command yang tersedia untuk umum: 1. halo untuk menyapa bot 2. sholat <spasi> <nama kota> untuk informasi waktu sholat 3. aku untuk informasi bot berjalan di system apa hehe""" send_message("`"+msg+"`",chat,"Markdown") elif text.startswith("log"): command = "cat /var/log/lastlog".split() p = terminal.Popen(command, stdout=terminal.PIPE, stderr=terminal.PIPE, stdin=terminal.PIPE) msg,err = p.communicate() if err.decode('utf-8') is not "": mer= "galat `" mer += err.decode('utf-8') mer += "`" print (chat) send_message(mer, chat, "Markdown") else: psn ="`" psn += msg.decode('utf-8') psn += "`" print(chat) print(psn) send_message(psn, chat, "json|Markdown") #send_message(psn, chat, "Markdown") elif text.lower().startswith("kirimdoc"): textsplit = text.split(' ') file = textsplit[1] if os.path.isfile('{}'.format(file)): caption= "mengirim berkas {}".format(file) send_document(chat, caption, open(file, 'rb')) else: send_message("maaf berkas tidak tersedia", chat, None) elif text.lower().startswith("kirimaudio"): textsplit= text.split(" ") file = textsplit[1] if os.path.isfile('/media/pi/data/Lagu-Lagu/{}'.format(file)): caption= "mengirim audio {}".format(file) send_audio(chat, caption, open('/media/pi/data/Lagu-Lagu/{}'.format(file), 'rb')) else: send_message("maaf berkas audio {} tidak ditemukan.".format(file), chat, None) elif text.lower().startswith("kirimphoto"): textsplit = text.split(' ') file = textsplit[1] if os.path.isfile("/media/pi/data/{}".format(file)): caption = "mengirim berkas gambar {}".format(file) send_photo(chat, caption, open('/media/pi/data/{}'.format(file), 'rb')) else: send_message("maaf berkas gambar {} tidak ditemukan".format(file), chat, None)
#!/usr/bin/env python import datetime import time import sys sys.path.insert(0, '/home/pi/adhan/crontab') from praytimes import PrayTimes PT = PrayTimes() from crontab import CronTab system_cron = CronTab(user='******') now = datetime.datetime.now() strPlayFajrAzaanMP3Command = 'omxplayer -o local /home/pi/adhan/Adhan-fajr.mp3 > /dev/null 2>&1' strPlayAzaanMP3Command = 'omxplayer -o local /home/pi/adhan/Adhan-Makkah.mp3 > /dev/null 2>&1' strUpdateCommand = 'python /home/pi/adhan/updateAzaanTimers.py >> /home/pi/adhan/adhan.log 2>&1' strClearLogsCommand = 'truncate -s 0 /home/pi/adhan/adhan.log 2>&1' strJobComment = 'rpiAdhanClockJob' #Set latitude and longitude here #-------------------- lat = 42.288788 long = -71.551678 #Set calculation method, utcOffset and dst here #By default system timezone will be used #-------------------- PT.setMethod('ISNA') utcOffset = -(time.timezone / 3600) isDst = time.localtime().tm_isdst
import json import requests import time import urllib from datetime import datetime, timedelta from dbhelper import DBHelper from praytimes import PrayTimes from googleplacesparser import GooglePlaceParser from surahtmlparser import HTMLParser db = DBHelper() gpp = GooglePlaceParser() pt = PrayTimes() stage = 0 reported = False TOKEN = "584920327:AAGKd2EDjQyIwyEwLalcMBnlMYZj6xF3K_s" URL = "https://api.telegram.org/bot{}/".format(TOKEN) praytimekeywords = [ 'ezan', 'ne', 'zaman', 'kaç dakika kaldı', 'okunmasına', 'ezana', 'ezanın', 'kaçta', 'pray', 'when', 'time', 'how many minutes', 'salah time', 'next', '/pray' ] allpraytimekeywords = [ 'ezanları', 'ezan', 'ezanlar', 'hepsi', 'vakitlerinin', 'tüm', 'tümü', 'bugünki', 'vakitlerini', 'vakitleri', 'saatleri', 'pray', 'times', 'all', 'pray times' 'salah', 'salah times', 'hours', 'salah time', 'when' ]
def generate(lat, lon, startdate, days, method, option): PT = PrayTimes(method) if option == '+8': PT.adjust({ 'imsak': '10 min', 'fajr': 17.8, 'dhuhr': '2 min', 'asr': '1.03', 'maghrib': 1.5, 'isha': 18.7 }) else: PT.adjust({ 'imsak': '10 min', 'fajr': 19.4, 'dhuhr': '2 min', 'asr': '1.03', 'maghrib': 1.8, 'isha': 18.7 }) #result = [] c = Calendar() formatDate = '%Y-%m-%d' formatDatetime = '%Y-%m-%d %H:%M:%S' hourDelta = 7 secondDelta = 5 mapTime = { 'Imsak': 'imsak', 'Subuh': 'fajr', 'Dzuhur': 'dhuhr', 'Asar': 'asr', 'Maghrib': 'maghrib', 'Isya': 'isha', } dte = datetime.strptime(startdate, formatDate) for i in range(days): today = dte + timedelta(days=i) times = PT.getTimes(today.date(), [float(lat), float(lon)], +7) ''' result.append({ 'imsak': times['imsak'], 'subuh': times['fajr'], 'dzuhur': times['dhuhr'], 'asar': times['asr'], 'maghrib': times['maghrib'], 'isya': times['isha'] }) ''' todayTimeStr = today.strftime(formatDate) for name, key in mapTime.items(): e = setEvent(times, name, key, todayTimeStr, hourDelta, secondDelta, formatDatetime) c.events.add(e) with open('jadwal_imsakiyah_%s_%s.ics' % (lat, lon), 'w') as f: f.write(str(c))
from praytimes import PrayTimes from datetime import date, datetime, time, timedelta import time as t import notify2 ICON_PATH = "/home/acep/Oprek/python/mitprayertime/mit.png" notify2.init("MITPrayer") app = notify2.Notification(None, icon=ICON_PATH) app.set_urgency(notify2.URGENCY_NORMAL) app.set_timeout(10000) prayTimes = PrayTimes() def update(): tgl = datetime.now() waktu = tgl.replace(second=0, microsecond=0) waktu = waktu.time() times = prayTimes.getTimes(date.today(), (-7.7500127, 110.3606701), +7) imsakiyah = ['Imsak', 'Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'] for i in imsakiyah: #['Imsak','Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha']: if (datetime.strptime(times[i.lower()], '%H:%M').time() == waktu): app.update('Sudah masuk waktu ' + i, 'Ayo Berangkat') app.show() print('sudah ' + i + ':' + times[i.lower()]) if (waktu < datetime.strptime(times[i.lower()], '%H:%M').time()): mynext = datetime.strptime(times[i.lower()], '%H:%M').time() mynext = datetime.combine(date.today(), mynext) mywaktu = datetime.combine(date.today(), waktu) durasi = mynext - mywaktu if (durasi.total_seconds() == 600): app.update('Ngasi Tau aja', 'bentar lagi ' + i)
def generate(lat, lon, startdate, days): PT = PrayTimes('Makkah') PT.adjust({'wkt':'10 min', 'fajr':17.8, 'dhuhr':'2 min', 'asr':'1.03', 'maghrib':1.5,'isha':18.7}) #result = [] c = Calendar() dte = datetime.strptime(startdate, '%Y-%m-%d') for i in range(days): today = dte + timedelta(days=i) times = PT.getTimes(today.date(), [float(lat),float(lon)],+7) ''' result.append({ 'imsak': times['imsak'], 'subuh': times['fajr'], 'dzuhur': times['dhuhr'], 'asar': times['asr'], 'maghrib': times['maghrib'], 'isya': times['isha'] }) ''' e = Event() e.name = 'Imsak' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['imsak']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) e = Event() e.name = 'Subuh' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['fajr']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) e = Event() e.name = 'Dzuhur' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['dhuhr']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) e = Event() e.name = 'Asar' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['asr']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) e = Event() e.name = 'Maghrib' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['maghrib']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) e = Event() e.name = 'Isya' wkt = datetime.strptime(today.strftime('%Y-%m-%d')+' '+times['isha']+':00', '%Y-%m-%d %H:%M:%S') wkt = wkt - timedelta(hours=7) e.begin = wkt.strftime('%Y-%m-%d %H:%M:%S') e.end = (wkt+timedelta(seconds=5)).strftime('%Y-%m-%d %H:%M:%S') c.events.add(e) with open('jadwal_imsakiyah_%s_%s.ics' % (lat, lon), 'w') as f: f.write(str(c))