Exemplo n.º 1
0
    async def altcorp(self, ctx):
        """
        Gets Auth data about an altcorp
        Input: a Eve Character Name
        """

        input_name = ctx.message.content[9:]
        chars = EveCharacter.objects.filter(corporation_name=input_name)
        own_ids = [settings.DISCORD_BOT_MEMBER_ALLIANCES]
        alts_in_corp = []
        for c in chars:
            if c.alliance_id not in own_ids:
                alts_in_corp.append(c)

        mains = {}
        for a in alts_in_corp:
            try:
                main = a.character_ownership.user.profile.main_character
                if main.character_id not in mains:
                    mains[main.character_id] = [main, 0]
                mains[main.character_id][1] += 1
                alt_corp_id = a.corporation_id
            except Exception as e:
                logger.error(e)
                pass
        output = []
        base_string = "[{}]({}) [ [{}]({}) ] has {} alt{}"
        for k, m in mains.items():
            output.append(
                base_string.format(m[0],
                                   evewho.character_url(m[0].character_id),
                                   m[0].corporation_ticker,
                                   evewho.corporation_url(m[0].corporation_id),
                                   m[1], "s" if m[1] > 1 else ""))

        for strings in [output[i:i + 10] for i in range(0, len(output), 10)]:
            embed = Embed(title=input_name)
            embed.colour = Color.blue()
            embed.description = "\n".join(strings)
            await ctx.send(embed=embed)
Exemplo n.º 2
0
    async def on_commons_division(self, division: CommonsDivision, bill: Bill):
        channel = self._guild.get_channel(
            int(self.config.get_channel_id("commons_divisions"))
        )
        if channel is None:
            return
        division_file = await self.generate_division_image(self.parliament, division)
        embed = Embed(
            color=discord.Colour.from_rgb(84, 174, 51), timestamp=datetime.now()
        )
        did_pass = division.get_aye_count() > division.get_no_count()
        embed.title = f"**{division.get_division_title()}**"
        next_line = "\n"
        description = (
            f"**Division Result:** {'Passed' if did_pass else 'Not passed'} by a division of"
            f" {division.get_aye_count() if did_pass else division.get_no_count()} {'Ayes' if did_pass else 'Noes'}"
            f" to {division.get_no_count() if did_pass else division.get_aye_count()} "
            f"{'Noes' if did_pass else 'Ayes'}{next_line}**Division Date:** "
            f"{division.get_division_date().strftime('%Y-%m-%d %H:%M:%S')}"
        )

        if bill is not None:
            description += (
                f"{next_line}**Bill Summary [(Link)](https://bills.parliament.uk/"
                f"bills/{bill.get_bill_id()})**: {bill.get_long_title()}"
            )

        embed.description = description
        embed.set_image(url="attachment://divisionimage.png")
        self.tracker_status["commonsdivisions"]["confirmed"] = True
        await channel.send(
            file=division_file,
            embed=embed,
        )
Exemplo n.º 3
0
    async def get_user_choice(cls, ctx: Context, search_query: str, entries: List[Tuple[str]]) -> int:

        em = Embed(colour=cls._embed_colour,)
        em.set_author(name=f'{cls._track_type} search results - {search_query} - Requested by {ctx.author}')

        for index, entry in enumerate(entries, 1):
            em.add_field(
                name=f'{index} - {entry[0]}', value=entry[1], inline=False)

        search_message = await ctx.send(embed=em)
        ensure_future(add_numeric_reactions(search_message, len(entries)))

        def check(react: Reaction, user: User):
            return any((
                    react.message.id == search_message.id,
                    user == ctx.author,
                    react.emoji in (numeric_emoji(n) for n in range(1, 1+len(entries)))
            ))

        try:
            reaction, _ = await ctx.bot.wait_for('reaction_add', check=check, timeout=60)

        except TimeoutError:
            raise BadArgument("You did not choose a search result in time.")

        await search_message.delete()
        return int(reaction.emoji[0]) - 1
