Esempio n. 1
0
    async def msgwithyear(self, ctx: commands.Context, *, message: str):
        """
        Set the message to be send when the user did provide a year.

        **Placeholders:**
            - `{name}` - the user's name
            - `{mention}` - an @ mention of the user
            - `{new_age}` - the user's new age

            All the placeholders are optional.

        **Examples:**
            - `[p]bdset msgwithyear {mention} has turned {new_age}, happy birthday!`
            - `[p]bdset msgwithyear {name} is {new_age} today! Happy birthday {mention}!`
        """
        # group has guild check
        if TYPE_CHECKING:
            assert ctx.guild is not None
            assert isinstance(ctx.author, discord.Member)

        if len(message) > MAX_BDAY_MSG_LEN:
            await ctx.send(
                "That message is too long! It needs to be under 750 characters."
            )

        async with self.config.guild(ctx.guild).all() as conf:
            if conf["message_w_year"] is None:
                conf["setup_state"] += 1

            conf["message_w_year"] = message

        await ctx.send(
            "Message set. Here's how it will look, if you're turning 20:")
        await ctx.send(
            format_bday_message(message, ctx.author, 20),
            allowed_mentions=discord.AllowedMentions(users=True),
        )
Esempio n. 2
0
    async def get_personal_feed(self) -> None:
        """Gets the current user (me)'s manga feed.
        This is all the latest released chapters in order.
        """
        order = FeedOrderQuery(created_at=Order.descending)
        ten_m_ago = datetime.datetime.now(
            datetime.timezone.utc) - datetime.timedelta(minutes=10)
        feed = await self.bot.manga_client.get_my_feed(
            limit=32,
            translated_language=["en", "ja"],
            order=order,
            created_at_since=ten_m_ago,
            content_rating=[
                hondana.ContentRating.pornographic,
                hondana.ContentRating.safe,
                hondana.ContentRating.suggestive,
                hondana.ContentRating.erotica,
            ],
        )

        if not feed.chapters:
            return

        embeds: list[discord.Embed] = []
        for chapter in feed.chapters:
            if chapter.manga is None:
                await chapter.get_parent_manga()
            embeds.append(MangaDexEmbed.from_chapter(chapter))

        for embeds in as_chunks(embeds, 10):
            await self.webhook.send(
                "<@!155863164544614402>",
                embeds=embeds,
                allowed_mentions=discord.AllowedMentions(users=True),
            )

        self.bot.manga_client.dump_refresh_token()
Esempio n. 3
0
    async def maybe_send_embed(self, message: str) -> discord.Message:
        """
        Simple helper to send a simple message to context
        without manually checking ctx.embed_requested
        This should only be used for simple messages.

        Parameters
        ----------
        message: `str`
            The string to send

        Returns
        -------
        discord.Message:
            the message which was sent

        Raises
        ------
        discord.Forbidden
            see `discord.abc.Messageable.send`
        discord.HTTPException
            see `discord.abc.Messageable.send`
        ValueError
            when the message's length is not between 1 and 2000 characters.
        """
        if not message or len(message) > 2000:
            raise ValueError("Message length must be between 1 and 2000")
        if await self.embed_requested():
            return await self.send(embed=discord.Embed(
                description=message, color=(await self.embed_colour())))
        else:
            return await self.send(
                message,
                allowed_mentions=discord.AllowedMentions(everyone=False,
                                                         roles=False,
                                                         users=False),
            )
Esempio n. 4
0
    async def publish(self, ctx, feed: str, *, content: str):
        """Publishes content to a feed.
        Everyone who is subscribed to the feed will be notified
        with the content. Use this to notify people of important
        events or changes.
        """
        feeds = await self.get_feeds(ctx.channel.id)
        feed = feed.lower()
        if feed not in feeds:
            await ctx.send("This feed does not exist.")
            return

        role = discord.utils.get(ctx.guild.roles, id=feeds[feed])
        if role is None:
            fmt = (
                "Uh.. a fatal error occurred here. The role associated with "
                "this feed has been removed or not found. "
                "Please recreate the feed."
            )
            await ctx.send(fmt)
            return

        # delete the message we used to invoke it
        try:
            await ctx.message.delete()
        except discord.HTTPException:
            pass

        # make the role mentionable
        await role.edit(mentionable=True)

        # then send the message..
        mentions = discord.AllowedMentions(roles=[role])
        await ctx.send(f"{role.mention}: {content}"[:2000], allowed_mentions=mentions)

        # then make the role unmentionable
        await role.edit(mentionable=False)
