async def notify():
    channel = client.get_channel(int(db['notify']))
    while True:
        if not db['429']:
            utils.logger('NOTIFIER: check')
            for boss in utils.BOSSES:
                timer = utils.get_timer(boss)
                if timer is not None:
                    minutes = utils.minutes_sub(int(timer))
                    if 10 >= minutes >= 0:
                        utils.logger(f'NOTIFIER: {boss}:{minutes} preparing')
                        msg = None
                        key = boss + utils.SUB_SUFFIX
                        try:
                            subs_id = db[key]
                            if subs_id:
                                msg = f'{boss} due in {utils.minutes_to_dhm(timer)} {" ".join(subs_id)}'
                            else:
                                raise IndexError
                        except (KeyError, IndexError):
                            msg = f'{boss} due in {utils.minutes_to_dhm(timer)}'
                        try:
                            utils.logger(f'NOTIFIER: {boss} sending')
                            await channel.send(msg)
                            utils.logger(f'NOTIFIER: {boss} sent')
                        except discord.errors.HTTPException as e:
                            message_error = str(e)
                            utils.logger(message_error)
                            if '429' in message_error:
                                utils.status(True)
                                time.sleep(utils._429)
                                utils.status(False)
        utils.logger('NOTIFIER: finish check')
        time.sleep(300)
def get_boss(successor=None):
    msg_to_send = {'type': 'all', 'msg': None}
    while True:
        msg = yield msg_to_send
        msg_to_send['type'] = 'all'
        if msg.length and msg.content[0] in get_commands:
            boss = msg.content[1]
            minutes = utils.get_timer(boss)
            if minutes is not None:
                msg_to_send['msg'] = utils.minutes_to_dhm(minutes)
            else:
                msg_to_send['msg'] = f'{boss} no timer set'
        elif successor is not None:
            msg_to_send = successor.send(msg)
def api_get():
    api_key = get_api_key(request)
    user = auth(api_key)
    if user is not None:
        res_bosses = {}
        json = request.json
        req_bosses = json['bosses']
        utils.logger(f'API: {user} {json}')
        for boss in req_bosses:
            res_bosses[boss] = utils.get_timer(boss)
        return jsonify(res_bosses)
    response = Response()
    response.status_code = 401
    return response
Exemple #4
0
 async def cooldown_cmd(self, ctx):
     """
 Callback for the cooldown command
 --
 input:
   ctx: interactions.CommandContext
 """
     user = ctx.author
     current_time = int(ctx.id.epoch)
     timer = utils.get_timer(user.id, current_time)
     if timer > 0:
         output_text = f"You still need to wait {utils.seconds_to_formatted_string(timer)} before earning more {Constants.PIFLOUZ_EMOJI}!"
     else:
         output_text = f"You can earn more {Constants.PIFLOUZ_EMOJI}. DO IT RIGHT NOW!"
     await ctx.send(output_text, ephemeral=True)
def when_boss(successor=None):
    msg_to_send = {'type': 'all', 'msg': None}
    while True:
        msg = yield msg_to_send
        msg_to_send['type'] = 'all'
        if msg.length == 2 and msg.content[0] in when_commands:
            boss = msg.content[1]
            if boss in utils.BOSSES:
                timer = utils.get_timer(boss)
                if timer is not None:
                    msg_to_send[
                        'msg'] = f'{boss} due at {datetime.fromtimestamp(timer * 60)} gt'
                else:
                    msg_to_send['msg'] = f'{boss} no timer set'
            else:
                msg_to_send['msg'] = f'{boss} is not tracked'
        elif successor is not None:
            msg_to_send = successor.send(msg)
Exemple #6
0
def update_piflouz(user_id, qty=None, check_cooldown=True, current_time=None):
    """
  This function does the generic piflouz mining, and returns wether it suceeded or not
  --
  input:
    user_id: int/str -> id of the person who reacted
    qty: int -> number of piflouz (not necesseraly positive)
    check_cooldown: boolean -> if we need to check the cooldown (for the piflouz mining)
  --
  output:
    res: boolean -> if the update succeded
    qty: int -> the amount actually sent/received (only returned if check_cooldown = True (corresponding to a /get))
    current_time: int -> the time at which the interaction was created
  """
    if "piflouz_bank" not in db.keys():
        db["piflouz_bank"] = dict()

    user_id = str(user_id)

    # New user
    if user_id not in db["piflouz_bank"].keys():
        db["piflouz_bank"][user_id] = 0
        db["timers_react"][user_id] = 0

    balance = db["piflouz_bank"][user_id]

    if check_cooldown:  # corresponding to a /get
        assert current_time is not None, "Got current_time = None"

        cooldown = utils.get_timer(user_id, current_time)
        qty = get_total_piflouz_earned(user_id, current_time)
    else:
        assert qty is not None, "Got qty = None"

    if (not check_cooldown or cooldown == 0) and balance + qty >= 0:
        db["piflouz_bank"][user_id] = balance + qty
        if check_cooldown:
            db["timers_react"][user_id] = current_time
            return True, qty
        return True

    if check_cooldown:
        return False, qty
    return False
Exemple #7
0
 def __init__(self,
              destinationAddress,
              event,
              socket,
              lock,
              timeout=ECHO_REQUEST_TIMEOUT,
              count=ECHO_REQUEST_DEFAULT_COUNT):
     threading.Thread.__init__(self)
     self.timeout = timeout
     self.event = event
     self.count = count
     self.destinationAddress = destinationAddress
     self.receivedPackets = []
     self.sequence_number = 1
     self.lock = lock
     self.socket = socket
     self.id = id(self) & 0xFFFF
     self.timer = get_timer()
     self.received_packet_count = 0