Exemplo n.º 4
0
async def form(message, params, **options):
    values = " ".join(params).strip()
    values = values.split(FORM_SEPARATOR)

    if len(values) > 10:
        return log((["b", "w"], "too many arguments"))

    title = values[0]
    form_options = [option for option in values[1:] if option]

    if not title:
        return log((["b", "w"], "not enough arguments"))

    embed_message = Embed()
    embed_message.description = f"📊 **{title}**\n\n"
    embed_message.colour = discord.Colour.from_rgb(77, 119, 215)
    embed_message.set_footer(text=f"by {message.author}")

    if not form_options:
        message_form = await message.channel.send(embed=embed_message)
        for emoji in ["✅", "❌"]:
            await message_form.add_reaction(emoji)
        return

    ziped_options = list(zip(FORM_EMOJIS, form_options))

    for number, desc in ziped_options:
        embed_message.description += f"{number} {desc}\n"

    message_form = await message.channel.send(embed=embed_message)

    for number in range(len(form_options)):
        await message_form.add_reaction(FORM_EMOJIS[number])
Exemplo n.º 5
0
async def add(ctx: Context, name: str):
    msg: Message = ctx.message
    attachments: List[Attachment] = msg.attachments
    for i, a in enumerate(attachments):
        print(a.filename, a.url)
        id_ = hashlib.sha256(
            (name + str(i) + repr(datetime.now())).encode()).digest().hex()
        em = Embed(title="Added!",
                   description=f"name: {name}, id(generated): {id_}",
                   url=a.url)
        await ctx.send(embed=em)
        with sm as s:
            s.add(name, id_, a.url)
Exemplo n.º 6
0
    async def coinflip(self, ctx):
        """
        Coinflip
        """
        c = randint(0, 1)
        if c == 0:
            result = "**Heads**"
        else:
            result = "**Tails**"

        await ctx.send(embed=Embed(title="Coinflip 🪙",
                                   description=f"You flipped {result}",
                                   color=Colour.dark_purple()))
Exemplo n.º 7
0
    async def _play_song(self, ctx, *, uri: str = None):
        if uri is not None:
            song = self.play_song(uri)
        else:
            self.sp.start_playback()
            sleep(0.1)
            song = self.sp.current_user_playing_track()

        if song is not None:
            await ctx.send(embed=self.create_song_embed(song, "Now Playing"))
        else:
            await ctx.send(
                embed=Embed(title="No Song playing", color=Color.red()))
Exemplo n.º 8
0
 async def on_message(self, message):
     if not message.author.bot and not message.content.startswith('z!'):
         words = taggingutils.parse_message(message)
         for word in words:
             word = taggingutils.sanitize(word)
             key = taggingutils.create_kv_key(message.guild.id, word)
             if key in self.lookup:
                 embed_dict = {'image': {'url': self.lookup[key].url}}
                 embed = Embed.from_dict(embed_dict)
                 await message.channel.send(embed=embed)
                 # await message.channel.send(file=File(self.lookup[key].local_url))
                 self.mark_usage(key)
                 break  # only allow one match per message
Exemplo n.º 9
0
    async def run(self, ctx, *, args: str):
        """
        run some code
        """

        if not (match := re.fullmatch(r"((```)?)([a-zA-Z\d]+)\n(.+?)\1", args, re.DOTALL)):
            await ctx.send(
                embed=Embed(
                    title="Usage",
                    description=strings.run_usage
                )
            )
            return
Exemplo n.º 10
0
    async def roger_foto(self, ctx: commands.Context):
        """Você perguntou? O Roger aparece!"""
        msg: Message = await ctx.send("Invocando o Roger...")
        try:
            roger_img = self._fetch_roger_image()
            embed = Embed(description=roger_img[0], colour=Colour(randint(0x000000, 0xFFFFFF)))
            embed.set_image(url=roger_img[1])

            if roger_img[0].lower() == "julio_cobra":
                cobra = True
                ct = 'Cacilda, agora a cobra fumou. Você tirou o julio_cobra.'
            else:
                cobra = False
                ct = None
            await msg.edit(content=ct, embed=embed)

            if cobra and ctx.guild.id == 567817989806882818:
                await self._aprisionar(ctx)

        except Exception as e:
            await msg.edit("Ih, deu zica.")
            print_exc("Zica thrown:")