Esempio n. 5
0
def main():
    """Main script to run the bot."""
    if discord.version_info.major < 1:
        print(
            f'discord.py is not at least 1.0.0x. (current version: {discord.__version__})'
        )
        return 2

    if not hexversion >= 0x30800f0:  # 3.8
        print('Kurisu requires 3.8 or later.')
        return 2

    # attempt to get current git information
    try:
        commit = check_output(['git', 'rev-parse',
                               'HEAD']).decode('ascii')[:-1]
    except CalledProcessError as e:
        print(f'Checking for git commit failed: {type(e).__name__}: {e}')
        commit = "<unknown>"

    try:
        branch = check_output(['git', 'rev-parse', '--abbrev-ref',
                               'HEAD']).decode()[:-1]
    except CalledProcessError as e:
        print(f'Checking for git branch failed: {type(e).__name__}: {e}')
        branch = "<unknown>"

    bot = Kurisu(('.', '!'),
                 description="Kurisu, the bot for Nintendo Homebrew!",
                 allowed_mentions=discord.AllowedMentions(everyone=False,
                                                          roles=False))
    bot.help_command = commands.DefaultHelpCommand(dm_help=None)
    print(f'Starting Kurisu on commit {commit} on branch {branch}')
    bot.load_cogs()
    bot.run(config['Main']['token'])

    return bot.exitcode
Esempio n. 6
0
async def scan_sgl_schedule():
    guild_id = await config.get(0, 'SGLAuditChannel')
    audit_channel_id = await config.get(guild_id, 'SGLAuditChannel')
    audit_channel = discordbot.get_channel(int(audit_channel_id))

    if c.DEBUG:
        events = ['test']
    else:
        events = EVENTS.keys()
    print("SGL - scanning SG schedule for races to create")
    for event in events:
        await asyncio.sleep(1) # this keeps SG's API from getting rekt
        try:
            delay = 0 if c.DEBUG else EVENTS[event]['delay']/60
            episodes = await speedgaming.get_upcoming_episodes_by_event(event, hours_past=0.5, hours_future=.53+delay)
        except Exception as e:
            logging.exception(
                "Encountered a problem when attempting to retrieve SG schedule.")
            if audit_channel:
                await audit_channel.send(
                    f"There was an error while trying to scan schedule for {event}`.\n\n{str(e)}")
            continue
        for episode in episodes:
            print(episode['id'])
            try:
                await create_sgl_match(episode)
            except Exception as e:
                logging.exception(
                    "Encountered a problem when attempting to create RT.gg race room.")
                if audit_channel:
                    await audit_channel.send(
                        f"<@185198185990324225> There was an error while automatically creating a race room for episode `{episode['id']}`.\n\n{str(e)}",
                        allowed_mentions=discord.AllowedMentions(
                            everyone=True)
                    )

    print('done')
Esempio n. 7
0
    def __init__(self):
        allowed_mentions = discord.AllowedMentions(
            roles=True, everyone=False, users=True
        )
        intents = discord.Intents(
            guilds=True,
            members=True,
            bans=True,
            emojis=True,
            voice_states=True,
            messages=True,
            reactions=True,
        )
        super().__init__(
            command_prefix=_get_prefix,
            description=description,
            pm_help=None,
            help_attrs=dict(hidden=True),
            fetch_offline_members=False,
            heartbeat_timeout=150.0,
            allowed_mentions=allowed_mentions,
            intents=intents,
        )

        # guild_id: list
        self.prefixes = Config("prefixes.yaml")

        # guild_id and user_id mapped to True
        # globally blacklisted users and guilds
        self.blacklist = Config("blacklist.yaml")

        for extension in initial_extensions:
            try:
                self.load_extension(extension)
            except Exception:
                print(f"Failed to load extension {extension}.", file=sys.stderr)
                traceback.print_exc()
Esempio n. 8
0
    async def open_ticket(self, guild, user):
        ticket_check = await self.bot.db.fetchval("SELECT ticket_channel FROM tickets WHERE user_id = $1 AND status = $2", user.id, 0)
        if ticket_check:
            return ticket_check
        category = self.bot.get_channel(783682371953098803)
        if len(category.channels) >= 41:
            self.bot.waiting_users[user.id] = datetime.now(timezone.utc)
            return None
        self.bot.waiting_users.pop(user.id, None)
        support = guild.get_role(679647636479148050)
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            user: discord.PermissionOverwrite(read_messages=True, send_messages=False),
            support: discord.PermissionOverwrite(read_messages=True, send_messages=True),
            guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_permissions=True, manage_channels=True)
        }

        channel = await category.create_text_channel(name=f"ticket-{user.name}", overwrites=overwrites,
                                                     reason=f"Support ticket channel - {user.id}",
                                                     topic=f"User ID: {user.id}")
        await self.bot.db.execute("INSERT INTO tickets(user_id, status, ticket_channel) VALUES($1, $2, $3)", user.id, 0, channel.id)

        return await channel.send(f"{user.mention} Please choose the subject of your ticket.",
                                  allowed_mentions=discord.AllowedMentions(users=True), view=DropdownView(self, channel))
