Exemplo n.º 1
0
async def send_reminder(client, timer: Timer):
    handles.pop(timer.id, None)
    del data['timers'][timer.id]
    storage.save()

    channel = client.get_channel(timer.channel_id)
    if not channel:
        logging.error(f"Cannot find channel for {timer}")
        return

    text = timer.text or "I am visiting from the past to remind you of something."
    text = f"<@{timer.user_id}> {text}"
    now = datetime.now()
    if now > timer.timestamp + timedelta(seconds=5):
        text = f"{text} ({format_timedelta(now - timer.timestamp)} late)"
    reference = discord.MessageReference(
        message_id=timer.message_id,
        channel_id=timer.channel_id,
        guild_id=timer.guild_id,
        fail_if_not_exists=False,
    )
    await channel.send(
        text,
        reference=reference,
        # Generally we want to allow mentions,
        # but no power abuse through the bot's permissions
        allowed_mentions=NO_EVERYONE_MENTIONS,
        mention_author=True,
    )
Exemplo n.º 2
0
	def on_mode(self, conn, event):
		if irc.client.is_channel(event.target):
			for mode in irc.modes.parse_channel_modes(" ".join(event.arguments)):
				if mode[0] == "+" and mode[1] == 'o':
					self.mods.add(mode[2].lower())
					storage.data['mods'] = list(self.mods)
					storage.save()
Exemplo n.º 3
0
def modify_commands(commands):
    bot.remove_command(generate_expression(storage.data["responses"]))
    storage.data["responses"] = {k.lower(): v for k, v in commands.items()}
    storage.save()
    static_response.__doc__ = generate_docstring()
    bot.add_command(generate_expression(storage.data["responses"]),
                    static_response)
Exemplo n.º 4
0
def alarm_save():
    fields = ['id_', 'name', 'volume', 'stream', 'action']
    data = dict([ (k, request.POST.get(k)) for k in fields  ])
    data['volume'] = int(data['volume'])
    data['type'] = 'radio'

    try:
        date = request.POST.get('date')
        hour = request.POST.get('hour')
        data['at'] = time.mktime(time.strptime("%s %s" % (date, hour),
                                               "%Y-%m-%d %H:%M:%S"))
        dt = datetime.datetime.fromtimestamp(data['at'])
        data['date'] = dt.strftime('%Y-%m-%d')
        data['hour'] = dt.strftime('%H:%M:%S')
    except:
        return "Problem with the date... Chek it, please"

    if data['id_']:
        data['id_'] = int(data['id_'])
        alarms_data = storage.replace('alarms', data)
        storage.save_table('alarms', alarms_data)
    else:
        # TODO: All this logic of getting a new ID for the given table should
        # be handled by the storage lib
        stored = storage.read()
        ids = map(lambda x: x['id_'], stored['alarms'])
        data['id_'] = max(ids)+1 if ids else 1

        stored['alarms'].append(data)
        storage.save(stored)

    alarms.set_alarms(storage.read('alarms'))

    redirect('/alarm/edit/%s' % data['id_'])
Exemplo n.º 5
0
	def on_notification(self, conn, event, respond_to):
		"""Handle notification messages from Twitch, sending the message up to the web"""
		log.info("Notification: %s" % event.arguments[0])
		notifyparams = {
			'apipass': config['apipass'],
			'message': event.arguments[0],
			'eventtime': time.time(),
		}
		if irc.client.is_channel(event.target):
			notifyparams['channel'] = event.target[1:]
		subscribe_match = self.re_subscription.match(event.arguments[0])
		if subscribe_match:
			notifyparams['subuser'] = subscribe_match.group(1)
			try:
				channel_info = twitch.get_info(subscribe_match.group(1))
			except:
				pass
			else:
				if channel_info.get('logo'):
					notifyparams['avatar'] = channel_info['logo']
			# have to get this in a roundabout way as datetime.date.today doesn't take a timezone argument
			today = datetime.datetime.now(config['timezone']).date().toordinal()
			if today != storage.data.get("storm",{}).get("date"):
				storage.data["storm"] = {
					"date": today,
					"count": 0,
				}
			storage.data["storm"]["count"] += 1
			storage.save()
			conn.privmsg(respond_to, "lrrSPOT Thanks for subscribing, %s! (Today's storm count: %d)" % (notifyparams['subuser'], storage.data["storm"]["count"]))

			self.subs.add(subscribe_match.group(1).lower())
			storage.data['subs'] = list(self.subs)
			storage.save()
		utils.api_request('notifications/newmessage', notifyparams, 'POST')
