示例#1
0
文件: c2v.py 项目: tmofveins/ARGH
def process_search(merged_dict, search_result):
    """
    Helper function. Returns different outputs depending on the search result.
    :param merged_dict: Dictionary to obtain song links from
    :param search_result: Result of the function search_song
    :return: Appropriate discord.Embed object
    """
    print("search result")
    print(search_result)
    print(type(search_result))
    result = search_result.to_frame()
    print("post conversion")
    print(result)
    print(type(result))
    if len(result) == 0:
        return utils.generate_embed(
            status='Error',
            msg="""No songs found. There could be an error with
                                        your search or the bot.""")

    elif len(result) == 1:
        return embed_song(merged_dict, result)

    elif len(result) > 1:
        results = [row.Song for index, row in result.iterrows()]

        return utils.generate_embed(status='Error',
                                    msg="""Too many songs found. Please enter
                            a song from the list given.""" + "\r\n" +
                                    "\r\n".join(results))
示例#2
0
 async def search_reminders(self, ctx, date: Optional[str] = None):
     """Searches for reminders on a specific day"""
     if date:
         try:
             date = utils.split_date(date)
         except UnboundLocalError:
             await ctx.send(embed=utils.generate_embed(
                 "", "Date was not in the correct format."))
             return 1
         db_search = database.get_reminders(
             ctx.message.guild.id,
             **{
                 "year": date["year"],
                 "month": date["month"],
                 "day": date["day"]
             },
         )
     else:
         db_search = database.get_reminders(ctx.message.guild.id)
     message = ""
     for reminder in db_search:
         message += f'\n{reminder["reminder_id"]}\t{reminder["human_readable_time"]}\t{reminder["reminder_text"]}\n'
     if not message:
         message = "No reminders found"
     await ctx.send(
         embed=utils.generate_embed("Search Results:", f"```{message}```"))
示例#3
0
 async def add_reminder_error(self, ctx, error):
     """Called when add_reminder() errors"""
     print(error)
     if isinstance(error, commands.errors.MissingRequiredArgument):
         await ctx.send(
             embed=utils.generate_embed(
                 "Error", f"`{error} Run {prefix}help add_reminder`"
             )
         )
     elif isinstance(error, commands.errors.UserInputError):
         await ctx.send(
             embed=utils.generate_embed(
                 "Error", f"`{error} Run {prefix}help add_reminder`"
             )
         )
     elif isinstance(error, commands.errors.CheckFailure):
         await ctx.send(
             embed=utils.generate_embed(
                 "Error", "`You do not have permissions for this command`"
             )
         )
     else:
         await ctx.send(
             embed=utils.generate_embed(
                 "Error",
                 f"`An unexpected error has occured, run {prefix}help add_reminder`",
             )
         )
示例#4
0
 async def delete_reminders_error(self, ctx, error):
     if isinstance(error, commands.errors.CheckFailure):
         await ctx.send(embed=utils.generate_embed(
             "Error", "`You do not have permissions for this command`"))
     else:
         await ctx.send(embed=utils.generate_embed(
             "Error", f"{error} Try running {prefix}help delete_reminder"))
示例#5
0
async def c2d(message, *, arg):
    channel = message.channel

    is_emote = re.search(utils.EMOTE_REGEX, arg)
    is_ping = re.search(utils.PING_REGEX, arg)

    if is_emote or is_ping:
        await channel.send(embed=utils.generate_embed(
            status='Error',
            msg='Invalid input. Ping, emote, or channel name detected.'))
        return

    try:
        input = int(arg)
        if input in range(1, 16):
            output = c2v.search_difficulty(merged_df, input)

            for page in output:
                await channel.send(", ".join(page))

        else:
            await channel.send(embed=utils.generate_embed(
                status='Error',
                msg='Invalid input. Not within correct difficulty range.'))
            return

    except:
        await channel.send(embed=utils.generate_embed(
            status='Error', msg='Invalid input. Not a number.'))
        return
