Exemplo n.º 1
0
 async def delete(self, ctx: SlashContext, name: str):
     await ctx.defer()
     if self.firebase_ref.child('tags/{0}'.format(name)).get():
         self.firebase_ref.child('tags/{0}'.format(name)).delete()
         await ctx.send(embed=hkd.create_embed(title='Successfully removed tag - {0}.'.format(name)))
     else:
         await ctx.send(embed=hkd.create_embed(title="That tag doesn't exist.", colour=Colour.red()))
Exemplo n.º 2
0
 async def choose(self, ctx: SlashContext, options: str):
     await ctx.defer()
     split_options = options.split()
     if len(split_options) > 1:
         await ctx.send(embed=hkd.create_embed(description=split_options[randrange(len(split_options))]))
     else:
         await ctx.send(embed=hkd.create_embed(description='Please provide 2 or more options to choose from, e.g. **/choose** *option1* *option2*.', colour=Colour.red()))
Exemplo n.º 3
0
 async def currency(self, ctx: SlashContext, conversion: str):
     await ctx.defer()
     conversion_split = conversion.split()
     if len(conversion_split) == 4 and conversion_split[2].lower() == 'to':
         with suppress(Exception):
             result = CurrencyRates().convert(conversion_split[1].upper(), conversion_split[3].upper(), Decimal(conversion_split[0]))
             await ctx.send(embed=hkd.create_embed(title='{0} {1}'.format('{:f}'.format(result).rstrip('0').rstrip('.'), conversion_split[3].upper())))
             return
     await ctx.send(embed=hkd.create_embed(description="Couldn't convert. Please follow this format for converting currency: **/currency** 12.34 AUD to USD.", colour=Colour.red()))
Exemplo n.º 4
0
 async def update(self, ctx: SlashContext, name: str):
     await ctx.defer()
     if len(split_update := name.split()) > 1:
         tag_name = split_update[0]
         updated_content = name[len(tag_name) + 1:]
         if tag_name in self.firebase_ref.child('tags').get():
             self.firebase_ref.child('tags/{0}'.format(tag_name)).set(updated_content)
             await ctx.send(embed=hkd.create_embed(title='Successfully updated tag - {0}.'.format(tag_name)))
         else:
             await ctx.send(embed=hkd.create_embed(title="That tag doesn't exist."))
         return
Exemplo n.º 5
0
 async def create(self, ctx: SlashContext, name: str):
     await ctx.defer()
     if len(split_request := name.split()) > 1:
         tag_name = split_request[0]
         tag_content = name[len(tag_name) + 1:]
         if tag_name not in self.firebase_ref.child('tags').get():
             self.firebase_ref.child('tags/{0}'.format(tag_name)).set(tag_content)
             await ctx.send(embed=hkd.create_embed(title='Successfully created tag - {0}'.format(tag_name)))
         else:
             await ctx.send(embed=hkd.create_embed(title='That tag already exists. Please choose a different tag name.', colour=Colour.red()))
         return
Exemplo n.º 6
0
 async def check_live_streams(self):
     channel = hkd.get_seiyuu_channel(self.bot.guilds)
     now = datetime.utcnow().isoformat() + 'Z'
     with suppress(Exception):
         events = self.calendar.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute().get('items', [])
         first_event = True
         for event in events:
             start = parser.parse(event['start'].get('dateTime', event['start'].get('date')))
             if start.timestamp() - time.time() < 900 and event['description'][0] != '*':
                 with suppress(Exception):
                     split_index = event['description'].find(';')
                     wug_members_str, stream_link = event['description'][:split_index], event['description'][split_index + 1:]
                     wug_members = wug_members_str.split(',')
                     if (link_start := stream_link.find('<a')) > 0:
                         stream_link = stream_link[:link_start]
                     elif stream_link.startswith('<a'):
                         stream_link = BeautifulSoup(stream_link, 'html.parser').find('a').contents[0]
                     colour = hkd.get_oshi_colour(hkd.get_wug_guild(self.bot.guilds), wug_members[0]) if len(wug_members) == 1 else Colour.teal()
                     embed_fields = []
                     embed_fields.append(('Time', '{0:%Y}-{0:%m}-{0:%d} {0:%H}:{0:%M} JST'.format(start.astimezone(pytz.timezone('Japan')))))
                     embed_fields.append(('WUG Members', ', '.join(wug_members)))
                     content = '**Starting in 15 Minutes**' if first_event else ''
                     await channel.send(content=content, embed=hkd.create_embed(title=event['summary'], colour=colour, url=stream_link, fields=embed_fields))
                     first_event = False
                     event['description'] = '*' + event['description']
                     self.calendar.events().update(calendarId='primary', eventId=event['id'], body=event).execute()