Exemplo n.º 6
0
def main(cmd, dataset, run, conf, make_videos):   
    if make_videos:
        from visualize_tracking import render_video
        from config import DatasetConfig
        from apply_mask import Masker
        
        mask = Masker(dataset)
        dc = DatasetConfig(dataset)
        
    config_path = "{rp}{ds}_{rn}/world_tracking_optimization.pklz".format(rp=runs_path, ds=dataset, rn=run)
    if isfile(config_path):
        config = load(config_path)
    else:
        #raise(ValueError("No world tracking optimized configuration exists at {}".format(config_path)))
        config = WorldTrackingConfig(default_config)
    
    calib = Calibration(dataset)    
    munkres = Munkres()
    ts = Timestamps(dataset)
    
    start_stop = None
    
    if cmd == "findvids":
        from glob import glob
        vidnames = glob('{dsp}{ds}/videos/*.mkv'.format(dsp=datasets_path, ds=dataset))
        vidnames = [right_remove(x.split('/')[-1], '.mkv') for x in vidnames]
        vidnames.sort()
        
        outfolder = '{}{}_{}/tracks_world/'.format(runs_path, dataset, run)
        mkdir(outfolder)
    else:
        vidnames = [cmd]
        outfolder = './'
        start_stop = (0,500)
            
    for v in vidnames:
        print_flush(v)    
        out_path = "{of}{v}_tracks.pklz".format(of=outfolder, v=v)
        
        print_flush("Loading data...")
        det_path = "{rp}{ds}_{rn}/detections_world/{v}_world.csv".format(rp=runs_path, ds=dataset, rn=run, v=v)
        detections3D = pd.read_csv(det_path)
        
        klt_path = det_path.replace('.csv', '_klt.pklz')
        klts = load(klt_path)
        
        print_flush("Tracking...")
        tracks = make_tracks(dataset, v, detections3D, klts, munkres, ts, calib, config, start_stop=start_stop)
        
        print_flush("Saving tracks...")
        save(tracks, out_path)
        
        if make_videos:

            vidpath = "{dsp}{ds}/videos/{v}.mkv".format(dsp=datasets_path, ds=dataset, v=v)
            print_flush("Rendering video...")
            render_video(tracks, vidpath, out_path.replace('.pklz','.mp4'), calib=calib, mask=mask, fps=dc.get('video_fps'))

    print_flush("Done!")
Exemplo n.º 7
0
def main(cmd, dataset, run, conf, make_videos):   
    from pathlib import Path
    
    if make_videos:
        from visualize_tracking import render_video
        from config import DatasetConfig
        from apply_mask import Masker
        
        mask = Masker(dataset)
        dc = DatasetConfig(dataset)
        
    config_path = runs_path / "{}_{}".format(dataset,run) / "world_tracking_optimization.pklz"
    if config_path.is_file():
        config = load(config_path)
    else:
        #raise(ValueError("No world tracking optimized configuration exists at {}".format(config_path)))
        config = WorldTrackingConfig(default_config)
    
    calib = Calibration(dataset)    
    munkres = Munkres()
    ts = Timestamps(dataset)
    
    start_stop = None
    
    if cmd == "findvids":
        vidnames = (datasets_path / dataset / "videos").glob('*.mkv')
        vidnames = [x.stem for x in vidnames]
        vidnames.sort()
        
        outfolder = runs_path / "{}_{}".format(dataset,run) / "tracks_world"
        mkdir(outfolder)
    else:
        vidnames = [cmd]
        outfolder = Path('./')
        start_stop = (0,500)
            
    for v in vidnames:
        print_flush(v) 
        out_path = outfolder / (v+'_tracks.pklz')   
        
        print_flush("Loading data...")
        det_path = runs_path / "{}_{}".format(dataset,run) / "detections_world" / (v+'_world.csv')
        detections3D = pd.read_csv(det_path)
        
        klt_path = det_path.with_name(det_path.stem + '_klt.pklz')
        klts = load(klt_path)
        
        print_flush("Tracking...")
        tracks = make_tracks(dataset, v, detections3D, klts, munkres, ts, calib, config, start_stop=start_stop)
        
        print_flush("Saving tracks...")
        save(tracks, out_path)
        
        if make_videos:            
            vidpath = datasets_path / dataset / "videos" / (v+'.mkv')
            print_flush("Rendering video...")
            render_video(tracks, vidpath, out_path.with_suffix('.mp4'), calib=calib, mask=mask, fps=dc.get('video_fps'))

    print_flush("Done!")
