def __init__(self, bot: Red, member: discord.Member, data: dict): self.bot: Red = bot self.member: discord.Member = member self.guild: discord.Guild = member.guild self.config: dict = data # Will contain the config of the guild. if not self.config["channel"]: raise MissingRequiredValueError( "Missing channel for verification.") self.channel: Union[discord.TextChannel, discord.DMChannel] = ( bot.get_channel(self.config["channel"]) if self.config.get("channel") != "dm" else self.member.dm_channel) self.type: str = self.config["type"] self.messages: dict = {} # bot_challenge: Message send for the challenge, contain captcha. # logs: The message that has been sent in the logging channel. # answer: Member's answer to captcha, may or may not exist. self.log = bot.get_cog("Captcha").send_or_update_log_message self.running: bool = False self.tasks: list = [] self.limit: int = self.config["retry"] self.trynum: int = 0 self.captcha: discapty.Captcha = discapty.Captcha(self.type)
def __init__(self, bot: Red): self.bot = bot self.config = Config.get_conf(self, identifier=9765573181940385953309, force_registration=True) self.config.register_guild(**self.default_guild) self.channel_cache = {} self.bump_tasks: DefaultDict[int, Dict[str, asyncio.Task]] = defaultdict(dict) # self.cache = defaultdict(lambda _: self.default_guild_cache.copy()) try: bot.add_dev_env_value("bprm", lambda _: self) except RuntimeError: pass blocks = [ tse.LooseVariableGetterBlock(), tse.AssignmentBlock(), tse.IfBlock(), tse.EmbedBlock(), ] self.tagscript_engine = tse.Interpreter(blocks) self.bump_loop = self.create_task(self.bump_check_loop()) self.initialize_task = self.create_task(self.initialize())
def setup(bot: Red) -> None: apc = AnotherPingCog(bot) global old_ping old_ping = bot.get_command("ping") if old_ping: bot.remove_command(old_ping.name) bot.add_cog(apc)
async def from_json(cls, data: dict, bot: Red): """Return a `BattleLog` object from dictionary representation of the log.""" self = cls() # Get player's `User` instance. self.player = bot.get_user(data["player_id"]) if self.player is None: self.player = await bot.fetch_user(data["player_id"]) self.player_brawler_name = data["player_brawler_name"] self.player_brawler_level = data["player_brawler_level"] # Get opponent's `User` instance. self.opponent = bot.get_user(data["opponent_id"]) if self.opponent is None: self.opponent = await bot.fetch_user(data["opponent_id"]) self.opponent_brawler_name = data["opponent_brawler_name"] self.opponent_brawler_level = data["opponent_brawler_level"] self.game_mode = data["game_mode"] self.result = data["result"] return self
def setup(bot: Red) -> None: cog = bot.get_cog("CustomCommands") if cog: raise CogLoadError( "This cog conflicts with CustomCommands and cannot be loaded with both at the same time." ) bot.add_cog(Tags(bot))
def __init__(self, bot: Red) -> None: self.bot = bot self.application_id = None self.eval_command = None self.http = SlashHTTP(self) self.config = Config.get_conf( self, identifier=70342502093747959723475890, force_registration=True, ) default_guild = {"tags": {}} default_global = {"application_id": None, "eval_command": None} self.config.register_guild(**default_guild) self.config.register_global(**default_global) self.command_cache = {} self.button_cache = {} self.guild_tag_cache: Dict[int, Dict[int, SlashTag]] = defaultdict(dict) self.global_tag_cache = {} self.load_task = self.create_task(self.initialize_task()) bot.add_dev_env_value("st", lambda ctx: self) super().__init__()
def __init__(self, bot: Red) -> None: self.bot = bot self.config = Config.get_conf( self, identifier=567234895692346562369, force_registration=True, ) default_guild = {"tags": {}} default_global = { "tags": {}, "blocks": {}, "async_enabled": False, "dot_parameter": False } self.config.register_guild(**default_guild) self.config.register_global(**default_global) self.guild_tag_cache = defaultdict(dict) self.global_tag_cache = {} self.initialize_task = None self.dot_parameter: bool = None self.async_enabled: bool = None self.initialize_task = self.create_task(self.initialize()) self.session = aiohttp.ClientSession() self.docs: list = [] if bot._cli_flags.logging_level == logging.DEBUG: logging.getLogger("TagScriptEngine").setLevel(logging.DEBUG) bot.add_dev_env_value("tags", lambda ctx: self) super().__init__()
async def setup(bot: Red) -> None: await maybe_migrate_config_identifier() cog = Status(bot) await out_of_date_check("status", cog.__version__) await cog.async_init() bot.add_cog(cog)
async def setup(bot: Red) -> None: if version_info < VersionInfo.from_str("3.1.3"): raise CogLoadError( "This cog requires at least Red 3.1.3.\n" "Go update, it's a straight improvement from previously supported versions." ) bot.add_cog(VoiceTools())
async def get_channel_obj(bot: Red, channel_id: int, data: dict) -> Optional[discord.TextChannel]: """ Requires a bot object to access config, channel_id, and channel config data Returns the channel object and sets the guild ID if it's missing from config This is used in Game objects and Goal objects so it's here to be shared between the two rather than duplicating the code """ if not data["guild_id"]: channel = bot.get_channel(id=channel_id) if not channel: await bot.get_cog("Hockey").config.channel_from_id(channel_id ).clear() log.info( f"{channel_id} channel was removed because it no longer exists" ) return None guild = channel.guild await bot.get_cog("Hockey").config.channel(channel).guild_id.set( guild.id) return channel guild = bot.get_guild(data["guild_id"]) if not guild: await bot.get_cog("Hockey").config.channel_from_id(channel_id).clear() log.info( f"{channel_id} channel was removed because it no longer exists") return None channel = guild.get_channel(channel_id) if channel is None: await bot.get_cog("Hockey").config.channel_from_id(channel_id).clear() log.info( f"{channel_id} channel was removed because it no longer exists") return None return channel
def __init__(self, bot: Red): self.bot = bot self.config = Config.get_conf(self, identifier=9765573181940385953309, force_registration=True) default_guild = { "channel": None, "role": None, "message": "It's been 2 hours since the last successful bump, could someone run `!d bump`?", "tyMessage": "{member(mention)} thank you for bumping! Make sure to leave a review at <https://disboard.org/server/{guild(id)}>.", "nextBump": None, "lock": False, "clean": False, } self.config.register_guild(**default_guild) self.channel_cache = {} self.bump_loop = self.create_task(self.bump_check_loop()) self.bump_tasks = defaultdict(dict) # self.cache = defaultdict(lambda _: self.default_guild_cache.copy()) bot.add_dev_env_value("bprm", lambda _: self) blocks = [ tse.LooseVariableGetterBlock(), tse.AssignmentBlock(), tse.IfBlock(), tse.EmbedBlock(), ] self.tagscript_engine = tse.Interpreter(blocks)
def setup(bot: Red): if not bot._cli_flags.dev: raise CogLoadError("This cog requires the `--dev` CLI flag.") if getattr(bot.get_cog("Dev"), "sessions", None): raise CogLoadError("End your REPL session(s) first.") bot.remove_cog("Dev") bot.add_cog(Dev())
def setup(bot: Red) -> None: for cog_name, module_name, tag_name in conflicting_cogs: if bot.get_cog(cog_name): raise CogLoadError( f"This cog conflicts with {cog_name} and both cannot be loaded at the same time. " f"After unloading `{module_name}`, you can migrate {tag_name} to tags with `[p]migrate{module_name}`." ) bot.add_cog(Tags(bot))
def setup(bot: Red) -> None: cog = bot.get_cog("CustomCommands") if cog: raise CogLoadError( "This cog conflicts with CustomCommands and both cannot be loaded at the same time. " "After unloading `customcom`, you can migrate custom commands to tags with `[p]migratecustomcom`." ) bot.add_cog(Tags(bot))
async def check_team_goals(self, bot: Red) -> None: """ Checks to see if a goal needs to be posted """ team_data = { self.home_team: await get_team(bot, self.home_team), self.away_team: await get_team(bot, self.away_team), } # home_team_data = await get_team(bot, self.home_team) # away_team_data = await get_team(bot, self.away_team) # all_data = await get_team("all") team_list = await bot.get_cog("Hockey").config.teams() # post_state = ["all", self.home_team, self.away_team] # home_goal_ids = [goal.goal_id for goal in self.home_goals] # away_goal_ids = [goal.goal_id for goal in self.away_goals] home_goal_list = list(team_data[self.home_team]["goal_id"]) away_goal_list = list(team_data[self.away_team]["goal_id"]) for goal in self.goals: # goal_id = str(goal["result"]["eventCode"]) # team = goal["team"]["name"] # team_data = await get_team(bot, goal.team_name) if goal.goal_id not in team_data[goal.team_name]["goal_id"]: # attempts to post the goal if there is a new goal bot.dispatch("hockey_goal", self, goal) goal.home_shots = self.home_shots goal.away_shots = self.away_shots msg_list = await goal.post_team_goal(bot, self) team_list.remove(team_data[goal.team_name]) team_data[goal.team_name]["goal_id"][goal.goal_id] = { "goal": goal.to_json(), "messages": msg_list, } team_list.append(team_data[goal.team_name]) await bot.get_cog("Hockey").config.teams.set(team_list) continue if goal.goal_id in team_data[goal.team_name]["goal_id"]: # attempts to edit the goal if the scorers have changed old_goal = Goal(**team_data[goal.team_name]["goal_id"][goal.goal_id]["goal"]) if goal.description != old_goal.description or goal.link != old_goal.link: goal.home_shots = old_goal.home_shots goal.away_shots = old_goal.away_shots # This is to keep shots consistent between edits # Shots should not update as the game continues bot.dispatch("hockey_goal_edit", self, goal) old_msgs = team_data[goal.team_name]["goal_id"][goal.goal_id]["messages"] team_list.remove(team_data[goal.team_name]) team_data[goal.team_name]["goal_id"][goal.goal_id]["goal"] = goal.to_json() team_list.append(team_data[goal.team_name]) await bot.get_cog("Hockey").config.teams.set(team_list) await goal.edit_team_goal(bot, self, old_msgs) # attempts to delete the goal if it was called back for goal_str in home_goal_list: await Goal.remove_goal_post(bot, goal_str, self.home_team, self) for goal_str in away_goal_list: await Goal.remove_goal_post(bot, goal_str, self.away_team, self)
def __init__(self, bot: Red) -> None: self.bot = bot self.config = Config.get_conf( self, identifier=567234895692346562369, force_registration=True, ) default_guild = {"tags": {}} default_global = {"tags": {}} self.config.register_guild(**default_guild) self.config.register_global(**default_global) tse_blocks = [ tse.MathBlock(), tse.RandomBlock(), tse.RangeBlock(), tse.AnyBlock(), tse.IfBlock(), tse.AllBlock(), tse.BreakBlock(), tse.StrfBlock(), tse.StopBlock(), tse.AssignmentBlock(), tse.FiftyFiftyBlock(), tse.ShortCutRedirectBlock("args"), tse.LooseVariableGetterBlock(), tse.SubstringBlock(), tse.EmbedBlock(), tse.ReplaceBlock(), tse.PythonBlock(), tse.URLEncodeBlock(), tse.RequireBlock(), tse.BlacklistBlock(), tse.CommandBlock(), tse.OverrideBlock(), ] tag_blocks = [ DeleteBlock(), SilentBlock(), ReactBlock(), RedirectBlock(), ReactUBlock(), ] self.engine = tse.Interpreter(tse_blocks + tag_blocks) self.role_converter = commands.RoleConverter() self.channel_converter = commands.TextChannelConverter() self.member_converter = commands.MemberConverter() self.emoji_converter = commands.EmojiConverter() self.guild_tag_cache = defaultdict(dict) self.global_tag_cache = {} self.cache_task = asyncio.create_task(self.cache_tags()) self.session = aiohttp.ClientSession() self.docs: list = [] super().__init__() bot.add_dev_env_value("tags", lambda ctx: self)
async def remove_goal_post(bot: Red, goal: str, team: str, data: Game) -> None: """ Attempt to delete a goal if it was pulled back """ config = bot.get_cog("Hockey").config team_list = await config.teams() team_data = await get_team(bot, team) if goal not in [goal.goal_id for goal in data.goals]: try: old_msgs = team_data["goal_id"][goal]["messages"] except KeyError: return except Exception: log.exception("Error iterating saved goals") return for guild_id, channel_id, message_id in old_msgs: guild = bot.get_guild(guild_id) if not guild: continue channel = guild.get_channel(int(channel_id)) if channel and channel.permissions_for( channel.guild.me).read_message_history: try: if version_info >= VersionInfo.from_str("3.4.6"): message = channel.get_partial_message(message_id) else: message = await channel.fetch_message(message_id) except (discord.errors.NotFound, discord.errors.Forbidden): continue except Exception: log.exception( f"Error getting old goal for {str(team)} {str(goal)} in " f"{guild_id=} {channel_id=}") pass if message is not None: try: await message.delete() except (discord.errors.NotFound, discord.errors.Forbidden): pass except Exception: log.exception( f"Error getting old goal for {str(team)} {str(goal)} in " f"{guild_id=} {channel_id=}") else: log.debug( "Channel does not have permission to read history") try: team_list.remove(team_data) del team_data["goal_id"][goal] team_list.append(team_data) await config.teams.set(team_list) except Exception: log.exception("Error removing teams goals") return return
async def setup(bot: Red): try: cog = Crossbar(bot) await cog.initialize() except ImportError: raise CogLoadError( "You need `crossbar`: https://pypi.org/project/crossbar") else: bot.add_cog(cog)
async def setup(bot: Red): for cog in INCOMPATIBLE_COGS: if cog in bot.cogs: raise CogLoadError(f"Cog {cog} is incompatible with this cog.") cog = CaseInsensitive(bot) await out_of_date_check("caseinsensitive", cog.__version__) cog.plug_core() cog.plug_alias() bot.add_cog(cog)
async def setup(bot: Red) -> None: global old_uptime old_uptime = bot.get_command("uptime") if old_uptime: bot.remove_command(old_uptime.name) cog = BetterUptime(bot) await cog.async_init() await out_of_date_check("betteruptime", cog.__version__) bot.add_cog(cog)
async def setup(bot: Red) -> None: global old_ping old_ping = bot.get_command("ping") if old_ping: bot.remove_command(old_ping.name) cog = AnotherPingCog(bot) await cog.async_init() await out_of_date_check("anotherpingcog", cog.__version__) bot.add_cog(cog)
async def setup(bot: Red) -> None: await validate_tagscriptengine(bot, tse_version) for cog_name, module_name, tag_name in conflicting_cogs: if bot.get_cog(cog_name): raise CogLoadError( f"This cog conflicts with {cog_name} and both cannot be loaded at the same time. " f"After unloading `{module_name}`, you can migrate {tag_name} to tags with `[p]migrate{module_name}`." ) tags = Tags(bot) bot.add_cog(tags)
def __init__(self, bot: Red) -> None: self.bot = bot self.application_id = None self.eval_command = None self.http = SlashHTTP(self) self.config = Config.get_conf( self, identifier=70342502093747959723475890, force_registration=True, ) default_guild = {"tags": {}} default_global = {"application_id": None, "eval_command": None} self.config.register_guild(**default_guild) self.config.register_global(**default_global) tse_blocks = [ tse.MathBlock(), tse.RandomBlock(), tse.RangeBlock(), tse.AnyBlock(), tse.IfBlock(), tse.AllBlock(), tse.BreakBlock(), tse.StrfBlock(), tse.StopBlock(), tse.AssignmentBlock(), tse.FiftyFiftyBlock(), tse.LooseVariableGetterBlock(), tse.SubstringBlock(), tse.EmbedBlock(), tse.ReplaceBlock(), tse.PythonBlock(), tse.RequireBlock(), tse.BlacklistBlock(), tse.URLEncodeBlock(), tse.CommandBlock(), ] slash_blocks = [HideBlock()] self.engine = tse.Interpreter(tse_blocks + slash_blocks) self.role_converter = commands.RoleConverter() self.channel_converter = commands.TextChannelConverter() self.member_converter = commands.MemberConverter() self.emoji_converter = commands.EmojiConverter() self.command_cache = {} self.guild_tag_cache: Dict[int, Dict[int, SlashTag]] = defaultdict(dict) self.global_tag_cache = {} self.load_task = self.create_task(self.initialize_task()) bot.add_dev_env_value("st", lambda ctx: self)
def load_or_reload(bot: Red, load: Type[commands.Cog], *args, **kwargs): name = load.__name__ if name not in loaded or loaded[name] is not bot.get_cog(name): old = bot.cogs.get(name) if old: log.debug("Unloading previously loaded version of internal cog %r", name) bot.remove_cog(name) log.info("Loading internal cog %r", name) loaded[name] = load = load(bot, *args, **kwargs) if old and hasattr(load, "sl_reload_hook"): load.sl_reload_hook(old) bot.add_cog(load)
async def setup(bot: Red): if bot.get_cog("OnJoin"): LOG.warning("OnJoin already loaded, attempting to unload first...") bot.remove_cog("OnJoin") await bot.remove_loaded_package("OnJoin") bot.unload_extension("OnJoin") n = OnJoin(bot) bot.add_listener(n.voice_state_update, "on_voice_state_update") bot.add_cog(n)
async def setup(bot: Red): try: setup_cog(bot, "Quotes", require_version="0.0.2a0") except TypeError: from redbot.core.errors import CogLoadError raise CogLoadError( "Your bot is running an outdated version of the shared library this" " cog depends on. You can resolve this issue by either running" "`[p]swiftlibs reload`, or by restarting your bot.") from quotes.quotes import Quotes bot.add_cog(Quotes(bot))
async def setup(bot: Red): try: setup_cog(bot, "RNDActivity", require_version="0.0.3a0") except TypeError: from redbot.core.errors import CogLoadError raise CogLoadError( "Your bot is running an outdated version of the shared library this" " cog depends on. You can resolve this issue by either running" "`[p]swiftlibs reload`, or by restarting your bot.") try_import("babel") from rndactivity.rndactivity import RNDActivity bot.add_cog(RNDActivity(bot))
def from_json(cls, bot: Red, data: dict): members = data.get("members", []) new_members = [] for m in members: if isinstance(m, tuple) or isinstance(m, list): log.debug( f"Converting to new members list in {data.get('channel')}") new_members.append(m[0]) else: new_members.append(m) start = data.get("start") if start: start = datetime.fromtimestamp(start, tz=timezone.utc) guild = data.get("guild") if not guild: chan = bot.get_channel(data.get("channel")) guild = chan.guild.id return cls( hoster=data.get("hoster"), members=new_members, event=data.get("event"), max_slots=data.get("max_slots"), approver=data.get("approver"), message=data.get("message"), guild=guild, channel=data.get("channel"), maybe=data.get("maybe"), start=start, )
async def edit_team_goal(self, bot: Red, game_data: Game, og_msg: Tuple[int, int, int]) -> None: """ When a goal scorer has changed we want to edit the original post """ # scorer = self.headshots.format(goal["players"][0]["player"]["id"]) # post_state = ["all", game_data.home_team, game_data.away_team] em = await self.goal_post_embed(game_data) async for guild_id, channel_id, message_id in AsyncIter(og_msg, steps=100): guild = bot.get_guild(guild_id) if not guild: continue channel = guild.get_channel(int(channel_id)) if channel is None: continue bot.loop.create_task(self.edit_goal(bot, channel, message_id, em)) # This is to prevent endlessly waiting incase someone # decided to publish one of our messages we want to edit # if we did bounded_gather here the gather would wait until # rate limits are up for editing that one message # in this case we can send off the task to do it's thing # and forget about it. If one never finishes I don't care return
def red_bot(): from redbot.core.cli import parse_cli_flags cli_flags = parse_cli_flags([]) description = "seplib pytest" red = Red(cli_flags=cli_flags, description=description) yield red
def setup(bot: Red): bot.add_cog(Alias(bot))
def setup(bot: Red): bot.add_cog(Mod(bot))
def setup(bot: Red): bot.add_cog(Reminder(bot))
def setup(bot: Red): bot.add_cog(Reports(bot))
def setup(bot: Red): bot.add_cog(Welcome(bot))
def setup(bot: Red): bot.add_cog(Filter(bot))
def setup(bot: Red): bot.add_cog(ReactRoles(bot))