示例#1
0
 def generic_user_data(self,
                       username,
                       title_template="{}",
                       guild=None,
                       **kwargs):
     user_data = self.get_user(username, guild)
     username = user_data["name"]
     if username is None:
         raise CommandError(
             "User should set a last.fm account using ``fm.username``")
     inline = {
         "Playcount":
         user_data["playcount"],
         "Registered":
         strftime(
             "%Y-%m-%d %H:%M",
             gmtime(user_data["registered"]["#text"]),
         ),
     }
     fm_embed = bot.generic_embed_values(
         title=title_template.format(user_data["name"]),
         url=user_data["url"],
         thumbnail=user_data["image"][len(user_data["image"]) - 1]["#text"],
         inlines=inline,
         skip_inlines="N/A",
         **kwargs,
     )
     return fm_embed, user_data["name"]
示例#2
0
 def on_alias_list_command(self, event, target=None):
     """
     Last.fm Used to get a list of a user's aliases in a guild.
     When no arguments are given, this will return the author's aliases.
     Otherwise, this accepts one argument (a target user's @, ID or alias) and will return a list of the target's alises.
     """
     if event.channel.is_dm:
         api_loop(
             event.channel.send_message,
             "Alias commands are guild specific.",
         )
     else:
         if target is None:
             target = event.author.id
         else:
             try:
                 target = AT_to_id(target)
             except CommandError as e:
                 data = handle_sql(
                     db_session.query(aliases).filter(
                         aliases.guild_id == event.guild.id,
                         aliases.alias.like(target),
                     ).first)
                 if data is None:
                     raise CommandError(
                         "User alias not found in this guild.")
                 else:
                     target = data.user_id
         data = handle_sql(
             db_session.query(aliases).filter_by(
                 user_id=target,
                 guild_id=event.guild.id,
             ).all)
         user = self.client.api.guilds_members_get(event.guild.id, target)
         if data:
             inline = {
                 str(index + 1): alias.alias
                 for index, alias in enumerate(data)
             }
             embed = bot.generic_embed_values(
                 title="{}'s aliases in {}".format(
                     user.name,
                     event.guild.name,
                 ),
                 non_inlines=inline,
             )
             api_loop(
                 event.channel.send_message,
                 embed=embed,
             )
         else:
             api_loop(
                 event.channel.send_message,
                 "User doesn't have any aliases set in this guild.",
             )
示例#3
0
 def on_help_command(self, event, command=None):
     """
     Miscellaneous Get a list of the commands in a module.
     If arg is passed, will try to return the info for the relevant command.
     Otherwise, it will just return a list of all the enabled commands.
     """
     if not event.channel.is_dm:
         channel = api_loop(event.author.open_dm)
     else:
         channel = event.channel
     if command is None:
         for help_embed in bot.help_embeds.values():
             dm_default_send(event, channel, embed=help_embed)
     else:
         command_obj = bot.commands_dict.get(command, None)
         if command_obj:
             if command_obj.raw_args is not None:
                 args = " " + command_obj.raw_args + ";"
             else:
                 args = str()
             docstring = command_obj.get_docstring().replace("    ",
                                                             "").strip("\n")
             embed = bot.generic_embed_values(
                 title="{}{}{} a command in the {} module.".format(
                     self.command_prefix,
                     str(command_obj.triggers).replace("[", "(").replace(
                         "'", "**").replace(",", " |").replace("]", ")") +
                     ":", args,
                     docstring.split(" ", 1)[0]),
                 url=bot.local.embed_values.url,
                 description=docstring.split(" ", 1)[1],
             )
             dm_default_send(event, channel, embed=embed)
         else:
             dm_default_send(
                 event,
                 channel,
                 content="``{}`` command not found.".format(command),
             )
     user_info = handle_sql(
         db_session.query(users).filter_by(user_id=event.author.id).first, )
     if user_info is None or user_info.last_username is None:
         dm_default_send(
             event,
             channel,
             content=
             "To get started with this bot, you can set your default last.fm username using the command ``{}username <username>``."
             .format(self.command_prefix),
         )
