Ejemplo n.º 1
0
    async def on_ready(self):
        """
        When the bot has loading all components and extensions.
        """

        # Initialize discord components
        DiscordComponents(bot=self)

        # Changing the current bot status
        self.logger.info(
            f'Successfully logged in as {self.user}\nSharded to {len(self.guilds)} guilds'
        )
        await self.change_presence(activity=discord.Game(
            name='Use the prefix "M."'))

        # Load our extensions to register commands in each specific sector
        for ext in initial_cogs:
            self.load_extension(ext)
        self.logger.info("All extensions have loaded!")

        # Send a new verification message on every reinstation of the bot
        embed = self.em(title="Verification",
                        description="This is to make sure you are not a bot!",
                        color=0x00ff00)
        button = Button(label="Verify")

        channel = self.get_channel(int(VERIFICATION_CHANNEL))

        return await channel.send(embed=embed, components=[button])
Ejemplo n.º 2
0
    async def game(self, ctx):
        DiscordComponents(self.bot)
        quote, name = self.get_random_quote()
        database = self.get_characters()
        component = self.create_random_components(database, name)

        question = await ctx.send(quote, components=[component])

        try:
            interaction = await self.bot.wait_for("button_click", timeout=10)

            if interaction.component.label == name:
                await question.edit(quote,
                                    components=[
                                        Button(style=ButtonStyle.green,
                                               label="Correct!",
                                               disabled=True)
                                    ])
                await interaction.respond(
                    type=InteractionType.ChannelMessageWithSource,
                    content="Lucky")
            else:
                await question.edit(quote,
                                    components=[
                                        Button(style=ButtonStyle.red,
                                               label="You're an idiot!",
                                               disabled=True)
                                    ])
                await interaction.respond(
                    type=InteractionType.ChannelMessageWithSource,
                    content="so bad")
        except:
            await question.edit(
                components=[Button(label="Too slow!", disabled=True)])
Ejemplo n.º 3
0
 async def test(self, ctx, *, arg=None):
     ddb = DiscordComponents(self.bot)
     counter = 0
     m = await ctx.send(f"{counter} Clicks",
                        components=[
                            Button(style=ButtonStyle.randomColor(),
                                   label="Click Me!",
                                   id="1",
                                   emoji="👉")
                        ])
     while True:
         res = await ddb.wait_for_interact("button_click")
         if res.channel == ctx.message.channel:
             counter += 1
             await m.edit(f"{counter} Clicks",
                          components=[
                              Button(style=ButtonStyle.randomColor(),
                                     label="Click Me!",
                                     id="1",
                                     emoji="👉")
                          ])
             print(counter)
             await res.respond(
                 type=InteractionType.ChannelMessageWithSource,
                 content=f'{res.component.label} {counter}')
         res = await ddb.wait_for_interact("button_click")
Ejemplo n.º 4
0
async def on_ready():
    DiscordComponents(client)
    await client.change_presence(
        activity=discord.Activity(
            name='Life', type=discord.ActivityType.competing))
    for filename in os.listdir('./extensions'):
        if filename.endswith('.py'):
            client.load_extension(f'extensions.{filename[:-3]}')
    print('Bot is ready.')
Ejemplo n.º 5
0
    async def on_connect():
        t0 = time()
        DiscordComponents(bot)

        bot.load_extension('src.cogs.search_engine_cog')
        bot.load_extension('src.cogs.administration_cog')
        bot.load_extension('src.cogs.administration_slashcog')
        bot.load_extension('src.cogs.search_engine_slashcog')

        auto_save.start()
        cache_clear.start()

        #add new servers to settings
        for servers in bot.guilds:
            bot.serverSettings = Sudo.server_settings_check(servers.id, bot)

        #sets bot globals
        bot.devmode = False

        #remove old servers from settings
        delete_queue = []
        guild_list = [g.id for g in bot.guilds]
        for keys in bot.serverSettings.keys():
            if int(keys, 0) not in guild_list:
                delete_queue.append(keys)

        for keys in delete_queue:
            del bot.serverSettings[keys]

        Sudo.save_configs(bot)

        with open("logs.csv", "r", newline='', encoding='utf-8-sig') as file:
            lines = [
                dict(row) for row in DictReader(file)
                if datetime.now(timezone.utc) -
                datetime.fromisoformat(row["Time"]) < timedelta(weeks=8)
            ]

        with open("logs.csv", "w", newline='', encoding='utf-8-sig') as file:
            logFieldnames = [
                "Time", "Guild", "User", "User_Plaintext", "Command", "Args"
            ]
            writer = DictWriter(file,
                                fieldnames=logFieldnames,
                                extrasaction='ignore')
            writer.writeheader()
            writer.writerows(lines)

        bot.session = ClientSession()

        bot.botuser = await bot.application_info()
        await bot.change_presence(activity=Activity(
            type=ActivityType.listening, name="command prefix '&'"))
        t1 = time()
        print(f"Bot alive. Took {t1-t0:.3f}s")
        return
Ejemplo n.º 6
0
async def on_ready():
    logging.info(
        'drop-discord is ready: everything should have loaded successfully.')
    if os.name == 'nt':
        if clear_terminal:
            os.system("cls")
        if change_terminal_name:
            os.system(f"title {bot.user}")
    elif os.name == 'posix':
        if clear_terminal:
            os.system("clear")
        if change_terminal_name:
            os.system(f"printf '\\033]2;{bot.user}\\a'"
                      )  # Sets terminal name to the bot's user.
    else:
        # What the hell is this running on!?
        print(f"Running on an unknown OS ({os.name})")
    DiscordComponents(bot)
    await get_github_config()
    print(
        f'I am {bot.user} (user ID {bot.user.id}), in {len(bot.guilds)} guilds.'
    )

    try:
        if ownerId:
            owner_refresh.start()
        activity_changer.start()
        inactivity_func.start()
        unban_task.start()
    except RuntimeError:
        # whoops, already started.
        pass

    if get_config_parameter('geniusApi', str):
        init_genius(get_config_parameter('geniusApi', str))

    global bot_mention
    global bot_mention_mobile
    bot_mention = f'<@!{bot.user.id}>'
    bot_mention_mobile = f'<@{bot.user.id}>'

    for guild in bot.guilds:  # loop through every guild we're in
        logging.info(f"found guild {guild.name}")
        try:
            invites = await guild.invites(
            )  # get a list of invites from the guild
        except discord.Forbidden:
            logging.info('not enough permissions, cancelling')
        else:
            logging.info(f"found invites: {invites}")
            bot.guild_invites[
                guild.id] = invites  # store the guild's invites internally
    # anti raid invites thing

    return