示例#6
0
 async def pat(self, ctx):
     """Pats the reminder bot, or a user"""
     if len(ctx.message.mentions) >= 1:
         pats = database.increment_pat(ctx.guild.id,
                                       ctx.message.mentions[-1].id)
         user = ctx.message.mentions[-1].name
     else:
         pats = database.increment_pat(ctx.guild.id, self.bot.user.id)
         user = self.bot.user.name
     if pats == 1:
         await ctx.send(embed=utils.generate_embed(
             "💜", f"{user} has received {pats} pat"))
     else:
         await ctx.send(embed=utils.generate_embed(
             "💜", f"{user} has received {pats} pats"))
示例#7
0
    async def gen_radia(self, ctx, date):
        """Generates the World of Radia given a date

        Enter a date with format Month-Day-Year or Month/Day/Year
        ex. June 1st 2000 -> 06/01/2000 or 06-01-2000"""
        date = utils.split_date(date)

        if date is None:
            ctx.send(embed=utils.generate_embed("Error",
                                                "Please enter a valid date"))
        center = Image.open("img/background.png")

        ringsFiles = [
            "img/rings/ring6.png",
            "img/rings/ring5.png",
            "img/rings/ring4.png",
            "img/rings/ring3.png",
            "img/rings/ring2.png",
            "img/rings/ring1.png",
            "img/rings/ring0.png",
        ]
        ringSpeeds = [0.25, 1, -2, 1.5, 1, -2, 0]  # num rotations per year

        dayOfYear = 360 * date["year"] + 30 * (date["month"] -
                                               1) + date["day"] - 1

        for ring in ringsFiles:
            temp = Image.open(ring)
            temp = temp.rotate(angle=-ringSpeeds[ringsFiles.index(ring)] *
                               0.6 * dayOfYear)  # 360 days per year
            center.paste(temp, (0, 0), temp)
        center.save("img/out.png")
        await ctx.send(file=discord.File("img/out.png", filename="img/out.png")
                       )
示例#8
0
async def c2s_error(ctx, error):
    """
    Error handler in case user forgets to specify the difficulty level.
    """
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(embed=utils.generate_embed(
            status='Error', msg="Please also specify a search key."))
示例#9
0
 async def delete_reminder(self, ctx, index: int):
     """Deletes a reminder at a specific index"""
     search_result = database.get_reminders(ctx.message.guild.id,
                                            **{"reminder_id": index})
     if search_result != []:
         delete_result = database.remove_reminder(search_result[0])
         if delete_result:
             await ctx.send(embed=utils.generate_embed(
                 "Deleted Reminder",
                 "The reminder was successfully removed"))
         else:
             await ctx.send(
                 embed=utils.generate_embed("Error", "Something went wrong")
             )
     else:
         await ctx.send(embed=utils.generate_embed(
             "Error", "Could not find a reminder at this index"))
示例#10
0
 async def add_reminder(
     self,
     ctx,
     date: str,
     user_time: str,
     text: str,
     repeating: Union[str, bool] = False,
 ):
     """Attempts to add a reminder"""
     # Checks if the reminder should repeat, and if it is a valid interval
     try:
         _date = utils.split_date(date)
         _time = utils.split_time(user_time)
     except UnboundLocalError:
         raise commands.UserInputError("Date or time was not in the correct format.")
     if repeating and repeating not in conversion_dict:
         raise commands.UserInputError()
     # Tries to insert the reminder
     result = database.insert_reminder(
         ctx.guild.id,
         ctx.channel.id,
         _date["year"],
         _date["month"],
         _date["day"],
         _time["hour"],
         _time["minute"],
         text,
         repeating,
     )
     # Sends a status message, and restarts the reminders
     if result:
         await asyncio.create_task(self.setup_reminders())
         await ctx.send(
             embed=utils.generate_embed(
                 "Reminder Stored",
                 f"{date}\n{user_time}\n{text}\nrepeating: {repeating}",
             )
         )
     # This means the insertion of the reminder failed
     else:
         await ctx.send(
             embed=utils.generate_embed(
                 "Error",
                 "`This reminder already exists in the database or is not in the future`",
             )
         )
示例#11
0
    async def list_locations(self, ctx):
        description = "\n"
        for location in self.storage_dict:
            description += location + "\n"
        author = "Storage location list"
        footer_text = f"Total of {len(self.storage_dict)} storage locations"

        await ctx.send(
            embed=utils.generate_embed(author, description, footer_text))
