コード例 #1
0
 async def command(client, message, guild:Converter('guild', default_code='message.guild'),
         user:Converter('user', ConverterFlag.user_default.update_by_keys(everywhere=True), default=None), reason):
     
     # Should not happen normally
     if guild is None:
         return
     
     if user is None:
         await client.message_create(message.channel, 'Please define a user to ban.')
         return
     
     if not reason:
         author = message.author
         reason = f'For the request of {author.full_name} ({author.id})'
     
     for maybe_banner in guild.clients:
         if guild.cached_permissions_for(client).can_ban_users:
             banner = maybe_banner
             break
     else:
         await client.message_create(message.channel, 'No one of has can ban the user in the guild.')
         return
     
     await banner.guild_ban_add(guild, user, reason=reason)
     await client.message_create(message.channel,
         f'{user.full_name} banned at guild {guild.name} by {banner.full_name}.')
コード例 #2
0
    async def command(client, message, message_id: int,
                      channel: Converter('channel',
                                         default_code='message.channel')):
        permissions = message.channel.cached_permissions_for(client)
        can_delete = permissions.can_manage_messages

        if not permissions.can_manage_webhooks:
            message = await client.message_create(
                message.channel,
                'I have no permissions to get webhooks from this channel.')
            if can_delete:
                await sleep(30.0, client.loop)
                await client.message_delete(message)
            return

        try:
            target_message = await client.message_get(channel, message_id)
        except DiscordException as err:
            message = await client.message_create(message.channel, repr(err))
            if can_delete:
                await sleep(30.0, client.loop)
                await client.message_delete(message)
            return

        webhooks = await client.webhook_get_channel(channel)
        if webhooks:
            webhook = webhooks[0]
        else:
            webhook = await client.webhook_create(channel, 'Love You')

        await client.webhook_message_create(
            webhook,
            embed=target_message.embeds,
            name=target_message.author.name,
            avatar_url=target_message.author.avatar_url)
コード例 #3
0
async def test_message_converter(client, message, value: Converter(
    'message',
    flags=ConverterFlag.message_default.update_by_keys(everywhere=True),
    default=None)):
    """
    Tries to parse the message from the content of the message.
    """
    await client.message_create(message.channel, repr(value))
コード例 #4
0
 async def command(client, message,user:Converter('user', ConverterFlag.user_default.update_by_keys(everywhere=True), default=None), rest):
     if user is None:
         await client.message_create(message.channel,
             'Please define a user as well.')
         return
     
     message = message.custom(author=user)
     
     await client.command_processer.commands['help'](client, message,rest)
コード例 #5
0
    async def update_application_info(client, message, user: Converter(
        'user',
        flags=ConverterFlag.user_default.update_by_keys(everywhere=True),
        default_code='client')):
        if isinstance(user, Client):
            await user.update_application_info()
            content = f'Application info of `{user:f}` is updated succesfully!'
        else:
            content = 'I can update application info only of a client.'

        await client.message_create(message.channel, content)
コード例 #6
0
    async def command(client, message, role: Converter(
        'role',
        ConverterFlag().update_by_keys(mention=True, name=True),
        default_code='message.guild.default_role')):

        if role is None:
            role_id = 'N/A'
        else:
            role_id = str(role.id)

        await client.message_create(message.channel, role_id)
コード例 #7
0
ファイル: games.py プロジェクト: JohnnyStein/Koishi
 async def command(client, message, target: Converter(
     'user',
     flags=ConverterFlag.user_default.update_by_keys(everywhere=True),
     default_code='message.author')):
     if target in CLIENTS or client.is_owner(target):
         result = 10
     else:
         result = target.id % 11
     #nickname check
     await client.message_create(
         message.channel,
         f'I rate {target.name_at(message.guild)} {result}/10')
コード例 #8
0
async def avatar(client, message,
                 user: Converter('user',
                                 ConverterFlag.user_all,
                                 default_code='message.author')):
    if user.avatar:
        color = user.avatar_hash & 0xffffff
    else:
        color = user.default_avatar.color

    url = user.avatar_url_as(size=4096)
    embed = Embed(f'{user:f}\'s avatar', color=color, url=url)
    embed.add_image(url)

    await client.message_create(message.channel, embed=embed)
コード例 #9
0
    async def command(client, message, user: Converter(
        'user',
        flags=ConverterFlag.user_default.update_by_keys(everywhere=True),
        default_code='message.author')):
        color = user.avatar_hash
        if color:
            color &= 0xffffff
        else:
            color = user.default_avatar.color

        url = user.avatar_url_as(size=4096)
        embed = Embed(f'{user:f}\'s avatar', color=color, url=url)
        embed.add_image(url)

        await client.message_create(message.channel, embed=embed)
