Ejemplo n.º 1
0
 async def crypto(self, ctx: SlashContext, money_code: str = 'USD'):
     limit = 8
     api_key_coinmarket = os.environ.get('API_KEY_COINMARKET')
     url_usd = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/' \
               f'listings/latest?start=1&limit={limit}&convert={money_code}&CMC_PRO_API_KEY={api_key_coinmarket}'
     req = requests.get(url_usd)
     req_json = req.json()
     embed = discord.Embed(
         title="Стоимости криптовалют",
         description=
         "Стоимость криптовалют на данный момент по данным биржи coinmarketcap.",
         color=0xd5de21)
     for i in req_json['data']:
         price = str(i['quote'][money_code]['price'])
         embed.add_field(name=i['name'], value=price, inline=True)
         embed.add_field(
             name='Изменения за Сутки',
             value="[{}]".format(
                 round(((int(float(price)) / 100) * int(
                     float(i['quote'][money_code]['percent_change_24h']))),
                       1)),
             inline=True)
         embed.add_field(
             name='Неделю',
             value="[{}]".format(
                 round(((int(float(price)) / 100) * int(
                     float(i['quote'][money_code]['percent_change_7d']))),
                       1)),
             inline=True)
     await ctx.send(embed=embed)
     logger.comm('crypto_price')
Ejemplo n.º 2
0
 async def set_status(self, ctx: SlashContext, text: str):
     try:
         db.update_setting('streaming_status_text', text)
         await ctx.send(embed=re.done(f'Статус [{text}] был установлен!'))
     except Exception as e:
         await ctx.send(embed=re.error(e))
     logger.comm(f'[Status Change] {ctx.author} {text}')
Ejemplo n.º 3
0
 async def change_rainbow(self, ctx: SlashContext, state: bool):
     rainbow_role_name = db.get_setting('role_rainbow')
     rainbow_role_status = db.get_setting('role_rainbow_status',
                                          boolean=True)
     role = discord.utils.get(ctx.guild.roles, name=rainbow_role_name)
     if role is not None:
         if state and not rainbow_role_status:
             db.update_setting('role_rainbow_status', True)
             await ctx.send(embed=re.done('Модуль ``RAINBOW`` Включен!'))
             logger.comm(f'[RAINBOW] Turn On! Guild: {ctx.guild.name}')
         elif not state and rainbow_role_status:
             db.update_setting('role_rainbow_status', False)
             await ctx.send(embed=re.done('Модуль ``RAINBOW`` Выключен!'))
             logger.comm(f'[RAINBOW] Turn Off! Guild: {ctx.guild.name}')
     else:
         try:
             await discord.Guild.create_role(
                 ctx.guild,
                 name='Rainbow',
                 hoist=True,
                 reason='SERVO-BOT Автоматическое добавление роли!')
             await ctx.send(embed=re.embed(
                 '``RAINBOW``',
                 'Т.к. роль не была найдена, она была добавлена автоматически!\n'
                 'Пожалуйста добавте эту роль, тем кому вы хотите сделать '
                 'радужный никнейм :3'))
         except discord.Forbidden:
             await ctx.send(embed=re.warn(
                 'Прав не завезли!\n'
                 'Добавте боту права "manage_roles" или сами создайте роль '
                 f'``{rainbow_role_name}``'))
Ejemplo n.º 4
0
 async def coub(self, ctx: SlashContext, url_to_coub: str):
     url = "http://coub.com//api/v2/coubs" + url_to_coub[21:]
     r = requests.get(url)
     coub_data = r.json()
     views = coub_data["views_count"]
     title = coub_data["title"]
     url_to_ass = "https://coubassistant.com/en/web"
     payload = f"-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"urlpost\"\r\n\r\n{url_to_coub}\r\n-----011000010111000001101001--\r\n"
     headers = {
         'content-type':
         'multipart/form-data; boundary=---011000010111000001101001'
     }
     response = requests.request("POST",
                                 url_to_ass,
                                 data=payload,
                                 headers=headers)
     result = BeautifulSoup(response.text, 'html.parser')
     song = coub_data["file_versions"]["html5"]['audio']['high']
     song_name = result.findAll('h3')[0].getText()
     if song_name == 'Easy way to search for music':
         song_name = 'Музыка не найдена!'
     try:
         link = coub_data["file_versions"]["share"]["default"]
     except Exception as e:
         await ctx.send(
             embed=re.warn('Что-то пошло не так, проверьте ссылку'))
         return
     await ctx.send(
         f'Название: ``{title}``\nПросмотров: ``{views}``\nМузыка из Куба: ``{song_name}``\nСсылка: {link} '
         f'\nАудио: {song["url"]}   {round(song["size"] / 1048576, 2)}mB')
     logger.comm(f'COUB. Author: {ctx.message.author}')
Ejemplo n.º 5
0
 async def bash(self, ctx: SlashContext):
     from bs4 import BeautifulSoup
     url = 'https://bash.im/random'
     rs = requests.get(url)
     root = BeautifulSoup(rs.text, 'html.parser')
     mydivs = root.find("div", {"class": "quote__body"})
     quote = mydivs.getText('\n', strip=True)
     await ctx.send(embed=re.done('Рандомная цитата с Bash.im\n' +
                                  str(quote)))
     logger.comm(f'BASH. Author: {ctx.author}')
Ejemplo n.º 6
0
    async def execute(self, ctx: SlashContext, code: str):
        code = code.replace("```", "")
        out, is_error = self._exec(code.strip().rstrip(), globals(), locals())

        if is_error:
            await ctx.send(embed=re.error(out))
            logger.error(
                f'Unsuccessful attempt to execute code. Author: {ctx.author}\n{out}'
            )
        else:
            await ctx.send(embed=re.done('Код успешно выполнен!\n' + out))
            logger.comm(f'EXECUTE. Author: {ctx.author}')
Ejemplo n.º 7
0
    async def clear(self, ctx: SlashContext, num_mes: int,
                    *user: discord.User):
        chan = ctx.channel
        if not user:
            deleted = await chan.purge(limit=num_mes)
        elif user[0]:

            def check(msg):
                return msg.author == user[0]

            deleted = await chan.purge(limit=num_mes, check=check)
        await ctx.send(embed=re.done(f'Удалено {len(deleted)} сообщений.'))
        logger.comm(f'CLEAR. Author: {ctx.author}')
Ejemplo n.º 8
0
async def reload(ctx: SlashContext, module):
    if str(module) == 'all':
        count = 0
        module_list = []
        for file in os.listdir('modules'):
            if file.endswith('.py'):
                module_list.append(file[:-3] + '\n')
                bot.unload_extension(f'modules.{file[:-3]}')
                bot.load_extension(f'modules.{file[:-3]}')
                logger.log(f'Reload Module: {file}')
                count += 1
        module_list_text = ''
        for mod in module_list:
            module_list_text = module_list_text + mod
        await ctx.send(embed=re.done(
            f'Всего модулей перезагружено: {count}\n{module_list_text}'))
        logger.comm(f'RELOAD module: [{module}]. Author: {ctx.author}')
    else:
        bot.unload_extension(f'modules.{module}')
        bot.load_extension(f'modules.{module}')
        await ctx.send(embed=re.done(f'Модуль [{module}] перезагружен'))
        # TODO Доделать импорты из Utilities
        logger.comm(f'RELOAD module: [{module}]. Author: {ctx.author}')