Esempio n. 9
0
    async def required_remove(
        self, ctx: Context, role: RoleHierarchyConverter, *required: RoleHierarchyConverter
    ):
        """
        Remove role requirements

        `<role>` This is the role a user may acquire you want to set requirements for.
        `<requires>` The role(s) you wish to have added when a user gains the `<role>`

        Note: This will only work for reaction roles from this cog.
        """
        cur_setting = await self.config.role(role).required()
        for included_role in required:
            if included_role.id in cur_setting:
                cur_setting.remove(included_role.id)
        await self.config.role(role).required.set(cur_setting)
        roles = [ctx.guild.get_role(i) for i in cur_setting]
        if roles:
            allowed_mentions = {}
            role_names = humanize_list([i.name for i in roles if i])
            if version_info >= VersionInfo.from_str("3.4.0"):
                allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=False)}
                role_names = humanize_list([i.mention for i in roles if i])
            await ctx.send(
                _(
                    "Role {role} will now only be given if the following roles "
                    "are already owned.\n{included_roles}."
                ).format(role=role.name, included_roles=role_names),
                **allowed_mentions
            )
        else:
            return await ctx.send(
                _("Role {role} will no longer require any other roles to be added.").format(
                    role=role.name
                )
            )
Esempio n. 10
0
    async def inclusive_add(
        self, ctx: Context, role: RoleHierarchyConverter, *include: RoleHierarchyConverter
    ):
        """
        Add role inclusion (This will add roles if the designated role is acquired
        if the designated role is removed the included roles will also be removed
        if the included roles are set to selfremovable)

        `<role>` This is the role a user may acquire you want to set exclusions for.
        `<include>` The role(s) you wish to have added when a user gains the `<role>`

        Note: This will only work for reaction roles and automatic roles from this cog.
        """
        cur_setting = await self.config.role(role).inclusive_with()
        exclusive = await self.config.role(role).exclusive_to()
        for included_role in include:
            if included_role.id in exclusive:
                return await ctx.send(
                    _("You cannot include a role that is already considered exclusive.")
                )
            if included_role.id not in cur_setting:
                cur_setting.append(included_role.id)
        await self.config.role(role).inclusive_with.set(cur_setting)
        roles = [ctx.guild.get_role(i) for i in cur_setting]
        allowed_mentions = {}
        role_names = humanize_list([i.name for i in roles if i])
        if version_info >= VersionInfo.from_str("3.4.0"):
            allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=False)}
            role_names = humanize_list([i.mention for i in roles if i])
        await ctx.send(
            _(
                "Role {role} will now add the following roles if it "
                "is acquired automatically or via reaction roles.\n{included_roles}."
            ).format(role=role.name, included_roles=role_names),
            **allowed_mentions
        )
Esempio n. 11
0
async def auto_guild_leave(ctx, abusive_user, guild):
    notif_channel = ctx.bot.get_channel(ctx.bot.settings['channels']['joins-leaves'])
    moksej = ctx.bot.get_user(345457928972533773)

    e = discord.Embed(color=ctx.bot.settings['colors']['error_color'], timestamp=datetime.utcnow())
    e.set_author(name="Left guild forcefully", icon_url=guild.icon_url)
    e.description = f"""
Hey {guild.owner}!
Just wanted to let you know that I left your server: **{guild.name}** ({guild.id}) as one of your members ({abusive_user} - {abusive_user.id}) was abusing my commands in a channel I can't send messages in.
The user will most likely get blacklisted, even if it turns out they were maliciously doing that.

Since this leave was an automatic leave, you may invite me back, but if same action will occur multiple times, the server might get blacklisted."""
    msg = ''
    try:
        await guild.owner.send(embed=e)
        msg += f' I DMed the server owner ({guild.owner} ({guild.owner.id})) letting them know I\'ve left their server.'
    except Exception:
        msg += ' Unfortunately I wasn\'t able to DM the server owner ({guild.owner} ({guild.owner.id})) as they had their DMs off.'

    notif_message = f"{moksej.mention} I left {guild} as **{abusive_user}** ({abusive_user.id}) was " \
                    f"abusing my commands in a private channel.{msg}"
    all_mentions = discord.AllowedMentions(users=True, everyone=False, roles=False)
    await notif_channel.send(notif_message, allowed_mentions=all_mentions)
    await guild.leave()
Esempio n. 12
0
 def __init__(self):
     """Regular init"""
     super().__init__(command_prefix=self.get_prefix,
                      pm_help=None,
                      allowed_mentions=discord.AllowedMentions(
                          users=True, roles=False, everyone=False),
                      case_insensitive=True,
                      status=discord.Status.online,
                      intents=discord.Intents.all())
     self.colour = 0x00dcff
     self.prefixes, self._tag_dict, self.global_votes = {}, {}, {}
     self.config = _cyber.config()
     self.logger = _cyber.logger()
     self.start_time = dt.utcnow()
     self.ext = [
         f"CyberTron5000.cogs.{filename[:-3]}"
         for filename in os.listdir('./cogs') if filename.endswith('.py')
     ]
     self.clever = Cleverbot(self.config.cleverbot)
     self.clever.set_context(DictContext(self))
     self.load_extension(name='jishaku')
     self.loop.create_task(self.__aioinit__())
     self.embed = CyberEmbed
     self.colour_chooser = CyberColours
