async def on_ready(): """Run post-launch setup.""" ut.log(f'{bot.user.name} has successfully connected to Discord!') # Ensure all guilds are in the DB (In case we joined one while not running) for guild in bot.guilds: Guild.first_or_create(id=guild.id)
async def setprefix(self, ctx, prefix: str = None): """ Set a custom prefix for your server """ if prefix is None: return await ctx.send_help('setprefix') guild = Guild.find_one({'guild_id': str(ctx.guild.id)}) guild['prefix'] = prefix[:5] Guild.save(guild) print(guild)
async def on_guild_join(self, guild): registering_id = None member_id = None for role in guild.roles: if role.name.lower() == "registering": registering_id = role.id if role.name.lower() == "member": member_id = role.id Guild.first_or_create(id=guild.id, registering_id=registering_id, member_id=member_id)
async def prefixes_for(guild): _guild = Guild.find_one({'guild_id': str(guild.id)}) if not _guild: guild_template = { 'guild_id': str(guild.id), 'name': guild.name, 'prefix': config.prefix } guild_id = Guild.insert_one(guild_template).inserted_id _guild = Guild.find_one({'guild_id': str(guild.id)}) return _guild.prefix
def CreateGuild(): json = request.json try: if 'nickname' in json: newGuild = Guild(json['name'], json['nickname']) else: newGuild = Guild(json['name']) db.session.add(newGuild) db.session.commit() data = jsonify(newGuild.to_dict()) data.status_code = 201 return data except IntegrityError as error: return Response(error.args[0], status=400)
async def on_member_join(self, member): """Send user a welcome message.""" if member.bot: return try: # Avoid throwing errors on users with friend-only DMs. await member.create_dm() await member.dm_channel.send( f'Hey {member.name}, welcome to the (unofficial) University ' f'of Sheffield Computer Science Discord!\n' 'We like to know who we\'re talking to, so please change your ' 'nickname on the server to include your real name ' 'in some way.\n' 'Apart from that, have fun on the server, get to know ' 'people and feel free to ask any questions about the course ' 'that you may have, ' 'we\'re all here to help each other!\n' 'Many thanks,\n' 'The Discord Server Admin Team\n\n' 'As a note, all messages that you send ' 'on the server are logged.\n' 'This is to help us in the case of messages that contain' 'offensive content and need to be reported.\n' 'If you would like your logged messages to be' 'removed for any reason, please contact <@247428233086238720>.' ) except discord.Forbidden: pass guild = Guild.find(member.guild.id) User.first_or_create(id=member.id, guild_id=guild.id) role_id = guild.registering_id await ut.add_role(member, role_id)
async def set_registering_role(self, ctx, role_id): """ Updates the registeringID for the guild. This command allows admins to update the role first given to users when they join the guild. """ if not ctx.message.role_mentions: await ctx.send("Could not find a valid role. Please ensure you " "have properly entered the role ID.") return guild = Guild.find(ctx.guild.id) if guild is None: await ctx.send("Failed to update role ID: guild was not found") return role = ctx.message.role_mentions[0] guild.registering_id = role.id guild.save() await ctx.send(f"Successfully updated registering role to {role.name}." )
async def set_welcome_msg(self, ctx, *, content: str): """ Updates the welcome message for the guild. This command allows admins to update the welcome message that users must react to when they wish to become members. """ if len(content) == 0: await ctx.send("You must include a message.") return if await ut.get_confirmation( ctx.channel, ctx.author, self.bot, "You are about to set the servers welcome" f"message to\n ```{content}```\n" "Please react with a thumbs up " "to confirm."): message = await ctx.send(content) await message.add_reaction(u"\u2705") await message.add_reaction(u"\u274E") guild = Guild.find(ctx.guild.id) guild.welcome_message_id = message.id guild.save()
async def on_raw_reaction_add(self, payload): # Member is bot, or the emoji is not relevant, # or the message reacted to is not the role assignment message guild = Guild.find(payload.guild_id) if (payload.member.bot or str(payload.emoji) not in EMOJI_TO_ROLES or payload.message_id != guild.role_assignment_msg_id): return async with ut.RemoveReaction(self, payload): # Get the corresponding role name for the emoji role_name = EMOJI_TO_ROLES[str(payload.emoji)] # Get member's existing roles member_role_names = [str(role) for role in payload.member.roles] if role_name in member_role_names: return # Return if the member is already assigned the role # Fetch the available roles from the server roles = await payload.member.guild.fetch_roles() # Get roles that are mutually exclusive mutex_roles = [role for role in roles if str(role) in MUTEX_ROLES] # Role to be assigned for role in roles: if str(role) == role_name: role_to_be_assigned = role break else: # End of for loop means role was not found channel = await self.bot.fetch_channel(payload.channel_id) return await channel.send( f"Role {role_name!r} does not exist. " "Please report this issue to an admin.") # Removes existing mutually exclusive roles if role_to_be_assigned in mutex_roles: await payload.member.remove_roles(*mutex_roles) # Adds the required role await payload.member.add_roles(role_to_be_assigned)
def setUp(self): app = create_app(test_config) with app.app_context(): db.drop_all() db.create_all() self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() guild = Guild('Flames of Exile') db.session.add(guild) db.session.commit() foe_guild = db.session.query(Guild).filter_by( name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit() campaign = Campaign('campaign_name', '/mediafiles/campaigns/campaign.png', True) db.session.add(campaign) db.session.commit() world = World('world_name', '/mediafiles/campaigns/campaign_name/world.png', 1, 1, 1, 1) db.session.add(world) db.session.commit() pin = Pin(1, 1, Pin.Symbol.ANIMAL, Pin.Resource.WOLF, 1, 1, '', 1, 1, 'notes', 1, 1) db.session.add(pin) db.session.commit() edit = Edit("", 1, 1) db.session.add(edit) db.session.commit() event = Event('event', 'game', datetime.datetime.now().isoformat(), 'note') db.session.add(event) db.session.commit() self.DEFAULT_GUILD = guild self.DEFAULT_USER = admin self.DEFAULT_CAMPAIGN = campaign self.DEFAULT_WORLD = world self.DEFAULT_PIN = pin self.DEFAULT_TOKEN = f'Bearer {self.login("DiscordBot", "admin").get_json()["token"]}' self.DEFAULT_EVENT = event self.maxDiff = None self.assertEqual(app.debug, False)
async def prefix(self, ctx): """ View the bot prefix """ guild = Guild.find_one({'guild_id': str(ctx.guild.id)}) prefix = self.config.prefix if guild: prefix = guild['prefix'] await ctx.send(f"```diff\nPrefix: { prefix }```")
def parse_guild_meta(text: str) -> Guild: rule = r"([^\[]+)\[(\w+)\]\s+(.+)" match = regex.match(rule, text) castle = match[1] tag = match[2] name = match[3] return Guild(castle=castle, tag=tag, name=name)
async def login(request: Request, code: str = None, state: str = None, error: str = None): if not code: state = token_urlsafe() auth_url = make_discord_session().get_authorize_url(scope='identify guilds', redirect_uri=urljoin(LOG_URL, request.url.path), state=state) request.session['oauth2_state'] = state return RedirectResponse(auth_url) if error: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f'There was an error authenticating with discord: {error}' ) #Verify state if request.session.get('oauth2_state') != state: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f'State mismatch' ) # Fetch token discord = make_discord_session() try: await discord.get_access_token(code, redirect_uri=urljoin(LOG_URL, request.url.path)) except Exception as e: traceback.print_exc() raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f'There was an error authenticating with discord: {e}' ) user = DiscordUser.parse_obj(await discord.request('GET', 'users/@me')) guilds = [Guild.parse_obj(obj) for obj in await discord.request('GET', 'users/@me/guilds') if int(obj.get('permissions')) & 32] log_guilds = list(map(int, await logs.distinct('guild_id'))) if not any(x.id in log_guilds for x in guilds): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f'You do not have access to modlogs in any guilds' ) doc = await users.find_one_and_update( {'id': user.id}, {"$set": { **user.dict(), **{"guilds": [guild.id for guild in guilds]} }}, upsert=True, return_document=ReturnDocument.AFTER ) request.session["user"] = SERIALIZER.dumps(str(doc.get('_id'))) target = SERIALIZER.loads(request.session.get('goto')) or app.url_path_for('root') return RedirectResponse(target)
def create_admin(): foe_guild = Guild('Flames of Exile') db.session.add(foe_guild) db.session.commit foe_guild = db.session.query(Guild).filter_by(name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt(os.environ['BOT_PASSWORD']), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit()
def guild_from_dict(guild_dict): return Guild( castle=guild_dict["castle"], tag=guild_dict["tag"], name=guild_dict["name"], before_war_status=status_from_dict(guild_dict["before_war_status"]), after_war_status=status_from_dict(guild_dict["after_war_status"]), latest_status=status_from_dict(guild_dict["latest_status"]), )
async def send_role_assignment_message(self, ctx): """ Sends the role assignment message """ guild = Guild.find(ctx.guild.id) message = await ctx.send(ROLE_ASSIGNMENT_MESSAGE) for emoji in EMOJI_TO_ROLES: await message.add_reaction(emoji) guild.role_assignment_msg_id = message.id guild.save()
async def on_raw_reaction_add(payload): if payload.member.bot: return guild = Guild.find(payload.guild_id) expected_id = guild.welcome_message_id if payload.message_id == expected_id: message = await payload.member.guild.get_channel(payload.channel_id)\ .fetch_message(payload.message_id) await message.remove_reaction(payload.emoji, payload.member) if payload.emoji.name == u"\u2705": registering_id = guild.registering_id member_id = guild.member_id await add_role(payload.member, member_id) await remove_role(payload.member, registering_id) elif payload.emoji.name == u"\u274E": await payload.member.guild.kick(payload.member, reason="Rejected T's&C's")
def ajax_subscribe(): error = [] type = request.form['subscribe-form-type'] name = request.form['subscribe-form-name'] tag = request.form['subscribe-form-tag'] description = request.form['subscribe-form-description'] region = request.form['subscribe-form-region'] print(type, name, tag, region) if len(name) < 2 or len(name) > 16: error.append('Invalid name') if len(tag) < 2 or len(tag) > 4: error.append('Invalid tag') if not error: if type == 'team': team = Team(id=uuid.uuid4(), name=name, tag=tag, shardId=region, description=description, captain=current_user.id) else: team = Guild(id=uuid.uuid4(), name=name, tag=tag, shardId=region, description=description, captain=current_user.id) try: db.session.add(team) db.session.commit() except SQLAlchemyError as e: db.session.rollback() app.logger.error('ERROR: Session rollback - reason "%s"' % str(e)) return jsonify({'error': ', '.join(error)})
async def on_guild_join(self, guild): guild_template = { 'guild_id': str(guild.id), 'name': guild.name, 'prefix': self.config.prefix } guild_id = Guild.insert_one(guild_template).inserted_id print(chalk.cyan(f"Joined Guild > ") + chalk.yellow(f'{guild.name}')) if not self.config.join_message: return try: to_send = sorted([chan for chan in guild.channels if chan.permissions_for(guild.me).send_messages and isinstance(chan, discord.TextChannel)], key=lambda x: x.position)[0] except IndexError: pass else: await to_send.send(self.config.join_message) botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None) log = botguild.get_channel(625767405641007106) await log.send(f"```css\nJoined Guild > {guild.name}```")
def setUp(self): app = create_app(test_config) with app.app_context(): db.drop_all() db.create_all() self.app = app self.test_client = app.test_client() self.app_context = app.app_context() self.app_context.push() self.socketio = SocketIO(app) self.socketio.on_event('connect', on_connect) self.socketio.on_event('campaign-update', handle_campaign_update) guild = Guild('Flames of Exile') db.session.add(guild) db.session.commit() foe_guild = db.session.query(Guild).filter_by( name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit() campaign = Campaign('campaign_name', '/mediafiles/campaign.png', True) db.session.add(campaign) db.session.commit() self.campaign = campaign.to_dict() self.maxDiff = None self.assertEqual(app.debug, False)
async def set_member_role(self, ctx, role_id): """ Updates the memberID for the guild. This command allows admins to update the role given to users once they have 'accepted' the guilds rules. """ if not ctx.message.role_mentions: await ctx.send("Could not find a valid role. Please ensure you " "have properly entered the role ID.") return guild = Guild.find(ctx.guild.id) if guild is None: await ctx.send("Failed to update role ID: guild was not found") return role = ctx.message.role_mentions[0] guild.member_id = role.id guild.save() await ctx.send(f"Successfully updated member role to {role.name}.")
def test_create_success(self): guild = Guild('new') guild.id = 2 response = self.create_guild(self.DEFAULT_TOKEN, 'new') self.assertEqual(response.status_code, 201) self.assertEqual(guild.to_dict(), response.get_json())