Exemplo n.º 7
0
 async def check_instagram(self):
     channel = hkd.get_updates_channel(self.bot.guilds)
     with suppress(Exception):
         for instagram_id in self.firebase_ref.child('last_instagram_posts').get().keys():
             last_post_id = int(self.firebase_ref.child('last_instagram_posts/{0}'.format(instagram_id)).get())
             profile = Profile.from_username(self.insta_api.context, instagram_id)
             user_name = profile.full_name
             posted_updates = []
             for post in profile.get_posts():
                 if post.mediaid <= last_post_id:
                     break
                 post_text = post.caption
                 post_pic = post.url
                 post_link = 'https://www.instagram.com/p/{0}/'.format(post.shortcode)
                 posted_updates.append(post.mediaid)
                 if instagram_id in hkd.WUG_INSTAGRAM_IDS.values():
                     colour = hkd.get_oshi_colour(hkd.get_wug_guild(self.bot.guilds), hkd.dict_reverse(hkd.WUG_INSTAGRAM_IDS)[instagram_id])
                 else:
                     colour = Colour(0x242424)
                 author = {}
                 author['name'] = '{0} (@{1})'.format(user_name, instagram_id)
                 author['url'] = 'https://www.instagram.com/{0}/'.format(instagram_id)
                 author['icon_url'] = profile.profile_pic_url
                 await channel.send(embed=hkd.create_embed(author=author, title='Post by {0}'.format(user_name), description=post_text, colour=colour, url=post_link, image=post_pic))
             if posted_updates:
                 self.firebase_ref.child('last_instagram_posts/{0}'.format(instagram_id)).set(str(max(posted_updates)))
     self.check_instagram.change_interval(minutes=random.randint(20, 30))
Exemplo n.º 8
0
class Tags(commands.Cog):
    def __init__(self, bot, firebase_ref):
        self.bot = bot
        self.firebase_ref = firebase_ref

    @cog_ext.cog_subcommand(
        base="tag",
        description="Create a tag.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="name",
                description="Name of the tag, followed by the content of the tag.",
                option_type=3,
                required=True
            )
        ]
    )
    @commands.guild_only()
    async def create(self, ctx: SlashContext, name: str):
        await ctx.defer()
        if len(split_request := name.split()) > 1:
            tag_name = split_request[0]
            tag_content = name[len(tag_name) + 1:]
            if tag_name not in self.firebase_ref.child('tags').get():
                self.firebase_ref.child('tags/{0}'.format(tag_name)).set(tag_content)
                await ctx.send(embed=hkd.create_embed(title='Successfully created tag - {0}'.format(tag_name)))
            else:
                await ctx.send(embed=hkd.create_embed(title='That tag already exists. Please choose a different tag name.', colour=Colour.red()))
            return
        await ctx.send(embed=hkd.create_embed(description="Couldn't create tag.", colour=Colour.red()))
Exemplo n.º 9
0
 async def on_member_remove(self, member):
     if (guild := hkd.get_wug_guild(self.bot.guilds)) == member.guild:
         channel = disc_utils.get(guild.channels, id=hkd.WELCOME_CHANNEL_ID)
         try:
             await member.guild.fetch_ban(member)
             return
         except discord.NotFound:
             await channel.send(embed=hkd.create_embed(title='{0} ({1}) has left the server.'.format(member.display_name, member)))
Exemplo n.º 10
0
 async def oshimashi(self, ctx: SlashContext, member: str = ''):
     await ctx.defer()
     if not (role := hkd.get_wug_role(ctx.guild, member)):
         await ctx.send(embed=hkd.create_embed(
             description=
             "Couldn't find that role. Use **/help roles** to show additional help on how to get roles.",
             colour=Colour.red()))
         return
Exemplo n.º 11
0
 async def eventsin(self, ctx: SlashContext, month: str, member: str = ''):
     await ctx.defer()
     if (search_month := hkd.parse_month(month)) == 'None':
         await ctx.send(embed=hkd.create_embed(
             description=
             "Couldn't find any events. Please follow this format for searching for events: **/eventsin** April Mayushii.",
             colour=Colour.red()))
         return