Esempio n. 13
0
    async def search(self, ctx:utils.Context, user:typing.Optional[discord.Member]=None, *, search_term:str=""):
        """Searches the datbase for a quote with some text in it babeyeyeyey"""

        # Grab data from the database
        async with self.bot.database() as db:
            if user is None:
                rows = await db("SELECT * FROM user_quotes WHERE text LIKE CONCAT('%', $1::text, '%') ORDER BY timestamp DESC LIMIT 10", search_term)
            else:
                rows = await db("SELECT * FROM user_quotes WHERE user_id=$1 AND text LIKE CONCAT('%', $2::text, '%') ORDER BY timestamp DESC LIMIT 10", user.id, search_term)
        if not rows:
            if search_term:
                return await ctx.send("I couldn't find any text matching that pattern.")
            return await ctx.send(f"{(user or ctx.author).mention} hasn't been featured in any quotes.", allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False))

        # Format output
        rows = rows[:10]
        embed = utils.Embed(use_random_colour=True)
        for row in rows:
            if len(row['text']) <= self.QUOTE_SEARCH_CHARACTER_CUTOFF:
                text = row['text']
            else:
                text = f"{row['text'][:self.QUOTE_SEARCH_CHARACTER_CUTOFF]}..."
            embed.add_field(name=row['quote_id'].upper(), value=text, inline=len(text) < 100)
        return await ctx.send(embed=embed, allowed_mentions=discord.AllowedMentions(everyone=False, users=False, roles=False))
Esempio n. 14
0
    async def _village_vote(self, target, author, target_id):
        if author in self.day_vote:
            self.vote_totals[self.day_vote[author]] -= 1

        self.day_vote[author] = target_id
        if target_id not in self.vote_totals:
            self.vote_totals[target_id] = 1
        else:
            self.vote_totals[target_id] += 1

        required_votes = len([player for player in self.players if player.alive]) // 7 + 2

        if self.vote_totals[target_id] < required_votes:
            await self.village_channel.send(
                f"{author.mention} has voted to put {target.member.mention} to trial. "
                f"{required_votes - self.vote_totals[target_id]} more votes needed",
                allowed_mentions=discord.AllowedMentions(everyone=False, users=[author, target]),
            )
        else:
            self.vote_totals[target_id] = 0
            self.day_vote = {
                k: v for k, v in self.day_vote.items() if v != target_id
            }  # Remove votes for this id
            await self._at_voted(target)
Esempio n. 15
0
    def __init__(self):
        super().__init__(command_prefix=get_prefix,
                         case_insensitive=True,
                         allowed_mentions=discord.AllowedMentions(
                             everyone=False, users=True, roles=True))
        self.logger = logging.getLogger('discord')

        self.start_time = start

        for extension in extensions:
            self.load_extension(extension)

        with open('custom_commands.json', 'r') as f:
            self.custom_commands = json.load(f)

        with open('config.json', 'r') as f:
            self.config = json.load(f)
            if not self.config['blacklist']:
                self.config['blacklist'] = []
            config = self.config

        self.session = aiohttp.ClientSession()

        self.current_count = 0
Esempio n. 16
0
    async def record_bad_user(self, member, role_name, guild=None):
        if guild is None:
            guild = member.guild

        latest_messages = self.logs.get(member.id, "")
        msg = 'Name={} Nick={} ID={} Joined={} Role={}\n'.format(
            member.name, member.display_name, member.id,
            member.joined_at if isinstance(member, discord.Member) else 'N/A',
            role_name)
        msg += '\n'.join(latest_messages)
        strikes = self.settings.count_user_strikes(guild.id, member.id)

        update_channel = self.settings.get_channel(guild.id)
        if update_channel is not None:
            channel_obj = guild.get_channel(update_channel)
            await channel_obj.send(inline('Detected bad user'))
            await channel_obj.send(box(msg))
            followup_msg = 'Hey @here please manually strike this user explaining why they are punished'
            await channel_obj.send(
                followup_msg,
                allowed_mentions=discord.AllowedMentions(everyone=True))
            await channel_obj.send('This user has {} strikes'.format(strikes))

            try:
                dm_msg = (
                    f'You were assigned the punishment role "{role_name}" in the server "{guild.name}".\n'
                    f'The Mods will contact you shortly regarding this.\n'
                    f'Attempting to clear this role yourself will result in punishment.'
                )
                await member.send(box(dm_msg))
                await channel_obj.send('User successfully notified')
            except Exception as e:
                if role_name != "BANNED":
                    await channel_obj.send(
                        'Failed to notify the user! I might be blocked\n' +
                        box(str(e)))
Esempio n. 17
0
    async def on_voice_state_update(self, member: discord.Member,
                                    before: discord.VoiceState,
                                    after: discord.VoiceState):
        """Log users joining or leaving VCs"""

        if before.channel == after.channel:
            return
        update_log_id = self.bot.guild_settings[
            member.guild.id]['voice_update_modlog_channel_id']
        if not update_log_id:
            return
        channel = self.bot.get_channel(update_log_id)
        if not channel:
            return
        try:
            if before.channel is None:
                text = f"{member.mention} joined the **{after.channel.name}** VC."
            elif after.channel is None:
                text = f"{member.mention} left the **{before.channel.name}** VC."
            else:
                text = f"{member.mention} moved from the **{before.channel.name}** VC to the **{after.channel.name}** VC."
            if channel.permissions_for(channel.guild.me).embed_links:
                data = {
                    "embed": utils.Embed(use_random_colour=True,
                                         description=text)
                }
            else:
                data = {
                    "content": text,
                    "allowed_mentions": discord.AllowedMentions(users=False)
                }
            await channel.send(**data)
            self.logger.info(
                f"Logging updated VC user (G{member.guild.id}/U{member.id})")
        except discord.Forbidden:
            pass