Ejemplo n.º 7
0
async def on_ready():
    DiscordComponents(client)

    # Load all cogs
    for file in os.listdir('Cogs'):
        if not file.startswith('__') and file.endswith('.py'):
            try:
                client.load_extension(f'Cogs.{file[:-3]}')
            except commands.errors.NoEntryPointError:
                pass
    print('Cogs loaded')
Ejemplo n.º 8
0
    def __init__(self, dyphanbot):
        super().__init__(dyphanbot)

        self._persist_fn = "persistence.json"
        self._config_fn = "config.json"

        self._persistence_data = self.load_json(self._persist_fn)
        self.config = self.load_json(self._config_fn, initial_data={
            "enabled_experiments": [],
            "use_webhooks": False
        }, save_json=self._save_config)

        self.ddb = None
        if 'components' in self.config.get('enabled_experiments', []):
            try:
                from discord_components import DiscordComponents
                self.ddb = DiscordComponents(self.dyphanbot, change_discord_methods=False)
            except ImportError:
                self.logger.warn("Experiment 'components' enabled, but 'discord_components' module not found.")

        self.controller = AudioController(dyphanbot, config=self.config, ddb=self.ddb)
Ejemplo n.º 9
0
    async def on_ready(self):
        DiscordComponents(self)

        self.reconnect_time = datetime.utcnow()
        login_msg = "Bot Connected at {} UTC".format(str(datetime.utcnow()))
        Logger.log_write(
            "----------------------------------------------------------\n"
            "{}\n"
            "".format(login_msg))
        print(login_msg)

        self.ensure_all_fields_server()
        IO.write_server(self.servers_config)
Ejemplo n.º 10
0
async def on_ready():
    # for guild in client.guilds:
    #     guild_id = str(guild.id)
    #     guild_name = str(guild.name)
    #     nos = len(guild.members)
    #     owner = str(guild.owner)
    #     print(f"Id = {guild_id} , Name = {guild_name}, Nos = {nos} , Owner {owner}")
    DiscordComponents(client)
    print("On Ready Function Working")
    await client.change_presence(activity=discord.Activity(
        status=discord.Status.idle,
        type=discord.ActivityType.watching,
        name=f"{len(set(client.users))} Members & {len(client.guilds)} Servers"
    ))
    print('Guild Function Working')
Ejemplo n.º 11
0
 async def on_ready(self):
     DiscordComponents(client)
     print(BANNER)
     print(
         "\n----------------------------------------------------------------\n"
     )
     print(
         f'Der Bot mit dem Namen "{self.user}" wurde erfolgreich gestartet!\n'
     )
     print(f"Discord.py Version: {discord.__version__}")
     print(f"Python Version: {platform.python_version()}")
     print(
         f"Operating System: {platform.system()} {platform.release()} ({os.name})"
     )
     client.loop.create_task(self.status_task())
Ejemplo n.º 12
0
async def on_ready():
    DiscordComponents(bot, change_discord_methods=True)
    t = time.strftime("%b %d, %I:%M:%S %p")
    print(f"[{t}] I am running")
    await bot.change_presence(activity=discord.Game(name="birdflop.com"))
    cursor = db.cursor(buffered=True)
    command = """CREATE TABLE IF NOT EXISTS guilds (
                    id bigint PRIMARY KEY,
                    panel bigint,
                    category bigint,
                    next int NOT NULL,
                    transcript bigint,
                    prefix char(2) DEFAULT '-');"""
    cursor.execute(command)
    db.commit()
    cursor = db.cursor(buffered=True)
    command = """CREATE TABLE IF NOT EXISTS tickets (
                 channel bigint PRIMARY KEY,
                 creator bigint NOT NULL,
                 guild bigint NOT NULL,
                 expiry int(11),
                 FOREIGN KEY (guild) REFERENCES guilds (id));"""
    cursor.execute(command)
    db.commit()
    now = int(time.time())
    cursor = db.cursor(buffered=True)
    command = f"SELECT expiry, channel FROM tickets WHERE expiry > 0 AND expiry < %s;"
    cursor.execute(command, (now, ))
    result = cursor.fetchall()
    for r in result:
        channel = bot.get_channel(r[1])
        if channel:
            await channel.send("This ticket has been automatically closed.")
            await saveandclose(channel)
        else:
            cursor = db.cursor(buffered=True)
            command = f"DELETE FROM tickets WHERE channel = %s;"
            cursor.execute(command, (r[1], ))
            db.commit()
Ejemplo n.º 13
0
async def on_ready():
    DiscordComponents(bot)
    print("===== [READY] =====")
    bot.me = await bot.fetch_user(210454616876253184)
    emotes = await bot.get_guild(BLACK_CARDS_GUILD_ID).fetch_emojis()
    emotes.extend(await bot.get_guild(RED_CARDS_GUILD_ID).fetch_emojis())
    bot.playing_cards = [
        Card(emote) for emote in emotes if emote.name != "card_back"
    ]
    embed = Embed(title="Bot Online :white_check_mark:", colour=0x77B255)
    now = datetime.datetime.now()
    embed.add_field(
        name="Ready at",
        value=
        f"{now.hour}:{now.minute}:{int(now.microsecond/1000)}\n{now.day}/{now.month}/{now.year}",
        inline=True)
    startup_time = datetime.datetime.now() - init_time
    embed.add_field(
        name="Startup Duration",
        value=
        f"{startup_time.seconds}.{str(startup_time.microseconds)[:3]} seconds")
    await bot.me.send(embed=embed)
    await bot.change_presence(activity=Game("$help"))
