Esempio n. 1
0
class HelpMethods(object):
    # :a: :b: :information_source: :pisces: :m: :scorpio: :virgo: :capricorn: :o2: :o: :parking: :Aries: :negative_squared_cross_mark: :x: :grey_exclamation: :grey_question:
    # emojdup = ['🅰', '🅱', 'ℹ', '♓', 'Ⓜ', '♏', '♍', '♑', '🅾', '⭕', '🅿', '♈', '❎', '❌', '❕', '❔', '✳', '✖']

    # :ab: :cl: :id: :ng: :ok: :vs: :wc: :bangbang: :interrobang: :new: :sos: :cool: :free: :10:
    emojdoub = [
        '🆎', '🆑', '🆔', '🆖', '🆗', '🆚', '🚾', '‼', '⁉', '🆕', '🆘', '🆒', '🆓', '🔟'
    ]

    # texttomorsedic = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'}

    def cmds(self):
        global servers
        if not servers:
            servers = tilndb.servers.find_one()
        return servers

    def updatecmds(self, serversu):
        global servers
        servers = serversu
        tilndb.servers.replace_one({}, servers)

    def cmddisabled(self, sid, cmd):
        global servers
        if not servers:
            servers = tilndb.servers.find_one()
        server = servers.get(sid) or []
        for x in server:
            if cmd == x:
                return True
        return False

    def freedom(self, sid):
        global freedomf
        if not freedomf:
            freedomf = tilndb.freedom.find_one()
        server = freedomf.get(sid) or True
        return server

    async def updateroles(self,
                          ctx,
                          rolestoadd,
                          rolestoremove,
                          client,
                          allroles,
                          specuser=None):
        updater = discord.utils.get(allroles, name='Updater')
        user = ''
        cmcs = ctx.message.content.split(' ')[1]

        respond = True
        if specuser is None:
            if cmcs.isdigit():
                user = await ctx.message.server.fetch_member(cmcs)
            else:
                user = ctx.message.mentions[0]
        else:
            user = specuser
            respond = False
        if ctx.message.channel.permissions_for(
                ctx.message.author
        ).manage_roles or updater in ctx.message.author.roles:
            if ((ctx.message.mentions or cmcs.isdigit()) and len(
                    ctx.message.content.split(' ')) > 2) or respond == False:
                roles = user.roles
                for x in rolestoremove:
                    if x in roles:
                        roles.remove(x)
                for x in rolestoadd:
                    if x not in roles:
                        roles.append(x)
                await user.edit(roles=roles)
                # if rtrnothave: print(rtrnothave)
                if respond:
                    await client.say('Successfully updated role(s)')
                return True
            else:
                await client.say('Please format it as ' +
                                 ctx.message.content.split(' ')[0] +
                                 ' @username role')
        else:
            await client.say(
                "You don't have permission to use that command or that part of that command :sweat_smile: "
            )
        return False

    async def createpc(self,
                       ctx,
                       owner,
                       catnid="private channels",
                       voice=False,
                       chin=1):
        cmc = ctx.message.content.split(" ")[1:]
        if not (chan := discord.utils.get(ctx.guild.channels, name=cmc[chin])
                or discord.utils.get(ctx.guild.channels, mention=cmc[chin])):
            if not (cat := discord.utils.get(
                    ctx.guild.categories, name=catnid)) and catnid.isdigit():
                cat = discord.utils.get(ctx.guild.categories, id=int(catnid))
            if not cat:
                try:
                    cat = await ctx.guild.create_category(
                        catnid, reason="Setting up private channels")
                except discord.HTTPException:
                    await ctx.channel.send("Invalid category name.")
                    return
            overwrites = {
                ctx.guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
                owner:
                discord.PermissionOverwrite(read_messages=True,
                                            manage_messages=True,
                                            priority_speaker=True,
                                            move_members=True)
            }
            for x in ctx.guild.roles:
                if x.permissions.manage_channels or (
                        x.permissions.manage_messages
                        and x.permissions.ban_members):
                    overwrites.update(
                        {x: discord.PermissionOverwrite(read_messages=True)})
            try:
                if voice:
                    chan = await ctx.guild.create_voice_channel(
                        cmc[chin],
                        overwrites=overwrites,
                        category=cat,
                        reason="Owner: " + str(owner) + " by command of: " +
                        str(ctx.author) + ".")
                else:
                    chan = await ctx.guild.create_text_channel(
                        cmc[chin],
                        overwrites=overwrites,
                        category=cat,
                        reason="Owner: " + str(owner) + " by command of: " +
                        str(ctx.author) + ".")
                await ctx.channel.send("Channel created")
            except discord.HTTPException:
                await ctx.channel.send("Invalid channel name.")
                return
Esempio n. 2
0
    async def galaxy_room(self, member):
        '''
		To-do:
		- Link the the text channels and the voice channel to the user in the database.
		- Make control commands within the text channel
		'''
        def check_size(m):
            value = m.content
            author = m.author
            if value.isnumeric(
            ) and author == member and m.channel == bot_msg.channel:
                value = int(value)
                if value >= 0 and value <= 25:
                    return True
                else:
                    self.client.loop.create_task(
                        member.send('**Please, a number between 1 and 25!**'))
            elif not value.isnumeric(
            ) and author == member and m.channel == bot_msg.channel:
                self.client.loop.create_task(
                    member.send('**Inform a valid value!**'))

        def check_name(m):
            value = m.content
            author = m.author
            if author == member and m.channel == bot_msg.channel:
                if 0 < len(m.content) <= 20:
                    return True
                else:
                    self.client.loop.create_task(
                        member.send(file=discord.File(
                            './images/smart_vc/galaxy/3 incorrect vc name.png')
                                    ))

        def check_cat_or_txt_name(m):
            value = m.content
            author = m.author
            if author == member and m.channel == bot_msg.channel:
                if 0 < len(m.content) <= 10:
                    return True
                else:
                    self.client.loop.create_task(
                        member.send(file=discord.File(
                            './images/smart_vc/galaxy/3 incorrect text chat name or category.png'
                        )))

        def check_confirm(reaction, user):
            return user == member and str(reaction.emoji) in '✅❌'

        # Setting room configs

        # Gets the name of the category
        bot_msg = ''
        msg = await member.send(
            file=discord.File('./images/smart_vc/galaxy/3 category.png'))
        bot_msg = msg
        category_name = await self.get_response(member, check_cat_or_txt_name)

        if category_name is None:
            return

        # Gets the size of the room
        msg2 = await member.send(
            file=discord.File('./images/smart_vc/galaxy/3 select size vc.png'))
        bot_msg = msg2
        limit = await self.get_response(member, check_size)

        if limit is None:
            return

        # Gets the name of the room
        msg3 = await member.send(
            file=discord.File('./images/smart_vc/galaxy/3 select name vc.png'))
        bot_msg = msg3
        vc_name = await self.get_response(member, check_name)

        if vc_name is None:
            return

        # Gets the name of the text channel 1
        msg4 = await member.send(file=discord.File(
            './images/smart_vc/galaxy/3 select text chat 1.png'))
        bot_msg = msg4
        txt1_name = await self.get_response(member, check_cat_or_txt_name)

        if txt1_name is None:
            return

        # Gets the name of the text channel 2
        msg5 = await member.send(file=discord.File(
            './images/smart_vc/galaxy/3 select text chat 2.png'))
        bot_msg = msg5
        txt2_name = await self.get_response(member, check_cat_or_txt_name)

        if txt2_name is None:
            return

        # Gets the name of the text channel 3
        msg6 = await member.send(file=discord.File(
            './images/smart_vc/galaxy/3 select text chat 3.png'))
        bot_msg = msg6
        txt3_name = await self.get_response(member, check_cat_or_txt_name)

        if txt3_name is None:
            return

        # Makes the preview image
        #member_id, cat_name, txt1, txt2, txt3, vc, size
        await self.make_preview_galaxy(member.id, category_name, txt1_name,
                                       txt2_name, txt3_name, vc_name, limit)
        # Gets the configuration confirmation
        msg7 = await member.send(file=discord.File(
            f'./images/smart_vc/user_previews/{member.id}.png'))
        await msg7.add_reaction('✅')
        await msg7.add_reaction('❌')
        bot_msg = msg7
        reaction, user = await self.get_reaction_response(
            member, check_confirm)
        if reaction is None:
            return

        # Confirm configurations
        if str(reaction.emoji) == '✅':
            # Checks if the user has money (350łł)
            user_currency = await SlothCurrency.get_user_currency(
                member, member.id)
            if user_currency:
                if user_currency[0][1] >= 350:
                    await SlothCurrency.update_user_money(
                        member, member.id, -350)
                else:
                    return await member.send(
                        "**You don't have enough money to buy this service!**")

            else:
                return await member.send(
                    "**You don't even have an account yet!**")
            # Gets the CreateSmartRoom category, creates the VC and text channel and tries to move the user to there
            overwrites = {
                member.guild.default_role:
                discord.PermissionOverwrite(read_messages=False,
                                            send_messages=False,
                                            connect=False,
                                            speak=False,
                                            view_channel=False),
                member:
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=True,
                                            connect=True,
                                            speak=True,
                                            view_channel=True)
            }
            #, overwrites=overwrites
            category_created = await member.guild.create_category(
                name=category_name, overwrites=overwrites)
            vc_creation = await category_created.create_voice_channel(
                name=f"{vc_name}", user_limit=limit)
            txt_creation1 = await category_created.create_text_channel(
                name=f"{txt1_name}")
            txt_creation2 = await category_created.create_text_channel(
                name=f"{txt2_name}")
            txt_creation3 = await category_created.create_text_channel(
                name=f"{txt3_name}")
            # Inserts the channels in the database
            epoch = datetime.utcfromtimestamp(0)
            the_time = (datetime.utcnow() - epoch).total_seconds()
            await self.insert_galaxy_vc(member.id, category_created.id,
                                        vc_creation.id, txt_creation1.id,
                                        txt_creation2.id, txt_creation3.id,
                                        the_time)
            await member.send(
                file=discord.File('./images/smart_vc/created.png'))
            try:
                await member.move_to(vc_creation)
            except discord.errors.HTTPException:
                await member.send(
                    "**You cannot be moved because you are not in a Voice-Channel, but your channels and category will remain alive nonetheless! 👍**"
                )
            finally:
                try:
                    os.remove(
                        f'./images/smart_vc/user_previews/{member.id}.png')
                except Exception:
                    pass

        else:
            await self.galaxy_room(member)
Esempio n. 3
0
 async def on_member_join(self, m):
     self.bot.cursor.execute("select * from welcome_auth where id = ?",
                             (m.guild.id, ))
     auths = self.bot.cursor.fetchone()
     if auths:
         if bool(auths["use"]):
             if type(auths["next_reaction"]) is int:
                 nr = self.bot.get_emoji(auths["next_reaction"])
             else:
                 nr = auths["next_reaction"]
             ow = {
                 m:
                 discord.PermissionOverwrite(read_messages=True,
                                             send_messages=True),
                 m.guild.default_role:
                 discord.PermissionOverwrite(read_messages=False),
                 m.guild.me:
                 discord.PermissionOverwrite(read_messages=True,
                                             send_messages=True,
                                             manage_messages=True)
             }
             for i in auths["can_view"]:
                 rl = m.guild.get_role(i)
                 if rl:
                     ow[rl] = discord.PermissionOverwrite(
                         read_messages=True)
             cg = m.guild.get_channel(auths["category"])
             if cg:
                 ch = await cg.create_text_channel(f"sinaauth-{m.name}",
                                                   overwrites=ow,
                                                   topic=str(m.id),
                                                   position=0)
             else:
                 ch = await m.guild.create_text_channel(
                     f"sinaauth-{m.name}",
                     overwrites=ow,
                     topic=str(m.id),
                     position=0)
             msg = await ch.send("please wait...\nしばらくお待ちください…")
             for i in auths["au_w"]:
                 await msg.edit(content=None,
                                embed=ut.getEmbed(
                                    f"サーバーユーザー認証",
                                    f"※{nr}で進行します。\n{i['text']}"))
                 for r in i["reactions"]:
                     if type(r) is int:
                         rct = self.bot.get_emoji(r)
                     else:
                         rct = r
                     await msg.add_reaction(rct)
                 await msg.add_reaction(nr)
                 r, u = await self.bot.wait_for(
                     "reaction_add",
                     check=lambda r, u: r.message.id == msg.id and u.id == m
                     .id and r.emoji == auths["next_reaction"])
                 ridx = [
                     i["reactions"].index(r.emoji)
                     for r in r.message.reactions
                     if r.count == 2 and r.emoji != nr
                 ]
                 for ri in ridx:
                     grl = m.guild.get_role(i["give_role"][ri])
                     if grl:
                         await m.add_roles(grl)
                 await msg.clear_reactions()
             await m.add_roles(m.guild.get_role(auths["give_role"]))
             await ch.send("> サーバーユーザー認証\n あなたの認証が完了しました!")
Esempio n. 4
0
    async def match(self, ctx, *params):
        """
        Abre un canal de texto para una carrera privada.

        Opcionalmente, puede asignársele un nombre. Si no se indica, se pondrá un nombre por defecto.

        Tras el nombre, debe mencionarse a los jugadores o roles que participarán en la carrera. Si no se menciona a ninguno, únicamente el creador de la carrera tendrá acceso al canal.

        Este comando solo puede ser ejecutado por un moderador.
        """
        db_conn, db_cur = open_db(ctx.guild.id)
        
        creator = ctx.author

        if not params:
            close_db(db_conn)
            raise commands.errors.CommandInvokeError("Faltan argumentos para ejecutar el comando.")

        # Comprobación de límite: máximo de 10 carreras privadas en el servidor
        races = get_active_private_races(db_cur)
        if races and len(races) >= 10:
            close_db(db_conn)
            raise commands.errors.CommandInvokeError("Demasiadas carreras activas en el servidor. Contacta a un moderador para purgar alguna.")

        # Comprobación de nombre
        name = params[0]
        players = params[1:]
        if re.match(r'<@[!&]?\d+>', name):
            name = "carrera-privada"
            players = params
        
        if len(name) > 20:
            name = name[:20]
        
        # Obtener participantes de la carrera
        participants = [ctx.author]
        roles = []
        for p in players:
            mention = re.match(r'<@!?(\d+)>', p)
            if mention:
                discord_id = int(mention.group(1))
                member = ctx.guild.get_member(discord_id)
                if member:
                    participants.append(member)
                continue
            mention = re.match(r'<@&(\d+)>', p)
            if mention:
                role_id = int(mention.group(1))
                role = ctx.guild.get_role(role_id)
                if role:
                    roles.append(role)

        # Crear canal para la carrera
        channel_overwrites = {
            ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            ctx.guild.me: discord.PermissionOverwrite(read_messages=True)
        }
        for m in participants:
            channel_overwrites[m] = discord.PermissionOverwrite(read_messages=True)
        for r in roles:
            channel_overwrites[r] = discord.PermissionOverwrite(read_messages=True)

        race_channel = await ctx.guild.create_text_channel(name, overwrites=channel_overwrites)

        async with write_lock:    
            for p in participants:
                insert_player_if_not_exists(db_cur, p.id, p.name, p.discriminator, p.mention)
            insert_private_race(db_cur, name, creator.id, race_channel.id)
            commit_db(db_conn)

        close_db(db_conn)

        text_ans = 'Abierta carrera privada con nombre: {}\nCanal: {}'.format(name, race_channel.mention)

        await ctx.reply(text_ans, mention_author=False)