Esempio n. 18
0
 async def settings(self, ctx: commands.Context):
     """Show settings for your guild."""
     params = {
         "autorole": "Automatic role to give",
         "temprole": "Temporary role to give through verification",
         "verifchannel": "Channel to send captcha",
         "logschannel": "Channel to logs actions",
         "active": "Captcher activated",
     }
     settings = await self.data.guild(ctx.guild).all()
     message = ""
     for setting in settings.items():
         parameter = params[setting[0]]
         rawvalue = setting[1]
         value = rawvalue
         if setting[0] in ("verifchannel", "logschannel"):
             value = f"<#{rawvalue}>"  # Channel mention.
         if setting[0] in ("autorole", "temprole"):
             value = f"<@&{rawvalue}>"  # Role mention, but don't worry, bot won't ping.
         if rawvalue is None:
             value = "Not set."
         message += "{param}: {val}\n".format(param=parameter, val=value)
     await ctx.send(message,
                    allowed_mentions=discord.AllowedMentions(roles=False))
Esempio n. 19
0
    def __init__(self, get_command_prefix, *args, **kwargs):
        intents = discord.Intents.all()
        allowed_mentions = discord.AllowedMentions(everyone=False, roles=False)
        super().__init__(*args,
                         **kwargs,
                         intents=intents,
                         command_prefix=get_command_prefix,
                         allowed_mentions=allowed_mentions)

        # status
        self.dev = bool(strtobool(
            os.environ["DEV"]))  # from docker compose file
        self.ready = False  # True if entire startup sequence connection done
        self.app_info: Optional[
            AppInfo] = None  # App info (loaded once in on_ready event)

        self.config = dict()  # Bot and server configs in one dictionary
        self.main_channel: Optional[
            discord.
            TextChannel] = None  # Main channel system messages will be sent in

        with open("/run/secrets/ipc-secret") as secret_file:
            secret = secret_file.read()
        self.ipc = ipc.Server(self, secret_key=secret, host="0.0.0.0")
Esempio n. 20
0
    def __init__(self):
        intents = discord.Intents.default()
        allowed_mentions = discord.AllowedMentions(everyone=False, users=True, roles=False, replied_user=True)
        intents.members = True
        super().__init__(command_prefix=get_prefix, description="A multipurpose Discord bot", case_insensitive=True, intents=intents, allowed_mentions=allowed_mentions)

        self.support_server_link = "https://discord.gg/eHxvStNJb7"
        self.uptime = datetime.datetime.utcnow()
        self.prefixes = config.Config("prefixes.json", loop=self.loop)
        self.translator = googletrans.Translator()
        self.players = {}
        self.spam_detectors = {}

        with open("assets/emojis.json") as file:
            self.default_emojis = json.load(file)

        self.load_extension("jishaku")
        self.get_cog("Jishaku").hidden = True

        for extension in extensions:
            try:
                self.load_extension(extension)
            except Exception as exc:
                log.info("Couldn't load extension %s", extension, exc_info=exc)
Esempio n. 21
0
    def __init__(self):
        allowed_mentions = discord.AllowedMentions(roles=False,
                                                   everyone=False,
                                                   users=True)
        intents = discord.Intents(guilds=True,
                                  members=True,
                                  bans=True,
                                  emojis=True,
                                  voice_states=True,
                                  messages=True,
                                  reactions=True)

        super().__init__(command_prefix=_prefix_callable,
                         description=description,
                         pm_help=None,
                         help_attrs=dict(hidden=True),
                         fetch_offline_members=True,
                         heartbeat_timeout=150.0,
                         help_command=EmbedHelpCommand(),
                         allowed_mentions=allowed_mentions,
                         intents=intents)

        # self.client_id = self.configs['client_id']
        load_cogs(self)
 async def bump_message(self, guild: discord.Guild):
     data = await self.config.guild(guild).all()
     channel = guild.get_channel(data["channel"])
     allowed_mentions = discord.AllowedMentions(roles=True)
     if not channel or not channel.permissions_for(guild.me).send_messages:
         await self.config.guild(guild).channel.clear()
     elif data["role"]:
         role = guild.get_role(data["role"])
         if role:
             message = f"{role.mention}: {data['message']}"
             cog = self.bot.get_cog("ForceMention")
             if cog:
                 await cog.forcemention(channel, role, message)
             else:
                 await channel.send(message, allowed_mentions=allowed_mentions)
         else:
             await self.config.guild(guild).role.clear()
     else:
         message = data["message"]
         try:
             await channel.send(message, allowed_mentions=allowed_mentions)
         except discord.errors.Forbidden:
             await self.config.guild(guild).channel.clear()
     await self.config.guild(guild).nextBump.clear()