Exemplo n.º 8
0
def set_game_name(lrrbot, conn, event, respond_to, name):
	game = lrrbot.get_current_game()
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game, if they are yell at them to update the stream")
		return
	game["display"] = name
	storage.save()
	conn.privmsg(respond_to, "OK, I'll start calling %(name)s \"%(display)s\"" % game)
Exemplo n.º 9
0
def completed(lrrbot, conn, event, respond_to):
	game = lrrbot.get_current_game()
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game")
		return
	game.setdefault("stats", {}).setdefault("completed", 0)
	game["stats"]["completed"] += 1
	storage.save()
	conn.privmsg(respond_to, "%s added to the completed list" % game_name(game))
Exemplo n.º 10
0
 def save(self, filename):
     """ save current state of todos list
     Args:
         filename: string
     Returns:
         Boolean
     """
     storage.save(dict(self), filename)
     return True
Exemplo n.º 11
0
def modify_explanations(commands):
    bot.remove_command("explain " +
                       generate_expression(storage.data["explanations"]))
    storage.data["explanations"] = {k.lower(): v for k, v in commands.items()}
    storage.save()
    explain_response.__doc__ = generate_explain_docstring()
    bot.add_command(
        "explain " + generate_expression(storage.data["explanations"]),
        explain_response)
Exemplo n.º 12
0
	def on_metadata(self, conn, event):
		subscriber_match = self.re_subscriber.match(event.arguments[0])
		if subscriber_match:
			subuser = subscriber_match.group(1).lower()
			if subuser not in self.subs:
				self.subs.add(subuser)
				storage.data['subs'] = list(self.subs)
				storage.save()
			self.upcomingsubs.add(subuser)
Exemplo n.º 13
0
def music(lrrbot, conn, event, respond_to, name):
	"""
	Command: !music playing NAME
	
	Replaces current Music: playing: string with NAME
	"""
	storage.data['music']["playing"] = name
	storage.save()
	conn.privmsg(respond_to, "Music added, now playing: %s" % name)
Exemplo n.º 14
0
def stormcount(lrrbot, conn, event, respond_to):
	today = datetime.datetime.now(config["timezone"]).date().toordinal()
	if today != storage.data.get("storm", {}).get("date"):
		storage.data["storm"] = {
			"date": today,
			"count": 0
		}
		storage.save()
	conn.privmsg(respond_to, "Today's storm count: %d" % storage.data["storm"]["count"])
Exemplo n.º 15
0
def crawl():
    """
    Main method for executing a report. Calls other modules to provide a result
    :return: void
    """
    crawler = Crawler()
    run(crawler)
    authors, articles = get(crawler.get_authors(), crawler.get_articles())
    save(authors, articles)
    visualize(authors, articles)
Exemplo n.º 16
0
def start():
    while True:
        # Oeffnet Tkinter Operation um Textdatei zu bekommen
        filename = window.getfilename()

        # Wenn gecancelt wird gefragt, ob das Programm beendet werden soll.
        if filename == '':
            askabort = input("Moechtest du das Programm beenden? (Y/N) ")
            if askabort is 'N':
                continue
            else:
                print("Auf Wiedersehen.")
                break

        with open(filename, 'r') as f:
            text = f.read()

        # Titel und Autor werden nochmal einzelnd eingeben
        # Erwingt Eingabe
        while True:
            titel = input("Bitte gebe den Titel des Textes ein: ")
            if titel == '':
                continue
            else:
                break
        while True:
            author = input("Bitte gebe den Autor des Textes ein: ")
            if author == '':
                continue
            else:
                break

        # Werte werden errechnet
        print("Bitte warten...")
        textsignatur = calculate.signatur(titel, author, text)
        print(textsignatur)

        # Text und Werte werden abgespeichert, um spaeter mit anderen Texten veglichen zu werden
        storage.save(textsignatur)

        # Abfrage, ob nur Signatur errechnet werden sollte, ob jetzt verglichen werden soll oder neuer Text eingescannt.
        answer = input("Aehnlichen Autoren finden? (Y/N) ")
        if answer == 'Y':
            with shelve.open('storage') as sto:
                if len(sto) < 2:
                    print("Leider gibt es noch keine vorigen Texte")
                else:
                    compare.toAll(textsignatur)

        answertwo = input("Weiteren Text erfassen? (Y/N) ")
        if answertwo == 'Y':
            continue
        else:
            print("Auf Wiedersehen")
            break