Exemplo n.º 12
0
class Oshi(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @cog_ext.cog_slash(
        description="Change to a different WUG member role.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(name="member",
                          description="The member that you want the role of.",
                          option_type=3,
                          required=True,
                          choices=hkd.get_member_choices())
        ])
    @commands.guild_only()
    async def oshihen(self, ctx: SlashContext, member: str = ''):
        await ctx.defer()
        if not (role := hkd.get_wug_role(ctx.guild, member)):
            await ctx.send(embed=hkd.create_embed(
                description=
                "Couldn't find that role. Use **/help roles** to show additional help on how to get roles.",
                colour=Colour.red()))
            return
        roles_to_remove = []
        for existing_role in ctx.author.roles:
            if existing_role.id in hkd.WUG_ROLE_IDS.values(
            ) or existing_role.id in hkd.WUG_KAMIOSHI_ROLE_IDS.values():
                roles_to_remove.append(existing_role)
        if len(roles_to_remove) == 1 and roles_to_remove[0].name == role.name:
            await ctx.send(embed=hkd.create_embed(
                description=
                'Hello {0.author.mention}, you already have that role.'.format(
                    ctx),
                colour=Colour.red()))
        elif roles_to_remove:
            await ctx.author.remove_roles(*roles_to_remove)
            await asyncio.sleep(0.5)
        await ctx.author.add_roles(role)
        await ctx.send(embed=hkd.create_embed(
            description=
            'Hello {0.author.mention}, you have oshihened to the **{1}** role {2.mention}.'
            .format(ctx, member.title(), role),
            colour=role.colour))
Exemplo n.º 13
0
 async def dl_vid(self, ctx: SlashContext, url: str):
     await ctx.defer()
     result = {}
     with suppress(Exception):
         ytdl_opts = {'outtmpl': '%(id)s.%(ext)s'}
         with youtube_dl.YoutubeDL(ytdl_opts) as ytdl:
             result = ytdl.extract_info(url)
     if not (vid_ids := hkd.get_ids_from_ytdl_result(result)):
         await ctx.send(embed=hkd.create_embed(title='Failed to download video.', colour=Colour.red()))
         return
Exemplo n.º 14
0
 async def roles(self, ctx: SlashContext):
     await ctx.defer()
     description = 'Users can have any of the 7 WUG member roles. Use the /oshihen command to get the role you want.\n\n'
     for oshi in hkd.WUG_ROLE_IDS:
         description += '**/oshihen** {0} for {1.mention}\n'.format(
             oshi.title(), hkd.get_wug_role(ctx.guild, oshi))
     description += "\nNote that using **/oshihen** will remove all of your existing member roles. To get an extra role without removing existing ones, use **/oshimashi** *member* instead. To get all 7 roles, use **/hakooshi**. Use **/kamioshi** *member* to specify which member you want to set as your highest role (you will get that member's colour).\n\n"
     description += 'Use **/oshi-count** to show the number of members with each WUG member role, or **/kamioshi-count** to show the number of members with each WUG member role as their highest role.\n'
     await ctx.send(content='**Commands for Roles**',
                    embed=hkd.create_embed(description=description))
Exemplo n.º 15
0
 async def events(self, ctx: SlashContext):
     await ctx.defer()
     embed_fields = []
     embed_fields.append((
         '/events *date*',
         'Get information for events involving WUG members on the specified date, e.g. **/events** apr 1. If *date* not specified, finds events happening today.'
     ))
     embed_fields.append((
         '/eventsin *month* *member*',
         'Get information for events involving WUG members for the specified month and member, e.g. **/eventsin** April Mayushii. If *member* not specified, searches for Wake, Up Girls! related events instead. Searches events from this month onwards only.'
     ))
     await ctx.send(content='**Commands for Searching Events**',
                    embed=hkd.create_embed(fields=embed_fields))
Exemplo n.º 16
0
 async def serverinfo(self, ctx: SlashContext):
     await ctx.defer()
     guild = ctx.guild
     embed_fields = []
     embed_fields.append(('{0}'.format(guild.name), '(ID: {0})'.format(guild.id)))
     embed_fields.append(('Owner', '{0} (ID: {1})'.format(guild.owner, guild.owner.id)))
     embed_fields.append(('Members', '{0}'.format(guild.member_count)))
     embed_fields.append(('Channels', '{0} text, {1} voice'.format(len(guild.text_channels), len(guild.voice_channels))))
     embed_fields.append(('Roles', '{0}'.format(len(guild.roles))))
     embed_fields.append(('Created On', '{0:%Y}-{0:%m}-{0:%d} {0:%H}:{0:%M}:{0:%S} UTC'.format(guild.created_at)))
     embed_fields.append(('Region', '{0}'.format(guild.region)))
     embed_fields.append(('Icon', '{0}'.format('<{0}>'.format(guild.icon_url) if guild.icon_url else 'None')))
     await ctx.send(content='**Server Information**', embed=hkd.create_embed(fields=embed_fields, inline=True))