Esempio n. 5
0
    async def on_raw_reaction_add(self, payload):
        if payload.channel_id == self.bot.config["apply_channel"]:
            if not payload.member:
                return
            if payload.member.bot:
                return
            channel = self.bot.get_channel(payload.channel_id)
            message = await channel.fetch_message(payload.message_id)
            member = payload.member
            if not member:
                return
            await message.remove_reaction(str(payload.emoji), member)

            doc = await self.bot.db.links.find_one({"user": member.id})
            if not doc:
                return await channel.send("**Please Link Your Account First!**", delete_after=3)

            uuid = doc["uuid"]
            ign = await uuid_to_name(self.bot, uuid)
            cat = self.bot.get_channel(self.bot.config["app_category"])

            overwrites = {
                channel.guild.default_role: discord.PermissionOverwrite(read_messages=False),
                channel.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True,
                                                              manage_messages=True),
                member: discord.PermissionOverwrite(
                    read_messages=True, send_messages=True)
            }

            apply_for_staff = await self.check_if_in_guild(uuid)

            nc = await channel.guild.create_text_channel(f"app-{member.name}", category=cat, overwrites=overwrites)
            if not apply_for_staff:
                try:
                    embed = discord.Embed()
                    embed.title = "Welcome to your Application"
                    embed.description = "You now need to answer some basic questions."

                    await nc.send(member.mention, embed=embed)

                    embed = discord.Embed()
                    embed.title = "Timezone"
                    embed.description = "Which timezone are you in, eg. GMT, CET?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    timezone = msg.content

                    embed = discord.Embed()
                    embed.title = "Why do you want to join us?"
                    embed.description = "How did you find our guild? What makes you interested?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    why = msg.content

                    embed = discord.Embed()
                    embed.title = "Can you be able to reach the guild requirement of %s?" % self.bot.config[
                        "req_xp"]
                    embed.description = \
                        "If yes, tell us how much xp you'll get on average, and if not, why not and how much you can get!"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    xpreq = msg.content

                    embed = discord.Embed()
                    embed.title = "Tell us a joke"
                    embed.description = "Whats your best joke?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    joke = msg.content

                    embed = discord.Embed()
                    embed.title = "Can you join our waitlist guild?"
                    embed.description = "If you cant, you wont be able to join our main guild."

                    mesg = await nc.send(embed=embed)
                    for e in ("✅", "❎"):
                        await mesg.add_reaction(e)
                    r = None
                    r, u = await self.bot.wait_for("reaction_add",
                                                check=lambda r, u: u.id == member.id and r.message.id == mesg.id and str(
                                                    r.emoji) in ("✅", "❎"),
                                                timeout=60*10)
                    waitlist = str(r.emoji) == "✅"
                except:
                    await nc.delete(reason="Application Timed Out!")
                    await member.send("Application Timed Out!")
                    return

                await nc.send("**Application Submitted! This channel will be deleted in 5 seconds!**")

                embed = discord.Embed()
                embed.title = "Application!"
                embed.description = "A new application has come in!"
                embed.color = discord.Color(random.randint(0x000000, 0xffffff))

                embed.add_field(name="IGN", value=uuid + " | " + ign, inline=True)
                embed.add_field(name="Discord", value=member.mention, inline=True)
                embed.add_field(name="Timezone", value=timezone, inline=False)
                embed.add_field(name="Reason for joining", value=why, inline=False)
                embed.add_field(name="Joke", value=joke, inline=False)
                embed.add_field(name="XP requirement", value=xpreq, inline=False)
                embed.add_field(name="Waitlist join", value=waitlist, inline=False)
                applications = self.bot.get_channel(
                    self.bot.config["applications"])
                m = await applications.send(embed=embed)
                await m.add_reaction("🤗")
                await asyncio.sleep(5)
                await nc.delete(reason="Application Finished!")
            else:
                try:
                    embed = discord.Embed()
                    embed.title = "Welcome to your Application"
                    embed.description = "You now need to answer some qusetions on why you want to become helper."

                    await nc.send(member.mention, embed=embed)

                    embed = discord.Embed()
                    embed.title = "Reason"
                    embed.description = "Why do you want to become a helper? What qualifies you?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    reason = msg.content



                    embed = discord.Embed()
                    embed.title = "Why Are You better?"
                    embed.description = "What puts you above other applicants? Why should we choose you?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    better = msg.content

                    embed = discord.Embed()
                    embed.title = "Referals"
                    embed.description = "Do you have any past expirience with moderating? What other servers have you / are you moderating?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    referals = msg.content


                    embed = discord.Embed()
                    embed.title = "Senario One: Ping Spam"
                    embed.description = "Someone is mentioning other users in the chat, repetedly and randomly. How do you react as a helper?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    s1 = msg.content

                    embed = discord.Embed()
                    embed.title = "Senario Two: Doxxing"
                    embed.description = "Someone is sending private/personal information about another member. How do you react as a helper?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    s2 = msg.content

                    embed = discord.Embed()
                    embed.title = "Senario Three: Toxicity"
                    embed.description = "Someone is being toxic in chat, lightly swearing at others and calling people bad. How do you react as a helper?"

                    await nc.send(embed=embed)
                    msg = await self.bot.wait_for("message",
                                                check=lambda m: m.author.id == member.id and m.channel.id == nc.id,
                                                timeout=60*10)
                    s3 = msg.content
                    await nc.send("**Application Submitted! This channel will be deleted in 5 seconds!**")

                    embed = discord.Embed()
                    embed.title = "Application!"
                    embed.description = "A new application for helper has come in! Current status: 'POSTED'"
                    embed.color = discord.Color(0x0000ff)

                    embed.add_field(name="IGN", value=uuid + " | " + ign, inline=True)
                    embed.add_field(name="Discord", value=member.mention, inline=True)
                    embed.add_field(name="Reason", value=reason, inline=False)
                    embed.add_field(name="Better than others", value=better, inline=False)
                    embed.add_field(name="Referals", value=referals, inline=False)
                    embed.add_field(name="Senario One: Ping Spamming", value=s1, inline=False)
                    embed.add_field(name="Senario Two: Doxxing", value=s2, inline=False)
                    embed.add_field(name="Senario Threee: Toxicity", value=s3, inline=False)
                    applications = self.bot.get_channel(
                        self.bot.config["helper_apps"])
                    m = await applications.send(embed=embed)
                    for e in ("✅", "❎"): await m.add_reaction(e)
                    await self.bot.db.helper_apps.insert_one({
                        "user": member.id,
                        "answers": {
                            "reason": reason,
                            "better": better,
                            "referals": referals,
                            "s1": s1,
                            "s2": s2,
                            "s3": s3
                        },
                        "status": "POSTED",
                        "message": m.id,
                        "deny_reason": None
                    })
                    await asyncio.sleep(5)
                    await nc.delete(reason="Application Finished!")
                except:
                    await nc.delete(reason="Application Timed Out!")
                    await member.send("Application Timed Out!")
                    return
        doc = await self.bot.db.helper_apps.find_one({
            "message": payload.message_id,
            "status": "POSTED"
        })
        if not doc:
            return
        if not payload.member:
            return
        if payload.member.bot:
            return

        channel = self.bot.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        member = payload.member
        if not member:
            return
        await message.remove_reaction(str(payload.emoji), member)

        if str(payload.emoji) in ("✅", "❎"):
            await message.clear_reactions()
            member = channel.guild.get_member(doc["user"])
            if str(payload.emoji) == "✅":
                color = discord.Color(0x00ff00)
                doc["status"] = "ACCEPTED"
                role = channel.guild.get_role(self.bot.config["helper_role"])
                await member.add_roles(role)
                try:
                    embed = discord.Embed(color=color)
                    embed.title = "Application Accepted!"
                    embed.description = "Your application has been accepted, and you have been added to the staff team."
                    await member.send(embed=embed)
                except:
                    pass
            else:
                color = discord.Color(0xff0000)
                await channel.send("**Please enter a reason for denial**, if you dont enter one in 30 seconds, it will default to none given.", delete_after=30)
                try:
                    m = await self.bot.wait_for("message", check=lambda m: m.author.id == member.id and m.channel.id == channel.id, timeout=30)
                    doc["deny_reason"] = m.content
                except:
                    doc["deny_reason"] = "No Given Reason!"
                try:
                    embed = discord.Embed(color=color)
                    embed.title = "Application Denied!"
                    embed.description = "Your application has been denied, you may re-apply in 3 months. Reason: '%s'" % doc["deny_reason"]
                    await member.send(embed=embed)
                except:
                    pass
                doc["status"] = "DENIED"

            await self.bot.db.helper_apps.find_one_and_replace({
            "message": payload.message_id,
            "status": "POSTED"
            }, doc)
            embed = message.embeds[0]
            embed.color = color
            embed.description = "Application! Current status: '%s'" % doc["status"]
            await message.edit(embed=embed)
Esempio n. 6
0
    async def transfer(self, ctx, member: discord.Member):
        # send to channel due to unsuccessful recruit
        try:
            if await isRecruiter(ctx) and await isRecruitee(ctx, member):
                emojis = [
                    "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣",
                    "9️⃣"
                ]
                channels = self.server["channels"]
                field = "Please react with the corresponding number: \n"
                for i in range(len(channels) - 1):
                    field += f"\n{emojis[i]} `#{self.client.get_channel(channels[list(channels)[i+1]]).name}`"

                embed = discord.Embed()
                embed.add_field(name="Where would you like to send this user?",
                                value=field)
                embed.set_footer(text=self.server["general"]["footer"],
                                 icon_url=self.client.user.avatar_url)
                message = await ctx.send(embed=embed)
                for e in emojis:
                    await message.add_reaction(e)

                def check(reaction, user):
                    return user == ctx.message.author and str(
                        reaction.emoji
                    ) in emojis and reaction.message.id == message.id

                try:
                    reaction, user = await self.client.wait_for('reaction_add',
                                                                check=check,
                                                                timeout=300)
                except asyncio.TimeoutError:
                    return await message.clear_reactions()

                for e in range(len(emojis)):
                    if str(reaction.emoji) == emojis[e]:
                        targetName = list(channels)[e + 1]
                        targetChannel = self.client.get_channel(
                            channels[targetName])
                        await ctx.channel.set_permissions(member,
                                                          overwrite=None)
                        overwrite = discord.PermissionOverwrite(
                            send_messages=True,
                            read_messages=True,
                            read_message_history=True)

                        if targetName == "General":
                            await member.remove_roles(
                                ctx.channel.guild.get_role(
                                    self.server["roles"]["Recruitee"]))
                            await member.add_roles(
                                ctx.channel.guild.get_role(
                                    self.server["roles"]["General"]))
                            await targetChannel.send(
                                f"(・ω・)ノ <@{member.id}> has joined the party!")
                            emoji = ""
                            recruitees = self.data.getRecruitees()
                            try:
                                recruitees.pop(str(member.id))
                            except:
                                pass
                            self.data.updateRecruitees(recruitees)
                        else:
                            if self.server["isOpen"][targetName] == "closed":
                                embed = discord.Embed()
                                embed.add_field(
                                    name=
                                    f"{targetName} is currently closed to new recruits! Please try a different guild ❌",
                                    value=f"** **")
                                embed.set_footer(
                                    text=self.server["general"]["footer"],
                                    icon_url=self.client.user.avatar_url)
                                await message.edit(embed=embed)
                                return await message.clear_reactions()
                            await targetChannel.set_permissions(
                                member, overwrite=overwrite)
                            leaderRole = self.server["roles"][targetName]
                            await targetChannel.send(
                                f"(・ω・)ノ <@{member.id}> has landed! (Sent over by @{ctx.author.name}) <@&{leaderRole}>"
                            )
                            recruitees = self.data.getRecruitees()
                            try:
                                recruitees[str(member.id)].append(
                                    f"[Transferred to {targetName} by @{ctx.author.name}]"
                                )
                            except:
                                pass
                            self.data.updateRecruitees(recruitees)
                            chatLog = "\n".join(recruitees[str(member.id)])
                            if len(chatLog) > 2000:
                                chatLog = chatLog[:1900] + "..."

                            embed = discord.Embed()
                            embed.add_field(
                                name=
                                f"{member.name}'s previous chat logs for your convenience:",
                                value=f"** **\n```{chatLog}```")
                            embed.set_footer(
                                text=self.server["general"]["footer"],
                                icon_url=self.client.user.avatar_url)
                            await targetChannel.send(embed=embed)
                            emoji = self.server["emojis"][targetName]

                        embed = discord.Embed()
                        embed.add_field(
                            name=
                            f"@{member.name} has been transferred to {targetName} {emoji}✅",
                            value=f"** **")
                        embed.set_footer(text=self.server["general"]["footer"],
                                         icon_url=self.client.user.avatar_url)
                        await message.edit(embed=embed)
                        await message.clear_reactions()
                        await logUsage(
                            f"@{member.name} has been transferred to {targetName} by @{ctx.author.name}.",
                            self.client)
                        break

        except Exception as e:
            await handleException(e, self.client)
def override_to_dpy(override_dict: dict):
    # dict comprehension because the structure might change later
    return discord.PermissionOverwrite(
        **{k: v
           for (k, v) in override_dict.items()})
Esempio n. 8
0
async def castVote(person):
    global vote
    global playerObjectList
    global origChannel
    global townName
    global werewolfChannel
    global timeToVote
    global nominationsToday
    global townName
    global voting
    global votedLive
    global votedDie
    global canNominate
    global nominees
    global nominators
    global gameIsRunning
    if gameIsRunning:
        await bot.send_message(origChannel, person.player.mention + " has been nominated and seconded. ")
        await bot.send_message(origChannel, person.player.mention + ", you have 20 seconds to state your defense.")
        unmuted = discord.PermissionOverwrite(send_messages=True)
        muted = discord.PermissionOverwrite(send_messages=False)
        for i in playerObjectList:
            if i != person:
                await bot.edit_channel_permissions(origChannel, i.player, muted)
        await asyncio.sleep(20)
        await bot.send_message(origChannel, "The time has come to vote! Use the \"w!live\" command or the \"w!die\" command IN THE PRIVATE WEREWOLF DM to vote for " + person.player.mention + ". You have 20 seconds to cast your vote, or you can abstain from voting.")
        timeToVote = True
        for i in playerObjectList:
            await bot.edit_channel_permissions(origChannel, i.player, unmuted)
        await asyncio.sleep(20)
        result = await tallyVote(vote)
        if result == "live":
            for i in votedLive:
                await bot.send_message(origChannel, i.player.mention + " voted live.")
            for i in votedDie:
                await bot.send_message(origChannel, i.player.mention + " voted  die.")
            for i in playerObjectList:
                if not i.hasVoted:
                    await bot.send_message(origChannel, i.player.mention + " abstained from voting.")
            await asyncio.sleep(1)
            await bot.send_message(origChannel, "The people have spoken, " + person.player.mention + " must live.")

            vote = []
            voting = False
            canNominate = True
            timeToVote = False
            votedLive = []
            votedDie = []
            nominees = []
            nominators = {}
            for i in playerObjectList:
                i.hasVoted = False
            if nominationsToday == 1:
                await bot.send_message(origChannel, "You may nominate one more person today. The night will start automatically if no one is nominated and seconded within the next 30 seconds.")
                print("Nominations today = " + str(nominationsToday))
                await delayStartNight(30)
            else:
                await bot.send_message(origChannel, "Having nominated two people, the town of " + townName + " goes to bed. The night will start in 30 seconds.")
                await night(30)
        elif result == "die":
            for i in votedLive:
                await bot.send_message(origChannel, i.player.mention + " voted live.")
            for i in votedDie:
                await bot.send_message(origChannel, i.player.mention + " voted  die.")
            for i in playerObjectList:
                if not i.hasVoted:
                    await bot.send_message(origChannel, i.player.mention + " abstained from voting.")
            await asyncio.sleep(1)
            await bot.send_message(origChannel, "The people have spoken, " + person.player.mention + " must be executed for their crimes.")
            await displayLog(person)
            await displayTeam(person)
            await bot.send_message(person.player, "You have been executed.")
            await bot.edit_channel_permissions(origChannel, person.player, muted)
            if person.role == "werewolf":
                await bot.edit_channel_permissions(werewolfChannel, person.player, muted)
            print("\n\nChecking win for vote\n\n")
            playerObjectList.remove(person)
            test = await checkWin()
            if test == None:
                vote = []
                voting = False
                canNominate = False
                timeToVote = False
                votedLive = []
                votedDie = []
                nominees = []
                nominators = {}
                for i in playerObjectList:
                    i.hasVoted = False
                await bot.send_message(origChannel, "Having satisfied it's lust for blood, the town of " + townName + " goes to bed. The night will start in 30 seconds.")
                await night(30)
        elif result == None:
            for i in playerObjectList:
                await bot.send_message(origChannel, i.player.mention + " abstained from voting.")
            await bot.send_message(origChannel, "Since apparently everyone (INCLUDING the people who nominated and seconded) chickened out of voting, " + person.player.mention + " gets to live I guess.")
            vote = []
            voting = False
            canNominate = True
            timeToVote = False
            votedLive = []
            votedDie = []
            nominees = []
            nominators = {}
            for i in playerObjectList:
                i.hasVoted = False
            if nominationsToday == 1:
                await bot.send_message(origChannel, "You may nominate one more person today. The night will start automatically if no one is nominated and seconded within the next 30 seconds.")
                await delayStartNight(30)
            else:
                await bot.send_message(origChannel, "Having nominated two people, the town of " + townName + " goes to bed. The night will start in 30 seconds.")
                await night(30)
        else:
            print(result)
            await stopGame()
Esempio n. 9
0
import discord