Exemplo n.º 11
0
async def rule34(ctx):
    emb = Embed(
        title='Rule34 :yum:',
        description=f'**Правило интернета №34**\nДобро пожаловать в интернет. По понятным причинам можно использовать только в NSFW каналах'
    )
    emb.add_field(name='Синтаксис', value='`-rule34`\n`-rule34 <список тегов через пробел>`')
    emb.add_field(name='Синонимы', value='`-r34`\n`-r`')
    await ctx.send(embed=emb)
Exemplo n.º 12
0
async def anek(ctx):
    emb = Embed(
        title='Anek :zany_face:',
        description=f'**Рандомный анекдот**\nРасскажу тебе случайный анекдот из паблика **Анектоды категории Б+**'
    )
    emb.add_field(name='Синтаксис', value='`-anek`')
    emb.add_field(name='Синонимы', value='`-anekdot`\n`-анек`\n`-прикол`\n`-смеяка`\n`-анекдот`\n`-ржака`')
    await ctx.send(embed=emb)
Exemplo n.º 13
0
class Other(Cog, name="Other Commands"):

    def __init__(self, bot) -> None:
        self.bot: Bot = bot

    @commands.command(name="run")
    @supported_languages_docs
    async def run(self, ctx, *, args: str):
        """
        run some code
        """

        if not (match := re.fullmatch(r"((```)?)([a-zA-Z\d]+)\n(.+?)\1", args, re.DOTALL)):
            await ctx.send(
                embed=Embed(
                    title="Usage",
                    description=strings.run_usage
                )
            )
            return

        *_, language, source = match.groups()

        await ctx.trigger_typing()

        try:
            api_result: dict = await Emkc.run_code(language, source)
        except EmkcAPIException as e:
            if e.message == "Supplied language is not supported by Piston":
                raise CommandError(f"language: {language} is not supported")

            raise CommandError(f"Error: {e.message}")
        except ClientError:
            raise CommandError("Error")

        output: str = api_result["output"]
        if len(output) > N_CHARS:
            newline = output.find("\n", N_CHARS, N_CHARS + 20)
            if newline == -1:
                newline = N_CHARS
            output = output[:newline] + "\n..."

        description = "```\n" + output.replace("`", "`\u200b") + "\n```"

        embed = Embed(title=f"Run Output ({language})", description=description)
        if api_result["stderr"] and not api_result["stdout"]:
            embed.colour = 0xFF0000

        embed.set_footer(text=f"requested by {ctx.author}", icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)
Exemplo n.º 14
0
    async def objet_fact(self, ctx, object: str):
        URL = "https://some-random-api.ml/meme"

        async with request("GET", URL, headers={}) as responses:
            if responses.status == 200:
                data = await responses.json()

                embed=Embed(title="💡 Facts ", url="https://some-random-api.ml", color=0x228acf)
                embed.set_thumbnail(url=data["image"])
                embed.add_field(name="***Respuesta***", value=f'{data["caption"]}', inline=True)
                embed.set_footer(text="Nobody!")
                await ctx.send(embed=embed)

            else:
                await ctx.send("API returned a {responses.status} status.")
Exemplo n.º 15
0
async def anek(ctx):
    response = requests.get(
        'https://api.vk.com/method/wall.get',
        params = {
            'owner_id': environ.get('ANEK_ID'), 'count': 1, 'offset': 0,
            'access_token': environ.get('VK_TOKEN'), 'v': '5.130'
        }
    )
    error = response.json().get('error')
    if error:
        print(f'VK API error (code = {error["error_code"]}): {error["error_msg"]}')
    post_count = response.json()['response']['count']
    response = requests.get(
        'https://api.vk.com/method/wall.get',
        params = {
            'owner_id': environ.get('ANEK_ID'), 'count': 1,
            'offset': random.randint(0, post_count - 1),
            'access_token': environ.get('VK_TOKEN'), 'v': '5.130', 'extended': '1'
        }
    )
    error = response.json().get('error')
    if error:
        print(f'VK API error (code = {error["error_code"]}): {error["error_msg"]}')
    content = response.json()['response']['items'][0]['text']
    emb = Embed(title=content) if len(content) < 256 else Embed(description=content)
    footer = '© ' + response.json()['response']['groups'][0]['name']
    emb.set_footer(text=footer)
    attachments = response.json()['response']['items'][0]
    try:
        if attachments['attachments'][0]['type'] == 'photo':
            image = attachments['attachments'][0]['photo']['sizes'][-1]['url']
            emb.set_image(url=image)
    except:
        pass
    thumbnail = response.json()['response']['groups'][0]['photo_200']
    emb.set_thumbnail(url=thumbnail)
    emb.color = discord.Color.from_rgb(22, 185, 247)
    await ctx.send(embed=emb)