Exemplo n.º 17
0
def stat_update(lrrbot, stat, n, set_=False):
    game = lrrbot.get_current_game()
    if game is None:
        return None
    game.setdefault("stats", {}).setdefault(stat, 0)
    if set_:
        game["stats"][stat] = n
    else:
        game["stats"][stat] += n
    storage.save()
    return game
Exemplo n.º 18
0
def post_world_tracking_config(dataset_name, run_name, world_tracking_config):
    dataset_name, run_name = map(quote, (dataset_name, run_name))
    path = "{rp}{dn}_{r}/world_tracking_optimization.pklz".format(rp=runs_path, dn=dataset_name, r=run_name)
    
    try:   
        wtc = WorldTrackingConfig(world_tracking_config)
    except ValueError:
        return (NoContent, 400)
    else:
        save(wtc, path)
        return (NoContent, 200)
Exemplo n.º 19
0
def stat_update(lrrbot, stat, n, set_=False):
	game = lrrbot.get_current_game()
	if game is None:
		return None
	game.setdefault("stats", {}).setdefault(stat, 0)
	if set_:
		game["stats"][stat] = n
	else:
		game["stats"][stat] += n
	storage.save()
	return game
Exemplo n.º 20
0
def get_files() -> Dict[str, str]:
    result = {}

    for key, file in request.files.items():
        name = hashlib.md5(file.read()).hexdigest()
        file.seek(0)

        storage.save(bucket=storage.Bucket.files, name=name, file=file)
        result[key] = name

    return result
Exemplo n.º 21
0
def vote(lrrbot, conn, event, respond_to, vote):
	game = lrrbot.get_current_game()
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game")
		return
	nick = irc.client.NickMask(event.source).nick
	game.setdefault("votes", {})
	game["votes"][nick.lower()] = (vote.lower() == "good")
	storage.save()
	lrrbot.vote_update = game
	vote_respond(lrrbot, conn, event, respond_to, game)
Exemplo n.º 22
0
    def handle_page(self, response):
        html = response.body.decode("utf-8")
        wallpapers_nodes = page_parser.parse_page(html)
        date = page_parser.extract_date(html)
        wallpapers = wallpapers_parser.parse_wallpapers(wallpapers_nodes)

        for wallpaper in wallpapers:
            wallpaper.year = date['year']
            wallpaper.month = date['month']

        storage.create()
        storage.save(wallpapers)
Exemplo n.º 23
0
def post_world_tracking_config(dataset_name, run_name, world_tracking_config):
    dataset_name, run_name = map(quote, (dataset_name, run_name))
    path = runs_path / "{}_{}".format(
        dataset_name, run_name) / "world_tracking_optimization.pklz"

    try:
        wtc = WorldTrackingConfig(world_tracking_config)
    except ValueError:
        return (NoContent, 400)
    else:
        save(wtc, str(path))
        return (NoContent, 200)
Exemplo n.º 24
0
	def check_subscriber(self, conn, nick):
		"""
		If a user says something that was not immediately preceded by
		jtv saying "SPECIALUSER thisguy subscriber" then remove them from
		the subscriber list, if they're in it.
		"""
		if nick not in self.upcomingsubs and nick in self.subs:
			self.subs.remove(nick)
			storage.data['subs'] = list(self.subs)
			storage.save()
		elif nick in self.upcomingsubs:
			self.upcomingsubs.remove(nick)
Exemplo n.º 25
0
def stormcount(lrrbot, conn, event, respond_to):
    """
	Command: !storm
	Command: !stormcount

	Show the current storm count (the number of viewers who have subscribed today)
	"""
    today = datetime.datetime.now(config["timezone"]).date().toordinal()
    if today != storage.data.get("storm", {}).get("date"):
        storage.data["storm"] = {"date": today, "count": 0}
        storage.save()
    conn.privmsg(respond_to,
                 "Today's storm count: %d" % storage.data["storm"]["count"])
Exemplo n.º 26
0
def klt_save(vidpath, datpath, imsize, mask, outvidpath=None):
    """ Computes and saves KLT point tracks
        
        Arguments:
        vidpath    -- path to input video
        datpath    -- path to store the tracks (use .pklz extension)
        imsize     -- size to resize frames to 
        mask       -- mask to apply if only parts of the image are of interest
        outvidpath -- path to output video, can be None
    """
    tracks = kltfull(vidpath, imsize, mask, outvidpath)

    print_flush("Saving...")
    save(tracks, datpath)