Exemplo n.º 17
0
 async def blogpics(self, ctx: SlashContext, url: str):
     await ctx.defer()
     pics, vid_ids = hkd.get_media_from_blog_post(
         url.replace('//gamp.ameblo.jp/', '//ameblo.jp/'))
     if len(pics) <= 1 and not vid_ids:
         await ctx.send(embed=hkd.create_embed(
             description="Couldn't find any images.", colour=Colour.red()))
     if len(pics) > 1:
         await hkd.send_content_with_delay(ctx, pics[1:])
     for vid_id in vid_ids:
         video_file = './{0}.mp4'.format(vid_id)
         video_link = 'https://static.blog-video.jp/output/hq/{0}.mp4'.format(
             vid_id)
         urlretrieve(video_link, video_file)
         await hkd.send_video_check_filesize(ctx, video_file, video_link)
Exemplo n.º 18
0
 async def aichan_blogpics(self, ctx: SlashContext):
     await ctx.defer()
     pics, vid_ids = hkd.get_media_from_blog_post(
         'https://ameblo.jp/eino-airi/')
     if not pics and not vid_ids:
         await ctx.send(embed=hkd.create_embed(
             description="Couldn't find any images.", colour=Colour.red()))
         return
     await hkd.send_content_with_delay(ctx, pics)
     for vid_id in vid_ids:
         video_file = './{0}.mp4'.format(vid_id)
         video_link = 'https://static.blog-video.jp/output/hq/{0}.mp4'.format(
             vid_id)
         urlretrieve(video_link, video_file)
         await hkd.send_video_check_filesize(ctx, video_file, video_link)
Exemplo n.º 19
0
 async def check_instagram_stories(self):
     channel = hkd.get_updates_channel(self.bot.guilds)
     with suppress(Exception):
         instaloader_args = ['instaloader', '--login={0}'.format(self.config['instagram_user']), '--sessionfile=./.instaloader-session', '--quiet', '--dirname-pattern={profile}', '--filename-pattern={profile}_{mediaid}', ':stories']
         proc = subprocess.Popen(args=instaloader_args)
         while proc.poll() is None:
             await asyncio.sleep(1)
         for instagram_id in self.firebase_ref.child('last_instagram_stories').get().keys():
             if not os.path.isdir(instagram_id):
                 continue
             story_videos = [v for v in os.listdir(instagram_id) if v.endswith('.mp4')]
             last_story_id = int(self.firebase_ref.child('last_instagram_stories/{0}'.format(instagram_id)).get())
             uploaded_story_ids = []
             stories_to_upload = []
             for vid in story_videos:
                 video_id = int(vid[:-4].split('_')[-1])
                 if video_id > last_story_id:
                     stories_to_upload.append(vid)
                     uploaded_story_ids.append(video_id)
             story_pics = [p for p in os.listdir(instagram_id) if p.endswith('.jpg')]
             for pic in story_pics:
                 pic_id = int(pic[:-4].split('_')[-1])
                 if pic_id > last_story_id and pic_id not in uploaded_story_ids:
                     stories_to_upload.append(pic)
                     uploaded_story_ids.append(pic_id)
             if uploaded_story_ids:
                 profile = Profile.from_username(self.insta_api.context, instagram_id)
                 user_name = profile.full_name
                 if instagram_id in hkd.WUG_INSTAGRAM_IDS.values():
                     colour = hkd.get_oshi_colour(hkd.get_wug_guild(self.bot.guilds), hkd.dict_reverse(hkd.WUG_INSTAGRAM_IDS)[instagram_id])
                 else:
                     colour = Colour(0x242424)
                 author = {}
                 author['name'] = '{0} (@{1})'.format(user_name, instagram_id)
                 author['url'] = 'https://www.instagram.com/{0}/'.format(instagram_id)
                 author['icon_url'] = profile.profile_pic_url
                 story_link = 'https://www.instagram.com/stories/{0}/'.format(instagram_id)
             first_upload = True
             for story in sorted(stories_to_upload):
                 if first_upload:
                     await channel.send(embed=hkd.create_embed(author=author, title='Instagram Story Updated by {0}'.format(user_name), colour=colour, url=story_link))
                     first_upload = False
                 await channel.send(file=File('./{0}/{1}'.format(instagram_id, story)))
             if uploaded_story_ids:
                 self.firebase_ref.child('last_instagram_stories/{0}'.format(instagram_id)).set(str(max(uploaded_story_ids)))
     self.check_instagram.change_interval(minutes=random.randint(30, 50))
