Example #1
0
async def donations(ctx, action=''):

    desc = ''
    server = servers[ctx.guild.id]

    if action:

        if action == 'reset':

            if has_permission(ctx.author, ctx.guild, 2):

                desc = server.reset_donations()

            else:

                desc = ':x: Du hast keine Rechte und darfst deswegen diese Aktion nicht ausführen! \nPech gehabt... :cry:'

    else:

        desc = server.get_donations()

    emb = discord.Embed(title='Donations',
                        description=desc,
                        colour=random.randint(0, 16777215))
    await ctx.send(embed=emb)
Example #2
0
async def update_role(
        id: int,
        body: UpdateRoleBody,
        roles=has_permissions([ManageRoles()]),
):
    role = await Role.fetch(id)
    if not role:
        raise HTTPException(404, "Role Not Found")

    # Check if the user has administrator permission or all the permissions provided in the role
    user_permissions = 0
    for r in roles:
        user_permissions |= r.permissions

    top_role = min(roles, key=lambda role: role.position)
    if top_role.position >= role.position:
        raise HTTPException(403, "Missing Permissions")

    data = body.dict(exclude_unset=True)
    if not utils.has_permission(user_permissions, body.permissions):
        raise HTTPException(403, "Missing Permissions")

    if name := data.get("name", None):
        record = await Role.pool.fetchrow(
            "SELECT * FROM roles WHERE name = $1", name)

        if record:
            raise HTTPException(409, "Role with that name already exists")
Example #3
0
async def shutdown(ctx):

    if has_permission(ctx.author, ctx.guild, 3):

        await bot_shutdown(ctx)

    else:

        await ctx.send('Du hast nicht die Berechtigungen für diesen Befehl!',
                       delete_after=10)
Example #4
0
async def settings(ctx, setting='', mode=''):

    if has_permission(ctx.author, ctx.guild, 2):
        desc = servers[ctx.guild.id]._settings(setting, mode)
    else:
        desc = 'Zugriff verweigert'

    emb = discord.Embed(title='Settings :memo:',
                        description=desc,
                        colour=random.randint(0, 16777215))
    await ctx.send(embed=emb)
Example #5
0
async def reload(ctx):

    if has_permission(ctx.author, ctx.guild, 3):

        global reboot
        await ctx.channel.send('Bot wird neu gestartet...')
        reboot = True
        await bot_shutdown(ctx)

    else:

        await ctx.send('Du hast nicht die Berechtigungen für diesen Befehl!',
                       delete_after=10)
Example #6
0
def meteors_nights(request):
    nights = MeteorsNightsView.objects.order_by('-night')
    aggregates = MeteorsView.objects.filter(night__gt='2014_01_01').aggregate(
        Count('id'), Min('night'), Max('night'))
    aggregates_favor = MeteorsView.objects.filter(
        night__lt='2014_01_01').aggregate(Count('id'), Min('night'),
                                          Max('night'))

    if not has_permission(request, 'fweb.access_realtime'):
        nights = nights.filter(night__in=MeteorsNightsProcessed.objects.all())

    context = {
        'nights': nights,
        'aggregates': aggregates,
        'aggregates_favor': aggregates_favor
    }

    return TemplateResponse(request, 'meteors_nights.html', context=context)