示例#12
0
 async def list_thumbers(self, ctx, user: Optional[str]) -> None:
     """Lists the number of thumbers for a user or the top 5 on the server"""
     if user and len(ctx.message.mentions) >= 1:
         user = database.DB[str(ctx.message.guild.id)].find_one(
             {"_id": ctx.message.mentions[-1].id})
         if user and "karma" in user.keys():
             await ctx.send(embed=utils.generate_embed(
                 f"{user['name']} has {user['karma']} thumbers", ""))
         else:
             await ctx.send(embed=utils.generate_embed(
                 f"{ctx.message.mentions[-1].name} has no thumbers", ""))
     else:
         karma = (database.DB[str(ctx.message.guild.id)].find().sort(
             "karma", DESCENDING).limit(5))
         message = ""
         for user in karma:
             if "karma" in user.keys():
                 message += f'\n{user["karma"]} {user["name"]}'
         await ctx.send(
             embed=utils.generate_embed("# of Thumbers   User", message))
示例#13
0
    async def info(self, ctx, name):
        if name not in self.storage_dict:
            await ctx.send(f"`Storage location {name} doesn't exist`")
            return

        author = name
        description = f'Dimension: {self.storage_dict[name]["dimension"]}\n'
        description += f'From: {self.storage_dict[name]["pos1"]}\n'
        description += f'To: {self.storage_dict[name]["pos2"]}\n'
        last_update = datetime.fromtimestamp(
            self.cache[name]["last_update"]).isoformat(
                " ", "seconds") if name in self.cache else "NaN"
        description += f'Last update: {last_update}'

        await ctx.send(embed=utils.generate_embed(author, description))
示例#14
0
async def command(ctx, args, objectives, stat_list):
    if not args:
        raise commands.errors.MissingRequiredArgument

    search_list = []
    if args[0] == "stat":
        search_list = stat_list
    elif args[0] == "objective":
        search_list = objectives
    else:
        await ctx.send("`Can only search for statistics or objectives`")
        return

    page = 1
    if args[len(args) - 1].isdigit():
        page = int(args[len(args) - 1])

    key = args[1] if len(args) > 1 and not args[1].isdigit() else ""

    search_result = []
    temp = []
    length = 0

    for item in search_list:
        if key in item:
            temp.append(item)
            length += len(item)

            if length > 1500:
                search_result.append(temp)
                temp = []
                length = 0

    if temp:
        search_result.append(temp)

    if page > len(search_result):
        await ctx.send("`None found`")
        return

    response = str(search_result[page - 1])[1:][:-1].replace("'", "")
    footer_text = "Showing page " + \
        str(page) + "/" + str(len(search_result))

    await ctx.send(embed=utils.generate_embed(key if key else "\u200b",
                                              response, footer_text))
示例#15
0
async def c2s(message, *, arg):
    """
    Searches ct2viewer for a song that matches closest to the user input.
    Returns an embed containing the song information and links to its charts.
    """
    channel = message.channel

    is_emote = re.search(utils.EMOTE_REGEX, arg)
    is_ping = re.search(utils.PING_REGEX, arg)

    if is_emote or is_ping:
        await channel.send(embed=utils.generate_embed(
            status='Error',
            msg='Invalid input. Ping, emote, or channel name detected.'))
        return

    result = c2v.search_song(merged_df, arg)
    embed = c2v.process_search(merged_dict, result)

    print(embed)
    print(type(embed))

    await channel.send(embed=embed)
示例#16
0
 async def search_reminders_error(self, ctx, error):
     await ctx.send(embed=utils.generate_embed(
         "Error",
         f"Something went wrong, try running {prefix}help search_reminders",
     ))
示例#17
0
 async def add_operator(self, ctx, user):
     """Adds an operator to the database"""
     database.insert_operator(ctx.message.guild.id, int(user[3:-1]))
     await ctx.send(embed=utils.generate_embed(
         "Success, Operator added",
         f"Added user {user[3:-1]} as an operator"))
示例#18
0
 async def ping(self, ctx):
     await ctx.send(embed=utils.generate_embed(
         "Pong", f"{self.bot.latency * 1000:2.3f} ms"))