code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.data = cellpydata self.step_table = self.data.dataset # hope it works... time_voltage = self.data.get_ocv(direction='up', cycles=cycle) time = time_voltage.Step_Time voltage = time_voltage.Voltage self.time = np.array(time) self.voltage = np.array(voltage)
def set_cellpydata(self, cellpydata, cycle)
Performing fit of the OCV steps in the cycles set by set_cycles() from the data set by set_data() r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start). c is found from using tau / r --> err(c) = err(r) + err(tau) Args: cellpydata (CellpyData): data object from cellreader cycle (int): cycle number to get from CellpyData object Returns: None
6.676257
7.172089
0.930866
# Check if data is set if self.time is []: self.result = [] return try: self.fit_model() except ValueError as e: print(e) except AttributeError as e: print(e)
def run_fit(self)
Performing fit of the OCV steps in the cycles set by set_cycles() from the data set by set_data() r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start). c is found from using tau / r --> err(c) = err(r) + err(tau) Returns: None: Resulting best fit parameters are stored in self.result for the given cycles
5.698886
5.425181
1.050451
def xpath(x): return html.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) try: value = xpath('//*[@data-type="binding"]/@data-value')[0] is_translucent = value == 'translucent' except IndexError: is_translucent = False if is_translucent: id = TRANSLUCENT_BINDER_ID tree = {'id': id, 'title': xpath('//*[@data-type="document-title"]/text()')[0], 'contents': [x for x in _nav_to_tree(xpath('//xhtml:nav')[0])] } return tree
def parse_navigation_html_to_tree(html, id)
Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value.
4.280034
4.2307
1.011661
def expath(e, x): return e.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) for li in expath(root, 'xhtml:ol/xhtml:li'): is_subtree = bool([e for e in li.getchildren() if e.tag[e.tag.find('}')+1:] == 'ol']) if is_subtree: # It's a sub-tree and have a 'span' and 'ol'. itemid = li.get('cnx-archive-uri', 'subcol') shortid = li.get('cnx-archive-shortid') yield {'id': itemid, # Title is wrapped in a span, div or some other element... 'title': squash_xml_to_text(expath(li, '*')[0], remove_namespaces=True), 'shortId': shortid, 'contents': [x for x in _nav_to_tree(li)], } else: # It's a node and should only have an li. a = li.xpath('xhtml:a', namespaces=HTML_DOCUMENT_NAMESPACES)[0] yield {'id': a.get('href'), 'shortid': li.get('cnx-archive-shortid'), 'title': squash_xml_to_text(a, remove_namespaces=True)}
def _nav_to_tree(root)
Given an etree containing a navigation document structure rooted from the 'nav' element, parse to a tree: {'id': <id>|'subcol', 'title': <title>, 'contents': [<tree>, ...]}
4.600165
4.259615
1.079948
xpath = '//*[@data-type="resources"]//xhtml:li/xhtml:a' for resource in html.xpath(xpath, namespaces=HTML_DOCUMENT_NAMESPACES): yield { 'id': resource.get('href'), 'filename': resource.text.strip(), }
def parse_resources(html)
Return a list of resource names found in the html metadata section.
5.230566
4.714599
1.10944
''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` constructor or :func:`paho.mqtt.client.Client.userdata_set`. flags : dict Response flags sent by the broker. The flag ``flags['session present']`` is useful for clients that are using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists. rc : int The connection result. The value of rc indicates success or not: - 0: Connection successful - 1: Connection refused - incorrect protocol version - 2: Connection refused - invalid client identifier - 3: Connection refused - server unavailable - 4: Connection refused - bad username or password - 5: Connection refused - not authorised - 6-255: Currently unused. Notes ----- Subscriptions should be defined in this method to ensure subscriptions will be renewed upon reconnecting after a loss of connection. ''' super(SerialDeviceManager, self).on_connect(client, userdata, flags, rc) if rc == 0: self.mqtt_client.subscribe('serial_device/+/connect') self.mqtt_client.subscribe('serial_device/+/send') self.mqtt_client.subscribe('serial_device/+/close') self.mqtt_client.subscribe('serial_device/refresh_comports') self.refresh_comports()
def on_connect(self, client, userdata, flags, rc)
Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` constructor or :func:`paho.mqtt.client.Client.userdata_set`. flags : dict Response flags sent by the broker. The flag ``flags['session present']`` is useful for clients that are using clean session set to 0 only. If a client with clean session=0, that reconnects to a broker that it has previously connected to, this flag indicates whether the broker still has the session information for the client. If 1, the session still exists. rc : int The connection result. The value of rc indicates success or not: - 0: Connection successful - 1: Connection refused - incorrect protocol version - 2: Connection refused - invalid client identifier - 3: Connection refused - server unavailable - 4: Connection refused - bad username or password - 5: Connection refused - not authorised - 6-255: Currently unused. Notes ----- Subscriptions should be defined in this method to ensure subscriptions will be renewed upon reconnecting after a loss of connection.
3.693389
1.410488
2.618519
''' Callback for when a ``PUBLISH`` message is received from the broker. ''' if msg.topic == 'serial_device/refresh_comports': self.refresh_comports() return match = CRE_MANAGER.match(msg.topic) if match is None: logger.debug('Topic NOT matched: `%s`', msg.topic) else: logger.debug('Topic matched: `%s`', msg.topic) # Message topic matches command. Handle request. command = match.group('command') port = match.group('port') # serial_device/<port>/send # Bytes to send if command == 'send': self._serial_send(port, msg.payload) elif command == 'connect': # serial_device/<port>/connect # Request connection try: request = json.loads(msg.payload) except ValueError as exception: logger.error('Error decoding "%s (%s)" request: %s', command, port, exception) return self._serial_connect(port, request) elif command == 'close': self._serial_close(port)
def on_message(self, client, userdata, msg)
Callback for when a ``PUBLISH`` message is received from the broker.
4.015534
3.814795
1.052621
''' Publish status for specified port. Parameters ---------- port : str Device name/port. ''' if port not in self.open_devices: status = {} else: device = self.open_devices[port].serial properties = ('port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout', 'xonxoff', 'rtscts', 'dsrdtr') status = {k: getattr(device, k) for k in properties} status_json = json.dumps(status) self.mqtt_client.publish(topic='serial_device/%s/status' % port, payload=status_json, retain=True)
def _publish_status(self, port)
Publish status for specified port. Parameters ---------- port : str Device name/port.
2.957548
2.504608
1.180843
''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: logger.error('Error closing device `%s`: %s', port, exception) return else: logger.debug('Device not connected to `%s`', port) self._publish_status(port) return
def _serial_close(self, port)
Handle close request. Parameters ---------- port : str Device name/port.
4.171185
3.352468
1.244213
''' Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device. ''' if port not in self.open_devices: # Not connected to device. logger.error('Error sending data: `%s` not connected', port) self._publish_status(port) else: try: device = self.open_devices[port] device.write(payload) logger.debug('Sent data to `%s`', port) except Exception as exception: logger.error('Error sending data to `%s`: %s', port, exception)
def _serial_send(self, port, payload)
Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device.
3.129812
2.493119
1.25538
print(dt) print('ctime :', dt.ctime()) print('tuple :', dt.timetuple()) print('ordinal:', dt.toordinal()) print('Year :', dt.year) print('Mon :', dt.month) print('Day :', dt.day)
def print_datetime_object(dt)
prints a date-object
2.802917
2.783219
1.007078
warnings.warn("raw limits have not been subject for testing yet") raw_limits = dict() raw_limits["current_hard"] = 0.1 # There is a bug in PEC raw_limits["current_soft"] = 1.0 raw_limits["stable_current_hard"] = 2.0 raw_limits["stable_current_soft"] = 4.0 raw_limits["stable_voltage_hard"] = 2.0 raw_limits["stable_voltage_soft"] = 4.0 raw_limits["stable_charge_hard"] = 2.0 raw_limits["stable_charge_soft"] = 5.0 raw_limits["ir_change"] = 0.00001 return raw_limits
def get_raw_limits(self)
Include the settings for how to decide what kind of step you are examining here. The raw limits are 'epsilons' used to check if the current and/or voltage is stable (for example for galvanostatic steps, one would expect that the current is stable (constant) and non-zero). It is expected that different instruments (with different resolution etc.) have different 'epsilons'. Returns: the raw limits (dict)
3.287483
3.00039
1.095685
if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not Iron) return True else: if 'PROCESSOR_ARCHITEW6432' in os.environ: return True # 32 bit program running on 64 bit Windows try: # 64 bit Windows 64 bit program return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64') except IndexError: pass # not Windows try: # this often works in Linux return '64' in platform.architecture()[0] except Exception: # is an older version of Python, assume also an older os@ # (best we can guess) return False
def check64bit(current_system="python")
checks if you are on a 64 bit platform
5.153514
5.063335
1.01781
# abbrevs = ( # (1 << 50L, 'PB'), # (1 << 40L, 'TB'), # (1 << 30L, 'GB'), # (1 << 20L, 'MB'), # (1 << 10L, 'kB'), # (1, 'b') # ) abbrevs = ( (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'b') ) if b == 1: return '1 byte' for factor, suffix in abbrevs: if b >= factor: break # return '%.*f %s' % (precision, old_div(b, factor), suffix) return '%.*f %s' % (precision, b // factor, suffix)
def humanize_bytes(b, precision=1)
Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12342,2) '12.05 MB' >>> humanize_bytes(1024*1234,2) '1.21 MB' >>> humanize_bytes(1024*1234*1111,2) '1.31 GB' >>> humanize_bytes(1024*1234*1111,1) '1.3 GB'
1.545673
1.661515
0.930279
# This does not work for numpy-arrays if option == "to_float": d = (xldate - 25589) * 86400.0 else: try: d = datetime.datetime(1899, 12, 30) + \ datetime.timedelta(days=xldate + 1462 * datemode) # date_format = "%Y-%m-%d %H:%M:%S:%f" # with microseconds, # excel cannot cope with this! if option == "to_string": date_format = "%Y-%m-%d %H:%M:%S" # without microseconds d = d.strftime(date_format) except TypeError: logging.info(f'The date is not of correct type [{xldate}]') d = xldate return d
def xldate_as_datetime(xldate, datemode=0, option="to_datetime")
Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object, float, or string).
3.727803
3.666554
1.016705
if os.path.isfile(filename): fid_st = os.stat(filename) self.name = os.path.abspath(filename) self.full_name = filename self.size = fid_st.st_size self.last_modified = fid_st.st_mtime self.last_accessed = fid_st.st_atime self.last_info_changed = fid_st.st_ctime self.location = os.path.dirname(filename)
def populate(self, filename)
Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file.
2.51739
2.406379
1.046132
return [self.name, self.size, self.last_modified, self.location]
def get_raw(self)
Get a list with information about the file. The returned list contains name, size, last_modified and location.
8.980975
3.288914
2.730681
try: empty = self.dfsummary.empty except AttributeError: empty = True return not empty
def dfsummary_made(self)
check if the summary table exists
5.681494
4.421165
1.285067
try: empty = self.step_table.empty except AttributeError: empty = True return not empty
def step_table_made(self)
check if the step table exists
6.465894
5.230394
1.236216
table_name = self.db_sheet_table header_row = self.db_header_row nrows = self.nrows if dtypes_dict is None: dtypes_dict = self.dtypes_dict rows_to_skip = self.skiprows logging.debug(f"Trying to open the file {self.db_file}") logging.debug(f"Number of rows: {nrows}") logging.debug(f"Skipping the following rows: {rows_to_skip}") logging.debug(f"Declaring the following dtyps: {dtypes_dict}") work_book = pd.ExcelFile(self.db_file) try: sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, dtype=dtypes_dict, nrows=nrows, ) except ValueError as e: logging.debug("Could not parse all the columns (ValueError) " "using given dtypes. Trying without dtypes.") logging.debug(str(e)) sheet = work_book.parse( table_name, header=header_row, skiprows=rows_to_skip, nrows=nrows, ) return sheet
def _open_sheet(self, dtypes_dict=None)
Opens sheets and returns it
2.719804
2.691007
1.010701
probably_good_to_go = True sheet = self.table identity = self.db_sheet_cols.id # check if you have unique srnos id_col = sheet.loc[:, identity] if any(id_col.duplicated()): warnings.warn( "your database is corrupt: duplicates" " encountered in the srno-column") logger.debug("srno duplicates:\n" + str( id_col.duplicated())) probably_good_to_go = False return probably_good_to_go
def _validate(self)
Checks that the db-file is ok Returns: True if OK, False if not.
8.06035
7.763752
1.038203
sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col] == serial_number return sheet.loc[rows, :]
def select_serial_number_row(self, serial_number)
Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame
9.596291
9.896134
0.969701
sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col].isin(serial_numbers) return sheet.loc[rows, :]
def select_all(self, serial_numbers)
Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame
8.483437
8.86384
0.957084
r = self.select_serial_number_row(serial_number) if r.empty: warnings.warn("missing serial number") return txt1 = 80 * "=" txt1 += "\n" txt1 += f" serial number {serial_number}\n" txt1 = 80 * "-" txt1 += "\n" txt2 = "" for label, value in zip(r.columns, r.values[0]): if label in self.headers: txt1 += f"{label}: \t {value}\n" else: txt2 += f"({label}: \t {value})\n" if print_to_screen: print(txt1) print(80 * "-") print(txt2) print(80 * "=") return else: return txt1
def print_serial_number_info(self, serial_number, print_to_screen=True)
Print information about the run. Args: serial_number: serial number. print_to_screen: runs the print statement if True, returns txt if not. Returns: txt if print_to_screen is False, else None.
3.093735
2.934284
1.054341
sheet = self.table identity = self.db_sheet_cols.id exists = self.db_sheet_cols.exists cellname = self.db_sheet_cols.cell_name search_string = "" if not isinstance(slurry, (list, tuple)): slurry = [slurry, ] first = True for slur in slurry: s_s = appender + slur + appender if first: search_string = s_s first = False else: search_string += "|" search_string += s_s criterion = sheet.loc[:, cellname].str.contains( search_string ) exists = sheet.loc[:, exists] > 0 sheet = sheet[criterion & exists] return sheet.loc[:, identity].values.astype(int)
def filter_by_slurry(self, slurry, appender="_")
Filters sheet/table by slurry name. Input is slurry name or list of slurry names, for example 'es030' or ["es012","es033","es031"]. Args: slurry (str or list of strings): slurry names. appender (chr): char that surrounds slurry names. Returns: List of serial_number (ints).
3.927335
3.745008
1.048685
if not isinstance(column_names, (list, tuple)): column_names = [column_names, ] sheet = self.table identity = self.db_sheet_cols.id exists = self.db_sheet_cols.exists criterion = True for column_name in column_names: _criterion = sheet.loc[:, column_name] > 0 _exists = sheet.loc[:, exists] > 0 criterion = criterion & _criterion & _exists return sheet.loc[criterion, identity].values.astype(int)
def filter_by_col(self, column_names)
filters sheet/table by columns (input is column header) The routine returns the serial numbers with values>1 in the selected columns. Args: column_names (list): the column headers. Returns: pandas.DataFrame
4.384507
4.537438
0.966296
sheet = self.table identity = self.db_sheet_cols.id exists_col_number = self.db_sheet_cols.exists exists = sheet.loc[:, exists_col_number] > 0 if min_val is not None and max_val is not None: criterion1 = sheet.loc[:, column_name] >= min_val criterion2 = sheet.loc[:, column_name] <= max_val sheet = sheet[criterion1 & criterion2 & exists] elif min_val is not None or max_val is not None: if min_val is not None: criterion = sheet.loc[:, column_name] >= min_val if max_val is not None: criterion = sheet.loc[:, column_name] <= max_val # noinspection PyUnboundLocalVariable sheet = sheet[criterion & exists] else: sheet = sheet[exists] return sheet.loc[:, identity].values.astype(int)
def filter_by_col_value(self, column_name, min_val=None, max_val=None)
filters sheet/table by column. The routine returns the serial-numbers with min_val <= values >= max_val in the selected column. Args: column_name (str): column name. min_val (int): minimum value of serial number. max_val (int): maximum value of serial number. Returns: pandas.DataFrame
2.52861
2.695098
0.938226
if not batch_col_name: batch_col_name = self.db_sheet_cols.batch logger.debug("selecting batch - %s" % batch) sheet = self.table identity = self.db_sheet_cols.id exists_col_number = self.db_sheet_cols.exists criterion = sheet.loc[:, batch_col_name] == batch exists = sheet.loc[:, exists_col_number] > 0 # This will crash if the col is not of dtype number sheet = sheet[criterion & exists] return sheet.loc[:, identity].values.astype(int)
def select_batch(self, batch, batch_col_name=None)
selects the rows in column batch_col_number (default: DbSheetCols.batch)
5.120159
4.326698
1.183387
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('collated_html', type=argparse.FileType('r'), help='Path to the collated html' ' file (use - for stdin)') parser.add_argument('-d', '--dump-tree', action='store_true', help='Print out parsed model tree.') parser.add_argument('-o', '--output', type=argparse.FileType('w+'), help='Write out epub of parsed tree.') parser.add_argument('-i', '--input', type=argparse.FileType('r'), help='Read and copy resources/ for output epub.') args = parser.parse_args(argv) if args.input and args.output == sys.stdout: raise ValueError('Cannot output to stdout if reading resources') from cnxepub.collation import reconstitute binder = reconstitute(args.collated_html) if args.dump_tree: print(pformat(cnxepub.model_to_tree(binder)), file=sys.stdout) if args.output: cnxepub.adapters.make_epub(binder, args.output) if args.input: args.output.seek(0) zout = ZipFile(args.output, 'a', ZIP_DEFLATED) zin = ZipFile(args.input, 'r') for res in zin.namelist(): if res.startswith('resources'): zres = zin.open(res) zi = zin.getinfo(res) zout.writestr(zi, zres.read(), ZIP_DEFLATED) zout.close() # TODO Check for documents that have no identifier. # These should likely be composite-documents # or the the metadata got wiped out. # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter) # if x.ident_hash is None] return 0
def main(argv=None)
Parse passed in cooked single HTML.
4.217336
4.088513
1.031508
hex_number = int(hex_str, 16) # Create embed UI object gui = ui_embed.UI( channel, "", "#{}".format(hex_str), modulename=modulename, colour=hex_number, thumbnail=image, ) return gui
def success(channel, image, hex_str)
Creates an embed UI containing a hex color message Args: channel (discord.Channel): The Discord channel to bind the embed to image (str): The url of the image to add hex_str (str): The hex value Returns: ui (ui_embed.UI): The embed UI object that was created
9.129038
5.754333
1.586463
if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
def add_md(text, s, level=0)
Adds text to the readme at the given level
3.02318
2.813849
1.074393
text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
def add_ul(text, ul)
Adds an unordered list to the readme
2.959753
2.910642
1.016873
d = {} nums = ['1', '2', '3', '4', '5', '6'] num_counter = 0 for k, date_dict in editions.items(): d['edition%s' % nums[num_counter]] = k if date_dict['start'] is not None: d['start_e%s' % nums[num_counter]] = date_dict['start'].isoformat() if date_dict['end'] is not None: d['end_e%s' % nums[num_counter]] = date_dict['end'].isoformat() num_counter += 1 return d
def make_editions_dict(editions)
Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter.
2.304765
2.245586
1.026354
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Commands section prefix = data["discord"]["servers"][server.id]["prefix"] if content.startswith(prefix): # Parse message package = content.split(" ") command = package[0][len(prefix):] args = package[1:] alias_steam = ["steam", "pc"] alias_ps = ["ps", "psn", "playstation", "ps4", "playstation 4"] alias_xbox = ["xbox", "xb", "xb1", "xbone", "xbox one", "xbox one"] platform = "steam" if len(args) > 0: player_name = args[0] else: return if len(args) > 1: platform = ' '.join(args[1:]).lower() if platform in alias_steam: platform = "steam" elif platform in alias_ps: platform = "ps" elif platform in alias_xbox: platform = "xbox" # Commands if command == 'rlstats': await client.send_typing(channel) # Get Rocket League stats from stats API success, rldata = api_rocketleaguestats.check_rank(player_name, platform) # Create embed UI if success: embed = ui_embed.success(channel, rldata[0], rldata[1], rldata[2], rldata[3]) else: embed = ui_embed.fail_api(channel) await embed.send()
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.761753
3.748638
1.003499
from ...main import add_api_key add_api_key("google_api_key", self.google_api_key.get()) add_api_key("soundcloud_client_id", self.soundcloud_client_id.get())
def update_keys(self)
Updates the Google API key with the text value
4.257895
3.486625
1.221208
# Create embed UI object gui = ui_embed.UI( channel, "{} updated".format(module_name), "{} is now {}".format(module_name, "activated" if module_state else "deactivated"), modulename=modulename ) return gui
def modify_module(channel, module_name, module_state)
Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed
6.691116
5.38261
1.243099
# Create embed UI object gui = ui_embed.UI( channel, "Prefix updated", "Modis prefix is now `{}`".format(new_prefix), modulename=modulename ) return gui
def modify_prefix(channel, new_prefix)
Creates an embed UI containing the prefix modified message Args: channel (discord.Channel): The Discord channel to bind the embed to new_prefix (str): The value of the new prefix Returns: embed: The created embed
12.592265
10.677318
1.179347
username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick warning_count_text = "warnings" if warnings != 1 else "warning" warning_text = "{} {}".format(warnings, warning_count_text) result_text = "at {} you will be banned".format(max_warnings) if warnings >= max_warnings: result_text = "you are being banned because you have more than the maximum warnings" # Create embed UI object gui = ui_embed.UI( channel, "Warning {}".format(username), "You now have {} {}, {}".format(warning_text, username, result_text), modulename=modulename ) return gui
def user_warning(channel, user, warnings, max_warnings)
Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to warn warnings (str): The warnings for the user max_warnings (str): The maximum warnings for the user Returns: ui (ui_embed.UI): The embed UI object
4.754348
4.001694
1.188084
username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick # Create embed UI object gui = ui_embed.UI( channel, "Banned {}".format(username), "{} has been banned from this server".format(username), modulename=modulename ) return gui
def user_ban(channel, user)
Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to ban Returns: ui (ui_embed.UI): The embed UI object
5.515864
3.925706
1.405063
# Create embed UI object gui = ui_embed.UI( channel, "Maximum Warnings Changed", "Users must now have {} warnings to be banned " "(this won't ban existing users with warnings)".format(max_warnings), modulename=modulename ) return gui
def warning_max_changed(channel, max_warnings)
Creates an embed UI containing an error message Args: channel (discord.Channel): The Discord channel to bind the embed to max_warnings (int): The new maximum warnings Returns: ui (ui_embed.UI): The embed UI object
14.639746
9.026434
1.621875
# Create embed UI object gui = ui_embed.UI( channel, title, description, modulename=modulename ) return gui
def error(channel, title, description)
Creates an embed UI containing an error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed description (str): The description for the error Returns: ui (ui_embed.UI): The embed UI object
13.479514
7.509982
1.79488
data = datatools.get_data() # Add the server to server data if it doesn't yet exist send_welcome_message = False if server.id not in data["discord"]["servers"]: logger.debug("Adding new server to serverdata") data["discord"]["servers"][server.id] = {"prefix": "!"} if "mute_intro" not in data or not data["mute_intro"]: send_welcome_message = True # Make sure all modules are in the server _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) for module_name in os.listdir(_dir_modules): if module_name.startswith("_") or module_name.startswith("!"): continue if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)): logger.warning("No _data.py file found for module {}".format(module_name)) continue try: import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data") _data = importlib.import_module(import_name, "modis") if _data.modulename not in data["discord"]["servers"][server.id]: data["discord"]["servers"][server.id][_data.modulename] = _data.sd_structure datatools.write_data(data) except Exception as e: logger.error("Could not initialise module {}".format(module_name)) logger.exception(e) datatools.write_data(data) # Send a welcome message now if send_welcome_message: default_channel = server.default_channel if not default_channel: for channel in server.channels: if channel.name == "general": default_channel = channel break if not default_channel: for channel in server.channels: if "general" in channel.name: default_channel = channel break if not default_channel: for channel in server.channels: if channel.type == discord.ChannelType.text: default_channel = channel break # Display a welcome message if default_channel: hello_message = "Hello! I'm Modis.\n\n" + \ "The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \ "You can use `!help` to get help commands for all modules, " + \ "or {} me to get the server prefix and help commands.".format(server.me.mention) await client.send_message(default_channel, hello_message)
async def update_server_data(server)
Updates the server info for the given server Args: server: The Discord server to update info for
2.954366
2.967388
0.995611
logger.debug("Removing server from serverdata") # Remove the server from data data = datatools.get_data() if server_id in data["discord"]["servers"]: data["discord"]["servers"].pop(server_id) datatools.write_data(data)
def remove_server_data(server_id)
Remove a server from the server data Args: server_id (int): The server to remove from the server data
4.058723
3.891347
1.043012
data = datatools.get_data() for server_id in data["discord"]["servers"]: is_in_client = False for client_server in client.servers: if server_id == client_server.id: is_in_client = True break if not is_in_client: remove_server_data(server_id)
def check_all_servers()
Checks all servers, removing any that Modis isn't part of any more
3.517548
3.227755
1.089782
for child in self.module_selection.winfo_children(): child.destroy() self.clear_ui() tk.Label(self.module_ui, text="Start Modis and select a module").grid( column=0, row=0, padx=0, pady=0, sticky="W E N S") if self.current_button is not None: self.current_button.config(bg="white") self.module_buttons = {} self.current_button = None
def clear_modules(self)
Clears all modules from the list
4.736226
4.670494
1.014074
m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w") m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S") self.module_buttons[module_name] = m_button m_button.bind("<Button-1>", lambda e: self.module_selected(module_name, module_ui))
def add_module(self, module_name, module_ui)
Adds a module to the list Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
2.661449
2.891927
0.920303
if self.current_button == self.module_buttons[module_name]: return self.module_buttons[module_name].config(bg="#cacaca") if self.current_button is not None: self.current_button.config(bg="white") self.current_button = self.module_buttons[module_name] self.clear_ui() try: # Create the UI module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui) module_ui_frame.grid(column=0, row=0, sticky="W E N S") except Exception as e: logger.error("Could not load UI for {}".format(module_name)) logger.exception(e) # Create a error UI tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid( column=0, row=0, padx=0, pady=0, sticky="W E N S")
def module_selected(self, module_name, module_ui)
Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
2.57184
2.632182
0.977075
if self.state == 'off': self.start(discord_token, discord_client_id) elif self.state == 'on': self.stop()
def toggle(self, discord_token, discord_client_id)
Toggles Modis on or off
2.492804
2.351469
1.060105
self.button_toggle_text.set("Stop Modis") self.state = "on" self.status_bar.set_status(1) logger.info("----------------STARTING DISCORD MODIS----------------") # Clear the module list self.module_frame.clear_modules() # Start Modis from modis.discord_modis import main logger.debug("Creating event loop") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.discord_thread = threading.Thread( target=main.start, args=[discord_token, discord_client_id, loop, self.on_ready]) logger.debug("Starting event loop") self.discord_thread.start() # Find module UIs database_dir = "{}/modules".format( os.path.dirname(os.path.realpath(__file__))) for module_name in os.listdir(database_dir): module_dir = "{}/{}".format(database_dir, module_name) # Iterate through files in module if os.path.isdir(module_dir) and not module_name.startswith("_"): # Add all defined event handlers in module files module_event_handlers = os.listdir(module_dir) if "_ui.py" in module_event_handlers: import_name = ".discord_modis.modules.{}.{}".format( module_name, "_ui") logger.debug( "Found module UI file {}".format(import_name[23:])) self.module_frame.add_module(module_name, importlib.import_module(import_name, "modis")) else: self.module_frame.add_module(module_name, None)
def start(self, discord_token, discord_client_id)
Start Modis and log it into Discord.
3.559962
3.352429
1.061905
self.button_toggle_text.set("Start Modis") self.state = "off" logger.info("Stopping Discord Modis") from ._client import client asyncio.run_coroutine_threadsafe(client.logout(), client.loop) self.status_bar.set_status(0)
def stop(self)
Stop Modis and log it out of Discord.
9.631688
6.270966
1.535918
if self.key_name.get() and self.key_val.get(): self.button_key_add.state(["!disabled"]) else: self.button_key_add.state(["disabled"])
def key_changed(self)
Checks if the key name and value fields have been set, and updates the add key button
3.209743
2.25257
1.424925
from .main import add_api_key add_api_key(self.key_name.get(), self.key_val.get()) # Clear the text fields self.key_name.set("") self.key_val.set("")
def key_add(self)
Adds the current API key to the bot's data
4.021824
3.809076
1.055853
text = "" colour = "#FFFFFF" if status == 0: text = "OFFLINE" colour = "#EF9A9A" elif status == 1: text = "STARTING" colour = "#FFE082" elif status == 2: text = "ONLINE" colour = "#A5D6A7" self.status.set(text) self.statusbar.config(background=colour)
def set_status(self, status)
Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online
2.946585
2.622724
1.123483
try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=OrderedDict) except Exception as e: logger.error("Could not load file {}".format(filepath)) logger.exception(e) return {}
def get_help_data(filepath)
Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file
2.656391
2.858773
0.929207
help_contents = get_help_data(filepath) datapacks = [] # Add the content for d in help_contents: heading = d content = "" if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue content += "- `" command = prefix + c["name"] content += "{}".format(command) if "params" in c: for param in c["params"]: content += " [{}]".format(param) content += "`: " if "description" in c: content += c["description"] content += "\n" else: content += help_contents[d] datapacks.append((heading, content, False)) return datapacks
def get_help_datapacks(filepath, prefix="!")
Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file
2.975983
3.113802
0.955739
import tkinter as tk import tkinter.ttk as ttk help_contents = get_help_data(filepath) text = tk.Text(parent, wrap='word', font=("Helvetica", 10)) text.grid(row=0, column=0, sticky="W E N S") text.tag_config("heading", font=("Helvetica", 14)) text.tag_config("command", font=("Courier", 10)) text.tag_config("param", font=("Courier", 10)) text.tag_config("description") # Vertical Scrollbar scrollbar = ttk.Scrollbar(parent, orient="vertical", command=text.yview) scrollbar.grid(column=1, row=0, sticky="N S") text['yscrollcommand'] = scrollbar.set # Add the content for d in help_contents: text.insert('end', d, "heading") text.insert('end', '\n') if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue command = prefix + c["name"] text.insert('end', command, ("command", "description")) if "params" in c: for param in c["params"]: text.insert('end', " [{}]".format(param), ("param", "description")) text.insert('end', ": ") if "description" in c: text.insert('end', c["description"], "description") text.insert('end', '\n') text.insert('end', '\n') else: text.insert('end', help_contents[d], "description") text.insert('end', '\n\n') text.config(state=tk.DISABLED)
def add_help_text(parent, filepath, prefix="!")
Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands
2.112089
2.082919
1.014004
# Simplify reaction info server = reaction.message.server emoji = reaction.emoji data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Commands section if user != reaction.message.channel.server.me: if server.id not in _data.cache or _data.cache[server.id].state == 'destroyed': return try: valid_reaction = reaction.message.id == _data.cache[server.id].embed.sent_embed.id except AttributeError: pass else: if valid_reaction: # Remove reaction try: await client.remove_reaction(reaction.message, emoji, user) except discord.errors.NotFound: pass except discord.errors.Forbidden: pass # Commands if emoji == "⏯": await _data.cache[server.id].toggle() if emoji == "⏹": await _data.cache[server.id].stop() if emoji == "⏭": await _data.cache[server.id].skip("1") if emoji == "⏮": await _data.cache[server.id].rewind("1") if emoji == "🔀": await _data.cache[server.id].shuffle() if emoji == "🔉": await _data.cache[server.id].setvolume('-') if emoji == "🔊": await _data.cache[server.id].setvolume('+')
async def on_reaction_add(reaction, user)
The on_message event handler for this module Args: reaction (discord.Reaction): Input reaction user (discord.User): The user that added the reaction
2.951065
2.965164
0.995245
state, response = datatools.get_compare_version() logger.info("Starting Modis in console") logger.info(response) import threading import asyncio logger.debug("Loading packages") from modis.discord_modis import main as discord_modis_console from modis.reddit_modis import main as reddit_modis_console from modis.facebook_modis import main as facebook_modis_console # Create threads logger.debug("Initiating threads") loop = asyncio.get_event_loop() discord_thread = threading.Thread( target=discord_modis_console.start, args=[discord_token, discord_client_id, loop]) reddit_thread = threading.Thread( target=reddit_modis_console.start, args=[]) facebook_thread = threading.Thread( target=facebook_modis_console.start, args=[]) # Run threads logger.debug("Starting threads") discord_thread.start() reddit_thread.start() facebook_thread.start() logger.debug("Root startup completed")
def console(discord_token, discord_client_id)
Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
2.95826
2.70462
1.09378
logger.info("Starting Modis in GUI") import tkinter as tk logger.debug("Loading packages") from modis.discord_modis import gui as discord_modis_gui from modis.reddit_modis import gui as reddit_modis_gui from modis.facebook_modis import gui as facebook_modis_gui logger.debug("Initialising window") # Setup the root window root = tk.Tk() root.minsize(width=800, height=400) root.geometry("800x600") root.title("Modis Control Panel") # Icon root.iconbitmap(r"{}/assets/modis.ico".format(file_dir)) # Setup the notebook discord = discord_modis_gui.Frame(root, discord_token, discord_client_id) discord.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S") # Configure stretch ratios root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) discord.columnconfigure(0, weight=1) discord.rowconfigure(0, weight=1) logger.debug("GUI initialised") # Run the window UI root.mainloop()
def gui(discord_token, discord_client_id)
Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
3.125327
2.900995
1.077329
sorted_dict = sort_recursive(data) with open(_datafile, 'w') as file: _json.dump(sorted_dict, file, indent=2)
def write_data(data)
Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis
6.259609
5.985445
1.045805
newdict = {} for i in data.items(): if type(i[1]) is dict: newdict[i[0]] = sort_recursive(i[1]) else: newdict[i[0]] = i[1] return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))
def sort_recursive(data)
Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict
2.470296
2.526881
0.977607
state, latest_version = compare_latest_version() if state < 0: return -1, "A new version of Modis is available (v{})".format(latest_version) elif state == 0: return 0, "You are running the latest version of Modis (v{})".format(version) else: return 1, "You are running a preview version of Modis (v{} pre-release)".format(version)
def get_compare_version()
Get the version comparison info. Returns: (tuple) state (int): -1 for lower version, 0 for same version, 1 for higher version than latest. response (str): The response string.
3.523472
3.207631
1.098466
# Create datapacks datapacks = [("Platform", platform, False)] for stat in stats: # Add stats if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"): stat_name = "__" + stat[0] + "__" stat_value = "**" + stat[1] + "**" else: stat_name = stat[0] stat_value = stat[1] # Add percentile if it exists if stat[2]: stat_value += " *(Top " + stat[2] + "%)*" datapacks.append((stat_name, stat_value, True)) # Create embed UI object gui = ui_embed.UI( channel, "Rocket League Stats: {}".format(name), "*Stats obtained from [Rocket League Tracker Network](https://rocketleague.tracker.network/)*", modulename=modulename, colour=0x0088FF, thumbnail=dp, datapacks=datapacks ) return gui
def success(channel, stats, name, platform, dp)
Creates an embed UI containing the Rocket League stats Args: channel (discord.Channel): The Discord channel to bind the embed to stats (tuple): Tuples of (field, value, percentile) name (str): The name of the player platform (str): The playfor to search on, can be 'steam', 'ps', or 'xbox' dp (str): URL to the player's dp Returns: (discord.Embed): The created embed
4.953006
4.310205
1.149135
gui = ui_embed.UI( channel, "That SteamID doesn't exist.", "You can get your SteamID by going to your profile page and looking at the url, " "or you can set a custom ID by going to edit profile on your profile page.", modulename=modulename, colour=0x0088FF ) return gui
def fail_steamid(channel)
Creates an embed UI for invalid SteamIDs Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
10.1432
8.153712
1.243998
gui = ui_embed.UI( channel, "Couldn't get stats off RLTrackerNetwork.", "Maybe the API changed, please tell Infraxion.", modulename=modulename, colour=0x0088FF ) return gui
def fail_api(channel)
Creates an embed UI for when the API call didn't work Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
33.339447
22.722794
1.467225
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Commands section prefix = data["discord"]["servers"][server.id]["prefix"] if content.startswith(prefix): # Parse message package = content.split(" ") command = package[0][len(prefix):] args = package[1:] arg = ' '.join(args) # Commands if command == 'hex': await client.send_typing(channel) # Parse message hex_strs = api_hexconvert.convert_hex_value(arg) # Create embed UI if len(hex_strs) > 0: for hex_str in hex_strs: image_url = convert_hex_to_url(hex_str) embed = ui_embed.success(channel, image_url, hex_str) await embed.send() else: embed = ui_embed.fail_api(channel) await embed.send() else: # Parse message hex_strs = api_hexconvert.convert_hex_value(content) # Create embed UI if len(hex_strs) > 0: for hex_str in hex_strs: await client.send_typing(channel) image_url = convert_hex_to_url(hex_str) embed = ui_embed.success(channel, image_url, hex_str) await embed.send()
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.23225
3.211288
1.006528
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Commands section prefix = data["discord"]["servers"][server.id]["prefix"] if content.startswith(prefix): # Parse message package = content.split(" ") command = package[0][len(prefix):] # Commands if command == 'gamedeals': await client.send_typing(channel) # Get posts from Reddit API posts = api_reddit.get_top10() if posts: for post in posts: # Create embed UI embed = ui_embed.success(channel, post) await embed.send() else: embed = ui_embed.no_results(channel) await embed.send()
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
5.184668
5.143788
1.007947
# Create datapacks datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)] # Create embed UI object gui = ui_embed.UI( channel, "Link", post[1], modulename=modulename, colour=0xFF8800, thumbnail=post[1], datapacks=datapacks ) return gui
def success(channel, post)
Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns:
8.968092
7.626122
1.17597
gui = ui_embed.UI( channel, "No results", ":c", modulename=modulename, colour=0xFF8800 ) return gui
def no_results(channel)
Creates an embed UI for when there were no results Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
17.130762
11.555493
1.482478
duration_string = api_music.duration_to_string(duration) if duration <= 0: return "---" time_counts = int(round((progress / duration) * TIMEBAR_LENGTH)) if time_counts > TIMEBAR_LENGTH: time_counts = TIMEBAR_LENGTH if duration > 0: bar = "│" + (TIMEBAR_PCHAR * time_counts) + (TIMEBAR_ECHAR * (TIMEBAR_LENGTH - time_counts)) + "│" time_bar = "{} {}".format(bar, duration_string) else: time_bar = duration_string return time_bar
def make_timebar(progress=0, duration=0)
Makes a new time bar string Args: progress: How far through the current song we are (in seconds) duration: The duration of the current song (in seconds) Returns: timebar (str): The time bar string
3.276514
3.542698
0.924864
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Only reply to mentions if channel.server.me in message.mentions: logger.info("Bot was mentioned, summoning Mitsuku") await client.send_typing(channel) # Get new botcust2 from Mitsuku if does not exist for channel in serverdata if channel.id not in data["discord"]["servers"][server.id][_data.modulename]["channels"]: new_serverdata = data new_serverdata["discord"]["servers"][server.id][_data.modulename]["channels"][channel.id] = \ api_mitsuku.get_botcust2() datatools.write_data(new_serverdata) # Get botcust2 from serverdata botcust2 = data["discord"]["servers"][server.id][_data.modulename]["channels"][channel.id] # Remove mention from message content so Mitsuku doesn't see it content = content.replace("<@{}>".format(str(channel.server.me.id)), ' ') content = content.replace("<@!{}>".format(str(channel.server.me.id)), ' ') # Send Mitsuku's reply if botcust2: response = api_mitsuku.query(botcust2, content) if response: await client.send_message(channel, response) else: await client.send_message(channel, "```Couldn't get readable response from Mitsuku.```") else: await client.send_message(channel, "```Couldn't initialise with Mitsuku.```")
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.468103
3.440303
1.008081
if self.colour: embed = discord.Embed( title=self.title, type='rich', description=self.description, colour=self.colour) else: embed = discord.Embed( title=self.title, type='rich', description=self.description) if self.thumbnail: embed.set_thumbnail(url=self.thumbnail) if self.image: embed.set_image(url=self.image) embed.set_author( name="Modis", url="https://musicbyango.com/modis/", icon_url="http://musicbyango.com/modis/dp/modis64t.png") for pack in self.datapacks: embed.add_field( name=pack[0], value=pack[1], inline=pack[2] ) return embed
def build(self)
Builds Discord embed GUI Returns: discord.Embed: Built GUI
2.828333
2.67601
1.056922
await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
async def send(self)
Send new GUI
5.883445
5.287488
1.112711
datapack = self.built_embed.to_dict()["fields"][index] self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])
def update_data(self, index, data)
Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack
5.322135
5.177539
1.027928
variations_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for variation_key, variation_value in data["variations"].items(): try: variations_list = variations_out[variation_key] if variation_value not in variations_list: variations_list.append(variation_value) except KeyError: # The item wasn't there; add it. variations_out[variation_key] = [variation_value] return variations_out
def suck_out_variations_only(reporters)
Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possibly referring to.
3.02415
3.175874
0.952226
editions_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for edition_key, edition_value in data["editions"].items(): try: editions_out[edition_key] except KeyError: # The item wasn't there; add it. editions_out[edition_key] = reporter_key return editions_out
def suck_out_editions(reporters)
Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key.
3.582977
3.423826
1.046483
names = {} for reporter_key, data_list in reporters.items(): for data in data_list: abbrevs = data['editions'].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data['editions'][x]['start']) + x abbrevs = sorted(abbrevs, key=sort_func) names[data['name']] = abbrevs sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0])) return sorted_names
def names_to_abbreviations(reporters)
Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date.
3.393392
3.288722
1.031827
# Get player ID and name Rocket League Tracker Network webpage = requests.get( "https://rocketleague.tracker.network/profile/{}/{}".format(platform, player) ).text try: # Get player ID playerid_index = webpage.index("/live?ids=") + len("/live?ids=") playerid_end_index = webpage.index(, playerid_index) playerid = webpage[playerid_index:playerid_end_index] # Get player name name_index = webpage.index("Stats Profile : ") + len("Stats Profile : ") name_end_index = webpage.index(, name_index) name = webpage[name_index:name_end_index] except (ValueError, IndexError): return False, () # Get player stats from Rocket League Tracker Network livedata = json.loads( requests.post( "https://rocketleague.tracker.network/live/data", json={"playerIds": [playerid]} ).text ) stats = [] try: for statpack in livedata['players'][0]['Stats']: field = statpack['Value']['Label'] value = str(statpack['Value']['DisplayValue']) if statpack['Value']['Percentile']: percentile = str(statpack['Value']['Percentile']) else: percentile = None stats.append((field, value, percentile)) except (IndexError, KeyError): return False, () dp = "https://rocketleague.media.zestyio.com/rocket-league-logos-vr-white.f1cb27a519bdb5b6ed34049a5b86e317.png" platform_display = platform if platform == "steam": platform_display = "Steam" elif platform == "ps": platform_display = "PlayStation" elif platform == "xbox": platform_display = "Xbox" return True, (stats, name, platform_display, dp)
def check_rank(player, platform="steam")
Gets the Rocket League stats and name and dp of a UserID Args: player (str): The UserID of the player we want to rank check platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox' Returns: success (bool): Whether the rank check was successful package (tuple): If successful, the retrieved stats, in order (stats, name, dp)
3.833692
3.563154
1.075927
channel = client.get_channel(channel_id) if channel is None: logger.info("{} is not a channel".format(channel_id)) return # Check that it's enabled in the server data = datatools.get_data() if not data["discord"]["servers"][channel.server.id][modulename]["activated"]: logger.info("This module has been disabled in {} ({})".format(channel.server.name, channel.server.id)) try: runcoro(client.send_message(channel, message)) except Exception as e: logger.exception(e)
def send_message(channel_id, message)
Send a message to a channel Args: channel_id (str): The id of the channel to send the message to message (str): The message to send to the channel
4.161166
4.293518
0.969174
future = _asyncio.run_coroutine_threadsafe(async_function, client.loop) result = future.result() return result
def runcoro(async_function)
Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run
4.82528
5.249746
0.919145
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Do a flip check flipchecked = api_flipcheck.flipcheck(content) if flipchecked: await client.send_typing(channel) await client.send_message(channel, flipchecked)
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
5.813117
5.698864
1.020048
from ...main import add_api_key add_api_key("reddit_api_user_agent", self.reddit_api_user_agent.get()) add_api_key("reddit_api_client_id", self.reddit_api_client_id.get()) add_api_key("reddit_api_client_secret", self.reddit_api_client_secret.get())
def update_keys(self)
Updates the Google API key with the text value
2.716383
2.493923
1.089201
data = datatools.get_data() server_id = channel.server.id _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)): await client.send_typing(channel) embed = ui_embed.error(channel, "Error", "No module found named '{}'".format(module_name)) await embed.send() return try: import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data") module_data = importlib.import_module(import_name, "modis") # Don't try and deactivate this module (not that it would do anything) if module_data.modulename == _data.modulename: await client.send_typing(channel) embed = ui_embed.error(channel, "Error", "I'm sorry, Dave. I'm afraid I can't do that.") await embed.send() return # This /should/ never happen if everything goes well if module_data.modulename not in data["discord"]["servers"][server_id]: await client.send_typing(channel) embed = ui_embed.error(channel, "Error", "No data found for module '{}'".format(module_data.modulename)) await embed.send() return # Modify the module if "activated" in data["discord"]["servers"][server_id][module_data.modulename]: data["discord"]["servers"][server_id][module_data.modulename]["activated"] = activate # Write the data datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.modify_module(channel, module_data.modulename, activate) await embed.send() return else: await client.send_typing(channel) embed = ui_embed.error(channel, "Error", "Can't deactivate module '{}'".format(module_data.modulename)) await embed.send() return except Exception as e: logger.error("Could not modify module {}".format(module_name)) logger.exception(e)
async def activate_module(channel, module_name, activate)
Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module
2.686509
2.632733
1.020426
data = datatools.get_data() server_id = channel.server.id if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3 if "warnings" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings"] = {} if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] += 1 else: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 1 datatools.write_data(data) warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] max_warnings = data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] await client.send_typing(channel) embed = ui_embed.user_warning(channel, user, warnings, max_warnings) await embed.send() if warnings >= max_warnings: await ban_user(channel, user)
async def warn_user(channel, user)
Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to
2.016828
1.962819
1.027516
data = datatools.get_data() server_id = channel.server.id try: await client.ban(user) except discord.errors.Forbidden: await client.send_typing(channel) embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.") await embed.send() return # Set the user's warnings to 0 if "warnings" in data["discord"]["servers"][server_id][_data.modulename]: if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]: data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 0 datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.user_ban(channel, user) await embed.send() try: response = "You have been banned from the server '{}' " \ "contact the owners to resolve this issue.".format(channel.server.name) await client.send_message(user, response) except Exception as e: logger.exception(e)
async def ban_user(channel, user)
Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to
3.105301
3.071017
1.011164
_dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) module_dir = "{}/../{}".format(_dir, module_name, "_help.json") if os.path.isdir(module_dir): module_help_path = "{}/{}".format(module_dir, "_help.json") if os.path.isfile(module_help_path): return helptools.get_help_datapacks(module_help_path, server_prefix) else: return [("Help", "{} does not have a help.json file".format(module_name), False)] else: return [("Help", "No module found called {}".format(module_name), False)]
def get_help_datapacks(module_name, server_prefix)
Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module
2.84214
2.831522
1.00375
datapacks = [] _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) for module_name in os.listdir("{}/../".format(_dir)): if not module_name.startswith("_") and not module_name.startswith("!"): help_command = "`{}help {}`".format(server_prefix, module_name) datapacks.append((module_name, help_command, True)) return datapacks
def get_help_commands(server_prefix)
Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules
3.467795
3.090765
1.121986
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Commands section prefix = data["discord"]["servers"][server.id]["prefix"] if content.startswith(prefix): # Parse message package = content.split(" ") command = package[0][len(prefix):] args = package[1:] arg = ' '.join(args) # Commands if command == 'help': if args: # Parse message datapacks = api_help.get_help_datapacks(arg, prefix) # Create embed UI if datapacks: await client.send_typing(channel) embed = ui_embed.success(channel, arg, datapacks) try: await embed.send() except discord.errors.HTTPException: embed = ui_embed.http_exception(channel, arg) await embed.send() else: # Parse message datapacks = api_help.get_help_commands(prefix) # Create embed UI if datapacks: await client.send_typing(channel) embed = ui_embed.success(channel, arg, datapacks) try: await embed.send() except discord.errors.HTTPException: embed = ui_embed.http_exception(channel, arg) await embed.send()
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.011278
3.019016
0.997437
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: prefix = data["discord"]["servers"][server.id]["prefix"] # Check for mentions reply to mentions if channel.server.me in message.mentions: await client.send_typing(channel) response = "The current server prefix is `{0}`. Type `{0}help` for help.".format(prefix) await client.send_message(channel, response) # Commands section if content.startswith(prefix): # Parse message package = content.split(" ") command = package[0][len(prefix):] args = package[1:] arg = ' '.join(args) # Commands if command not in ["prefix", "activate", "deactivate", "warnmax", "warn", "ban"]: return is_admin = author == server.owner for role in message.author.roles: if role.permissions.administrator: is_admin = True if not is_admin: await client.send_typing(channel) reason = "You must have a role that has the permission 'Administrator'" embed = ui_embed.error(channel, "Insufficient Permissions", reason) await embed.send() return if command == "prefix" and args: new_prefix = arg.replace(" ", "").strip() data["discord"]["servers"][server.id]["prefix"] = new_prefix # Write the data datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.modify_prefix(channel, new_prefix) await embed.send() if command == "warnmax" and args: try: warn_max = int(arg) if warn_max > 0: data["discord"]["servers"][server.id][_data.modulename]["warnings_max"] = warn_max datatools.write_data(data) await client.send_typing(channel) embed = ui_embed.warning_max_changed(channel, warn_max) await embed.send() else: reason = "Maximum warnings must be greater than 0" embed = ui_embed.error(channel, "Error", reason) await embed.send() except (ValueError, TypeError): reason = "Warning maximum must be a number" embed = ui_embed.error(channel, "Error", reason) await embed.send() except Exception as e: logger.exception(e) if command == "warn" and args: for user in message.mentions: await api_manager.warn_user(channel, user) if command == "ban" and args: for user in message.mentions: await api_manager.ban_user(channel, user) if command == "activate" and args: await api_manager.activate_module(channel, arg, True) elif command == "deactivate" and args: await api_manager.activate_module(channel, arg, False)
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
2.641267
2.631391
1.003753
if topic_channel is not None: try: channel_message = "Topic channel is now `{}`.".format(topic_channel.name) except Exception as e: logger.exception(e) channel_message = "Topic channel has been updated." else: channel_message = "Topic channel has been cleared." # Create embed UI object gui = ui_embed.UI( channel, "Topic channel updated", channel_message, modulename=modulename, colour=modulecolor_info ) return gui
def topic_update(channel, topic_channel)
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed
5.420123
5.108436
1.061014
# Create embed UI object gui = ui_embed.UI( channel, err_title, err_message, modulename=modulename, colour=modulecolor_error ) return gui
def error_message(channel, err_title, err_message)
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to err_title: The title for the error err_message: The message for the error Returns: embed: The created embed
12.621381
11.911576
1.059589
logger.debug("Clearing root cache") if os.path.isdir(_root_songcache_dir): for filename in os.listdir(_root_songcache_dir): file_path = os.path.join(_root_songcache_dir, filename) try: if os.path.isfile(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except PermissionError: pass except Exception as e: logger.exception(e) logger.debug("Root cache cleared")
def clear_cache_root()
Clears everything in the song cache
2.004451
1.920916
1.043487
if self.state == 'off': self.state = 'starting' self.prev_queue = [] await self.set_topic("") # Init the music player await self.msetup(text_channel) # Queue the song await self.enqueue(query, index, stop_current, shuffle) # Connect to voice await self.vsetup(author) # Mark as 'ready' if everything is ok self.state = 'ready' if self.mready and self.vready else 'off' else: # Queue the song await self.enqueue(query, index, stop_current, shuffle) if self.state == 'ready': if self.streamer is None: await self.vplay()
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False)
The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end of the queue stop_current (bool): Whether to stop the currently playing song shuffle (bool): Whether to shuffle the queue after starting
4.422714
4.552378
0.971517
self.logger.debug("destroy command") self.state = 'destroyed' await self.set_topic("") self.nowplayinglog.debug("---") self.nowplayingauthorlog.debug("---") self.nowplayingsourcelog.debug("---") self.timelog.debug(_timebar.make_timebar()) self.prev_time = "---" self.statuslog.debug("Destroying") self.mready = False self.vready = False self.pause_time = None self.loop_type = 'off' if self.vclient: try: await self.vclient.disconnect() except Exception as e: logger.error(e) pass if self.streamer: try: self.streamer.stop() except: pass self.vclient = None self.vchannel = None self.streamer = None self.current_duration = 0 self.current_download_elapsed = 0 self.is_live = False self.queue = [] self.prev_queue = [] if self.embed: await self.embed.delete() self.embed = None self.clear_cache()
async def destroy(self)
Destroy the whole gui and music player
4.66751
4.398261
1.061217
self.logger.debug("toggle command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): await self.pause() else: await self.resume() except Exception as e: logger.error(e) pass
async def toggle(self)
Toggles between pause and resume command
4.346364
3.498307
1.242419
self.logger.debug("pause command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): self.streamer.pause() self.pause_time = self.vclient.loop.time() self.statuslog.info("Paused") except Exception as e: logger.error(e) pass
async def pause(self)
Pauses playback if playing
5.464334
4.838497
1.129345
self.logger.debug("resume command") if not self.state == 'ready': return if self.streamer is None: return try: if not self.streamer.is_playing(): play_state = "Streaming" if self.is_live else "Playing" self.statuslog.info(play_state) self.streamer.resume() if self.pause_time is not None: self.vclient_starttime += (self.vclient.loop.time() - self.pause_time) self.pause_time = None except Exception as e: logger.error(e) pass
async def resume(self)
Resumes playback if paused
5.098827
4.764505
1.070169
if not self.state == 'ready': logger.debug("Trying to skip from wrong state '{}'".format(self.state)) return if query == "": query = "1" elif query == "all": query = str(len(self.queue) + 1) try: num = int(query) except TypeError: self.statuslog.error("Skip argument must be a number") except ValueError: self.statuslog.error("Skip argument must be a number") else: self.statuslog.info("Skipping") for i in range(num - 1): if len(self.queue) > 0: self.prev_queue.append(self.queue.pop(0)) try: self.streamer.stop() except Exception as e: logger.exception(e)
async def skip(self, query="1")
The skip command Args: query (str): The number of items to skip
3.190114
3.210371
0.99369
if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.state)) return if index == "": self.statuslog.error("Must provide index to remove") return elif index == "all": self.queue = [] self.update_queue() self.statuslog.info("Removed all songs") return indexes = index.split("-") self.logger.debug("Removing {}".format(indexes)) try: if len(indexes) == 0: self.statuslog.error("Remove must specify an index or range") return elif len(indexes) == 1: num_lower = int(indexes[0]) - 1 num_upper = num_lower + 1 elif len(indexes) == 2: num_lower = int(indexes[0]) - 1 num_upper = int(indexes[1]) else: self.statuslog.error("Cannot have more than 2 indexes for remove range") return except TypeError: self.statuslog.error("Remove index must be a number") return except ValueError: self.statuslog.error("Remove index must be a number") return if num_lower < 0 or num_lower >= len(self.queue) or num_upper > len(self.queue): if len(self.queue) == 0: self.statuslog.warning("No songs in queue") elif len(self.queue) == 1: self.statuslog.error("Remove index must be 1 (only 1 song in queue)") else: self.statuslog.error("Remove index must be between 1 and {}".format(len(self.queue))) return if num_upper <= num_lower: self.statuslog.error("Second index in range must be greater than first") return lower_songname = self.queue[num_lower][1] for num in range(0, num_upper - num_lower): self.logger.debug("Removed {}".format(self.queue[num_lower][1])) self.queue.pop(num_lower) if len(indexes) == 1: self.statuslog.info("Removed {}".format(lower_songname)) else: self.statuslog.info("Removed songs {}-{}".format(num_lower + 1, num_upper)) self.update_queue()
async def remove(self, index="")
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
2.220737
2.17077
1.023018
if not self.state == 'ready': logger.debug("Trying to rewind from wrong state '{}'".format(self.state)) return if query == "": query = "1" try: num = int(query) except TypeError: self.statuslog.error("Rewind argument must be a number") except ValueError: self.statuslog.error("Rewind argument must be a number") else: if len(self.prev_queue) == 0: self.statuslog.error("No songs to rewind") return if num < 0: self.statuslog.error("Rewind must be postitive or 0") return elif num > len(self.prev_queue): self.statuslog.warning("Rewinding to start") else: self.statuslog.info("Rewinding") for i in range(num + 1): if len(self.prev_queue) > 0: self.queue.insert(0, self.prev_queue.pop()) try: self.streamer.stop() except Exception as e: logger.exception(e)
async def rewind(self, query="1")
The rewind command Args: query (str): The number of items to skip
2.711597
2.734034
0.991793