Exemplo n.º 20
0
 async def check_tweets(self):
     channel = hkd.get_updates_channel(self.bot.guilds)
     with suppress(Exception):
         twitter_user_ids = self.firebase_ref.child('last_userid_tweets').get().keys()
         for user_id_str in twitter_user_ids:
             user_id = int(user_id_str)
             last_tweet_id = int(self.firebase_ref.child('last_userid_tweets/{0}'.format(user_id)).get())
             posted_tweets = []
             tweets = self.twitter_api.GetUserTimeline(user_id=user_id, since_id=last_tweet_id, count=40, include_rts=False)
             for tweet in reversed(tweets):
                 user = tweet.user
                 name = user.name
                 username = user.screen_name
                 if tweet.in_reply_to_user_id and str(tweet.in_reply_to_user_id) not in twitter_user_ids:
                     continue
                 await asyncio.sleep(0.5)
                 tweet_id = tweet.id
                 posted_tweets.append(tweet_id)
                 tweet_content = unescape(tweet.full_text)
                 if user_id in hkd.WUG_TWITTER_IDS.values():
                     colour = hkd.get_oshi_colour(hkd.get_wug_guild(self.bot.guilds), hkd.dict_reverse(hkd.WUG_TWITTER_IDS)[user_id])
                 else:
                     colour = Colour(0x242424)
                 author = {}
                 author['name'] = '{0} (@{1})'.format(name, username)
                 author['url'] = 'https://twitter.com/{0}'.format(username)
                 author['icon_url'] = user.profile_image_url_https
                 image = ''
                 if (expanded_urls := tweet.urls) and (expanded_url := expanded_urls[0].expanded_url) and hkd.is_blog_post(expanded_url):
                     soup = hkd.get_html_from_url(expanded_url)
                     blog_entry = soup.find(attrs={'class': 'skin-entryBody'})
                     if blog_images := [p['src'] for p in blog_entry.find_all('img') if '?caw=' in p['src'][-9:]]:
                         image = blog_images[0]
                 if media := tweet.media:
                     image = media[0].media_url_https
                 await channel.send(embed=hkd.create_embed(author=author, title='Tweet by {0}'.format(name), description=tweet_content, colour=colour, url='https://twitter.com/{0}/status/{1}'.format(username, tweet_id), image=image))
Exemplo n.º 21
0
 async def onmusu(self, ctx: SlashContext, member: str = ''):
     await ctx.defer()
     char, char_colour = hkd.WUG_ONMUSU_CHARS[hkd.parse_oshi_name(member)]
     profile_link = 'https://onsen-musume.jp/character/{0}'.format(char)
     soup = hkd.get_html_from_url(profile_link)
     char_pic = 'https://onsen-musume.jp{0}'.format(soup.find('div', class_='character_ph__main').find('img')['src'])
     serifu = soup.find('div', class_='character_ph__serif').find('img')['alt']
     char_main = soup.find('div', class_='character_post__main')
     char_name = char_main.find('img')['alt']
     seiyuu = char_main.find('h2').find('img')['alt'][3:7]
     char_catch = char_main.find('p', class_='character_post__catch').contents[0]
     embed_fields = []
     for item in char_main.find('ul', class_='character_profile').find_all('li'):
         for i, entry in enumerate(item.find_all('span')):
             embed_fields.append((entry.contents[0], item.contents[(i + 1) * 2][1:]))
     soup = hkd.get_html_from_url('https://onsen-musume.jp/character/')
     thumbnail = 'https://onsen-musume.jp{0}'.format(soup.find('li', class_='character-list__item02 {0}'.format(char)).find('img')['src'])
     author = {}
     author['name'] = char_name
     author['url'] = profile_link
     author['icon_url'] = 'https://onsen-musume.jp/wp/wp-content/themes/onsenmusume/pc/assets/img/character/thumb/list/yu_icon.png'
     footer = {}
     footer['text'] = serifu
     await ctx.send(embed=hkd.create_embed(author=author, title='CV: {0}'.format(seiyuu), description=char_catch, colour=Colour(char_colour), image=char_pic, thumbnail=thumbnail, fields=embed_fields, footer=footer, inline=True))
