def _music(self):
        """
        Command /music
        Gets the links sent by all the users of the chat in the last week
        and group them by user>links
        """
        days = 7
        now = datetime.datetime.now()
        last_week_timedelta = datetime.timedelta(days=days)

        last_week_links = defaultdict(list)

        try:
            username = self.command_args[0]
            username = username.replace('@', '')
            links = Link.select() \
                .join(Chat, on=(Chat.id == Link.chat)) \
                .join(User, on=(User.id == Link.user)) \
                .where((Chat.id == self.update.message.chat_id) & (User.username == username)) \
                .where((Link.created_at >= now - last_week_timedelta) | (Link.updated_at >= now - last_week_timedelta)) \
                .order_by(Link.updated_at.asc(), Link.created_at.asc())

        except IndexError:
            links = Link.select() \
                .join(Chat) \
                .where(Chat.id == self.update.message.chat_id) \
                .where((Link.created_at >= now - last_week_timedelta) | (Link.updated_at >= now - last_week_timedelta)) \
                .order_by(Link.updated_at.asc(), Link.created_at.asc())

        for link in links:
            last_week_links[link.user].append(link)
        last_week_links = dict(last_week_links)

        self.responser.reply_music(last_week_links)
示例#2
0
 def _build_message(last_week_links):
     msg = '<strong>Music from the last week:</strong> \n'
     for user, sent_links in last_week_links.items():
         msg += '- {} <strong>{}:</strong>\n'.format(emojis.EMOJI_USER, user)
         for sent_link in sent_links:
             link = sent_link.get('link')
             genres = Link.get_genres(link)
             msg += '    {} <a href="{}">{}</a> {}\n'.format(
                 emojis.get_music_emoji(link.get('link_type')),
                 link.get('url'),
                 Link.get_name(link),
                 '({})'.format(', '.join(genres)) if genres else ''
             )
         msg += '\n'
     return msg
    def _music_from_beginning(self):
        """
        Command /music_from_beginning @username
        Gets the links sent by an specific username of the chat from the beginning
        """
        all_time_links = defaultdict(list)

        try:
            username = self.command_args[0]
            username = username.replace('@', '')
        except IndexError:
            self.responser.error_music_from_beginning_no_username()
            return

        links = Link.select() \
            .join(Chat, on=(Chat.id == Link.chat)) \
            .join(User, on=(User.id == Link.user)) \
            .where((Chat.id == self.update.message.chat_id) & (User.username == username)) \
            .order_by(Link.updated_at.asc(), Link.created_at.asc())

        if len(links) == 0:
            self.responser.error_no_links_found(username)
            return

        for link in links:
            all_time_links[link.user].append(link)
        all_time_links = dict(all_time_links)

        self.responser.reply_music_from_beginning(all_time_links)
示例#4
0
 def _build_message(all_time_links):
     msg = '<strong>Music from the beginning of time:</strong> \n'
     for user, sent_links in all_time_links.items():
         msg += '- {} <strong>{}:</strong>\n'.format(emojis.EMOJI_USER, user)
         for sent_link in sent_links:
             link = sent_link.get('link')
             genres = Link.get_genres(link)
             msg += '    {}  <a href="{}">{}</a> {}\n'.format(
                 emojis.get_music_emoji(link.get('link_type')),
                 f'[{datetime.datetime.fromisoformat(sent_link.get("sent_at")).strftime(OUTPUT_DATE_FORMAT)}]',
                 link.get('url'),
                 Link.get_name(link),
                 '({})'.format(', '.join(genres)) if genres else ''
             )
         msg += '\n'
     return msg
