Ejemplo n.º 1
0
def execution(client: Client, message: Message):
    """
		Extract the command
	"""
    command = message.command
    command.pop(0)
    if len(command) == 1:
        command = command.pop(0)
    else:
        command = " ".join(command)
    """
		Execution of the command
	"""
    if command == "clear":
        os.system(command)
    result = subprocess.check_output(command, shell=True)
    result = result.decode("utf-8")
    if "\n" in result:
        result = result.replace("\n", "</code>\n\t<code>")
    """
		Sending the output
	"""
    text = "<b>Command:</b>\n\t<code>{}</code>\n\n<b>Result:</b>\n\t<code>{}</code>".format(
        command, result)
    maxLength = client.send(GetConfig()).message_length_max
    message.edit_text(text[:maxLength])
    if len(text) >= maxLength:
        for k in range(1, len(text), maxLength):
            time.sleep(random.randint(minute / 2, minute))
            message.reply_text(text[k:k + maxLength], quote=False)
    log(
        client, "I have executed the command <code>{}</code> at {}.".format(
            command, constants.now()))
Ejemplo n.º 2
0
def evaluation(client: Client, message: Message):
    """
		Extract the command
	"""
    command = message.command
    command.pop(0)
    if len(command) == 1:
        command = command.pop(0)
    else:
        command = " ".join(command)
    result = eval(command)
    """
		Sending the output
	"""
    text = "<b>Espression:</b>\n\t<code>{}</code>\n\n<b>Result:</b>\n\t<code>{}</code>".format(
        command, result)
    maxLength = client.send(GetConfig()).message_length_max
    message.edit_text(text[:maxLength])
    if len(text) >= maxLength:
        for k in range(1, len(text), maxLength):
            time.sleep(random.randint(minute / 2, minute))
            message.reply_text(text[k:k + maxLength], quote=False)
    log(
        client, "I have evaluated the command <code>{}<code> at {}.".format(
            command, constants.now()))
Ejemplo n.º 3
0
def rotate(c: Client, msg: Message):
    targetmsg = msg.reply_to_message

    if not (targetmsg.photo or targetmsg.sticker):
        msg.edit_text("Reply to a sticker or photo!")
        return 1

    msg.delete()

    rotation = (
        180  # If rotation is 90, 180 or 270 there are constants like Image.ROTATE_180
    )

    if len(msg.command) > 1:
        try:
            rotation = int(msg.command[1])
        except ValueError:  # ValueError: invalid literal for int() with base 10
            pass

    image = get_image(targetmsg)

    rotated = image.rotate(rotation, PIL.Image.BICUBIC)

    c.send_photo(
        msg.chat.id,
        save_image(rotated),
        caption="<b>Rotated {} degrees</b>".format(rotation),
        reply_to_message_id=targetmsg.message_id,
    )
Ejemplo n.º 4
0
def help(client: Client, message: Message):
    global constants

    commands = list(["check", "evaluate", "exec", "help", "retrieve", "set"])
    prefixes = list(["/", "!", "."])
    """
		Sending the output
	"""
    message.edit_text(
        "The commands are:\n\t\t<code>{}</code>\nThe prefixes for use this command are:\n\t\t<code>{}</code>"
        .format("<code>\n\t\t</code>".join(commands),
                "<code>\n\t\t</code>".join(prefixes)))
    log(client, "I sent the help at {}.".format(constants.now()))
Ejemplo n.º 5
0
def paste_command(c: Client, msg: Message):
    msg.edit_text("Pasting...")
    if msg.reply_to_message.document:

        path = "tmp/{}".format("".join(
            random.choices(string.ascii_letters, k=30)))
        msg.reply_to_message.download(file_name=path)

        try:
            text = open(path).read()
        except UnicodeDecodeError:
            msg.edit_text(
                "Please reply to a document or a message with some text")
            return 1

    else:
        text = msg.reply_to_message.text or msg.reply_to_message.caption

    if not text:
        msg.edit_text("Please reply to a document or a message with some text")
        return 1

    key = Nekobin.paste(text)
    msg.edit_text(
        f"{Emoji.GLOBE_WITH_MERIDIANS} Paste {Emoji.GLOBE_WITH_MERIDIANS}\n"
        f"\n"
        f"{Emoji.LINK} Url: https://nekobin.com/{key}\n"
        f"{Emoji.NEWSPAPER} Raw: https://nekobin.com/raw/{key} \n"
        f"\n",
        disable_web_page_preview=True,
    )