Esempio n. 23
0
    async def points(self,
                     ctx: utils.Context,
                     user: typing.Optional[discord.Member] = None,
                     days: int = 7):
        """
        Shows you your message amount over 7 days.
        """

        days = days if days > 0 else 7
        user = user or ctx.author
        async with self.bot.database() as db:
            message_rows = await db(
                """SELECT user_id, COUNT(timestamp) FROM user_messages WHERE guild_id=$1 AND user_id=$2
                AND timestamp > TIMEZONE('UTC', NOW()) - CAST(CONCAT($3 * 1, ' days') AS INTERVAL) GROUP BY user_id""",
                ctx.guild.id,
                user.id,
                days,
            )
            vc_rows = await db(
                """SELECT user_id, COUNT(timestamp) FROM user_vc_activity WHERE guild_id=$1 AND user_id=$2
                AND timestamp > TIMEZONE('UTC', NOW()) - CAST(CONCAT($3 * 1, ' days') AS INTERVAL) GROUP BY user_id""",
                ctx.guild.id,
                user.id,
                days,
            )
        try:
            text = message_rows[0]['count']
        except IndexError:
            text = 0
        try:
            vc = vc_rows[0]['count']
        except IndexError:
            vc = 0
        await ctx.send(
            f"Over the past {days} days, {user.mention} has gained **{text:,}** tracked messages and been in VC for **{utils.TimeValue(vc * 60).clean or '0m'}**, giving them a total of **{text + (vc // 5):,}** points.",
            allowed_mentions=discord.AllowedMentions(users=[ctx.author]))
Esempio n. 24
0
    async def transferchar(self, ctx, user: discord.Member):
        """Gives a copy of the active character to another user."""
        character: Character = await Character.from_ctx(ctx)
        overwrite = ''

        conflict = await self.bot.mdb.characters.find_one({"owner": str(user.id), "upstream": character.upstream})
        if conflict:
            overwrite = "**WARNING**: This will overwrite an existing character."

        await ctx.send(f"{user.mention}, accept a copy of {character.name}? (Type yes/no)\n{overwrite}",
                       allowed_mentions=discord.AllowedMentions(users=[ctx.author]))
        try:
            m = await self.bot.wait_for('message', timeout=300,
                                        check=lambda msg: msg.author == user
                                                          and msg.channel == ctx.channel
                                                          and get_positivity(msg.content) is not None)
        except asyncio.TimeoutError:
            m = None

        if m is None or not get_positivity(m.content): return await ctx.send("Transfer not confirmed, aborting.")

        character.owner = str(user.id)
        await character.commit(ctx)
        await ctx.send(f"Copied {character.name} to {user.display_name}'s storage.")
Esempio n. 25
0
 async def nlp(self, data, message):
     '''
     Get the sentiment with `TextBlob`
     '''
     # getEmotion()
     article_info = dodgyness.getEmotion(data, plotAttitude=True)
     # TextBlob sentiment
     blob = TextBlob(str(data['sentences']))
     article_info['polarity'] = blob.sentiment.polarity
     article_info['sentiment'] = blob.sentiment.subjectivity
     out_str = 'Emotional Charge: ', article_info[
         'emotional charge'], 'attitude:', article_info[
             'attitude'], 'polarity:', article_info[
                 'polarity'], 'sentiment:', article_info['sentiment']
     print("out", out_str)
     out_string_builder = 'Emotional Charge: {} \n Attitude: {} \n Polarity: {} \n Sentiment: {} \n  '.format(
         out_str[1], out_str[3], out_str[5], out_str[7])
     await asyncio.sleep(2)
     await message.channel.send(out_string_builder,
                                allowed_mentions=discord.AllowedMentions(
                                    everyone=False,
                                    roles=False,
                                    users=False))
     return article_info, out_str
Esempio n. 26
0
 def __init__(self, launcher, name, shard_ids, max_shards):
     self.launcher = launcher
     self.process = None
     self.kwargs = dict(
         token=config.BOT_TOKEN,
         shard_ids=shard_ids,
         shard_count=max_shards,
         cluster_name=name,
         cluster_idx=CLUSTER_NAMES.index(name),
         case_insensitive=True,
         fetch_offline_members=False,
         member_cache_flags=discord.MemberCacheFlags.none(),
         allowed_mentions=discord.AllowedMentions(everyone=False, roles=False),
         intents=intents,
     )
     self.name = name
     self.log = logging.getLogger(f"Cluster#{name}")
     self.log.setLevel(logging.DEBUG)
     hdlr = logging.StreamHandler()
     hdlr.setFormatter(logging.Formatter("[%(asctime)s %(name)s/%(levelname)s] %(message)s"))
     fhdlr = logging.FileHandler("logs/launcher.log", encoding="utf-8")
     fhdlr.setFormatter(logging.Formatter("[%(asctime)s %(name)s/%(levelname)s] %(message)s"))
     self.log.handlers = [hdlr, fhdlr]
     self.log.info(f"Initialized with shard ids {shard_ids}, total shards {max_shards}")
Esempio n. 27
0
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
import cog_admin
import cog_basic

bot = commands.Bot(command_prefix="__",
                   allowed_mentions=discord.AllowedMentions(everyone=True,
                                                            users=True))


