def test_dispatch(self):

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('10.255.255.255', 1))
        except Exception as e:
            self.fail("Can't be tested without an internet connection")
        finally:
            s.close()

        # Should result in 3 messages, one embed, one embed with photo, and one photo.
        builder = EmbedBuilder()
        builder.set_title("Test title")
        builder.set_description("No snapshot")

        self.assertTrue(
            self.discord._dispatch_message(embed=builder.get_embeds()[0]))

        with open(self._get_path("test_pattern.png"), "rb") as f:
            builder.set_description("With snapshot")
            builder.set_image(("snapshot.png", f))
            self.assertTrue(
                self.discord._dispatch_message(embed=builder.get_embeds()[0]))

            f.seek(0)
            self.assertTrue(
                self.discord._dispatch_message(snapshot=("snapshot.png", f)))
示例#2
0
    def timelapse(self):
        path = os.path.join(os.getcwd(), self.plugin._data_folder, '..', '..',
                            'timelapse')
        path = os.path.abspath(path)

        builder = EmbedBuilder()
        builder.set_title('Files and Details')
        builder.set_description('Download with /gettimelapse {filename}')
        builder.set_author(name=self.plugin.get_printer_name())

        baseurl = self.plugin.get_settings().get(["baseurl"])
        port = self.plugin.get_port()
        if baseurl is None or baseurl == "":
            baseurl = "%s:%s" % (self.plugin.get_ip_address(), port)

        for root, dirs, files in os.walk(path):
            for name in files:
                try:
                    file_path = os.path.join(root, name)

                    title = os.path.basename(file_path)

                    description = ''
                    description += 'Size: %s\n' % os.path.getsize(file_path)
                    description += 'Date of Creation: %s\n' % time.ctime(
                        os.path.getctime(file_path))
                    description += 'Download Path: %s\n' %\
                                   ("http://" + baseurl + "/downloads/timelapse/" + urllib.quote(title))

                    builder.add_field(title=title, text=description)
                except Exception as e:
                    pass

        return None, builder.get_embeds()
示例#3
0
    def list_system_commands(self):
        api_key = self.plugin.get_settings().global_get(['api', 'key'])
        port = self.plugin.get_settings().global_get(['server', 'port'])
        header = {'X-Api-Key': api_key, 'Content-Type': 'application/json'}

        response = requests.get('http://127.0.0.1:%s/api/system/commands' %
                                port,
                                headers=header)
        if response.status_code != 200:
            return None, error_embed(author=self.plugin.get_printer_name(),
                                     title="Error code: %i" %
                                     response.status_code,
                                     description=response.content)

        builder = EmbedBuilder()
        builder.set_title('List of system commands')
        builder.set_author(name=self.plugin.get_printer_name())
        builder.set_description(
            'To execute a system command, use /systemcommand {command}. '
            'Where command is similar to "core/restart"')
        data = json.loads(response.content)
        for source in data:
            for comm in data[source]:
                if 'name' not in comm:
                    continue
                comm_name = comm['name']
                comm_description = "%s/%s" % (source, comm['action'])
                if 'command' in comm:
                    comm_description = "%s - %s" % (comm_description,
                                                    comm['command'])
                builder.add_field(title=comm_name, text=comm_description)
        return None, builder.get_embeds()
