Example #1
0
    def get_urls_list():
        '''
        Controls the buffer to reduce number of youtubeAPI calls (max 1 per day).
        Uses the database to save content of day, if day expires, makes api call
        to update list.

        Args:
            - None.
        Returns:
            - url_list (list of str): List of URLs.
        '''

        logger = DockerLogger(prefix='BufferYouTubeAPI', lvl=DockerLogger.INFO)

        now = datetime.now()
        date_now = now.strftime("%Y-%m-%d")

        bot_confs = dbBotConfig()
        contents = bot_confs.yt_yaml

        if contents is None:
            logger.log(lvl=logger.INFO,
                       msg="Content of buffer is None, making API Call")
            videos_lst = YoutubeHelper._make_api_call()
            contents = {date_now: videos_lst}
            bot_confs.update_yt_yaml(contents)
            return videos_lst

        date_time_obj = None

        # Only has 1 key, but we use for anyway
        for key in contents.keys():
            date_time_obj = datetime.strptime(key, '%Y-%m-%d')

        videos_lst = list(contents.values())[0]

        if (now - date_time_obj).days > 1:
            logger.log(lvl=logger.INFO, msg="Buffer Expired, making API Call")

            new_videos_lst = YoutubeHelper._make_api_call()
            new_videos_lst = list(set(videos_lst + new_videos_lst))

            new_contents = {date_now: new_videos_lst}
            bot_confs.update_yt_yaml(new_contents)

            return new_videos_lst

        logger.log(lvl=logger.INFO, msg="Using buffer")
        return videos_lst
Example #2
0
import os
import discord

from discord.ext import commands
from sqlalchemy.ext.declarative import declarative_base

from utils.utls import get_prefix
from utils.docker import DockerLogger

logger = DockerLogger(prefix='BOT_RUNNER', lvl=DockerLogger.INFO)

logger.log('Initializing bot', lvl=DockerLogger.INFO)

Base = declarative_base()

cogs = [
    filename for filename in os.listdir('./cogs') if filename[-3::] == '.py'
]

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix=get_prefix, intents=intents)

client.remove_command('help')

if __name__ == '__main__':

    for filename in cogs:
        client.load_extension(f'cogs.{filename[:-3]}')
Example #3
0
    def __init__(self, guild_id):
        self.logger = DockerLogger(prefix='dbManager', lvl=DockerLogger.INFO)

        self.log_handler = logging.FileHandler('./logs/sqlalchemy.log',
                                               mode='a+')
        # self.log_handler.setLevel(logging.INFO)
        self.db_logger = logging.getLogger('sqlalchemy')
        self.db_logger.addHandler(self.log_handler)
        # self.db_logger.setLevel(logging.INFO)

        self.guild_id = str(guild_id)

        db_user = os.environ.get('POSTGRES_USER')
        db_pass = os.environ.get('POSTGRES_PASSWORD')

        host = os.environ.get('DB_HOST')
        db_host = host if host is not None else 'db'

        db_name = os.environ.get('POSTGRES_DB')
        db_port = os.environ.get('POSTGRES_PORT')

        # If debug mode, creates local sqlite database
        if int(os.environ.get('DEBUG')):

            self.log_handler.setLevel(logging.INFO)
            self.db_logger.setLevel(logging.INFO)

            self.engine = create_engine(
                'sqlite:////devdb/sqlite.db?check_same_thread=False',
                echo=True)
            self.logger.log(
                "Connected to SQLITE DB (Do NOT use in production)",
                lvl=self.logger.WARNING)

        else:
            # Raises an error if any of the needed env vars were not declared
            if any(not var for var in [db_user, db_pass, db_name, db_port]):
                self.logger.log(f"""Missing ENV VARS:
                    POSTGRES_USER: '******',
                    POSTGRES_PASSWORD: '******',
                    POSTGRES_DB: '{db_name}',
                    DB_HOST: '{db_host}',
                    POSTGRES_PORT: '{db_port}'
                    """,
                                lvl=self.logger.ERROR)
                raise NameError(f"""Missing ENV VARS:
                        POSTGRES_USER: '******',
                        POSTGRES_PASSWORD: '******',
                        POSTGRES_DB: '{db_name}',
                        DB_HOST: '{db_host}',
                        POSTGRES_PORT: '{db_port}'
                        """)

            self.log_handler.setLevel(logging.WARNING)
            self.db_logger.setLevel(logging.WARNING)

            self.engine = create_engine(
                f'postgresql+psycopg2://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}',
                echo=False)

        Base.metadata.create_all(bind=self.engine)
        self.session = sessionmaker(bind=self.engine)
Example #4
0
 def __init__(self, client):
     self.client = client
     self.logger = DockerLogger(lvl=DockerLogger.INFO, prefix='TiozaoZap')
