コード例 #1
0
 def get_scaling_state(self,
                       instance_id,
                       default=None,
                       meta=None,
                       default_date=None,
                       do_not_return_excluded=False):
     if meta is not None:
         for i in ["action", "draining", "error", "bounced"]:
             meta["last_%s_date" % i] = misc.str2utc(
                 self.get_state("ec2.instance.scaling.last_%s_date.%s" %
                                (i, instance_id),
                                default=self.context["now"]))
     r = self.get_state("ec2.instance.scaling.state.%s" % instance_id,
                        default=default)
     #Special case for 'excluded': We test it here so tags will override the value
     i = self.get_instance_by_id(instance_id)
     excluded_instances = Cfg.get_list("ec2.state.excluded_instance_ids",
                                       default=[])
     if (i is not None and not do_not_return_excluded
             and (self.instance_has_tag(
                 i, "clonesquad:excluded", value=["1", "True", "true"])
                  or i in excluded_instances
                  or self.is_static_subfleet_instance(instance_id))):
         r = "excluded"
     # Force error state for some VM (debug usage)
     error_instance_ids = Cfg.get_list("ec2.state.error_instance_ids",
                                       default=[])
     if instance_id in error_instance_ids:
         r = "error"
     return r
コード例 #2
0
def build(static_lib = False, shared_lib = False, options = '',
          crossbuild_options=True, libs = '', cflags = '', subdir = ''):
    if static_lib and shared_lib:
        raise ValueError('Both static_lib and shared_lib options are specified')

    build_dir = _add_subpath(_info.build_dir, subdir)
    all_options = [
        _find_configure(build_dir),
        '--prefix=' + cmdutil.to_unix_path(_info.install_dir)
    ]
    if toolchain.crossbuild and crossbuild_options:
        all_options.extend([
            '--build=' + toolchain.build_triplet,
            '--host=' + toolchain.host_triplet])
    if static_lib:
        all_options.extend(['--enable-static', '--disable-shared'])
    if shared_lib:
        all_options.extend(['--enable-shared', '--disable-static'])
    all_options.extend(options.split())
    all_options.extend(config.get_list('options'))
    all_options.extend(config.get_list(_info.name + '-options'))
    env = _build_configure_env(libs.split(), cflags.split())

    cmdutil.unix_exec('sh', all_options, work_dir=build_dir, extra_env=env)
    cmdutil.unix_make([], work_dir=build_dir)
    cmdutil.unix_make(['install'], work_dir=build_dir)
コード例 #3
0
def _build_configure_env(user_libs, user_cflags):
    paths = []
    libs = []
    cflags = []
    pkg_config_paths = []

    for dep_name in _info.dependency_map().iterkeys():
        if dep_name == _info.name:
            continue
        p = packageinfo.get(dep_name).install_dir
        bin_dir = path.join(p, 'bin')
        lib_dir = path.join(p, 'lib')
        include_dir = path.join(p, 'include')
        pkg_config_dir = path.join(p, 'lib', 'pkgconfig')

        if path.exists(bin_dir):
            paths.append(bin_dir)
        if path.exists(lib_dir):
            libs.append('-L' + cmdutil.to_unix_path(lib_dir))
        if path.exists(include_dir):
            cflags.append('-I' + cmdutil.to_unix_path(include_dir))
        if path.exists(pkg_config_dir):
            pkg_config_paths.append(cmdutil.to_unix_path(pkg_config_dir))

    env_libs = config.get_list('libs') + config.get_list(_info.name + '-libs')
    env_cflags = config.get_list('cflags') + config.get_list(_info.name + '-cflags')

    result_path = os.pathsep.join(paths)
    result_libs = ' '.join(libs + user_libs + env_libs)
    result_cflags = ' '.join(cflags + user_cflags + env_cflags)
    result_pkg_config_path = ':'.join(pkg_config_paths)

    result = {
        'PATH'            : result_path,
        'LIBS'            : result_libs,
        'CFLAGS'          : result_cflags,
        'CXXFLAGS'        : result_cflags,
        'PKG_CONFIG_PATH' : result_pkg_config_path,
    }

    if toolchain.crossbuild:
        pkg_config_libdir = path.join(toolchain.sysroot, 'lib', 'pkgconfig')
        result.update({
            'AR'      : toolchain.tool_name('ar'),
            'AS'      : toolchain.tool_name('as'),
            'CC'      : toolchain.tool_name('gcc'),
            'CXX'     : toolchain.tool_name('g++'),
            'LD'      : toolchain.tool_name('ld'),
            'NM'      : toolchain.tool_name('nm'),
            'DLLTOOL' : toolchain.tool_name('dlltool'),
            'OBJDUMP' : toolchain.tool_name('objdump'),
            'RANLIB'  : toolchain.tool_name('ranlib'),
            'STRIP'   : toolchain.tool_name('strip'),
            'WINRC'   : toolchain.tool_name('windres'),
            'PKG_CONFIG_LIBDIR' : cmdutil.to_unix_path(pkg_config_libdir)
        })

    return result
