Beispiel #1
0
def webhook():
    secret = request.args.get("secret")
    if not secret or secret != WEBHOOK_SECRET:
        return abort(403, "Unauthorized! Invalid secret!")

    event_type = request.headers.get("X-Gitlab-Event")
    embed = None
    if event_type == "Push Hook":
        data = request.get_json()
        embed = webhook_push(data)
    if event_type == "Pipeline Hook":
        data = request.get_json()
        if data["object_attributes"]["status"] in [
                "success", "failed", "manual"
        ]:
            embed = webhook_pipeline(data)

    if embed:
        send_webhook(embed, DISCORD_WEBHOOK_URL)
        return "Ok"

    return abort(
        400, "Could not create message for event type {}".format(event_type))
Beispiel #2
0
    def submitRaid(self,
                   gym,
                   pkm,
                   lvl,
                   start,
                   end,
                   type,
                   raidNo,
                   captureTime,
                   MonWithNoEgg=False):
        log.debug('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) +
                  ') ] ' + 'submitRaid: Submitting raid')

        try:
            connection = mysql.connector.connect(host=self.host,
                                                 user=self.user,
                                                 port=self.port,
                                                 passwd=self.password,
                                                 db=self.database)
        except:
            log.error("Could not connect to the SQL database")
            return False

        if start is not None:
            start -= self.timezone * 60 * 60

        if end is not None:
            end -= self.timezone * 60 * 60
        wh_send = False
        wh_start = 0
        wh_end = 0
        eggHatched = False

        cursor = connection.cursor()
        log.debug('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) +
                  ') ] ' +
                  'submitRaid: Submitting something of type %s' % type)

        log.info(
            "Submitting. Gym: %s, Lv: %s, Start and Spawn: %s, End: %s, Mon: %s"
            % (gym, lvl, start, end, pkm))

        # always insert timestamp to last_scanned to have rows change if raid has been reported before
        updateStr = 'UPDATE raid '
        whereStr = 'WHERE gym_id = \'%s\' ' % str(gym)
        if MonWithNoEgg:
            # submit mon without egginfo -> we have an endtime
            start = end - 45 * 60
            log.info("Updating mon without egg")
            setStr = 'SET level = %s, spawn = FROM_UNIXTIME(%s), start = FROM_UNIXTIME(%s), end = FROM_UNIXTIME(%s), ' \
                     'pokemon_id = %s, last_scanned = FROM_UNIXTIME(%s) '
            data = (lvl, captureTime, start, end, pkm, int(time.time()))
        elif end is None or start is None:
            # no end or start time given, just update anything there is
            log.info(
                "Updating without end- or starttime - we should've seen the egg before"
            )
            setStr = 'SET level = %s, pokemon_id = %s, last_scanned = FROM_UNIXTIME(%s) '
            data = (lvl, pkm, int(time.time()))

            foundEndTime, EndTime = self.getRaidEndtime(gym, raidNo)
            if foundEndTime:
                wh_send = True
                wh_start = int(EndTime) - 2700
                wh_end = EndTime
                eggHatched = True
            else:
                wh_send = False
        else:
            log.info("Updating everything")
            # we have start and end, mon is either with egg or we're submitting an egg
            setStr = 'SET level = %s, spawn = FROM_UNIXTIME(%s), start = FROM_UNIXTIME(%s), end = FROM_UNIXTIME(%s), ' \
                     'pokemon_id = %s, ' \
                     'last_scanned = FROM_UNIXTIME(%s) '
            data = (lvl, captureTime, start, end, pkm, int(time.time()))

        query = updateStr + setStr + whereStr
        log.debug(query % data)
        cursor.execute(query, data)
        affectedRows = cursor.rowcount
        connection.commit()
        cursor.close()
        if affectedRows == 0 and not eggHatched:
            # we need to insert the raid...
            log.info("Gotta insert")
            if MonWithNoEgg:
                # submit mon without egg info -> we have an endtime
                log.info("Inserting mon without egg")
                start = end - 45 * 60
                query = (
                    'INSERT INTO raid (gym_id, level, spawn, start, end, pokemon_id, last_scanned) '
                    'VALUES (%s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))'
                )
                data = (gym, lvl, captureTime, start, end, pkm,
                        int(time.time()))
            elif end is None or start is None:
                log.info("Inserting without end or start")
                # no end or start time given, just inserting won't help much...
                log.warning("Useless to insert without endtime...")
                return False
            else:
                # we have start and end, mon is either with egg or we're submitting an egg
                log.info("Inserting everything")
                query = (
                    'INSERT INTO raid (gym_id, level, spawn, start, end, pokemon_id, last_scanned) '
                    'VALUES (%s, %s, FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))'
                )
                data = (gym, lvl, captureTime, start, end, pkm,
                        int(time.time()))

            cursorIns = connection.cursor()
            log.debug(query % data)
            cursorIns.execute(query, data)
            connection.commit()
            cursorIns.close()

            wh_send = True
            if MonWithNoEgg:
                wh_start = int(end) - 2700
            else:
                wh_start = start
            wh_end = end
            if pkm is None:
                pkm = 0

        connection.close()
        log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) +
                 ') ] ' + 'submitRaid: Submit finished')
        self.refreshTimes(gym, raidNo, captureTime)

        if args.webhook and wh_send:
            log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) +
                     ') ] ' + 'submitRaid: Send webhook')
            if wh_start:
                wh_start += (self.timezone * 60 * 60)
            if wh_end:
                wh_end += (self.timezone * 60 * 60)
            send_webhook(gym, 'RAID', wh_start, wh_end, lvl, pkm)

        return True