Example #5
0
class TiozaoZap(commands.Cog):
    '''
    TiozaoZap Cogs
    '''
    def __init__(self, client):
        self.client = client
        self.logger = DockerLogger(lvl=DockerLogger.INFO, prefix='TiozaoZap')

    async def _play_from_url(self, ctx, video_url, send_message=False):
        '''
        Plays the zap audio.
        '''

        voice_client = discord.utils.get(self.client.voice_clients,
                                         guild=ctx.guild)

        async with ctx.typing():
            player = await YTDLSource.from_url(video_url,
                                               loop=self.client.loop)
            voice_client.play(player,
                              after=lambda e: print(f'Player error: %{e}')
                              if e else None)

        if send_message:
            await ctx.message.channel.send(
                f'Se liga nesse audio... {player.title}')

    @commands.Cog.listener()
    @commands.guild_only()
    async def on_message(self, message):
        '''
        When any member sends a message inside a guild text-channel.
        '''
        # Cancels the request if the sender was a bot.
        if message.author.bot:
            return

        # bozo xingo
        if any(word in message.content.lower()
               for word in constants.BOZO_XINGO_TRIGGERS):
            choice(constants.RESPOSTA_XINGO)
            await message.channel.send(choice(constants.RESPOSTA_XINGO))

    @commands.command(name='audio_do_zap',
                      aliases=['zap', 'audio', 'audio_zap'])
    @decorators.in_voice_chat_only
    @commands.guild_only()
    async def audio_do_zap(self, ctx):
        '''
        Plays a video of selection 'audios do zap' to the users channel.
        '''

        voice_channel = ctx.message.author.voice.channel

        # Só tenta conectar se não está conectado, depois reseta
        voice_client = discord.utils.get(self.client.voice_clients,
                                         guild=ctx.guild)
        if not voice_client:
            await voice_channel.connect()
            voice_client = discord.utils.get(self.client.voice_clients,
                                             guild=ctx.guild)

        await self._play_from_url(ctx,
                                  video_url=choice(
                                      YoutubeHelper.get_urls_list()),
                                  send_message=True)

        self.logger.log(
            f'{ctx.guild.id} - {ctx.message.author.id} requested ZAP_AUDIO',
            lvl=self.logger.INFO)

        # Disconnects after 5 seconds of audio ending
        while voice_client.is_playing():
            await sleep(5)

        await voice_client.disconnect()

    @commands.command(name='sus_sound_effect', aliases=['sus'])
    @decorators.in_voice_chat_only
    @commands.guild_only()
    async def play_sus_sound(self, ctx):
        '''
        Plays the "sus" sound effect from amongus.
        '''

        voice_channel = ctx.message.author.voice.channel

        # Só tenta conectar se não está conectado, depois reseta
        voice_client = discord.utils.get(self.client.voice_clients,
                                         guild=ctx.guild)
        if not voice_client:
            await voice_channel.connect()
            voice_client = discord.utils.get(self.client.voice_clients,
                                             guild=ctx.guild)

        await self._play_from_url(ctx,
                                  video_url=constants.SUS_VIDEO_URL,
                                  send_message=False)

        self.logger.log(
            f'{ctx.guild.id} - {ctx.message.author.id} requested ZAP_AUDIO',
            lvl=self.logger.INFO)

        # Disconnects after 5 seconds of audio ending
        while voice_client.is_playing():
            await sleep(5)

        await voice_client.disconnect()
Example #6
0
 def __init__(self, client):
     self.client = client
     self.logger = DockerLogger(lvl=DockerLogger.INFO, prefix='AutoRole')
Example #7
0
class AutoModerator(commands.Cog):
    '''
    AutoModerator Cogs
    '''

    def __init__(self, client):
        self.client = client
        self.logger = DockerLogger(lvl=DockerLogger.INFO, prefix='AutoModerator')

    @commands.Cog.listener()
    async def on_ready(self):
        '''
        Used mainly for logging and a greet for the guilds
        '''

        usr_num = 0
        for guild in self.client.guilds:
            usr_num += len(guild.members)

        self.logger.log(
            msg=f'Logged-in on {len(self.client.guilds)} servers, at the reach of {usr_num} users',
            lvl=self.logger.INFO)

        await self.client.change_presence(activity=discord.Game(name='Truco com o Wanderley'))

    @commands.command(name='ping', aliases=["ping server"])
    async def ping(self, ctx):
        '''
        Pings the bot server.
        '''
        await ctx.channel.send(f"Latency: `{round(self.client.latency * 1000)}ms`")

    @commands.command(name='ajuda', aliases=['ajuda noix'])
    async def ajuda(self, ctx, our_input=None):
        '''
        Custom made help command. Pulls configs from extras/commands.yml
        '''
        await ctx.channel.send(MessageFormater.ajuda(our_input))

    @commands.command(name='desenvolvimento', aliases=[
        'dev', 'development', 'git', 'info', 'status', '-v', '--version'])
    async def desenvolvimento(self, ctx):
        '''
        Replies with an embed about the current state of development.
        '''
        await ctx.channel.send(embed=MessageFormater.development())

        msg = ""
        msg += "O Projeto deste bot é completamente open-source! "
        msg += "Sinta-se a vontade para dar uma olhada no código, pedir novas features, "
        msg += "reportar bugs, ou até colaborar. Sua opinião é sempre bem-vinda!"

        await ctx.channel.send(msg)

    @commands.command(name='set_cursed_words', aliases=[
        'set_cursed_word', 'add_cursed_words', 'add_cursed_word',
    ])
    @commands.guild_only()
    @admin_only
    async def set_cursed_words(self, ctx, our_input):
        '''
        Sets the cursed words.
        '''

        words = our_input.split(',')

        mod = dbAutoMod(ctx.guild.id)
        mod.add_cursed_words(words)

        self.logger.log(
            f'{ctx.guild.id} - {ctx.message.author.id} added cursed word(s): {our_input}',
            lvl=self.logger.INFO)
        await ctx.message.channel.send(choice(constants.POSITIVE_RESPONSES))

    @commands.command(name='list_cursed_words', aliases=[
        'list_curse_words', 'ls_curse_words', 'ls_cursed_words'
    ])
    @commands.guild_only()
    async def list_cursed_words(self, ctx):
        '''
        Lists all cursed words from guild.
        '''

        mod = dbAutoMod(ctx.guild.id)

        if (cursed_words_buffer := mod.cursed_words) is not None:
            for word in cursed_words_buffer:
                await ctx.message.channel.send(word)