Exemplo n.º 1
0
    async def fake_artist(self, ctx, number: int):
        conf = self.conf.get('fake_artist', {})
        themes = conf.get('themes', [])
        themes = random.sample(themes, len(themes) - len(themes) % number)
        output = [[] for i in range(number)]
        fakes = list(range(number)) * (len(themes) // number)
        random.shuffle(fakes)
        say = 'here are the links:'

        # generate
        for theme, fake in zip(themes, fakes):
            for i in range(len(output)):
                output[i].append(theme if i != fake else 'YOU ARE THE FAKE')

        # generate master file
        with open(os.path.join(conf.get('path', ''), 'master.html'), 'w') as f:
            f.write(conf.get('rules'))
            for i, theme in enumerate(themes):
                f.write(f'''<li><input class="spoilerbutton" type="button"'''+ \
                        f'''value="show" onclick="this.value=this.value=='show'''+ \
                        f'''\'?'{html.escape(theme)}':'show';"></li>''')
            f.write(conf.get('out'))

        # generate player files
        for i in range(len(output)):
            filename = os.path.join(conf.get('path', ''), f'{i+1}.html')
            with open(filename, 'w') as f:
                f.write(conf.get('rules'))
                for theme in output[i]:
                    f.write(f'<li>{html.escape(theme)}</li>')
                f.write(conf.get('out'))
            say += f'\nhttps://andy29485.tk/files/{i+1}.html'

        await self.bot.say(formatter.ok(say))
Exemplo n.º 2
0
  async def _add_reminder(self, ctx, *, message : str):
    """
    adds a reminder

    'at' must be used when specifing exact time
    'in' is optional for offsets
    'me' can be seperate or part of the command name (also optinal)
    cannot mix offsets and exact times

    Samples:
    .remind me in 5 h message
    .remind me in 5 hours 3 m message
    .remind me 1 week message
    .remind me 7 months message
    .remindme in 7 months message
    .remind me at 2017-10-23 message
    .remind me at 2017-10-23T05:11:56 message
    .remindme at 2017-10-23 05:11:56 message
    .remindme at 10/23/2017 5:11 PM message
    .remind at 7:11 message
    .remind at 7:11:15 message
"""
    author  = ctx.message.author.mention
    channel = ctx.message.channel.id
    r = Reminder(channel, author, message)
    r.insertInto(self.conf['reminders'])
    self.conf.save()
    t = datetime.fromtimestamp(r.end_time).isoformat()
    await self.bot.say(formatter.ok('Will remind you at {}'.format(t)))
Exemplo n.º 3
0
    async def add_groupme_link(self, ctx, g_id: str):
        channel = ctx.message.channel
        group, g_bot = self.get_group_bot(g_id)

        if not group:
            await self.bot.say(
                formatter.error("I am not in a group with that id"))
            return

        if g_id not in self.g_groups:
            self.l_bots.append(g_bot)
            self.g_groups[g_id] = group

        if channel.id in self.g_bots:
            self.g_bots[channel.id].append(g_bot)
            self.conf['links'][channel.id].append(g_id)
        else:
            self.g_bots[channel.id] = [g_bot]
            self.conf['links'][channel.id] = [g_id]

        if g_id in self.d_chans:
            self.d_chans[g_id].append(channel)
        else:
            self.d_chans[g_id] = [channel]

        if g_id not in self.g_groups:
            self.conf['g_old'][g_id] = None

        self.conf.save()

        await self.bot.say(formatter.ok())
Exemplo n.º 4
0
 async def unload(self, *, module : str):
   """Unloads a module."""
   try:
     self.bot.unload_extension(module)
   except Exception as e:
     await self.bot.say('\N{PISTOL}')
     await self.bot.say('{}: {}'.format(type(e).__name__, e))
   else:
     await self.bot.say(formatter.ok())
Exemplo n.º 5
0
 async def _td_add(self, ctx, *, task : str):
   '''
   adds a new task to your todo list
   '''
   todos = self.conf['todo'].get(ctx.message.author.id, [])
   todos.append([False, task])
   self.conf['todo'][ctx.message.author.id] = todos
   self.conf.save()
   await self.bot.say(formatter.ok())
Exemplo n.º 6
0
 async def update(self):
   loop = asyncio.get_event_loop()
   g = git.cmd.Git('.')
   await loop.run_in_executor(None,g.execute,['git','reset','HEAD~1','--hard'])
   await loop.run_in_executor(None,g.pull)
   await self.bot.say(formatter.ok('restarting'))
   await self.bot.logout()
   loop.stop()
   #concurrent.futures.ProcessPoolExecutor().shutdown()
   sys.exit()
Exemplo n.º 7
0
 async def begin(self, bot):
   t = datetime.datetime.fromtimestamp(self.end_time).isoformat()
   if not self.reminder_id:
     while True:
       self.reminder_id = int(time.time()*1000000)%1000000
       for rem in self.heap:
         if self is not rem and self == rem:
           break
       else:
         break
   await bot.say(ok(f'Will remind you at {t} (id: {self.reminder_id})'))
Exemplo n.º 8
0
 async def _td_remove(self, ctx, *, index : int):
   '''
   remove a task from your todo list
   Note: indicies start at 1
   '''
   todos = self.conf['todo'].get(ctx.message.author.id, [])
   if len(todos) < index or index <= 0:
     await self.bot.say(formatter.error('Invalid index'))
   else:
     task = todos.pop(index - 1)
     self.conf['todo'][ctx.message.author.id] = todos
     self.conf.save()
     await self.bot.say(formatter.ok('Removed task #{}'.format(index)))
Exemplo n.º 9
0
    async def _uwatch(self, ctx, *, item_ids=''):
        """
    Remove show id from this channel;s follow list

    Usage: .emby unwatch <show id>
    see ".emby watch" for more details
    """
        for item_id in item_ids.split():
            watching = self.conf['watching'].get(item_id)
            if watching and ctx.message.channel.id in watching:
                self.conf['watching'].get(item_id).remove(
                    ctx.message.channel.id)
        await self.bot.say(formatter.ok())
        self.conf.save()
Exemplo n.º 10
0
 async def _td_done(self, ctx, *, index : int):
   '''
   sets/unsets a task as complete
   Note: indicies start at 1
   '''
   todos = self.conf['todo'].get(ctx.message.author.id, [])
   if len(todos) < index or index <= 0:
     await self.bot.say(formatter.error('Invalid index'))
   else:
     index -= 1
     todos[index][0] = not todos[index][0]
     self.conf['todo'][ctx.message.author.id] = todos
     self.conf.save()
     await self.bot.say(formatter.ok())
Exemplo n.º 11
0
    async def _rm(self, ctx, index: int):
        """remove an existing replacement by index"""

        if index >= len(self.quotes_dict['quotes']):
            await self.bot.say(
                formatter.error('Quote {} does not exist'.format(index)))
            return

        if ctx.message.author.id != self.quotes_dict['quotes'][index]['id'] \
           and not perms.check_permissions(ctx.message, manage_messages=True):
            raise commands.errors.CheckFailure('Cannot delete')

        self.quotes_dict['quotes'].pop(index)
        self.quotes_dict.save()

        await self.bot.say(formatter.ok())
Exemplo n.º 12
0
    async def _add(self, ctx, *, regex):
        """adds a new replacement
    Format `s/old/new/`
    """

        if ctx.message.author.id in self.permissions['rep-blacklist']:
            await self.bot.say(formatter.error('No ') + ':poi:')
            return

        #Find requested replacement
        rep = get_match(regex)

        #ensure that replace was found before proceeding
        if not rep:
            await self.bot.say(formatter.error('Could not find valid regex'))
            return

        p1 = formatter.escape_mentions(rep.group(2))
        p2 = formatter.escape_mentions(rep.group(4))

        #check regex for validity
        if not comp(p1, p2):
            await self.bot.say(formatter.error('regex is invalid'))
            return

        #make sure that there are no similar regexes in db
        for i in self.replacements:
            if similar(p1, i):
                r = '\"{}\" -> \"{}\"'.format(i, self.replacements[i][0])
                message = 'Similar regex already exists, delete or edit it\n{}'.format(
                    formatter.inline(r))
                await self.bot.say(formatter.error(message))
                return

        #make sure regex is not too broad
        if bad_re(p1):
            await self.bot.say(formatter.error('regex is too broad'))
            return

        #check that regex does not already exist
        if p1 in self.replacements:
            await self.bot.say(formatter.error('regex already exists'))
            return

        self.replacements[p1] = [p2, ctx.message.author.id]
        await self.bot.say(formatter.ok())
Exemplo n.º 13
0
    async def _watch(self, ctx, *, item_ids=''):
        """
    Add show id to follow list

    Usage: .emby watch <show id>
    When an episode for that show is added to emby,
    the bot will alert this channel of that
    """
        for item_id in item_ids.split():
            watching = self.conf['watching'].get(item_id)
            if watching and ctx.message.channel.id not in watching:
                self.conf['watching'].get(item_id).append(
                    ctx.message.channel.id)
            elif not watching:
                self.conf['watching'][item_id] = [ctx.message.channel.id]
        await self.bot.say(formatter.ok())
        self.conf.save()
Exemplo n.º 14
0
    async def _add(self, ctx, *, quote):
        """adds a quote"""

        for i in self.quotes_dict['quotes']:
            if quote.lower() == i['quote'].lower():
                await self.bot.say(formatter.error('Quote already exists'))
                return

        index = len(self.quotes_dict['quotes'])
        date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.quotes_dict['quotes'].append({
            'date': date,
            'quote': quote,
            'id': ctx.message.author.id
        })
        self.quotes_dict.save()

        await self.bot.say(formatter.ok('quote added, index {}'.format(index)))
Exemplo n.º 15
0
  async def _osu_delink(self, ctx):
    """
    Unlinks a channel from watching an osu account
    """
    auth = ctx.message.author.id
    chan = ctx.message.channel.id

    if auth not in self.conf['watched-users']:
      await self.bot.say("You arn't linked to an OSU account yet")
      return

    if chan not in self.conf['watched-users'][auth]['chans']:
      await self.bot.say('This channel is not linked to your account')
      return

    self.conf['watched-users'][auth]['chans'].remove(chan)
    self.conf.save()

    await self.bot.say(formatter.ok("Channel is now unlinked"))
Exemplo n.º 16
0
  async def _osu_link(self, ctx, osu_username = '', top_scores : int = 50):
    """
    Links a discord user account to an osu account
    osu_username - the username that you go by on https://osu.ppy.sh
    top_scores   - the top scores to report from latest [0, 100]
    """
    auth = ctx.message.author.id
    chan = ctx.message.channel.id

    user = self.conf['watched-users'].get(auth, {}).get('uid', None)
    user = await self.api.get_user(osu_username or user)
    if not user:
      await self.bot.say('could not find user')
      return

    top_scores = max(0, min(100, top_scores))
    name       = user[0].username
    user       = user[0].user_id
    if top_scores:
      best     = await self.api.get_user_best(user, limit=top_scores)
      best     = [(i.beatmap_id, i.score) for i in best]
    else:
      best = []

    if auth in self.conf['watched-users']:
      self.conf['watched-users'][auth]['uid'] = user
      if chan not in self.conf['watched-users'][auth]['chans']:
        self.conf['watched-users'][auth]['chans'].append(chan)
      self.conf['watched-users'][auth]['last'] = best

    else:
      self.conf['watched-users'][auth] = {
              'uid':   user,
              'num':   top_scores,
              'chans': [chan],
              'last':  best
      }
    self.conf.save()
    await self.bot.say(
        formatter.ok(f'you are now linked to: {name}')
    )
Exemplo n.º 17
0
    async def _edit(self, ctx, *, regex):
        """edits an existing replacement
    Format `s/old/new/`
    """

        #Find requested replacement
        rep = get_match(regex)

        #ensure that replace was found before proceeding
        if not rep:
            await self.bot.say(formatter.error('Could not find valid regex'))
            return

        p1 = formatter.escape_mentions(rep.group(2))
        p2 = formatter.escape_mentions(rep.group(4))

        #check regex for validity
        if not comp(p1, p2):
            await self.bot.say(formatter.error('regex is invalid'))
            return

        #make sure regex is not too broad
        if bad_re(p1):
            await self.bot.say(formatter.error('regex is too broad'))
            return

        #ensure that replace was found before proceeding
        if p1 not in self.replacements:
            await self.bot.say(formatter.error('Regex not in replacements.'))
            return

        #check if they have correct permissions
        if ctx.message.author.id != self.replacements[p1][1] \
           and not perms.is_owner_check(ctx.message):
            #will uncomment next line when reps are a per server thing
            #and not perms.check_permissions(ctx.message, manage_messages=True):
            raise commands.errors.CheckFailure('Cannot edit')

        self.replacements[p1] = [p2, ctx.message.author.id]
        await self.bot.say(formatter.ok())
Exemplo n.º 18
0
    async def _rm(self, ctx, *, pattern):
        """remove an existing replacement"""

        #pattern = re.sub('^(`)?\\(\\?[^\\)]*\\)', '\\1', pattern)
        pattern = formatter.escape_mentions(pattern)

        #ensure that replace was found before proceeding
        if pattern not in self.replacements:
            if re.search('^`.*`$',
                         pattern) and pattern[1:-1] in self.replacements:
                pattern = pattern[1:-1]
            else:
                await self.bot.say(
                    formatter.error('Regex not in replacements.'))
                return

        #check if they have correct permissions
        if ctx.message.author.id != self.replacements[pattern][1] \
           and not perms.is_owner_check(ctx.message):
            raise commands.errors.CheckFailure('Cannot delete')

        self.replacements.pop(pattern)
        self.replacements.save()
        await self.bot.say(formatter.ok())
Exemplo n.º 19
0
 async def fake_artist_add(self, ctx, *, themes):
     self.conf['fake_artist']['themes'].extend(themes.strip().split('\n'))
     self.conf.save()
     await self.bot.say(formatter.ok())
Exemplo n.º 20
0
 async def debug_off(self):
   logging.getLogger('navi').setLevel(logging.INFO)
   await self.bot.say(formatter.ok())