示例#4
0
    def test_embedbuilder(self):
        # Success
        builder = EmbedBuilder()
        builder.set_title("Test Title")
        builder.set_description("This is a description")
        builder.set_color(COLOR_INFO)
        for i in range(0, 30):
            builder.add_field("a" * MAX_TITLE,
                              "b" * MAX_VALUE)
        messages = builder.get_embeds()
        self.assertEqual(8, len(messages))

        embed, snapshot = messages[0]
        self.assertEqual("Test Title", embed.title)
        self.assertEqual("This is a description", embed.description)
        for embed, snapshot in messages:
            self.assertEqual(COLOR_INFO, embed.color.value)
            self.assertIsNotNone(embed.timestamp)
            self.assertLessEqual(len(embed.fields), MAX_NUM_FIELDS)
            for field in embed.fields:
                self.assertEqual("a" * MAX_TITLE, field.name)
                self.assertEqual("b" * MAX_VALUE, field.value)

        if "NET_TEST" in os.environ:
            self.discord.send(messages=messages)
    def test_embedbuilder(self):
        # Success
        builder = EmbedBuilder()
        builder.set_title("Test Title")
        builder.set_description("This is a description")
        builder.set_color(COLOR_INFO)
        for i in range(0, 30):
            builder.add_field("a" * MAX_TITLE, "b" * MAX_VALUE)
        embeds = builder.get_embeds()
        self.assertEqual(8, len(embeds))

        first_embed = embeds[0].get_embed()
        self.assertEqual("Test Title", first_embed['title'])
        self.assertEqual("This is a description", first_embed['description'])
        for embed in embeds:
            embed_obj = embed.get_embed()
            self.assertEqual(COLOR_INFO, embed_obj['color'])
            self.assertIsNotNone(embed_obj['timestamp'])
            self.assertLessEqual(len(embed_obj['fields']), MAX_NUM_FIELDS)
            for field in embed_obj['fields']:
                self.assertEqual("a" * MAX_TITLE, field['name'])
                self.assertEqual("b" * MAX_VALUE, field['value'])

        if "NET_TEST" in os.environ:
            self.assertTrue(self.discord.send(embeds=embeds))
 def sus(self,n):
     builder = EmbedBuilder()
     builder.set_title(n)
     x=random.randint(0,9)
     if x==0:
         builder.add_field(title=n, text="is sus")
     else
         builder.add_field(title=n, text="is sus")
     return None, builder.get_embeds()
示例#7
0
    def test_unicode_embed(self):
        teststr = "٩(-̮̮̃-̃)۶ ٩(●̮̮̃•̃)۶ ٩(͡๏̯͡๏)۶ ٩(-̮̮̃•̃)."
        embed_builder = EmbedBuilder()
        embed_builder.set_title(teststr)
        embed_builder.set_description(teststr)
        embed_builder.set_author(teststr)
        embed_builder.add_field(teststr, teststr)
        embeds = embed_builder.get_embeds()

        self.assertIsNotNone(embeds)
示例#8
0
    def list_files(self):
        port = self.plugin.get_port()
        baseurl = self.plugin.get_settings().get(["baseurl"])
        if baseurl is None or baseurl == "":
            baseurl = "%s:%s" % (self.plugin.get_ip_address(), port)

        builder = EmbedBuilder()
        builder.set_title('Files and Details')
        builder.set_author(name=self.plugin.get_printer_name())
        file_list = self.get_flat_file_list()
        for details in file_list:
            description = ''
            title = ''
            try:
                title = details['path'].lstrip('/')
            except:
                pass

            try:
                description += 'Location: %s\n' % details['location']
            except:
                pass

            try:
                estimated_print_time = humanfriendly.format_timespan(
                    details['analysis']['estimatedPrintTime'], max_units=2)
                description += 'Estimated Print Time: %s\n' % estimated_print_time
            except:
                pass

            try:
                average_print_time = humanfriendly.format_timespan(
                    details['statistics']['averagePrintTime']['_default'],
                    max_units=2)
                description += 'Average Print Time: %s\n' % average_print_time
            except:
                pass

            try:
                filament_required = humanfriendly.format_length(
                    details['analysis']['filament']['tool0']['length'] / 1000)
                description += 'Filament Required: %s\n' % filament_required
            except:
                pass

            try:
                url = "http://" + baseurl + "/downloads/files/" + details[
                    'location'] + "/" + details['path'].lstrip('/')
                description += 'Download Path: %s\n' % url
            except:
                pass

            builder.add_field(title=title, text=description)

        return None, builder.get_embeds()
    def help(self):
        builder = EmbedBuilder()
        builder.set_title('Commands, Parameters and Description')
        builder.set_author(self.plugin.get_printer_name())

        for command, details in self.command_dict.items():
            builder.add_field(
                title='%s %s' % (self.plugin.get_settings().get(["prefix"]) + command, details.get('params') or ''),
                text=details.get('description'))

        return None, builder.get_embeds()
