Пример #1
0
    def __init__(self, config, prefix, scheme=None):
        if scheme is None:
            scheme = COLOR_SCHEME
        super(IRCProtocol, self).__init__(config, prefix, scheme)

        if log.root.level <= log.DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            log.info(u'[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(event,
                                           getattr(self, u'on_' + event), 0)
        self.joined_channels = []
        self.channels = []
        self.names = {}
        self.last_names_update = unix_time()
        self.update_channel_list()

        # throttling
        self.delay = self.config.irc.delay / float(1000)
        self.last_response = 0.0

        # keepalive
        self.keepalive = self.config.irc.keepalive
        if self.keepalive:
            self.last_keepalive = self.last_pong = unix_time()
            self.keepalive_freq = self.config.irc.keepalive_freq
            self.keepalive_timeout = self.config.irc.keepalive_timeout
Пример #2
0
    def __init__(self, base):
        super(IRCProtocol, self).__init__(base, scheme=COLOR_SCHEME)
        if settings.IRC_DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            self.log.info(u'[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(event, getattr(self, u'on_' + event), 0)
        self.channels = settings.IRC_CHANNELS
        self.names = {}
        self.last_names_update = unix_time()

        # throttling
        self.delay = settings.IRC_DELAY_LINES / float(1000)
        self.last_response = 0.0

        # keepalive
        self.keepalive = settings.IRC_KEEPALIVE
        if self.keepalive:
            self.last_keepalive = self.last_pong = unix_time()
            self.keepalive_freq = settings.IRC_KEEPALIVE_FREQ
            self.keepalive_timeout = settings.IRC_KEEPALIVE_TIMEOUT
Пример #3
0
    def __init__(self, base):
        super(IRCProtocol, self).__init__(base, scheme=COLOR_SCHEME)
        if settings.IRC_DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            self.log.info(u'[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(event, getattr(self, u'on_' + event), 0)
        self.channels = settings.IRC_CHANNELS
        self.names = {}
        self.last_names_update = unix_time()

        # throttling
        self.delay = settings.IRC_DELAY_LINES / float(1000)
        self.last_response = 0.0

        # keepalive
        self.keepalive = settings.IRC_KEEPALIVE
        if self.keepalive:
            self.last_keepalive = self.last_pong = unix_time()
            self.keepalive_freq = settings.IRC_KEEPALIVE_FREQ
            self.keepalive_timeout = settings.IRC_KEEPALIVE_TIMEOUT
Пример #4
0
 def inner(*args, **kwargs):
     if method in cache:
         if unix_time() - cache[method]['lastrun'] > timeout:
             del cache[method]
     if method not in cache:
         cache[method] = dict(lastrun=unix_time(),
                              result=method(*args, **kwargs))
     return cache[method]['result']
Пример #5
0
    def _privmsg(self, callback, sendto, message):
        for line in message.splitlines():
            delta = unix_time() - self.last_response
            if delta < self.delay:
                sleep(self.delay - delta)

            # XXX i guess pysilc expects unicode.. so, no control over
            # what the encoding is, sadly... silc FTL
            #line = line.encode(self.charset, 'replace')

            callback(sendto, line)
            self.last_response = unix_time()
Пример #6
0
 def run(self):
     """While bot is alive, process periodic event queue"""
     self.last_run = dict.fromkeys(self.bot.periodics.dict().keys(),
             unix_time())
     while self.bot.running:
         self.process_queue()
         sleep(self._process_frequency)
Пример #7
0
def split_finished(context):
    bottle.response.set_header('Cache-Control', 'max-age=900')
    fare_total = context['fare_total']
    total = context['total']
    if fare_total['fare'] != '-' and total < fare_total[
            'fare'] and not context['exclude'] and not request.query.all:
        typ = ''
        if context['day'] == 'y':
            typ = ' for the day'
        elif context['day'] == 'n':
            typ = ' return'
        line = u'%s to %s%s, around %s – <a href="%s">%s</a> instead of %s (<strong>%d%%</strong> saving)' % (
            context['fr_desc'], context['to_desc'], typ, context['time'],
            make_url(), utils.price(total), utils.price(fare_total['fare']),
            100 - round(total / fare_total['fare'] * 100))
        key = '%s%s' % (context['from'], context['to'])
        pipe = R.pipeline()
        pipe.hset('split-ticket-lines', key, line)
        pipe.zadd('split-ticket-latest', key, unix_time())
        pipe.zremrangebyrank('split-ticket-latest', 0, -11)
        pipe.incrby('split-ticket-total-saved',
                    int(fare_total['fare'] - total))
        pipe.incrby('split-ticket-total-orig', int(fare_total['fare']))
        pipe.incrby('split-ticket-total-split', int(total))
        pipe.execute()

    return context
Пример #8
0
 def connect(self):
     self.log.info("[IRC] * Connecting to %s:%s", settings.IRC_HOST, settings.IRC_PORT)
     self.server.connect(
         settings.IRC_HOST, settings.IRC_PORT, settings.BOTNAME, ssl=settings.IRC_SSL, password=settings.IRC_PASSWORD
     )
     if self.keepalive:
         self.last_keepalive = self.last_pong = unix_time()
Пример #9
0
    def _sign_request(self, method, url, params=None, payload=None):
        """Algorithm to sign a request as per the BigDoor documentation. Adds
        defaults to `params` and `payload` if not present.

        Parameters:
            - method string The HTTP method for the request

            - url string The full URL, including the base /api/publisher/[app_key]

            - params dict The parameters to be sent via the GET query string

            - payload dict The data to be sent via the POST body
        """
        if params is None:
            params = {}
        is_postish = method in ['post', 'put']

        # The payload time is assumed to be the correct value
        if is_postish and 'time' in payload:
            params['time'] = payload['time']
        if not 'time' in params:
            params['time'] = str(unix_time())
        if is_postish and not 'time' in payload:
            payload['time'] = params['time']

        if is_postish and not 'token' in payload:
            payload['token'] = self.generate_token()

        if method == 'delete' and not 'delete_token' in params:
            params['delete_token'] = self.generate_token()

        params['sig'] = self.generate_signature(url, params, payload)
        return params, payload
Пример #10
0
def split_finished(context):
    bottle.response.set_header('Cache-Control', 'max-age=900')
    fare_total = context['fare_total']
    total = context['total']
    if fare_total['fare'] != '-' and total < fare_total['fare'] and not context['exclude'] and not request.query.all:
        typ = ''
        if context['day'] == 'y':
            typ = ' for the day'
        elif context['day'] == 'n':
            typ = ' return'
        line = u'%s to %s%s, around %s – <a href="%s">%s</a> instead of %s (<strong>%d%%</strong> saving)' % (
            context['fr_desc'], context['to_desc'],
            typ, context['time'],
            make_url(), utils.price(total),
            utils.price(fare_total['fare']), 100-round(total/fare_total['fare']*100)
        )
        key = '%s%s' % (context['from'], context['to'])
        pipe = R.pipeline()
        pipe.hset( 'split-ticket-lines', key, line )
        pipe.zadd( 'split-ticket-latest', key, unix_time() )
        pipe.zremrangebyrank( 'split-ticket-latest', 0, -11 )
        pipe.incrby( 'split-ticket-total-saved', int(fare_total['fare'] - total) )
        pipe.incrby( 'split-ticket-total-orig', int(fare_total['fare']) )
        pipe.incrby( 'split-ticket-total-split', int(total) )
        pipe.execute()

    return context
Пример #11
0
    def response(self, *args):
        # determine who can be opped
        auto_op = []
        passwd = self.madcow.admin.authlib.get_passwd()
        for nick, data in passwd.items():
            if u'o' in data[u'flags']:
                auto_op.append(nick.lower())

        # issue NAMES update and wait for it to refresh (handled in irc.py)
        self.madcow.server.names(self.madcow.channels)
        while True:
            now = unix_time()
            delta = now - self.madcow.last_names_update
            if delta < self.frequency:
                break
            if delta >= (self.frequency * 2 -1):
                return
            sleep(.25)

        for channel, names in self.madcow.names.items():
            nicks = [nick for nick, opped in names.items() if not opped]
            if self.madcow.server.get_nickname() in nicks:
                self.log.warn(u'cannot give ops until i get it myself')
                return
            nicks = [nick for nick in nicks if nick in auto_op]
            for i in range(0, len(nicks), 6):
                line = nicks[i:i+6]
                self.log.info(u'opping on %s to %s' % (channel, u' '.join(line)))
                line = u'+' + (u'o' * len(line)) + u' ' + u' '.join(line)
                self.madcow.server.mode(channel, line)
Пример #12
0
    def run(self):
        self.connect()
        while self.running:
            try:
                self.check_response_queue()
                self.irc.process_once(0.5)

                if self.keepalive:
                    now = unix_time()

                    # a new keepalive should be sent
                    if now - self.last_keepalive > self.keepalive_freq:
                        self.server.ping(now)
                        self.last_keepalive = now
                        self.log.debug('PING %s' % now)

                    # server seems unresponsive
                    if now - self.last_pong > self.keepalive_timeout:
                        self.log.warn('server appears to have gone away')
                        self.server.disconnect('server unresponsive')

            except KeyboardInterrupt:
                self.running = False
            except irclib.ServerNotConnectedError:
                # There's a bug where sometimes on_disconnect doesn't fire
                if settings.IRC_RECONNECT and self.running:
                    sleep(settings.IRC_RECONNECT_WAIT)
                    self.connect()
            except:
                self.log.exception('Error in IRC loop')
Пример #13
0
def _log_event(request, event_type):
    try:
        time = int(unix_time())
        key = request.form['authkey']
        user = request.form['user']
        machine = request.form['machine']
        address = request.form['address']
    except KeyError:
        return json.dumps({'error': 'Missing POST data', 'code': 400}), 400

    if not utils.validate_key(key):
        return json.dumps({
            'error': 'Not Authorised, bad key {}'.format(key),
            'code': 401
        }), 401

    if event_type == 'login':
        utils.login(machine, time)
    elif event_type == 'logout':
        utils.logout(machine, time)

    # TODO: Do something with user and address data

    return json.dumps({
        'machine': machine,
        'time': time,
        'address': address,
        'user': user,
        'code': 200
    })
def write_data(script_name,
               run_time,
               red,
               green,
               blue,
               x_coordinate,
               y_coordinate,
               finished=None):
    """Given a row data, writes it to the main CSV"""
    LOGGER.info('Writing data to file')
    with open(DATA_FILE_NAME, 'a') as log_file:
        log_writer = writer(log_file,
                            delimiter=',',
                            quotechar='"',
                            quoting=QUOTE_NONNUMERIC)
        # Attach a final timestamp if not already there
        if finished is None:
            finished = unix_time()
        log_writer.writerow([
            script_name, run_time, red, green, blue, x_coordinate,
            y_coordinate, finished
        ])
        LOGGER.debug('Write successful')
        return Promise.resolve('written')
    LOGGER.error('Write failed')
    return Promise.reject('Unable to write data')
Пример #15
0
 def run(self):
     """While bot is alive, process periodic event queue"""
     self.last_run = dict.fromkeys(self.bot.periodics.dict().keys(),
                                   unix_time())
     while self.bot.running:
         self.process_queue()
         sleep(self._process_frequency)
Пример #16
0
def create_todo_reminder():
    if (guild_id := request.json.get('guild_id')) is not None:

        member = User.query.get(get_internal_id())

        if guild_id in [x.id for x in member.permitted_guilds()]:

            if (time_diff := request.json.get('time')) is not None and \
                    (todo_id := request.json.get('todo_id')) is not None:

                if (todo := Todo.query.get(todo_id)) is not None and \
                        todo.guild_id == guild_id:

                    reminder = Reminder(message=Message(embed=Embed(
                        title='Todo Reminder!',
                        description=
                        'You have stuff to do. More specifically, **{}**'.
                        format(todo.value),
                        color=0xFFFFFF)),
                                        time=unix_time() + time_diff,
                                        channel_id=todo.channel_id,
                                        username='******',
                                        method='todo',
                                        set_by=get_internal_id(),
                                        name='Todo Reminder')

                    db.session.add(reminder)
                    db.session.commit()

                else:
                    abort(400)
Пример #17
0
    def run(self):
        self.connect()
        while self.running:
            try:
                self.check_response_queue()
                self.irc.process_once(0.5)

                if self.keepalive:
                    now = unix_time()

                    # a new keepalive should be sent
                    if now - self.last_keepalive > self.keepalive_freq:
                        self.server.ping(now)
                        self.last_keepalive = now
                        self.log.debug('PING %s' % now)

                    # server seems unresponsive
                    if now - self.last_pong > self.keepalive_timeout:
                        self.log.warn('server appears to have gone away')
                        self.server.disconnect('server unresponsive')

            except KeyboardInterrupt:
                self.running = False
            except irclib.ServerNotConnectedError:
                # There's a bug where sometimes on_disconnect doesn't fire
                if settings.IRC_RECONNECT and self.running:
                    sleep(settings.IRC_RECONNECT_WAIT)
                    self.connect()
            except:
                self.log.exception('Error in IRC loop')
Пример #18
0
def process_covid_data(mac, service_data, rssi, flags):
    global vib_mode
    global packet_count

    if vib_mode in [MODE_ON_RX, MODE_BOTH]:
        vibra.vibrate(10)

    if vib_mode in [MODE_ON_NEW_MAC, MODE_BOTH] and mac not in seen:
        vibra.vibrate(100)

    if led_mode in [MODE_ON_RX, MODE_BOTH]:
        leds.flash_rocket(0, 31, 20)

    if led_mode in [MODE_ON_NEW_MAC, MODE_BOTH] and mac not in seen:
        leds.flash_rocket(1, 31, 200)

    packet_count += 1

    # try to produce a small int
    last_rx_time = time.time() - t0
    if mac in seen:
        print(bytes2hex(mac, ":"), rssi, bytes2hex(service_data), flags,
              seen[mac][1] + 1)
        seen[mac][0] = int(last_rx_time)
        seen[mac][1] += 1  # increase counter
        seen[mac][2][0] = max(seen[mac][2][0], rssi)
        seen[mac][2][1] = (seen[mac][2][1] + rssi) / 2
        seen[mac][2][2] = min(seen[mac][2][2], rssi)
        seen[mac][3][1] = time.unix_time()
    else:
        print(bytes2hex(mac, ":"), rssi, bytes2hex(service_data), flags, "1")
        # The elements are
        # - last rx time
        # - seen count
        # - rssi
        #   - max
        #   - avg
        #   - min
        # - timestamps
        #   - first seen
        #   - last seen
        # - flags
        # - service data
        seen[mac] = [
            int(last_rx_time), 1, [rssi, rssi, rssi],
            [time.unix_time(), time.unix_time()], flags, service_data
        ]
Пример #19
0
Файл: main.py Проект: pgsvox/bot
    async def timer(self, message, stripped, prefs):

        owner: int = message.guild.id

        if message.guild is None:
            owner = message.author.id

        if stripped == 'list':
            timers = session.query(Timer).filter(Timer.owner == owner)

            e = discord.Embed(title='Timers')
            for timer in timers:
                delta = int(unix_time() - timer.start_time)
                minutes, seconds = divmod(delta, 60)
                hours, minutes = divmod(minutes, 60)
                e.add_field(name=timer.name, value="{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds))

            await message.channel.send(embed=e)

        elif stripped.startswith('start'):
            timers = session.query(Timer).filter(Timer.owner == owner)

            if timers.count() >= 25:
                await message.channel.send(prefs.language.get_string('timer/limit'))

            else:
                n = stripped.split(' ')[1:2] or 'New timer #{}'.format(timers.count() + 1)

                if len(n) > 32:
                    await message.channel.send(prefs.language.get_string('timer/name_length').format(len(n)))

                elif n in [x.name for x in timers]:
                    await message.channel.send(prefs.language.get_string('timer/unique'))

                else:
                    t = Timer(name=n, owner=owner)
                    session.add(t)

                    session.commit()

                    await message.channel.send(prefs.language.get_string('timer/success'))

        elif stripped.startswith('delete '):

            n = ' '.join(stripped.split(' ')[1:])

            timers = session.query(Timer).filter(Timer.owner == owner).filter(Timer.name == n)

            if timers.count() < 1:
                await message.channel.send(prefs.language.get_string('timer/not_found'))

            else:
                timers.delete(synchronize_session='fetch')
                await message.channel.send(prefs.language.get_string('timer/deleted'))

                session.commit()

        else:
            await message.channel.send(prefs.language.get_string('timer/help'))
Пример #20
0
def process_matrix(time):
    # check whether this file has actually already been written
    output_file = out_dir + str(time) + '.csv'
    # and if it has skip it. No need to do that again
    if os.path.exists(output_file):
        print output_file, 'already exists'
        return
    start = unix_time()
    # make a router
    router = otp.getRouter()
    request = otp.createRequest()
    request.setModes('WALK, TRANSIT')
    request.setMaxTimeSec(1 * 3600)  # seconds
    request.setClampInitialWait(0)
    request.setMaxWalkDistance(3000)  # meters?
    request.setDateTime(time.year, time.month, time.day, time.hour,
                        time.minute, time.second)
    # open the output list with list of header values
    out = [['-'] + [p['id'] for p in points]]
    # loop over origins
    for o in points:
        if int(o['id']) % 10 == 0:
            print router_name, str(time), o['id'] + '/' + str(len(points))
        # add origin to request and walk out from that point
        request.setOrigin(o['lat'], o['lon'])
        spt = router.plan(request)
        if spt is None:
            # add an empty row if the origin doesn't reach anything
            out.append([o['id']] + ['-'] * len(points))
            continue
        # loop over destinations, getting times
        times = []
        for d in points:
            result = spt.eval(d['lat'], d['lon'])
            if result is not None:
                times.append(str(result.getTime()))
            else:
                times.append('-')
        # add the times for this origin
        out.append([o['id']] + times)
    # format and write the output. Currently a list of lists of strings
    with open(output_file, 'w+') as out_file:
        # add commas and newlines and write to file
        formatted_text = '\n'.join([','.join(r) for r in out])
        out_file.write(formatted_text)
    print unix_time() - start, 'seconds to complete'
Пример #21
0
 def callback(*args, **kwargs):
     r = repr(self.__state)
     if (unix_time() - self.state['first_event']) > self.period:
         self._reset()
     if self.state['count'] >= self.threshold:
         return
     self.state['count'] += 1
     return function(*args, **kwargs)
Пример #22
0
 def connect(self):
     log.info(u'[IRC] * Connecting to %s:%s' % (
         self.config.irc.host, self.config.irc.port))
     self.server.connect(self.config.irc.host, self.config.irc.port,
                         self.config.irc.nick, ssl=self.config.irc.ssl,
                         password=self.config.irc.password)
     if self.keepalive:
         self.last_keepalive = self.last_pong = unix_time()
Пример #23
0
 def callback(*args, **kwargs):
     r = repr(self.__state)
     if (unix_time() - self.state['first_event']) > self.period:
         self._reset()
     if self.state['count'] >= self.threshold:
         return
     self.state['count'] += 1
     return function(*args, **kwargs)
Пример #24
0
    def _process_spaceless(self) -> float:
        if self.process_type == TimeExtractionTypes.EXPLICIT:
            d = self._process_explicit()
            return d

        else:
            d = self._process_displacement()
            return unix_time() + d
Пример #25
0
    async def remind(self, is_interval, message, stripped, server):

        args = stripped.split(' ')

        if len(args) < 2:
            if is_interval:
                await message.channel.send(embed=discord.Embed(
                    description=server.language.get_string('interval/no_argument').format(prefix=server.prefix)))

            else:
                await message.channel.send(embed=discord.Embed(
                    description=server.language.get_string('remind/no_argument').format(prefix=server.prefix)))

        else:
            if is_interval and not await self.is_patron(message.author.id):
                await message.channel.send(
                    embed=discord.Embed(description=server.language.get_string('interval/donor')))

            else:
                interval = None
                scope_id = message.channel.id

                if args[0][0] == '<' and message.guild is not None:
                    arg = args.pop(0)
                    scope_id = int(''.join(x for x in arg if x in '0123456789'))

                t = args.pop(0)
                time_parser = TimeExtractor(t, server.timezone)

                try:
                    mtime = time_parser.extract_exact()

                except InvalidTime:
                    await message.channel.send(
                        embed=discord.Embed(description=server.language.get_string('remind/invalid_time')))
                else:
                    if is_interval:
                        i = args.pop(0)

                        parser = TimeExtractor(i, server.timezone)

                        try:
                            interval = parser.extract_displacement()

                        except InvalidTime:
                            await message.channel.send(embed=discord.Embed(
                                description=server.language.get_string('interval/invalid_interval')))
                            return

                    text = ' '.join(args)

                    result = await self.create_reminder(message, scope_id, text, mtime, interval, method='remind')

                    response = server.language.get_string(REMIND_STRINGS[result.status]).format(
                        location=result.location.mention, offset=int(result.time - unix_time()),
                        min_interval=MIN_INTERVAL, max_time=MAX_TIME_DAYS)

                    await message.channel.send(embed=discord.Embed(description=response))
Пример #26
0
 def validate_key(self, key):
     '''
     Check if key exists, touch it if so
     '''
     if self.r.zscore(self.keys_key, key) is not None:
         # Update 'touched' score
         self.r.zadd(self.keys_key, int(unix_time()), key)
         return True
     return False
Пример #27
0
    def frame_from_sink(self, sink):
        sample = sink.emit("pull-sample")
        if sample is not None:
            buffer = sample.get_buffer()
            string = buffer.extract_dup(0, buffer.get_size())
            self.time = unix_time()
            self.jpeg = string

        return False
Пример #28
0
    def __init__(self, *args, **kwargs):
        self.start_time: float = unix_time()

        self.commands: typing.Dict[str, Command] = {

            'ping': Command('ping', self.time_stats),

            'help': Command('help', self.help, blacklists=False),
            'info': Command('info', self.info),
            'donate': Command('donate', self.donate),

            'timezone': Command('timezone', self.set_timezone),
            'lang': Command('lang', self.set_language),
            'clock': Command('clock', self.clock),

            'todo': Command('todo', self.todo),
            'todos': Command('todos', self.todos, False, PermissionLevels.MANAGED),

            'natural': Command('natural', self.natural, True, PermissionLevels.MANAGED),
            'n': Command('natural', self.natural, True, PermissionLevels.MANAGED),
            'remind': Command('remind', self.remind_cmd, True, PermissionLevels.MANAGED),
            'r': Command('remind', self.remind_cmd, True, PermissionLevels.MANAGED),
            'interval': Command('interval', self.interval_cmd, True, PermissionLevels.MANAGED),
            # TODO: remodel timer table with FKs for guild table
            'timer': Command('timer', self.timer, False, PermissionLevels.MANAGED),
            'del': Command('del', self.delete, True, PermissionLevels.MANAGED),
            # TODO: allow looking at reminder attributes in full by name
            'look': Command('look', self.look, True, PermissionLevels.MANAGED),

            'alias': Command('alias', self.create_alias, False, PermissionLevels.MANAGED),
            'a': Command('alias', self.create_alias, False, PermissionLevels.MANAGED),

            'prefix': Command('prefix', self.change_prefix, False, PermissionLevels.RESTRICTED),

            'blacklist': Command('blacklist', self.blacklist, False, PermissionLevels.RESTRICTED, blacklists=False),
            'restrict': Command('restrict', self.restrict, False, PermissionLevels.RESTRICTED),

            'offset': Command('offset', self.offset_reminders, True, PermissionLevels.RESTRICTED),
            'nudge': Command('nudge', self.nudge_channel, True, PermissionLevels.RESTRICTED),
            'pause': Command('pause', self.pause_channel, False, PermissionLevels.RESTRICTED),
        }

        self.match_string = None

        self.command_names = set(self.commands.keys())
        self.joined_names = '|'.join(self.command_names)

        # used in restrict command for filtration
        self.max_command_length = max(len(x) for x in self.command_names)

        self.config: Config = Config(filename='config.ini')

        self.executor: concurrent.futures.ThreadPoolExecutor = concurrent.futures.ThreadPoolExecutor()
        self.c_session: typing.Optional[aiohttp.ClientSession] = None

        super(BotClient, self).__init__(*args, **kwargs)
Пример #29
0
    def run(self):
        """While bot is alive, process periodic event queue"""
        delay = 5
        now = unix_time()
        for mod_name, mod in self.bot.periodics.modules.iteritems():
            self.last_run[mod_name] = now - mod[u'obj'].frequency + delay

        while self.bot.running:
            self.process_queue()
            sleep(self._process_frequency)
Пример #30
0
    def auth_token(cls):
        if not os.path.exists(WX_TOKEN_PATH):
            return cls.update_token()

        with open(WX_TOKEN_PATH, 'r') as _file:
            token_data = json.loads(_file.read())

        if (int(unix_time()) - token_data['timestamp']) > 7000:
            return cls.update_token()

        return token_data
Пример #31
0
 def process_queue(self):
     """Process queue"""
     now = unix_time()
     for mod_name, obj in self.bot.periodics.dict().items():
         if (now - self.last_run[mod_name]) < obj.frequency:
             continue
         self.last_run[mod_name] = now
         req = Request(None)
         req.sendTo = obj.output
         request = (obj, None, None, {'req': req})
         self.bot.request_queue.put(request)
Пример #32
0
 def process_queue(self):
     """Process queue"""
     now = unix_time()
     for mod_name, obj in self.bot.periodics.dict().items():
         if (now - self.last_run[mod_name]) < obj.frequency:
             continue
         self.last_run[mod_name] = now
         req = Request(None)
         req.sendTo = obj.output
         request = (obj, None, None, {'req': req})
         self.bot.request_queue.put(request)
Пример #33
0
    def _process_spaceless(self) -> float:
        if self.process_type == TimeExtractionTypes.EXPLICIT:
            try:
                d = self._process_explicit()
            except ValueError:
                raise InvalidTime()
            return d

        else:
            d = self._process_displacement()
            return unix_time() + d
Пример #34
0
        def relative_time(t):
            days, seconds = divmod(int(t - unix_time()), 86400)
            hours, seconds = divmod(seconds, 3600)
            minutes, seconds = divmod(seconds, 60)

            sections = []

            for var, name in zip((days, hours, minutes, seconds), ('days', 'hours', 'minutes', 'seconds')):
                if var > 0:
                    sections.append('{} {}'.format(var, name))

            return ', '.join(sections)
Пример #35
0
 def process_queue(self):
     """Process queue"""
     now = unix_time()
     for mod_name, mod in self.bot.periodics.modules.iteritems():
         obj = mod[u'obj']
         if (now - self.last_run[mod_name]) < obj.frequency:
             continue
         self.last_run[mod_name] = now
         req = Request()
         req.sendto = obj.output
         request = (obj, None, None, {u'req': req})
         self.bot.request_queue.put(request)
Пример #36
0
    async def time_stats(self, message, *_):
        uptime: float = unix_time() - self.start_time

        message_ts: float = message.created_at.timestamp()

        m: discord.Message = await message.channel.send('.')

        ping: float = m.created_at.timestamp() - message_ts

        await m.edit(content='''
        Uptime: {}s
        Ping: {}ms
        '''.format(round(uptime), round(ping * 1000)))
Пример #37
0
        def callback(*args, **kwargs):
            now = unix_time()

            # expire cache values that have aged beyond timeout
            for key, item in self.cached.items():
                if (now - item['created']) > self.timeout:
                    del self.cached[key]

            # run wrapped function if there is no cached data
            if not self.cached.has_key(args):
                value = function(*args, **kwargs)
                self.cached[args] = {'created': now, 'value': value}

            # return
            return self.cached[args]['value']
Пример #38
0
    def gen_query_session_id(self, query):
        """
            Generates a query key ID and stores the query
            in the cache associating it with the generated ID.
            Arguments:
                query: query in dictionary form.
            Returns:
                The generated ID.
        """
        query_ses_id = md5(str(unix_time()).encode('utf-8')).hexdigest()

        self._session_cache.add_data(query, query_ses_id, "query")
        self._session_cache.add_data(None, query_ses_id, "backend_qid")
        #print ('Generated qsid: %s with query: %s' % (query_ses_id, query['qdef']))
        return query_ses_id
Пример #39
0
        def callback(*args, **kwargs):
            now = unix_time()

            # expire cache values that have aged beyond timeout
            for key, item in self.cached.items():
                if (now - item['created']) > self.timeout:
                    del self.cached[key]

            # run wrapped function if there is no cached data
            if not self.cached.has_key(args):
                value = function(*args, **kwargs)
                self.cached[args] = {'created': now, 'value': value}

            # return
            return self.cached[args]['value']
Пример #40
0
    def update_token(cls):
        re_code, re_data = HttpUtils.json_request(url=WX_URL.get('Token'),
                                                  method='post',
                                                  params={
                                                      'corpid': WX_CORP_ID,
                                                      'corpsecret': WX_SECRET
                                                  })

        HttpUtils.re_code_check(re_code, re_data)

        token_data = {
            'timestamp': int(unix_time()),
            'token': re_data['result'].get('access_token')
        }

        print(json.dumps(token_data), file=open(WX_TOKEN_PATH, 'w'))
        return token_data
Пример #41
0
 def on_namreply(self, server, event):
     """NAMES requested, cache their opped status"""
     self.log.debug(u'[IRC] Updating NAMES list')
     args = event.arguments()
     channel = args[1]
     nicks = {}
     for nick in args[2].split():
         nick = nick.lower()
         opped = False
         if nick.startswith(u'@'):
             opped = True
             nick = nick[1:]
         elif nick.startswith(u'+'):
             nick = nick[1:]
         nicks[nick] = opped
     self.names[channel] = nicks
     self.last_names_update = unix_time()
Пример #42
0
 def on_namreply(self, server, event):
     """NAMES requested, cache their opped status"""
     self.log.debug(u'[IRC] Updating NAMES list')
     args = event.arguments()
     channel = args[1]
     nicks = {}
     for nick in args[2].split():
         nick = nick.lower()
         opped = False
         if nick.startswith(u'@'):
             opped = True
             nick = nick[1:]
         elif nick.startswith(u'+'):
             nick = nick[1:]
         nicks[nick] = opped
     self.names[channel] = nicks
     self.last_names_update = unix_time()
Пример #43
0
    def __init__(self, *args, **kwargs):
        self.start_time: float = unix_time()

        self.commands: dict = {

            'help' : Command(self.help),
            'info' : Command(self.info),
            'donate' : Command(self.donate),

            'prefix' : Command(self.change_prefix, False, PermissionLevels.RESTRICTED),
            'blacklist' : Command(self.blacklist, False, PermissionLevels.RESTRICTED),
            'restrict' : Command(self.restrict, False, PermissionLevels.RESTRICTED),

            'timezone' : Command(self.set_timezone),
            'lang' : Command(self.set_language),
            'clock' : Command(self.clock),

            'offset' : Command(self.offset_reminders, True, PermissionLevels.RESTRICTED),
            'nudge' : Command(self.nudge_channel, True, PermissionLevels.RESTRICTED),

            'natural' : Command(self.natural, True, PermissionLevels.MANAGED),
            'remind' : Command(self.remind, True, PermissionLevels.MANAGED),
            'interval' : Command(self.remind, True, PermissionLevels.MANAGED),
            'timer' : Command(self.timer, True, PermissionLevels.MANAGED),
            'del' : Command(self.delete, True),
            'look' : Command(self.look, True),
            'clear' : Command(self.clear, True),

            'todo' : Command(self.todo),
            'todos' : Command(self.todo, False, PermissionLevels.MANAGED),

            'ping' : Command(self.time_stats),

        }

        self.config: Config = Config()

        self.executor: concurrent.futures.ThreadPoolExecutor = concurrent.futures.ThreadPoolExecutor()
        self.csession: aiohttp.ClientSession = None

        super(BotClient, self).__init__(*args, **kwargs)
Пример #44
0
Файл: irc.py Проект: gipi/Richie
    def __init__(self, config=None, dir=None):
        Madcow.__init__(self, config=config, dir=dir)

        self.colorlib = ColorLib('mirc')
        if log.root.level <= log.DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            log.info('[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(
                event,
                getattr(self, 'on_' + event),
                0,
            )
        if self.config.irc.channels is not None:
            self.channels = self._delim.split(self.config.irc.channels)
        else:
            self.channels = []
        self.names = {}
        self.last_names_update = unix_time()
Пример #45
0
Файл: irc.py Проект: gipi/Richie
    def __init__(self, config=None, dir=None):
        Madcow.__init__(self, config=config, dir=dir)

        self.colorlib = ColorLib('mirc')
        if log.root.level <= log.DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            log.info('[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(
                event,
                getattr(self, 'on_' + event),
                0,
            )
        if self.config.irc.channels is not None:
            self.channels = self._delim.split(self.config.irc.channels)
        else:
            self.channels = []
        self.names = {}
        self.last_names_update = unix_time()
Пример #46
0
    async def create_reminder(self, message: discord.Message, location: int, text: str, time: int,
                              interval: typing.Optional[int] = None, method: str = 'natural') -> ReminderInformation:
        ut: float = unix_time()

        if time > ut + MAX_TIME:
            return ReminderInformation(CreateReminderResponse.LONG_TIME)

        elif time < ut:

            if (ut - time) < 10:
                time = int(ut)

            else:
                return ReminderInformation(CreateReminderResponse.PAST_TIME)

        channel: typing.Optional[Channel] = None
        user: typing.Optional[User] = None

        creator: User = User.from_discord(message.author)

        # noinspection PyUnusedLocal
        discord_channel: typing.Optional[typing.Union[discord.TextChannel, DMChannelId]] = None

        # command fired inside a guild
        if message.guild is not None:
            discord_channel = message.guild.get_channel(location)

            if discord_channel is not None:  # if not a DM reminder

                channel, _ = Channel.get_or_create(discord_channel)

                await channel.attach_webhook(discord_channel)

                time += channel.nudge

            else:
                user = await self.find_and_create_member(location, message.guild)

                if user is None:
                    return ReminderInformation(CreateReminderResponse.INVALID_TAG)

                discord_channel = DMChannelId(user.dm_channel, user.user)

        # command fired in a DM; only possible target is the DM itself
        else:
            user = User.from_discord(message.author)
            discord_channel = DMChannelId(user.dm_channel, message.author.id)

        if interval is not None:
            if MIN_INTERVAL > interval:
                return ReminderInformation(CreateReminderResponse.SHORT_INTERVAL)

            elif interval > MAX_TIME:
                return ReminderInformation(CreateReminderResponse.LONG_INTERVAL)

            else:
                # noinspection PyArgumentList
                reminder = Reminder(
                    message=Message(content=text),
                    channel=channel or user.channel,
                    time=time,
                    enabled=True,
                    method=method,
                    interval=interval,
                    set_by=creator.id)
                session.add(reminder)
                session.commit()

        else:
            # noinspection PyArgumentList
            reminder = Reminder(
                message=Message(content=text),
                channel=channel or user.channel,
                time=time,
                enabled=True,
                method=method,
                set_by=creator.id)
            session.add(reminder)
            session.commit()

        return ReminderInformation(CreateReminderResponse.OK, channel=discord_channel, time=time)
Пример #47
0
    async def natural(self, message, stripped, server):

        if len(stripped.split(server.language.get_string('natural/send'))) < 2:
            await message.channel.send(embed=discord.Embed(
                description=server.language.get_string('natural/no_argument').format(prefix=server.prefix)))
            return

        location_ids: typing.List[int] = [message.channel.id]

        time_crop = stripped.split(server.language.get_string('natural/send'))[0]
        message_crop = stripped.split(server.language.get_string('natural/send'), 1)[1]
        datetime_obj = await self.do_blocking(partial(dateparser.parse, time_crop, settings={
            'TIMEZONE': server.timezone,
            'TO_TIMEZONE': self.config.local_timezone,
            'RELATIVE_BASE': datetime.now(pytz.timezone(server.timezone)).replace(tzinfo=None),
            'PREFER_DATES_FROM': 'future'
        }))

        if datetime_obj is None:
            await message.channel.send(
                embed=discord.Embed(description=server.language.get_string('natural/invalid_time')))
            return

        if message.guild is not None:
            chan_split = message_crop.split(server.language.get_string('natural/to'))
            if len(chan_split) > 1 and all(bool(set(x) & set('0123456789')) for x in chan_split[-1].split(' ')):
                location_ids = [int(''.join([x for x in z if x in '0123456789'])) for z in chan_split[-1].split(' ')]

                message_crop: str = message_crop.rsplit(server.language.get_string('natural/to'), 1)[0]

        interval_split = message_crop.split(server.language.get_string('natural/every'))
        recurring: bool = False
        interval: int = 0

        if len(interval_split) > 1:
            interval_dt = await self.do_blocking(partial(dateparser.parse, '1 ' + interval_split[-1]))

            if interval_dt is None:
                pass

            elif await self.is_patron(message.author.id):
                recurring = True

                interval = abs((interval_dt - datetime.now()).total_seconds())

                message_crop = message_crop.rsplit(server.language.get_string('natural/every'), 1)[0]

            else:
                await message.channel.send(embed=discord.Embed(
                    description=server.language.get_string('interval/donor').format(prefix=server.prefix)))
                return

        mtime: int = int(datetime_obj.timestamp())
        responses: typing.List[ReminderInformation] = []

        for location_id in location_ids:
            response: ReminderInformation = await self.create_reminder(message, location_id, message_crop, mtime,
                                                                       interval=interval if recurring else None,
                                                                       method='natural')
            responses.append(response)

        if len(responses) == 1:
            result: ReminderInformation = responses[0]
            string: str = NATURAL_STRINGS.get(result.status, REMIND_STRINGS[result.status])

            response = server.language.get_string(string).format(location=result.location.mention,
                                                                 offset=timedelta(
                                                                     seconds=int(result.time - unix_time())),
                                                                 min_interval=MIN_INTERVAL, max_time=MAX_TIME_DAYS)

            await message.channel.send(embed=discord.Embed(description=response))

        else:
            successes: int = len([r for r in responses if r.status == CreateReminderResponse.OK])

            await message.channel.send(
                embed=discord.Embed(description=server.language.get_string('natural/bulk_set').format(successes)))
Пример #48
0
 def _reset(self):
     self.state['count'] = 0
     self.state['first_event'] = unix_time()
Пример #49
0
 def __init__(self, user, flags):
     self.user = user
     self.flags = flags
     self.loggedIn = int(unix_time())
Пример #50
0
 def _privmsg(self, sendto, line):
     delta = unix_time() - self.last_response
     if delta < self.delay:
         sleep(self.delay - delta)
     self.server.privmsg(sendto.encode(self.charset), line)
     self.last_response = unix_time()
Пример #51
0
                log.error(u'Error in IRC loop')
                log.exception(error)

    def on_pong(self, server, event):
        # this should never happen, but don't take any chances
        if not self.keepalive:
            return

        pong = event.arguments()[0]
        try:
            pong = float(pong)
        except Exception, error:
            log.error('unexpected PONG reply: %s' % pong)
            log.exception(error)
            return
        now = unix_time()
        log.debug('PONG: latency = %s' % (now - pong))
        self.last_pong = now

    def botname(self):
        return self.server.get_nickname()

    def on_welcome(self, server, event):
        """welcome event triggers startup sequence"""
        log.info(u'[IRC] * Connected')

        # clear any connected channel listing
        self.joined_channels = []

        # identify with nickserv
        if self.config.irc.nickServUser and self.config.irc.nickServPass: