async def searchRole(cls: "PhaazebotWeb", WebRequest: ExtendedRequest, Data: WebRequestContent) -> Response: search_term: str = Data.getStr("term", "") guild_id: str = Data.getStr("guild_id", "", must_be_digit=True) if not guild_id: return await apiMissingData(cls, WebRequest, msg="invalid or missing 'guild_id'") Guild: discord.Guild = discord.utils.get(cls.BASE.Discord.guilds, id=int(guild_id)) if not Guild: return await apiDiscordGuildUnknown(cls, WebRequest) Role: discord.Role = getDiscordRoleFromString(cls.BASE.Discord, Guild, search_term, contains=True) if not Role: return await apiDiscordRoleNotFound(cls, WebRequest) data: dict = { "name": str(Role.name), "id": str(Role.id), "color": Role.color.value, "managed": Role.managed, "position": Role.position } return cls.response(text=json.dumps(dict(result=data, status=200)), content_type="application/json", status=200)
async def loggingOnAssignroleCreate(cls: "PhaazebotDiscord", Settings: DiscordServerSettings, **kwargs) -> None: """ Logs the event when someone creates a new assignrole via web. If track option `Assignrole.create` is active, it will send a message to discord Required keywords: ------------------ * `Creator` - discord.Member * `assign_role_id` - str * `trigger` - str """ logging_signature: str = "Assignrole.create" Creator: discord.Member = kwargs["Creator"] assign_role_id: str = kwargs["assign_role_id"] trigger: str = kwargs["trigger"] AssignRole: discord.Role = getDiscordRoleFromString( cls, Creator.guild, assign_role_id) assign_role_name: str = AssignRole.name if AssignRole else "(Unknown)" new_log_id: int = cls.BASE.PhaazeDB.insertQuery( table="discord_log", content={ "guild_id": Settings.server_id, "event_value": TRACK_OPTIONS[logging_signature], "initiator_id": str(Creator.id), "content": f"{Creator.name} created a new assign role {assign_role_name} with {trigger=}" }) if not (TRACK_OPTIONS[logging_signature] & Settings.track_value): return # track option not active, skip message to discord server TargetChannel: discord.TextChannel = getDiscordChannelFromString( cls, Creator.guild, Settings.track_channel, required_type="text") if not TargetChannel: return # no channel found Emb: discord.Embed = discord.Embed( title=f"Log Event - [{logging_signature}]", description=f"{Creator.name} created a assignrole", timestamp=datetime.datetime.now(), color=EVENT_COLOR_POSITIVE, url=makeWebAccessLink(cls, Creator.guild.id, new_log_id)) Emb.set_thumbnail(url=Creator.avatar_url or Creator.default_avatar_url) Emb.add_field(name="Trigger:", value=trigger, inline=False) Emb.add_field(name="Linked with role:", value=assign_role_name, inline=False) try: await TargetChannel.send(embed=Emb) except Exception as E: cls.BASE.Logger.warning( f"Can't log message: {E} {traceback.format_exc()}")
async def apiDiscordConfigsExceptionRolesCreate( cls: "PhaazebotWeb", WebRequest: ExtendedRequest) -> Response: """ Default url: /api/discord/configs/exceptionroles/create """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff Create: StorageTransformer = StorageTransformer() Create["guild_id"] = Data.getStr("guild_id", UNDEFINED, must_be_digit=True) Create["role_id"] = Data.getStr("role_id", UNDEFINED, len_max=512) # checks if not Create["guild_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'guild_id'") if not Create["role_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'role_id'") PhaazeDiscord: "PhaazebotDiscord" = cls.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(Create["guild_id"])) if not Guild: return await cls.Tree.Api.Discord.errors.apiDiscordGuildUnknown( cls, WebRequest) # get user info AuthDiscord: AuthDiscordWebUser = await authDiscordWebUser(cls, WebRequest) if not AuthDiscord.found: return await cls.Tree.Api.errors.apiMissingAuthorisation( cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member( int(AuthDiscord.User.user_id)) if not CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMemberNotFound( cls, WebRequest, guild_id=Create["guild_id"], user_id=AuthDiscord.User.user_id) # check permissions if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Create["guild_id"], user_id=AuthDiscord.User.user_id) ActionRole: discord.Role = getDiscordRoleFromString( PhaazeDiscord, Guild, Create["role_id"]) if not ActionRole: return await cls.Tree.Api.Discord.errors.apiDiscordRoleNotFound( cls, WebRequest, guild_id=Guild.id, guild_name=Guild.name, role_id=Create["role_id"]) # check if already exists res: list = cls.BASE.PhaazeDB.selectQuery( """ SELECT COUNT(*) AS `match` FROM `discord_blacklist_whitelistrole` WHERE `discord_blacklist_whitelistrole`.`guild_id` = %s AND `discord_blacklist_whitelistrole`.`role_id` = %s""", (Create["guild_id"], Create["role_id"])) if res[0]["match"]: return await cls.Tree.Api.Discord.Configs.Exceptionroles.errors.apiDiscordExceptionRoleExists( cls, WebRequest, role_id=Create["role_id"], role_name=ActionRole.name) cls.BASE.PhaazeDB.insertQuery(table="discord_blacklist_whitelistrole", content={ "guild_id": Create["guild_id"], "role_id": Create["role_id"] }) cls.BASE.Logger.debug( f"(API/Discord) Exceptionrole: {Create['guild_id']=} added: {Create['role_id']=}", require="discord:configs") return cls.response(text=json.dumps( dict(msg="Exceptionrole: Added new entry", entry=Create["role_id"], status=200)), content_type="application/json", status=200)
async def apiDiscordAssignrolesEdit(cls: "WebIndex", WebRequest: Request) -> Response: """ Default url: /api/discord/assignroles/edit """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff guild_id: str = Data.getStr("guild_id", "", must_be_digit=True) assignrole_id: str = Data.getStr("assignrole_id", "", must_be_digit=True) # checks if not guild_id: return await apiMissingData(cls, WebRequest, msg="missing or invalid 'guild_id'") if not assignrole_id: return await apiMissingData(cls, WebRequest, msg="missing or invalid 'assignrole_id'") PhaazeDiscord: "PhaazebotDiscord" = cls.Web.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(guild_id)) if not Guild: return await apiDiscordGuildUnknown(cls, WebRequest) # check if exists res_assignroles: list = await getDiscordServerAssignRoles( PhaazeDiscord, guild_id, assignrole_id=assignrole_id) if not res_assignroles: return await apiDiscordAssignRoleNotExists(cls, WebRequest) AssignRoleToEdit: DiscordAssignRole = res_assignroles.pop(0) # check all update values db_update: dict = dict() update: dict = dict() value: str = Data.getStr("role_id", UNDEFINED, must_be_digit=True) if value != UNDEFINED: AssignRole: discord.Role = getDiscordRoleFromString(cls, Guild, value) if not AssignRole: return await apiMissingData( cls, WebRequest, msg=f"Could not find any role matching '{value}'") if AssignRole > Guild.me.top_role: return await apiWrongData( cls, WebRequest, msg=f"The Role `{AssignRole.name}` is to high") db_update["role_id"] = validateDBInput(str, value) update["role_id"] = value value: str = Data.getStr("trigger", "").lower().split(" ")[0] if value: # try to get command with this trigger check_double_trigger: list = await getDiscordServerAssignRoles( cls.Web.BASE.Discord, guild_id, trigger=value) if check_double_trigger: AssignRoleToCheck: DiscordAssignRole = check_double_trigger.pop(0) # tryed to set a trigger twice if str(AssignRoleToEdit.assignrole_id) != str( AssignRoleToCheck.assignrole_id): return await apiDiscordAssignRoleExists(cls, WebRequest, trigger=value) db_update["trigger"] = validateDBInput(str, value) update["trigger"] = value # get user info DiscordUser: DiscordWebUserInfo = await cls.getDiscordUserInfo(WebRequest) if not DiscordUser.found: return await apiMissingAuthorisation(cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member(int(DiscordUser.user_id)) if not CheckMember: return await apiDiscordMemberNotFound(cls, WebRequest, guild_id=guild_id, user_id=DiscordUser.user_id) # check permissions if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await apiDiscordMissingPermission(cls, WebRequest, guild_id=guild_id, user_id=DiscordUser.user_id) if not update: return await apiWrongData(cls, WebRequest, msg=f"No changes, please add at least one") cls.Web.BASE.PhaazeDB.updateQuery( table="discord_assignrole", content=db_update, where= "`discord_assignrole`.`guild_id` = %s AND `discord_assignrole`.`id` = %s", where_values=(AssignRoleToEdit.guild_id, AssignRoleToEdit.assignrole_id)) cls.Web.BASE.Logger.debug( f"(API/Discord) Created new assign role: S:{guild_id} T:{assignrole_id} N:{str(update)}", require="discord:role") return cls.response(text=json.dumps( dict(msg="assign role successfull updated", changes=update, status=200)), content_type="application/json", status=200)
async def eventOnMemberJoin(cls: "PhaazebotDiscord", Member: discord.Member) -> None: """ Get's triggered everytime a new member joins a guild, the following action may be taken (in this order): * Send logging message * Send a welcome message to guild channel * Send a private welcome message to the new member * Give the new member a predefined role * (if the member was on this guild before) set member active in levels table """ Settings: DiscordServerSettings = await getDiscordSeverSettings( cls, Member.guild.id) link_in_name: bool = bool(ContainsLink.match(Member.name)) # logging message log_coro: Coroutine = loggingOnMemberJoin(cls, Settings, NewMember=Member, link_in_name=link_in_name) asyncio.ensure_future(log_coro, loop=cls.BASE.DiscordLoop) # send welcome message if Settings.welcome_chan and Settings.welcome_msg and (not link_in_name): WelcomeChan: discord.TextChannel = getDiscordChannelFromString( cls, Member.guild, Settings.welcome_chan, required_type="text") if WelcomeChan: welcome_msg_vars: dict = { "user-name": Member.name, "user-mention": Member.mention, "server-name": Member.guild.name, "member-count": str(Member.guild.member_count) } finished_message: str = await responseFormatter( cls, Settings.welcome_msg, var_dict=welcome_msg_vars, enable_special=True, DiscordGuild=Member.guild) try: finished_message = finished_message[:1997] await WelcomeChan.send(finished_message) except Exception as E: cls.BASE.Logger.warning( f"Can't send welcome message: {E} {traceback.format_exc()}" ) # send private welcome message if Settings.welcome_msg_priv: welcome_msg_priv_vars: dict = { "user-name": Member.name, "server-name": Member.guild.name, "member-count": str(Member.guild.member_count) } finished_message: str = await responseFormatter( cls, Settings.welcome_msg_priv, var_dict=welcome_msg_priv_vars, enable_special=True, DiscordGuild=Member.guild) try: finished_message = finished_message[:1997] await Member.send(finished_message) except Exception as E: cls.BASE.Logger.warning( f"Can't send private welcome message: {E} {traceback.format_exc()}" ) # give member autorole if Settings.autorole_id: RoleToGive: discord.Role = getDiscordRoleFromString( cls, Member.guild, Settings.autorole_id) if RoleToGive and RoleToGive < Member.guild.me.top_role: # there is a role found and phaaze can give this role try: await Member.add_roles(RoleToGive) except Exception as E: cls.BASE.Logger.warning( f"Can't add role to member: {E} {traceback.format_exc()}") # set member active, if there was a known entry cls.BASE.PhaazeDB.updateQuery(table="discord_user", content={"on_server": 1}, where="guild_id = %s AND member_id = %s", where_values=(str(Member.guild.id), str(Member.id)))
async def apiDiscordConfigsEdit(cls: "PhaazebotWeb", WebRequest: ExtendedRequest) -> Response: """ Default url: /api/discord/configs/edit """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff Edit: StorageTransformer = StorageTransformer() Edit["guild_id"] = Data.getStr("guild_id", "", must_be_digit=True) # checks if not Edit["guild_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'guild_id'") PhaazeDiscord: "PhaazebotDiscord" = cls.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(Edit["guild_id"])) if not Guild: return await cls.Tree.Api.Discord.errors.apiDiscordGuildUnknown( cls, WebRequest) # get user info AuthDiscord: AuthDiscordWebUser = await authDiscordWebUser(cls, WebRequest) if not AuthDiscord.found: return await cls.Tree.Api.errors.apiMissingAuthorisation( cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member( int(AuthDiscord.User.user_id)) if not CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMemberNotFound( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id) # check permissions # to edit configs, at least moderator rights are needed, (there can be options that require server only duh) if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id) Configs: DiscordServerSettings = await getDiscordSeverSettings( PhaazeDiscord, origin=Edit["guild_id"], prevent_new=True) if not Configs: return await cls.Tree.Api.Discord.errors.apiDiscordGuildUnknown( cls, WebRequest, msg="Could not find configs for this guild") # check all update values update: dict = dict() Edit["autorole_id"] = Data.getStr("autorole_id", UNDEFINED, len_max=128, allow_none=True) if Edit["autorole_id"] != UNDEFINED: error: bool = False if not Edit["autorole_id"]: update["autorole_id"] = None else: Role: discord.Role = getDiscordRoleFromString( PhaazeDiscord, Guild, Edit["autorole_id"]) if not Role: error = True elif Role >= Guild.me.top_role: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg=f"The Role `{Role.name}` is to high") else: update["autorole_id"] = str(Role.id) if error: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg= f"{Edit['autorole_id']} could not be resolved as a valid discord role" ) # blacklist_ban_links Edit["blacklist_ban_links"] = Data.getBool("blacklist_ban_links", UNDEFINED) if Edit["blacklist_ban_links"] != UNDEFINED: update["blacklist_ban_links"] = Edit["blacklist_ban_links"] # blacklist_punishment Edit["blacklist_punishment"] = Data.getStr("blacklist_punishment", UNDEFINED, len_max=32) if Edit["blacklist_punishment"] != UNDEFINED: Edit["blacklist_punishment"] = checkPunishmentString( Edit["blacklist_punishment"]) update["blacklist_punishment"] = Edit["blacklist_punishment"] # currency_name Edit["currency_name"] = Data.getStr("currency_name", UNDEFINED, len_max=256, allow_none=True) if Edit["currency_name"] != UNDEFINED: if not Edit['currency_name']: update["currency_name"] = None else: update["currency_name"] = Edit["currency_name"] # currency_name_multi Edit["currency_name_multi"] = Data.getStr("currency_name_multi", UNDEFINED, len_max=256, allow_none=True) if Edit["currency_name_multi"] != UNDEFINED: if not Edit["currency_name_multi"]: update["currency_name_multi"] = None else: update["currency_name_multi"] = Edit["currency_name_multi"] # leave_chan Edit["leave_chan"] = Data.getStr("leave_chan", UNDEFINED, len_max=128, allow_none=True) if Edit["leave_chan"] != UNDEFINED: error: bool = False if not Edit["leave_chan"]: update["leave_chan"] = None else: Chan: discord.TextChannel = getDiscordChannelFromString( PhaazeDiscord, Guild, Edit["leave_chan"], required_type="text") if not Chan: error = True else: update["leave_chan"] = str(Chan.id) if error: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg= f"'{Edit['leave_chan']}' could not be resolved as a valid discord text channel" ) # leave_msg Edit["leave_msg"] = Data.getStr("leave_msg", UNDEFINED, len_max=1750, allow_none=True) if Edit["leave_msg"] != UNDEFINED: if not Edit["leave_msg"]: update["leave_msg"] = None else: update["leave_msg"] = Edit["leave_msg"] # level_custom_msg Edit["level_custom_msg"] = Data.getStr("level_custom_msg", UNDEFINED, len_max=1750, allow_none=True) if Edit["level_custom_msg"] != UNDEFINED: if not Edit["level_custom_msg"]: update["level_custom_msg"] = None else: update["level_custom_msg"] = Edit["level_custom_msg"] # level_announce_chan Edit["level_announce_chan"] = Data.getStr("level_announce_chan", UNDEFINED, len_max=128, allow_none=True) if Edit["level_announce_chan"] != UNDEFINED: error: bool = False if not Edit["level_announce_chan"]: update["level_announce_chan"] = None else: Chan: discord.TextChannel = getDiscordChannelFromString( PhaazeDiscord, Guild, Edit["level_announce_chan"], required_type="text") if not Chan: error = True else: update["level_announce_chan"] = str(Chan.id) if error: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg= f"'{Edit['level_announce_chan']}' could not be resolved as a valid discord text channel" ) update["level_announce_chan"] = Edit["level_announce_chan"] # owner_disable_level Edit["owner_disable_level"] = Data.getBool("owner_disable_level", UNDEFINED) if Edit["owner_disable_level"] != UNDEFINED: if not Guild.owner == CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id, msg="changing 'owner_disable_level' require server owner") update["owner_disable_level"] = Edit["owner_disable_level"] # owner_disable_normal Edit["owner_disable_normal"] = Data.getBool("owner_disable_normal", UNDEFINED) if Edit["owner_disable_normal"] != UNDEFINED: if not Guild.owner == CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id, msg="changing 'owner_disable_level' require server owner") update["owner_disable_normal"] = Edit["owner_disable_normal"] # owner_disable_regular Edit["owner_disable_regular"] = Data.getBool("owner_disable_regular", UNDEFINED) if Edit["owner_disable_regular"] != UNDEFINED: if not Guild.owner == CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id, msg="changing 'owner_disable_level' require server owner") update["owner_disable_regular"] = Edit["owner_disable_regular"] # owner_disable_mod Edit["owner_disable_mod"] = Data.getBool("owner_disable_mod", UNDEFINED) if Edit["owner_disable_mod"] != UNDEFINED: if not Guild.owner == CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id, msg="changing 'owner_disable_level' require server owner") update["owner_disable_mod"] = Edit["owner_disable_mod"] # track_channel Edit["track_channel"] = Data.getStr("track_channel", UNDEFINED, len_max=128, allow_none=True) if Edit["track_channel"] != UNDEFINED: error: bool = False if not Edit["track_channel"]: update["track_channel"] = Edit["track_channel"] else: Chan: discord.TextChannel = getDiscordChannelFromString( PhaazeDiscord, Guild, Edit["track_channel"], required_type="text") if not Chan: error = True else: update["track_channel"] = str(Chan.id) if error: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg= f"'{Edit['track_channel']}' could not be resolved as a valid discord text channel" ) # track_value Edit["track_value"] = Data.getInt("track_value", UNDEFINED, min_x=0) if Edit["track_value"] != UNDEFINED: update["track_value"] = Edit["track_value"] # welcome_chan Edit["welcome_chan"] = Data.getStr("welcome_chan", UNDEFINED, len_max=128, allow_none=True) if Edit["welcome_chan"] != UNDEFINED: error: bool = False if not Edit["welcome_chan"]: update["welcome_chan"] = None else: Chan: discord.TextChannel = getDiscordChannelFromString( PhaazeDiscord, Guild, Edit["welcome_chan"], required_type="text") if not Chan: error = True else: update["welcome_chan"] = str(Chan.id) if error: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg= f"'{Edit['welcome_chan']}' could not be resolved as a valid discord text channel" ) # welcome_msg Edit["welcome_msg"] = Data.getStr("welcome_msg", UNDEFINED, len_max=1750, allow_none=True) if Edit["welcome_msg"] != UNDEFINED: if not Edit["welcome_msg"]: update["welcome_msg"] = None else: update["welcome_msg"] = Edit["welcome_msg"] # welcome_msg_priv Edit["welcome_msg_priv"] = Data.getStr("welcome_msg_priv", UNDEFINED, len_max=1750, allow_none=True) if Edit["welcome_msg_priv"] != UNDEFINED: if not Edit["welcome_msg_priv"]: update["welcome_msg_priv"] = None else: update["welcome_msg_priv"] = Edit["welcome_msg_priv"] if not update: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="No changes, please add at least one") cls.BASE.PhaazeDB.updateQuery(table="discord_setting", content=update, where="`discord_setting`.`guild_id` = %s", where_values=(Edit["guild_id"], )) # logging log_coro: Coroutine = loggingOnConfigEdit(PhaazeDiscord, Configs, Editor=CheckMember, changes=update) asyncio.ensure_future(log_coro, loop=cls.BASE.DiscordLoop) cls.BASE.Logger.debug( f"(API/Discord) Configs: {Edit['guild_id']=} updated", require="discord:configs") return cls.response(text=json.dumps( dict(msg="Configs: Updated", changes=update, status=200)), content_type="application/json", status=200)
async def apiDiscordAssignrolesCreate(cls: "WebIndex", WebRequest: Request) -> Response: """ Default url: /api/discord/assignroles/create """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff guild_id: str = Data.getStr("guild_id", "", must_be_digit=True) role_id: str = Data.getStr("role_id", "", must_be_digit=True) trigger: str = Data.getStr("trigger", "").lower().split( " " )[0] # only take the first argument trigger, since everything else can't be typed in a channel # checks if not guild_id: return await apiMissingData(cls, WebRequest, msg="missing or invalid 'guild_id'") if not role_id: return await apiMissingData(cls, WebRequest, msg="missing or invalid 'role_id'") if not trigger: return await apiMissingData(cls, WebRequest, msg="missing or invalid 'trigger'") PhaazeDiscord: "PhaazebotDiscord" = cls.Web.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(guild_id)) if not Guild: return await apiDiscordGuildUnknown(cls, WebRequest) # check if already exists and limits res: list = cls.Web.BASE.PhaazeDB.selectQuery( """ SELECT COUNT(*) AS `all`, SUM( CASE WHEN `discord_assignrole`.`role_id` = %s OR LOWER(`discord_assignrole`.`trigger`) = LOWER(%s) THEN 1 ELSE 0 END ) AS `match` FROM `discord_assignrole` WHERE `discord_assignrole`.`guild_id` = %s""", (role_id, trigger, guild_id)) if res[0]["match"]: return await apiDiscordAssignRoleExists(cls, WebRequest, role_id=role_id, trigger=trigger) if res[0]["all"] >= cls.Web.BASE.Limit.DISCORD_ASSIGNROLE_AMOUNT: return await apiDiscordAssignRoleLimit(cls, WebRequest) # get server role AssignRole: discord.Role = getDiscordRoleFromString(cls, Guild, role_id) if not AssignRole: return await apiMissingData( cls, WebRequest, msg=f"Could not find any role matching '{role_id}'") if AssignRole > Guild.me.top_role: return await apiWrongData( cls, WebRequest, msg=f"The Role `{AssignRole.name}` is to high") # get user info DiscordUser: DiscordWebUserInfo = await cls.getDiscordUserInfo(WebRequest) if not DiscordUser.found: return await apiMissingAuthorisation(cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member(int(DiscordUser.user_id)) if not CheckMember: return await apiDiscordMemberNotFound(cls, WebRequest, guild_id=guild_id, user_id=DiscordUser.user_id) # check permissions if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await apiDiscordMissingPermission(cls, WebRequest, guild_id=guild_id, user_id=DiscordUser.user_id) new_assign_role: dict = dict(guild_id=guild_id, trigger=trigger, role_id=role_id) cls.Web.BASE.PhaazeDB.insertQuery(table="discord_assignrole", content=new_assign_role) cls.Web.BASE.Logger.debug( f"(API/Discord) Created new assign role: S:{guild_id} T:'{trigger}' N:{str(new_assign_role)}", require="discord:role") return cls.response(text=json.dumps( dict(msg="new assign role successfull created", trigger=trigger, status=200)), content_type="application/json", status=200)
async def apiDiscordAssignrolesCreate(cls: "PhaazebotWeb", WebRequest: ExtendedRequest) -> Response: """ Default url: /api/discord/assignroles/create """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff Create: StorageTransformer = StorageTransformer() Create["guild_id"] = Data.getStr("guild_id", UNDEFINED, must_be_digit=True) Create["role_id"] = Data.getStr("role_id", UNDEFINED, must_be_digit=True) Create["trigger"] = Data.getStr("trigger", "").lower().split( " " )[0] # only take the first argument trigger, since everything else can't be typed in a channel # checks if not Create["guild_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'guild_id'") if not Create["role_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'role_id'") if not Create["trigger"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'trigger'") PhaazeDiscord: "PhaazebotDiscord" = cls.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(Create["guild_id"])) if not Guild: return await cls.Tree.Api.Discord.errors.apiDiscordGuildUnknown( cls, WebRequest) # get user info AuthDiscord: AuthDiscordWebUser = await authDiscordWebUser(cls, WebRequest) if not AuthDiscord.found: return await cls.Tree.Api.errors.apiMissingAuthorisation( cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member( int(AuthDiscord.User.user_id)) if not CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMemberNotFound( cls, WebRequest, guild_id=Create["guild_id"], user_id=AuthDiscord.User.user_id) # check permissions if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Create["guild_id"], user_id=AuthDiscord.User.user_id) # get server role AssignRole: discord.Role = getDiscordRoleFromString( PhaazeDiscord, Guild, Create["role_id"]) if not AssignRole: return await cls.Tree.Api.Discord.errors.apiDiscordRoleNotFound( cls, WebRequest, guild_id=Guild.name, guild_name=Guild.name, role_id=Create["role_id"]) if AssignRole >= Guild.me.top_role or AssignRole == Guild.default_role: return await cls.Tree.errors.piWrongData( cls, WebRequest, msg=f"The Role `{AssignRole.name}` is to high") # check if already exists and limits res: list = cls.BASE.PhaazeDB.selectQuery( """ SELECT COUNT(*) AS `all`, SUM( CASE WHEN `discord_assignrole`.`role_id` = %s THEN 1 ELSE 0 END ) AS `match_role_id`, SUM( CASE WHEN LOWER(`discord_assignrole`.`trigger`) = LOWER(%s) THEN 1 ELSE 0 END ) AS `match_trigger` FROM `discord_assignrole` WHERE `discord_assignrole`.`guild_id` = %s""", (Create["role_id"], Create["trigger"], Create["guild_id"])) if res[0]["match_role_id"]: return await cls.Tree.Api.Discord.errors.apiDiscordAssignRoleExists( cls, WebRequest, role_id=Create["role_id"], role_name=AssignRole.name) if res[0]["match_trigger"]: return await cls.Tree.Api.Discord.errors.apiDiscordAssignRoleExists( cls, WebRequest, trigger=Create["trigger"]) if res[0]["all"] >= cls.BASE.Limit.discord_assignrole_amount: return await cls.Tree.Api.Discord.errors.apiDiscordAssignRoleLimit( cls, WebRequest, limit=cls.BASE.Limit.discord_assignrole_amount) cls.BASE.PhaazeDB.insertQuery(table="discord_assignrole", content={ "guild_id": Create["guild_id"], "trigger": Create["trigger"], "role_id": str(AssignRole.id) }) # logging GuildSettings: DiscordServerSettings = await getDiscordSeverSettings( PhaazeDiscord, Create["guild_id"], prevent_new=True) log_coro: Coroutine = loggingOnAssignroleCreate( PhaazeDiscord, GuildSettings, Creator=CheckMember, assign_role_id=Create["role_id"], trigger=Create["trigger"]) asyncio.ensure_future(log_coro, loop=cls.BASE.DiscordLoop) cls.BASE.Logger.debug( f"(API/Discord) Assignroles: {Create['guild_id']=} added: {Create['trigger']=}", require="discord:configs") return cls.response(text=json.dumps( dict(msg="Assignroles: Added new entry", entry=Create["trigger"], status=200)), content_type="application/json", status=200)
async def apiDiscordAssignrolesEdit(cls: "PhaazebotWeb", WebRequest: ExtendedRequest) -> Response: """ Default url: /api/discord/assignroles/edit """ Data: WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required stuff Edit: StorageTransformer = StorageTransformer() Edit["assignrole_id"] = Data.getInt("assignrole_id", "", min_x=1) Edit["guild_id"] = Data.getStr("guild_id", "", must_be_digit=True) # checks if not Edit["assignrole_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'assignrole_id'") if not Edit["guild_id"]: return await cls.Tree.Api.errors.apiMissingData( cls, WebRequest, msg="missing or invalid 'guild_id'") # get/check discord PhaazeDiscord: "PhaazebotDiscord" = cls.BASE.Discord Guild: discord.Guild = discord.utils.get(PhaazeDiscord.guilds, id=int(Edit["guild_id"])) if not Guild: return await cls.Tree.Api.Discord.errors.apiDiscordGuildUnknown( cls, WebRequest) # check if exists res_assignroles: list = await getDiscordServerAssignRoles( PhaazeDiscord, guild_id=Edit["guild_id"], assignrole_id=Edit["assignrole_id"]) if not res_assignroles: return await cls.Tree.Api.Discord.errors.apiDiscordAssignRoleNotExists( cls, WebRequest, assignrole_id=Edit["assignrole_id"]) AssignRoleToEdit: DiscordAssignRole = res_assignroles.pop(0) # check all update values update: dict = dict() Edit["role_id"] = Data.getStr("role_id", UNDEFINED, must_be_digit=True) if Edit["role_id"] != UNDEFINED: AssignRole: discord.Role = getDiscordRoleFromString( PhaazeDiscord, Guild, Edit["role_id"]) if not AssignRole: return await cls.Tree.Api.Discord.errors.apiDiscordRoleNotFound( cls, WebRequest, guild_name=Guild.name, guild_id=Guild.id, role_id=Edit["role_id"]) if AssignRole > Guild.me.top_role or AssignRole == Guild.default_role: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg=f"The Role `{AssignRole.name}` is to high") update["role_id"] = Edit["role_id"] Edit["trigger"] = Data.getStr("trigger", "").lower().split(" ")[0] if Edit["trigger"]: # try to get command with this trigger check_double_trigger: list = await getDiscordServerAssignRoles( cls.BASE.Discord, guild_id=Edit["guild_id"], trigger=Edit["trigger"]) if check_double_trigger: AssignRoleToCheck: DiscordAssignRole = check_double_trigger.pop(0) # tried to set a trigger twice if str(AssignRoleToEdit.assignrole_id) != str( AssignRoleToCheck.assignrole_id): return await cls.Tree.Api.Discord.Assignroles.errors.apiDiscordAssignRoleExists( cls, WebRequest, trigger=Edit["trigger"]) update["trigger"] = Edit["trigger"] # get user info AuthDiscord: AuthDiscordWebUser = await authDiscordWebUser(cls, WebRequest) if not AuthDiscord.found: return await cls.Tree.Api.errors.apiMissingAuthorisation( cls, WebRequest) # get member CheckMember: discord.Member = Guild.get_member( int(AuthDiscord.User.user_id)) if not CheckMember: return await cls.Tree.Api.Discord.errors.apiDiscordMemberNotFound( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id) # check permissions if not (CheckMember.guild_permissions.administrator or CheckMember.guild_permissions.manage_guild): return await cls.Tree.Api.Discord.errors.apiDiscordMissingPermission( cls, WebRequest, guild_id=Edit["guild_id"], user_id=AuthDiscord.User.user_id) if not update: return await cls.Tree.Api.errors.apiWrongData( cls, WebRequest, msg=f"No changes, please add at least one") cls.BASE.PhaazeDB.updateQuery( table="discord_assignrole", content=update, where= "`discord_assignrole`.`guild_id` = %s AND `discord_assignrole`.`id` = %s", where_values=(AssignRoleToEdit.guild_id, AssignRoleToEdit.assignrole_id)) # logging GuildSettings: DiscordServerSettings = await getDiscordSeverSettings( PhaazeDiscord, Edit["guild_id"], prevent_new=True) log_coro: Coroutine = loggingOnAssignroleEdit( PhaazeDiscord, GuildSettings, Editor=CheckMember, assign_role_trigger=AssignRoleToEdit.trigger, changes=update) asyncio.ensure_future(log_coro, loop=cls.BASE.DiscordLoop) cls.BASE.Logger.debug( f"(API/Discord) Assignrole: {Edit['guild_id']=} edited {Edit['assignrole_id']=}", require="discord:role") return cls.response(text=json.dumps( dict(msg="Assignrole: Edited entry", changes=update, status=200)), content_type="application/json", status=200)
async def addAssignRole(cls: "PhaazebotDiscord", Command: DiscordCommand, CommandContext: DiscordCommandContext) -> dict: Perm: discord.Permissions = CommandContext.Message.channel.permissions_for( CommandContext.Message.guild.me) if not Perm.manage_roles: return { "content": ":no_entry_sign: Phaaze don't has a role with the `Manage Roles` permission." } trigger: str = CommandContext.part(1) query_str: str = " ".join(CommandContext.parts[2:]) if not trigger or not query_str: return { "content": ":warning: You need to define a role-trigger and a role." } AssignRole: discord.Role = getDiscordRoleFromString( cls, CommandContext.Message.guild, query_str, Message=CommandContext.Message) if not AssignRole: return { "content": f":warning: Could not find any role matching: `{query_str}`" } res: list = cls.BASE.PhaazeDB.selectQuery( """ SELECT COUNT(*) AS `all`, SUM( CASE WHEN `discord_assignrole`.`role_id` = %s OR LOWER(`discord_assignrole`.`trigger`) = LOWER(%s) THEN 1 ELSE 0 END ) AS `match` FROM `discord_assignrole` WHERE `discord_assignrole`.`guild_id` = %s""", (str(AssignRole.id), trigger, str(Command.server_id))) if res[0]["all"] >= cls.BASE.Limit.DISCORD_ASSIGNROLE_AMOUNT: return { "content": ":no_entry_sign: This server hit the assign role limit, please remove some first." } if res[0]["match"] >= 1: return { "content": ":no_entry_sign: This Assignrole or the used trigger already exists." } if CommandContext.Message.guild.me.top_role < AssignRole: return { "content": f":no_entry_sign: The Role `{AssignRole.name}` is to high. Phaaze highest role has to be higher in hierarchy then `{AssignRole.name}`" } cls.BASE.PhaazeDB.insertQuery(table="discord_assignrole", content=dict(guild_id=str(Command.server_id), role_id=str(AssignRole.id), trigger=trigger)) return { "content": f":white_check_mark: Successfull added assign role `{str(AssignRole)}` with trigger `{trigger}`" }