コード例 #1
0
async def handle_message(message: discord.Message):
    await message.channel.trigger_typing()

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_length == 0:
        await message.channel.send("Not enough args!")

    req = requests.get(
        "https://archlinux.org/packages/search/json/?q={}&repo=Community&repo=Core&repo=Extra&repo=Multilib"
        .format(urllib.parse.quote(cmd.content, safe='')))
    json = req.json()

    pkgs = []

    for pkg in json["results"]:
        pkgs.append(" ‣ `{}` - {}\n".format(pkg["pkgname"], pkg["pkgdesc"]))

    try:
        await cmd.st("**{} search results for `{}` in Arch Linux**\n\n".format(
            len(pkgs), cmd.content) + "".join(pkgs[:3]))
    except:
        await cmd.st(
            "There was an error or your result did not return anything!")
コード例 #2
0
ファイル: bash.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_message(message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_length == 0:
        await message.channel.send("Not enough args!")

    urlcmd = urllib.parse.quote(cmd.content)

    URL = "https://rextester.com/rundotnet/api?LanguageChoice=38&Program=" + urlcmd

    r = requests.get(url=URL)
    data = r.json()
    output = ""

    if data["Warnings"] is not None:
        output += data["Warnings"]

    if data["Errors"] is not None:
        output += data["Errors"]

    if data["Result"] is not None:
        output += data["Result"]

    await cmd.st(content="```\n" + message.author.display_name +
                 "@unnamed-linux" + " > " + cmd.content + "\n" + output +
                 "\n```")
コード例 #3
0
async def handle_aur_message(message: discord.Message):
    await message.channel.trigger_typing()

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_length == 0:
        await cmd.st("Not enough args!")

    req = requests.get(
        "https://aur.archlinux.org/rpc/?v=5&type=info&arg={}".format(
            urllib.parse.quote(cmd.content, safe='')))
    json = req.json()

    print(json)

    pkgs = []

    for pkg in json["results"]:
        pkgs.append(" ‣ `{}` - {}\n".format(pkg["Name"], pkg["Description"]))

    try:
        await cmd.st("**{} search results for `{}` in the AUR**\n\n".format(
            len(pkgs), query) + "".join(pkgs[:3]))
    except:
        await cmd.st(
            "There was an error or your result did not return anything!")
コード例 #4
0
ファイル: echo.py プロジェクト: pontaoski/unnamed-linux-bot
async def echo_message(message: discord.Message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)
    await cmd.send_msg(
        content="{} said: ".format(message.author.display_name) +
        discord.utils.escape_mentions(cmd.content))
    return
コード例 #5
0
ファイル: info.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_message(message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_length == 0:
        await cmd.st("Not enough args!")
    urlquery = urllib.parse.quote(cmd.content)
    await message.channel.trigger_typing()

    msgToSend = ""

    if "arch" in cmd.content.lower():
        msgToSend += "**Arch Linux**\n\n"
        msgToSend += "An independent rolling release distro. You can install it if you can read, but you’ll probably want some other skills before you try this one out.\n\n"
        msgToSend += "**Package Manager** - `pacman`\n"
        msgToSend += "**Package Format** - `pkg.tar.xz`\n"
        msgToSend += "**Community Repository** - AUR"
    elif "ubuntu" in cmd.content.lower():
        msgToSend += "**Ubuntu**\n\n"
        msgToSend += "Debian-based distribution backed by Canonical. Perfect for whatever you’re doing if it doesn’t require the latest software. Just avoid the snaps, alright?\n\n"
        msgToSend += "**Package Manager** - `apt`\n"
        msgToSend += "**Package Format** - `deb`\n"
        msgToSend += "Community Repository - https://www.ubuntuupdates.org/ppas"
    elif "fedora" in cmd.content.lower():
        msgToSend += "**Fedora**\n\n"
        msgToSend += "The Fedora Project is backed by Red Hat and is treated as the upstream source for the commercial Red Hat Enterprise Linux. Arguably the distro that does GNOME how the developers intended it best. Fedora, like Ubuntu, comes in flavours of different DEs. \nHas five variants: Workstation, Server, CoreOS, Silverblue and IoT.\nCoreOS is for Container Environments\nSilverblue is transactional desktop with an immutable core-image, rpm-ostree overlays and flatpaks\nIoT is for embedded devices.\n\n"
        msgToSend += "**Package Manager** - `dnf` or `rpm-ostree`\n"
        msgToSend += "**Package Format** - `rpm`"

    if not msgToSend == "":
        await cmd.st(msgToSend)
        return

    wikirequest = None
    wikijson = None

    try:
        wikirequest = requests.get(
            "https://wikipedia.org/w/api.php?action=opensearch&search=" +
            urlquery + "&format=json&suggest=1&redirects=resolve")
        wikijson = wikirequest.json()
    except:
        await cmd.st(
            "Whoops! Looks like there was an error using Wikipedia's API.")

    if "may refer to" in wikijson[2][0]:
        msgToSend += "**" + wikijson[2][0] + "**" + "\n\n"
        if wikijson[2][1] is not None:
            msgToSend += wikijson[2][1] + "\n\n"
        if wikijson[2][2] is not None:
            msgToSend += wikijson[2][2] + "\n\n"
        if wikijson[2][3] is not None:
            msgToSend += wikijson[2][3] + "\n\n"
    else:
        msgToSend += "**" + wikijson[1][0] + "**" + "\n\n"
        msgToSend += wikijson[2][0] + "\n\n"
        msgToSend += "<" + wikijson[3][0] + ">"

    await cmd.st(msgToSend)
コード例 #6
0
ファイル: about.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_help_message(message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)
    msg = ""
    msg += "Hello, I'm Cafétera!\n"
    msg += "Do you want to know how to use me?\n\n"
    msg += "Learn how at <https://linux-cafe.github.io/commands.html>!\n"
    await cmd.st(content=msg)
コード例 #7
0
ファイル: about.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_message(message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)
    msg = ""
    msg += "Hello, I'm Cafétera!\n"
    msg += "I like helping out wherever.\n\n"
    msg += "You can see me and my pals' source at <https://github.com/linux-cafe>!\n"
    msg += "Maybe you'd like to contribute as well?"
    await cmd.st(content=msg)
コード例 #8
0
ファイル: quote.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_message(message: discord.Message):
    cmd = _c(cmds.cmdutils.lex_command(message))

    helpmsg = ""
    helpmsg += "```dsconfig\n"
    helpmsg += "# Syntax: sudo quote --message id --channel id\n"
    helpmsg += " ( --message | -m )\n"
    helpmsg += " \tThe message ID to quote. Required.\n"
    helpmsg += " ( --channel | -c )\n"
    helpmsg += " \tThe channel ID of the message. Required.\n"
    helpmsg += " ( --reply | -r )\n"
    helpmsg += " \tReply to the message you're quoting.\n"
    helpmsg += "```"

    query_array = cmd.query_array

    if not query_array:
        await cmd.st("You didn't pass any arguments!\n\n" + helpmsg)
        return

    mid = None
    cid = None

    if cmd.get_flag_pair("-m", "--message") is not None:
        mid = cmd.get_flag_pair("-m", "--message")

    if cmd.get_flag_pair("-c", "--channel") is not None:
        cid = cmd.get_flag_pair("-c", "--channel")

    if mid is None or cid is None:
        await cmd.st("Not enough arguments!\n\n" + helpmsg)
        return

    guild = message.guild
    channel = guild.get_channel(int(cid))
    quoted_msg = await channel.fetch_message(int(mid))

    reply = None

    if cmd.get_flag_pair("-r", "--reply") is not None:
        reply = cmd.get_flag_pair("-r", "--reply")

    msg_to_send = """
**{}** said:
{}
""".format(quoted_msg.author.display_name, quoted_msg.clean_content)
    if reply is not None:
        msg_to_send += "\n**{}** replied:\n{}".format(
            message.author.display_name, reply)

    await cmd.st(msg_to_send)
コード例 #9
0
async def handle_message(message: discord.Message):
    if "sudoer" in [y.name.lower() for y in message.author.roles
                    ] and not message.author.guild_permissions.administrator:
        return

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_array[0] == "stop":
        await cmd.st("🛑 Stopping chat... 🛑")
        await message.channel.edit(slowmode_delay=30)
    elif cmd.query_array[0] == "start":
        await cmd.st("✔️ Starting chat... ✔️")
        await message.channel.edit(slowmode_delay=0)
コード例 #10
0
async def handle_message(message: discord.Message):
    global fedora_dnf_obj

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)
    
    if cmd.query_length == 0:
        await cmd.st("Not enough args!")

    dnf_query = fedora_dnf_obj.sack.query()
    available_packages = dnf_query.available()
    available_packages = available_packages.filter(name__substr=cmd.content,arch=["noarch","x86_64"])

    pkgs = []

    for pkg in available_packages:
        pkgs.append(" ‣ `{}` - {}\n".format(pkg.name, pkg.summary))
 
    try:
        await cmd.st("**{} search results for `{}` in Fedora**\n\n".format(len(pkgs), cmd.content) + "".join(pkgs[:3]))
    except:
        await cmd.st("There was an error!")
コード例 #11
0
async def handle_message(message):
    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    if cmd.query_length == 0:
        await cmd.st("Not enough args!")
    query_casefold = query.casefold()

    update_required = True
    force_update = False

    if "-r" in query_casefold.split(" "):
        force_update = True
        query_casefold = query_casefold.replace("-r", "").strip()
        query = query.replace("-r", "").strip()

    app_list = []
    cache_dir = Path("./cache")
    cache_file = cache_dir / "flatpak.json"

    if (cache_dir).is_dir():
        if (cache_file.is_file() and force_update != True):
            with cache_file.open() as flatpak_cache:
                app_list = json.load(flatpak_cache)

                # do not update if the cache is less than one hour old
                if app_list[-1]['timestamp'] - time.time() < 3600:
                    update_required = False
    else:
        Path.mkdir(cache_dir)

    if update_required:
        req = requests.get("https://flathub.org/api/v1/apps")
        app_list = json.loads(req.text)

        # adds the timestamp of the current database update to the end of the array.
        timestamp_json = json.loads(f"{{\"timestamp\" : {time.time()}}}")
        app_list.append(timestamp_json)

        cache_file.write_text(json.dumps(app_list))
        print("flatpak cache updated in cache/flatpak.json")

    name_match = []
    appid_match = []
    summary_match = []
    total_matches = 0

    for app in app_list:
        # stops at 3 matches
        if total_matches == 3:
            break

        # I would want to print total number of matches possible, but this
        # feels like a waste of calculation because it might mismatch with
        # what it appears on the site (the search algorithm might be
        # different). And it doesn't really affect the usage of the bot, so
        # maybe we'll just leave it like that for now.

        # do not attempt to search in the timestamp row
        if "timestamp" in app.keys():
            continue

        if query_casefold in app['name'].casefold():
            name_match.append(app)
            total_matches += 1
            continue

        if query_casefold in app['flatpakAppId'].casefold():
            appid_match.append(app)
            total_matches += 1
            continue

        if query_casefold in app['summary'].casefold():
            summary_match.append(app)
            total_matches += 1
            continue

    response = ""

    if total_matches == 0:
        response += f"**No search results for \"{query}\" on Flathub.**"
    else:
        response += f"**Search results for \"{query}\" on Flathub.**\n\n"

        for app in name_match:
            response += f"  ‣ `{app['name']}` - {app['summary']}\n"
        for app in appid_match:
            response += f"  ‣ `{app['name']}` - {app['summary']}\n"
        for app in summary_match:
            response += f"  ‣ `{app['name']}` - {app['summary']}\n"

        urlquery = urllib.parse.quote(query)
        response += f"\nView full results: <https://flathub.org/apps/search/{urlquery}>"

    await cmd.st(response)
コード例 #12
0
async def handle_message(message: discord.Message):
    db = pickledb.load('profile.db', True)

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    args_dict = {}
    sender = message.author
    sender_id = sender.id

    helpmsg = ""
    helpmsg += "```dsconfig\n"
    helpmsg += "# Syntax: sudo profile --flag value\n"
    helpmsg += " ( --user | -u )\n"
    helpmsg += " \tGet the user specified.\n"
    helpmsg += " ( --set-desktop-environment | -w )\n"
    helpmsg += " \tSet your desktop environment or window manager.\n"
    helpmsg += " ( --set-distro | -d )\n"
    helpmsg += " \tSet your distro.\n"
    helpmsg += " ( --set-shell | -s )\n"
    helpmsg += " \tSet your shell.\n"
    helpmsg += " ( --set-editor | -e )\n"
    helpmsg += " \tSet your editor.\n"
    helpmsg += " ( --set-languages | -p )\n"
    helpmsg += " \tSet your programming languages.\n"
    helpmsg += " ( --set-blurb | -b )\n"
    helpmsg += " \tSet your profile blurb.\n"
    helpmsg += "```"

    query_array = cmd.query_array

    if not query_array:
        await cmd.st("Not enough arguments!\n\n" + helpmsg)
        return

    while query_array:
        distro_query = cmds.cmdutils.get_flag_value(
            "-w", "--set-desktop-environment", query_array)
        if distro_query is not None:
            args_dict["desktop"] = distro_query
        distro_query = cmds.cmdutils.get_flag_value("-d", "--set-distro",
                                                    query_array)
        if distro_query is not None:
            args_dict["distro"] = distro_query
        shell_query = cmds.cmdutils.get_flag_value("-s", "--set-shell",
                                                   query_array)
        if shell_query is not None:
            args_dict["shell"] = shell_query
        editor_query = cmds.cmdutils.get_flag_value("-e", "--set-editor",
                                                    query_array)
        if editor_query is not None:
            args_dict["editor"] = editor_query
        langs_query = cmds.cmdutils.get_flag_value("-p", "--set-languages",
                                                   query_array)
        if langs_query is not None:
            args_dict["langs"] = langs_query
        blurb_query = cmds.cmdutils.get_flag_value("-b", "--set-blurb",
                                                   query_array)
        if blurb_query is not None:
            args_dict["blurb"] = blurb_query
        user_query = cmds.cmdutils.get_flag_value("-u", "--user", query_array)
        if user_query is not None:
            args_dict["user"] = user_query

        query_array.pop(0)

    if args_dict == {}:
        await cmd.st("Invalid arguments!\n" + helpmsg)
    profile_updated = None
    if "desktop" in args_dict.keys():
        db.set(str(sender_id) + "_de", args_dict["desktop"])
        profile_updated = True
    if "distro" in args_dict.keys():
        db.set(str(sender_id) + "_distro", args_dict["distro"])
        profile_updated = True
    if "shell" in args_dict.keys():
        db.set(str(sender_id) + "_shell", args_dict["shell"])
        profile_updated = True
    if "editor" in args_dict.keys():
        db.set(str(sender_id) + "_editor", args_dict["editor"])
        profile_updated = True
    if "langs" in args_dict.keys():
        db.set(str(sender_id) + "_langs", args_dict["langs"])
        profile_updated = True
    if "blurb" in args_dict.keys():
        db.set(str(sender_id) + "_blurb", args_dict["blurb"])
        profile_updated = True

    if profile_updated is not None:
        await cmd.st("Profile updated!")
        return

    if "user" in args_dict.keys():
        mentioned_member = cmds.cmdutils.get_user_closest_to_name(
            message.guild, args_dict["user"])
        try:
            mentioned_member = message.mentions[0]
        except IndexError:
            a = "a"

        if mentioned_member is None:
            await cmd.st(
                "That person does not exist. Please be more specific, or check that they exist. If you were trying to use a command, please check your syntax."
            )
            return

        mmid = mentioned_member.id

        desktop = default(db.get(str(mentioned_member.id) + "_de"),
                          "No DE/WM set.")
        distro = default(db.get(str(mentioned_member.id) + "_distro"),
                         "No distro set.")
        shell = default(db.get(str(mentioned_member.id) + "_shell"),
                        "No shell set.")
        editor = default(db.get(str(mentioned_member.id) + "_editor"),
                         "No editor set.")
        langs = default(db.get(str(mentioned_member.id) + "_langs"),
                        "No languages set.")
        blurb = default(db.get(str(mentioned_member.id) + "_blurb"), None)

        pmsg = ""
        pmsg += "> **{}'s profile**\n".format(mentioned_member.display_name)
        pmsg += "> Distro: {}\n".format(distro)
        pmsg += "> DE/WM: {}\n".format(desktop)
        pmsg += "> Shell: {}\n".format(shell)
        pmsg += "> Editor: {}\n".format(editor)
        pmsg += "> Programming Languages: {}\n".format(langs)
        if blurb is not None:
            pmsg += "> \n"
            pmsg += "> *{}*\n".format(blurb)

        await cmd.st(pmsg)
コード例 #13
0
ファイル: ss.py プロジェクト: pontaoski/unnamed-linux-bot
async def handle_message(message):
    db = pickledb.load('ss.db', True)

    lex = cmds.cmdutils.lex_command(message)
    cmd = _c(lex)

    query_array = cmd.query_array
    
    if cmd.query_length == 0:
        await cmd.st("Not enough args!")

    sender = message.author
    sender_id = sender.id

    screenshots = db.get("screenshots")
    if screenshots is False:
        db.set("screenshots", " ")
        screenshots = db.get("screenshots")
    
    screenshots_array = screenshots.split(',')

    if not db.get(str(sender_id) + "_ss_url"):
        db.set(str(sender_id) + "_ss_url", "")
    if not db.get(str(sender_id) + "_ss_desc"):
        db.set(str(sender_id) + "_ss_desc", "")

    if query_array[0] == "set":
        query_array.pop(0)
        if not query_array:
            await cmd.st("Invalid arguments!")
        
        if query_array[0] == "url":
            query_array.pop(0)
            if not query_array:
                await cmd.st("Invalid arguments!")

            db.set(str(sender_id) + "_ss_url", query_array[0])
            if str(sender_id) not in screenshots:
                screenshots_array.append(str(sender_id))
                screenshots = ",".join(screenshots_array)
                db.set("screenshots", screenshots)
            await cmd.st("Screenshot set!")


        elif query_array[0] == "desc":
            query_array.pop(0)
            if not query_array:
                await cmd.st("Invalid arguments!")

            desc = " ".join(query_array)
            db.set(str(sender_id) + "_ss_desc", desc)
            await cmd.st("Description set!")

        else:
            await cmd.st("Invalid arguments!")

    elif query_array[0] == "ls" or query_array[0] == "list":
        await message.channel.trigger_typing()
        posttitle = "Screenshots in Unnamed Linux Community"
        postbody = ""

        for i in screenshots_array:
            ss_url = db.get(i + "_ss_url")
            desc = db.get(i + "_ss_desc")

            if desc is False:
                desc = ""

            if ss_url is False or ss_url == "":
                continue

            member = message.guild.get_member(int(i))
            
            if member is None:
                continue

            postbody += "\n# **" + member.display_name + "**\n"
            if desc != "":
                postbody += desc + "\n\n"
            else:
                postbody += "\n"

            postbody += "<img src=\"{url}\">".format(url=ss_url)

        postdict = {"body": postbody, "title": posttitle}
        r = requests.post("https://write.as/api/posts",json=postdict)
        r_json = r.json()
        post_id = r_json["data"]["id"]
        await cmd.st("List of screenshots: https://write.as/" + post_id + ".md")

    else:
        mentioned_member = cmds.cmdutils.get_user_closest_to_name(message.guild, query)
        try:
            mentioned_member = message.mentions[0]
        except IndexError:
            a="a"

        if mentioned_member is None:
            await cmd.st("That person does not exist. Please be more specific, or check that they exist. If you were trying to use a command, please check your syntax.")
            return

        url = db.get(str(mentioned_member.id) + "_ss_url")
        desc = db.get(str(mentioned_member.id) + "_ss_desc")

        if desc is False:
            desc = ""

        if url is False or url == "":
            await cmd.st(mentioned_member.display_name + " does not have a screenshot set!")
            return

        embed = discord.Embed(title=mentioned_member.display_name + "'s screenshot", color=mentioned_member.colour, description=desc)
        embed.set_image(url=url)

        await cmd.se(embed=embed)