Beispiel #3
0
async def reconstruct_server(server_json, client, message, *, messages=False):
    server = message.channel.guild
    roles = {}
    timeout = 20
    embed=discord.Embed()
    embed.add_field(name=':warning: Are you sure?', value='Re-creating {} here will completely erase the current state of this server'.format(server_json['name']), inline=False)
    embed.add_field(name='Type "I understand" to continue', value=f'(timout in {timeout}s)', inline=False)
    warning = await message.channel.send(embed=embed)

    def check(author):
        def inner_check(message):
            return message.author == author and message.content.lower() == "i understand"
        return inner_check
    try:
        msg = await client.wait_for('message', check=check(message.author), timeout=timeout)
    except asyncio.TimeoutError:
        await warning.delete()
        await message.channel.send(':timer: **Timeout! Server re-creation canceled**')
        return

    print('Reconstructing ' + server_json['name'])

    #Deletes all channels, categories and roles
    await clear_server(server)

    #A mess to konvert the server .webp icon to a .jpg
    #(since discord stores icons as .webp, but doesen't accept it as input :/)
    if server_json['icon_url'] != '':
        r = requests.get(server_json['icon_url'], stream=True)
        with open('files/icon.webp', 'w+b') as out_file:
            shutil.copyfileobj(r.raw, out_file)
        im = Image.open('files/icon.webp').convert('RGB')
        im.save('files/icon.jpg','jpeg')
        with open('files/icon.jpg', 'rb') as in_file:
            icon = in_file.read()
        await server.edit(icon=icon)


    '''Creates all the roles
    The dictionary "roles" links the id of the role on the last
    server, to the object of the role on the current one, since
    the roles id:s is stored with their old one in the .json'''
    for role_id, role in server_json['roles'].items():
        if role['name'] != '@everyone':
            perm = discord.Permissions()._from_value(role['permissions'])
            #Convert the hex string to a RGB tuple
            color = tuple(int(role['color'].lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
            color = discord.Colour(0).from_rgb(color[0], color[1], color[2])

            role = await server.create_role(name=role['name'], color=color, permissions=perm)
            roles[role_id] = role
        else:
            #Can not create the @everyone, but need it as an object,
            #so we just call server.default_role
            roles[role_id] = server.default_role

    #Don't have to reformat anything
    #since it's already good in the file
    users = server_json['user_info']

    #Create all the channels and cetegories with the correct permissions
    for cn, channels in server_json['categories'].items():
        category = await server.create_category(cn)

        for channel in channels:
            #Create a PermissionOverwrite object for every channel
            overwrites = {}
            for role_id, perms in channel['overwrites'].items():
                role = roles[role_id]
                perm = {x: perms[x] for x in perms if x != 'type'}
                overwrites[role] = discord.PermissionOverwrite(**perm)

            #If it has a description it means it's a text channel, else a voice
            if 'description' in channel:
                channel_object = await server.create_text_channel(channel['name'], category=category,
                topic=channel['description'], overwrites=overwrites)

                #Recreate all the messages if requested
                #(very slow, took over 3 hours for ~5200 messages)
                if messages:
                    web = await channel_object.create_webhook(name='Archiver Webhook')
                    url = web.url
                    for msg in channel['messages']:
                        user = users[msg['author']]
                        if msg['content'] != '':
                            send_webhook(url, user['avatar_url'], user['name'], msg['content'], msg['attachments'])
            else:
                channel = await server.create_voice_channel(channel['name'], category=category, overwrites=overwrites)
        if category.name == 'no-category':
            await category.delete()
                
            print(' Reconstructed #' + channel['name'])
Beispiel #4
0
    def submitRaid(self, gym, pkm, lvl, start, end, type, raidNo, captureTime, MonWithNoEgg=False):
        log.debug('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + 'submitRaid: Submitting raid')

        try:
            connection = mysql.connector.connect(host=self.host,
                                                 user=self.user, port=self.port, passwd=self.password,
                                                 db=self.database)
        except:
            log.error("Could not connect to the SQL database")
            return False

        wh_send = False
        eggHatched = False
        cursor = connection.cursor()
        log.debug('[Crop: ' + str(raidNo) + ' (' + str(
            self.uniqueHash) + ') ] ' + 'submitRaid: Submitting something of type %s' % type)

        log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' +
                 "Submitting. Gym: %s, Lv: %s, Start and Spawn: %s, End: %s, Mon: %s" % (gym, lvl, start, end, pkm))

        # always insert timestamp to time_spawn to have rows change if raid has been reported before
        updateStr = 'UPDATE raids '
        whereStr = 'WHERE fort_id = %s AND time_end >= %s' % (str(gym), str(int(time.time())))
        if MonWithNoEgg:
            # submit mon without egg info -> we have an endtime
            start = end - 45 * 60
            log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Updating mon without egg")

            setStr = 'SET level = %s, time_spawn = %s, time_battle = %s, time_end = %s, ' \
                     'pokemon_id = %s, last_updated = %s '
            data = (lvl, captureTime, start, end, pkm, int(time.time()))

        elif end is None or start is None:
            # no end or start time given, just update the other stuff
            # TODO: consider skipping UPDATING/INSERTING
            # TODO: this will be an update of a hatched egg to a boss!
            log.info('[Crop: ' + str(raidNo) + ' (' + str(
                self.uniqueHash) + ') ] ' + "Updating without endtime or starttime - we should've seen an egg before "
                                            "then")
            setStr = 'SET level = %s, pokemon_id = %s, last_updated = %s '
            data = (lvl, pkm, int(time.time()))

            foundEndTime, EndTime = self.getRaidEndtime(gym, raidNo)

            if foundEndTime:
                wh_send = True
                wh_start = int(EndTime) - 2700
                wh_end = EndTime
                eggHatched = True
            else:
                wh_send = False

            # TODO: check for start/end
        else:
            log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Updating everything")
            # we have start and end, mon is either with egg or we're submitting an egg
            setStr = 'SET level = %s, time_spawn = %s, time_battle = %s, time_end = %s, pokemon_id = %s, ' \
                     'last_updated = %s '
            data = (lvl, captureTime, start, end, pkm, int(time.time()))

        query = updateStr + setStr + whereStr
        log.debug(query % data)
        cursor.execute(query, data)
        affectedRows = cursor.rowcount
        connection.commit()
        cursor.close()
        if affectedRows == 0 and not eggHatched:
            # we need to insert the raid...
            log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Gotta insert")
            if MonWithNoEgg:
                # submit mon without egg info -> we have an endtime
                log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Inserting mon without egg")
                start = end - 45 * 60
                query = (
                    'INSERT INTO raids (fort_id, level, time_spawn, time_battle, time_end, pokemon_id) '
                    'VALUES (%s, %s, %s, %s, %s, %s)')
                data = (gym, lvl, captureTime, start, end, pkm)
            elif end is None or start is None:
                log.info(
                    '[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Inserting without end or start")
                # no end or start time given, just inserting won't help much...
                log.warning("Useless to insert without endtime...")
                return False
            else:
                # we have start and end, mon is either with egg or we're submitting an egg
                log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + "Inserting everything")
                query = (
                    'INSERT INTO raids (fort_id, level, time_spawn, time_battle, time_end, pokemon_id) '
                    'VALUES (%s, %s, %s, %s, %s, %s)')
                data = (gym, lvl, captureTime, start, end, pkm)

            cursorIns = connection.cursor()
            log.debug('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + query % data)
            cursorIns.execute(query, data)
            connection.commit()
            cursorIns.close()

            wh_send = True
            if MonWithNoEgg:
                wh_start = int(end) - 2700
            else:
                wh_start = start
            wh_end = end
            if pkm is None:
                pkm = 0

        connection.close()
        log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + 'submitRaid: Submit finished')
        self.refreshTimes(gym, raidNo, captureTime)

        if args.webhook and wh_send:
            log.info('[Crop: ' + str(raidNo) + ' (' + str(self.uniqueHash) + ') ] ' + 'submitRaid: Send webhook')
            send_webhook(gym, 'RAID', wh_start, wh_end, lvl, pkm)

        return True