示例#4
0
 def search_embed(self,
                  data: dict,
                  index: int,
                  names: list,
                  name_format: str,
                  values: list,
                  value_format: str,
                  item: str = "item",
                  url_index: list = ("url", ),
                  thumbnail_index: list = ("image", -1, "#text"),
                  limit: int = 5,
                  **kwargs):  # "last"
     non_inlines = dict()
     if len(data) - index < limit:
         limit = len(data) - index
     for x in range(limit):
         current_index = index + x
         braces = name_format.count("{}")
         current_name = self.replace_reg.sub(
             str(current_index + 1),
             name_format[:],
             1,
         )
         current_value = value_format[:]
         for index_list in names:
             current_name = self.replace_reg.sub(
                 get_dict_item(data[current_index], index_list),
                 current_name,
                 1,
             )
         for index_list in values:
             current_value = self.replace_reg.sub(
                 get_dict_item(
                     data[current_index],
                     index_list,
                 ),
                 current_value,
                 1,
             )
         non_inlines[current_name] = current_value
     return bot.generic_embed_values(
         title="{} results.".format(item),
         url=get_dict_item(data[index], url_index),
         thumbnail=get_dict_item(data[index], thumbnail_index),
         non_inlines=non_inlines,
         **kwargs,
     )
示例#5
0
 def on_artist_command(self, event, artist):
     """
     Last.fm Get an artist's info on Last.fm.
     """
     artist_info = self.get_artist(artist)
     inline = {
         "Listeners": artist_info["stats"]["listeners"],
         "Play Count": artist_info["stats"]["playcount"],
         "On-Tour": str(bool(artist_info["ontour"])),
     }
     artist_embed = bot.generic_embed_values(
         title=artist_info["name"],
         url=artist_info["url"],
         thumbnail=artist_info["image"][len(artist_info["image"]) -
                                        1]["#text"],
         inlines=inline,
         skip_inlines="N/A",
     )
     api_loop(event.channel.send_message, embed=artist_embed)
示例#6
0
 def on_lyrics_command(self, event, content):
     """
     Api Return lyrics for a song.
     """
     self.pre_check("google_key", "google_cse_engine_ID")
     first_message = api_loop(
         event.channel.send_message,
         "Searching for lyrics...",
     )
     title, lyrics = get_lyrics(
         self.google_key,
         self.google_cse_engine_ID,
     ).get_lyrics(quote_plus(content))
     if len(lyrics) > 46300:
         return first_message.edit("I doubt that's a song.")
     if not lyrics:
         return first_message.edit("No Lyrics found for ``{}``".format(
             sanitize(
                 content,
                 escape_codeblocks=True,
             )
         ))
     lyrics_embed = bot.generic_embed_values(
         title=title,
         footer_text="Requested by {}".format(event.author),
         footer_img=event.author.get_avatar_url(size=32),
         timestamp=event.msg.timestamp.isoformat(),
     )
     first_message.delete()
     responses = 1
     while lyrics and responses < 4:
         lyrics_embed.description = lyrics[:2048]
         lyrics = lyrics[2048:]
         if lyrics:
             tmp_to_shift = lyrics_embed.description.splitlines()[-1]
             lyrics = tmp_to_shift + lyrics
             lyrics_embed.description = lyrics_embed.description[
                 :-len(tmp_to_shift)
             ]
         api_loop(event.channel.send_message, embed=lyrics_embed)
         responses += 1
示例#7
0
 def friends_search(self, data, index, author, limit=5, **kwargs):
     embed = bot.generic_embed_values(**kwargs)
     if len(data) - index < limit:
         limit = len(data) - index
     for x in range(limit):
         current_index = index + x
         while True:
             user = self.state.users.get(int(data[current_index]))
             if user is not None:
                 user = str(user)
             else:
                 user = data[current_index]
             try:
                 friend = self.get_user_info(data[current_index])
             except CommandError:
                 handle_sql(
                     db_session.query(friends).filter_by(
                         master_id=author,
                         slave_id=data[current_index]).delete, )
                 handle_sql(db_session.flush)
                 data.pop(current_index)
                 if current_index >= len(data) - 1:
                     finished = True
                     break
             else:
                 finished = False
                 break
         if finished:
             break
         limit = 2
         url = "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user={}&api_key={}&format=json&limit={}".format(
             friend["username"],
             self.last_key,
             limit,
         )
         try:
             self.get_fm_secondary(
                 embed=embed,
                 url=url,
                 name="[{}] {} ({})".format(
                     current_index + 1,
                     user,
                     friend["username"],
                 ),
                 primary_index="recenttracks",
                 secondary_index="track",
                 artists=True,
                 artist_name="#text",
                 entry_format="ago",
                 seperator="\n",
                 limit=limit,
             )
         except CommandError:
             embed.add_field(
                 name="[{}] {}".format(current_index + 1, user),
                 value=("Last.fm account `{}` was not found.".format(
                     friend["username"], )),
                 inline=True,
             )
         if current_index >= len(data) - 1:
             break
     return None, embed
