async def create_message_text(self, server_roles, ctx): """ Returns the message text for the role manage init message including the reactions and mod roles for the roles :param server_roles: the roles on the server :param ctx: The context of the used command to create the new message """ msg = "{}\n".format(Config().get(self)['message']['content']) for rid in self.rc(): role = discord.utils.get(server_roles, id=rid) emote_msg = "" modrole_msg = "" if self.rc()[rid]['emoji']: emote_msg = Config().lang( self, 'init_reaction', await utils.emojize(self.rc()[rid]['emoji'], ctx)) if self.rc()[rid]['modrole'] != 0: modrole = discord.utils.get(server_roles, id=self.rc()[rid]['modrole']) modrole_msg = Config().lang(self, 'init_modrole', modrole.name) if emote_msg and modrole_msg: todo_part = "{}, {}".format(emote_msg, modrole_msg) elif emote_msg: todo_part = emote_msg elif modrole_msg: todo_part = modrole_msg else: todo_part = Config().lang(self, 'init_admin') msg += "\n{} - {}".format(role.name, todo_part) return msg
async def role_update(self, ctx, *message_content): if len(message_content) > 0: Config().get(self)['message']['content'] = " ".join( message_content) Config().save(self) await self.update_role_management(ctx) await ctx.send(Config().lang(self, 'role_update')) await utils.log_to_admin_channel(ctx)
async def get_init_msg(self): """Returns the role management init message or None if not set""" if self.has_init_msg_set(): channel = self.bot.get_channel( Config().get(self)['message']['channel_id']) return await channel.fetch_message( Config().get(self)['message']['message_id']) else: return None
def _params_add_api_key(self, params=None): """ Adds the API key to the params dictionary """ if not Config().GOOGLE_API_KEY: raise NoApiKey() if params is None: params = [] params.append(('key', Config().GOOGLE_API_KEY)) return params
def setUp(self): """ 为测试方法的初始化,每个case运行前执行一次 :param self.url: 请求域名 :param self.user_info: 请求参数 """ # self.url_twweb = 'http://39.105.191.175:8080/twweb' # self.url_system = 'http://39.105.191.175:8080/tw_system' # self.user_info = {'mobile': 14611110000, 'password': '******'} self.url_twweb = Config().getconf("http_url").url_twweb self.url_system = Config().getconf("http_url").url_system self.user_info = Config().getconf("user").user_info self.user_id = Config().getconf("user").user_id
async def role_add(self, ctx, role_name, emoji_or_modrole, color: discord.Color = None): emoji_str = await utils.demojize(emoji_or_modrole, ctx) try: modrole = await commands.RoleConverter().convert( ctx, emoji_or_modrole) modrole_id = modrole.id emoji_str = "" except commands.CommandError: modrole_id = 0 if not emoji_str and modrole_id == 0: try: color = await commands.ColourConverter().convert( ctx, emoji_or_modrole) except commands.CommandError: color = discord.Color.default() existing_role = discord.utils.get(ctx.guild.roles, name=role_name) if existing_role is not None: if existing_role.id in self.rc(): # Update role data if emoji_str: self.rc()[existing_role.id]['emoji'] = emoji_str if modrole_id != 0: self.rc()[existing_role.id]['modrole'] = modrole_id await self.update_role_management(ctx) await ctx.send(Config().lang(self, 'role_add_updated', role_name)) else: # role exists on server, but not in config, add it there self.rc()[existing_role.id] = { 'emoji': emoji_str, 'modrole': modrole_id } await self.update_role_management(ctx) await ctx.send(Config().lang(self, 'role_add_config', role_name)) return # Execute role add new_role = await RoleManagement.add_server_role( ctx.guild, role_name, color) self.rc()[new_role.id] = {'emoji': emoji_str, 'modrole': modrole_id} await self.update_role_management(ctx) await ctx.send(Config().lang(self, 'role_add_created', role_name, color)) await utils.log_to_admin_channel(ctx)
def whitelist_check_id(user_id: int): """ Checks if the given user can use the bot based on the debug whitelist. Note: The debug whitelist is active only if the list is not empty and debug mode is enabled. :param user_id: The user id to check :returns: If debug mode is disabled: True. If debug mode is enabled: False if user is not permitted to use the bot, otherwise True. """ if (Config().DEBUG_MODE and len(Config().DEBUG_WHITELIST) > 0 and user_id not in Config().DEBUG_WHITELIST): return False return True
async def role_request(self, ctx, role: discord.Role): modrole = None for configured_role in self.rc(): if configured_role == role.id: modrole = discord.utils.get( ctx.guild.roles, id=self.rc()[configured_role]['modrole']) break if modrole is None: await ctx.send(Config().lang(self, 'role_request_no_modrole', role.name)) else: await ctx.send(Config().lang(self, 'role_request_ping', modrole.mention, ctx.author.mention, role.name))
async def bugscore_increment(self, ctx, user, increment): if discord.utils.get(ctx.author.roles, id=Config().BOTMASTER_ROLE_ID) is None: await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS) return # find user try: user = await commands.MemberConverter().convert(ctx, user) except (commands.CommandError, IndexError): await ctx.send(Lang.lang(self, "bugscore_user_not_found", user)) await ctx.message.add_reaction(Lang.CMDERROR) return try: increment = int(increment) except (ValueError, TypeError): await ctx.send(Lang.lang(self, "bugscore_nan", increment)) await ctx.message.add_reaction(Lang.CMDERROR) return if user.id in self.storage["bugscore"]: self.storage["bugscore"][user.id] += increment else: self.storage["bugscore"][user.id] = increment if self.storage["bugscore"][user.id] <= 0: del self.storage["bugscore"][user.id] Storage.save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS)
def test_whitelist_check(self): Config().DEBUG_MODE = False Config().DEBUG_WHITELIST = [1, 2, 3] self.assertEqual(permChecks.whitelist_check_id(1), True) self.assertEqual(permChecks.whitelist_check_id(4), True) Config().DEBUG_MODE = True self.assertEqual(permChecks.whitelist_check_id(1), True) self.assertEqual(permChecks.whitelist_check_id(4), False) Config().DEBUG_WHITELIST = [] self.assertEqual(permChecks.whitelist_check_id(1), True) self.assertEqual(permChecks.whitelist_check_id(4), True)
def logging_setup(): """ Put all debug loggers on info and everything else on info/debug, depending on config """ level = logging.INFO if Config().DEBUG_MODE: level = logging.DEBUG Path("logs/").mkdir(parents=True, exist_ok=True) file_handler = logging.handlers.TimedRotatingFileHandler( filename="logs/geckarbot.log", when="midnight", interval=1) file_handler.setLevel(level) file_handler.setFormatter( logging.Formatter( '%(asctime)s : %(levelname)s : %(name)s : %(message)s')) console_handler = logging.StreamHandler() console_handler.setLevel(level) console_handler.setFormatter( logging.Formatter( '%(asctime)s : %(levelname)s : %(name)s : %(message)s')) logger = logging.getLogger('') logger.setLevel(level) logger.addHandler(file_handler) logger.addHandler(console_handler) for el in logging.root.manager.loggerDict: logger = logging.root.manager.loggerDict[el] if isinstance(logger, logging.PlaceHolder): continue logger.setLevel(logging.INFO)
async def fantasy_save_state(self, ctx, new_state: FantasyState): """Saves the new Fantasy state and prints it to user""" self.fantasy_conf()['state'] = new_state state_str = str(FantasyState(self.fantasy_conf()['state'])) state_str = state_str[state_str.find(".") + 1:].replace("_", " ") Config().save(self) await ctx.send(self.fantasy_lang('phase_set', state_str))
async def disable(self, ctx, command, *args): user = ctx.author date_args_start_index = 0 if len(args) > 0: try: user = await commands.MemberConverter().convert(ctx, args[0]) date_args_start_index = 1 except (commands.CommandError, IndexError): date_args_start_index = 0 if user != ctx.author and not permChecks.check_full_access(ctx.author): raise commands.MissingAnyRole(Config().FULL_ACCESS_ROLES) until = utils.analyze_time_input(*args[date_args_start_index:]) result = self.bot.ignoring.add_user_command(user, command, until) if result == IgnoreEditResult.Success: await ctx.message.add_reaction(Lang.CMDSUCCESS) elif result == IgnoreEditResult.Already_in_list: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'user_cmd_already_blocked', command, utils.get_best_username(user))) elif result == IgnoreEditResult.Until_in_past: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'no_time_machine')) await utils.log_to_admin_channel(ctx)
def main(): parser = argparse.ArgumentParser(description="""Sniff for SSIDs and determine their potential physical location. To stop sniffing, send SIGINT to the process.""", epilog="""When using wigle, data is printed out in the following format: {latitude},{longitude}: {country} - {region} - {city} - {postalcode} - {street} - {house number} ({last update}) """) parser.add_argument('interface', metavar='INTERFACE', type=str, help="the wifi interface to use (must be capable of monitor mode") parser.add_argument('-c', '--censor', dest='censor', action='store_true', help="censor SSIDs, MAC addresses, and any other sensitive information") parser.add_argument('-w', '--wigle-auth', dest='auth_token', type=str, help="the auth code used for the wigle api") parser.add_argument('-m', '--mac-vendors', dest='mac_vendors', type=str, help="use a MAC to brand mapping to print the devices' brands") parser.add_argument('-s', '--summary', dest='summary', help="store all results to this json file") args = parser.parse_args() Config(args) try: wifi.monitor() except AssertionError: print("Switching wifi interface {} to monitor mode not possible, exiting".format(Config.interface), file=sys.stderr) __cleanup__() sniff = Sniff() try: sniff.start(callback) except KeyboardInterrupt: pass if Config.summary: summary.summarize() __cleanup__()
async def fantasy_set_state_end(self, ctx, dateStr, timeStr=None): """Sets the end date (and time) of the current Fantasy state""" if not timeStr: timeStr = "23:59" self.fantasy_conf()['state_end'] = datetime.strptime( f"{dateStr} {timeStr}", "%d.%m.%Y %H:%M") Config().save(self) await ctx.send(self.fantasy_lang('state_end_set'))
async def on_ready(): """Loads plugins and prints on server that bot is ready""" guild = discord.utils.get(bot.guilds, id=Config().SERVER_ID) bot.guild = guild logging.info("Loading plugins") bot.load_plugins(Config().PLUGIN_DIR) logging.info(f"{bot.user} is connected to the following server:\n" f"{guild.name}(id: {guild.id})") members = "\n - ".join([member.name for member in guild.members]) logging.info(f"Server Members:\n - {members}") await utils.write_debug_channel( bot, f"Geckarbot {Config().VERSION} connected on " f"{guild.name} with {len(guild.members)} users.")
def run_predict(): # === 单张图预测 conf = Config(code_type=400, ) img_model = ImgModel(conf) img = Image.open(r'D:\working\pyWorking\codeIdentify\imgs\400\2879_00.png') img = img.convert('L') vcode = img_model.predict(img) print(vcode)
def default_config(self): return { 'message': { 'channel_id': Config().CHAN_IDS['announcements'], 'message_id': 0, 'content': "" }, 'roles': {} }
def readConfig(self): self.__configuration__ = Config() status = self.__configuration__.read_config() if status == 1: log.logger.info("Configuration read success") else: log.logger.info( "Configuration read not successful! Exiting automation script") sys.exit()
def check_full_access(user: discord.Member): """ Checks if the user has full access to bot commands. If you can, use @commands.has_any_role(*Config().FULL_ACCESS_ROLES) instead. """ for role in user.roles: if role.id in Config().FULL_ACCESS_ROLES: return True return False
def __init__(self): self.__run = True self.pg = pygame self.pg.init() self.global_conf = Config() self.clock = self.pg.time.Clock() self.global_settings = self.global_conf.GLOBAL_SETTINGS self.camera = Camera(self) self.viewport = Viewport(self) self.events = Events(self)
async def dsc_set(self, ctx): if (not permChecks.check_full_access(ctx.author) and Config.get(self)['songmaster_role_id'] != 0 and Config.get(self)['songmaster_role_id'] not in [role.id for role in ctx.author.roles]): raise commands.BotMissingAnyRole([*Config().FULL_ACCESS_ROLES, Config.get(self)['songmaster_role_id']]) if Config.get(self)['channel_id'] != 0 and Config.get(self)['channel_id'] != ctx.channel.id: raise commands.CheckFailure() if ctx.invoked_subcommand is None: await ctx.send_help(self.dsc_set)
def run(train=False): if train: conf = Config(code_type=501, epochs=500, batch_size=512, per=96.) create_verifycode_img(100, conf) img_dataset = ImgDataset(config=conf) ImgModel(conf).train(imgDataset=img_dataset) else: # 预测用新测试数据集 conf = Config(code_type=501, ) conf.img_dir = os.path.join(conf._IMG_DIR, 'test_{}'.format(conf.code_type)) if not os.path.exists(conf.img_dir): os.makedirs(conf.img_dir) create_verifycode_img(2, conf) img_dataset = ImgDataset(config=conf) ImgModel(conf).validate(img_dataset)
def __init__(self): self.conf = Config() self.channels = Channels() self.delay = __delay__ self.version = __version__ self.ENCODING = "utf-8" self._replacer, self._endreplacer = utils._replacer, utils._endreplacer self.chan = [] self.startdir = os.getcwd() + "/" self.disconnection = False self.connect() os.chdir(self.startdir)
def __init__(self, configFile=None): self.config = Config(configFile) self.cookiejar = CookieJar() if self.config.cookiePath and os.path.exists(self.config.cookiePath): self.load_cookies() install_opener(build_opener(HTTPCookieProcessor(self.cookiejar))) for name in settings.FEEDS: setattr(self, name, self.__get_xml_page(name)) setattr(self, 'message', self.__get_xml_page('message'))
async def enable(self, ctx, command, user: discord.Member = None): if user is None: user = ctx.author if user != ctx.author and not permChecks.check_full_access(ctx.author): raise commands.MissingAnyRole(*Config().FULL_ACCESS_ROLES) result = self.bot.ignoring.remove_user_command(user, command) if result == IgnoreEditResult.Success: await ctx.message.add_reaction(Lang.CMDSUCCESS) elif result == IgnoreEditResult.Not_in_list: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'user_cmd_not_blocked', command, utils.get_best_username(user))) await utils.log_to_admin_channel(ctx)
async def update_news(self, channel, version=None): """ Sends release notes to channel. :param channel: Channel to send the release notes to. :param version: Release version that the news should be about. """ if version is None: version = Config().VERSION ver = None body = None for el in self.get_releases(): ver = sanitize_version_s(el["tag_name"]) logging.getLogger(__name__).debug( "Comparing versions: {} and {}".format(Config().VERSION, ver)) if is_equal(sanitize_version_s(version), ver): body = el["body"] break if body is None: await channel.send(lang["err_no_news_for_version"].format(version)) return # Make headlines great again! lines = [] p = re.compile(r"\s*#+\s*(.*)") for el in body.split("\n"): m = p.match(el) if m: el = "**{}**".format(m.groups()[0]) lines.append(el) for page in utils.paginate(lines, prefix="**Version {}:**\n".format(ver), msg_prefix="_ _\n", delimiter=""): await channel.send(page)
def __init__(self, *args, **kwargs): self.geck_cogs = [] self.guild = None self._plugins = [] super().__init__(*args, **kwargs) self.reaction_listener = reactions.ReactionListener(self) self.dm_listener = dmlisteners.DMListener(self) self.timers = timers.Mothership(self) self.ignoring = ignoring.Ignoring(self) self.helpsys = help.GeckiHelp(self) Lang().bot = self Config().bot = self Storage().bot = self
async def bugscore_del(self, ctx, user): if discord.utils.get(ctx.author.roles, id=Config().BOTMASTER_ROLE_ID) is None: await ctx.message.add_reaction(Lang.CMDNOPERMISSIONS) return try: user = await commands.MemberConverter().convert(ctx, user) except (commands.CommandError, IndexError): await ctx.send(Lang.lang(self, "bugscore_user_not_found", user)) await ctx.message.add_reaction(Lang.CMDERROR) return if user.id in self.storage["bugscore"]: del self.storage["bugscore"][user.id] Storage.save(self) await ctx.message.add_reaction(Lang.CMDSUCCESS) else: await ctx.message.add_reaction(Lang.CMDNOCHANGE)
def check_release(self): """ Checks GitHub if there is a new release. Assumes that the GitHub releases are ordered by release date. :return: Tag of the newest release that is newer than the current version, None if there is none. """ # return "1.3" # TESTING # find newest release with tag (all the others are worthless anyway) release = None for el in self.get_releases(): if "tag_name" in el: release = el break if release is None: return None release = release["tag_name"] if is_newer(release, Config().VERSION): return release return None