示例#10
0
    def listjobs(self):
        data = self.plugin.get_settings().global_get(["plugins", "printscheduler", "scheduled_jobs"])

        builder = EmbedBuilder()
        builder.set_title('Scheduled Jobs')
        builder.set_author(name=self.plugin.get_printer_name())

        for job in data:
            title = "%s: %s" % (job['start_at'], job['name'])
            description = "remove: `/removejob %s %s`" % (job['start_at'], job['path'])

            builder.add_field(title=title, text=description)

        # Use data in status to build an embed
        return builder.get_embeds()
    def enc_status(self):
        result = self.api_command("state", -1)
        data = result.json()

        builder = EmbedBuilder()
        builder.set_title('Enclosure Status')
        builder.set_author(name=self.plugin.get_printer_name())

        for file in data:
            title = ("ID: %s" % unicode(file['index_id']))
            description = unicode(file['status'])

            builder.add_field(title=title, text=description)

        # Use data in status to build an embed
        return None, builder.get_embeds()
    def status(self):
        builder = EmbedBuilder()
        builder.set_title('Status')
        builder.set_author(name=self.plugin.get_printer_name())

        if self.plugin.get_settings().get(['show_local_ip'], merged=True):
            ip_addr = self.plugin.get_ip_address()
            if ip_addr != '127.0.0.1':
                builder.add_field(title='Local IP', text=ip_addr, inline=True)

        if self.plugin.get_settings().get(['show_external_ip'], merged=True):
            builder.add_field(title='External IP', text=self.plugin.get_external_ip_address(), inline=True)

        operational = self.plugin.get_printer().is_operational()
        builder.add_field(title='Operational', text='Yes' if operational else 'No', inline=True)
        current_data = self.plugin.get_printer().get_current_data()

        if current_data.get('currentZ'):
            builder.add_field(title='Current Z', text=current_data['currentZ'], inline=True)
        if operational:
            temperatures = self.plugin.get_printer().get_current_temperatures()
            for heater in temperatures.keys():
                if heater == 'bed':
                    continue
                builder.add_field(title='Extruder Temp (%s)' % heater, text=temperatures[heater]['actual'], inline=True)

            if temperatures['bed']['actual']:
                builder.add_field(title='Bed Temp', text=temperatures['bed']['actual'], inline=True)

            printing = self.plugin.get_printer().is_printing()
            builder.add_field(title='Printing', text='Yes' if printing else 'No', inline=True)
            if printing:
                builder.add_field(title='File', text=current_data['job']['file']['name'], inline=True)
                completion = current_data['progress']['completion']
                if completion:
                    builder.add_field(title='Progress', text='%d%%' % completion, inline=True)

                builder.add_field(title='Time Spent', text=self.plugin.get_print_time_spent(), inline=True)
                builder.add_field(title='Time Remaining', text=self.plugin.get_print_time_remaining(), inline=True)

        snapshots = self.plugin.get_snapshot()
        if snapshots and len(snapshots) == 1:
            builder.set_image(snapshots[0])
        return None, builder.get_embeds()
    def timelapse(self):

        api_key = self.plugin.get_settings().global_get(["api", "key"])
        baseurl = self.plugin.get_settings().get(["baseurl"])
        port = self.plugin.get_port()
        if baseurl is None or baseurl == "":
            baseurl = "%s:%s" % (self.plugin.get_ip_address(), port)
        header = {'X-Api-Key': api_key}

        builder = EmbedBuilder()
        builder.set_title('Files and Details')
        builder.set_author(name=self.plugin.get_printer_name())

        response = requests.get("http://127.0.0.1:%s/api/timelapse" % port, headers=header)
        data = response.json()

        for video in data['files']:
            description = ''
            title = ''
            try:
                title = video['name']
            except:
                pass

            try:
                description += 'Size: %s\n' % video['size']
            except:
                pass

            try:
                description += 'Date of Creation: %s\n' % video['date']
            except:
                pass

            try:
                description += 'Download Path: %s\n' % ("http://" + baseurl + video['url'])
            except:
                pass

            builder.add_field(title=title, text=description)

        return None, builder.get_embeds()