Example #7
0
async def on_message(ctx):

    if not ctx.author.bot:

        await servers[ctx.guild.id].process_msg(ctx)

        if ctx.channel.category.name == 'ehrenbot':

            if ctx.channel.name == 'ehrenwerte-tabelle':

                await ctx.delete()
            else:

                msg = await client.get_context(ctx)
                if msg.valid:
                    if devmode and str(ctx.author) != admin:
                        await ctx.channel.send(embed=discord.Embed(
                            title=':warning: Devmode aktiv :warning:',
                            description=
                            'Der Bot befindet sich grade im Testmodus, Bugfixes oder neue Features werden getestet weshalb vorrübergehend keine Kommands zur Verfügung stehen!',
                            colour=random.randint(0, 16777215)))
                    else:
                        await client.process_commands(ctx)

                elif has_permission(ctx.author, ctx.guild,
                                    3) and ctx.content.startswith(
                                        '//') or ctx.content.startswith('dev'):

                    aliases = {
                        'reboot': 'reload',
                        'shut': 'shutdown',
                        'devmode': 'testmode',
                        'system': 'sysstats',
                        'systemstats': 'sysstats',
                        'usage': 'sysstats'
                    }

                    func = ctx.content.replace('//', '')
                    if func in aliases:
                        func = aliases[func]
                    func += '(ctx)'
                    await eval(func)
Example #8
0
async def create_role(body: NewRoleBody,
                      roles=has_permissions([ManageRoles()])):
    # Check if the user has administrator permission or all the permissions provided in the role
    user_permissions = 0
    for role in roles:
        user_permissions |= role.permissions

    if not utils.has_permission(user_permissions, body.permissions):
        raise HTTPException(403, "Missing Permissions")

    query = """
        INSERT INTO roles (id, name, color, permissions, position)
            VALUES (create_snowflake(), $1, $2, $3, (SELECT COUNT(*) FROM roles) + 1)
            RETURNING *;
    """

    try:
        record = await Role.pool.fetchrow(query, body.name, body.color,
                                          body.permissions)
    except asyncpg.exceptions.UniqueViolationError:
        raise HTTPException(409, "Role with that name already exists")

    return utils.JSONResponse(status_code=201, content=dict(record))
Example #9
0
async def profile(ctx, member: discord.Member = None):

    desc = ''
    profile_pic = None
    member = ctx.author if not member else member

    if member == ctx.author or has_permission(ctx.author, ctx.guild, 2):

        if not member.bot:
            desc = servers[ctx.guild.id].get_profile(member.id)
            profile_pic = member.avatar_url

        else:
            desc = 'Bots haben keine Accounts!'

    else:
        desc = 'Zugriff verweigert'

    emb = discord.Embed(title='Member profile',
                        description=desc,
                        colour=random.randint(0, 16777215))
    emb.set_thumbnail(url=profile_pic)
    await ctx.send(embed=emb)