Exemplo n.º 27
0
	def on_server_event_set_data(self, user, data):
		if not isinstance(data['key'], (list, tuple)):
			data['key'] = [data['key']]
		log.info("Setting storage %s to %r" % ('.'.join(data['key']), data['value']))
		# if key is, eg, ["a", "b", "c"]
		# then we want to effectively do:
		# storage.data["a"]["b"]["c"] = value
		# But in case one of those intermediate dicts doesn't exist:
		# storage.data.setdefault("a", {}).setdefault("b", {})["c"] = value
		node = storage.data
		for subkey in data['key'][:-1]:
			node = node.setdefault(subkey, {})
		node[data['key'][-1]] = data['value']
		storage.save()
Exemplo n.º 28
0
	def check_subscriber(self, conn, nick, metadata):
		"""
		Whenever a user says something, update the subscriber list according to whether
		their message has the subscriber-badge metadata attached to it.
		"""
		is_sub = 'subscriber' in metadata.get('specialuser', set())
		if not is_sub and nick in self.subs:
			self.subs.remove(nick)
			storage.data['subs'] = list(self.subs)
			storage.save()
		elif is_sub and nick not in self.subs:
			self.subs.add(nick)
			storage.data['subs'] = list(self.subs)
			storage.save()
Exemplo n.º 29
0
def set_game_name(lrrbot, conn, event, respond_to, name):
	"""
	Command: !game display NAME

	eg. !game display Resident Evil: Man Fellating Giraffe

	Change the display name of the current game to NAME.
	"""
	game = lrrbot.get_current_game(readonly=False)
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game, if they are yell at them to update the stream")
		return
	game["display"] = name
	storage.save()
	conn.privmsg(respond_to, "OK, I'll start calling %(name)s \"%(display)s\"" % game)
Exemplo n.º 30
0
def stormcount(lrrbot, conn, event, respond_to):
	"""
	Command: !storm
	Command: !stormcount

	Show the current storm count (the number of viewers who have subscribed today)
	"""
	today = datetime.datetime.now(config["timezone"]).date().toordinal()
	if today != storage.data.get("storm", {}).get("date"):
		storage.data["storm"] = {
			"date": today,
			"count": 0
		}
		storage.save()
	conn.privmsg(respond_to, "Today's storm count: %d" % storage.data["storm"]["count"])
Exemplo n.º 31
0
def spamcount(lrrbot, conn, event, respond_to):
	"""
	Command: !spam
	Command: !spamcount

	Show the number of users who have been automatically banned today for spamming
	"""
	today = datetime.datetime.now(config["timezone"]).date().toordinal()
	if today != storage.data.get("spam", {}).get("date"):
		storage.data["spam"] = {
			"date": today,
			"count": [0, 0, 0],
		}
		storage.save()
	conn.privmsg(respond_to, "Today's spam counts: %d hits, %d repeat offenders, %d bannings" % tuple(storage.data["spam"]["count"]))
Exemplo n.º 32
0
 def test_read_save(self):
     self.prepare_storage()
     save([{
         'name': 'author'
     }], [{
         'title': 'article',
         'date': 1541631600.0
     }])
     authors, articles = get([{
         'name': 'author2'
     }], [{
         'title': 'article2',
         'date': 1542236400.0
     }])
     self.assertEqual(len(articles), 2)
     self.assertEqual(len(authors), 2)
Exemplo n.º 33
0
    def POST(self, format):
        cgi.maxlen = settings.MAX_UP_FILE_SIZE
        if not format:
            format = '.json'

        input = web.input(file={})
        if input.file.file:
            if not is_mp3(input.file.file):
                return simplejson.dumps({
                    'code':
                    1,
                    'error':
                    'Check file format and try again'
                })
            try:
                info = get_mp3_info(input.file.file)
                info['FILENAME'] = input.file.filename
            except:
                return simplejson.dumps({
                    'code':
                    2,
                    'error':
                    'Error getting file information'
                })
            id = storage.save(info, input.file.file, db.master)
            search.update(id, info)
        return simplejson.dumps({'code': 0})
Exemplo n.º 34
0
def completed(lrrbot, conn, event, respond_to):
	"""
	Command: !game completed

	Mark a game as having been completed.
	"""
	game = lrrbot.get_current_game(readonly=False)
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game")
		return
	game.setdefault("stats", {}).setdefault("completed", 0)
	game["stats"]["completed"] += 1
	storage.save()
	emote = storage.data.get('stats', {}).get('completed', {}).get('emote', "")
	if emote:
		emote += " "
	conn.privmsg(respond_to, "%s%s added to the completed list" % (emote, game_name(game)))