コード例 #4
0
def display_player_name(follow_id):
    """
    Displays the player's name in the player-name custom cvar. Censor if in the list of blacklisted words.
    """
    follow_player = STATE.get_player_by_id(follow_id)
    if follow_player is not None:
        player_name = follow_player.n
        display_name = player_name if player_name.strip(
        ) not in config.get_list('blacklist_names') else "*" * len(player_name)
コード例 #5
0
async def connect(ctx, author, args):
    ip = args[0]
    if ip.split(':')[0] not in config.get_list("whitelist_servers"):
        msg = f"Server \"{ip}\" is not whitelisted. Refusing connection."
        api.exec_command(
            f"cg_centertime 5;displaymessage 140 8 ^3{author} ^1{msg};")
        logging.info(msg)
        await ctx.channel.send(msg)
        return
    serverstate.connect(ip, author)
コード例 #6
0
def apply_whitelist(servers_data):
    """
    Applies the server ip whitelist to current server data object
    :param servers_data:
    :return:
    """
    from config import get_list
    filtered_server_data = dict()
    for sv_ip, sv_data in servers_data['active'].items():
        if sv_ip.split(':')[0] in get_list('whitelist_servers'):
            filtered_server_data[sv_ip] = sv_data
    return filtered_server_data
コード例 #7
0
async def gamma(ctx, author, args):
    whitelisted_twitch_users = config.get_list('whitelist_twitchusers')
    if USE_WHITELIST and author not in whitelisted_twitch_users and not ctx.author.is_mod:
        await ctx.channel.send(
            f"{author}, you do not have the correct permissions to use this command."
            f"If you wanna be whitelisted to use such a command, please contact neyo#0382 on discord."
        )
        return
    value = float(args[0])
    if 0.5 <= (value) <= 1.6:
        logging.info("i did it..")
        api.exec_command(f"r_gamma {value}")
        MapData.save(serverstate.STATE.mapname, 'gamma', value)
    else:
        await ctx.channel.send(
            f"{author}, the allowed values for gamma are 1.0-1.6")
コード例 #8
0
ファイル: plugin_control.py プロジェクト: sushi-irc/nigiri
def _find_module(filename):
	""" wrapper for imp.find_module.
		Searches for the module named after
		filename in the configured search
		path (tekka, plugin_dirs).
	"""
	# get the name of the module to search for
	name = strip_suffix(filename)

	mod_info = None
	try:
		mod_info = imp.find_module(
			name, config.get_list("nigiri","plugin_dirs",[]))

	except ImportError, e:
		print_error("Error while finding module for '%s'" % (filename))
		return None
コード例 #9
0
def _find_module(filename):
    """ wrapper for imp.find_module.
		Searches for the module named after
		filename in the configured search
		path (tekka, plugin_dirs).
	"""
    # get the name of the module to search for
    name = strip_suffix(filename)

    mod_info = None
    try:
        mod_info = imp.find_module(
            name, config.get_list("nigiri", "plugin_dirs", []))

    except ImportError, e:
        print_error("Error while finding module for '%s'" % (filename))
        return None