示例#5
0
 def _build_message(all_time_links):
     msg = '<strong>Music sent in all your chats from the beginning of time:</strong> \n'
     for sent_link in all_time_links:
         link = sent_link.get('link')
         genres = Link.get_genres(link)
         msg += '    {}  {} <a href="{}">{}</a> {}\n'.format(
             emojis.get_music_emoji(link.get('type')),
             '[{}@{}]'.format(
                 datetime.datetime.fromisoformat(sent_link.get('sent_at')).strftime(OUTPUT_DATE_FORMAT),
                 sent_link.get('chat').get('name')
             ),
             link.get('url'),
             Link.get_name(link),
             '({})'.format(', '.join(genres)) if genres else ''
         )
     msg += '\n'
     return msg
    def _save_link(self, cleaned_url, link_type, user, chat):
        # Update the link if it exists for a chat, create if it doesn't exist
        link = Link.get_or_none((Link.url == cleaned_url)
                                & (Link.chat == chat))
        was_updated = False
        if link is not None:
            # If link already exists, set updated_at and last_update_user to current
            link.apply_update(user)
            link.save()
            was_updated = True
            Logger.log_db_operation(Logger.DBOperation.UPDATE, link)
        else:
            link = Link.create(url=cleaned_url,
                               link_type=link_type.value,
                               created_at=datetime.datetime.now(),
                               user=user,
                               chat=chat)
            Logger.log_db_operation(Logger.DBOperation.CREATE, link)

        return link, was_updated
示例#7
0
 def get_keyboard_markup(cls, saved_links):
     keyboard = []
     for saved_link in saved_links:
         link = saved_link.get('link')
         keyboard.append([InlineKeyboardButton(
             Link.get_name(link), callback_data=f'{cls.CALLBACK_NAME}:{saved_link.get("id")}'
         )])
     keyboard.append([InlineKeyboardButton(
         'Cancel', callback_data=f'{cls.CALLBACK_NAME}:'
     )])
     return InlineKeyboardMarkup(keyboard)
示例#8
0
    def _build_message(saved_links_response: {}):
        if not saved_links_response:
            return 'You have not saved links'

        msg = '<strong>Saved links:</strong> \n'
        for saved_link in saved_links_response:
            link = saved_link.get('link')
            genres = Link.get_genres(link)
            msg += f'- {emojis.get_music_emoji(link.get("link_type"))} <a href="{link.get("url")}">{Link.get_name(link)}</a> ' \
                   f'({", ".join(genres) if genres else ""}). ' \
                   f'Saved at: {datetime.datetime.fromisoformat(saved_link.get("saved_at")).strftime(OUTPUT_DATE_FORMAT)}\n'
        return msg
示例#9
0
    def _build_message(self, sent_link: OrderedDict):
        from bot.commands import NowPlayingCommand
        msg = '<strong>Saved: </strong>'
        link = sent_link.get('link')
        genres = ', '.join(Link.get_genres(link))

        if link.get('link_type') == LinkType.ARTIST.value:
            msg += '{} <strong>{}</strong>\n'.format(
                emojis.EMOJI_ARTIST,
                link.get('artist').get('name'))
        elif link.get('link_type') == LinkType.ALBUM.value:
            msg += '{} <strong>{}</strong> - <strong>{}</strong>\n'.format(
                emojis.EMOJI_ALBUM,
                link.get('album').get('artists')[0].get('name'),
                link.get('album').get('name'))
        elif link.get('link_type') == LinkType.TRACK.value:
            msg += '{} {} by <strong>{}</strong>\n'.format(
                emojis.EMOJI_TRACK,
                link.get('track').get('name'),
                link.get('track').get('artists')[0].get('name'),
            )
        # Only show the link if the processed url comes from a /np command
        if isinstance(self.command, NowPlayingCommand):
            msg += f'{link.get("url")} \n'

        msg += '<strong>Genres:</strong> {}'.format(
            genres if genres else 'N/A')
        save_link_button_keyboard_markup = SaveLinkButton.get_keyboard_markup(
            link.get('id'))
        preview_track = sent_link.get('spotify_preview_track', None)
        if preview_track and preview_track.get('preview_url'):
            performer = preview_track.get('artists')[0].get('name', 'unknown')
            title = preview_track.get('name', 'unknown')
            self.reply(update=self.update,
                       context=self.context,
                       message=msg,
                       reply_type=ReplyType.AUDIO,
                       audio=preview_track.get('preview_url'),
                       title=title,
                       performer=performer,
                       reply_markup=save_link_button_keyboard_markup)
        else:
            self.reply(self.update,
                       self.context,
                       msg,
                       reply_markup=save_link_button_keyboard_markup)