Example #1
0
async def commission_configure(bot, context):
    """Configures the channel and cooldown for the commission channel rules."""
    rules = data.get(bot,
                     __name__,
                     'rules',
                     guild_id=context.guild.id,
                     default={})
    default_cooldown = configurations.get(bot, __name__, 'default_cooldown')
    replace_channel = context.options.get('channel', rules.get('channel'))
    replace_cooldown = context.options.get(
        'cooldown', rules.get('cooldown', default_cooldown))
    if not replace_channel:
        raise CBException("No commission channel configured.")

    # Reset advertisement data
    rules = {'channel': replace_channel, 'cooldown': replace_cooldown}
    data.add(bot, __name__, 'rules', rules, guild_id=context.guild.id)
    data.remove(bot,
                __name__,
                'advertisements',
                guild_id=context.guild.id,
                volatile=True,
                safe=True)
    await _get_advertisement_data(bot, context.guild)

    description = 'Channel: {0.mention}\nCooldown: {1}'.format(
        data.get_channel(bot, replace_channel),
        utilities.get_time_string(replace_cooldown, text=True, full=True))
    embed = discord.Embed(title='Commission channel configuration:',
                          description=description)
    return Response(embed=embed)
Example #2
0
def _embed_games_information(bot, games, guild_id):
    """Formats the given games into an embedded format."""
    result = []
    current_time = datetime.datetime.utcnow()
    for game in games:
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])
        setup_time = start_time + setup_delta

        extra = ''
        if current_time < start_time:  # Upcoming
            title = "Upcoming: "
            seconds = (start_time - current_time).total_seconds()
            if seconds > 60:
                begins_in = utilities.get_time_string(seconds,
                                                      text=True,
                                                      full=False)
            else:
                begins_in = 'a few moments!'
            offset, adjusted_time = utilities.get_timezone_offset(
                bot, guild_id, utc_dt=start_time, as_string=True)
            scheduled = '{} [{}]'.format(adjusted_time.strftime('%a %I:%M %p'),
                                         offset)
            extra = '\n\tStarts {} ({})'.format(scheduled, begins_in)

        elif current_time <= setup_time:  # In setup
            title = "Setting up: "

        elif current_time < end_time:  # Current
            title = "Current: "
            current_seconds = (current_time - start_time -
                               setup_delta).total_seconds()
            extra = '\n\tCurrently at {}'.format(
                utilities.get_time_string(current_seconds))

        else:  # Finished
            title = "Finished: "

        title += '{}{}'.format(
            game['game'], ' ({})'.format(game['type']) if game['type'] else '')
        value = '\u200b\tRun by {} in {}'.format(game['runners'],
                                                 game['estimation']) + extra
        result.append((title, value))

    return result
Example #3
0
def _toggle_notification(bot, game, context, use_channel=False):
    """Adds the user or channel to the notifications list."""
    if use_channel:
        destination = 'c{}'.format(context.channel.id)
        destination_text = "This channel"
    else:
        destination = 'u{}'.format(context.author.id)
        destination_text = "You"
    key = game['key']
    game_text = '{} ({})'.format(game['game'], game['type'])
    pending_notification = utilities.get_schedule_entries(
        bot, __name__, search=key, destination=destination)
    if pending_notification:  # Remove from schedule
        utilities.remove_schedule_entries(bot,
                                          __name__,
                                          search=key,
                                          destination=destination)
        return "{} will no longer be notified when {} is about to be streamed.".format(
            destination_text, game_text)
    else:  # Add to schedule
        stream_url = configurations.get(bot, __name__, 'stream_url')
        current_time = datetime.datetime.utcnow()
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])

        if current_time < start_time:
            scheduled_seconds = start_time.replace(
                tzinfo=datetime.timezone.utc).timestamp()
            delta = utilities.get_time_string(scheduled_seconds - time.time(),
                                              text=True)
            info = 'GDQ game notification: {}'.format(game_text)
            payload = {
                'text': game_text,
                'end': scheduled_seconds + game['seconds']
            }
            utilities.schedule(bot,
                               __name__,
                               scheduled_seconds,
                               _notify,
                               payload=payload,
                               search=key,
                               destination=destination,
                               info=info)
            return ("{} will be notified when {} is about to be streamed!\n"
                    "(In approximately {})".format(destination_text, game_text,
                                                   delta))

        elif current_time < start_time + setup_delta:
            return "The game is scheduled to start soon!\nWatch it at {}".format(
                stream_url)
        elif current_time < end_time:
            return "The game has already started!\nWatch it at {}".format(
                stream_url)
        else:
            return "Sorry, this game has already been finished."
Example #4
0
def _embed_games_information(bot, games, guild_id):
    """Formats the given games into an embedded format."""
    result = []
    current_time = datetime.datetime.utcnow()
    for game in games:
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])
        setup_time = start_time + setup_delta

        extra = ''
        if current_time < start_time:  # Upcoming
            title = "Upcoming: "
            seconds = (start_time - current_time).total_seconds()
            if seconds > 60:
                begins_in = utilities.get_time_string(seconds, text=True, full=False)
            else:
                begins_in = 'a few moments!'
            offset, adjusted_time = utilities.get_timezone_offset(
                bot, guild_id, utc_dt=start_time, as_string=True)
            scheduled = '{} [{}]'.format(adjusted_time.strftime('%a %I:%M %p'), offset)
            extra = '\n\tStarts {} ({})'.format(scheduled, begins_in)

        elif current_time <= setup_time:  # In setup
            title = "Setting up: "

        elif current_time < end_time:  # Current
            title = "Current: "
            current_seconds = (current_time - start_time - setup_delta).total_seconds()
            extra = '\n\tCurrently at {}'.format(utilities.get_time_string(current_seconds))

        else:  # Finished
            title = "Finished: "

        title += '{}{}'.format(game['game'], ' ({})'.format(game['type']) if game['type'] else '')
        value = '\u200b\tRun by {} in {}'.format(game['runners'], game['estimation']) + extra
        result.append((title, value))

    return result