Exemplo n.º 35
0
    def _load(self):
        loader = self._loader_builder(rows=self._rows,
                                      costs_file_id=self._get_document().get(
                                          'files', {}).get('costs'))

        output: io.BytesIO = io.BytesIO()

        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            for sheet_name, df in loader.get_dataframes(
            ):  # type: str, pd.DataFrame
                self._translated(df).to_excel(writer, sheet_name)
            writer.save()

        output.seek(0, 0)
        storage.save(storage.Bucket.reports, self._id, output)

        self._update_document(loader.state_after)
Exemplo n.º 36
0
async def timer(client, message, args):
    now = datetime.now()
    delta = parse_timedelta(args.timestamp)
    if not delta:
        timestamp = parse_datetime(args.timestamp)
        if not timestamp:
            await message.channel.send("Unable to parse timestamp.",
                                       reference=message)
            return
        delta = timestamp - now
    else:
        timestamp = now + delta

    if timestamp <= now:
        await message.channel.send(
            f"This timestamp is in the past (by {format_timedelta(-delta)})",
            reference=message,
        )
        return
    elif delta > MAX_DELTA:
        await message.channel.send(
            "This timestamp is too far in the future"
            f" (more than {format_timedelta(MAX_DELTA)})",
            reference=message,
        )
        return

    timer = Timer(
        timestamp=timestamp,
        guild_id=message.guild.id if message.guild else None,
        channel_id=message.channel.id,
        message_id=message.id,
        user_id=message.author.id,
        text=args.text,
    )
    data['timers'][timer.id] = timer
    storage.save()
    schedule(client, timer)

    await message.channel.send(
        f"I will remind you in **{format_timedelta(delta)}** ({timestamp:%Y-%m-%d %H:%M:%S%z});"
        f" ID: {timer.id}",
        reference=message,
        mention_author=False,
    )
Exemplo n.º 37
0
def spamcount(lrrbot, conn, event, respond_to):
    """
	Command: !spam
	Command: !spamcount

	Show the number of users who have been automatically banned today for spamming
	"""
    today = datetime.datetime.now(config["timezone"]).date().toordinal()
    if today != storage.data.get("spam", {}).get("date"):
        storage.data["spam"] = {
            "date": today,
            "count": [0, 0, 0],
        }
        storage.save()
    conn.privmsg(
        respond_to,
        "Today's spam counts: %d hits, %d repeat offenders, %d bannings" %
        tuple(storage.data["spam"]["count"]))
Exemplo n.º 38
0
def completed(lrrbot, conn, event, respond_to):
    """
	Command: !game completed

	Mark a game as having been completed.
	"""
    game = lrrbot.get_current_game()
    if game is None:
        conn.privmsg(respond_to, "Not currently playing any game")
        return
    game.setdefault("stats", {}).setdefault("completed", 0)
    game["stats"]["completed"] += 1
    storage.save()
    emote = storage.data.get('stats', {}).get('completed', {}).get('emote', "")
    if emote:
        emote += " "
    conn.privmsg(respond_to,
                 "%s%s added to the completed list" % (emote, game_name(game)))
Exemplo n.º 39
0
def set_game_name(lrrbot, conn, event, respond_to, name):
    """
	Command: !game display NAME

	eg. !game display Resident Evil: Man Fellating Giraffe

	Change the display name of the current game to NAME.
	"""
    game = lrrbot.get_current_game()
    if game is None:
        conn.privmsg(
            respond_to,
            "Not currently playing any game, if they are yell at them to update the stream"
        )
        return
    game["display"] = name
    storage.save()
    conn.privmsg(respond_to,
                 "OK, I'll start calling %(name)s \"%(display)s\"" % game)
Exemplo n.º 40
0
def highlight(lrrbot, conn, event, respond_to, description):
	"""
	Command: !highlight DESCRIPTION

	For use when something particularly awesome happens onstream, adds an entry on the Highlight Reel spreadsheet: https://docs.google.com/spreadsheets/d/1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y

	Note that the highlights won't appear on the spreadsheet immediately, as the link won't be available until the stream finishes and the video is in the archive. It should appear within a day.
	"""
	if not twitch.get_info()["live"]:
		conn.privmsg(respond_to, "Not currently streaming.")
		return
	storage.data.setdefault("staged_highlights", [])
	storage.data["staged_highlights"] += [{
		"time": time.time(),
		"user": irc.client.NickMask(event.source).nick,
		"description": description,
	}]
	storage.save()
	conn.privmsg(respond_to, "Highlight added.")