示例#8
0
 def exception_response(self, event, e, respond: bool = True):
     if respond:
         if not isinstance(e, APIException) or e.code != 50013:
             api_loop(
                 event.channel.send_message,
                 "Oops, looks like we've blown a fuse back here. Our technicians have been alerted and will fix the problem as soon as possible.",
             )
     if (self.exception_dms):
         if event.channel.is_dm:
             footer_text = "DM"
         else:
             footer_text = "{}: {}".format(event.guild.name, event.guild.id)
         embed = bot.generic_embed_values(
             author_name=str(event.author),
             author_icon=event.author.get_avatar_url(size=32),
             author_url="https://discordapp.com/users/{}".format(
                 event.author.id, ),
             title="Exception occured: {}".format(str(e)),
             description=event.message.content,
             footer_text=footer_text,
             timestamp=event.message.timestamp.isoformat(),
         )
         for target in self.exception_dms.copy():
             target_dm = self.client.api.users_me_dms_create(
                 int(self.owners[0]))
             try:
                 api_loop(target_dm.send_message, embed=embed)
             except APIException as e:
                 if e.code == 50013:
                     log.warning(
                         "Unable to exception dm: {}".format(target))
                     self.exception_dms.remove(guild)
                 else:
                     raise e
     if self.exception_channels:
         embed = bot.generic_embed_values(
             title="Exception occured: {}".format(str(e)),
             description=extract_stack(),
             footer_text=event.message.content,
         )
         for guild, channel in self.exception_channels.copy().items():
             guild_obj = self.client.state.guilds(guild, None)
             if guild_obj is not None:
                 channel_obj = guild.channels.get(channel, None)
                 if channel_obj is not None:
                     try:
                         api_loop(
                             channel_obj.send_message,
                             embed=embed,
                         )
                     except APIException as e:
                         if e.code == 50013:
                             log.warning(
                                 "Unable to post in exception channel: {}".
                                 format(channel))
                             del self.exception_channels[guild]
                         else:
                             raise e
                 else:
                     log.warning(
                         "Invalid exception channel: {}".format(channel))
                     del self.exception_channels[guild]
             else:
                 log.warning("Invalid exception guild: {}".format(guild))
                 del self.exception_channels[guild]
     log.exception(e)
示例#9
0
 def on_queued_command(self, event, index=None):
     """
     Voice Get the information of a certain song in the queue or the amount of songs in the queue.
     If an integer argument is input, then this will return the relevant queue entry.
     If a string is input, then the string will be used to search for queue entry titles.
     Otherwise, if no arguments are passed, this will return the current length of the queue.
     """
     self.pre_check(event)
     if not self.get_player(event.guild.id).queue:
         api_loop(
             event.channel.send_message,
             "There aren't any songs queued right now.",
         )
     elif index is None:
         api_loop(
             event.channel.send_message,
             "There are {} songs queued ({} minutes). To get a specific song's info, just do this command + index."
             .format(
                 len(self.get_player(event.guild.id).queue),
                 self.minutes_format(
                     self.get_player(event.guild.id, ).queue_length),
             ),
         )
     elif (index.replace("-", "").strip(" ").isdigit() and 0 <=
           (int(index.replace("-", "").strip(" ")) - 1) <= len(
               self.get_player(event.guild.id).queue)):
         ytdata = self.get_ytdl_values(
             self.get_player(event.guild.id).queue[
                 int(index.replace("-", "").strip(" ")) - 1].metadata, )
         api_loop(
             event.channel.send_message,
             "The song at index ``{}`` is ``{}`` by ``{}`` with length ``{}`` minutes and is sourced from ``{}``."
             .format(
                 int(index.replace("-", "").strip(" ")),
                 ytdata["title"],
                 ytdata["uploader"],
                 ytdata["time_formated"],
                 ytdata["source"],
             ),
         )
     elif index.replace("-", "").isdigit():
         api_loop(event.channel.send_message, "Invalid index input.")
     else:
         matched_list = dict()
         for item in self.get_player(event.guild.id).queue:
             ratio = partial_ratio(item.metadata["title"], index)
             if ratio >= 70:
                 matched_list["#{} ({}% match)".format(
                     self.get_player(event.guild.id).queue.index(item) + 1,
                     ratio,
                 )] = item.metadata["title"]
         if matched_list:
             embed = bot.generic_embed_values(
                 title="Queue search results",
                 footer_text="Requested by {}".format(event.author),
                 non_inlines={
                     k: matched_list[k]
                     for k in list(matched_list)[-25:]
                 },
                 footer_img=event.author.get_avatar_url(size=32),
                 timestamp=event.msg.timestamp.isoformat(),
             )
             api_loop(event.channel.send_message, embed=embed)
         else:
             api_loop(
                 event.channel.send_message,
                 "No similar items found in queue.",
             )