コード例 #10
0
async def picmip(ctx, author, args):
    whitelisted_twitch_users = config.get_list('whitelist_twitchusers')
    if USE_WHITELIST and author not in whitelisted_twitch_users and not ctx.author.is_mod:
        await ctx.channel.send(
            f"{author}, you do not have the correct permissions to use this command."
            f"If you wanna be whitelisted to use such a command, please contact neyo#0382 on discord."
        )
        return
    value = args[0]
    if value.isdigit() and (0 <= int(value) <= 6):
        logging.info("vid_restarting..")
        serverstate.VID_RESTARTING = True
        serverstate.PAUSE_STATE = True
        api.exec_command(f"r_picmip {value};vid_restart")
        MapData.save(serverstate.STATE.mapname, 'picmip', value)
    else:
        await ctx.channel.send(
            f"{author}, the allowed values for picmip are 0-5.")
コード例 #11
0
ファイル: signals.py プロジェクト: StephenMeansMe/nigiri
def is_highlighted(server, text):
    def has_highlight(text, needle):
        punctuation = string.punctuation + " \n\t"
        ln = len(needle)
        for line in text.split("\n"):
            line = line.lower()
            i = line.find(needle)
            if i >= 0:
                if (line[i - 1:i] in punctuation
                        and line[ln + i:ln + i + 1] in punctuation):
                    return True
        return False

    server_tab = main_window.find_server(server)
    highlightwords = config.get_list("chatting", "highlight_words", [])
    highlightwords.append(server_tab.get_nick())

    for word in highlightwords:
        if has_highlight(text, word):
            return True
    return False
コード例 #12
0
ファイル: signals.py プロジェクト: sushi-irc/nigiri
def is_highlighted (server, text):
	def has_highlight(text, needle):
		punctuation = string.punctuation + " \n\t"
		ln = len(needle)
		for line in text.split("\n"):
			line = line.lower()
			i = line.find(needle)
			if i >= 0:
				if (line[i-1:i] in punctuation
				and line[ln+i:ln+i+1] in punctuation):
					return True
		return False

	server_tab = main_window.find_server(server)
	highlightwords = config.get_list("chatting", "highlight_words", [])
	highlightwords.append(server_tab.get_nick())

	for word in highlightwords:
		if has_highlight(text, word):
			return True
	return False