@bot.event
async def on_ready():
    print("MineBOT est prêt à l'usage !")
    await bot.change_presence(activity=discord.Activity(
        type=discord.ActivityType.playing, name="with a lot of users"))


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("Looks like you are not allowed to do this...")


bot.add_cog(cog_basic.CogBasic(bot))
bot.add_cog(cog_admin.CogAdmin(bot))
bot.run("token")
Esempio n. 28
0
 async def create_ticket(self, index, member, category, guild):
     overwrites = {
         guild.default_role: discord.PermissionOverwrite(read_messages=True)
     }
     ticket_channel = await guild.create_text_channel(f'📩-Ticket - {index}', overwrites=overwrites, category=category, reason="L'utilisateur a demandé de l'aide")
     await ticket_channel.send(f"{member.mention}\nDécrit ton problème ici, un membre te répondra vite", allowed_mentions=discord.AllowedMentions(users=True))
     options = ["Close"]
     reactions = ['🔒']
     embed = discord.Embed(colour=0x00aa40, title="Support", description="Pour fermer le ticket, cliquez sur 🔒")
     react_message = await ticket_channel.send(embed=embed)
     for reaction in reactions[:len(options)]:
         await react_message.add_reaction(reaction)
     embed.set_footer(text='Ticket ID: {}'.format(index))
     tickets = await self.config.TICKETS()
     tickets[str(index)]=[ticket_channel.id, react_message.id]
     await self.config.TICKETS.set(tickets)
     users = await self.config.USERS()
     users[str(index)] = member.id
     await self.config.USERS.set(users)
     await react_message.edit(embed=embed)