Exemplo n.º 41
0
def vote(lrrbot, conn, event, respond_to, vote_good, vote_bad):
	"""
	Command: !game good
	Command: !game bad

	Declare whether you believe this game is entertaining to watch
	on-stream. Voting a second time replaces your existing vote. The
	host may heed this or ignore it at their choice. Probably ignore
	it.
	"""
	game = lrrbot.get_current_game(readonly=False)
	if game is None:
		conn.privmsg(respond_to, "Not currently playing any game")
		return
	nick = irc.client.NickMask(event.source).nick
	game.setdefault("votes", {})
	game["votes"][nick.lower()] = vote_good is not None
	storage.save()
	lrrbot.vote_update = game
	vote_respond(lrrbot, conn, event, respond_to, game)
Exemplo n.º 42
0
def vote(lrrbot, conn, event, respond_to, vote):
    """
	Command: !game good
	Command: !game bad

	Declare whether you believe this game is entertaining to watch
	on-stream. Voting a second time replaces your existing vote. The
	host may heed this or ignore it at their choice. Probably ignore
	it.
	"""
    game = lrrbot.get_current_game()
    if game is None:
        conn.privmsg(respond_to, "Not currently playing any game")
        return
    nick = irc.client.NickMask(event.source).nick
    game.setdefault("votes", {})
    game["votes"][nick.lower()] = (vote.lower() == "good")
    storage.save()
    lrrbot.vote_update = game
    vote_respond(lrrbot, conn, event, respond_to, game)
Exemplo n.º 43
0
def hecking_facebook_auth():
    data = request.json
    if data is None:
        data = json.loads(request.data)
    if 'username' not in data \
            or 'password' not in data \
            or 'tanda_id' not in data:
        return {'response': 'Error! Malformed data'}
    username = data['username']
    password = data['password']
    tanda_id = data['tanda_id']

    fb_access = tinder_api.get_fb_access_token(username, password)
    if 'error' in fb_access:
        return {'response': 'Failed to login. Incorrect email/password '
                            'combination?'}
    fb_user = tinder_api.get_fb_id(fb_access)

    add_store(tanda_id, fb_access, fb_user)
    save()

    return {'response': 'success'}
Exemplo n.º 44
0
	def check_spam(self, conn, event, message):
		"""Check the message against spam detection rules"""
		if not irc.client.is_channel(event.target):
			return False
		respond_to = event.target
		source = irc.client.NickMask(event.source)
		for re, desc in self.spam_rules:
			matches = re.search(message)
			if matches:
				log.info("Detected spam from %s - %r matches %s" % (source.nick, message, re.pattern))
				groups = {str(i+1):v for i,v in enumerate(matches.groups())}
				desc = desc % groups
				self.spammers.setdefault(source.nick.lower(), 0)
				self.spammers[source.nick.lower()] += 1
				level = self.spammers[source.nick.lower()]
				if level <= 1:
					log.info("First offence, flickering %s" % source.nick)
					conn.privmsg(event.target, ".timeout %s 1" % source.nick)
					conn.privmsg(event.target, "%s: Message deleted (first warning) for auto-detected spam (%s). Please contact mrphlip or d3fr0st5 if this is incorrect." % (source.nick, desc))
				elif level <= 2:
					log.info("Second offence, timing out %s" % source.nick)
					conn.privmsg(event.target, ".timeout %s" % source.nick)
					conn.privmsg(event.target, "%s: Timeout (second warning) for auto-detected spam (%s). Please contact mrphlip or d3fr0st5 if this is incorrect." % (source.nick, desc))
				else:
					log.info("Third offence, banning %s" % source.nick)
					conn.privmsg(event.target, ".ban %s" % source.nick)
					conn.privmsg(event.target, "%s: Banned for persistent spam (%s). Please contact mrphlip or d3fr0st5 if this is incorrect." % (source.nick, desc))
					level = 3
				today = datetime.datetime.now(config['timezone']).date().toordinal()
				if today != storage.data.get("spam",{}).get("date"):
					storage.data["spam"] = {
						"date": today,
						"count": [0, 0, 0],
				}
				storage.data["spam"]["count"][level - 1] += 1
				storage.save()
				return True
		return False
Exemplo n.º 45
0
def command_save():
    id_ = request.POST.get('id')
    class_ = request.POST.get('class')
    action = request.POST.get('action')
    command = request.POST.get('command', '')

    if not class_ or not action:
        return "Invalid data. CLASS and ACTION are required fields."

    if id_:
        new_command = {"id_": int(id_), "class_": class_, "action": action, "command": command}
        commands = storage.replace('commands', new_command)
        storage.save_table('commands', commands)
    else:
        data = storage.read()
        ids = map(lambda x: x['id_'], data['commands'])
        id_ = max(ids)+1 if ids else 1

        new_command = {"id_": int(id_), "class_": class_, "action": action, "command": command}
        data['commands'].append(new_command)
        storage.save(data)

    redirect("/command/edit/%s" % id_)