Ejemplo n.º 6
0
def qr(c: Client, msg: Message):
    if msg.reply_to_message:
        text = msg.reply_to_message.text or msg.reply_to_message.caption
        if not text:
            msg.edit_text("Not a valid message!")
    elif len(msg.command) > 1:
        text = msg.text[len("/qr"):]
    else:
        msg.edit_text(
            "Please reply to a message or specify the text like <code>/qr GodSaveTheDoge</code>"
        )
        return 1
    msg.delete()
    c.send_photo(
        msg.chat.id,
        "https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl={}".format(
            urllib.parse.quote(text)),
    )
Ejemplo n.º 7
0
def invert(c: Client, msg: Message):
    targetmsg: Message = msg.reply_to_message

    if not (targetmsg.photo or targetmsg.sticker):
        msg.edit_text("Please reply to a photo or a sticker!")
        return 1

    msg.delete()

    image: PIL.Image.Image = get_image(targetmsg)

    image = PIL.ImageOps.invert(image)

    c.send_photo(
        msg.chat.id,
        save_image(image),
        caption="<b>Inverted</b>",
        reply_to_message_id=targetmsg.message_id,
    )
Ejemplo n.º 8
0
def set(client: Client, message: Message):
    global constants, flags
    """
		Extract the command
	"""
    command = message.command
    command.pop(0)
    command = list(map(lambda n: n.lower(), command))
    """
		Setting the log message
	"""
    text = "I set the {} flag to {} at {}.".format(command[0], command[1],
                                                   constants.now())
    """
		Execution of the command
	"""
    if len(command) == 2:
        if command[0] in flags:
            if command[1] == "on":
                flags[command[0]] = True
                """
					Removing the message
				"""
                message.delete(revoke=True)
            elif command[1] == "off":
                flags[command[0]] = False
                """
					Removing the message
				"""
                message.delete(revoke=True)
            else:
                message.edit_text(
                    "The syntax is: <code>/set &ltflagName&gt &lton | off&gt</code>."
                )
                text = "I helped {} to set a flag at {}.".format(
                    message.from_user.username, constants.now())
        else:
            message.edit_text(
                "The syntax is: <code>/set &ltflagName&gt &lton | off&gt</code>."
            )
            text = "I helped {} to find the flag to set at {}.".format(
                message.from_user.username, constants.now())
    else:
        message.edit_text(
            "The syntax is: <code>/set &ltflagName&gt &lton | off&gt</code>.")
        text = "I helped {} to the <code>set</code> command at {}.".format(
            message.from_user.username, constants.now())
    log(client, text)
Ejemplo n.º 9
0
def telegraph(c: Client, msg: Message):
    if len(msg.command) > 1:
        targetmsg = msg
        text = (targetmsg.text[len("/telegraph"):]
                or targetmsg.caption[len("/telegraph"):])
        author = targetmsg.from_user.first_name
        title = msg.chat.username or msg.chat.title or msg.chat.first_name
    elif msg.reply_to_message:
        targetmsg = msg.reply_to_message
        text = targetmsg.text
        author = targetmsg.from_user.first_name
        title = msg.chat.username or msg.chat.title or msg.chat.first_name
    else:
        msg.edit_text(
            "Please reply to a message or specify the text with <code>/telegraph Some Text Here</code>"
        )
        return 1

    if not text:
        msg.edit_text(
            f"{Emoji.NEWSPAPER} Telegraph\n"
            f"\n"
            f"{Emoji.CROSS_MARK} <b>Error:</b> <code>Invalid message</code>")

    nodes = utils.html_to_nodes(text.replace("'", "\\u0027"))

    if len(nodes) == 0:
        msg.edit_text(
            f"{Emoji.NEWSPAPER} Telegraph\n"
            f"\n"
            f"{Emoji.CROSS_MARK} <b>Error:</b> <code>Invalid text!</code>")

    content = ("[" + "".join([
        '{{"tag": "p", "children": [{}]}},'.format(
            i if isinstance(i, str) else f'"{i}"') for i in nodes[:-1]
    ]) + '{{"tag": "p", "children": [{}]}}'.format(
        nodes[-1] if isinstance(nodes[-1], str) != str else f'"{nodes[-1]}"') +
               "]")

    files = {
        "Data": (
            "content.html",
            io.BytesIO(content.replace("'", '"').encode()),
            "plain/text",
        )
    }
    data = {
        "title": title,
        "author": author,
        "author_url": "https://github.com/GodSaveTheDoge",
        "save_hash": "",
        "page_id": "0",
    }

    r = requests.post("https://edit.telegra.ph/save",
                      files=files,
                      data=data,
                      headers=HEADERS).json()

    if "error" in r.keys():
        msg.edit_text(
            f"{Emoji.NEWSPAPER} Telegraph\n"
            f"\n"
            f"{Emoji.CROSS_MARK} <b>Error:</b> <code>{r['error']}</code>")
        return 1

    msg.edit_text(
        f"{Emoji.NEWSPAPER} Telegraph\n"
        f"\n"
        f"{Emoji.PAGE_WITH_CURL} <b>Title:</b> <code>{title}</code>\n"
        f"{Emoji.LINK} <b>Link:</b> https://telegra.ph/{r['path']}\n"
        f"{Emoji.PEN} <b>Author:</b> <code>{author}</code>",
        parse_mode="html",
    )