Ejemplo n.º 14
0
    async def on_ready(self):
        """
        Sets the status of the bot, instantiates the logger and adds stuff to the db
        """
        DiscordComponents(self.bot)

        public_log_channel = self.bot.get_channel(
            int(os.getenv("PUBLIC_LOG_CHANNEL")))
        log_channel = self.bot.get_channel(int(os.getenv("LOG_CHANNEL")))
        error_channel = self.bot.get_channel(int(os.getenv("ERROR_CHANNEL")))
        hooks = await log_channel.webhooks()
        if len(hooks) == 0:
            log_hook = await log_channel.create_webhook(
                name=f"{self.bot.user.name} logs")
        else:
            log_hook = hooks[0]
        hooks = await error_channel.webhooks()
        if len(hooks) == 0:
            error_hook = await error_channel.create_webhook(
                name=f"{self.bot.user.name} errors")
        else:
            error_hook = hooks[0]
        self.bot.log = Logger(log_hook, error_hook, public_log_channel,
                              self._log_file, self.bot.user.name)
        await self.bot.log.change_level(int(os.getenv("LOG_LEVEL")),
                                        self.bot.user.name)

        for guild in self.bot.guilds:
            try:
                await self.bot.db.execute(
                    "INSERT INTO guilds (id) VALUES ($1)", guild.id)
            except asyncpg.UniqueViolationError:
                pass
            for member in guild.members:
                try:
                    await self.bot.db.execute(
                        "INSERT INTO users (id, trusted, dad_mode) VALUES ($1, false, false)",
                        member.id)
                except asyncpg.UniqueViolationError:
                    pass
                try:
                    await self.bot.db.execute(
                        "INSERT INTO mutes (guild, member) VALUES ($1, $2)",
                        guild.id, member.id)
                except asyncpg.UniqueViolationError:
                    pass
            for channel in guild.text_channels:
                try:
                    await self.bot.db.execute(
                        "INSERT INTO channels (id, guild_id) VALUES ($1, $2)",
                        channel.id, guild.id)
                except asyncpg.UniqueViolationError:
                    pass

        types = {
            "playing": discord.ActivityType.playing,
            "watching": discord.ActivityType.watching,
            "streaming": discord.ActivityType.streaming,
            "listening": discord.ActivityType.listening,
            "competing": discord.ActivityType.competing,
            "custom": discord.ActivityType.custom
        }
        activity = discord.Activity(type=types[os.getenv("ACTIVITY_TYPE")],
                                    name=os.getenv("ACTIVITY"))
        statuses = {
            "online": discord.Status.online,
            "idle": discord.Status.idle,
            "dnd": discord.Status.dnd,
            "invisible": discord.Status.invisible
        }
        await self.bot.change_presence(status=statuses[os.getenv("STATUS")],
                                       activity=activity)

        await self.bot.log.info("Bot online")
        await self.bot.log.public("Bot online!")
Ejemplo n.º 15
0
import config

from discord.ext import commands
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType


bot = commands.Bot(command_prefix='$')
components = DiscordComponents(bot)


@bot.command()
async def test(ctx):
    await ctx.send("Przyciski", components=[Button(style=ButtonStyle.blue, label="test1", disabled=True),
                                            Button(style=ButtonStyle.red, label="test2")])
    res = await bot.wait_for("button_click")
    await res.respond(
        type=InteractionType.ChannelMessageWithSource,
        content=res.component.label
    )


bot.run(config.bot_token)
Ejemplo n.º 16
0
 async def on_ready():
     DiscordComponents(bot)
     print('Im alive.')
Ejemplo n.º 17
0
        cfg["Settings"]["prefix"].strip("\""),
        cfg["Settings"]["secondary-prefix"].strip("\""))
else:
    prefixes = commands.when_mentioned_or(
        cfg["Settings"]["prefix"].strip("\""))

intents = discord.Intents.all()

client = commands.Bot(command_prefix=prefixes,
                      case_insensitive=True,
                      help_command=ComradeHelp(),
                      intents=intents,
                      status=discord.Status.online,
                      activity=discord.Game(cfg["Settings"]["Status"]))

ddb = DiscordComponents(client)

slash = SlashCommand(client,
                     override_type=True,
                     sync_commands=True,
                     sync_on_cog_reload=True,
                     delete_from_unused_guilds=True)


# Listeners for client events
@client.event
async def on_error(event, *args, **kwargs):
    try:
        raise event
    except discord.HTTPException:
        os.system("kill 1")  # hard restart on 429
Ejemplo n.º 18
0
 def __init__(self, bot):
     self.bot = bot
     self.db = db()
     DiscordComponents(self.bot)
     with open("json/picture.json", "r") as f:
         self.colla_num = json.load(f)
Ejemplo n.º 19
0
async def on_ready():
    DiscordComponents(client)
Ejemplo n.º 20
0
async def on_ready():
    DiscordComponents(bot)
    channel = bot.get_channel(int(jdata['Bot_channel']))
    await channel.send('OuO Bot is now Online')
    print("\\OuO Bot is online/")
Ejemplo n.º 21
0
async def on_ready():

    DiscordComponents(bot)

    print(f"Logged in as {bot.user}!")
Ejemplo n.º 22
0
def command_prefix(bot, message):
    if message.guild is None:
        return ''
    else:
        return 'n!'


async def get_prefix(ctx):
    return '' if ctx.guild is None else 'n!'


bot = commands.Bot(command_prefix, case_insensitive=True)
slash = SlashCommand(bot, sync_commands=True)
bot.remove_command('help')
ddb = DiscordComponents(bot)


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}!')
    activity = discord.Game(name=f"n!help | Naxxatra Bot")
    await bot.change_presence(activity=activity)


