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")
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")
class prayerindicator: def __init__(self, timeout): self.load_configuration_on_start() self.ind = AppIndicator.Indicator.new("salatuk-indicator", get_resource_path('img/icon.svg'), AppIndicator.IndicatorCategory.APPLICATION_STATUS) self.ind.set_status (AppIndicator.IndicatorStatus.ACTIVE) self.ind.set_attention_icon("new-messages-red") #change it to uclean icon with red color self.win = SalatukWindow(self) #preferences window # self.audio = Audio() # self.audio.play_athan() self.menu_setup() self.ind.set_menu(self.menu) check_prayer(self, self.check_time) # register a periodic timer GLib.timeout_add_seconds(timeout, self.callback) def load_configuration_on_start(self): # create configparser object config = ConfigParser.RawConfigParser() cfile = get_resource_path('preferences/preferences.conf') # add your config items - see the ConfigParser docs for how to do this if os.path.exists(cfile): config.read (cfile) # add the settings to the structure of the file, and lets write it out... self.Method = config.get('preferences','method') self.timezone = config.get('preferences','timezone') self.latitude = config.get('preferences','latitude') self.longitude = config.get('preferences','longitude') self.dstValue = config.get('preferences','dstValue') self.athanToggle = config.get('preferences','athanToggle') self.set_prayer_time() def set_prayer_time(self): self.today = datetime.datetime.now() self.PT = PrayTimes() self.PT.setMethod(self.Method) self.check_time = self.PT.getTimes(date.today(), (float(self.latitude) , float(self.longitude)),float(self.timezone), int(self.dstValue)) self.times = self.PT.getTimes(date.today(), (float(self.latitude) , float(self.longitude)),float(self.timezone), int(self.dstValue), '12h') def menu_setup(self): self.menu = Gtk.Menu() cal = calverter() jd = cal.gregorian_to_jd(self.today.year, self.today.month, self.today.day) self.date = add2menu(self.menu,text =(self.today.strftime("%A, ") + str(cal.string_jd_to_islamic(jd)))) self.date.show() add2menu(self.menu) self.Fajr = Gtk.MenuItem("Fajr\t\t\t" + self.times['fajr']) self.Fajr.set_sensitive(False) #use this to enable only one prayer self.Fajr.show() self.menu.append(self.Fajr) self.Sunrise = Gtk.MenuItem("Sunrise\t\t" + self.times['sunrise']) self.Sunrise.set_sensitive(False) self.Sunrise.show() self.menu.append(self.Sunrise) self.Dhuhr = Gtk.MenuItem("Dhuhr\t\t\t" + self.times['dhuhr']) self.Dhuhr.set_sensitive(False) self.Dhuhr.show() self.menu.append(self.Dhuhr) self.Asr = Gtk.MenuItem("Asr\t\t\t" + self.times['asr']) self.Asr.set_sensitive(False) self.Asr.show() self.menu.append(self.Asr) self.Maghrib = Gtk.MenuItem("Maghrib\t\t" + self.times['maghrib']) self.Maghrib.set_sensitive(False) self.Maghrib.show() self.menu.append(self.Maghrib) self.Isha = Gtk.MenuItem("Isha\t\t\t" + self.times['isha']) self.Isha.set_sensitive(False) self.Isha.show() self.menu.append(self.Isha) add2menu(self.menu) self.preferences = add2menu(self.menu,text=('Preferences')) self.preferences.connect("activate", self.show_preferences) # write a uclean def self.preferences.show() self.help_menu = add2menu(self.menu,text =('Help')) self.help_menu.set_submenu(self.get_help_menu()) self.help_menu.show() self.quit_item = Gtk.MenuItem("Quit Salatuk") self.quit_item.connect("activate", self.quit) self.quit_item.show() self.menu.append(self.quit_item) def show_preferences(self, widget): self.win.load_at_startup() self.win.show_all() def main(self): Gtk.main() def quit(self, widget): exit(0) def update_prayers(self): self.load_configuration_on_start() self.Fajr.set_label("Fajr\t\t\t" + self.times['fajr']) self.Sunrise.set_label("Sunrise\t\t" + self.times['sunrise']) self.Dhuhr.set_label("Dhuhr\t\t\t" + self.times['dhuhr']) self.Asr.set_label("Asr\t\t\t" + self.times['asr']) self.Maghrib.set_label("Maghrib\t\t" + self.times['maghrib']) self.Isha.set_label("Isha\t\t\t" + self.times['isha']) def update_hijri_date(self): cal = calverter() jd = cal.gregorian_to_jd(self.today.year, self.today.month, self.today.day) self.date.set_label(self.today.strftime("%A, ") + str(cal.string_jd_to_islamic(jd))) def get_help_menu(self): # This function was written by Lorenzo Carbonell for My_Weather_Indicator. I modified this copy to work with uClean under the terms of the GNU General Public License as published by the Free Software Foundation. help_menu = Gtk.Menu() # add2menu(help_menu,text = ('In Github'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('https://github.com/fo2adzz/Salatuk')) add2menu(help_menu,text = ('Report a bug...'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('https://github.com/fo2adzz/Salatuk/issues')) add2menu(help_menu) web = add2menu(help_menu,text = ('Homepage'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('http://www.fo2adzz.com')) twitter = add2menu(help_menu,text = ('Follow us in Twitter'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('https://twitter.com/fo2adzz')) googleplus = add2menu(help_menu,text = ('Follow us in Google+'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('https://plus.google.com/u/0/112984301584620244860/posts')) facebook = add2menu(help_menu,text = ('Follow us in Facebook'),conector_event = 'activate',conector_action = lambda x: webbrowser.open('https://www.facebook.com/fouad.hassouneh')) # add2menu(help_menu,text = _('About'),conector_event = 'activate',conector_action = self.menu_about_response) web.set_image(Gtk.Image.new_from_file(get_resource_path('img/social/fo2adzz.png'))) web.set_always_show_image(True) twitter.set_image(Gtk.Image.new_from_file(get_resource_path('img/social/twitter.png'))) twitter.set_always_show_image(True) googleplus.set_image(Gtk.Image.new_from_file(get_resource_path('img/social/googleplus.png'))) googleplus.set_always_show_image(True) facebook.set_image(Gtk.Image.new_from_file(get_resource_path('img/social/facebook.png'))) facebook.set_always_show_image(True) # help_menu.show() return help_menu # # update all the labels every timeout seconds def callback(self): self.update_hijri_date() self.update_prayers() check_prayer(self, self.check_time) return True
#!/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
#!/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
#!/usr/bin/env python import datetime from praytimes import PrayTimes #Get Prayer Times #-------------------- lat = 48.1844202348964 long = 11.57306412752331 now = datetime.datetime.now() 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
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' ]
#!/usr/bin/env python from praytimes import PrayTimes from gi.repository import Notify from datetime import date import time praytime = PrayTimes() # tune and adjustment based on shalat.landak.com praytime.adjust({ 'fajr': 20, 'dhuhr': '2 min', 'maghrib': 1, 'isha': 18 }) praytime.tune({ 'fajr': 2, 'sunrise': -2, 'asr': 2, 'maghrib': 2, 'isha': 2 }) translasi = { 'imsak': 'Imsak', 'fajr': 'Subuh', 'dhuhr': 'Duhur', 'asr': 'Ashar', 'maghrib': 'Maghrib',
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))
from django.core import serializers from praytimes import PrayTimes from datetime import date, timedelta from math import floor from lxml import objectify from lxml import etree import os import os.path import requests import simplejson DEFAULT_METHOD = 'Karachi' DEFAULT_ASR = 'Hanafi' p = PrayTimes(DEFAULT_METHOD) p.setMethod(DEFAULT_METHOD) p.adjust({'asr':DEFAULT_ASR}) def timezone(lat, lng): r = requests.get("http://api.geonames.org/timezoneJSON?lat=%s&lng=%s&username=usmanghani" % (lat, lng)) json = simplejson.loads(r.text) rawOffset = json['rawOffset'] dstOffset = json['dstOffset'] dst = rawOffset != dstOffset # r = requests.get("http://www.earthtools.org/timezone/%s/%s" % (lat, lng)) # root = objectify.fromstring(r.text.encode('ascii')) # dst = False
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)
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 p = PrayTimes("Karachi") p.setMethod("Karachi") p.adjust({"asr": "Hanafi"}) import datetime times = p.getTimes(datetime.date.today(), (47.6097, -122.3331), -8, True) from pprint import pprint pprint(times) from lxml import objectify from lxml import etree from requests import get r = get("http://www.earthtools.org/timezone/47.6097/-122.3331") root = objectify.fromstring(r.text.encode("ascii")) # root = objectify.fromstring( # '''<?xml version="1.0" encoding="ISO-8859-1" ?> # <timezone xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.earthtools.org/timezone-1.1.xsd"> # <version>1.1</version> # <location> # <latitude>47.6097</latitude> # <longitude>-122.3331</longitude> # </location>
from praytimes import PrayTimes p = PrayTimes('Karachi') p.setMethod('Karachi') p.adjust({'asr':'Hanafi'}) import datetime times = p.getTimes(datetime.date.today(), (47.6097, -122.3331), -8, True) from pprint import pprint pprint(times)
def post(self): urlfetch.set_default_fetch_deadline(60) body = json.loads(self.request.body) logging.info('request body:') logging.info(body) self.response.write(json.dumps(body)) update_id = body['update_id'] message = body['message'] message_id = message.get('message_id') date = message.get('date') text = message.get('text') fr = message.get('from') chat = message['chat'] chat_id = chat['id'] if not text: logging.info('no text') return def reply(msg=None, img=None): if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg.encode('utf-8'), 'disable_web_page_preview': 'true', 'reply_to_message_id': str(message_id), })).read() elif img: resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [ ('chat_id', str(chat_id)), ('reply_to_message_id', str(message_id)), ], [ ('photo', 'image.jpg', img), ]) else: logging.error('no msg or img specified') resp = None logging.info('send response:') logging.info(resp) if text.startswith('/'): if text == '/start': reply('Bot enabled') setEnabled(chat_id, True) elif text == '/stop': reply('Bot disabled') setEnabled(chat_id, False) elif text == '/image': img = Image.new('RGB', (512, 512)) base = random.randint(0, 16777216) pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image img.putdata(pixels) output = StringIO.StringIO() img.save(output, 'JPEG') reply(img=output.getvalue()) else: reply('What command?') # CUSTOMIZE FROM HERE elif 'Rizky' in text: reply('handsome') elif 'firja' in text: reply('ganteng gann... suerr') elif 'rizky' in text: reply('apa manggil-manggil si rizky. dia itu punya aku') elif 'who are you' in text: reply('octaphire created by kucengaerdev laboratory gan, https://github.com/kucengaerdev/Octhphire') elif 'what time' in text: reply('look at the top-right corner of your screen!') elif 'siapa lo' in text: reply('aku adalah seorang muslim jika aku sendirian dan komunis jika aku dalam kerumunan karena Allah berfirman setan ada dalam kerumunan (Tan Malaka)') elif 'qget' in text: reply("wait") awal= text.replace("qget", "www.quran.com") akhir= awal.replace(" ", "/") def openurl(url): try: page = urllib2.urlopen(url).read() except: print "/!\ Error getting URL content!" sys.exit(1) return page url = "http://" + akhir soup = BeautifulSoup(openurl(url)) khabarc = soup.find('div', attrs={"class":"ayah language_6 text"}) x = khabarc.get_text() if 'Sahih International' in x: y = x.replace("Sahih International", "") else: y = "sorry. a little bit error here" reply(y) #quran elif 'sholat' in text: awal = text.replace("sholat","maps.googleapis.com/maps/api/geocode/json?address") ahir = text.replace(" ","=") url= "https://"+ahir json_string = urllib2.urlopen(url) data = json.load(json_string) lat = data['results'][0]['geometry']['location']['lat'] lng = data['results'][0]['geometry']['location']['lng'] city = url.replace("https://maps.googleapis.com/maps/api/geocode/json?address=","waktu sholat untuk kota ") string_reply = city+" dalam waktu indonesia bagian barat(WIB). " j = PrayTimes() times = j.getTimes(date.today(),(lat,lng),7) for u in ['Imsak','Fajr','Sunrise','Dhuhr','Asr','Maghrib','Isha']: string_reply += (u + ': '+times[u.lower()]) reply(string_reply) else: if getEnabled(chat_id): resp1 = json.load(urllib2.urlopen('http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' + urllib.quote_plus(text.encode('utf-8')))) back = resp1.get('res') if not back: reply('okay...') elif 'I HAVE NO RESPONSE' in back: reply('you said something with no meaning') else: reply(back) else: logging.info('not enabled for chat_id {}'.format(chat_id))
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)
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 set_prayer_time(self): self.today = datetime.datetime.now() self.PT = PrayTimes() self.PT.setMethod(self.Method) self.check_time = self.PT.getTimes(date.today(), (float(self.latitude) , float(self.longitude)),float(self.timezone), int(self.dstValue)) self.times = self.PT.getTimes(date.today(), (float(self.latitude) , float(self.longitude)),float(self.timezone), int(self.dstValue), '12h')
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
otherAzansDir = dirPath + '/azans/others' otherAzans = os.listdir(otherAzansDir) fjrRand = randint(0, len(fajrAzans)-1) fajr = fajrAzansDir + '/' + fajrAzans[fjrRand] # otherRand = randint(0, len(otherAzans)-1) dhuhr = otherAzansDir + '/' + otherAzans[randint(0, len(otherAzans)-1)] asr = otherAzansDir + '/' + otherAzans[randint(0, len(otherAzans)-1)] maghrib = otherAzansDir + '/' + otherAzans[randint(0, len(otherAzans)-1)] isha = otherAzansDir + '/' + otherAzans[randint(0, len(otherAzans)-1)] pt = PrayTimes() dsT = time.localtime().tm_isdst dic = {'imsak':0, 'fajr':5, 'sunrise':0, 'dhuhr':0, 'asr':0, 'maghrib':-16, 'isha':4, 'midnight':0} dt = date.today() cords = (40.277310, -74.561890) pt.tune(dic) print(-(time.timezone/3600)) times = pt.getTimes(dt, cords, -(time.timezone/3600), dst=dsT) system_cron = CronTab(user='******')