Example #10
0
def satellite_download(request,
                       id=0,
                       track_id=0,
                       param=None,
                       show_records=False):
    response = HttpResponse(request, content_type='text/plain')

    if track_id:
        try:
            track = SatelliteTracks.objects.get(id=track_id)
        except:
            raise Http404('No such track')

        satellite = track.satellite
        #records = SatelliteRecordsSimple.objects.filter(track_id=track_id).order_by('time')
        records = track.satelliterecords_set.order_by('time')

        response[
            'Content-Disposition'] = 'attachment; filename=track_%s.txt' % track_id

        print >> response, "# satellite: %d %s / %s" % (
            satellite.catalogue_id, satellite.name, satellite.country)
        print >> response, "# catalogue:", satellite.catalogue, satellite_catalogue(
            satellite.catalogue)
        print >> response, "# track:", track.id
        print >> response, "# variability:", track.variability, {
            0: 'Not variable',
            1: 'Aperiodic',
            2: 'Periodic'
        }.get(track.variability)
        print >> response, "# variability_period:", track.variability_period
        print >> response, "# npoints:", len(records)

        print >> response, "#"

        print >> response, "# Date Time StdMag Mag Filter Penumbra Distance Phase Channel"

        for record in records:
            print >> response, record.time, record.stdmag, record.mag, filter_name(
                record.filter_id
            ), record.penumbra, record.distance, record.phase, record.channel_id

    elif id and param is not None:
        try:
            satellite = Satellites.objects.get(id=id)
        except:
            raise Http404('No such satellite')

        tracks = satellite.satellitetracks_set.order_by('id')

        response[
            'Content-Disposition'] = 'attachment; filename=satellite_%s_%s.txt' % (
                param, id)

        print >> response, "# satellite: %d %s / %s" % (
            satellite.catalogue_id, satellite.name, satellite.country)
        print >> response, "# catalogue:", satellite.catalogue, satellite_catalogue(
            satellite.catalogue)
        print >> response, "# variability:", satellite.variability, {
            0: 'Not variable',
            1: 'Aperiodic',
            2: 'Periodic'
        }.get(satellite.variability)
        print >> response, "# variability_period:", satellite.variability_period
        print >> response, "# ntracks:", len(tracks)

        print >> response, "#"

        print >> response, "# Date Time Track MJD %s" % param.capitalize()

        for track in tracks:
            if param == 'period':
                if track.variability == 2:
                    time = track.satelliterecords_set.order_by(
                        'time').first().time
                    mjd = astropy.time.Time(time).mjd
                    print >> response, time, track.id, mjd, track.variability_period

    elif id == 'all':
        # records = SatelliteRecords.objects.order_by('track').order_by('time')

        # if not has_permission(request, 'fweb.access_satellites_all'):
        #     records = records.exclude(satellite__catalogue=2)
        #     records = records.exclude(satellite__country='CIS',satellite__country__isnull=False)

        # if request.method == 'GET' and request.GET.get('after'):
        #     records = records.filter(track__gt=request.GET.get('after'))

        # if request.method == 'GET' and request.GET.get('before'):
        #     records = records.filter(track__lt=request.GET.get('before'))

        # print >>response, "# Date Time StdMag Mag Filter Penumbra Distance Phase Channel Track Satellite"

        # for record in records:
        #     print >>response, record.time, record.stdmag, record.mag, filter_name(record.filter_id), record.penumbra, record.distance, record.phase, record.channel_id, record.track_id, record.satellite.catalogue_id

        tracks = SatelliteTracks.objects.order_by('id')
        if not has_permission(request, 'fweb.access_satellites_all'):
            tracks = tracks.exclude(satellite__catalogue=2)
            tracks = tracks.exclude(satellite__country='CIS',
                                    satellite__country__isnull=False)

        if request.method == 'GET' and request.GET.get('after'):
            tracks = tracks.filter(id__gt=request.GET.get('after'))

        if request.method == 'GET' and request.GET.get('before'):
            tracks = tracks.filter(id__lt=request.GET.get('before'))

        response[
            'Content-Disposition'] = 'attachment; filename=satellites_all.txt'

        print >> response, "# Date Time StdMag Mag Filter Penumbra Distance Phase Channel Track Satellite"

        for i, track in enumerate(tracks):
            #print i,'/',len(tracks)

            #records = SatelliteRecords.get(track__id=track).order_by('track').order_by('time')
            records = track.satelliterecords_set.order_by('time')

            for record in records:
                print >> response, record.time, record.stdmag, record.mag, filter_name(
                    record.filter_id
                ), record.penumbra, record.distance, record.phase, record.channel_id, record.track_id, track.satellite.catalogue_id

    elif id:
        try:
            satellite = Satellites.objects.get(id=id)
        except:
            raise Http404('No such satellite')

        records = satellite.satelliterecords_set.order_by('time')

        if satellite.catalogue == 2 or satellite.country == 'CIS':
            assert_permission(request, 'fweb.access_satellites_all')

        if request.method == 'GET' and request.GET.get('after'):
            records = records.filter(track__gt=request.GET.get('after'))

        if request.method == 'GET' and request.GET.get('before'):
            records = records.filter(track__lt=request.GET.get('before'))

        response[
            'Content-Disposition'] = 'attachment; filename=satellite_%s.txt' % id

        print >> response, "# satellite: %d %s / %s" % (
            satellite.catalogue_id, satellite.name, satellite.country)
        print >> response, "# catalogue:", satellite.catalogue, satellite_catalogue(
            satellite.catalogue)
        print >> response, "# variability:", satellite.variability, {
            0: 'Not variable',
            1: 'Aperiodic',
            2: 'Periodic'
        }.get(satellite.variability)
        print >> response, "# variability_period:", satellite.variability_period
        print >> response, "# npoints:", len(records)

        print >> response, "#"

        print >> response, "# Date Time StdMag Mag Filter Penumbra Distance Phase Channel Track"

        for record in records:
            print >> response, record.time, record.stdmag, record.mag, filter_name(
                record.filter_id
            ), record.penumbra, record.distance, record.phase, record.channel_id, record.track_id

    else:
        satellites = SatellitesView.objects.order_by('catalogue_id')

        if not has_permission(request, 'fweb.access_satellites_all'):
            satellites = satellites.exclude(catalogue=2)
            satellites = satellites.exclude(country='CIS',
                                            country__isnull=False)

        response[
            'Content-Disposition'] = 'attachment; filename=satellites_list.txt'

        print >> response, "# nsatellites:", len(satellites)

        print >> response, "#"

        print >> response, "# Catalogue Id Name Country Variability Period StdMag_Clear StdMag_Clear_Sigma StdMag_B StdMag_B_Sigma StdMag_V StdMag_V_Sigma StdMag_R StdMag_R_Sigma StdMag_Clear_Median StdMag_Clear_Min StdMag_Clear_Max"

        for satellite in satellites:
            satellite.country = satellite.country or None
            satellite.variability_period = satellite.variability_period or 0

            satellite.mean_clear = satellite.mean_clear or np.nan
            satellite.mean_b = satellite.mean_b or np.nan
            satellite.mean_v = satellite.mean_v or np.nan
            satellite.mean_r = satellite.mean_r or np.nan

            satellite.sigma_clear = satellite.sigma_clear or np.nan
            satellite.sigma_b = satellite.sigma_b or np.nan
            satellite.sigma_v = satellite.sigma_v or np.nan
            satellite.sigma_r = satellite.sigma_r or np.nan

            satellite.median_clear = satellite.median_clear or np.nan
            satellite.min_clear = satellite.min_clear or np.nan
            satellite.max_clear = satellite.max_clear or np.nan

            print >> response, satellite_catalogue(
                satellite.catalogue
            ), satellite.catalogue_id, '"%s"' % satellite.name, satellite.country, satellite.variability, satellite.variability_period, "%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f" % (
                satellite.mean_clear, satellite.sigma_clear, satellite.mean_b,
                satellite.sigma_b, satellite.mean_v, satellite.sigma_v,
                satellite.mean_r, satellite.sigma_r, satellite.median_clear,
                satellite.min_clear, satellite.max_clear)

    return response