def get_all(successor=None):
    msg_to_send = {'type': 'all', 'msg': None}
    while True:
        msg = yield msg_to_send
        msg_to_send['type'] = 'all'
        if msg.length == 1 and msg.content[0] in all_commands:
            msg_to_send['msg'] = ''
            frozen = False
            dl = False
            edl = False
            raid = False
            for boss in utils.BOSSES:
                timer = utils.get_timer(boss)
                if timer is not None:
                    boss2 = None
                    if boss.isdigit():
                        boss2 = int(boss)
                    if not frozen and boss2 is not None and 110 <= boss2 <= 140 and utils.minutes_sub(
                            timer) >= -10:
                        frozen = True
                        msg_to_send['msg'] += utils.separator_label(
                            'frozen:', separator='')
                    elif not dl and boss2 is not None and 155 <= boss2 <= 180 and utils.minutes_sub(
                            timer) >= -10:
                        dl = True
                        msg_to_send['msg'] += utils.separator_label('dl:')
                    elif not edl and boss2 is not None and 185 <= boss2 <= 215 and utils.minutes_sub(
                            timer) >= -10:
                        edl = True
                        msg_to_send['msg'] += utils.separator_label('edl:')
                    elif not raid and boss2 is None:
                        raid = True
                        msg_to_send['msg'] += utils.separator_label('raid:')
                    if boss2 is None or utils.minutes_sub(timer) >= -10:
                        msg_to_send[
                            'msg'] += f'{boss}: {utils.minutes_to_dhm(timer)}\n'
            if len(msg_to_send['msg']) < 1:
                msg_to_send['msg'] = 'no timers found'
        elif successor is not None:
            msg_to_send = successor.send(msg)
Exemple #9
0
    async def get_cmd(self, ctx):
        """
    Callback for the get command
    --
    input:
      ctx: interactions.CommandContext
    """
        await ctx.defer(ephemeral=True)

        current_time = int(ctx.id.epoch)
        piflouz_handlers.update_combo(ctx.author.id, current_time)
        successful_update, qty = piflouz_handlers.update_piflouz(
            ctx.author.id, current_time=current_time)

        if not successful_update:
            timer = utils.get_timer(ctx.author.id, current_time)

            output_text = f"You still need to wait {utils.seconds_to_formatted_string(timer)} before earning more {Constants.PIFLOUZ_EMOJI}!"
        else:
            output_text = f"You just earned {qty} {Constants.PIFLOUZ_EMOJI}! Come back later for some more\nYour current combo: {db['mining_combo'][str(ctx.author.id)]} / {piflouz_handlers.get_max_rewardable_combo(ctx.author.id)}"

        await ctx.send(output_text, ephemeral=True)
        await utils.update_piflouz_message(self.bot)
        self.bot.dispatch("combo_updated", ctx.author.id)
Exemple #10
0
async def on_ready():
    utils.status(False)
    utils.logger('BOT: logged')
    for boss in utils.BOSSES:
        db[boss] = utils.get_timer(boss)
Exemple #11
0
# Setup experiment model
trainer = Trainer(config)
trainer = mdl_to_device(trainer, gpu_info)

# Setup logger and output folders
exp_name = os.path.splitext(os.path.basename(opts.config))[0]
results_dir = logger_config['results_dir']
exp_dir, checkpoint_dir, img_dir = create_results_dir(results_dir, exp_name)
train_summary = SummaryWriter(os.path.join(exp_dir, 'logs/train_weight'))
val_summary = SummaryWriter(os.path.join(exp_dir, 'logs/val'))
img_summary = SummaryWriter(img_dir)
shutil.copy(opts.config, os.path.join(exp_dir, 'config.yaml'))

# Commence with new training or resume from checkpoint
iteration = trainer.resume(checkpoint_dir, val_loader, gpu_info) if opts.resume else 0
with get_timer("Elapsed time: %f"):
    while True:
        for it, (samples) in enumerate(train_loader):
            samples = dict_to_device(samples, gpu_info)

            # Weights training step
            trainer.update_model(samples)

            # Training logging step
            if (iteration + 1) % logger_config['train_log_iter'] == 0 or (iteration + 1) >= max_iter:
                print("Iteration - Weights update: %08d/%08d" % (iteration + 1, max_iter))
                model_statistics = trainer.get_train_loss()
                write_loss(iteration, train_summary, model_statistics)
                write_param(iteration, train_summary, trainer)
                write_grad(iteration, train_summary, trainer)
Exemple #12
0
#!/usr/bin/env python

import os, sys, socket, select, time
from ping_thread import *
from utils import get_timer, create_socket, print_statistics

lock = threading.Lock()
        
if __name__ == '__main__':
    default_timer = get_timer()
    ping_socket = create_socket()
    if(ping_socket != None):
        threads = []
        for host in sys.argv[1:]:
            event = threading.Event()
            thread = PingThread(host, event, ping_socket, lock)
            threads.append((id(thread) & 0xFFFF, event, thread))
            thread.setDaemon(True)
            thread.start()
            
        while(any(thread[2].isAlive() == True for thread in threads)):
        
            ready = select.select([ping_socket], [], [], 1)
            if not ready[0]:
                continue
                
            try:
                with lock:
                    recPacket, addr = ping_socket.recvfrom(2048)
            except socket.error:
                print("Can't receive")