Example #5
0
def _toggle_notification(bot, game, context, use_channel=False):
    """Adds the user or channel to the notifications list."""
    if use_channel:
        destination = 'c{}'.format(context.channel.id)
        destination_text = "This channel"
    else:
        destination = 'u{}'.format(context.author.id)
        destination_text = "You"
    key = game['key']
    game_text = '{} ({})'.format(game['game'], game['type'])
    pending_notification = utilities.get_schedule_entries(
        bot, __name__, search=key, destination=destination)
    if pending_notification:  # Remove from schedule
        utilities.remove_schedule_entries(bot, __name__, search=key, destination=destination)
        return "{} will no longer be notified when {} is about to be streamed.".format(
            destination_text, game_text)
    else:  # Add to schedule
        stream_url = configurations.get(bot, __name__, 'stream_url')
        current_time = datetime.datetime.utcnow()
        start_time, end_time = game['scheduled'], game['end']
        setup_delta = datetime.timedelta(seconds=game['setup_seconds'])

        if current_time < start_time:
            scheduled_seconds = start_time.replace(tzinfo=datetime.timezone.utc).timestamp()
            delta = utilities.get_time_string(scheduled_seconds - time.time(), text=True)
            info = 'GDQ game notification: {}'.format(game_text)
            payload = {
                'text': game_text,
                'end': scheduled_seconds + game['seconds']}
            utilities.schedule(
                bot, __name__, scheduled_seconds, _notify, payload=payload,
                search=key, destination=destination, info=info)
            return (
                "{} will be notified when {} is about to be streamed!\n"
                "(In approximately {})".format(destination_text, game_text, delta))

        elif current_time < start_time + setup_delta:
            return "The game is scheduled to start soon!\nWatch it at {}".format(stream_url)
        elif current_time < end_time:
            return "The game has already started!\nWatch it at {}".format(stream_url)
        else:
            return "Sorry, this game has already been finished."
Example #6
0
async def check_commission_advertisement(bot, message):
    """Checks new messages in the commissions channel."""
    if isinstance(message.channel, discord.abc.PrivateChannel):
        return
    guild_data = data.get(bot,
                          __name__,
                          None,
                          guild_id=message.guild.id,
                          default={})
    if (not guild_data.get('rules')
            or message.channel.id != guild_data['rules']['channel']
            or message.author.id in guild_data.get('whitelist', [])
            or message.author.bot):
        return

    cooldown = guild_data['rules']['cooldown']
    advertisement_data = await _get_advertisement_data(
        bot, message.guild, ignore_user_id=message.author.id)
    deleted_persistence = data.get(bot,
                                   __name__,
                                   'recently_deleted',
                                   guild_id=message.guild.id,
                                   default={})
    time_delta = cooldown  # Assume cooldown has been passed
    author_id = message.author.id

    # Check the last advertisement's creation time (if it exists)
    if str(author_id) in deleted_persistence:
        time_delta = time.time() - deleted_persistence[str(author_id)]
    if author_id in advertisement_data:
        last_message = advertisement_data[author_id]
        time_delta = time.time() - last_message.created_at.replace(
            tzinfo=tz.utc).timestamp()

    # Not enough time has passed
    if time_delta < cooldown:
        # content_backup = message.content  # TODO: Consider sending the user a content backup?
        await message.delete()
        wait_for = utilities.get_time_string(cooldown - time_delta,
                                             text=True,
                                             full=True)
        warning = ('You cannot send another advertisement at this time. '
                   'You must wait {}.').format(wait_for)
        await message.author.send(embed=discord.Embed(
            colour=discord.Colour(0xffcc4d), description=warning))
        return

    # Enough time has passed - delete the last message
    elif author_id in advertisement_data:
        try:
            await advertisement_data[author_id].delete()
        except:  # User deleted their advertisement already
            logger.warn("Failed to delete the last advertisement.")

    # Schedule a notification for when a new advertisement post is eligible
    utilities.schedule(bot,
                       __name__,
                       time.time() + cooldown,
                       _notify_advertisement_available,
                       search='c_ad_{}'.format(message.guild.id),
                       destination='u{}'.format(author_id),
                       info='Commission advertisement post eligibility.')

    advertisement_data[author_id] = message
    notification = (
        'Hello! Your advertisement post in the commissions channel has been recorded. '
        '**Please remember that there can only be one message per advertisement**.\n\n'
        'If you want to revise your advertisement [(like adding an image)]'
        '(https://imgur.com/a/qXB2v "Click here for a guide on how to add an image '
        'with a message"), you can delete your advertisement and submit it again, '
        'although this only works within the next 10 minutes and if nobody else has '
        'posted another advertisement after yours.\n\nYou are eligible to post a '
        'new advertisement after the waiting period of {}. When you post a new '
        'advertisement, your previous one will be automatically deleted.\n\n'
        'For convenience, you will be notified when you are eligible to make '
        'a new post.').format(
            utilities.get_time_string(cooldown, text=True, full=True))
    await message.author.send(embed=discord.Embed(
        colour=discord.Colour(0x77b255), description=notification))