def main(): global bot global WEATHER_API_KEY # Read config file parser = SafeConfigParser() # Open the file with the correct encoding with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f: parser.readfp(f) try: WEATHER_API_KEY = parser.get('Weather', 'api_key') except: print(u'Cannot get weather endpoint API Key.') sys.exit(1) try: # Create access to bot bot = telepot.Bot(parser.get('Telegram', 'token')) bot.message_loop(handle) except: print(u'Cannot access Telegram. Please do /start') sys.exit(1) print("Telegram bot started...") # Keep the program running. while 1: time.sleep(10)
def cli(host, port, db, user, password, file, config, dataformat, start, end): """Tool to gather data about GitHub repositories. Requires the GHTorrent MySQL database (http://ghtorrent.org/). To get an up to date copy: https://github.com/OSSHealth/ghtorrent-sync To get help on subcommands, type the command with --help. """ # Read config file if passed if (config): parser = configparser.ConfigParser() parser.readfp(config) host = parser.get('Database', 'host') port = parser.get('Database', 'port') user = parser.get('Database', 'user') password = parser.get('Database', 'pass') db = parser.get('Database', 'name') dataformat = parser.get('Format', 'format') global client client = GHDataClient(db_host=host, db_port=port, db_user=user, db_pass=password, db_name=db, file=file, dataformat=dataformat, start=start, end=end)
def main(): global bot global uid # Read config file parser = SafeConfigParser() # Open the file with the correct encoding with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f: parser.readfp(f) try: # Create access to bot bot = telepot.Bot(parser.get('Telegram', 'token')) bot.message_loop(handle) uid = parser.get('Telegram', 'uid') bot.sendMessage( uid, text=u"Start %s\n%s\n%s" % (os.path.basename( sys.argv[0]), version.__version__, datetime.datetime.now())) except: print u'Cannot access Telegram. Please do /start' sys.exit(1) global DATABASE DATABASE = parser.get('Database', 'File') # Keep the program running. while 1: time.sleep(10)
def main(): global bot global uid # Read config file parser = SafeConfigParser() # Open the file with the correct encoding with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f: parser.readfp(f) try: # Create access to bot bot = telepot.Bot(parser.get('Telegram', 'token')) bot.message_loop(handle) uid = parser.get('Telegram', 'uid') bot.sendMessage(uid, text=u"Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now())) except: print u'Cannot access Telegram. Please do /start' sys.exit(1) global DATABASE DATABASE = parser.get('Database', 'File') # Keep the program running. while 1: time.sleep(10)
def main(): # Read config file parser = SafeConfigParser() # Open the file with the correct encoding with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f: parser.readfp(f) global DATABASE DATABASE = parser.get('Database', 'File') if VERBOSE: print "Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now()) conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row c = conn.cursor() #get quotes for all stocks marked to track for row in c.execute("select * from stocks where tracked='True';"): stockid = row["id"] stockname = row["name"] if VERBOSE: print "\n" if not(monitorstock.checkifmarketopen(row["exchangeid"], row["symbolgoogle"], stockname,conn)): if VERBOSE: print "Stock market CLOSED for %s(%s)" % (row["symbolgoogle"],stockname) c1 = conn.cursor() c1.execute("select MAX(timestamp), value from quotes where stockid=:id", {'id':row['id']}) newquote = c1.fetchone() quote = newquote['value'] newtimestamp = newquote['MAX(timestamp)'] print "LAST quote available in database for %s(%s) of %s @%s" % (row["symbolgoogle"],stockname,quote,newtimestamp) continue if not(row["lastquotestamp"] is None): timestamp = dateutil.parser.parse(row["lastquotestamp"]) # get last quote timestamp and parse into time object else: timestamp = None interval = row["interval"] now = datetime.datetime.utcnow().replace(tzinfo = pytz.utc) # get current date and time in UTC with timezone info if (timestamp is None) or (now> timestamp + datetime.timedelta(minutes=interval) ): #see if it is time to get a new quote newtimestamp, quote = monitorstock.savequote(int(stockid), timestamp, conn) if VERBOSE: print "Got NEW quote for %s(%s) of %s @%s" % (row["symbolgoogle"],stockname,quote,newtimestamp) else: if VERBOSE: c1 = conn.cursor() c1.execute("select MAX(timestamp), value from quotes where stockid=:id", {'id':row['id']}) newquote = c1.fetchone() quote = newquote['value'] newtimestamp = newquote['MAX(timestamp)'] print "RECENT quote available in database for %s(%s) of %s @%s" % (row["symbolgoogle"],stockname,quote,newtimestamp)
def getConfig(): """ Reads the config from the configuration file. :return: configuration parser. """ import ConfigParser parser = ConfigParser.RawConfigParser() try: parser.readfp(open("config.ini")) except IOError: print "Are you sure you have config.ini? You should create it if you don't. You can use config_example.ini " \ "as example" exit(0) return parser
def read_main_conf(config_file): options = {} parser = SafeConfigParser() fd = open(config_file, 'r') parser.readfp(fd) fd.close() sec = parser.sections() # we'll read "generic" for db information and "r" for start_date and "bicho" for backend for s in sec: if not(s in ["generic","r","bicho","bicho_1"]): continue options[s] = {} opti = parser.options(s) for o in opti: options[s][o] = parser.get(s, o) return options
def read_main_conf(config_file): options = {} parser = SafeConfigParser() fd = open(config_file, 'r') parser.readfp(fd) fd.close() sec = parser.sections() # we'll read "generic" for db information and "r" for start_date and "bicho" for backend for s in sec: if not (s in ["generic", "r", "bicho", "bicho_1"]): continue options[s] = {} opti = parser.options(s) for o in opti: options[s][o] = parser.get(s, o) return options
def main(): global newdayalert initializetz() # Read config file parser = SafeConfigParser() # Open the file with the correct encoding with codecs.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), SETTINGSFILE), 'r', encoding='utf-8') as f: parser.readfp(f) DATABASE = parser.get('Database', 'File') try: # Create access to bot bot = telepot.Bot(parser.get('Telegram', 'token')) uid = parser.get('Telegram', 'uid') # bot.sendMessage(uid, text=u"Start %s\n%s\n%s" % (os.path.basename(sys.argv[0]), version.__version__, datetime.datetime.now())) except: print u'Cannot access Telegram. Please do /start' sys.exit(1) conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row #sellstock('NASDAQ:QLIK', 10, 30,None,conn) c = conn.cursor() #Check if it is time to buy or sell in active strategies for stock in c.execute(""" select strategies.*, stocks.name, stocks.symbolgoogle, stocks.symbolyahoo, stocks.exchangeid, stocks.lastquotestamp from strategies, stocks where strategies.stockid=stocks.id and strategies.active='True'; """): #Check if market open if not(checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'], stock['name'],conn)): continue symbol = str(stock["symbolgoogle"]) minreturn = float(stock['minreturn']) lowcount = int(stock['lowcount']) c1 = conn.cursor() c1.execute(""" select portfolio.*, stocks.lastquotestamp from portfolio, stocks where portfolio.stockid=:id and portfolio.stockid=stocks.id """, {'id':stock['stockid']}) stockinportfolio = c1.fetchone() try: qty = float(stockinportfolio['qty']) buyprice = float(stockinportfolio['cost']) except: qty = 0 buyprice = 0 try: lasttradedatetime = dateutil.parser.parse(stock['lastquotestamp']) except: lasttradedatetime = None #Get current quote quote = getQuotes(symbol)[0] correcteddate = quote["LastTradeDateTimeLong"] #parse uses posix stype for timezone offsets. ISO requires inversion in sign!! if correcteddate.find('+'): correcteddate=correcteddate.replace('+', '-') elif correcteddate.find('-'): correcteddate=correcteddate.replace('-', '+') datetradenow = dateutil.parser.parse(correcteddate, tzinfos=tzd) #get current last trade time on market nowquotevalue = float(quote['LastTradePrice']) #get last quote newdayalert = False if (lasttradedatetime is None) or datetradenow.date()!=lasttradedatetime.date(): #New Day! bot.sendMessage(uid, text=u"New Day for stock %s" % stock['name']) if VERBOSE: print "New Day for stock %s" % stock['name'] newdayalert = True if newdayalert: #Number of days descending reached, and opend low if checkiftimetobuy(stock['symbolyahoo'], lowcount, datetradenow, nowquotevalue): bot.sendMessage(uid, text=u"Time to BUY %s (%s) Price = %8.3f" % (stock['name'], symbol, nowquotevalue)) if VERBOSE: print "Time to BUY %s (%s) Price = %8.3f" % (stock['name'], symbol, nowquotevalue) checkifdividendday(datetradenow.date() ,conn) checkifsplitday(datetradenow.date() ,conn) c2 = conn.cursor() c2.execute("UPDATE stocks SET lastquotestamp = ?, lastquote = ? WHERE id = ?;", (datetradenow.isoformat(), nowquotevalue, stock['stockid'])) #update last quote timestamp conn.commit() if qty>0 and nowquotevalue>=(1+minreturn)*buyprice and newdayalert: newdayalert = False bot.sendMessage(uid, text=u"Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" % (stock['name'], symbol, qty, nowquotevalue)) if VERBOSE: print "Time to SELL %s (%s) Qty = %8.2f Price = %8.3f" % (stock['name'], symbol, qty, nowquotevalue) #Update quotes in tracked stocks for stock in c.execute("select * from stocks where tracked='True'"): if not(checkifmarketopen(stock["exchangeid"], stock['symbolgoogle'], stock['name'],conn)): continue nowutc = datetime.datetime.utcnow().replace(tzinfo = pytz.utc) lastdateplus = dateutil.parser.parse(stock['lastquotestamp']) + datetime.timedelta( minutes=int(stock['interval'] )) if (stock['lastquotestamp'] is None) or (lastdateplus< nowutc): timestamp, nowquotevalue = savequote(int(stock['id']), stock['lastquotestamp'], conn) conn.commit()
#!/usr/bin/python # finds currently recorded shows that have two or more copies import os import sys, getopt import operator from dateutil import parser from MythTV import MythBE, Program, MythDB from ConfigParser import ConfigParser from StringIO import StringIO parser = ConfigParser() with open("data") as stream: stream = StringIO("[top]\n" + stream.read()) parser.readfp(stream) # returns a map from a unique key (programid) to a list of matching shows def findDupes(orig): seen = {} result = [] for item in orig: second = item.subtitle if second is None: second = item.programid # key = "%s - %s - %s" % (item.title, item.subtitle, item.programid) key = item.programid items = seen.get(key,[]) items.append(item) seen[key] = items return dict((title,items) for title,items in seen.iteritems() if len(items) > 1)