def init(): data.query('''CREATE TABLE IF NOT EXISTS lastfm_alias (alias TEXT, username TEXT, PRIMARY KEY (alias))''') set_api_key(open("data/lastFMAPIKey.txt").readline()) dynamic_core.register_tag('lastfm',tag_fetchfm) command.ComHook('addfm',command_addfm,name='fmBot')
def command_unschedule(i,command,args): try: data.query("DELETE FROM schedule WHERE interface = ? AND name = ?", (i.interface_name,args)) except Exception as e: i.reply(e) else: i.reply("Event deleted.")
def init(): data.query('''CREATE TABLE IF NOT EXISTS schedule (interface TEXT, name TEXT, datetime_added TEXT, user TEXT, text TEXT, datetime DATETIME, recurrence TEXT, PRIMARY KEY (interface, name))''') command.ComHook('schedule',command_schedule,name='AlarmBot') command.ComHook('unschedule',command_unschedule,name='AlarmBot') load_events()
def command_unreplace(i,command,args): find = args r = find_replacement(find) if not r: find = args.lower() r = find_replacement(find) if r: data.query('''DELETE FROM replacebot_subs WHERE find=?''',(find,)) i.reply("%s no longer replaces to %s."%(args,r[1])) else: i.reply("%s is not currently being replaced."%args)
def add_event(dt,message,recur,eventname, username, interfacename): now = datetime.now().replace(microsecond=0) dt = dt.replace(microsecond=0) while dt < now: dt = increment_datetime(dt,recur) nowstr = now.isoformat(' ') datestr = dt.isoformat(' ') data.query('INSERT INTO schedule VALUES (?,?,?,?,?,?,?)',(interfacename,eventname,nowstr,username,message,datestr,recur)) queue_event(interfacename,eventname,dt)
def init(): command.ComHook('autoreplace',command_toggle_autoreplace) command.ComHook('replace',command_replace,"ReplaceBot") command.ComHook('rxreplace',command_rxreplace,"ReplaceBot") command.ComHook('unreplace',command_unreplace,"ReplaceBot") command.ComHook('getreplacements',command_getreplacements,"ReplaceBot") modules.add_hook('message',message_hook) data.query('''CREATE TABLE IF NOT EXISTS replacebot_subs (find TEXT, replace TEXT, is_regex INTEGER, setby TEXT, PRIMARY KEY (find))''')
def load_commands(): # numcommands = data.query("SELECT COUNT(DISTINCT name) FROM dynamic")[0][0] # results = data.query("SELECT DISTINCT name, version, source FROM dynamic ORDER BY name, version DESC LIMIT %u"%numcommands) results = data.query("SELECT version,name,source,help FROM dynamic GROUP BY name") for result in results: hook = command.ComHook(result[1], command_runfunc, name="%sBot" % result[1], data=result[2]) hook.set_help(result[3])
def init(): data.query( """CREATE TABLE IF NOT EXISTS dynamic (version INTEGER, name TEXT, source TEXT, timestamp DATE, help TEXT, author TEXT, PRIMARY KEY (version, name))""" ) load_commands() command.ComHook("addfunc", command_addfunc, security=2) command.ComHook("docfunc", command_document_func, security=2) # command.ComHook('documentfunc',command_documentfunc,security=2) dynamic_core.register_tag("dyn_source", tag_source) dynamic_core.register_tag("dyn_version", tag_version) dynamic_core.register_tag("dyn_author", tag_author) dynamic_core.register_tag("dyn_updater", tag_updater)
def document_func(funcname, doc): com = find_command(funcname)[0] if com: result = data.query("UPDATE dynamic SET help=? WHERE version=? AND name=?", (doc, com["version"], funcname)) command.get_command(funcname).set_help(doc) return result else: raise InvalidFuncNameError, funcname
def do_event(interfacename,eventname,dt): d = data.query('SELECT text, recurrence, datetime FROM schedule WHERE interface = ? AND name = ?',(interfacename,eventname))[0] dt = datetime.strptime(d[2],'%Y-%m-%d %H:%M:%S') rec = d[1] if rec=='': data.query('DELETE FROM schedule WHERE interface = ? and name = ?',(interfacename,eventname)) else: dt = increment_datetime(dt,rec) data.query('UPDATE schedule SET datetime = ? WHERE interface = ? and name = ?',(dt.isoformat(' '),interfacename,eventname)) try: i = modules.Interface.interfaces[interfacename] except: print "Alarm triggered for non-existing interface %s."%interfacename return context = dynamic_core.TagContext(i=i,args=d[2]) message = dynamic_core.parse_markup(d[0]).process(context) i.reply("AlarmBot: "+message)
def add_command(name, line, author): logging.info("Attempt to add function %s" % name) version = 0 help = "" if "!" in name: raise InvalidFuncNameError, name if find_command(name): # logging.warn("Dynamic command %s already exists!"%name) version = find_command(name)[0]["version"] help = find_command(name)[0]["help"] elif name in command.com_hooks: raise CannotModifyStdFuncsError, name data.query( "INSERT INTO dynamic VALUES (?,?,?,?,?,?)", (version + 1, name, line, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), help, author), ) command.ComHook(name, command_runfunc, name="%sBot" % name, data=line) return version + 1
def init(): global categories global current_category categories = {} command.ComHook('quiz',command_pubquiz,name="Quiz") command.ComHook('listquizzes',command_listquizzes,name="Quiz") categories['all'] = {} for i in os.listdir('data/pubquiz'): if i[-4:]!=".txt": if not i.lower() in categories: categories[i.lower()] = {} for q in os.listdir('data/pubquiz/'+i): if q[-4:]==".txt": n = PubQuiz('data/pubquiz/'+i+'/'+q) categories['all'][q.lower()[:-4]] = n categories[i.lower()][q.lower()[:-4]] = n current_category='all' data.query('''CREATE TABLE IF NOT EXISTS pubquiz_stats (handle TEXT NOT NULL , correct INTEGER DEFAULT 0, attempts INTEGER DEFAULT 0, score INTEGER DEFAULT 0, questions INTEGER DEFAULT 0, record_time INTEGER DEFAULT 0, PRIMARY KEY (handle))''')
def command_pubquiz(i,command,args): """!randomtopic - Sets a random conversation topic. Can only be used once every 20 seconds.""" global current_question global categories global current_category global current_category_type if current_question: if args: pq = current_question try: a = current_question.check_answer(args,i.user_address) except UnicodeError: i.reply("Unicode Error. Abandoning question.") current_question = None return if a==1: if current_question.type=='multi': points = len(current_question.choices)-len(current_question.attempted) else: points=3 data.query("UPDATE pubquiz_stats SET attempts=attempts+1,score=score+?,correct=correct+1 WHERE handle=?",(points,i.user_address)) stats = data.query("SELECT * FROM pubquiz_stats WHERE handle=?",(i.user_address,))[0] i.reply("Correct, +%d points! %s"%(points,current_question.comment)) c = float(stats[1]) a = float(stats[2]) p = (c/a)*100 i.reply("%s now has %d points and %d%% correct attempts."%(i.user_name,stats[3],p)) current_question=None elif a==0: i.reply("Incorrect.") data.query("UPDATE pubquiz_stats SET attempts=attempts+1 WHERE handle=?",(i.user_address,)) elif a==-1: i.reply("Ambiguous answer.") elif a==-2: i.reply("Not an option.") elif a==-3: i.reply("Someone already tried that!") if current_question: if (len(current_question.attempted) == len(current_question.choices)-1) and current_question.type=="multi": i.reply("You all fail! "+current_question.comment) current_question=None if not current_question: for u in pq.attemptors.keys(): data.query("UPDATE pubquiz_stats SET questions=questions+1 WHERE handle=?",(u,)) else: i.reply(str(current_question)) else: if args: args = args.strip().lower() if args in categories: current_category = args i.reply("Category is now %s." % args) current_category_type='super' current_question = random.choice(categories[args].values()).get_question() elif args in categories['all']: i.reply("Category is now %s." % args) current_category = args current_category_type='sub' current_question = categories['all'][args].get_question() else: i.reply("No category found for "+args+".") return else: if current_category_type=='sub': current_question = categories['all'][current_category].get_question() elif current_category_type=='super': current_question = random.choice(categories[current_category].values()).get_question() i.reply(str(current_question))
def alias_to_lastfm(name): alias = data.query('SELECT username FROM lastfm_alias WHERE alias = ?',(name.lower(),)) if alias: return alias[0][0] else: return name
def add_replacement(find,replace,regex,setby): exists = find_replacement(find) if exists: data.query('''UPDATE replacebot_subs SET replace=?,is_regex=?,setby=? WHERE find=? ''',(replace,regex,setby,find)) else: data.query('''INSERT INTO replacebot_subs VALUES (?,?,?,?)''',(find,replace,regex,setby))
def AddUserIfNotExists(user): data.query("INSERT OR IGNORE INTO pubquiz_stats (handle) VALUES (?)", (user,))
def get_all_replacements(): return data.query('''SELECT * FROM replacebot_subs''')
def find_command(name): result = data.query("SELECT * FROM dynamic WHERE name = ? ORDER BY version DESC", (name,)) r = [] for x in result: r.append(dictify_result(x)) return r
def load_events(): d = data.query('SELECT interface, name, datetime FROM schedule') for e in d: dt = datetime.strptime(e[2],'%Y-%m-%d %H:%M:%S') if dt < datetime.now(): dt = datetime.now() queue_event(e[0],e[1],dt)
def find_replacement(text): q = data.query("SELECT * FROM replacebot_subs WHERE find = ?",(text,)) if q: return q[0]
def add_user_alias(alias, username): if get_recent_track(username): return data.query('INSERT INTO lastfm_alias VALUES (?,?)',(alias.lower(),username)) else: raise LastfmFetchFailed, alias