Exemplo n.º 16
0
    async def bash(self):
        '''
        А нука башни!
        '''
        url = 'http://bash.im/forweb/?u'
        headers = {'User-Agent': 'Mozilla/5.0'}
        loop = asyncio.get_event_loop()
        async_request = loop.run_in_executor(
            None, lambda: requests.get(url, headers=headers))
        r = await async_request
        r.encoding = 'utf-8'
        text = r.text
        text = text[text.find('b_q_t'):]
        text = text[text.find('">') + 2:]

        text = text[:text.find("<' + '/div>")]
        text = text.replace("<' + 'br>", '\n')
        text = text.replace("<' + 'br />", '\n')
        text = html.unescape(text)

        embed = Embed(color=1, description=text)
        embed.set_footer(text="Bash.im")
        await self._bot.say(embed=embed)
Exemplo n.º 17
0
    def __init__(self, *, state, channel, data):
        self._state = state
        self._data = data
        self.id = int(data["id"])
        self.webhook_id = utils._get_as_snowflake(data, "webhook_id")
        self.reactions = [
            Reaction(message=self, data=x, emoji="x")
            for x in data.get("reactions", [])
        ]
        self.attachments = [
            Attachment(data=x, state=self._state) for x in data["attachments"]
        ]
        self.embeds = [Embed.from_dict(x) for x in data["embeds"]]
        self.application = data.get("application")
        self.activity = data.get("activity")
        self.channel = channel
        self._edited_timestamp = utils.parse_time(data["edited_timestamp"])
        self.type = try_enum(MessageType, data["type"])
        self.pinned = data["pinned"]
        self.flags = MessageFlags._from_value(data.get("flags", 0))
        self.mention_everyone = data["mention_everyone"]
        self.tts = data["tts"]
        self.content = data["content"]
        self.nonce = data.get("nonce")

        ref = data.get("message_reference")
        self.reference = MessageReference.with_state(
            state, ref) if ref is not None else None

        try:
            self._author = self._state.store_user(self._data["author"])
        except KeyError:
            self._author = None

        try:
            author = self._author
            try:
                author._update_from_message(self._data["member"])
            except AttributeError:
                author = Member._from_message(message=self,
                                              data=self._data["member"])
            self._member = author
        except KeyError:
            self._member = None

        for handler in ("call", "flags"):
            try:
                getattr(self, f"_handle_{handler}")(data[handler])
            except KeyError:
                continue
Exemplo n.º 18
0
    async def on_command_error(ctx, exception):
        # if the exception is of any of selected classes redirect to discord
        if isinstance(
                exception,
            (BadArgument, CommandError, CommandNotFound, CommandOnCooldown,
             CheckAnyFailure, NoPrivateMessage, MissingPermissions,
             UnexpectedQuoteError, BotMissingPermissions,
             MaxConcurrencyReached, MissingRequiredArgument,
             ExpectedClosingQuoteError, InvalidEndOfQuotedStringError)):
            await ctx.send(embed=Embed(description=str(exception)))

        # as well as in stdout with rest of the exception classes too
        traceback.print_exception(exception.__class__, exception,
                                  exception.__traceback__)
Exemplo n.º 19
0
async def on_error(event, *args, **kwargs):
    message = args[0]
    console.print(Panel('[bold red]Error Failure![/bold red]'),
                  justify='center')
    console.print(Panel('[bold red]' + traceback.format_exc(limit=2) +
                        "[/bold red]"),
                  justify='center')
    embed = Embed(
        title="New Error!",
        description=
        f"**Thrown By**: <@{str(message.author.id)}>\n**Channel:** {str(message.channel.id)}\n\n```{str(traceback.format_exc(limit=2))}```"
    )
    await bot.get_channel(830932320771899432).send(
        embed=embed, content="<@368083908862017537>")