CHANNEL_ADMIN = discord.PermissionOverwrite(
    read_messages=True,
    send_messages=True,
    manage_messages=True,
    manage_channels=True,
    read_message_history=True
)
CHANNEL_READ_WRITE = discord.PermissionOverwrite(
    read_messages=True,
    send_messages=True,
    read_message_history=True,
)
CHANNEL_HIDDEN = discord.PermissionOverwrite(
    read_messages=False,
    send_messages=False,
    read_message_history=False
)
CHANNEL_READ = discord.PermissionOverwrite(
    read_messages=True,
    send_messages=False,
    read_message_history=True
)
Esempio n. 10
0
    async def rebuildGuild(self, guild, reboot=False, verbose=False):
        try:
            config = self.get_config(guild)
            lst = [f"{guild}  [{guild.id}]"]

            # leave guild not in YATA database
            if not len(config):
                lst.append(f'\tWTF I\'m doing here?')
                # send message to guild
                owner = self.get_user(guild.owner_id)
                await owner.send(
                    f"Contact Kivou [2000607] if you want me on your guild {guild} [{guild.id}]."
                )
                await owner.send(
                    "As for now I can't do anything without him setting me up... so I'll be leaving."
                )

                # leave guild
                await guild.leave()

                # send message to creator
                for administratorId in self.administrators:
                    administrator = self.get_user(int(administratorId))
                    await administrator.send(
                        f"On reboot I left **{guild} [{guild.id}]** owned by **{owner}** because no configurations were found in the database."
                    )

                if verbose:
                    await fmt.send_tt(verbose, lst)
                return

            # push guild name to yata
            bot = get(guild.members, id=self.user.id)
            await push_guild_info(guild, bot, self.bot_id)

            # stop if not managing channels
            if not config["admin"].get("manage", False):
                lst.append("Skip managing")
                if verbose:
                    await fmt.send_tt(verbose, lst)
                return

            # create category
            yata_category = get(guild.categories, name="yata-bot")
            bot_role = get(guild.roles, name=self.user.name)
            if yata_category is None:
                lst.append("Create category yata-bot")
                yata_category = await guild.create_category("yata-bot")

            # create admin channel
            channel_name = "yata-admin"
            if get(guild.channels, name=channel_name) is None:
                lst.append(f"\tCreate channel {channel_name}")
                overwrites = {
                    guild.default_role:
                    discord.PermissionOverwrite(read_messages=False),
                    bot_role:
                    discord.PermissionOverwrite(read_messages=True)
                }
                channel_admin = await guild.create_text_channel(
                    channel_name,
                    topic="Administration channel for the YATA bot",
                    overwrites=overwrites,
                    category=yata_category)
                await channel_admin.send(
                    f"This is the admin channel for `!verifyAll`, `!checkFactions` or `!reviveServers`"
                )

            # create verified role and channels
            if self.check_module(guild, "verify"):
                role_verified = get(guild.roles, name="Verified")
                if role_verified is None:
                    lst.append(f"\tCreate role Verified")
                    role_verified = await guild.create_role(name="Verified")

                # create faction roles
                fac = config.get("factions", dict({}))
                for k, v in fac.items():
                    role_name = f"{v} [{k}]" if config['verify'].get(
                        'id', False) else f"{v}"
                    if get(guild.roles, name=role_name) is None:
                        lst.append(f"\tCreate faction role {role_name}")
                        await guild.create_role(name=role_name)

                # create common role
                com = config['verify'].get("common")
                if com:
                    role_name = get(guild.roles, name=com)
                    if role_name is None:
                        lst.append(f"\tCreate common role {com}")
                        await guild.create_role(name=com)

                for channel_name in [
                        c
                        for c in config["verify"].get("channels", ["verify"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        channel_verif = await guild.create_text_channel(
                            channel_name,
                            topic="Verification channel for the YATA bot",
                            category=yata_category)
                        await channel_verif.send(
                            f"If you haven't been assigned the {role_verified.mention} that's where you can type `!verify` or `!verify tornId` to verify another member"
                        )

            if self.check_module(guild, "chain"):
                # create chain channel
                for channel_name in [
                        c for c in config["chain"].get("channels", ["chain"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        channel_chain = await guild.create_text_channel(
                            channel_name,
                            topic="Chain channel for the YATA bot",
                            category=yata_category)
                        await channel_chain.send(
                            "Type `!chain` here to start getting notifications and `!stopchain` to stop them."
                        )
                    # if reboot:
                    #     await get(guild.channels, name=channel_name).send(":arrows_counterclockwise: I had to reboot which stop all potential chains and retals watching. Please relaunch them.")

            if self.check_module(guild, "crimes"):
                # create crimes channel
                for channel_name in [
                        c for c in config["crimes"].get("channels", ["oc"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        channel_oc = await guild.create_text_channel(
                            channel_name,
                            topic="Crimes channel for the YATA bot",
                            category=yata_category)
                        await channel_oc.send(
                            "Type `!oc` here to start/stop getting notifications when ocs are ready."
                        )

            if self.check_module(guild, "loot"):
                # create Looter role
                role_loot = get(guild.roles, name="Looter")
                if role_loot is None:
                    lst.append(f"\tCreate role Looter")
                    role_loot = await guild.create_role(name="Looter",
                                                        mentionable=True)

                # create loot channel
                for channel_name in [
                        c for c in config["loot"].get("channels", ["loot"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        overwrites = {
                            guild.default_role:
                            discord.PermissionOverwrite(read_messages=False),
                            role_loot:
                            discord.PermissionOverwrite(read_messages=True),
                            bot_role:
                            discord.PermissionOverwrite(read_messages=True)
                        }
                        channel_loot = await guild.create_text_channel(
                            channel_name,
                            topic="Loot channel for the YATA bot",
                            overwrites=overwrites,
                            category=yata_category)
                        await channel_loot.send(
                            f"{role_loot.mention} will reveive notification here"
                        )
                        await channel_loot.send(
                            "Type `!loot` here to get the npc timings")
                        await channel_loot.send(
                            f"Type `!looter` to remove your {role_loot.mention} role"
                        )

            if self.check_module(guild, "revive"):
                # create Reviver role
                reviver = get(guild.roles, name="Reviver")
                if reviver is None:
                    lst.append(f"\tCreate role Reviver")
                    reviver = await guild.create_role(name="Reviver",
                                                      mentionable=True)

                # create revive channel
                for channel_name in [
                        c
                        for c in config["revive"].get("channels", ["revive"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        channel_revive = await guild.create_text_channel(
                            channel_name,
                            topic="Revive channel for the YATA bot",
                            category=yata_category)
                        await channel_revive.send(
                            f"{reviver.mention} will reveive notifications here"
                        )
                        await channel_revive.send(
                            "Type `!revive` or `!r` here to send a revive call"
                        )
                        await channel_revive.send(
                            f"Type `!reviver` to add or remove your {reviver.mention} role"
                        )

            if self.check_module(guild, "api"):
                # create api channels
                for channel_name in [
                        c for c in config["api"].get("channels", ["api"])
                        if c != "*"
                ]:
                    if get(guild.channels, name=channel_name) is None:
                        lst.append(f"\tCreate channel {channel_name}")
                        channel_api = await guild.create_text_channel(
                            channel_name,
                            topic="API channel for the YATA bot",
                            category=yata_category)
                        await channel_api.send(
                            "Use the API module commands here")

            # create socks role and channels
            if self.check_module(guild, "stocks"):
                stocks = config.get("stocks")

                # wssb and tcb
                for stock in [
                        s for s in stocks
                        if s not in ["active", "channels", 'alerts']
                ]:
                    stock_role = get(guild.roles, name=stock)
                    if stock_role is None:
                        lst.append(f"\tCreate role {stock}")
                        stock_role = await guild.create_role(name=stock)

                    # create stock channel
                    if get(guild.channels, name=stock) is None:
                        lst.append(f"\tCreate channel {stock}")
                        overwrites = {
                            guild.default_role:
                            discord.PermissionOverwrite(read_messages=False),
                            stock_role:
                            discord.PermissionOverwrite(read_messages=True),
                            bot_role:
                            discord.PermissionOverwrite(read_messages=True)
                        }
                        channel_stock = await guild.create_text_channel(
                            stock,
                            topic=f"{stock} stock channel for the YATA bot",
                            overwrites=overwrites,
                            category=yata_category)
                        await channel_stock.send(
                            f"Type `!{stock}` to see the {stock} BB status amoung the members"
                        )

                # create alerts
                if stocks.get("alerts"):
                    stock_role = get(guild.roles, name="Trader")
                    if stock_role is None:
                        lst.append(f"\tCreate role Trader")
                        stock_role = await guild.create_role(name="Trader",
                                                             mentionable=True)

                    for channel_name in [
                            c for c in config["stocks"].get(
                                "channels", ["stocks"]) if c != "*"
                    ]:
                        if get(guild.channels, name=channel_name) is None:
                            lst.append(f"\tCreate channel {channel_name}")
                            overwrites = {
                                guild.default_role:
                                discord.PermissionOverwrite(
                                    read_messages=False),
                                stock_role:
                                discord.PermissionOverwrite(
                                    read_messages=True),
                                bot_role:
                                discord.PermissionOverwrite(read_messages=True)
                            }
                            channel_stock = await guild.create_text_channel(
                                channel_name,
                                topic=f"Alerts stock channel for the YATA bot",
                                overwrites=overwrites,
                                category=yata_category)
                            await channel_stock.send(
                                f"{stock_role.mention} will be notified here")

            if verbose:
                await fmt.send_tt(verbose, lst)

        except BaseException as e:
            print(f'ERROR in {guild} [{guild.id}]: {e}')
            print(f'{traceback.format_exc()}')
            if verbose:
                await verbose.send(f'```ERROR in {guild} [{guild.id}]: {e}```')
                await verbose.send(f'```{traceback.format_exc()}```')
Esempio n. 11
0
async def day(delay):
    global playerObjectList
    global origChannel
    global time
    global townName
    global isFirstNight
    global werewolfVote
    global nominationsToday
    global canNominate
    global allWerewolvesVoted
    global haveWerewolvesEaten
    global nominationsToday
    global gameIsRunning
    await asyncio.sleep(delay)
    if gameIsRunning:
        muted = discord.PermissionOverwrite(send_messages = False)
        unmuted = discord.PermissionOverwrite(send_messages = True)
        time = "day"
        allWerewolvesVoted = False
        nominationsToday = 0
        isFirstNight = False
        if werewolfVote != []:
            victim = await tallyVote(werewolfVote)
            victim.wasAttacked = True
            haveWerewolvesEaten = True
            werewolfVote = []
            victim.causeOfDeath = " was torn to shreds by werewolves last night."
        await bot.send_message(origChannel, "@everyone, the sun rises on the town of " + townName + ".")
        for person in playerObjectList:
            if person.role != "lalma":
                person.usedAbility = False
            if person.wasAttacked == True and person.invulnerable == False:
                await bot.send_message(origChannel, person.player.mention + person.causeOfDeath)
                await displayLog(person)
                await displayTeam(person)
                if person.role == "werewolf":
                    await bot.edit_channel_permissions(werewolfChannel, person.player, muted)
                await bot.edit_channel_permissions(origChannel, person.player, muted)
                playerObjectList.remove(person)
            elif person.wasAttacked == True and person.invulnerable == True:
                await bot.send_message(origChannel, person.player.mention + " was attacked last night, but miraculously survived.")
                person.wasAttacked = False
                person.invulnerable = False
                person.causeOfDeath = None
        
        print("\n\nChecking win for overnight kills\n\n")
        whoWon = await checkWin()

        if whoWon == None:
            for person in playerObjectList:
                if person.silenced == False:
                    await bot.edit_channel_permissions(origChannel, person.player, unmuted)
                else:
                    person.silenced = False
                    await bot.send_message(person.player, "You have been silenced. You cannot talk for today.")
            await bot.send_message(origChannel, "You have 60 seconds to talk amongst yourselves before nominations can begin.")
            await asyncio.sleep(60)
            await bot.send_message(origChannel, "You may now start nominating people! Use the \"w!nominate [player name here]\" command to nominate someone, and use the \"w!second [player name here]\" command to second someone. You have 30 seconds to nominate someone before the next night will begin automatically.")
            canNominate = True
            for person in playerObjectList:
                if person.markedByVampire == True:
                    await bot.send_message(origChannel, person.player.mention + " feels a sharp pain in their chest and falls to the ground.")
                    await displayLog(person)
                    await displayTeam(person)
                    await bot.send_message(person.player, "You had a heart attack and died.")
                    if person.role == "werewolf":
                        await bot.edit_channel_permissions(werewolfChannel, person.player, muted)
                    await bot.edit_channel_permissions(origChannel, person.player, muted)
                    playerObjectList.remove(person)
            print("\n\nChecking win for vampire kills\n\n")
            test = await checkWin()
            if test == None:
                await asyncio.sleep(30)
                if nominationsToday == 0:
                    canNominate = False
                    await bot.send_message(origChannel, "No one was nominated and seconded today. The night will start in 30 seconds.")
                    await night(30)
Esempio n. 12
0
    async def _enter_race(self, ctx):
        """Start an animal race and enter yourself as participant

            Returns:
                Two text outputs. One to start the race,
                and the second to represent the race. The second
                msg will be edited multiple times to represent the race.

            Notes:
                Must wait 2 minutes after every race to start a new one.
                You cannot start a race if a race is already active.
                A race is considered active once this command is used.
                A race is considered started once the track is displayed.
                The user who starts a race, will be automatically entered.
                The bot will always join a race.
                There are no cheaters and it isn't rigged.
        """
        author = ctx.message.author
        server = ctx.message.server
        data = self.check_server(author.server)
        cooldown = self.check_cooldown(author.server)
        settings = self.check_config(author.server)
        cost = settings["Cost"]
        timer = 600

        channel = ctx.message.channel
        if channel.name != "race":
            return await self.bot.say(
                "You cannot run this command in this channel. Please run this command at #race"
            )

        if data['Race Active']:
            if author.id in data['Players']:
                return await self.bot.say("You are already in the race!")
            elif not self.bank_check(settings, author):
                return await self.bot.say(
                    "You do not meet the cost of entry. You need at least {} credits."
                    .format(cost))
            elif len(data['Players']) == 10:
                return await self.bot.say(
                    "There are no more spots left in the race!")
            else:
                bank = self.bot.get_cog('Economy').bank
                bank.withdraw_credits(author, cost)
                data['Players'][author.id] = {}
                return await self.bot.say("**{}** entered the race!".format(
                    author.display_name))

        if time.time() - cooldown < timer:
            return await self.bot.say(
                "You need to wait {} before starting another race.".format(
                    self.time_format(int(timer - (time.time() - cooldown)))))

        if self.bank_check(settings, author):
            bank = self.bot.get_cog('Economy').bank
            bank.withdraw_credits(author, cost)
        else:
            return await self.bot.say(
                "You do not meet the cost of entry. You need atleast {} credits."
                .format(cost))

        role_name = "Race"
        raceRole = discord.utils.get(server.roles, name=role_name)
        if raceRole is None:
            await self.bot.create_role(server, name=role_name)
            raceRole = discord.utils.get(server.roles, name=role_name)

        self.game_teardown(data, force=True)
        data['Race Active'] = True
        data['Players'][author.id] = {}
        wait = settings['Time']

        await self.bot.edit_role(server, raceRole, mentionable=True)
        await self.bot.say(
            ":triangular_flag_on_post: {} has started a race! Type ``{}re`` "
            "to join! :triangular_flag_on_post:\n{}The {} will "
            "begin in {} seconds!".format(author.mention, ctx.prefix, ' ' * 23,
                                          raceRole.mention, wait))
        await self.bot.edit_role(server, raceRole, mentionable=False)

        await asyncio.sleep(wait)

        racers = self.game_setup(author, data, settings['Mode'])

        await self.bot.say(
            ":checkered_flag: The race is now in progress :checkered_flag:")

        data['Race Start'] = True

        perm = discord.PermissionOverwrite(send_messages=False,
                                           read_messages=False)
        await self.bot.edit_channel_permissions(ctx.message.channel,
                                                server.default_role, perm)

        race_msg = await self.bot.say(
            '\u200b' + '\n' + '\n'.join([player.field() for player in racers]))
        await self.run_game(racers, race_msg, data)

        first = ':first_place:  {0.display_name}'.format(*data['First'])
        fv = '{1} {2:.2f}s'.format(*data['First'])
        second = ':second_place: {0.display_name}'.format(*data['Second'])
        sv = '{1} {2:.2f}s'.format(*data['Second'])
        if data['Third']:
            mention = "{} {} {}".format(data['First'][0].mention,
                                        data['Second'][0].mention,
                                        data['Third'][0].mention)
            third = ':third_place:  {0.display_name}'.format(*data['Third'])
            tv = '{1} {2:.2f}s'.format(*data['Third'])
        else:
            mention = "{} {}".format(data['First'][0].mention,
                                     data['Second'][0].mention)
            third = ':third_place:'
            tv = '--'

        perm = discord.PermissionOverwrite(send_messages=None,
                                           read_messages=False)
        await self.bot.edit_channel_permissions(ctx.message.channel,
                                                server.default_role, perm)

        embed = discord.Embed(colour=0x00CC33)
        embed.add_field(name=first, value=fv)
        embed.add_field(name=second, value=sv)
        embed.add_field(name=third, value=tv)
        embed.add_field(
            name='-' * 70,
            value=
            'Type ``>race claim`` to receive prize money. \nType ``>togglerole race`` to get notified on the next race.'
        )
        embed.title = "Race Results"
        embed.set_footer(text=credits, icon_url=creditIcon)
        await self.bot.say(content=mention, embed=embed)

        self.game_teardown(data)

        self.cooldown[server.id] = time.time()
Esempio n. 13
0
async def create_interview(guild: discord.Guild,
                           interviewee: discord.Member,
                           raid_level: int = 0):
    """
    Creates an interview channel for a given member, then starts the interview.
    """

    interview_category: discord.CategoryChannel = await get_category(
        guild, guild_settings['interview_category_id'])

    channel_name = "{}-Interview".format(interviewee.name,
                                         interviewee.discriminator)
    channel_topic = "Temporary interview room for {}".format(interviewee.name)

    member_role = guild.get_role(guild_settings['member_role_id'])
    ignore_interview_role: discord.Role = guild.get_role(
        guild_settings["hide_interviews_id"])
    greeter_role = guild.get_role(guild_settings['team_role_id'])

    cooldown_configs: List[Dict] = bot.guild_setting(guild.id,
                                                     'cooldown_config')
    cooldown_roles: List[discord.Role] = [
        guild.get_role(cooldown_config["role"])
        for cooldown_config in cooldown_configs
    ]

    inactive_configs: List[Dict] = bot.guild_setting(
        guild.id, 'inactive_member_configs')
    inactive_roles: List[discord.Role] = [
        guild.get_role(inactive_config["role"])
        for inactive_config in inactive_configs
    ]

    new_perms = category_perms = interview_category.overwrites  # Inherit perms from the category.
    """
    Perms should be set as follows for proper functionality:
    @Everyone: All perms Inherit. This is essential for making the no interviews role work.
    @Hide Interviews: Read: Deny
    @Member: Read: Inherit
    @Greeter: Read: Allow, Send: Allow
    @Cooldown & @Inactive Member: Deny
    Role override for everyone with no roles -> Read: Deny.
    Role override for interviewee -> Read: Allow, Send: Allow.
    """

    new_perms[guild.default_role] = discord.PermissionOverwrite(
        send_messages=None, read_messages=None, add_reactions=False
    )  # @Everyone: All perms Inherit. This is essential for making the no interviews role work.

    new_perms[member_role] = discord.PermissionOverwrite(
        send_messages=False, read_messages=None, add_reactions=False
    )  # The Member Role. Doesn't need Read perms. It will defacto get them even w/ None. This is essential for making the no interviews role work.
    new_perms[greeter_role] = discord.PermissionOverwrite(
        send_messages=True, read_messages=True, add_reactions=True
    )  # Make sure greeters can see and interact with interviews.

    # Prohibit cooldown, inactive members, & Hide interviews from seeing the interviews
    for deny_access_role in cooldown_roles + inactive_roles + [
            ignore_interview_role
    ]:
        new_perms[deny_access_role] = discord.PermissionOverwrite(
            send_messages=False, read_messages=False)

    # Add role overrides for any user with no roles, except the interviewee
    roleless_members = [
        member for member in guild.members if len(member.roles) == 1
    ]
    for roleless_member in roleless_members:
        if roleless_member != interviewee:
            new_perms[roleless_member] = discord.PermissionOverwrite(
                send_messages=False, read_messages=False)

    if raid_level > 0:  # Raid Protection Enabled
        new_perms[guild.default_role] = discord.PermissionOverwrite(
            send_messages=False, read_messages=False)  # @Everyone
        new_perms[member_role] = discord.PermissionOverwrite(
            send_messages=False, read_messages=False)  # The Member Role

    new_perms[interviewee] = discord.PermissionOverwrite(
        send_messages=True, read_messages=True,
        add_reactions=True)  # The user who just joined

    # Create the channel
    interview_channel = await guild.create_text_channel(
        channel_name,
        category=interview_category,
        topic=channel_topic,
        overwrites=new_perms)

    await asyncio.sleep(
        1)  # Wait a sec after the channel is created before sending anything.

    await interview_channel.send(guild_settings['welcome_message'].format(
        guild=guild, user=interviewee))

    await asyncio.sleep(1)  # Wait another sec before opening the interview.

    # Open the interview.
    interview = await open_interviews.new_interview(interviewee,
                                                    interview_channel)
Esempio n. 14
0
 async def serverload(self, ctx, server=":"):  # filenames cannot contain : so I'm using this as a workaround to make it only use the current server ID if no server is given
     """Load an entire server?!?!?!??!
     Loads in the saved data from a previously saved server.
     Usage:
     >serverload - Attempt to find a save of the current server and load it.
     >serverload <filename> - Find a saved server by filename (if a whole filename is not given, the latest save from all of the filenames that contain the given filename is used)
     """
     if not os.path.exists("server_save") or not os.listdir("server_save"):
         return await ctx.send(self.bot.bot_prefix + "You have no servers saved!")
     
     saves = os.listdir("server_save")
     guild_saves = [x for x in saves if server in x or str(ctx.guild.id) in x]
     
     if not guild_saves:
         return await ctx.send(self.bot.bot_prefix + "That server couldn't be found in your saves.")
         
     parsed_guild_saves = [datetime.strptime(x.split("_")[2].split(".")[0], "%Y-%m-%d") for x in guild_saves]
     
     server_save = guild_saves[parsed_guild_saves.index(max(parsed_guild_saves))]
     
     await ctx.send(self.bot.bot_prefix + "Loading server... (this may take a few minutes, check console for progress)")
     
     print("Beginning server load process...")
     
     with open("server_save/" + server_save, "r") as f:
         g = json.load(f)
         
     print("Loading roles...")
      
     for role in ctx.guild.roles[:]:
         if role.name not in [x["name"] for x in g["roles"]]:
             await role.delete(reason="Loading saved server")
     for role in g["roles"]:
         permissions = discord.Permissions()
         permissions.update(**dict(role["permissions"]))
         if role["name"] not in [x.name for x in ctx.guild.roles]:
             await ctx.guild.create_role(name=role["name"], colour=discord.Colour.from_rgb(*role["colour"]), hoist=role["hoist"], mentionable=role["mentionable"], permissions=permissions, reason="Loading saved server")
         else:
             await [x for x in ctx.guild.roles if x.name == role["name"]][0].edit(name=role["name"], colour=discord.Colour.from_rgb(*role["colour"]), hoist=role["hoist"], mentionable=role["mentionable"], permissions=permissions, reason="Loading saved server")
             
     print("Loading text channels...")
        
     for channel in ctx.guild.text_channels:
         if channel.name not in [x["name"] for x in g["text_channels"]]:
             await channel.delete(reason="Loading saved server")
     for channel in g["text_channels"]:
         overwrites = []
         for overwrite in channel["overwrites"]:
             if overwrite["type"] == "role":
                 if overwrite["name"] not in [x.name for x in ctx.guild.roles]:
                     pass
                 else:
                     role = [x for x in ctx.guild.roles if x.name == overwrite["name"]][0]
                     permissions = discord.PermissionOverwrite()
                     permissions.update(**dict(overwrite["permissions"]))
                     overwrites.append((role, permissions))
             else:
                 if overwrite["name"] not in [x.name for x in ctx.guild.members]:
                     pass
                 else:
                     member = [x for x in ctx.guild.members if x.name == overwrite["name"]][0]
                     permissions = discord.PermissionOverwrite()
                     permissions.update(**dict(overwrite["permissions"]))
                     overwrites.append((member, permissions))
         if channel["name"] in [x.name for x in ctx.guild.text_channels]:
             channel_obj = [x for x in ctx.guild.text_channels if x.name == channel["name"]][0]
             await channel_obj.edit(name=channel["name"], topic=channel["topic"], reason="Loading saved server")
             overwrites_dict = dict(overwrites)
             for overwrite in overwrites_dict:
                 await channel_obj.set_permissions(overwrite, overwrite=overwrites_dict[overwrite], reason="Loading saved server")
         else:
             new_chan = await ctx.guild.create_text_channel(channel["name"], overwrites=dict(overwrites), reason="Loading saved server")
             await new_chan.edit(topic=channel["topic"], nsfw=channel["nsfw"], reason="Loading saved server")
             
     print("Loading voice channels...")   
       
     for channel in ctx.guild.voice_channels:
         if channel.name not in [x["name"] for x in g["voice_channels"]]:
             await channel.delete(reason="Loading saved server")
     for channel in g["voice_channels"]:
         if channel["name"] not in [x.name for x in ctx.guild.voice_channels]:
             overwrites = []
             for overwrite in channel["overwrites"]:
                 if overwrite["type"] == "role":
                     if overwrite["name"] not in [x.name for x in ctx.guild.roles]:
                         pass
                     else:
                         role = [x for x in ctx.guild.roles if x.name == overwrite["name"]][0]
                         permissions = discord.PermissionOverwrite()
                         permissions.update(**dict(overwrite["permissions"]))
                         overwrites.append((role, permissions))
                 else:
                     if overwrite["name"] not in [x.name for x in ctx.guild.members]:
                         pass
                     else:
                         members = [x for x in ctx.guild.members if x.name == overwrite["name"]][0]
                         permissions = discord.PermissionOverwrite()
                         permissions.update(**dict(overwrite["permissions"]))
                         overwrites.append((member, permissions))
             if channel["name"] in [x.name for x in ctx.guild.voice_channels]:
                 channel_obj = [x for x in ctx.guild.voice_channels if x.name == channel["name"]][0]
                 await channel_obj.edit(name=channel["name"], topic=channel["topic"], reason="Loading saved server")
                 overwrites_dict = dict(overwrites)
                 for overwrite in overwrites_dict:
                     await channel_obj.set_permissions(overwrite, overwrite=overwrites_dict[overwrite], reason="Loading saved server")
             else:
                 new_chan = await ctx.guild.create_voice_channel(channel["name"], overwrites=dict(overwrites), reason="Loading saved server")
                 await new_chan.edit(bitrate=channel["bitrate"], user_limit=channel["user_limit"], reason="Loading saved server")
             
     print("Loading emotes...")       
           
     for emoji in ctx.guild.emojis:
         if emoji.name not in [x["name"] for x in g["emojis"]]:
             await emoji.delete(reason="Loading saved server")
     for emoji in g["emojis"]:
         if emoji["name"] in [x.name for x in ctx.guild.emojis]:
             await [x for x in ctx.guild.emojis if x.name == emoji["name"]][0].delete(reason="Loading saved server")
         await ctx.guild.create_custom_emoji(name=emoji["name"], image=requests.get(emoji["url"]).content, reason="Loaded saved server")
             
     print("Positioning channels and roles...")
             
     # set up channel and role positions
     for channel in g["text_channels"]:
         await [x for x in ctx.guild.text_channels if x.name == channel["name"]][0].edit(position=channel["position"] if channel["position"] < len(ctx.guild.text_channels) else len(ctx.guild.text_channels) - 1)
         
     for channel in g["voice_channels"]:
         await [x for x in ctx.guild.voice_channels if x.name == channel["name"]][0].edit(position=channel["position"] if channel["position"] < len(ctx.guild.voice_channels) else len(ctx.guild.voice_channels) - 1)
         
     for role in g["roles"]:
         if role["name"] != "@everyone":
             await [x for x in ctx.guild.roles if x.name == role["name"]][0].edit(position=role["position"] if role["position"] < len(ctx.guild.roles) else len(ctx.guild.roles) - 1)
         
     print("Editing server settings...")
         
     await ctx.guild.edit(name=g["name"], icon=requests.get(g["icon"].rsplit(".", 1)[0] + ".png").content if g["icon"] else None, region=discord.VoiceRegion(g["region"]), afk_channel=[x for x in ctx.guild.voice_channels if x.name == g["afk_channel"]][0] if g["afk_channel"] else None, afk_timeout=g["afk_timeout"], verification_level=discord.VerificationLevel(g["verification_level"]), reason="Loading saved server")
     
     print("Finished loading server backup!")
Esempio n. 15
0
    async def guildTimeout(self, ogChannel, member):
        try:

            def whosent(m):
                return isRecruiterMessage(m.author) and m.channel == ogChannel

            message = await self.client.wait_for('message',
                                                 check=whosent,
                                                 timeout=600)
        except asyncio.TimeoutError:
            openGuilds = 0
            for guild in self.server["isOpen"]:
                if self.server["isOpen"][guild] == "open":
                    openGuilds += 1
            if openGuilds < 2:
                return await ogChannel.send(
                    "All other guilds are closed! Unable to redirect.")
            channels = self.server["channels"]
            for i in range(len(channels)):
                if channels[list(channels)[i]] == ogChannel.id:
                    index = i + 1
                    if index >= len(self.server["channels"]):
                        index = 2
                    break
            while True:
                nextChannel = list(channels)[index]
                if self.server["isOpen"][nextChannel] == "open":
                    break
                else:
                    index += 1
                    if index >= len(self.server["channels"]):
                        index = 2

            channel = self.client.get_channel(channels[nextChannel])
            leaderRole = self.server["roles"][nextChannel]
            overwrite = discord.PermissionOverwrite(send_messages=True,
                                                    read_messages=True,
                                                    read_message_history=True)
            for role in range(1, len(member.roles)):
                await member.remove_roles(member.roles[role])
            await member.add_roles(
                channel.guild.get_role(self.server["roles"]["Recruitee"]))
            await ogChannel.set_permissions(member, overwrite=None)
            await ogChannel.send(
                f"`User has been sent to another guild due to timeout.`")
            await channel.set_permissions(member, overwrite=overwrite)
            await channel.send(
                f"(・ω・)ノ <@{member.id}> has arrived! (Redirected due to timeout) <@&{leaderRole}>\nGuild leaders have 10m to respond or <@{member.id}> will be redirected to a new channel."
            )

            recruitees = self.data.getRecruitees()
            try:
                recruitees[str(member.id)].append(
                    f"[Sent to {nextChannel} due to timeout]")
            except:
                pass
            self.data.updateRecruitees(recruitees)

            chatLog = "\n".join(recruitees[str(member.id)])
            if len(chatLog) > 2000:
                chatLog = chatLog[:1900] + "..."

            embed = discord.Embed()
            embed.add_field(
                name=
                f"{member.name}'s previous chat logs for your convenience:",
                value=f"** **\n```{chatLog}```")
            embed.set_footer(text=self.server["general"]["footer"],
                             icon_url=self.client.user.avatar_url)
            await channel.send(embed=embed)

            await logUsage(
                f"@{member.name} has been sent to #{channel.name} by @Raider Bot due to timeout.",
                self.client)
            await self.guildTimeout(channel, member)
async def create_join_channels(client):
    start_time = time()
    if not client.is_ready():
        return

    to_remove = []
    priv_channels = list(cfg.PRIV_CHANNELS.keys())
    for pc in priv_channels:
        try:
            pcv = cfg.PRIV_CHANNELS[pc]
        except KeyError:
            print("Ignoring error:")
            traceback.print_exc()
            continue

        if 'request_time' in pcv and time() - pcv['request_time'] > 120:
            # Unable to create join channel for 120s
            to_remove.append(pc)
            await pcv['text_channel'].send(
                ":warning: {} For some reason I was unable to create your \"⇩ Join\" channel, please try again later. "
                "Your channel is still private, but there's now no way for anyone to join you. "
                "Use `{}public` to make it public again."
                "".format(pcv['creator'].mention, pcv['prefix']))
            log("Failed to create join-channel, timed out.")
            continue

        guild = client.get_guild(pcv['guild_id'])
        if guild not in func.get_guilds(client):
            continue
        settings = utils.get_serv_settings(guild)
        for p, pv in settings['auto_channels'].items():
            for s, sv in pv['secondaries'].items():
                if 'priv' in sv and 'jc' not in sv:
                    creator = pcv['creator'].display_name
                    vc = pcv['voice_channel']

                    c_position = vc.position

                    overwrites = vc.overwrites
                    k = guild.default_role
                    v = overwrites[
                        k] if k in overwrites else discord.PermissionOverwrite(
                        )
                    v.update(connect=True)
                    overwrites[k] = v

                    try:
                        jc = await guild.create_voice_channel(
                            "⇩ Join {}".format(
                                creator),  # TODO creator can change
                            category=vc.category,
                            overwrites=overwrites)
                    except discord.errors.Forbidden:
                        to_remove.append(pc)
                        try:
                            await pcv['text_channel'].send(
                                ":warning: {} I don't have permission to make the \"⇩ Join\" channel for you anymore."
                                "".format(pcv['creator'].mention))
                        except:
                            log("Failed to create join-channel, and failed to notify {}"
                                .format(creator))
                            break
                    utils.permastore_secondary(jc.id)
                    settings['auto_channels'][p]['secondaries'][s][
                        'jc'] = jc.id
                    utils.set_serv_settings(guild, settings)
                    to_remove.append(pc)
                    try:
                        # Set position again, sometimes create_voice_channel gets it wrong.
                        await jc.edit(position=c_position)
                    except discord.errors.Forbidden:
                        # Harmless error, no idea why it sometimes throws this, seems like a bug.
                        pass
                    break

    for i in to_remove:
        try:
            del cfg.PRIV_CHANNELS[i]
        except KeyError:
            # Already deleted somehow.
            print("Ignoring error:")
            traceback.print_exc()
            pass

    end_time = time()
    fn_name = "create_join_channels"
    cfg.TIMINGS[fn_name] = end_time - start_time
    if cfg.TIMINGS[fn_name] > 10:
        await func.log_timings(client, fn_name)
Esempio n. 17
0
    async def recruit(self, ctx, member: discord.Member):
        # recruit a user to a guild
        try:
            if await isRecruiter(ctx) and await isRecruitee(ctx, member):
                channels = self.server["channels"]
                for c in channels:
                    if channels[c] == ctx.channel.id:
                        channelName = c

                embed = discord.Embed()
                embed.add_field(
                    name=
                    f"Do you want to recruit @{member.name} to {channelName}?",
                    value=
                    f"Please react with the corresponding emoji:\n\n✅`Yes`\n❌`No`\n"
                )
                embed.set_footer(text=self.server["general"]["footer"],
                                 icon_url=self.client.user.avatar_url)
                message = await ctx.send(embed=embed)
                await message.add_reaction("✅")
                await message.add_reaction("❌")

                def check(reaction, user):
                    return user == ctx.message.author and (
                        str(reaction.emoji) == "✅" or str(reaction.emoji)
                        == "❌") and reaction.message.id == message.id

                try:
                    reaction, user = await self.client.wait_for('reaction_add',
                                                                check=check,
                                                                timeout=300)
                except asyncio.TimeoutError:
                    return await message.clear_reactions()

                embed = discord.Embed()
                embed.set_footer(text=self.server["general"]["footer"],
                                 icon_url=self.client.user.avatar_url)
                if str(reaction.emoji) == "✅":
                    await ctx.channel.set_permissions(member, overwrite=None)
                    overwrite = discord.PermissionOverwrite(
                        send_messages=True,
                        read_messages=True,
                        read_message_history=True)
                    await member.remove_roles(
                        ctx.channel.guild.get_role(
                            self.server["roles"]["Recruitee"]))
                    await member.add_roles(
                        ctx.channel.guild.get_role(
                            self.server["roles"][channelName]))
                    with open("data/server.json", "w") as f:
                        self.server["newMembers"][channelName] += 1
                        json.dump(self.server, f, indent=4)
                    emoji = self.server["emojis"][channelName]
                    embed.add_field(
                        name=
                        f"@{member.name} has been recruited to {channelName} {emoji}✅",
                        value="** **")
                    guildChannel = self.client.get_channel(
                        self.server["guildChannels"][channelName])
                    await guildChannel.send(
                        f"<@{member.id}> has arrived! `(Recruited to {channelName} by {ctx.author.name})`{emoji}"
                    )
                    recruitees = self.data.getRecruitees()
                    try:
                        recruitees.pop(str(member.id))
                    except:
                        pass
                    self.data.updateRecruitees(recruitees)
                    await logUsage(
                        f"@{member.name} has been recruited to {channelName} by @{ctx.author.name}.",
                        self.client)
                elif str(reaction.emoji) == "❌":
                    embed.add_field(
                        name=f"@{member.name}'s recruitment has been aborted ❌",
                        value="** **")
                await message.edit(embed=embed)
                await message.clear_reactions()
        except Exception as e:
            await handleException(e, self.client)
Esempio n. 18
0
    async def setup(self, *, creator=None, category=None):
        """Create the thread channel and other io related initialisation tasks"""

        self.bot.dispatch('thread_create', self)

        recipient = self.recipient

        # in case it creates a channel outside of category
        overwrites = {
            self.bot.modmail_guild.default_role:
                discord.PermissionOverwrite(read_messages=False)
        }

        category = category or self.bot.main_category

        if category is not None:
            overwrites = None

        channel = await self.bot.modmail_guild.create_text_channel(
            name=self.manager.format_channel_name(recipient),
            category=category,
            overwrites=overwrites,
            reason='Creating a thread channel'
        )

        self._channel = channel

        try:
            log_url, log_data = await asyncio.gather(
                self.bot.api.create_log_entry(recipient, channel,
                                              creator or recipient),
                self.bot.api.get_user_logs(recipient.id)
            )

            log_count = sum(1 for log in log_data if not log['open'])
        except:  # Something went wrong with database?
            log_url = log_count = None
            # ensure core functionality still works

        info_embed = self.manager.format_info_embed(recipient, log_url,
                                                    log_count,
                                                    discord.Color.green())

        topic = f'User ID: {recipient.id}'
        if creator:
            mention = None
        else:
            mention = self.bot.config.get('mention', '@here')

        async def send_genesis_message():
            try:
                msg = await channel.send(mention, embed=info_embed)
                self.bot.loop.create_task(msg.pin())
                self.genesis_message = msg
            except:
                pass
            finally:
                self.ready = True
                self.bot.dispatch('thread_ready', self)

        await channel.edit(topic=topic)
        self.bot.loop.create_task(send_genesis_message())

        # Once thread is ready, tell the recipient.
        thread_creation_response = self.bot.config.get(
            'thread_creation_response',
            'The staff team will get back to you as soon as possible.'
        )

        embed = discord.Embed(
            color=self.bot.mod_color,
            description=thread_creation_response,
            timestamp=channel.created_at,
        )

        footer = 'Your message has been sent'
        if not self.bot.config.get('disable_recipient_thread_close'):
            footer = 'Click the lock to close the thread'

        footer = self.bot.config.get('thread_creation_footer', footer)
        embed.set_footer(text=footer, icon_url=self.bot.guild.icon_url)
        embed.title = self.bot.config.get('thread_creation_title',
                                          'Thread Created')

        if creator is None:
            msg = await recipient.send(embed=embed)
            if not self.bot.config.get('disable_recipient_thread_close'):
                close_emoji = self.bot.config.get('close_emoji', '🔒')
                close_emoji = await self.bot.convert_emoji(close_emoji)
                await msg.add_reaction(close_emoji)
Esempio n. 19
0
async def on_message(message):
    server = client.get_server("366177253673140224")
    if message.author == client.user:
        return  #prevent a bot talking to himself

    elif message.content.startswith('.'):
        text = message.content[1:]  # the message's content without the .
        endCommand = text.find(" ") + 1
        contenu = str(text[endCommand:])

        if text == "help":
            content = "`.help` Affiche ce menu. ( Tu viens de le faire, non ? :thinking:)\n\
`.ping` Donne la latence du bot.\n\
`.info` Affiche la description de ProBot\n\
`.invite` Donne un lien pour inviter ProBot"

            emb = discord.Embed(description=content)
            emb.set_author(name="Probot's help menu",
                           icon_url=client.user.avatar_url)
            await client.send_message(message.channel, embed=emb)

        if text == "ping":
            timePing = time.monotonic()
            pinger = await client.send_message(message.channel,
                                               ":ping_pong: **Pong !**")
            ping = '%.2f' % (1000 * (time.monotonic() - timePing))
            await client.edit_message(
                pinger,
                ":ping_pong: **Pong !**\nLatence : " + '`' + ping + " ms`.")

        if text.startswith("say"):
            arguments = text[4:].split(" | ")
            print(arguments)
            if "^#" in arguments:
                print("un #")
            target = message.channel

            emb = discord.Embed(title="Title",
                                description="Hope it's working...")
            #emb.set_author(name=client.user.name, icon_url=client.user.avatar_url)
            await client.send_message(target, embed=emb)

        if text == "info":
            content = "*Mince, c'est là qu'il faut se présenter...*\n\
**Hey, salut à ~~toutes~~ et à tous !** ; ici pour augmenter le nombre de membres et faire pro.\n\
Utilisez `.help` pour la liste des commandes.\n"

            emb = discord.Embed(description=content)
            emb.set_author(name="Probot, official ProTech's bot",
                           icon_url=client.user.avatar_url)
            emb.set_footer(text="Coded with ❤ by FrenchMasterSword#5079")
            await client.send_message(message.channel, embed=emb)

        #if text == "invite":

        # MODERATION-ONLY commands
        moderateur = discord.utils.get(server.roles, id='366182752602554369')
        print(message.author.top_role.name)
        target = None
        if message.author.top_role >= moderateur:
            overwrite = discord.PermissionOverwrite()
            ID = text[-19:
                      -1]  # extract the ID of any mention ending the message
            if text.startswith("mute"):
                target = discord.utils.get(server.members, id=ID)
                overwrite.read_messages = False
                await client.edit_channel_permissions(message.channel, target,
                                                      overwrite)
                await client.send_message(
                    message.channel,
                    target.mention + " ne peut plus parler ici.")

            if text.startswith("unmute"):
                target = discord.utils.get(server.members, id=ID)
                overwrite.read_messages = True
                await client.send_message(
                    message.channel,
                    target.mention + " peut à nouveau parler ici.")
                await client.edit_channel_permissions(message.channel, target,
                                                      overwrite)
Esempio n. 20
0
File: game.py Progetto: AXVin/Tanya
import dataclasses
from extensions.players import Player
import discord
from discord.ext import commands
from discord.mentions import AllowedMentions
import random
import typing

if typing.TYPE_CHECKING:
    from extensions import players


default_role_overwrites = discord.PermissionOverwrite(
    read_messages=False,
    send_messages=True,
    read_message_history=True,
    attach_files=False,
    add_reactions=False,
)
default_role_disabled_overwrites = discord.PermissionOverwrite(
    read_messages=False,
    send_messages=False,
    read_message_history=True,
    attach_files=False,
    add_reactions=False,
)
jail_overwrites = discord.PermissionOverwrite(
    read_messages=False,
    send_messages=True,
    read_message_history=False,
    attach_files=False,
Esempio n. 21
0
async def on_message(message):

    commands = message.content.split(" ")

    if commands[0] == "!buzzfeed" and is_number(commands[1]):
        n = min(25, int(commands[1]))
        await message.channel.send(
            content="\n".join([get_headline() for i in range(n)]))

    #if it was sent to the #privacy channel
    if message.channel.id == 796169676031524915:

        if "!private create" in message.content:

            guild = message.channel.guild

            name = f"private_{commands[2]}"

            # role_name = f"private_{commands[2]}"

            channel = await guild.create_voice_channel(name=name)

            overwrite = discord.PermissionOverwrite()
            overwrite2 = discord.PermissionOverwrite()

            overwrite.connect = False
            overwrite2.connect = True

            overwrite.view_channel = False
            overwrite2.view_channel = True

            at_everyone = guild.get_role(588794934526607370)

            # make it so people cannot see/connect by default
            await channel.set_permissions(at_everyone, overwrite=overwrite)

            # make it so people can connect
            await channel.set_permissions(message.author, overwrite=overwrite2)

        if "!private add" in message.content:

            channel = [
                channel for channel in message.guild.channels
                if channel.name == f"private_{commands[2]}"
            ][0]

            overwrite = discord.PermissionOverwrite()

            overwrite.connect = True
            overwrite.view_channel = True

            for member in message.mentions:
                await channel.set_permissions(member, overwrite=overwrite)

        await message.delete(delay=0)

    if "!ring" in message.content and "ringing" in message.channel.name:

        if len(message.mentions) == 0:

            for _ in range(5):
                for member in [
                        member for member in message.channel.members
                        if member != message.author
                ]:
                    # while 1:
                    try:
                        await member.send(content="ring ring!")
                        # break
                    except AttributeError:
                        pass
                        # continue

                await message.channel.send(content="@here")

        else:
            for _ in range(5):
                for member in message.mentions:
                    # while 1:
                    try:
                        await member.send(content="ring ring!")
                        # break
                    except AttributeError:
                        pass
                        # continue

                await message.channel.send(
                    content=' '.join([m.mention for m in message.mentions]))

    if message.content == "!ring toggle":

        author = message.author

        role = message.channel.guild.get_role(707265471086329886)

        member_has_role = role in author.roles

        if member_has_role: await author.remove_roles(role)
        else: await author.add_roles(role)

    #if the message was sent to the vote-creation channel
    if message.channel.id == 707556037334401135:

        #if someone wants to make a new vote
        #if it's a !newVote commeand and the person doesn't have an active vote
        if commands[
                0] == "!vote" and message.author not in members_with_active_votes:

            #if it's a vote to mute
            if len(commands) == 3 and commands[1] == "mute" and len(
                    message.mentions) == 1:

                #set up the vote
                win_proportion = vote_attributes["mute_proportion"]
                duration = vote_attributes["mute_duration"]
                min_yes_votes = vote_attributes["mute_min_yes_votes"]
                mutePerson = message.mentions[0]
                initiative_message = "muting {0}".format(
                    mutePerson.display_name)
                winCommand = (lambda x=mutePerson: x.edit(mute=True))
                creator = message.author
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            #if it's a vote to unmute
            if len(commands) == 3 and commands[1] == "unmute" and len(
                    message.mentions) == 1:

                #and they've tagged someone

                #set up the vote
                win_proportion = vote_attributes["unmute_proportion"]
                duration = vote_attributes["unmute_duration"]
                min_yes_votes = vote_attributes["unmute_min_yes_votes"]
                unmutePerson = message.mentions[0]
                initiative_message = "unmuting {0}".format(
                    unmutePerson.display_name)
                winCommand = (lambda x=unmutePerson: x.edit(mute=False))
                creator = message.author
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            #if it's a voice kick command
            if len(commands) == 3 and commands[1] == "disconnect" and len(
                    message.mentions) == 1:

                #set up the vote
                win_proportion = vote_attributes["disconnect_proportion"]
                duration = vote_attributes["disconnect_duration"]
                min_yes_votes = vote_attributes["disconnect_min_yes_votes"]
                kickPerson = message.mentions[0]
                initiative_message = "disconnecting {0}".format(
                    kickPerson.display_name)
                winCommand = (lambda x=kickPerson: x.edit(voice_channel=None))
                creator = message.author
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            #if it's a vote to rename someone
            elif len(commands) >= 4 and commands[1] == "rename" and len(
                    message.mentions) == 1:

                #reconstruct the name
                new_name = " ".join(commands[3:])

                if len(new_name) <= 32:

                    #set up the vote

                    win_proportion = vote_attributes["rename_proportion"]
                    duration = vote_attributes["rename_duration"]
                    min_yes_votes = vote_attributes["rename_min_yes_votes"]

                    #the person to rename
                    rename_person = message.mentions[0]

                    #the initiative message that is sent in the message
                    initiative_message = "renaming {} to {}".format(
                        rename_person.display_name, new_name)

                    #the actual command to rename them
                    async def winCommand(x=rename_person, new_name=new_name):
                        await x.edit(nick="Changing Nickname...")
                        await asyncio.sleep(2)
                        await x.edit(nick=new_name)

                    creator = message.author

                    #instantiate a vote object
                    v = vote()
                    await v.new(duration, initiative_message, winCommand,
                                win_proportion, min_yes_votes, creator)

                else:

                    await message.channel.send(
                        content=
                        "Error: discord only supports nicknames of length 32 or less."
                    )

            elif len(commands) >= 3 and commands[1] == "ban" and len(
                    message.mentions) == 1:

                #set up the vote

                win_proportion = vote_attributes["ban_proportion"]
                duration = vote_attributes["ban_duration"]
                min_yes_votes = vote_attributes["ban_min_yes_votes"]

                #the person to ban
                ban_person = message.mentions[0]

                #the initiative message that is sent in the message
                initiative_message = "banning {}".format(
                    ban_person.display_name)

                #the actual command to ban them
                winCommand = (lambda x=ban_person: x.ban(
                    reason="DEMOCRACY", delete_message_days=0))

                creator = message.author

                #instantiate a vote object
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            elif len(commands) >= 3 and commands[1] == "rename_server":

                #set up the vote

                win_proportion = vote_attributes["server_rename_proportion"]
                duration = vote_attributes["server_rename_duration"]
                min_yes_votes = vote_attributes["server_rename_min_yes_votes"]

                #the person to ban
                # ban_person=message.mentions[0]
                new_name = " ".join(commands[2:])

                #the initiative message that is sent in the message
                initiative_message = "renaming the server to {}".format(
                    new_name)

                #the actual command to ban them
                winCommand = (lambda new_name=new_name, server=message.channel.
                              guild: server.edit(name=new_name))

                creator = message.author

                #instantiate a vote object
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            elif len(commands) == 2 and commands[1] == "unban":

                channel = message.channel
                server = channel.guild
                banned_users = [
                    ban_entry.user.name for ban_entry in await server.bans()
                ]
                text = ""
                for n, banned_user in enumerate(banned_users):
                    text += "{} : {}".format(str(n), banned_user)
                await channel.send(content=text)

            elif len(commands) >= 3 and commands[1] == "unban":

                unban_user_index = int(commands[2])

                channel = message.channel

                server = channel.guild

                banned_users = [
                    ban_entry.user for ban_entry in await server.bans()
                ]

                unban_user = banned_users[unban_user_index]

                #set up the vote

                win_proportion = vote_attributes["unban_proportion"]
                duration = vote_attributes["unban_duration"]
                min_yes_votes = vote_attributes["unban_min_yes_votes"]

                #the initiative message that is sent in the message
                initiative_message = "unbanning {}".format(unban_user.name)

                #the actual command to ban them
                winCommand = (lambda sever=server, unban_person=unban_user:
                              server.unban(unban_person))

                creator = message.author

                #instantiate a vote object
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

            elif len(commands) >= 2 and commands[1] == "bot_status":

                status = " ".join(commands[2:])

                initiative_message = f"Changing the bot's status to {status}"

                winCommand = lambda x=status: client.change_presence(
                    activity=discord.Game(x))

                win_proportion = vote_attributes["bot_status_proportion"]
                duration = vote_attributes["bot_status_duration"]
                min_yes_votes = vote_attributes["bot_status_min_yes_votes"]

                creator = message.author
                v = vote()
                await v.new(duration, initiative_message, winCommand,
                            win_proportion, min_yes_votes, creator)

        #help command implementation
        if message.content == "!voteHelp":

            #send help message
            await message.channel.send(
                content=
                "[this is WIP sory] possible syntaxes: '!newVote mute @Bruno'")
Esempio n. 22
0
    async def setup_bot(self,
                        ctx,
                        bot: discord.Member = None,
                        owner: discord.Member = None):
        """Admin use only: For adding bot demo channels
        Creates channel (based on bot name)
        Alphabatizes channel within the Bot-Demos category
        Sets proper permissions
        Sets the channel topic to 'Maintained by [owner]'
        Pings owner so they see the channel and can demonstrate features
        Adds the "Bots" role to the bot.

        **Example:**
        /setup @bot @owner

        **Permissions:**
        Admin role required
        """
        if not bot or not owner:
            return await ctx.send(
                "Please be sure to provide a Discord ID or mention both the bot and the owner. "
                "`/setup @bot @owner`")
        if not bot.bot:
            return await ctx.send(
                f"{bot.mention} does not appear to be a bot. Please try again with "
                f"`/setup @bot @owner`.")
        if owner.bot:
            return await ctx.send(
                f"{owner.mention} appears to be a bot, but should be the bot owner. Please try "
                f"again with `/setup @bot @owner`.")

        category = self.bot.get_channel(BOT_DEMO_CATEGORY_ID)
        channel_name = f"{bot.name}-demo"
        topic = f"Maintained by {owner.display_name}"
        overwrites = {
            ctx.guild.default_role:
            discord.PermissionOverwrite(read_messages=False),
            ctx.guild.get_role(BOTS_ROLE_ID):
            discord.PermissionOverwrite(read_messages=False),
            ctx.guild.get_role(BOT_MAKER_ROLE_ID):
            discord.PermissionOverwrite(read_messages=True),
            bot:
            discord.PermissionOverwrite(read_messages=True,
                                        send_messages=True,
                                        read_message_history=True,
                                        manage_messages=True,
                                        embed_links=True,
                                        attach_files=True,
                                        external_emojis=True,
                                        add_reactions=True),
        }
        position = category.channels[0].position + sorted(
            category.channels + [channel_name],
            key=lambda c: str(c)).index(channel_name)

        channel = await ctx.guild.create_text_channel(
            channel_name,
            overwrites=overwrites,
            category=category,
            position=position,
            topic=topic,
            reason=f"Created by the setup command of Hog Rider ({ctx.author})",
        )
        # ping owner
        await channel.send(
            f"{owner.mention} This channel has been set up for your use in demonstrating the features "
            f"of **{bot.name}**. Limited troubleshooting with others is acceptable, but please do not "
            f"allow this channel to become a testing platform.  Thanks!")

        # add the "Bots" role
        await bot.add_roles(
            ctx.guild.get_role(BOTS_ROLE_ID),
            reason=f"Added by setup command of Hog Rider ({ctx.author})",
        )

        # sort the Bot-Demo channels alphabetically
        for index, channel in enumerate(sorted(category.channels,
                                               key=lambda c: str(c)),
                                        start=category.channels[0].position):
            if channel.position != index:
                await channel.edit(position=index)
Esempio n. 23
0
async def Candidature(ctx):
    if ctx.channel.name == 'apply':
        guild = ctx.guild
        authour = ctx.message.author
        checkRole = discord.utils.get(ctx.guild.roles, name="Roster")
        idiot = "Idiot du village"
        if checkRole in ctx.author.roles:
            #Already has a role
            await ctx.author.send('Tu as déjà un rôle idiot !')
            if get(ctx.guild.roles, name=idiot):
                idiotRole = discord.utils.get(ctx.guild.roles, name=idiot)
                await authour.add_roles(idiotRole)
            else:
                idiotRole = await guild.create_role(
                    name=idiot,
                    permissions=discord.Permissions(3072),
                    reason="Un idiot est née")
                await authour.add_roles(idiotRole)
        else:
            #No role continu
            #All member who can access
            member = ctx.author
            admin_role = get(guild.roles, name="Sainte trinité")
            apply_manager_role = get(guild.roles,
                                     name="Public Relations Manager")
            roster_role = get(guild.roles, name="Roster")
            tmp = 'Candidature ' + str(authour.display_name)

            #Create new role
            if get(ctx.guild.roles, name=tmp):
                await ctx.author.send(alreadyapply)
            else:
                #Create role with permissions Read / Send messages / Embed link / History / View channel
                role = await guild.create_role(
                    name=tmp,
                    permissions=discord.Permissions(84992),
                    reason='new_apply')
                await authour.add_roles(role)
                authour_role = get(guild.roles, name=str(tmp))
                #List of permissions
                overwrites = {
                    guild.default_role:
                    discord.PermissionOverwrite(read_messages=False),
                    guild.me:
                    discord.PermissionOverwrite(read_messages=True),
                    admin_role:
                    discord.PermissionOverwrite(read_messages=True),
                    apply_manager_role:
                    discord.PermissionOverwrite(read_messages=True,
                                                manage_messages=False,
                                                send_messages=True),
                    roster_role:
                    discord.PermissionOverwrite(manage_messages=False,
                                                read_messages=True,
                                                send_messages=False),
                    authour_role:
                    discord.PermissionOverwrite(read_messages=True)
                }

                #Create channel
                nameChannel = "candidature " + str(ctx.author.display_name)
                await guild.create_text_channel(name=nameChannel,
                                                overwrites=overwrites)
                #Send Private Message
                await ctx.author.send(privatemessage)
        await ctx.message.delete()
Esempio n. 24
0
     return
 self.dynamic_ready[vc.id] = asyncio.Event()
 guild_role = self.guild_cache[guild.id]["role"]
 if dynamic_name := self.guild_cache[guild.id]["dynamic_name"]:
     name = re.sub(r"(?i){vc}", vc.name, dynamic_name)
 else:
     name = "\N{SPEAKER WITH THREE SOUND WAVES} " + vc.name
 role = await guild.create_role(name=name, reason="Dynamic role for {vc}".format(vc=vc))
 await self.config.channel(vc).role.set(role.id)
 self.channel_cache[vc.id]["role"] = role.id
 if vc.category:
     overs = vc.category.overwrites
 else:
     overs = {}
 # inherit guild role and remove its overwrites
 default = overs.pop(guild_role, discord.PermissionOverwrite())
 # vc-specific role, inherited from guild role
 overs.setdefault(role, default).update(read_messages=True, send_messages=True)
 # @everyone, remove read permissions
 overs.setdefault(guild.default_role, discord.PermissionOverwrite()).update(
     read_messages=False
 )
 # add bot to the channel
 overs.setdefault(guild.me, discord.PermissionOverwrite()).update(
     read_messages=True, send_messages=True
 )
 text = await guild.create_text_channel(
     name=name,
     overwrites=overs,
     category=vc.category,
     reason="Dynamic channel for {vc}".format(vc=vc),
Esempio n. 25
0
async def process_message(message, result):
    general.add_activity(message.author.id, message.author.name)

    gamelog_channel = client.get_channel(int(config.game_log))
    botspam_channel = client.get_channel(int(config.bot_spam))
    storytime_channel = client.get_channel(int(config.story_time))

    # The temp_msg list is for keeping track of temporary messages for deletion.
    temp_msg = []

    for mailbox in result:

        # If a Mailbox says so, all existing polls will be evaluated.
        if mailbox.evaluate_polls == True:
            for poll in db.get_all_polls():
                # poll.msg_table -> list of message ids
                # poll.blamed -> name of killer
                # poll.purpose -> the reason of the kill

                poll_channel = client.get_channel(int(poll.channel))
                if poll_channel == None:
                    await botspam_channel.send(
                        "We got a problem! Could you send these results to the appropriate channel, please?"
                    )
                    poll_channel = botspam_channel

                user_table = []
                for msg in poll.msg_table:
                    poll_msg = await poll_channel.get_message(msg)
                    for emoji in poll_msg.reactions:
                        users = await emoji.users().flatten()

                        for person in users:
                            if db.isParticipant(person.id):
                                user_table.append([person.id, emoji.emoji])

                log, result, chosen_emoji = count_votes(
                    user_table, poll.purpose, dy.get_mayor())

                await gamelog_channel.send(log)
                await poll_channel.send(result)

                chosen_one = db.emoji_to_player(chosen_emoji)
                chosen_one = int(chosen_one)

                if chosen_emoji != '' and chosen_one != None:
                    if poll.purpose == 'lynch':
                        db.add_kill(chosen_one, 'Innocent')
                    elif poll.purpose == 'Mayor':
                        dy.set_mayor(chosen_one)
                        # TODO: give Mayor role
                    elif poll.purpose == 'Reporter':
                        dy.set_reporter(chosen_one)
                        # TODO: give Reporter role
                    elif poll.purpose == 'wolf':
                        db.add_kill(chosen_one, 'Werewolf', db.random_wolf())
                    elif poll.purpose == 'cult':
                        db.add_kill(chosen_one, 'Cult Leader',
                                    db.random_cult())
                    elif poll.purpose == 'thing':
                        db.add_kill(chosen_one, 'The Thing', '')

        for user_id in mailbox.demotions:
            if user_id == message.author.id and message.guild == gamelog_channel.guild:
                member = message.author
            else:
                member = gamelog_channel.guild.get_member(int(user_id))

            if member != None:
                for role in member.roles:
                    if role.id == config.mayor:
                        await member.remove_roles(role,
                                                  reason="Demoting the Mayor")
                    if role.id == config.reporter:
                        await member.remove_roles(
                            role, reason="Demoting the Reporter")

        # Create a new shop instance
        for element in mailbox.shops:
            shop_data = db_shop.get_shop_config(element.shop_config)
            i = 1
            j = 0
            emoji_table = []
            page_amount = int(len(shop_data["items"]) - 1 / 20) + 1

            for item in shop_data["items"]:
                if j % 20 == 0:
                    embed = discord.Embed(
                        title="Shop (Page {}/{})".format(i, page_amount),
                        description=shop_data["shop_description"],
                        color=0x00ff00)

                embed.add_field(name="[{}] {}".format(item["emoji"],
                                                      item["name"]),
                                value="{} {}\n*{}*\n".format(
                                    item["price"], shop_data["currency"],
                                    item["description"]),
                                inline=False)  # Add item to shop
                emoji_table.append(emojize(item["emoji"]))
                j += 1

                if j % 20 == 0:
                    i += 1
                    response = await client.get_channel(
                        int(element.destination)).send(embed=embed)
                    db_shop.add_shop(response.id)

                    for item in emoji_table:
                        await response.add_reaction(item)
                    emoji_table = []

            if j % 20 != 0:
                response = await client.get_channel(int(element.destination)
                                                    ).send(embed=embed)
                db_shop.add_shop(response.id)

                for item in emoji_table:
                    await response.add_reaction(item)

        # If the Mailbox has a message for the gamelog, this is where it's sent.
        for element in mailbox.gamelog:
            msg = await gamelog_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # If the Mailbox has a message for the botspam, this is where it's sent.
        for element in mailbox.botspam:
            msg = await botspam_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # If the Mailbox has a message for the storytime (in-game announcements) channel, this is where it's sent.
        for element in mailbox.storytime:
            msg = await storytime_channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # The messages are sent here if they are a direct message to the one sending a command.
        for element in mailbox.answer:
            msg = await message.channel.send(element.content)
            for emoji in element.reactions:
                await msg.add_reaction(emoji)
            if element.temporary == True:
                temp_msg.append(msg)

        # The messages that are destined for a specific channel, are sent here.
        for element in mailbox.channel:

            # The following code is sent if the message is an embed.
            if element.embed:
                if element.destination == "spam":
                    msg = await botspam_channel.send(embed=element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
                else:
                    msg = await client.get_channel(int(element.destination)
                                                   ).send(embed=element.content
                                                          )
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
            # The following code is sent if the message is a regular message.
            else:
                msg = await client.get_channel(int(element.destination)
                                               ).send(element.content)
                for emoji in element.reactions:
                    await msg.add_reaction(emoji)
                if element.temporary == True:
                    temp_msg.append(msg)

        # DMs are sent here.
        for element in mailbox.player:
            member = client.get_user(int(element.destination))
            main_guild = botspam_channel.guild
            if member == None:
                member = main_guild.get_member(int(element.destination))
            if member == None:
                await message.channel.send(
                    "Couldn't send a DM to <@{}>!".format(element.destination))
                await botspam_channel.send(
                    "<@{}> has attempted to send a DM to <@{}>, but failed, because we couldn't find the specified user via `client.get_user`."
                    .format(message.author.id, element.destination))
            else:
                try:
                    msg = await member.send(element.content)
                    for emoji in element.reactions:
                        await msg.add_reaction(emoji)
                    if element.temporary == True:
                        temp_msg.append(msg)
                except discord.errors.Forbidden:
                    botspam_channel.send(
                        'I wasn\'t allowed to send a DM to <@{}>! Here\'s the content:'
                        .format(member.id))
                    botspam_channel.send(element.content)
                except Exception:
                    botspam_channel.send(
                        'I failed to send a DM to <@{}>! Could somebody send this, please?'
                        .format(member.id))
                    botspam_channel.send(element.content)

        # Settings of existing channels are altered here.
        for element in mailbox.oldchannels:
            # element.channel - channel to be edited;
            # element.victim - person's permission to be changed;
            # element.number - type of setting to set to: see issue #83 for more info.

            channel = client.get_channel(element.channel)
            user = client.get_user(int(element.victim))
            main_guild = botspam_channel.guild
            member = main_guild.get_member(int(element.victim))
            if member == None:
                if user == None:
                    await botspam_channel.send(
                        "That\'s problematic! I couldn\'t edit the cc info of <@{0}> *(<#{0}> <@&{0}> ?)*"
                        .format(element.victim))
                    print('Unable to locate member {}.'.format(element.victim))
                member = user
            if channel == None:
                await botspam_channel.send(
                    'Unable to edit channel <#{0}> *(<@{0}> <@&{0}> ?)*'.
                    format(int(element.victim)))
            elif member != None:
                await remove_all_game_roles(member)
                if element.number == 0:
                    await channel.set_permissions(user,
                                                  read_messages=False,
                                                  send_messages=False)
                    try:
                        if int(db_get(member.id, 'frozen')) == 0:
                            raise NotImplementedError(
                                "This is a purposeful error raise!")
                    except Exception:
                        if db.isParticipant(member.id):
                            await member.add_roles(
                                get_role(main_guild.roles, config.participant),
                                reason="Updating CC Permissions")
                        elif db.isParticipant(member.id, True, True):
                            await member.add_roles(
                                get_role(main_guild.roles,
                                         config.dead_participant),
                                reason="Updating CC Permissions")
                        elif db.isParticipant(member.id, True, True, True):
                            await member.add_roles(
                                get_role(main_guild.roles, config.suspended),
                                reason="Updating CC Permissions")
                    else:
                        await member.add_roles(
                            get_role(main_guild.roles,
                                     config.frozen_participant),
                            reason="Updating CC Permissions")
                elif element.number == 1:
                    await channel.set_permissions(user,
                                                  read_messages=True,
                                                  send_messages=True)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.participant),
                                           reason="Updating CC Permissions")
                elif element.number == 2:
                    await channel.set_permissions(user,
                                                  read_messages=True,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.frozen_participant),
                                           reason="Updating CC Permissions")
                elif element.number == 3:
                    await channel.set_permissions(user,
                                                  read_messages=False,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.participant),
                                           reason="Updating CC Permissions")
                elif element.number == 4:
                    await channel.set_permissions(user,
                                                  read_messages=True,
                                                  send_messages=False)
                    if db.isParticipant(member.id, False, True):
                        await member.add_roles(
                            get_role(main_guild.roles,
                                     config.dead_participant),
                            reason="Updating CC Permissions")
                elif element.number == 5:
                    await channel.set_permissions(user,
                                                  read_messages=True,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.participant),
                                           reason="Updating CC Permissions")
                elif element.number == 6:
                    await channel.set_permissions(user,
                                                  read_messages=False,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.participant),
                                           reason="Updating CC Permissions")
                elif element.number == 7:
                    await channel.set_permissions(user,
                                                  read_messages=False,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.participant),
                                           reason="Updating CC Permissions")
                elif element.number == 8:
                    await channel.set_permissions(user,
                                                  read_messages=False,
                                                  send_messages=False)
                    await member.add_roles(get_role(main_guild.roles,
                                                    config.suspended),
                                           reason="Updating CC Permissions")
                else:
                    await msg.channel.send(
                        'Something went wrong! Please contact a Game Master.')
                    return
                if db.isParticipant(element.victim, True, True):
                    db.set_user_in_channel(element.channel, element.victim,
                                           element.number)

        # New channels are created here.
        for element in mailbox.newchannels:
            # element.name - name of the channel;
            # element.owner - owner of the channel;
            # element.members - members of the channel
            # element.settlers - members for whom this shall become their home channel
            # element.secret - boolean if the channel is a secret channel

            if element.secret:
                element.owner = client.user.id

            if ' ' not in element.name:

                main_guild = botspam_channel.guild  # Find the guild we're in

                if element.owner not in element.members:
                    element.members.append(element.owner)
                for buddy in element.settlers:
                    if buddy not in element.members:
                        msg = """**Warning:** I'm adding settlers to a channel!\nThis is should not be a problem, \
                        but it does at least indicate a flaw in the bot's code. Please, report this to the Game Masters!"""
                        await client.get_channel(message.channel).send(msg)
                        element.members.append(buddy)

                viewers = []
                frozones = []
                abductees = []
                deadies = []

                # Add dead people & spectators to cc
                if not element.secret:
                    for user in [
                            dead_buddy for dead_buddy in db.player_list()
                            if dead_buddy not in db.player_list(True)
                    ]:
                        element.members.append(user)

                # Categorize all players
                for user in element.members:
                    member = main_guild.get_member(user)

                    if member == None:
                        await botspam_channel.send(
                            "That\'s problematic! I couldn\'t add <@{0}> to a cc. *(<#{0}> <@&{0}> ?)*"
                            .format(element.victim))
                        await message.author.send(
                            "It doesn't seem like <@{}> is part of the server! I am sorry, I can't add them to your **conspiracy channel**."
                            .format(user))
                    elif db.isParticipant(user, False, True) == True:
                        if int(db_get(user, 'abducted')) == 1:
                            abductees.append(member)
                        elif int(db_get(user, 'frozen')) == 1:
                            frozones.append(member)
                        elif db.isParticipant(user, False, False) == False:
                            deadies.append(member)
                        else:
                            viewers.append(member)
                    elif db_get(user, 'role') == 'Suspended':
                        pass
                    else:
                        deadies.append(member)

                # Delete any potential duplicates
                viewers = list(set(viewers))
                frozones = list(set(frozones))
                abductees = list(set(abductees))
                deadies = list(set(deadies))

                # Role objects (based on ID)
                roles = main_guild.roles  # Roles from the guild
                game_master_role = discord.utils.find(
                    lambda r: r.id == game_master, roles)
                # TODO: Add read permissions for spectators if element.secret == False
                default_permissions = {
                    main_guild.default_role:
                    discord.PermissionOverwrite(read_messages=False,
                                                send_messages=False),
                    game_master_role:
                    discord.PermissionOverwrite(read_messages=True,
                                                send_messages=True),
                    client.user:
                    discord.PermissionOverwrite(read_messages=True,
                                                send_messages=True),
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,
                                                            send_messages=True)
                        for member in viewers
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,
                                                            send_messages=False)
                        for member in frozones
                    },
                    **{
                        member: discord.PermissionOverwrite(read_messages=True,
                                                            send_messages=False)
                        for member in deadies
                    }
                }

                if not element.secret:
                    intro_msg = creation_messages.cc_intro(
                        [v.id for v in viewers])
                    reason_msg = 'CC requested by ' + message.author.name
                    title = "s{}_cc_{}".format(config.season, element.name)
                    category_name = 'S{} CCs PART {}'.format(
                        config.season,
                        db.count_categories(element.secret) + 1)
                else:
                    intro_msg = secret_messages.creation(
                        element.name, [v.id for v in viewers])
                    reason_msg = 'Secret {} channel created.'.format(
                        element.name)
                    title = "s{}_{}".format(config.season, element.name)
                    category_name = 'S{} Secret Channels Part {}'.format(
                        config.season,
                        db.count_categories(element.secret) + 1)

                # Create a new category if needed
                if db.get_category(element.secret) == None:
                    category = await main_guild.create_category(
                        category_name,
                        reason=
                        'It seems like we couldn\'t use our previous category! Don\'t worry, I just created a new one.'
                    )
                    db.add_category(category.id, element.secret)
                else:
                    category = main_guild.get_channel(
                        db.get_category(element.secret))

                try:
                    # Create the text channel
                    channel = await main_guild.create_text_channel(
                        name=title,
                        category=category,
                        overwrites=default_permissions,
                        reason=reason_msg)
                    db.add_channel(channel.id, element.owner, element.secret)
                    if element.secret:
                        db.add_secret_channel(channel.id, element.name)

                        # If the channel is meant for an amulet holder, assign the amulet holder.
                        if element.name == 'Amulet_Holder':
                            for member in viewers:
                                if db_get(member.id,
                                          'role') == 'Amulet Holder':
                                    db_set(member.id, 'amulet', channel.id)
                    if element.trashy:
                        db.add_trash_channel(channel.id)

                    await channel.send(intro_msg)

                    # Set all access rules in the database
                    for member in viewers:
                        db.set_user_in_channel(channel.id, member.id, 1)
                    for member in frozones:
                        db.set_user_in_channel(channel.id, member.id, 2)
                    for member in abductees:
                        db.set_user_in_channel(channel.id, member.id, 3)
                    for member in deadies:
                        if db.isParticipant(member.id, True, True) == True:
                            db.set_user_in_channel(channel.id, member.id, 4)

                except Exception as e:  # Catch any thrown exceptions and send an error to the user.
                    await message.channel.send(
                        'It seems like I\'ve encountered an error! Please let the Game Masters know about this!'
                    )
                    await botspam_channel.send(
                        "Oi, Game Masters! I got a problem concerning channel creation for ya to fix."
                    )
                    await botspam_channel.send(e)
                    raise e  # Send the full log to Buddy1913 and his sketchy VM.

                # Give the settlers their own happy little residence
                for buddy in element.settlers:
                    db_set(buddy, "channel", channel.id)

            else:
                """This should not happen, but we'll use it, to prevent the bot from purposely causing an error
                everytime someone attempts to create a channel that contains spaces. 'cause believe me,
                that happens ALL the time."""
                msg = await message.channel.send(
                    "I\'m terribly sorry, but you can\'t use spaces in your channel name. Try again!"
                )
                temp_msg.append(msg)

        # Polls are created here.
        for element in mailbox.polls:
            # element.channel
            # element.purpose
            # element.user_id
            # element.description

            msg = element.description + '\n'
            emoji_table = []
            msg_table = []
            i = 0

            for user in db.poll_list():
                if db.isParticipant(int(user[0])):
                    i += 1
                    msg += user[1] + " - <@" + str(user[0]) + "> "

                    if int(user[2]) + int(user[3]) > 0:
                        if int(user[2]) == 1:
                            msg += "**[FROZEN]** "
                        if int(user[3]) == 1:
                            msg += "**[ABDUCTED] **"
                    else:
                        emoji_table.append(user[1])

                    if i % 20 == 19:
                        msg = await client.get_channel(int(element.channel)
                                                       ).send(msg)
                        for emoji in emoji_table:
                            await msg.add_reaction(emoji)
                        msg_table.append(msg)
                        emoji_table = []
                        msg = ''
                    else:
                        msg += '\n'

            if msg != '':
                msg = await client.get_channel(element.channel).send(msg)
                for emoji in emoji_table:
                    await msg.add_reaction(emoji)
                msg_table.append(msg)
            db.add_poll(msg_table, element.purpose, element.channel,
                        element.user_id)
            await botspam_channel.send(
                "A poll has been created in <#{}>!".format(element.channel))

        # Categories are deleted here.
        for element in mailbox.deletecategories:
            id = element.channel
            category = client.get_channel(id)
            if category != None:
                bot_message = await message.channel.send(
                    'Please react with 👍 to confirm deletion of category `' +
                    category.name +
                    '`.\n\nNote: This action will irreversibly delete all channels contained within the specified category. Please use with discretion.'
                )
                await bot_message.add_reaction('👍')

                def check(reaction, user):
                    return user == message.author and str(
                        reaction.emoji) == '👍'

                try:
                    reaction, user = await client.wait_for('reaction_add',
                                                           timeout=30.0,
                                                           check=check)
                except asyncio.TimeoutError:
                    await message.channel.send('Confirmation timed out.')
                    try:
                        await bot_message.delete()
                    except Exception:
                        pass
                else:
                    await message.channel.send(
                        'Ok, I\'ll get right on that.\n\n*This might take some time.*'
                    )
                    for channel in category.channels:
                        await channel.delete()
                    await category.delete()
                    await message.channel.send(
                        '\n:thumbsup: Channels and category deleted')
            else:
                await message.channel.send(
                    'Sorry, I couldn\'t find that category.')

        clean_time = len(mailbox.cleaners)
        if clean_time > 0:
            await botspam_channel.send(
                "Cleaning up {} channels! This may take some time.".format(
                    clean_time))

        for channel in mailbox.cleaners:

            trash_channel = client.get_channel(int(channel))

            if trash_channel != None:
                for message_id in db.empty_trash_channel(channel):
                    message = await trash_channel.get_message(int(message_id))
                    if message != None:
                        await message.delete()

    # Delete all temporary messages after about two minutes.
    await asyncio.sleep(120)
    for msg in temp_msg:
        try:
            await msg.delete()
        except Exception:
            # Unable to delete the message.
            # It was probaly already deleted or something.
            pass
Esempio n. 26
0
async def on_member_join(member):
    guild = member.guild
    privateChannelName = str(member).replace(' ', '-').replace('#',
                                                               '-').lower()
    joinLeaveChannel = guild.get_channel(JOINLEAVE)
    newbieRole = guild.get_role(NEWB)
    checkpointCategory = guild.get_channel(CHECKPOINT)
    securityTeam = guild.get_role(SECURITY)
    justJoinedNick = "(" + str(member.display_name) + ")"

    await member.edit(nick=justJoinedNick)

    now = datetime.today()

    current_time = now.strftime("%H:%M:%S")

    # log join
    logger.info(
        f'({current_time}) ON_MEMBER_JOIN: {member.name} has joined the server. Private room of {privateChannelName} created'
    )

    # Give the member the 'Just Joined' role
    await member.add_roles(newbieRole)

    # Set of permissions for the new channel
    overwrites = {
        guild.default_role:
        discord.PermissionOverwrite(read_messages=False),
        guild.me:
        discord.PermissionOverwrite(read_messages=True),
        securityTeam:
        discord.PermissionOverwrite(read_messages=True,
                                    send_messages=True,
                                    attach_files=True,
                                    read_message_history=True),
        member:
        discord.PermissionOverwrite(read_messages=True,
                                    send_messages=True,
                                    attach_files=True,
                                    read_message_history=True)
    }

    privateChannel = await guild.create_text_channel(
        privateChannelName, overwrites=overwrites, category=checkpointCategory)
    # welcome message
    await privateChannel.send(
        f'{member.mention}, Welcome! You are new to our server! Here is a private channel for us '
        f'to interview you.')
    await privateChannel.send(
        f'We take security very seriously here!\n\nOne of our {securityTeam.mention} team members '
        f'will be along shortly to interview you.\n\nIn the mean time stop by #welcome-to-home '
        f'in order to choose why you\'ve come to HOME and be allowed to chat in #welcome-lobby. '
        f'If you are here to Apply to join HOME, you can speed up the process by leaving a '
        f'screenshot of your character select screen for all of your accounts.\n\nThanks for your'
        f' patience and welcome to HOME!')

    # Server Entry Exit Logging - create the Embed
    logEmbed = discord.Embed(title="New Member Joined", color=0x00A71E)
    logEmbed.description = f'{member.mention} ( {member.name} ) has joined the server'
    logEmbed.add_field(name='Create Date', value=member.created_at)
    logEmbed.add_field(name='Private Channel', value=privateChannelName)
    logEmbed.set_thumbnail(url=member.avatar_url)

    await joinLeaveChannel.send(embed=logEmbed)
    logger.info(
        f'ON_MEMBER_JOIN: Join Embed pushed to {joinLeaveChannel} channel')
    # check if account less than 7 days old - 604800 seconds is 7 days
    if time.time() - member.created_at.timestamp() < 604800:
        # set log message for file
        logger.info(
            f'ON_MEMBER_JOIN: {member.name} was created on {member.created_at} - which is less than 7 days ago.'
        )

        # mention security role if the account is less than 7 days old
        await joinLeaveChannel.send(
            f'{securityTeam.mention} the above account is less than 7 days old'
        )
Esempio n. 27
0
 async def _check_channels(self):
     """Loop to check whether or not we should create/delete the TempChannel"""
     while self == self.bot.get_cog("TempChannels"):
         await asyncio.sleep(15)
         # Create/maintain the channel during a valid time and duration, else delete it.
         try:
             for server in self.settings:
                 keys_settings = self.settings[server].keys()
                 keys_required = [ "channelName", "channelPosition", "channelCategory", "channelTopic", "channelCreated", "startHour", "startMinute", "durationHours", "durationMinutes", "nsfw", "roleallow", "roledeny", "enabled"]
                 missing = False
                 for key in keys_required:
                     if key not in keys_settings:
                         missing = True
                         print("TempChannels: Key {} is missing in settings! Run [p]tc default.".format(key))
                 if missing:
                     continue
                     
                 if not self.settings[server]["enabled"]:
                     continue
                 
                 if ( int(time.strftime("%H")) == self.settings[server]["startHour"]) and (int(time.strftime("%M")) == self.settings[server]["startMinute"]) and (self.settings[server]["channelCreated"] is False):
                     # Create the channel, and store the ID, and time to delete channel in the settings.
                     
                     if self.settings[server]["channel"] is None:
                         # Start with permissions
                         allow_list = []
                         deny_list = []
                         allow_perms = [ discord.PermissionOverwrite(read_messages=True, send_messages=False) ]
                         allow_roles = [ self.bot.user ]
                         deny_perms = []
                         deny_roles = []
                         
                         if len(self.settings[server]["roleallow"]) > 0:
                         # If we have allow roles, automatically deny @everyone read messages.
                             deny_perms.append(discord.PermissionOverwrite(read_messages=False, add_reactions=False))
                             deny_roles.append(self.bot.get_server(server).default_role)
                             for override_roles in self.settings[server]["roleallow"]:
                                 find_role = discord.utils.get(self.bot.get_server(server).roles, name=override_roles)
                                 allow_roles.append(find_role)
                         
                         allow_list = itertools.zip_longest(allow_roles, allow_perms, fillvalue=discord.PermissionOverwrite(read_messages=True, add_reactions=False))
                         
                         
                         # Check for deny permissions.
                         if len(self.settings[server]["roledeny"]) > 0:
                             deny_perms.append(discord.PermissionOverwrite(send_messages=False, add_reactions=False))
                             for override_roles2 in self.settings[server]["roledeny"]:
                                 find_role2 = discord.utils.get(self.bot.get_server(server).roles, name=override_roles2)
                                 deny_roles.append(find_role2)
                         deny_list = itertools.zip_longest(deny_roles, deny_perms, fillvalue=discord.PermissionOverwrite(send_messages=False))
                         
                         if self.settings[server]["nsfw"]:
                             created_channel = await self.bot.create_channel(self.bot.get_server(server), "nsfw-{}".format(self.settings[server]["channelName"]), *list(allow_list), *list(deny_list))
                             
                             # This is most definitely not the best way of doing it, but since no NSFW method, we have this:
                             header = { "Authorization" : "Bot {}".format(self.bot.settings.token), "content-type" : "application/json" }
                             body = { "nsfw" : True }
                             
                             async with aiohttp.ClientSession() as session:
                                 async with session.patch('https://discordapp.com/api/channels/{}'.format(created_channel.id),headers=header,data=json.dumps(body)) as resp:
                                     print(resp.status)
                                     print(await resp.text())
                         else: # Not NSFW
                             created_channel = await self.bot.create_channel(self.bot.get_server(server), self.settings[server]["channelName"], *list(allow_list), *list(deny_list))
                             
                         self.settings[server]["channel"] = created_channel.id
                         self._sync_settings()
                         print("TempChannel: Channel created at "+format(time.strftime("%H:%M:%S")))
                         
                         # Change topic.
                         await self.bot.edit_channel(created_channel, topic=self.settings[server]["channelTopic"],name=self.settings[server]["channelName"])
                         
                         # Set parent category.  Must use this method because library does not 
                         # have a method for this yet.
                         if self.settings[server]["channelCategory"] != 0:
                             header = { "Authorization" : "Bot {}".format(self.bot.settings.token), "content-type" : "application/json" }
                             body = { "parent_id" : self.settings[server]["channelCategory"] }
                             
                             async with aiohttp.ClientSession() as session:
                                 async with session.patch('https://discordapp.com/api/channels/{}'.format(created_channel.id),headers=header,data=json.dumps(body)) as resp:
                                     print(resp.status)
                                     print(await resp.text())
                         
                         # Move channel position.
                         try:
                             await self.bot.move_channel(created_channel, self.settings[server]["channelPosition"])
                         except:
                             print("TempChannel: Could not move channel position")
                             
                         # Set delete times, and save settings.
                         self.settings[server]["stopTime"] = time.time() + (self.settings[server]["durationHours"]*60*60) + (self.settings[server]["durationMinutes"]*60)
                         self.settings[server]["channelCreated"] = True
                         self._sync_settings()
                                     
                 elif self.settings[server]["channelCreated"]:
                     # Channel created, see when we should delete it.
                     self._sync_settings()
                     if time.time() >= self.settings[server]["stopTime"]:
                         try:
                             if self.settings[server]["channel"] is not None:
                                 try:
                                     await self.bot.delete_channel(self.bot.get_channel(self.settings[server]["channel"]))
                                     self.settings[server]["channel"] = None
                                 except Exception as e:
                                     print("TempChannel: "+e)
                         except:
                             self.settings[server]["channel"] = None
                         print("TempChannel: Channel deleted at "+format(time.strftime("%H:%M:%S")))
                         self.settings[server]["channelCreated"] = False
                         self._sync_settings()
         except Exception as e:
             print("TempChannels: No servers. {}".format(e))
Esempio n. 28
0
    async def create(cls, member, ctx=None, **flags):
        player = member
        guild = member.guild
        settings = Settings.get_for(guild.id)

        def flag(key):
            return cls.unpack_value(
                flags[key], cls.props[key]
            ) if key in settings.allowed_host_commands and key in flags and len(
                flags[key]) > 0 else None

        if not guild.me.guild_permissions.manage_channels or not guild.me.guild_permissions.manage_roles:
            raise discord.ext.commands.errors.CommandInvokeError(
                "Missing Permissons")

        # check if able to make room
        if not settings.allow_multiple_rooms and cls.player_is_in_any(
                player.id, guild.id):
            if ctx:
                await ctx.send(settings.get_text('already_in_room'))
            return

        # activity (room name)
        name = player.display_name
        top = player.top_role.name
        bottom = player.roles[1].name if len(player.roles) > 1 else top
        activity = flag('activity') or choice(settings.default_names).format(
            name, top, bottom)
        activity = activity[0:90].strip()

        # color
        if flag('color'):
            color = get_color(flag('color'))
        elif settings.use_role_color and player.top_role.color != discord.Color.default(
        ):
            color = player.top_role.color
        else:
            color = discord.Color(int(choice(settings.default_colors)))

        # role
        role = await guild.create_role(name="({}) {}".format(
            settings.get_text('room'), activity),
                                       color=color,
                                       hoist=True,
                                       mentionable=True)

        # overwrites
        accessors_ids = settings.access_all_rooms_role
        accessors = []
        for accessor_id in accessors_ids:
            accessor_player = guild.get_member(accessor_id)
            accessor_role = guild.get_role(accessor_id)
            if accessor_player:
                accessors.append(accessor_player)
            elif accessor_role:
                accessors.append(accessor_role)
        if len(accessors) < 1:
            accessors = list(filter(lambda m: m.bot, guild.members))

        overwrites = {
            guild.default_role:
            discord.PermissionOverwrite(read_messages=False),
            guild.me:
            discord.PermissionOverwrite(read_messages=True,
                                        manage_channels=True),
            role:
            discord.PermissionOverwrite(read_messages=True)
        }
        for accessor in accessors:
            overwrites[accessor] = discord.PermissionOverwrite(
                read_messages=True)

        # channel
        category = await get_rooms_category(guild, settings)
        o = category.overwrites
        o.update(overwrites)
        overwrites = o
        channel = await category.create_text_channel(name=activity,
                                                     position=0,
                                                     overwrites=overwrites)

        voice_channel = None
        if settings.default_voice_channel:
            voice_channel = await guild.create_voice_channel(
                name=activity,
                bitrate=settings.bitrate * 1000,
                category=category,
                position=0,
                overwrites=overwrites)

        # new room
        room = Room(role_id=role.id,
                    channel_id=channel.id,
                    voice_channel_id=voice_channel.id if voice_channel else 0,
                    guild=guild.id,
                    birth_channel=ctx.message.channel.id if ctx else 0,
                    host=player.id,
                    players=[player.id],
                    activity=activity,
                    color=color,
                    lock=flag('lock') or settings.default_lock,
                    nsfw=flag('nsfw') or settings.default_nsfw,
                    description=flag('description')
                    or choice(settings.default_descriptions),
                    size=flag('size') or settings.default_size,
                    timeout=flag('timeout') or settings.default_timeout,
                    created=now(),
                    last_active=now())
        await player.add_roles(role)
        await channel.edit(topic="({}/{}) {}".format(len(room.players),
                                                     room.size,
                                                     room.description),
                           nsfw=room.nsfw)
        await channel.send(
            choice(settings.join_messages).format(player.display_name))
        if ctx:
            await RoomEmbed(ctx, room, 'new_room', settings).send()
Esempio n. 29
0
async def on_raw_reaction_add(payload):
    guild = discord.utils.find(lambda g: g.id == payload.guild_id,
                               client.guilds)
    user = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
    channel = discord.utils.find(lambda c: c.id == payload.channel_id,
                                 guild.channels)

    #Проверка на новичка
    if not user.display_name.startswith("["):
        try:
            await user.edit(nick='[0] ' + user.name)
        except:
            print('cant add [0] to ' + user.name)

    #Проверка на бота
    if payload.user_id == 668040788482981899:
        return

    #проверка на канал поиска боксфайтов
    if payload.channel_id == 668140694996779072:

        #проверка на очередь и файты
        if (user in fights) or (user in queue):
            await user.send('Вы уже ищете боксфайт.')
            return

        queue.append(user)

        #очередь больше или равна двум
        if len(queue) >= 2:
            print('queue >= 2')

            queue.remove(user)

            oponnent = queue[random.randint(0, len(queue)) - 1]

            #если искавший = опонненту
            if user == oponnent:
                await user.send('Произошла ошибка. Попробуйте ещё раз.')
                queue.remove(user)
                return

            #если кто то из них бот
            if (user == client.user) and (oponnent == client.user):
                await user.send('Произошла ошибка. Попробуйте ещё раз.')
                queue.remove(user)
                return

            queue.remove(oponnent)

            #создание боксфайт канала
            overwrites_admin = {
                user.guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
                user:
                discord.PermissionOverwrite(read_messages=True),
                oponnent:
                discord.PermissionOverwrite(read_messages=True)
            }
            boxchannel = await user.guild.create_text_channel(
                'boxfight-' + str(randint(1000, 10000)),
                overwrites=overwrites_admin,
                topic=str(payload.user_id) + ' p2 ' + str(oponnent.id))
            embedplayers = discord.Embed(title="CIS Creative",
                                         description="Боксфайт.")
            embedplayers.set_thumbnail(
                url=
                "https://media.discordapp.net/attachments/668037249056768020/668166034783600670/Logo_cis_customs.png?width=473&height=473"
            )
            embedplayers.add_field(name="Первый игрок (♥): ",
                                   value=user.mention,
                                   inline=False)
            embedplayers.add_field(name="Второй игрок (💩): ",
                                   value=oponnent.mention,
                                   inline=False)
            embedrules = discord.Embed(title="CIS Creative",
                                       description="Правила.")
            embedrules.set_thumbnail(
                url=
                "https://media.discordapp.net/attachments/668037249056768020/668166034783600670/Logo_cis_customs.png?width=473&height=473"
            )
            embedrules.add_field(name="Карта:",
                                 value="7620-0771-9529",
                                 inline=False)
            embedrules.add_field(name="Играете до:",
                                 value="3 побед",
                                 inline=False)
            msg = await boxchannel.send(embed=embedplayers)
            await boxchannel.send(embed=embedrules)
            await msg.add_reaction('♥')
            await msg.add_reaction('💩')
            ########################

            fights.append(user)
            fights.append(oponnent)
    if payload.emoji.name == '♥':
        p1 = discord.utils.find(lambda m: m.id == int(get_p1(channel.topic)),
                                guild.members)
        p2 = discord.utils.find(lambda m: m.id == int(get_p2(channel.topic)),
                                guild.members)
        message: discord.Message = await channel.fetch_message(
            payload.message_id)

        #проверка на то что голос не один.
        for reaction in message.reactions:
            if reaction.count <= 2 and reaction.emoji == '♥':
                return
        ##################################

        #отправить сообщение о результате
        embed = discord.Embed(title="CIS Creative",
                              description="Результаты боксфайта:")
        embed.set_thumbnail(
            url=
            "https://media.discordapp.net/attachments/668037249056768020/668166034783600670/Logo_cis_customs.png?width=473&height=473"
        )
        embed.add_field(name="Победитель:",
                        value=p1.name + " (+10)",
                        inline=False)
        embed.add_field(name="Проигравший:",
                        value=p2.name + " (-10)",
                        inline=False)
        await p2.send(embed=embed)
        await p1.send(embed=embed)
        #################################

        #изменить никнеймы
        try:
            await p1.edit(nick='[' + str(get_points(p1.display_name) + 10) +
                          '] ' + p1.name)
        except:
            print('cant change nick for p1')

        try:
            await p2.edit(nick='[' + str(get_points(p2.display_name) - 10) +
                          '] ' + p2.name)
        except:
            print('cant change nick for p2')
        ##

        fights.remove(p1)
        fights.remove(p2)
        await channel.delete()
    if payload.emoji.name == '💩':
        p1 = discord.utils.find(lambda m: m.id == int(get_p1(channel.topic)),
                                guild.members)
        p2 = discord.utils.find(lambda m: m.id == int(get_p2(channel.topic)),
                                guild.members)
        message: discord.Message = await channel.fetch_message(
            payload.message_id)

        #проверка на то что голос не один.
        for reaction in message.reactions:
            if reaction.count <= 2 and reaction.emoji == '💩':
                return
        ##################################

        #отправить сообщение о результате
        embed = discord.Embed(title="CIS Creative",
                              description="Результаты боксфайта:")
        embed.set_thumbnail(
            url=
            "https://media.discordapp.net/attachments/668037249056768020/668166034783600670/Logo_cis_customs.png?width=473&height=473"
        )
        embed.add_field(name="Победитель:",
                        value=p2.name + " (+10)",
                        inline=False)
        embed.add_field(name="Проигравший:",
                        value=p1.name + " (-10)",
                        inline=False)
        await p2.send(embed=embed)
        await p1.send(embed=embed)
        #################################

        #изменить никнеймы
        try:
            await p1.edit(nick='[' + str(get_points(p1.display_name) - 10) +
                          '] ' + p1.name)
        except:
            print('cant change nick for p1')

        try:
            await p2.edit(nick='[' + str(get_points(p2.display_name) + 10) +
                          '] ' + p2.name)
        except:
            print('cant change nick for p2')
        #################################

        fights.remove(p1)
        fights.remove(p2)
        await channel.delete()
Esempio n. 30
0
    async def increment_roles(self, ctx):
        database.base.metadata.create_all(database.db)

        guild = self.bot.get_guild(config.guild_id)

        BIT_names = [str(x) + "BIT" + ("+" if x == 4 else "")
                     for x in range(5)]
        BIT = [discord.utils.get(guild.roles, name=role_name)
               for role_name in BIT_names]

        MIT_names = [str(x) + "MIT" + ("+" if x == 3 else "")
                     for x in range(4)]
        MIT = [discord.utils.get(guild.roles, name=role_name)
               for role_name in MIT_names]

        # pridat kazdeho 3BIT a 2MIT cloveka do DB pred tim nez je jebnem do
        # 4BIT+ respektive 3MIT+ role kvuli rollbacku
        session.query(User_backup).delete()

        for member in BIT[3].members:
            session.add(User_backup(member_ID=member.id))
        for member in MIT[2].members:
            session.add(User_backup(member_ID=member.id))

        session.commit()

        for member in BIT[3].members:
            await member.add_roles(BIT[4])
        for member in MIT[2].members:
            await member.add_roles(MIT[3])

        BIT_colors = [role.color for role in BIT]
        await BIT[3].delete()
        await BIT[2].edit(name="3BIT", color=BIT_colors[3])
        await BIT[1].edit(name="2BIT", color=BIT_colors[2])
        await BIT[0].edit(name="1BIT", color=BIT_colors[1])
        bit0 = await guild.create_role(name='0BIT', color=BIT_colors[0])
        await bit0.edit(position=BIT[0].position - 1)

        MIT_colors = [role.color for role in MIT]
        await MIT[2].delete()
        await MIT[1].edit(name="2MIT", color=MIT_colors[2])
        await MIT[0].edit(name="1MIT", color=MIT_colors[1])
        mit0 = await guild.create_role(name='0MIT', color=MIT_colors[0])
        await mit0.edit(position=MIT[0].position - 1)

        general_names = [str(x) + "bit-general" for x in range(4)]
        terminy_names = [str(x) + "bit-terminy" for x in range(1, 3)]
        general_channels = [discord.utils.get(guild.channels,
                                              name=channel_name)
                            for channel_name in general_names]
        terminy_channels = [discord.utils.get(guild.channels,
                                              name=channel_name)
                            for channel_name in terminy_names]
        # TODO: do smth about 4bit general next year, delete it in the meantime
        bit4_general = discord.utils.get(guild.channels, name="4bit-general")
        if bit4_general is not None:
            await bit4_general.delete()

        # move names
        await general_channels[3].edit(name="4bit-general")
        await general_channels[2].edit(name="3bit-general")
        await general_channels[1].edit(name="2bit-general")
        await general_channels[0].edit(name="1bit-general")
        # create 0bit-general
        overwrites = {
            guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
            discord.utils.get(guild.roles, name="0BIT"):
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=True)
        }
        await guild.create_text_channel(
            '0bit-general', overwrites=overwrites,
            category=general_channels[0].category,
            position=general_channels[0].position - 1
        )

        # delete 3bit-terminy
        await discord.utils.get(guild.channels, name="3bit-terminy").delete()

        await terminy_channels[1].edit(name="3bit-terminy")
        await terminy_channels[0].edit(name="2bit-terminy")
        # create 1bit-terminy
        overwrites = {
            guild.default_role:
                discord.PermissionOverwrite(read_messages=False),
            discord.utils.get(guild.roles, name="1BIT"):
                discord.PermissionOverwrite(read_messages=True,
                                            send_messages=False)
        }
        await guild.create_text_channel(
            '1bit-terminy', overwrites=overwrites,
            category=terminy_channels[0].category,
            position=terminy_channels[0].position - 1
        )

        # give 4bit perms to the new 3bit terminy
        await terminy_channels[1].set_permissions(
            discord.utils.get(guild.roles, name="4BIT+"),
            read_messages=True, send_messages=False
        )

        # Give people the correct mandatory classes after increment
        semester_names = [str(x) + ". Semestr" for x in range(1, 6)]
        semester = [discord.utils.get(guild.categories, name=semester_name)
                    for semester_name in semester_names]
        await semester[0].set_permissions(discord.utils.get(guild.roles,
                                                            name="1BIT"),
                                          read_messages=True,
                                          send_messages=True)
        await semester[0].set_permissions(discord.utils.get(guild.roles,
                                                            name="2BIT"),
                                          overwrite=None)
        await semester[1].set_permissions(discord.utils.get(guild.roles,
                                                            name="1BIT"),
                                          read_messages=True,
                                          send_messages=True)
        await semester[1].set_permissions(discord.utils.get(guild.roles,
                                                            name="2BIT"),
                                          overwrite=None)
        await semester[2].set_permissions(discord.utils.get(guild.roles,
                                                            name="2BIT"),
                                          read_messages=True,
                                          send_messages=True)
        await semester[2].set_permissions(discord.utils.get(guild.roles,
                                                            name="3BIT"),
                                          overwrite=None)
        await semester[3].set_permissions(discord.utils.get(guild.roles,
                                                            name="2BIT"),
                                          read_messages=True,
                                          send_messages=True)
        await semester[3].set_permissions(discord.utils.get(guild.roles,
                                                            name="3BIT"),
                                          overwrite=None)
        await semester[4].set_permissions(discord.utils.get(guild.roles,
                                                            name="3BIT"),
                                          read_messages=True,
                                          send_messages=True)

        await ctx.send('Holy f**k, všechno se povedlo, '
                       'tak zase za rok <:Cauec:602052606210211850>')