コード例 #10
0
    async def command(client, message, message_id: int,
                      channel: Converter('channel',
                                         default_code='message.channel')):
        if not channel.cached_permissions_for(client).can_read_message_history:
            await client.message_create(
                message.channel,
                'I am unable to read the messages at the specified channel.')
            return

        try:
            target_message = await client.message_get(channel, message_id)
        except DiscordException as err:
            await client.message_create(message.channel, err.__repr__())
            return
        await Pagination(
            client, message.channel,
            [Embed(description=chunk) for chunk in pchunkify(target_message)])
コード例 #11
0
ファイル: help.py プロジェクト: JohnnyStein/Koishi
async def aliases(client, message, name: str,
                  target_client: Converter('client',
                                           flags=ConverterFlag.client_all,
                                           default_code='client')):
    while True:
        if len(name) > 64:
            fail = True
            break

        if not name.islower():
            name = name.lower()

        try:
            command = target_client.command_processer.commands[name]
        except KeyError:
            fail = True
            break

        if await command.run_all_checks(target_client, message):
            fail = False
            break

        fail = True
        break

    if fail:
        title = None
        if client is target_client:
            description = f'I have no command named as {name!r}.'
        else:
            description = f'{target_client.name_at(message.guild)} has no command named as {name!r}.'
    else:
        aliases = command.aliases
        if aliases is None:
            title = f'There are no alises provided for command: {name!r}.'
            description = None
        else:
            title = f'Aliases for: {command.display_name!r}:'
            description = '\n'.join(aliases)

    await client.message_create(message.channel,
                                embed=Embed(title,
                                            description,
                                            color=KOISHI_HELP_COLOR))
コード例 #12
0
    async def command(client, message, message_id: int,
                      channel: Converter('channel',
                                         default_code='message.channel')):
        if not channel.cached_permissions_for(client).can_read_message_history:
            await client.message_create(
                message.channel,
                'I am unable to read the messages at the specified channel.')
            return

        try:
            data = await client.http.message_get(channel.id, message_id)
        except DiscordException as err:
            await client.message_create(message.channel, repr(err))
            return

        await Pagination(client, message.channel, [
            Embed(description=chunk) for chunk in cchunkify(
                json.dumps(data, indent=4, sort_keys=True).splitlines())
        ])
コード例 #13
0
ファイル: games.py プロジェクト: JohnnyStein/Koishi
    async def command(client, message,
                      target: Converter('user', flags=ConverterFlag.user_all)):
        source = message.author
        if source is target:
            prefix = client.command_processer.get_prefix_for(message)
            embed = Embed('love', ('How much you two fit together?\n'
                                   f'Usage: `{prefix}user *user*`'),
                          color=GAMES_COLOR)
        else:
            percent = ((source.id & 0x1111111111111111111111) +
                       (target.id & 0x1111111111111111111111)) % 101
            element = LOVE_VALUES[percent]

            embed = Embed(
                choice(element['titles']),
                f'{source:f} {BUILTIN_EMOJIS["heart"]:e} {target:f} scored {percent}%!',
                0xad1457,
            )
            embed.add_field('My advice:', element['text'])

        await client.message_create(message.channel, embed=embed)
コード例 #14
0
 async def command(client, message, user: Converter(
     'user',
     ConverterFlag().update_by_keys(mention=True, name=True),
     default_code='message.author')):
     await client.message_create(message.channel, str(user.id))
コード例 #15
0
 async def command(client, message, limit : Converter('int', default=1,), reason):
     if not reason:
         reason = f'{message.author.full_name} asked for it'
     if limit>0:
         await client.message_delete_sequence(channel=message.channel,limit=limit,reason=reason)
コード例 #16
0
 async def command(client, message, channel: Converter(
     'channel',
     ConverterFlag().update_by_keys(mention=True, name=True),
     default_code='message.channel')):
     await client.message_create(message.channel, str(channel.id))