Exemplo n.º 20
0
    async def jf(self, ctx, dest, volume):
        """
        Calculates the cost by m3 for GreenSwarm Express contracts. Valid destinations at this point are: d-o, do, home, d-ojez, and jita
        """
        priceIn = 800
        priceOut = 500
        minimumValue = 5000000

        allowedIn = ['d-o', 'home', 'do', 'd-ojez']
        allowedOut = ['jita']

        if dest in allowedIn:
            costs = int(priceIn) * int(volume)
        elif dest in allowedOut:
            costs = int(priceOut) * int(volume)
        else:
            return await ctx.send('Please select a valid destination. For now, the only valid destnations are \'d-o\', \'home\', \'do\', \'d-ojez\', \'jita\'')
        if int(costs) < int(minimumValue):
            costs = 5000000
        embed = Embed(title='Cost to transport {} m3 to {}: {:,} isk'.format(volume, dest, costs))
        embed.color = Color.green()

        return await ctx.send(embed=embed)
Exemplo n.º 21
0
    def playing_message(self) -> Dict[str, Embed]:
        em = Embed(
            colour=self._embed_colour,
            description=f'[{self._title}]({self._url})'
        )
        em.set_author(name=self._uploader, url=self._uploader_url)
        em.set_thumbnail(url=self._thumbnail)

        return {'embed': em}
Exemplo n.º 22
0
    async def error_channel(self, ctx, val=None):
        if val:
            try:
                val = int(val)
            except ValueError:
                em = Embed(
                    title="Administration: Error Log Channel Config",
                    description=f"`ValueError`: `val` must be an integer.",
                    color=0xff0000)
                return await ctx.send(embed=em)

            orig = deepcopy(self.bot.config['error_log_channel'])
            self.bot.config['error_log_channel'] = val

            em = Embed(title="Administration: Error Log Channel Config",
                       description=f"New error channel id: `{val}`\n"
                       f"Original error original channel id: `{orig}`",
                       color=0x00ff00)

        else:
            err_channel = self.bot.get_channel(
                self.bot.config['error_log_channel'])
            if err_channel:
                em = Embed(
                    title="Administration: Error Log Channel Config",
                    description=f"Current error channel id: `{err_channel.id}`\n"
                    f"Located in guild: `{err_channel.guild.name}`\n"
                    f"Channel name: {err_channel.mention}",
                    color=0x0000ff)
            else:
                em = Embed(
                    title="Administration: Error Log Channel Config",
                    description=f"Current error channel id: `{err_channel.id}`\n"
                    f":warning: Channel does not exist!",
                    color=0x0000ff)

        return await ctx.send(embed=em)
Exemplo n.º 23
0
 async def _list(self, ctx: Context) -> None:
     if len(self._env_store.keys()):
         emb = Embed(title='Environment Store List', color=Colour.green())
         for k, v in self._env_store.items():
             emb.add_field(name=k, value=repr(v))
     else:
         emb = Embed(title='Environment Store List', description='Environment Store is currently empty',
                     color=Colour.green())
     await ctx.send(embed=emb)
Exemplo n.º 24
0
 async def config(self, ctx: Context):
     """View Bot settings"""
     em = Embed(
         title="Administration: Config",
         description=f"The options and values are listed below:\n"
         f"```"
         f"debug_mode: {self.bot.config['debug_mode']}\n"
         f"auto_pull: {self.bot.config['auto_pull']}\n"
         f"text_status: \"{self.bot.text_status}\" (namespace only)\n"
         f"prefix: {self.bot.command_prefix} (namespace only)\n"
         f"changelog: Not shown here ( {self.bot.command_prefix}help updates )\n"
         f"error_log_channel: {self.bot.config['error_log_channel']}"
         f"```",
         color=0x0000ff)
     return await ctx.send(embed=em)