Exemplo n.º 46
0
	def POST(self):
		cgi.maxlen = settings.MAX_UP_FILE_SIZE

		input = web.input(file={})
		if input.file.file:
			if not is_mp3(input.file.file):
				raise web.seeother('/upload/error')
			try:
				info = get_mp3_info(input.file.file)
				info['FILENAME'] = input.file.filename
			except:
				raise web.seeother('/upload/error')
			id = storage.save(info, input.file.file, db.master)
			search.update(id, info)
		raise web.seeother('/')
Exemplo n.º 47
0
	def POST(self, format):
		cgi.maxlen = settings.MAX_UP_FILE_SIZE
		if not format:
			format = '.json'

		input = web.input(file={})
		if input.file.file:
			if not is_mp3(input.file.file):
				return simplejson.dumps({'code':1, 'error':'Check file format and try again'})
			try:
				info = get_mp3_info(input.file.file)
				info['FILENAME'] = input.file.filename
			except:
				return simplejson.dumps({'code':2, 'error':'Error getting file information'})
			id = storage.save(info, input.file.file, db.master)
			search.update(id, info)
		return simplejson.dumps({'code':0})
Exemplo n.º 48
0
    "http://www.white2tea.com/tea-shop/product-category/teaware-and-tea-accessories/teacups-teaware-and-tea-accessories/",
    "http://www.white2tea.com/tea-shop/product-category/teaware-and-tea-accessories/teapots/"

]
product_urls = []

output_filename = "output"
data = {"products": []}

for category_url in category_urls:
    year_urls.extend(find_year_urls(category_url))

for year_url in year_urls:
    product_urls.extend(find_product_urls(year_url))

print("done finding product urls")

for product_url in product_urls:
    try:
        page = load_single_page(product_url)
        name = find_name(page)
        options = find_options(page)
        single_product = {
            "name": name,
            "options": options
        }
        data["products"].append(single_product)
    except NoMaxQuantity as exception:
        print(str(exception).upper())
save(data, output_filename)
Exemplo n.º 49
0
	def on_server_event_modify_spam_rules(self, user, data):
		storage.data['spam_rules'] = data
		storage.save()
		self.spam_rules = [(re.compile(i['re']), i['message']) for i in storage.data['spam_rules']]
Exemplo n.º 50
0
            filtration_steps=args.filtration_steps)

    print "Decomp. took {}s.".format(time.time() - t0)
    print "Number of loops:", dual.number_of_nodes()
    print "Number of tree nodes:", tree.number_of_nodes()

    if args.save != "":
        print "Saving file."
        
        SAVE_FORMAT_VERSION = 5
        sav = {'version':SAVE_FORMAT_VERSION, \
                'leaf':leaf, 'tree':tree, 'dual':dual, \
                'filtration':filtr, 'pruned':pruned, \
                'removed-edges':removed_edges}
        
        storage.save(sav, args.save)
    
    print "Done."

    if args.plot:
        plt.figure()
        plot.draw_leaf(leaf, "Input leaf data")
        plt.figure()
        plot.draw_leaf(pruned, "Pruned leaf data and dual graph")
        plot.draw_dual(dual)
        plt.figure()
        plot.draw_tree(tree)
        plt.figure()
        plot.draw_filtration(filtr)
        plt.show()
Exemplo n.º 51
0
def postquote(nick, id, msg, date, action):
    logging.info('Quote #%s%s "%s" -%s by %s' % (id, action, msg, date, nick))
    bot.sendmsg('Quote #%s%s "%s" -%s' % (id, action, msg, date))
    save('Quote%s' % action)
Exemplo n.º 52
0
 def save_state(self):
     storage.save(self.id, self.voted_for, self.current_term, self.log)
Exemplo n.º 53
0
def modify_spam_rules(lrrbot, user, data):
	storage.data['spam_rules'] = data
	storage.save()
	lrrbot.spam_rules = [(re.compile(i['re']), i['message']) for i in storage.data['spam_rules']]
Exemplo n.º 54
0
def modify_commands(commands):
	storage.data["responses"] = {" ".join(k.lower().split()): v for k,v in commands.items()}
	storage.save()
	generate_hook()