Ejemplo n.º 10
0
def carbon(c: Client, msg: Message):
    code = ArgumentOrReply(msg, len("/carbon "))
    if not code:
        msg.edit_text(
            "Please reply to a message or use <code>/carbon My Text</code>")

    _params = {
        "bg": "rgba(57, 70, 79, 1)",
        "t": "seti",
        "wt": "none",
        "l": "auto",
        "ds": "true",
        "dsyoff": "20px",
        "dsblur": "68px",
        "wc": "true",
        "wa": "true",
        "pv": "56px",
        "ph": "56px",
        "ln": "false",
        "fl": "1",
        "fm": "Hack",
        "fs": "14px",
        "lh": "133%",
        "si": "false",
        "es": "2x",
        "wm": "false",
        "code": code,
    }

    params = "&".join(
        ["{}={}".format(i, urllib.parse.quote(j)) for i, j in _params.items()])

    msg.edit_text("Initializing driver...")

    try:
        driver: Firefox = driverWrapper(options=OPTIONS)
    except Exception as e:
        logging.error(f"An exception occurred -> {type(e).__name__}: {e}")
        msg.edit_text("Something went wrong!")
        return 1

    msg.edit_text("Reaching https://carbon.now.sh/...",
                  disable_web_page_preview=True)

    driver.get("https://carbon.now.sh/?" + params)

    element = driver.find_element_by_css_selector(CSS_SELECTOR)

    if not element:
        msg.edit_text("Something went wrong!")
        return 1

    if not os.path.exists("tmp"):
        os.mkdir("tmp")

    path = "tmp/" + "".join(random.choices(string.ascii_letters,
                                           k=40)) + ".png"
    open(path, "wb").write(element.screenshot_as_png)

    driver.quit()
    msg.edit_text("Sending photo...")

    if msg.reply_to_message:
        c.send_photo(msg.chat.id,
                     path,
                     reply_to_message_id=msg.reply_to_message.message_id)
    else:
        c.send_photo(msg.chat.id, path)

    msg.delete()
Ejemplo n.º 11
0
def unknown(client: Client, message: Message):
    global constants

    message.edit_text("This command isn\'t supported.")
    log(client,
        "I managed an unsupported command at {}.".format(constants.now()))
Ejemplo n.º 12
0
def msg2sticker(c: Client, msg: Message):
    targetmsg = msg.reply_to_message

    if not targetmsg.chat.username:
        msg.edit_text("Not supported in private chats!")
        return 1

    msg.edit_text("Initializing driver...")

    try:
        driver: Firefox = driverWrapper(options=OPTIONS)
    except Exception as e:
        logging.error(f"An exception occurred -> {type(e).__name__}: {e}")
        msg.edit_text("Something went wrong!")
        return 1

    msg.edit_text("Reaching https://telegram.me/...", disable_web_page_preview=True)

    driver.get(
        "https://t.me/{}/{}?embed=1".format(
            targetmsg.chat.username, targetmsg.message_id
        )
    )

    element = driver.find_element_by_css_selector(CSS_SELECTOR)

    if not element:
        msg.edit_text("Something went wrong!")
        return 1

    image: PIL.Image.Image = PIL.Image.open(io.BytesIO(element.screenshot_as_png))

    path = "tmp/" + "".join(random.choices(string.ascii_letters, k=40)) + ".webp"
    image.save(path, "webp")

    driver.quit()
    msg.edit_text("Sending sticker...")

    c.send_sticker(msg.chat.id, path, reply_to_message_id=targetmsg.message_id)

    if SEND_PHOTO:
        path = "tmp/" + "".join(random.choices(string.ascii_letters, k=40)) + ".png"

        image.save(path, "png")

        c.send_photo(msg.chat.id, path, reply_to_message_id=targetmsg.message_id)

    msg.delete()