示例#14
0
    def status(self):
        builder = EmbedBuilder()
        builder.set_title('Current Status')
        builder.set_author(name=self.plugin.get_printer_name())

        if self.plugin.get_settings().get(['show_local_ip'], merged=True) != 'off':
            ip_addr = self.plugin.get_ip_address()
            if ip_addr != '127.0.0.1':
                builder.add_field(title='Local IP', text=ip_addr, inline=True)

        if self.plugin.get_settings().get(['show_external_ip'], merged=True) != 'off':
            builder.add_field(title='External IP', text=self.plugin.get_external_ip_address(), inline=True)

        operational = self.plugin.get_printer().is_operational()
        builder.add_field(title='Operational', text='Yes' if operational else 'No', inline=True)
        current_data = self.plugin.get_printer().get_current_data()

        if current_data.get('currentZ'):
            builder.add_field(title='Current Z', text=str(current_data['currentZ']), inline=True)
        if operational:
            temperatures = self.plugin.get_printer().get_current_temperatures()
            for heater in temperatures.keys():
                if heater == 'bed':
                    continue
                if temperatures[heater]['actual'] is None or len(str(temperatures[heater]['actual'])) == 0:
                    continue
                builder.add_field(title='Extruder Temp (%s)' % heater,
                                  text=str(temperatures[heater]['actual']),
                                  inline=True)

            if temperatures['bed']['actual']:
                builder.add_field(title='Bed Temp', text=str(temperatures['bed']['actual']), inline=True)

            printing = self.plugin.get_printer().is_printing()
            builder.add_field(title='Printing', text='Yes' if printing else 'No', inline=True)
            if printing:
                builder.add_field(title='File', text=current_data['job']['file']['name'], inline=True)
                completion = current_data['progress']['completion']
                if completion:
                    builder.add_field(title='Progress', text='%d%%' % completion, inline=True)

                builder.add_field(title='Time Spent', text=self.plugin.get_print_time_spent(), inline=True)
                builder.add_field(title='Time Remaining', text=self.plugin.get_print_time_remaining(), inline=True)

        try:
            cmd_response = subprocess.Popen(['vcgencmd', 'get_throttled'], stdout=subprocess.PIPE).communicate()
            throttled_string = cmd_response[0].decode().split('=')[1].strip()
            throttled_value = int(throttled_string, 0)
            if throttled_value & (1 << 0):
                builder.add_field(title='WARNING', text="PI is under-voltage", inline=True)
            if throttled_value & (1 << 1):
                builder.add_field(title='WARNING', text="PI has capped it's ARM frequency", inline=True)
            if throttled_value & (1 << 2):
                builder.add_field(title='WARNING', text="PI is currently throttled", inline=True)
            if throttled_value & (1 << 3):
                builder.add_field(title='WARNING', text="PI has reached temperature limit", inline=True)
            if throttled_value & (1 << 16):
                builder.add_field(title='WARNING', text="PI Under-voltage has occurred", inline=True)
            if throttled_value & (1 << 17):
                builder.add_field(title='WARNING', text="PI ARM frequency capped has occurred", inline=True)
            if throttled_value & (1 << 18):
                builder.add_field(title='WARNING', text="PI Throttling has occurred", inline=True)
            if throttled_value & (1 << 19):
                builder.add_field(title='WARNING', text="PI temperature limit has occurred", inline=True)
        except OSError as e:
            pass

        snapshots = self.plugin.get_snapshot()
        if snapshots and len(snapshots) == 1:
            builder.set_image(snapshots[0])
        return None, builder.get_embeds()