def apod_get():
    url = f"https://api.nasa.gov/planetary/apod?api_key={os.getenv('NASA_API_KEY')}"
    r = requests.get(url)
    content = r.json()
    embed = discord.Embed(title=content['title'],
                          description=content['explanation'],
Ejemplo n.º 23
0
class Audio(Plugin):
    """ Handles the 'audio' commands for DyphanBot """

    def __init__(self, dyphanbot):
        super().__init__(dyphanbot)

        self._persist_fn = "persistence.json"
        self._config_fn = "config.json"

        self._persistence_data = self.load_json(self._persist_fn)
        self.config = self.load_json(self._config_fn, initial_data={
            "enabled_experiments": [],
            "use_webhooks": False
        }, save_json=self._save_config)

        self.ddb = None
        if 'components' in self.config.get('enabled_experiments', []):
            try:
                from discord_components import DiscordComponents
                self.ddb = DiscordComponents(self.dyphanbot, change_discord_methods=False)
            except ImportError:
                self.logger.warn("Experiment 'components' enabled, but 'discord_components' module not found.")

        self.controller = AudioController(dyphanbot, config=self.config, ddb=self.ddb)

    def _save_persistence(self):
        return self.save_json(self._persist_fn, self._persistence_data)
    
    def _save_config(self, filename, data):
        return self.dyphanbot.data.save_json(filename, data, indent=4)
    
    async def help(self, message, args):
        prefix = self.get_local_prefix(message)
        command = args[0] if args else 'audio'
        invocation = "{}{}".format(prefix, command)
        return {
            "helptext": HELP_TEXT,
            "shorthelp": "Plays audio in voice channels.",
            "sections": [{
                "name": "> {} join".format(invocation),
                "value": "Joins the voice channel the user is in.",
                "inline": False
            }, {
                "name": "> {} play `URL or search query`".format(invocation),
                "value": "Joins and plays a URL or searches YouTube. "
                         "Resumes a paused audio if called by itself.",
                "inline": False
            }, {
                "name": "> {} pause".format(invocation),
                "value": "Pauses the currently playing audio.",
                "inline": False
            }, {
                "name": "> {} stop".format(invocation),
                "value": "Stops playing audio and clears the playlist queue.",
                "inline": False
            }, {
                "name": "> {} repeat".format(invocation),
                "value": "Toggles repeat for the current or next song.",
                "inline": False
            }, {
                "name": "> {} volume `(+/-)1-100`".format(invocation),
                "value": ("Sets the volume. Can be either number from 1 to 100, "
                          "or a change preceeded by `+` or `-`.\n"
                          "Displays the current volume if called by itself.\n"
                          "e.g:\n"
                          "    `{0} volume 75` sets volume to *75%*\n"
                          "    `{0} volume +10` increases volume by *10%*\n"
                          "    `{0} volume -5` decreases volume by *5%*\n"
                          "    `{0} volume` displays current volume (*80%* after "
                          "running the previous commands)\n").format(invocation),
                "inline": False
            }, {
                "name": "> {} skip".format(invocation),
                "value": "Skips to the next queued audio source.",
                "inline": False
            }, {
                "name": "> {} status".format(invocation),
                "value": "Displays the currently playing/paused audio.",
                "inline": False
            }, {
                "name": "> {} queue".format(invocation),
                "value": "Lists the queued playlist.",
                "inline": False
            }, {
                "name": "> {} leave".format(invocation),
                "value": "Disconnects from the voice channel.",
                "inline": False
            }]

        }

    async def playonjoin(self, message, args):
        # Highly experimental, doesn't even work... might scrap
        if message.author.id not in self.dyphanbot.get_bot_masters():
            return
        
        guild_id = str(message.guild.id)
        query = " ".join(args).strip()
        if not query:
            return await message.channel.send("You haven't specified a query.")
        
        if not message.author.voice or not message.author.voice.channel:
            return await message.channel.send("You're not in a voice channel.")
        
        if guild_id not in self._persistence_data:
            self._persistence_data[guild_id] = {
                "playonjoin": {}
            }
        
        msg = await message.channel.send("Preparing requested source(s)...")
        try:
            ytdl_extractor = YTDLExtractor()
            info = await ytdl_extractor.process_entries(query)
            if isinstance(info, YTDLPlaylist) and not info.title:
                info.title = "*Untitled Playlist*"
            
            vchannel = message.author.voice.channel
            vch_id = str(vchannel.id)
            poj = self._persistence_data[guild_id]['playonjoin']
            if vch_id not in poj:
                poj[vch_id] = {}
            poj[vch_id]['query'] = query
            poj[vch_id]['text_channel'] = str(message.channel.id)
            self._persistence_data[guild_id]['playonjoin'] = poj
            self._save_persistence()

            await msg.edit(
                content="Play-on-join was successfully set for `{}`.".format(
                    vchannel.name),
                embed=discord.Embed(
                    title=info.title or "*Untitled*",
                    url=info.web_url if info.web_url and info.web_url.startswith("http") else discord.Embed.Empty
                ))
        except AudioExtractionError as err:
            self.logger.error(err.message)
            return await msg.edit(content=err.display_message)
        except ValueError:
            pass
        except Exception as e:
            await message.channel.send("Whoops! Something went wrong... ```py\n{}: {}\n```".format(type(e).__name__, e))
            raise
    
    @Plugin.event
    async def on_voice_state_update(self, member, before, after):
        # Highly experimental, doesn't even work... might scrap
        if member.id not in self.dyphanbot.get_bot_masters():
            return
        
        v_client = member.guild.voice_client
        if member != member.guild.me:
            try:
                vchannel = None
                guild_id = str(member.guild.id)
                poj = self._persistence_data[guild_id]['playonjoin']
                if after.channel != before.channel:
                    if after.channel and str(after.channel.id) in poj:
                        self.logger.info("PoJ Voice join: %s", str(member))
                        vchannel = after.channel

                        if v_client and v_client.is_connected():
                            # bot is busy now... we'll get em next time
                            return
                        
                        poj_channel = poj[str(vchannel.id)]
                        query = poj_channel['query']
                        text_channel = poj_channel['text_channel']

                        try:
                            await self.controller.join(vchannel.guild, vchannel, reconnect=False)
                            player = self.controller.get_player(self.dyphanbot, None, vchannel.guild)
                            after_playback = partial(self.controller.stab_player_to_death, vchannel.guild)
                            await player.prepare_entries(query, None,
                                silent=True,
                                requester=member,
                                custom_data={
                                    "after_playback": after_playback
                                }
                            )
                        except ConnectionClosed:
                            await self.controller.stab_player_to_death(vchannel.guild)
                    elif before.channel and str(before.channel.id) in poj:
                        self.logger.info("PoJ Voice leave: %s", str(member))
                        vchannel = before.channel
                        if not v_client or (v_client and not v_client.is_connected()):
                            return
                        if len(vchannel.members) > 1:
                            return
                        if v_client.channel == vchannel:
                            await v_client.disconnect(force=True)
                            # K I L L
                            await self.controller.stab_player_to_death(vchannel.guild)
                        return
            except KeyError:
                pass

    async def join(self, message, args):
        if not message.author.voice or not message.author.voice.channel:
            return await message.channel.send(
                "You're not in a voice channel... ~~dummy~~")
        
        return await self.controller.join(
            message.guild, message.author.voice.channel)

    async def play(self, message, args):
        query = " ".join(args)
        if len(args) <= 0 or query.strip() == "":
            resumed = await self.controller.resume(message.guild, message)
            if not resumed:
                await message.channel.send("Nothing was paused, bruh.")
            return
        
        if not message.author.voice or not message.author.voice.channel:
            return await message.channel.send(
                "You're not in a voice channel... ~~dummy~~")
        
        return await self.controller.play(
            message.guild, message.author.voice.channel, query, message)


    async def pause(self, message, args):
        paused = await self.controller.pause(message.guild, message)
        if paused is False:
            return await message.channel.send(
                "I wasn't even playing anything~~, baka~~!")
        if paused is None:
            return await message.channel.send("Already paused, bruh.")
        
        return paused

    async def stop(self, message, args):
        stopped = await self.controller.stop(message.guild, message)
        if not stopped:
            return await message.channel.send("I wasn't even playing anything!")
        
        return await message.channel.send("Stopped the playlist.")
    
    async def repeat(self, message, args):
        repeat_toggle = await self.controller.repeat(message.guild, message)
        if repeat_toggle is None:
            return await message.channel.send("I need to be in a voice channel...")
        
        return await message.channel.send(
            "**`{0}`**: Turned {1} repeat.".format(
                message.author,
                "ON" if repeat_toggle else "OFF"
            ))

    async def volume(self, message, args):
        current_volume = await self.controller.volume(message.guild, message=message)
        if current_volume is False:
            return await message.channel.send("I ain't in a voice chat, bruh..")
        if len(args) <= 0:
            return await message.channel.send(
                "Volume: **{0:.0f}%**\n"
                "Use `{1}{2} volume <amount>` where `<amount>` is either a "
                "number from 1 to 100 or an increment/decrement.\n"
                "To increase or decrease the volume by an amount, preceed the "
                "number with a `+` or `-` respectively.".format(
                    current_volume, self.get_local_prefix(message), "audio"
                ))
        
        volume_in: str = args[0].strip()
        delta = volume_in and (volume_in.startswith("+") or volume_in.startswith("-"))
        try:
            volume = int(volume_in)
            change_volume = await self.controller.volume(
                message.guild, volume, delta, message=message)
            if change_volume is False:
                return await message.channel.send(
                    "I ain't in a voice channel, bruh..")
            if change_volume is None:
                return await message.channel.send(
                    "Volume goes from 1 to 100...")
            
            return await message.channel.send(
                "**`{0}`**: Set the volume to **{1:.0f}%**".format(
                    message.author, change_volume))
        except ValueError:
            return await message.channel.send(
                "... What? Volume has to be set by a number from 1 to 100 or "
                "an increment/decrement with `+`/`-` respectively.")

    async def skip(self, message, args):
        skipped = await self.controller.skip(message.guild, message)
        if skipped is False:
            return await message.channel.send("I'm not even in a voice channel!")
        if skipped is None:
            return await message.channel.send("I wasn't playing anything!")
        
        return skipped

    async def status(self, message, args):
        status = await self.controller.status(message.guild, message)
        if status is False:
            return await message.channel.send(
                "I'm not even connected to a voice channel, dude!!")
        if status is None:
            return await message.channel.send("I'm not playing anything...")
        
        return status

    async def queue(self, message, args):
        status = await self.controller.status(message.guild)
        queue = await self.controller.queue(message.guild, message)
        if queue is False:
            return await message.channel.send(
                "I'm not even connected to a voice channel, dude!!")
        
        queue_str = ""
        if status:
            progress_str = utils.secs_to_hms(status.get_progress())
            duration_str = utils.secs_to_hms(status.duration) if status.duration else "?"
            queue_str += "{0} **{1}:**\n **`{2}`**{3}\n\n".format(
                "\u25B6\uFE0E" if status.is_playing else "\u23F8\uFE0E",
                status.np_str if status.np_str else "Now Playing",
                status.title,
                "\n[ {} / {} ]".format(progress_str, duration_str)
            )
        
        if queue['is_empty'] and not queue['next_source']:
            queue_str += "Playlist queue is empty..."
        elif queue['size'] <= 0 and not queue['next_source']:
            queue_str += "Playlist queue has no songs."
        else:
            queue_str += "**Next Up:**\n"
            queue_str += "» *`{0}`*\n".format(queue['next_source'].title) if queue['next_source'] else ""
            for entry in queue['entries']:
                queue_str += "• `{0}`\n".format(entry.title)
            if queue['next_count'] > 0:
                queue_str += "*+ {} more...*".format(queue['next_count'])
        
        return await message.channel.send(embed=discord.Embed(
            title="Queue",
            description=queue_str,
            colour=discord.Colour(0x7289DA)
        ))

    async def leave(self, message, args):
        leaving = await self.controller.leave(message.guild)
        if leaving is False:
            return await message.channel.send(
                "I'm not connected to a voice channel, bruh...")

    async def reset(self, message, args):
        await self.controller.reset(message.guild)
        return await message.channel.send("Reset player. Maybe it works now?")
    
    async def experiments(self, message, args):
        if str(message.author.id) not in self.dyphanbot.get_bot_masters():
            print("no permission!")
            return
        
        if len(args) <= 0:
            return # no need to say anything about this command...
        
        subcmd = args[0]
        experiments = args[1:]
        if subcmd == "enable":
            self.config["enabled_experiments"] = experiments
            await message.reply("Set enabled experiments to: {}".format(
                " ".join([f"`{x}`" for x in experiments])
            ))
        elif subcmd == "list":
            await message.reply("Enabled audio plugin experiments: {}".format(
                " ".join([f"`{x}`" for x in self.config.get("enabled_experiments", [])])
            ))
    
    @Plugin.event
    async def on_socket_response(self, res):
        if 'components' in self.config.get('enabled_experiments', []) and self.ddb:
            try:
                from discord_components import InteractionEventType
                if (res["t"] != "INTERACTION_CREATE") or (res["d"]["type"] != 3):
                    return

                ctx = self.ddb._get_context(res)
                for key, value in InteractionEventType.items():
                    if value == res["d"]["data"]["component_type"]:
                        self.dyphanbot.dispatch(key, ctx)
                        break
            except ImportError:
                pass

    @Plugin.event
    async def on_button_click(self, res):
        print("button clicked...")
        if 'components' in self.config.get('enabled_experiments', []):
            try:
                from discord_components import InteractionType
                author = res.guild.get_member(res.user.id) # res.author doesn't actually get this
                if res.component.id == "play-pause":
                    play_or_pause = "paused"
                    pausing = await self.controller.pause(res.guild, res.message)
                    if not pausing:
                        play_or_pause = "resumed"
                        await self.controller.resume(res.guild, res.message)
                    return await res.respond(
                        content=f"*{author.display_name}* {play_or_pause} playback.",
                        type=InteractionType.ChannelMessageWithSource,
                        flags=None)
                elif res.component.id == "stop":
                    stopping = await self.controller.stop(res.guild, res.message)
                    if stopping:
                        return await res.respond(
                            content=f"*{author.display_name}* stopped playback and cleared queue.",
                            type=InteractionType.ChannelMessageWithSource,
                            flags=None)
                elif res.component.id == "skip":
                    skipping = await self.controller.skip(res.guild, res.message)
                    if skipping:
                        return await res.respond(
                            content=f"*{author.display_name}* skipped this playback.",
                            type=InteractionType.ChannelMessageWithSource,
                            flags=None)
                elif res.component.id == "repeat":
                    repeat_toggle = await self.controller.repeat(res.guild, res.message)
                    if repeat_toggle is not None:
                        await self.controller.status(res.guild, res.message, res.channel)
                        return await res.respond(
                            content=f"*{author.display_name}* put it on repeat." if repeat_toggle else f"*{author.display_name}* turned off repeat.",
                            type=InteractionType.ChannelMessageWithSource,
                            flags=None)
            except ImportError:
                pass

    @Plugin.command
    async def audio(self, client, message, args, _cmd='audio'):
        """ The Voice command.
        Handles subcommands for playing and controlling audio.
        """
        sub_cmds = ['join', 'play', 'fplay', 'pause', 'stop', 'repeat',
                    'volume', 'skip', 'status', 'queue', 'leave', 'reset']

        if len(args) > 0:
            scmd = args[0].strip()
            if scmd in sub_cmds:
                if not hasattr(self, scmd):
                    return await message.channel.send("Not implemented yet...")
                await getattr(self, scmd)(message, args[1:])
            elif scmd == 'playonjoin':
                await self.playonjoin(message,args[1:])
            elif scmd == 'experiments':
                await self.experiments(message, args[1:])
            elif scmd == 'help':
                await self.dyphanbot.bot_controller.help(message, [_cmd])
            else:
                await message.channel.send("lol wut?")
        else:
            await message.channel.send("La la la!!")
    
    @Plugin.command
    async def voice(self, client, message, args):
        return await self.audio(client, message, args, _cmd='voice')
    
    @Plugin.command(cmd='music')
    async def music_cmd(self, client, message, args):
        return await self.audio(client, message, args, _cmd='music')
    
    @Plugin.command(cmd='m')
    async def m_cmd(self, client, message, args):
        return await self.audio(client, message, args, _cmd='m')
Ejemplo n.º 24
0
 async def on_ready(self):
     DiscordComponents(self.bot)
Ejemplo n.º 25
0
 def __init__(self, bot):
     self.bot = bot
     DiscordComponents(bot)
Ejemplo n.º 26
0
import discord

sys.path.insert(1, (os.path.dirname(os.path.dirname(__file__))))
from functools import reduce
from discord.ext import commands
from src import tkfinder, util
from src.resources import embed, const
from github import Github
from discord_components import DiscordComponents

base_path = os.path.dirname(__file__)
config = configurator.Configurator(os.path.abspath(os.path.join(base_path, "resources", "config.json")))
prefix = '§'
description = 'The premier Tekken 7 Frame bot, made by Baikonur#4927, continued by Tib#1303'
bot = commands.Bot(command_prefix=prefix, description=description)
buttons = DiscordComponents(bot)

# Set logger to log errors
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)