Exemplo n.º 22
0
 async def userinfo(self, ctx: SlashContext, member: Member = None):
     await ctx.defer()
     user = member or ctx.author
     embed_fields = []
     embed_fields.append(('Name', '{0}'.format(user.display_name)))
     embed_fields.append(('ID', '{0}'.format(user.id)))
     embed_fields.append(('Joined Server', '{0:%Y}-{0:%m}-{0:%d} {0:%H}:{0:%M}:{0:%S} UTC'.format(user.joined_at)))
     embed_fields.append(('Account Created', '{0:%Y}-{0:%m}-{0:%d} {0:%H}:{0:%M}:{0:%S} UTC'.format(user.created_at)))
     embed_fields.append(('Roles', '{0}'.format(', '.join([r.name for r in user.roles[1:]]) if user.roles[1:] else 'None')))
     embed_fields.append(('Avatar', '{0}'.format('<{0}>'.format(user.avatar_url) if user.avatar_url else 'None')))
     await ctx.send(content='**User Information for {0.mention}**'.format(user), embed=hkd.create_embed(fields=embed_fields, inline=True))
Exemplo n.º 23
0
 with suppress(Exception):
     ytdl_opts = {'outtmpl': '%(id)s.%(ext)s'}
     with youtube_dl.YoutubeDL(ytdl_opts) as ytdl:
         result = ytdl.extract_info(url)
 if not (vid_ids := hkd.get_ids_from_ytdl_result(result)):
     await ctx.send(embed=hkd.create_embed(title='Failed to download video.', colour=Colour.red()))
     return
 if not (files := [f for f in os.listdir('.') if os.path.isfile(f) and f.startswith(vid_ids[0])]):
     for _ in range(3):
         with suppress(Exception):
             ytdl_opts = {'outtmpl': '%(id)s.%(ext)s', 'proxy': hkd.get_random_proxy()}
             with youtube_dl.YoutubeDL(ytdl_opts) as ytdl:
                 result = ytdl.extract_info(url)
                 break
 if not (files := [f for f in os.listdir('.') if os.path.isfile(f) and f.startswith(vid_ids[0])]):
     await ctx.send(embed=hkd.create_embed(title='Failed to download video.', colour=Colour.red()))
     return        
 for vid_id in vid_ids:
     if (files := [f for f in os.listdir('.') if os.path.isfile(f) and f.startswith(vid_id)]):
         vid_filename = files[0]
         if os.path.getsize(vid_filename) < ctx.guild.filesize_limit:
             await ctx.send(file=File(vid_filename))
             with suppress(Exception):
                 os.remove(vid_filename)
         else:
             proc = subprocess.Popen(args=['python', 'gdrive_upload.py', vid_filename, self.config['uploads_folder']])
             while proc.poll() is None:
                 await asyncio.sleep(1)
             if proc.returncode != 0:
                 await ctx.send(embed=hkd.create_embed(title='Failed to upload video to Google Drive.', colour=Colour.red()))
                 with suppress(Exception):
Exemplo n.º 24
0
            )
        ]
    )
    @commands.guild_only()
    async def update(self, ctx: SlashContext, name: str):
        await ctx.defer()
        if len(split_update := name.split()) > 1:
            tag_name = split_update[0]
            updated_content = name[len(tag_name) + 1:]
            if tag_name in self.firebase_ref.child('tags').get():
                self.firebase_ref.child('tags/{0}'.format(tag_name)).set(updated_content)
                await ctx.send(embed=hkd.create_embed(title='Successfully updated tag - {0}.'.format(tag_name)))
            else:
                await ctx.send(embed=hkd.create_embed(title="That tag doesn't exist."))
            return
        await ctx.send(embed=hkd.create_embed(description="Couldn't update tag.", colour=Colour.red()))

    @cog_ext.cog_subcommand(
        base="tag",
        description="Delete a tag.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="name",
                description="Name of the tag to delete.",
                option_type=3,
                required=True
            )
        ]
    )
    @commands.guild_only()