Esempio n. 29
0
    async def on_raw_reaction_add(self, payload):
        channel = self.bot.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        if message.author.id == payload.user_id:
            return
        if not message.embeds:
            return
        embed = message.embeds[0]
        guild = self.bot.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id)
        index = await self.config.INDEX()
        try:
            if embed.footer.text.startswith('Pannel ID:'):
                pass
        except:
            return
        if embed.footer.text.startswith('Pannel ID:'):
            await message.remove_reaction(payload.emoji, member)
            category_id = channel.category_id
            categories = guild.categories
            for k in categories:
                if k.id == category_id:
                    category = k
            await self.config.INDEX.set(index + 1)
            await self.create_ticket(index, member, category, guild)

        elif embed.footer.text.startswith('Ticket ID:'):
            await message.remove_reaction(payload.emoji, member)
            await message.clear_reactions()
            emb = message.embeds[0]
            embed = discord.Embed(colour=0xfbfe32, title="", description=f"Ticket fermé par {member.mention}")
            await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions(users=True))

            options = ['Réouvrir le Ticket', 'Supprimer le Ticket']
            reactions = ['🔓', '⛔']
            description = []
            for x, option in enumerate(options):
                description += '\n {} {}'.format(reactions[x], option)
            index = emb.footer.text.split(':')[1][1:]

            users = await self.config.USERS()
            member = guild.get_member(users[str(index)])
            await channel.set_permissions(guild.default_role, read_messages=False, reason='Ticket fermé')
            await channel.edit(reason='Ticket fermé', name=f'🔒-Fermé - {index}')

            embed = discord.Embed(colour=0xd32f2f, title="Outils d'adminitration", description=''.join(description))
            react_message = await channel.send(embed=embed)
            for reaction in reactions[:len(options)]:
                await react_message.add_reaction(reaction)
            embed.set_footer(text='Mod ID: {}'.format(index))
            await react_message.edit(embed=embed)

        elif embed.footer.text.startswith('Mod ID:'):
            if str(payload.emoji) == '🔓':
                await message.delete()
                embed = discord.Embed(colour=0x00aa40, title="", description=f"Ticket ouvert par {member.mention}")
                await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions(users=True))
                emb = message.embeds[0]
                index = emb.footer.text.split(':')[1][1:]
                users = await self.config.USERS()
                member = guild.get_member(users[str(index)])
                await channel.set_permissions(guild.default_role, read_messages=True)
                await channel.edit(reason='Ticket ouvert', name=f'📩-Ticket - {index}')
                tickets = await self.config.TICKETS()
                channel_id = tickets[str(index)][0]
                message_id = tickets[str(index)][1]
                channel = self.bot.get_channel(channel_id)
                react_message = await channel.fetch_message(message_id)
                options = ["Close"]
                reactions = ['🔒']
                for reaction in reactions[:len(options)]:
                    await react_message.add_reaction(reaction)
            elif str(payload.emoji) == 'â›”':
                await message.delete()
                transcript = self.bot.get_channel(self.transcript_id)
                embed = discord.Embed(colour=0xfbfe32, title="", description=f"Transcript en cours de génération, le channel sera automatiquement supprimé")
                await channel.send(embed=embed)
                emb = message.embeds[0]
                index = emb.footer.text.split(':')[1][1:]
                users = await self.config.USERS()
                member = guild.get_member(users[str(index)])
                subprocess.call(['dotnet', '/data/DiscordChatExplorer/DiscordChatExporter.Cli.dll', 'export', '-c', f'{payload.channel_id}', '-t', f'{self.token}', '-b', '-o', f'/data/DiscordChatExplorer/transcript-{index}.html'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                presents = []
                async for message in channel.history(limit=5000):
                    if guild.get_member(message.author.id).mention not in presents:
                        presents.append(guild.get_member(message.author.id).mention)
                presents.pop(0)
                embed = discord.Embed(colour=0xfffc80, title=f"Ticket - {index}", description=f"Détails du transcript")
                embed.add_field(name='Propriétaire du ticket', value=f'{member.mention}', inline=False)
                if len(presents) != 0:
                    embed.add_field(name='Utilisateurs dans le transcript', value=' '.join(presents), inline=False)
                else:
                    embed.add_field(name='Utilisateurs dans le transcript', value='-', inline=False)
                await transcript.send(embed=embed, file=discord.File(f'/data/DiscordChatExplorer/transcript-{index}.html'), allowed_mentions=discord.AllowedMentions(users=True))
                os.remove(f'/data/DiscordChatExplorer/transcript-{index}.html')
                await channel.delete(reason='Ticket Supprimé')
                tickets = await self.config.TICKETS()
                del tickets[str(index)]
                await self.config.TICKETS.set(tickets)
                users = await self.config.USERS()
                del users[str(index)]
                await self.config.USERS.set(users)
Esempio n. 30
0
    async def approvecoc(self, ctx, key: str, member: discord.Member):
        if ctx.guild.id == 374596069989810176:
            async with self.config.members() as database:
                if str(member.id) not in database.keys():
                    return await ctx.send(
                        "You don't have a tag saved please use !savecoc to save your tag"
                    )
                player_tag = database[str(member.id)]
                url = "https://api.clashofclans.com/v1/players/%23" + player_tag
                async with self.session.request("GET",
                                                url=url,
                                                headers=HEADERS) as resp:
                    response = await resp.text()
                player_data = json.loads(response)
                player_name = player_data['name']
                townhall = player_data['townHallLevel']
                trophies = player_data['trophies']
                nick_correct = False
                nicks = ""
                for clan in self.family_clans:
                    nicks += f"{self.family_clans[clan]['nick']}, "
                    if self.family_clans[clan]["nick"] == key:
                        nick_correct = True
                        tag = self.family_clans[clan]["tag"]
                        url = "https://api.clashofclans.com/v1/clans/%23" + tag
                        async with self.session.request(
                                "GET", url=url, headers=HEADERS) as resp:
                            response = await resp.text()
                        clan_data = json.loads(response)
                        if townhall >= self.family_clans[clan][
                                'th_level'] and trophies >= clan_data[
                                    'requiredTrophies']:
                            if clan_data['members'] == 50:
                                return await ctx.maybe_send_embed(
                                    f"Approval failed, the clan is full")
                            await member.edit(nick=f"{player_name} (Approved)")
                            channel = ctx.guild.get_channel(375839851955748874)

                            role_id = self.family_clans[clan]['role']
                            role_to_ping = ctx.guild.get_role(role_id)
                            recruit_code = "".join(
                                random.choice(string.ascii_uppercase +
                                              string.digits) for _ in range(6))

                            message = f"Congratulations, You have been approved to join {clan}(#{tag}) \n Your **RECRUIT CODE** is: ``{recruit_code}`` \n\n To join Search for #{tag} or {clan} in-game.\n Send a request **using recruit code** above and wait for your clan leadership to accept you. It usually takes a few minutes to get accepted, but it may take up to a few hours. \n\n**IMPORTANT**: Once your clan leadership has accepted your request, let a staff member in discord know that you have been accepted. They will then unlock all the member channels for you."
                            try:
                                await member.send(message)
                            except discord.Forbidden:
                                return await ctx.maybe_send_embed(
                                    f"Approval failed, please allow Direct messages from this server and try again later."
                                )
                            await ctx.maybe_send_embed(
                                f"Approval succesful, please check your DMs {member.mention}"
                            )
                            embed = discord.Embed(color=0xFAA61A)
                            embed.set_author(
                                name="New Recruit",
                                icon_url=
                                "https://cdn.discordapp.com/emojis/709796075581735012.gif?v=1"
                            )
                            embed.set_footer(
                                text="By Kingslayer | Legend Gaming",
                                icon_url=
                                "https://cdn.discordapp.com/emojis/709796075581735012.gif?v=1"
                            )
                            embed.add_field(name="Name", value=player_name)
                            embed.add_field(name="Recruit Code",
                                            value=recruit_code)
                            embed.add_field(name="Clan", value=clan)
                            await channel.send(
                                f"{role_to_ping.mention}",
                                allowed_mentions=discord.AllowedMentions(
                                    roles=True),
                                embed=embed)

                        else:
                            await ctx.maybe_send_embed(
                                f"Approval failed, the player doesn't meet requirements for {clan}"
                            )

                if not (nick_correct):
                    return await ctx.send(
                        f"Incorrect clan key provided! Please use any of these as keys {nicks[0:len(nicks)-2]}."
                    )

        else:
            await ctx.send("This command only works on the Legend server")