Example #11
0
def satellites_list(request,
                    id=0,
                    catalogue_id=0,
                    name=None,
                    comments=None,
                    sort=None):
    context = {}

    context['should_paginate'] = True

    if request.method == 'POST':
        id = request.POST.get('id')
        catalogue_id = request.POST.get('catalogue_id')
        name = request.POST.get('name')
        comments = request.POST.get('comments')
        context['should_paginate'] = False
    elif request.method == 'GET':
        sort = request.GET.get('sort')

    if not sort:
        sort = '-time_last'

    satellites = SatellitesView.objects.order_by(sort)
    tracks = SatelliteTracks.objects.all()

    context['nsatellites'] = satellites.count()
    context['nsatellites_str'] = "".join(
        ["*" for i in xrange(context['nsatellites'] / 1000)])
    context['ntracks'] = tracks.count()
    context['time_min'] = SatelliteRecords.objects.aggregate(
        Min('time'))['time__min']
    context['time_max'] = SatelliteRecords.objects.aggregate(
        Max('time'))['time__max']

    if sort:
        nsort = sort
        if sort[0] == '-':
            nsort = sort[1:]

        if nsort in satellites.model._meta.get_all_field_names():
            satellites = satellites.extra(where=["%s is not Null" % nsort])

    if sort in ['variability_period', '-variability_period']:
        satellites = satellites.filter(variability=2)

    context['sort'] = sort
    context['sort_description'] = {
        'time_last': 'oldest last track',
        '-time_last': 'latest track',
        'time_first': 'oldest first track',
        '-time_first': 'newest first track',
        'catalogue_id': 'catalogue id',
        '-catalogue_id': 'catalogue id, descending',
        'ntracks': 'number of tracks',
        '-ntracks': 'number of tracks, descending',
        'variability_period': 'variability period',
        '-variability_period': 'variability period, descending',
        'mean_clear': 'mean brightness',
        '-mean_clear': 'mean brightness, descending',
        'rcs': 'Radar Cross-Section',
        '-rcs': 'Radar Cross-Section, descending',
    }.get(sort, sort)

    if request.method == 'POST':
        if not request.POST.get('var_nonvariable'):
            satellites = satellites.exclude(variability=0)

        if not request.POST.get('var_variable'):
            satellites = satellites.exclude(variability=1)

        if not request.POST.get('var_periodic'):
            satellites = satellites.exclude(variability=2)
        else:
            if request.POST.get('var_pmin') or request.POST.get('var_pmax'):
                satellites = satellites.filter(variability=2)

            if request.POST.get('var_pmin'):
                satellites = satellites.filter(
                    variability_period__gt=request.POST.get('var_pmin'))
            if request.POST.get('var_pmax'):
                satellites = satellites.filter(
                    variability_period__lt=request.POST.get('var_pmax'))

        for i in range(8):
            if not request.POST.get('type_%d' % i):
                satellites = satellites.exclude(type=i)

        if request.POST.get('orb_incl_min'):
            satellites = satellites.filter(
                orbit_inclination__gt=request.POST.get('orb_incl_min'))
        if request.POST.get('orb_incl_max'):
            satellites = satellites.filter(
                orbit_inclination__lt=request.POST.get('orb_incl_max'))
        if request.POST.get('orb_period_min'):
            satellites = satellites.filter(
                orbit_period__gt=request.POST.get('orb_period_min'))
        if request.POST.get('orb_period_max'):
            satellites = satellites.filter(
                orbit_period__lt=request.POST.get('orb_period_max'))
        if request.POST.get('orb_ecc_min'):
            satellites = satellites.filter(
                orbit_eccentricity__gt=request.POST.get('orb_ecc_min'))
        if request.POST.get('orb_ecc_max'):
            satellites = satellites.filter(
                orbit_eccentricity__gt__lt=request.POST.get('orb_ecc_max'))

    if id:
        satellites = satellites.filter(id=id)
        context['id'] = id

    if catalogue_id:
        cat_ids = [int(i) for i in catalogue_id.replace(',', ' ').split()]
        satellites = satellites.filter(catalogue_id__in=cat_ids)
        context['catalogue_id'] = catalogue_id

    if name:
        if len(name) == 9 and name[4] == '-' and satellites.filter(
                iname__iexact=name).exists():
            satellites = satellites.filter(iname__iexact=name)
        elif satellites.filter(name__iexact=name).exists():
            satellites = satellites.filter(name__iexact=name)
        else:
            satellites = satellites.filter(name__icontains=name)
        context['name'] = name

    if comments:
        satellites = satellites.filter(comments__icontains=comments)

    if not has_permission(request, 'fweb.access_satellites_all'):
        satellites = satellites.exclude(catalogue=2)
        satellites = satellites.exclude(country='CIS', country__isnull=False)

    if request.method == 'POST' and satellites.count() == 1:
        return redirect('satellite_details', id=satellites.first().id)

    context['satellites'] = satellites
    context['tracks'] = tracks

    return TemplateResponse(request, 'satellites.html', context=context)