Exemplo n.º 25
0
 async def events(self, ctx: SlashContext, date: str = ''):
     await ctx.defer()
     event_urls = []
     current_time = datetime.now(timezone('Japan'))
     search_date = parser.parse(date) if date else current_time
     if current_time.month > search_date.month or current_time.month == search_date.month and current_time.day > search_date.day:
         search_year = current_time.year + 1
     else:
         search_year = current_time.year
     first = True
     for _ in range(3):
         with suppress(Exception):
             soup = hkd.get_html_from_url(
                 'https://www.eventernote.com/events/month/{0}-{1}-{2}/1?limit=1000'
                 .format(search_year, search_date.month, search_date.day))
             result = soup.find_all(
                 attrs={'class': ['date', 'event', 'actor', 'note_count']})
             for event in [
                     result[i:i + 4] for i in range(0, len(result), 4)
             ]:
                 info = event[1].find_all('a')
                 event_time = event[1].find('span')
                 if (event_url := info[0]['href']) not in event_urls:
                     performers = [
                         p.contents[0] for p in event[2].find_all('a')
                     ]
                     wug_performers = [
                         p for p in performers if p in hkd.WUG_MEMBERS
                     ]
                     if not wug_performers:
                         continue
                     colour = hkd.get_oshi_colour(
                         ctx.guild,
                         list(hkd.WUG_ROLE_IDS.keys())
                         [hkd.WUG_MEMBERS.index(wug_performers[0]) -
                          1]) if len(
                              wug_performers) == 1 else Colour.teal()
                     if first:
                         first = False
                         await ctx.send(
                             '**Events Involving WUG Members on {0:%Y}-{0:%m}-{0:%d} ({0:%A})**'
                             .format(search_date.replace(year=search_year)))
                         await asyncio.sleep(0.5)
                     other_performers = [
                         p for p in performers if p not in hkd.WUG_MEMBERS
                         and p not in hkd.WUG_OTHER_UNITS
                     ]
                     embed_fields = []
                     embed_fields.append(('Location', info[1].contents[0]))
                     embed_fields.append(
                         ('Time', event_time.contents[0]
                          if event_time else 'To be announced'))
                     embed_fields.append(
                         ('WUG Members', ', '.join(wug_performers)))
                     embed_fields.append(
                         ('Other Performers', ', '.join(other_performers)
                          if other_performers else 'None'))
                     embed_fields.append(('Eventernote Attendees',
                                          event[3].find('p').contents[0]))
                     event_urls.append(event_url)
                     await asyncio.sleep(0.5)
                     await ctx.send(embed=hkd.create_embed(
                         title=info[0].contents[0],
                         colour=colour,
                         url='https://www.eventernote.com{0}'.format(
                             event_url),
                         thumbnail=event[0].find('img')['src'],
                         fields=embed_fields,
                         inline=True))
             break