コード例 #13
0
    def get_prerequisites(self):
        """ Gather instance status by calling SSM APIs.
        """
        if not Cfg.get_int("ssm.enable"):
            log.log(log.NOTICE, "SSM support is currently disabled. Set ssm.enable to 1 to enabled it.")
            return
        now       = self.context["now"]
        self.ttl  = Cfg.get_duration_secs("ssm.state.default_ttl")
        GroupName = self.context["GroupName"]

        misc.initialize_clients(["ssm"], self.context)
        client = self.context["ssm.client"]

        # Retrive all SSM maintenace windows applicable to this CloneSquad deployment
        mw_names = {
            "__globaldefault__": {},
            "__default__": {},
            "__main__": {},
            "__all__":  {}
        }

        fmt                              = self.context.copy()
        mw_names["__globaldefault__"]["Names"] = Cfg.get_list("ssm.feature.maintenance_window.global_defaults", fmt=fmt)
        mw_names["__default__"]["Names"] = Cfg.get_list("ssm.feature.maintenance_window.defaults", fmt=fmt)
        mw_names["__main__"]["Names"]    = Cfg.get_list("ssm.feature.maintenance_window.mainfleet.defaults", fmt=fmt)
        mw_names["__all__"]["Names"]     = Cfg.get_list("ssm.feature.maintenance_window.subfleet.__all__.defaults", fmt=fmt)

        all_mw_names = mw_names["__globaldefault__"]["Names"]
        all_mw_names.extend([ n for n in mw_names["__default__"]["Names"] if n not in all_mw_names])
        all_mw_names.extend([ n for n in mw_names["__main__"]["Names"] if n not in all_mw_names])
        all_mw_names.extend([ n for n in mw_names["__all__"]["Names"] if n not in all_mw_names])

        Cfg.register({
                f"ssm.feature.maintenance_window.subfleet.__all__.force_running":
                    Cfg.get("ssm.feature.maintenance_window.subfleet.{SubfleetName}.force_running"),
                f"ssm.feature.events.ec2.scaling_state_changes.draining.__main__.connection_refused_tcp_ports": 
                    Cfg.get("ssm.feature.events.ec2.scaling_state_changes.draining.connection_refused_tcp_ports")
            })

        for SubfleetName in self.o_ec2.get_subfleet_names():
            fmt["SubfleetName"] = SubfleetName
            mw_names[f"Subfleet.{SubfleetName}"] = {}
            Cfg.register({
                f"ssm.feature.maintenance_window.subfleet.{SubfleetName}.defaults": Cfg.get("ssm.feature.maintenance_window.subfleet.{SubfleetName}.defaults"),
                f"ssm.feature.maintenance_window.subfleet.{SubfleetName}.ec2.schedule.min_instance_count": 
                    Cfg.get("ssm.feature.maintenance_window.subfleet.{SubfleetName}.ec2.schedule.min_instance_count"),
                f"ssm.feature.maintenance_window.subfleet.{SubfleetName}.force_running":
                    Cfg.get("ssm.feature.maintenance_window.subfleet.{SubfleetName}.force_running"),
                f"ssm.feature.events.ec2.scaling_state_changes.draining.{SubfleetName}.connection_refused_tcp_ports": 
                    Cfg.get("ssm.feature.events.ec2.scaling_state_changes.draining.connection_refused_tcp_ports")
            })
            mw_names[f"Subfleet.{SubfleetName}"]["Names"] = Cfg.get_list(f"ssm.feature.maintenance_window.subfleet.{SubfleetName}.defaults", fmt=fmt)
            all_mw_names.extend([ n for n in mw_names[f"Subfleet.{SubfleetName}"]["Names"] if n not in all_mw_names])


        names = all_mw_names
        mws   = []
        while len(names):
            paginator = client.get_paginator('describe_maintenance_windows')
            response_iterator = paginator.paginate(
                Filters=[
                    {
                        'Key': 'Name',
                        'Values': names[:20]
                    },
                ])
            for r in response_iterator:
                for wi in r["WindowIdentities"]:
                    if not wi["Enabled"]:
                        log.log(log.NOTICE, f"SSM Maintenance Window '%s' not enabled. Ignored..." % wi["Name"])
                        continue
                    if "NextExecutionTime" not in wi:
                        log.log(log.NOTICE, f"/!\ SSM Maintenance Window '%s' without 'NextExecutionTime'." % wi["Name"])
                    if wi not in mws:
                        mws.append(wi)
            names = names[20:]
        # Make string dates as object dates
        for d in mws:
            if "NextExecutionTime" in d:
                d["NextExecutionTime"] = misc.str2utc(d["NextExecutionTime"])

        # Retrieve Maintenace Window tags with the resourcegroup API
        tagged_mws = self.context["o_state"].get_resources(service="ssm", resource_name="maintenancewindow")
        for tmw in tagged_mws:
            mw_id = tmw["ResourceARN"].split("/")[1]
            mw = next(filter(lambda w: w["WindowId"] == mw_id, mws), None)
            if mw:
                mw["Tags"] = tmw["Tags"]
        valid_mws = []
        for mw in mws:
            mw_id=mw["WindowId"]
            if "Tags" not in mw:
                try:
                    response   = client.list_tags_for_resource(ResourceType='MaintenanceWindow', ResourceId=mw_id)
                    mw["Tags"] = response['TagList'] if 'TagList' in response else []
                except Exception as e:
                    log.error(f"Failed to fetch Tags for MaintenanceWindow '{mw_id}'")
            if ("Tags" not in mw or not len(mw["Tags"])) and mw["Name"] not in mw_names["__globaldefault__"]["Names"]:
                log.warning(f"Please tag SSM Maintenance Window '%s/%s' with 'clonesquad:group-name': '%s'!" %
                        (mw["Name"], mw["WindowId"], self.context["GroupName"]))
                continue
            valid_mws.append(mw)
        
        self.maintenance_windows = {
            "Names": mw_names,
            "Windows": valid_mws
        }

        # Update asynchronous results from previously launched commands
        self.update_pending_command_statuses()

        # Perform maintenance window house keeping
        self.manage_maintenance_windows()
        if len(mws):
            log.log(log.NOTICE, f"Found matching SSM maintenance windows: %s" % self.maintenance_windows["Windows"])
       
        # Hard dependency toward EC2 module. We update the SSM instance initializing states
        self.o_ec2.update_ssm_initializing_states()