Exemplo n.º 25
0
 async def __updateUserRole(self, guild: Guild, user: User, member: Member,
                            rank: int, channelToUse: GuildChannel,
                            internal: bool):
     if user:
         if member:
             newRoles = RoleUtil.getKfpRolesFromLevel(guild.id, rank)
             if len(newRoles) > 0:
                 for newRole in newRoles:
                     newGuildRole: Role = guild.get_role(newRole.role_id)
                     if newGuildRole:
                         if not newGuildRole in user.roles:
                             # 用戶有新身份組
                             # 先移除所有不符合的身份組
                             oldRoles: KfpRole = RoleUtil.getCurrentRoles(
                                 guild.id,
                                 Util.RoleCategory(newRole.category))
                             if oldRoles:
                                 oldGuildRoles = []
                                 for oldRole in oldRoles:
                                     guildRole = guild.get_role(
                                         oldRole.role_id)
                                     if guildRole and guildRole in user.roles:
                                         oldGuildRoles.append(guildRole)
                                 for oldGuildRole in oldGuildRoles:
                                     await user.remove_roles(oldGuildRole)
                             # 添加新的身份組
                             await user.add_roles(newGuildRole)
                             if internal:
                                 print(
                                     "adding role {} to member {} successed!"
                                     .format(newGuildRole.name, user.name))
                             else:
                                 embed = Embed()
                                 embed.description = '恭喜<@!{}> 成為 {}'.format(
                                     user.id, newGuildRole.name)
                                 await channelToUse.send(embed=embed)
Exemplo n.º 26
0
 def create_embed(self, msg: str, state: Aria) -> Embed:
     image = "neutral"
     if state.mood < 0:
         image = "strict"
     embed = Embed(title="ARIA",
                   description=msg,
                   color=discord.Color.from_rgb(255, 0, 0))
     embed.add_field(name="Mistress Mood", value=str(state.mood))
     embed.set_image(url=IMAGES[image])
     return embed
Exemplo n.º 27
0
async def weather(ctx, city: str):
    await ctx.send(embed=Embed(
        title="This command is under testing",
        description=
        "due to the recent updates to the Open Weather api,  the bot's weather api is broken, but still a new api is under work",
        color=0x0000ff))
    async with ctx.typing():
        obs: pyowm.weatherapi25.observation.Observation = owm.weather_at_place(
            city)
        print(obs)
        await ctx.send(repr(obs))
        ret: pyowm.weatherapi25.observation.weather.Weather = obs.weather
        print(ret)
        await ctx.send(
            f'the weather conditions will most likely be {ret["detailed_status"]},\nTemperature will remain around {ret["temperature"]["temp"]-273.15}\u00b0C, Humidity {ret["humidity"]}%. Winds will blow at {ret["wind"]["speed"]*3.6} kph at {ret["wind"]["deg"]}\u00b0 from North'
        )
Exemplo n.º 28
0
 async def _autoplay(self):
     while True:
         song = self.sp.current_user_playing_track()
         time_left_ms = song['item']['duration_ms'] - song['progress_ms']
         await asyncio.sleep(time_left_ms / 1000)
         song = self.play_next_song(reset=False)
         channel = self.bot.get_channel(self.stdout)
         if song is not None and channel is not None:
             await self.bot.send_message(channel,
                                         embed=self.create_song_embed(
                                             song, "Now Playing"))
         elif song is None and channel is not None:
             await self.bot.send_message(channel,
                                         embed=Embed(
                                             title="No Song playing",
                                             color=Color.red()))
Exemplo n.º 29
0
    def base_embed(self, channel, awmap: AWMap) -> Embed:
        """Formats and returns the base embed with map
        title and author."""

        if awmap.awbw_id:
            a_url = f"http://awbw.amarriner.com/profile.php?username={quote(awmap.author)}"
            if awmap.author == "[Unknown]":
                author = "Design Map by [Unknown]"
            else:
                author = f"Design map by [{awmap.author}]({a_url})"
            m_url = f"http://awbw.amarriner.com/prevmaps.php?maps_id={awmap.awbw_id}"
        else:
            author = f"Design map by {awmap.author}"
            m_url = ""

        return Embed(color=self._color(channel), title=awmap.title, description=author, url=m_url)
Exemplo n.º 30
0
 async def ping(self, ctx):
     """ Tests Functionality """
     VERSION = os.getenv('HEROKU_RELEASE_VERSION')
     e = Embed(title='Pong!',
               description=':ping_pong:!',
               color=discord.Color.green())
     e.set_footer(text=f"Caseus Version {VERSION}")
     e.add_field(
         name="Latency:",
         value=f"Responded in {round(self.cas.latency, 2)} microseconds.")
     await ctx.send(embed=e)