コード例 #17
0
async def battle_manager(client, message, target:Converter('user', flags=ConverterFlag.user_default.update_by_keys(everywhere=True), default=None)):
    text = ''
    while True:
        if target is None:
            break
        
        guild = message.guild
        source = message.author
        
        if source in BS_GAMES:
            text = 'You cant start a game, if you are in 1 already'
            break
        
        if source in BS_REQUESTERS:
            text = 'You can have only one active request'
            break

        if target is source:
            text = 'Say 2 and easier.'
            break

        if target is client:
            text = 'NO AI opponent yet!'
            break
        
        if target in BS_GAMES:
            text = 'The user is already in game'
            break

        
        request = active_request(source, target)
        
        is_reversed = BS_REQUESTS.get(request)

        if is_reversed is not None:
            is_reversed.future.set_result(message)
            return

        BS_REQUESTS[request] = request
        
        BS_REQUESTERS.add(source)
        
        channel = message.channel
        private = await client.channel_private_create(target)
        
        await client.message_create(channel,
            f'Waiting on {target.full_name}\'s reply here and at dm.\nType:"accept name/mention" to accept')
        
        
        future = request.future=Future(KOKORO)
        check = wait_on_reply(guild, source, target)
        event = client.events.message_create
        
        waiter1 = WaitAndContinue(future, check, channel, event, 300.)
        waiter2 = WaitAndContinue(future, check, private, event, 300.)
        
        try:
            result = await future
        except TimeoutError:
            try:
                BS_REQUESTERS.remove(source)
                text = f'The request from {source.full_name} timed out'
            except KeyError:
                pass
            break
        finally:
            try:
                del BS_REQUESTS[request]
            except KeyError:
                pass

            for waiter in (waiter1,waiter2):
                waiter.cancel()

        try:
            BS_REQUESTERS.remove(source)
        except KeyError:
            text = 'The requester is already in a game'
            break
        
        if target in BS_GAMES:
            text='You already accepted a game'
            break

        try:
            BS_REQUESTERS.remove(target)
            await client.message_create(channel, f'Request from {target.full_name} got cancelled')
        except KeyError:
            pass
            
        game = battleships_game(client, source, target, private)
        break
    
    if text:
        await client.message_create(message.channel, text)
    else:
        embed = await bs_description(client, message)
        await Closer(client, message.channel, embed)
コード例 #18
0
    async def command(client, message, user: Converter(
        'user',
        ConverterFlag.user_default.update_by_keys(everywhere=True,
                                                  profile=True),
        default_code='message.author')):
        guild = message.guild

        embed = Embed(user.full_name)
        embed.add_field(
            'User Information',
            f'Created: {elapsed_time(user.created_at)} ago\n'
            f'Profile: {user:m}\n'
            f'ID: {user.id}')

        if guild is None:
            profile = None
        else:
            profile = user.guild_profiles.get(guild)

        if profile is None:
            if user.avatar_type is ICON_TYPE_NONE:
                color = user.default_avatar.color
            else:
                color = user.avatar_hash & 0xFFFFFF
            embed.color = color

        else:
            embed.color = user.color_at(guild)
            roles = profile.roles
            if roles is None:
                roles = '*none*'
            else:
                roles.sort()
                roles = ', '.join(role.mention for role in reversed(roles))

            text = []
            if profile.nick is not None:
                text.append(f'Nick: {profile.nick}')

            if profile.joined_at is None:
                await client.guild_user_get(user.id)

            text.append(f'Joined: {elapsed_time(profile.joined_at)} ago')

            boosts_since = profile.boosts_since
            if (boosts_since is not None):
                text.append(f'Booster since: {elapsed_time(boosts_since)}')

            text.append(f'Roles: {roles}')
            embed.add_field('In guild profile', '\n'.join(text))

        embed.add_thumbnail(user.avatar_url_as(size=128))

        if user.activity is not ActivityUnknown or user.status is not Status.offline:
            text = []

            if user.status is Status.offline:
                text.append('Status : offline\n')
            elif len(user.statuses) == 1:
                for platform, status in user.statuses.items():
                    text.append(f'Status : {status} ({platform})\n')
            else:
                text.append('Statuses :\n')
                for platform, status in user.statuses.items():
                    text.append(f'**>>** {status} ({platform})\n')

            if user.activity is ActivityUnknown:
                text.append('Activity : *unknown*\n')
            elif len(user.activities) == 1:
                text.append('Activity : ')
                add_activity(text, user.activities[0])
            else:
                text.append('Activities : \n')
                for index, activity in enumerate(user.activities, 1):
                    text.append(f'{index}.: ')
                    add_activity(text, activity)

            embed.add_field('Status and Activity', ''.join(text))
        await client.message_create(message.channel, embed=embed)
コード例 #19
0
async def test_invite_converter(client, message,
                                value: Converter('invite', default=None)):
    """
    Tries to parse an invite from the content of the message.
    """
    await client.message_create(message.channel, repr(value))
コード例 #20
0
import re

from hata import CHANNELS, KOKORO, DiscordException, ERROR_CODES, sleep, ScarletExecutor, MESSAGES, Permission, \
    Color, Embed, Emoji, CLIENTS, Role, eventlist, ROLES, EMOJIS, WeakKeyDictionary