Exemplo n.º 26
0
 if (search_month := hkd.parse_month(month)) == 'None':
     await ctx.send(embed=hkd.create_embed(
         description=
         "Couldn't find any events. Please follow this format for searching for events: **/eventsin** April Mayushii.",
         colour=Colour.red()))
     return
 current_time = datetime.now(timezone('Japan'))
 search_year = str(current_time.year if current_time.
                   month <= int(search_month) else current_time.year +
                   1)
 search_index = [0]
 wug_names = list(hkd.WUG_ROLE_IDS.keys())
 if member:
     if hkd.parse_oshi_name(member) not in wug_names:
         await ctx.send(embed=hkd.create_embed(
             description=
             "Couldn't find any events. Please follow this format for searching for events: **/eventsin** April Mayushii.",
             colour=Colour.red()))
         return
     search_index = [wug_names.index(hkd.parse_oshi_name(member)) + 1]
 event_urls = []
 first = True
 search_start = False
 for i in search_index:
     for _ in range(3):
         with suppress(Exception):
             soup = hkd.get_html_from_url(
                 'https://www.eventernote.com/actors/{0}/{1}/events?actor_id={1}&limit=5000'
                 .format(quote(hkd.WUG_MEMBERS[i]),
                         hkd.WUG_EVENTERNOTE_IDS[i]))
             result = soup.find_all(attrs={
                 'class': ['date', 'event', 'actor', 'note_count']
Exemplo n.º 27
0
 async def search(self, ctx: SlashContext):
     await ctx.defer()
     tag_list = self.firebase_ref.child('tags').get()
     await ctx.send(content='Existing Tags', embed=hkd.create_embed(title=', '.join(list(tag_list.keys()))))
Exemplo n.º 28
0
class Misc(commands.Cog):
    def __init__(self, bot, config):
        self.bot = bot
        self.config = config

    @cog_ext.cog_slash(
        description="Translate the provided Japanese text into English via Google Translate.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="text",
                description="The text to translate.",
                option_type=3,
                required=True
            )
        ]
    )
    async def translate(self, ctx: SlashContext, text: str):
        await ctx.defer()
        await ctx.send(embed=hkd.create_embed(description=Translator().translate(text, src='ja', dest='en').text))

    @cog_ext.cog_slash(
        description="Convert currency from one type to another.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="conversion",
                description="Convert amount of currency-a to currency-b.",
                option_type=3,
                required=True
            )
        ]
    )
    async def currency(self, ctx: SlashContext, conversion: str):
        await ctx.defer()
        conversion_split = conversion.split()
        if len(conversion_split) == 4 and conversion_split[2].lower() == 'to':
            with suppress(Exception):
                result = CurrencyRates().convert(conversion_split[1].upper(), conversion_split[3].upper(), Decimal(conversion_split[0]))
                await ctx.send(embed=hkd.create_embed(title='{0} {1}'.format('{:f}'.format(result).rstrip('0').rstrip('.'), conversion_split[3].upper())))
                return
        await ctx.send(embed=hkd.create_embed(description="Couldn't convert. Please follow this format for converting currency: **/currency** 12.34 AUD to USD.", colour=Colour.red()))

    @cog_ext.cog_slash(
        description="Show weather information for the specified location.",
        guild_ids=hkd.get_all_guild_ids(),
        options=[
            create_option(
                name="location",
                description="The location to show the weather for.",
                option_type=3,
                required=True
            )
        ]
    )
    async def weather(self, ctx: SlashContext, location: str):
        await ctx.defer()
        if len(query := location.split(',')) > 1:
            with suppress(Exception):
                query[1] = countries.get(name=query[1].strip().title()).alpha_2
        with suppress(Exception):
            result = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': ','.join(query), 'APPID': self.config['weather_api_key']}).json()
            timezone = pytz.timezone(TimezoneFinder().timezone_at(lat=result['coord']['lat'], lng=result['coord']['lon']))
            embed_fields = []
            embed_fields.append(('Weather', '{0}'.format(result['weather'][0]['description'].title())))
            embed_fields.append(('Temperature', '{0} °C, {1} °F'.format('{0:.2f}'.format(float(result['main']['temp']) - 273.15), '{0:.2f}'.format((1.8 * (float(result['main']['temp']) - 273.15)) + 32.0))))
            embed_fields.append(('Humidity', '{0}%'.format(result['main']['humidity'])))
            embed_fields.append(('Wind Speed', '{0} m/s'.format(result['wind']['speed'])))
            embed_fields.append(('Sunrise', '{0:%I}:{0:%M} {0:%p}'.format(datetime.fromtimestamp(result['sys']['sunrise'], tz=timezone))))
            embed_fields.append(('Sunset', '{0:%I}:{0:%M} {0:%p}'.format(datetime.fromtimestamp(result['sys']['sunset'], tz=timezone))))
            embed_fields.append(('Pressure', '{0} hPa'.format(result['main']['pressure'])))
            await ctx.send(content='**Weather for {0}, {1}**'.format(result['name'], countries.lookup(result['sys']['country']).name), embed=hkd.create_embed(fields=embed_fields, inline=True))
            return
        await ctx.send(embed=hkd.create_embed(description="Couldn't get weather. Please follow this format for checking the weather: **/weather** Melbourne, Australia.", colour=Colour.red()))
Exemplo n.º 29
0
 async def translate(self, ctx: SlashContext, text: str):
     await ctx.defer()
     await ctx.send(embed=hkd.create_embed(description=Translator().translate(text, src='ja', dest='en').text))
Exemplo n.º 30
0
                          choices=hkd.get_member_choices())
        ])
    @commands.guild_only()
    async def oshimashi(self, ctx: SlashContext, member: str = ''):
        await ctx.defer()
        if not (role := hkd.get_wug_role(ctx.guild, member)):
            await ctx.send(embed=hkd.create_embed(
                description=
                "Couldn't find that role. Use **/help roles** to show additional help on how to get roles.",
                colour=Colour.red()))
            return
        if role not in ctx.author.roles:
            await ctx.author.add_roles(role)
            await ctx.send(embed=hkd.create_embed(
                description=
                'Hello {0.author.mention}, you now have the **{1}** oshi role {2.mention}.'
                .format(ctx, member.title(), role),
                colour=role.colour))
        else:
            await ctx.send(embed=hkd.create_embed(
                description=
                'Hello {0.author.mention}, you already have that role.'.format(
                    ctx),
                colour=Colour.red()))

    @cog_ext.cog_slash(
        description="Get all WUG member roles.",
        guild_ids=hkd.get_all_guild_ids(),
    )
    @commands.guild_only()
    async def hakooshi(self, ctx: SlashContext):