logfile_directory = os.path.abspath(os.path.join(base_path, "..", "log"))
logfile_path = logfile_directory + "\\logfile.log"

# Create logfile if not exists
if not os.path.exists(logfile_directory):
    os.makedirs(logfile_directory)

if not os.path.isfile(logfile_path):
    open(logfile_path, "w")
Ejemplo n.º 27
0
def main():
    """the main method"""

    # Initialize logging
    init_logging()

    # Initialize the client
    print("Starting up...")
    client = Bot('!', intents=intents)

    #start webserver
    webserver_thread = threading.Thread(target=run_server,
                                        args=(aiohttp_server(client), ))
    webserver_thread.start()

    # enable slash commands and send them to the discord API
    SlashCommand(client, sync_commands=True)

    # enable buttons
    DiscordComponents(client)

    # load slash command cogs
    # to do that, loop through the files and import all classes and commands
    print("Loading commands...")
    slash_dir = "slash_commands"
    for file in os.listdir(slash_dir):
        if file.endswith(".py"):
            file = file.removesuffix(".py")
            extension = f"{slash_dir}.{file}"
            client.load_extension(extension)

    # pylint: disable=no-member
    print(f"{len(client.slash.commands)} commands loaded")

    # Define event handlers for the client
    # on_ready may be called multiple times in the event of a reconnect,
    @client.event
    async def on_ready():
        if this.running:
            return
        this.running = True
        print("Logged in")

        # run further launch event loops
        await launch_event_loops(client)

    # The message handler for both new message and edits
    @client.event
    async def common_handle_message(message):
        text = message.content

        # if the message was from an dm, post it in #admin-discussions: Don't do that if bot send an command
        if isinstance(message.channel, discord.channel.DMChannel):
            if not message.author.bot:
                if not text.startswith(COMMAND_PREFIX):
                    admin_discussions_channel = client.get_channel(
                        admin_discussions_channel_id)
                    if message.attachments:
                        attached_files = [
                            discord.File(BytesIO(await attachment.read()),
                                         filename=attachment.filename)
                            for attachment in message.attachments
                        ]
                        await admin_discussions_channel.send(
                            f"From {message.author.mention}: \n{text}",
                            files=attached_files)
                    else:
                        await admin_discussions_channel.send(
                            f"From {message.author.mention}: \n{text}")
                    await message.author.send(
                        "Forwarded your message to staff, you will be contacted shortly 🙃"
                    )

        if 'äbidöpfel' in text:
            texts = [
                '<:NeriaHeart:671389916277506063> <:NeriaHeart:671389916277506063> <:NeriaHeart:671389916277506063>',
                'knows what`s up', 'knows you can do the thing',
                'has been voted plushie of the month', 'knows da wey', 'yes!',
                'does`nt yeet teammtes of the map, be like Häbidöpfel',
                'debuggin has proven effective 99.9% of the time (editors note: now 98.9%)',
                'is cuteness incarnate'
            ]
            addition = random.choice(texts)
            await message.channel.send(f'Häbidöpfel {addition}')

        if "welcome" in text.lower() and message.mentions:
            for mention in message.mentions:
                neria_id = 109022023979667456
                if mention.id == neria_id:
                    welcome_choice = [
                        "Welcome",
                        "I mirëpritur",
                        "Dobrodošli",
                        "Vitejte",
                        "Welkom",
                        "Tere tulemast",
                        "Tervetuloa",
                        "Bienvenue",
                        "Herzlich willkommen",
                        "Üdvözöljük",
                        "Velkominn",
                        "Fáilte",
                        "Benvenuta",
                        "Velkommen",
                        "Witamy",
                        "Bine ați venit (this is spelled correctly thanks to <@171371726444167168>)",
                        "Bienvenidas",
                        "Välkommen",
                        "Croeso",
                        "Yeeeeeeeeeeeeeeeeeeeeeeeeeeeeehaw",
                    ]
                    await message.channel.send(
                        f'{random.choice(welcome_choice)} <@{neria_id}>!')

        if client.user in message.mentions:  # If bot has been tagged
            notification = client.get_emoji(
                751771924866269214)  # notification/angerping
            # sentimentPositive = client.get_emoji(670369126983794700) #POGGERS
            # sentimentNegative = client.get_emoji(670672093263822877) #SadChamp
            await message.add_reaction(notification)

        # mute pepe for an hour if he trashes destiny
        if message.author.id == 367385031569702912420:
            if "destiny" in text.lower():
                for insult in ["suck", "bad", "f**k", "shit", "trash"]:
                    if insult in text.lower():
                        # mute pepe and msg him about it
                        await assignRolesToUser([muted_role_id],
                                                message.author, message.guild)
                        await message.author.send(
                            "Stop trashing on destiny, muted for an hour :)")
                        nick = message.author.nick
                        await message.author.edit(
                            nick="!Pepe the Muted for an Hour")

                        # remove muted role after an hour
                        await asyncio.sleep(60 * 60)
                        await removeRolesFromUser([muted_role_id],
                                                  message.author,
                                                  message.guild)
                        await message.author.edit(nick=nick)
                        await message.author.send("Unmuted again :(")
                        return

        # run the command if starts with !
        if text.startswith(COMMAND_PREFIX) and text != COMMAND_PREFIX:
            cmd_split = text[len(COMMAND_PREFIX):].split()
            try:
                await message_handler.handle_command(cmd_split[0].lower(),
                                                     cmd_split[1:], message,
                                                     client)
            except:
                print("Error while handling message", flush=True)
                raise
        else:
            badwords = [
                'kanen', 'cyber', 'dicknugget', 'nigg', 'cmonbrug', ' bo ',
                'bloodoak', 'ascend', 'c**k', 'c**t'
            ]
            goodchannels = [
                670400011519000616,  # general
                670400027155365929,  # media
                670402166103474190,  # spoiler-chat
                670362162660900895,  # off-topic
                # 672541982157045791 #markov-chat-channel
            ]
            if not message.content.startswith('http') and len(
                    message.clean_content) > 5 and not any([
                        badword in message.clean_content.lower()
                        for badword in badwords
                    ]) and message.channel.id in goodchannels:
                await insertIntoMessageDB(message.clean_content,
                                          message.author.id,
                                          message.channel.id, message.id)

        if message.author.name == 'EscalatorBot':
            for user in message.mentions:
                member = await message.guild.fetch_member(user.id)
                await member.add_roles(
                    message.guild.get_role(registered_role_id)
                )  # registered role
                await member.remove_roles(
                    message.guild.get_role(not_registered_role_id)
                )  # unregistered role
                await message.channel.send(
                    f'{member.mention} has been marked as Registered')
                await member.send(
                    'Registration successful!\nCome say hi in <#670400011519000616>'
                )

                # update user DB
                destinyID = await lookupDestinyID(member.id)
                await updateDB(destinyID)

    @client.event
    async def on_message(message):
        # ignore msg from itself
        if (message.author == client.user):
            return
        asyncio.ensure_future(common_handle_message(message))

    @client.event
    async def on_member_join(member):
        # inform the user that they should register with the bot
        await member.send(embed=embed_message(
            f'Welcome to Descend {member.name}!',
            'You can join the destiny clan in **#registration**. \nYou can find our current requirements in the same channel. \n⁣\nWe have a wide variety of roles you can earn, for more information, check out #community-roles. \n⁣\nIf you have any problems / questions, do not hesitate to write **@ElevatorBot** (me) a personal message with your problem / question'
        ))

    @client.event
    async def on_member_remove(member):
        await removeFromClanAfterLeftDiscord(client, member)

    @client.event
    async def on_message_edit(before, after):
        await common_handle_message(after)

    # https://discordpy.readthedocs.io/en/latest/api.html#discord.RawReactionActionEvent
    @client.event
    async def on_raw_reaction_add(payload):
        if not payload.member or payload.member.bot:
            return

        # check if reaction is on a persistent message
        await check_reaction_for_persistent_message(client, payload)

    @client.event
    async def on_voice_state_update(member, before, after):
        guild = member.guild
        lfg_voice_category_channel = await get_persistent_message_or_channel(
            client, "lfgVoiceCategory", guild.id)

        if before.channel is None:
            # print(f'{member.name} joined VC {after.channel.name}')
            await joined_channel(client, member, after.channel)
            return

        if after.channel is None:
            # print(f'{member.name} left VC {before.channel.name}')
            await left_channel(client, member, before.channel, after.channel,
                               lfg_voice_category_channel)
            return

        if before.channel != after.channel:
            # print(f'{member.name} changed VC from {before.channel.name} to {after.channel.name}')
            await joined_channel(client, member, after.channel)
            await left_channel(client, member, before.channel, after.channel,
                               lfg_voice_category_channel)
            return

    @client.event
    async def on_member_update(before, after):
        """ Add member role after Role Screening """

        if before.bot or after.bot:
            return
        if before.pending and not after.pending:
            member = client.get_guild(before.guild.id).get_member(before.id)

            # add @member
            await assignRolesToUser([member_role_id], member, member.guild)

            # add @Not Registered to user
            await assignRolesToUser([not_registered_role_id], member,
                                    member.guild)

            # add filler roles
            await assignRolesToUser([divider_raider_role_id], member,
                                    member.guild)
            await assignRolesToUser([divider_achievement_role_id], member,
                                    member.guild)
            await assignRolesToUser([divider_misc_role_id], member,
                                    member.guild)

    @client.event
    async def on_slash_command(ctx: SlashContext):
        """ Gets triggered every slash command """

        # print the command
        print(
            f"{ctx.author.display_name} used '/{ctx.name}' with kwargs '{ctx.kwargs}'"
        )

        # log the command
        logger = logging.getLogger('slash_commands')
        logger.info(
            f"InteractionID '{ctx.interaction_id}' - User '{ctx.author.name}' with discordID '{ctx.author.id}' executed '/{ctx.name}' with kwargs '{ctx.kwargs}' in guildID '{ctx.guild.id}', channelID '{ctx.channel.id}'"
        )

    @client.event
    async def on_slash_command_error(ctx: SlashContext, error: Exception):
        """ Gets triggered on slash errors """

        await ctx.send(embed=embed_message(
            "Error",
            f"Sorry, something went wrong \nPlease contact a {ctx.guild.get_role(dev_role_id)}",
            error))

        # log the error
        logger = logging.getLogger('slash_commands')
        logger.exception(
            f"InteractionID '{ctx.interaction_id}' - Error {error} - Traceback: \n{''.join(traceback.format_tb(error.__traceback__))}"
        )

        # raising error again to making deving easier
        raise error

    @client.event
    async def on_button_click(interaction: discord_components.Context):
        # look if they are lfg buttons
        if interaction.component.id.startswith("lfg"):
            # get the lfg message
            lfg_message = await get_lfg_message(
                client=interaction.bot,
                lfg_message_id=interaction.message.id,
                guild=interaction.guild)

            if interaction.component.label == "Join":
                res = await lfg_message.add_member(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be added to the event\nThis is either because you are already in the event, the event is full, or the creator has blacklisted you from their events"
                        ))

            if interaction.component.label == "Leave":
                res = await lfg_message.remove_member(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be removed from the event\nThis is because you are neither in the main nor in the backup roster"
                        ))

            if interaction.component.label == "Backup":
                res = await lfg_message.add_backup(
                    member=interaction.guild.get_member(interaction.author.id))
                if res:
                    await interaction.respond(type=6)
                else:
                    await interaction.respond(
                        type=discord_components.InteractionType.
                        ChannelMessageWithSource,
                        embed=embed_message(
                            "Error",
                            "You could not be added as a backup to the event\nThis is either because you are already in the backup roster, or the creator has blacklisted you from their events"
                        ))

    # Finally, set the bot running
    client.run(BOT_TOKEN)