from hata.ext.commands import ContentParser, checks, Converter, ChooseMenu, Pagination, ConverterFlag

from bot_utils.shared import permission_check_handler
from bot_utils.models import DB_ENGINE, auto_react_role_model, AUTO_REACT_ROLE_TABLE

ROLE_CONVERTER = Converter(
    'role', flags=ConverterFlag.role_default.update_by_keys(everywhere=True))
MESSAGE_CONVERTER = Converter(
    'message',
    flags=ConverterFlag.message_default.update_by_keys(everywhere=True))


def setup(lib):
    for client in CLIENTS:
        client.events(load_auto_react_roles, 'ready')

    Koishi.commands.extend(AUTO_REACT_ROLE_COMMANDS)


async def teardown(lib):
    for client in CLIENTS:
        client.events.remove(load_auto_react_roles, 'ready', by_type=True)

    Koishi.commands.unextend(AUTO_REACT_ROLE_COMMANDS)

    async with ScarletExecutor(limit=20) as executor:
        for gui in AUTO_REACT_ROLE_GUIS.values():
コード例 #21
0
ファイル: image_handler.py プロジェクト: JohnnyStein/Koishi
async def upload(client, message, target_message: Converter(
    'message',
    flags=ConverterFlag.user_default.update_by_keys(everywhere=True)), *tags):
    if UPLOAD:
        tags = [tag.lower() for tag in tags if not is_mention(tag)]
        for tag in tags:
            if tag in RESERVED_TAGS:
                result_message = f'Reserved tag: {tag!r}!'
                break
        else:
            if tags:
                found_image = None
                attachments = target_message.attachments
                if (attachments is not None):
                    for attachment in attachments:
                        filename = attachment.name

                        index = filename.rfind('.')
                        if index < 0:
                            continue

                        extension = filename[index + 1:].lower()

                        if extension in IMAGE_FORMATS_STATIC:
                            is_static = True
                        elif extension in IMAGE_FORMATS_ANIMATED:
                            is_static = False
                        else:
                            continue

                        found_image = attachment
                        break

                if (found_image is None):
                    embeds = target_message.embeds
                    if (embeds is not None):
                        for embed in embeds:
                            embed_image = embed.image
                            if embed_image is None:
                                continue

                            filename = embed_image.url
                            if filename is None:
                                continue

                            index = filename.rfind('.')
                            if index < 0:
                                continue

                            extension = filename[index + 1:].lower()

                            if extension in IMAGE_FORMATS_STATIC:
                                is_static = True
                            elif extension in IMAGE_FORMATS_ANIMATED:
                                is_static = False
                            else:
                                continue

                            found_image = embed_image
                            break

                if found_image is None:
                    result_message = 'The given message has no image attached.'
                else:
                    with client.keep_typing(message.channel):
                        async with UPLOAD_LOCK:
                            data = await client.download_attachment(found_image
                                                                    )

                            index = f'{(len(IMAGES_STATIC)+len(IMAGES_ANIMATED)):08X}'
                            if is_static:
                                path = f'{index}_{"_".join(tags)}.png'
                                filename = join(IMAGE_PATH, path)
                                if extension != 'png':
                                    #we save everything in png, ~~rasism~~
                                    if extension in ('jpg', 'jpeg'):
                                        image_type = image_type_JPG
                                    elif extension == 'bmp':
                                        image_type = image_type_BMP
                                    image = object.__new__(image_type)
                                    image.fp = BytesIO(data)
                                    image.info = {}
                                    image.palette = None
                                    image.im = None
                                    image.filename = None
                                    image._exclusive_fp = None
                                    image.decoderconfig = ()
                                    image.decodermaxblock = 65536
                                    image.readonly = False
                                    image._exif = None
                                    image.pyaccess = None
                                    image._open()
                                    await KOKORO.run_in_executor(
                                        functools.partial(
                                            image.save, filename))
                                else:
                                    with (await AsyncIO(filename,
                                                        'wb')) as file:
                                        await file.write(data)
                            else:
                                path = f'{index}_{"_".join(tags)}.{extension}'
                                filename = join(IMAGE_PATH, path)
                                with (await AsyncIO(filename, 'wb')) as file:
                                    await file.write(data)

                            image_details(path)

                    result_message = 'Done Masuta~!'

            else:
                result_message = 'Please give tags as well!'

    else:
        result_message = 'Upload is not supported, PIL library not found.'

    await Closer(client, message.channel,
                 Embed(result_message, color=IMAGE_COLOR))