コード例 #14
0
    def get_prerequisites(self, only_if_not_already_done=False):
        if only_if_not_already_done and self.prereqs_done:
            return

        self.state_table = self.o_state.get_state_table()
        client = self.context["ec2.client"]

        # Retrieve list of instances with appropriate tag
        Filters = [{
            'Name': 'tag:clonesquad:group-name',
            'Values': [self.context["GroupName"]]
        }]

        instances = []
        response = None
        while (response is None or "NextToken" in response):
            response = client.describe_instances(
                Filters=Filters,
                MaxResults=Cfg.get_int("ec2.describe_instances.max_results"),
                NextToken=response["NextToken"]
                if response is not None else "")
            for reservation in response["Reservations"]:
                instances.extend(reservation["Instances"])

        # Filter out instances with inappropriate state
        non_terminated_instances = []
        for i in instances:
            if i["State"]["Name"] not in ["shutting-down", "terminated"]:
                non_terminated_instances.append(i)

        self.instances = non_terminated_instances
        self.instance_ids = [i["InstanceId"] for i in self.instances]

        # Enrich describe_instances output with instance type details
        if Cfg.get_int("ec2.describe_instance_types.enabled"):
            self.instance_types = []
            [
                self.instance_types.append(i["InstanceType"])
                for i in self.instances
                if i["InstanceType"] not in self.instance_types
            ]
            if len(self.instance_types):
                response = client.describe_instance_types(
                    InstanceTypes=self.instance_types)
                self.instance_type_details = response["InstanceTypes"]
                for i in self.instances:
                    i["_InstanceType"] = next(
                        filter(
                            lambda it: it["InstanceType"] == i["InstanceType"],
                            self.instance_type_details), None)

        # Get instances status
        instance_statuses = []
        response = None
        while response is None or "NextToken" in response:
            q = {"InstanceIds": self.instance_ids}
            if response is not None and "NextToken" in response:
                q["NextToken"] = response["NextToken"]
            response = client.describe_instance_status(**q)
            instance_statuses.extend(response["InstanceStatuses"])
        self.instance_statuses = instance_statuses

        # Get AZ status
        response = client.describe_availability_zones()
        self.availability_zones = response["AvailabilityZones"]
        if len(self.availability_zones) == 0:
            raise Exception("Can't have a region with no AZ...")

        self.az_with_issues = []
        if not Cfg.get_int("ec2.az.statusmgt.disable"):
            for az in self.availability_zones:
                if az["State"] in ["impaired", "unavailable"]:
                    self.az_with_issues.append(az)
                if az["State"] != "available":
                    log.warning(
                        "AZ %s(%s) is marked with status '%s' by EC2.describe_availability_zones() API!"
                        % (zone_name, zone_id, zone_state))
        else:
            log.warning(
                "Automatic AZ issues detection through describe_availability_zones() is DISABLED (ec2.az.statusmgt.disable != 0)..."
            )

        # Use these config keys to simulate an AWS Large Scale Event
        all_az_names = [az["ZoneName"] for az in self.availability_zones]
        all_az_ids = [az["ZoneId"] for az in self.availability_zones]
        [
            log.warning(
                "ec2.debug.availability_zones_impaired do not match local AZs! '%s'"
                % a)
            for a in Cfg.get_list("ec2.debug.availability_zones_impaired",
                                  default=[])
            if a not in all_az_names and a not in all_az_ids
        ]
        [
            log.warning(
                "ec2.az.unavailable_list do not match local AZs! '%s'" % a)
            for a in Cfg.get_list("ec2.az.unavailable_list", default=[])
            if a not in all_az_names and a not in all_az_ids
        ]
        for az in self.availability_zones:
            zone_name = az["ZoneName"]
            zone_id = az["ZoneId"]
            zone_state = az["State"]
            if zone_name in Cfg.get_list(
                    "ec2.debug.availability_zones_impaired", default=[]):
                zone_state = "impaired"
            if zone_id in Cfg.get_list("ec2.debug.availability_zones_impaired",
                                       default=[]):
                zone_state = "impaired"
            if zone_name in Cfg.get_list("ec2.az.unavailable_list",
                                         default=[]):
                zone_state = "unavailable"
            if zone_id in Cfg.get_list("ec2.az.unavailable_list", default=[]):
                zone_state = "unavailable"
            if zone_state != az["State"] and zone_state in [
                    "impaired", "unavailable"
            ] and az not in self.az_with_issues:
                self.az_with_issues.append(az)
            az["State"] = zone_state
            if zone_state != "available":
                log.warning(
                    "AZ %s(%s) is marked with status '%s' by configuration keys!"
                    % (zone_name, zone_id, zone_state))

        # We need to register dynamically static subfleet configuration keys to avoid a 'key unknown' warning
        #   when the user is going to set it
        static_subfleet_names = self.get_static_subfleet_names()
        for static_fleet in static_subfleet_names:
            key = "staticfleet.%s.state" % static_fleet
            if not Cfg.is_builtin_key_exist(key):
                Cfg.register({key: ""})
        log.log(
            log.NOTICE,
            "Detected following static subfleet names across EC2 resources: %s"
            % static_subfleet_names)

        self.prereqs_done = True
コード例 #15
0
    def query(self, query):
        results = []
        # 翻译
        if query[0] != "_":
            # 识别语言
            [SL, TL] = RecgLang(query)
            # 翻译
            Jresponse = GoogleTranslate(SL, TL, query)

            # 简单翻译结果
            results.append({
                "IcoPath": ICO_PATH,
                "Title": Jresponse[0][0][0],
                "SubTitle": "复制到剪贴板",
                "JsonRPCAction": {
                    "method": "copy",
                    "parameters": [Jresponse[0][0][0]],
                    "dontHideAfterAction": False,
                },
            })

            # 词(组)详情
            if Jresponse[1] != None:
                for item in Jresponse[1]:
                    prefix = item[0]
                    if prefix in DICT_PREFIX:
                        prefix = DICT_PREFIX[prefix]

                    str = "{}.  {}".format(prefix, ", ".join(
                        item[1][:(min(len(item[1]), ITEM_MAX_LEN))]))
                    results.append({
                        "IcoPath": ICO_PATH,
                        "Title": str,
                        "SubTitle": "浏览器查看详情",
                        "JsonRPCAction": {
                            "method": "openUrl",
                            "parameters": ["https://translate.google.cn/#view=home&op=translate&sl={}&tl={}&text={}"
                                           .format(SL, TL, query)],
                            "dontHideAfterAction": False,
                        },
                    })

        # 设置
        else:
            conf = query.split()
            if conf[0] == "_config":
                f_json = get_list()

                flag = {}
                # 设置语言
                if (len(conf) == 4) and (conf[1] in f_json):
                    if f_json[conf[1]] != conf[3]:
                        if (set_lang(conf[1], conf[3])):
                            flag = {conf[1]: " (Successful)"}
                        else:
                            flag = {conf[1]: " (ERROR: Input not supported)"}

                for item in f_json.keys():
                    if item in flag:
                        if "Success" in flag[item]:
                            title = "{} = {}".format(item, conf[3])
                        else:
                            title = "{} = {}".format(item, f_json[item])
                        Title = title+flag[item]
                    else:
                        title = "{} = {}".format(item, f_json[item])
                        Title = title
                    results.append({
                        "IcoPath": ICO_PATH,
                        "Title": Title,
                        "SubTitle": "Set up {} (Modified directly in the input box)".format(item),
                        "JsonRPCAction": {
                            "method": "selectConfig",
                            "parameters": [title],
                            "dontHideAfterAction": True,
                        },
                    })

            else:
                results.append({
                    "IcoPath": ICO_PATH,
                    "Title": "_config",
                    "SubTitle": PREFIX_CONFIG + ": Set up Gtranslate",
                    "JsonRPCAction": {
                        "method": "openConfig",
                        "parameters": [],
                        "dontHideAfterAction": True,
                    },
                })

        return results
コード例 #16
0
ファイル: bot.py プロジェクト: JBustos22/DFTwitchBot
async def event_message(ctx):
    """Activates for every message"""
    debounce = 1  # interval between consecutive commands and messages
    author = ctx.author.name
    message = ctx.content

    if ";" in message:  # prevent q3 command injections
        message = message[:message.index(";")]

    # bot.py, at the bottom of event_message
    if message.startswith("?"):  # spectator client customization and controls
        message = message.strip('?').lower()
        split_msg = message.split(' ')
        cmd = split_msg[0]
        args = split_msg[1:] if len(split_msg) > 0 else None
        logging.info(f"TWITCH COMMAND RECEIVED: '{cmd}' from user '{author}'")

        for command in TWITCH_CMDS:
            if cmd in command:
                twitch_function = getattr(twitch_commands, command[0])
                await twitch_function(ctx, author, args)
        time.sleep(debounce)

    elif message.startswith(">") or message.startswith("<"):  # chat bridge
        message = message.lstrip('>').lstrip('<').lstrip(' ')
        blacklisted_words = config.get_list("blacklist_chat")

        for word in blacklisted_words:
            if word in message:
                logging.info(f"Blacklisted word '{word}' detected in message \"{message}\" by \"{author}\". Aborting message.")
                return

        if author.lower() == 'nightbot'.lower():  # ignore twitch Nightbot's name
            author = ''
            author_color_char = 0
        else:
            author += ' ^7> '
            author_color_char = author[0]

        api.exec_command(f"say ^{author_color_char}{author} ^2{message}")
        logging.info("Chat message sent")
        time.sleep(debounce)

    elif message.startswith("**"):  # team chat bridge
        message = message.lstrip('**')
        blacklisted_words = config.get_list("blacklist_chat")

        for word in blacklisted_words:
            if word in message:
                logging.info(f"Blacklisted word '{word}' detected in message \"{message}\" by \"{author}\". Aborting message.")
                return

        if author.lower() == 'nightbot'.lower():  # ignore twitch Nightbot's name
            author = ''
            author_color_char = 0
        else:
            author += ' ^7> '
            author_color_char = author[0]

        api.exec_command(f"say_team ^{author_color_char}{author} ^5{message}")
        logging.info("Chat message sent")
        time.sleep(debounce)

    elif message.startswith("!"):  # proxy mod commands (!top, !rank, etc.)
        logging.info("proxy command received")
        api.exec_command(message)
        time.sleep(debounce)

    elif  message.startswith("$"):  # viewer sound commands
        for sound_cmd in SOUND_CMDS:
            if message.startswith(sound_cmd):
                logging.info(f"Sound command recieved ({sound_cmd})")
                api.play_sound(sound_cmd.replace('$', '') + '.wav') #odfe appears to only support .wav format, not mp3, so we can hardcode it
                time.sleep(debounce)
    return
コード例 #17
0
def get_last_key(data):
    datalist = get_list(data)
    lastkey = datalist[-1]
    return lastkey
コード例 #18
0
Copyright (c) 2016-2018 Uwe Krien <*****@*****.**>

SPDX-License-Identifier: GPL-3.0-or-later
"""
__copyright__ = "Uwe Krien <*****@*****.**>"
__license__ = "GPLv3"

import os
import config as cfg

print("Gefundene ini-Dateien:")
for filename in cfg.get_ini_filenames():
    print(filename)

for n in range(4):
    v = cfg.get('values', 'value{0}'.format(n + 1))
    print(v, type(v))

print(cfg.get_dict('parameter'))

print(cfg.get_list('something', 'members'))
print(cfg.get_list('something', 'members')[1])
print(cfg.get('something', 'members'))
print(cfg.get('something', 'members')[1])

try:
    print(os.listdir(cfg.get('paths', 'basic')))
except FileNotFoundError:
    print("Please create an ini-file in your home directory and add the "
          "correct path.")