Esempio n. 1
0
def auctionCommand(client: Client, message: Message) -> None:
    message.delete()
    user = message.from_user
    if not Database.isUserRegistered(user):
        message.reply_text("Usa il comando /register <Password> per registrarti!")
    for auction in auctions:
        message.reply_text(auction.__str__(),reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Elimina", callback_data=auction.name + "_del")]]))
Esempio n. 2
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,
    )
Esempio n. 3
0
def upscale(c: Client, msg: Message):
    if not (msg.reply_to_message.photo or msg.reply_to_message.document):
        msg.edit_text("Please reply to a photo or document")
        return 1
    if msg.reply_to_message.document:
        logging.warning("Documents aren't always upscalable.")

    fname = "tmp/" + "".join(random.choices(
        string.ascii_letters, k=30)) + ".jpeg"  # Photos are sent as jpeg
    msg.reply_to_message.download(file_name=fname,
                                  progress=download_update,
                                  progress_args=(msg, ))

    msg.edit_text("Upscaling...\n" "[{s}????{s}] ??%".format(s=" " * 8))

    try:
        ufname = "tmp/" + "".join(random.choices(
            string.ascii_letters, k=30)) + ".png"  # Photos are recived in .png
        open(ufname, "wb").write(imu.upscale(fname))
    except InternalServerError:
        msg.edit_text("Document not valid!")
        return 1

    msg.edit_text("Uploading...\n" "[{s}????{s}] ??%".format(s=" " * 8))
    c.send_photo(msg.chat.id,
                 ufname,
                 reply_to_message_id=msg.reply_to_message.message_id,
                 caption="<b>Upscaled</b>")
    msg.delete()
Esempio n. 4
0
def newAuction(client: Client, message: Message) -> None:
    message.delete()
    user = message.from_user
    if not Database.isUserRegistered(user):
        message.reply_text("Usa il comando /register <Password> per registrarti!")
        return
    chat: Chat = message.chat
    AuctionCreator(chat, app)
Esempio n. 5
0
def reply_msg(message: Message, message2: Message, delete_orig=False):
    try:
        message2.copy(chat_id=message.chat.id, reply_to_message_id=message.id)

        if delete_orig:
            message.delete()
    except Exception as e:
        raise e
Esempio n. 6
0
 def on_private_message(self, client: Client, message: Message):
     message.delete()
     if self.creationStatus == CreationStatus.NAME_CHANGE:
         name = message.text
         self.name = name
     elif self.creationStatus == CreationStatus.DESCRIPTION:
         description = message.text
         self.description = description
     self._redirectToMainMenu()
def mention_admins(client: Client, message: Message):
    message.delete()
    message_text = message.text
    for admin in client.iter_chat_members(message.chat.id, 0, '', 'administrators'):
        message_text += f'<a href="tg://user?id={admin.user.id}">&#8203;</a>'   # add invisible mention to message text
    try:
        client.send_message(message.chat.id, message_text)
    except SlowmodeWait as e:   # if slow mode enabled
        sleep(e.x)
        client.send_message(message.chat.id, message_text)
Esempio n. 8
0
 def my_handler(client, message: types.Message):
     message_data = message.text.split(' ')
     command = message_data[0]
     if message.chat.id == self.my_id:
         if command == "!help":
             message.reply(
                 "In chat with yourself you can change settings of your addon:\n\n"
                 "<code>!ping_all_from_non_me</code> - toggle using !ping_all command "
                 f"by all members of chat\n<b>({self.ping_all_from_non_me})</b>\n\n",
                 parse_mode="html")
         elif command == "!ping_all_from_non_me":
             self.ping_all_from_non_me = not self.ping_all_from_non_me
             message.reply(
                 f"ping_all_from_non_me = <b>{self.ping_all_from_non_me}</b> ",
                 parse_mode="html")
     else:
         if command == '!ping_all':
             if self.ping_all_from_non_me or (self.my_id
                                              == message.from_user.id):
                 logging.warning(f"Pinging all in {message.chat.title}")
                 list_mentions = []
                 for member in message.chat.iter_members():
                     if not member.user.is_bot:
                         try:
                             list_mentions.append(member.user.mention)
                         except AttributeError:
                             pass
                 conclusion = ''
                 if self.my_id != message.from_user.id:
                     conclusion = '\n\n<b>Requested by:</b>\n'
                     try:
                         conclusion += message.from_user.mention
                     except AttributeError:
                         pass
                 message.reply('\n'.join(list_mentions) + conclusion)
                 logging.warning(
                     f"Done pinging all in {message.chat.title}")
         elif command == "!get_all":
             message.delete()
             list_mentions = []
             for member in message.chat.iter_members():
                 if not member.user.is_bot:
                     try:
                         list_mentions.append(member.user.mention)
                     except AttributeError:
                         pass
             app.send_message(
                 "me", "\n".join(list_mentions) +
                 f"\n\nfrom {message.chat.title}")
Esempio n. 9
0
def register(client: Client, message: Message) -> None:
    message.delete()
    user = message.from_user
    if Database.isUserRegistered(user):
        message.reply_text("Sei già registrato!")
        return
    messageWords: List[str] = message.text.split(' ')
    if len(messageWords) != 2:
        message.reply_text("Comando errato! \n Usa il comando /register <Password> per registrarti!")
        return
    if Database.isPasswordCorrect(messageWords[1]):
        message.reply_text("Correttamente registrato!")
        Database.registerUser(user)
    else:
        message.reply_text("Password errata!")
Esempio n. 10
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()
Esempio n. 11
0
async def paste(_, message: Message):
    text = message.reply_to_message.text
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post("https://nekobin.com/api/documents",
                                    json={"content": text},
                                    timeout=3) as response:
                key = (await response.json())["result"]["key"]
    except Exception:
        await message.edit_text("`Pasting failed`")
        await asyncio.sleep(2)
        await message.delete()
        return
    else:
        url = f"https://nekobin.com/{key}"
        reply_text = f"Nekofied to **Nekobin** : {url}"
        delete = (True if len(message.command) > 1
                  and message.command[1] in ["d", "del"]
                  and message.reply_to_message.from_user.is_self else False)
        if delete:
            await asyncio.gather(
                app.send_message(message.chat.id,
                                 reply_text,
                                 disable_web_page_preview=True),
                message.reply_to_message.delete(),
                message.delete(),
            )
        else:
            await message.edit_text(
                reply_text,
                disable_web_page_preview=True,
            )
Esempio n. 12
0
async def unsplash_pictures(bot: UserBot, message: Message):
    cmd = message.command

    if len(cmd) > 1 and isinstance(cmd[1], str):
        keyword = cmd[1]

        if len(cmd) > 2 and int(cmd[2]) < 10:
            await message.edit("```Getting Pictures```")
            count = int(cmd[2])
            images = []
            while len(images) is not count:
                img = await AioHttp().get_url(
                    f"https://source.unsplash.com/1600x900/?{keyword}")
                if img not in images:
                    images.append(img)

            for img in images:
                await bot.send_photo(message.chat.id, str(img))

            await message.delete()
            return
        else:
            await message.edit("```Getting Picture```")
            img = await AioHttp().get_url(
                f"https://source.unsplash.com/1600x900/?{keyword}")
            await asyncio.gather(message.delete(),
                                 bot.send_photo(message.chat.id, str(img)))
Esempio n. 13
0
async def neko(_, message: Message):
    text = message.reply_to_message.text
    try:
        params = {"content": text}
        headers = {'content-type': 'application/json'}
        url = "https://nekobin.com/api/documents"
        neko = requests.post(url, json=params, headers=headers)
        key = neko.json()["result"]["key"]
    except Exception:
        await message.edit_text("`API is down try again later`")
        await asyncio.sleep(2)
        await message.delete()
        return
    else:
        url = f"https://nekobin.com/{key}"
        reply_text = f"**Pasted to: [Nekobin]({url})**"
        delete = (True if len(message.command) > 1
                  and message.command[1] in ["d", "del"]
                  and message.reply_to_message.from_user.is_self else False)
        if delete:
            await asyncio.gather(
                app.send_message(message.chat.id,
                                 reply_text,
                                 disable_web_page_preview=True),
                message.reply_to_message.delete(),
                message.delete(),
            )
        else:
            await message.edit_text(
                reply_text,
                disable_web_page_preview=True,
            )
Esempio n. 14
0
async def paste(_, message: Message):
    text = message.reply_to_message.text
    try:
        params = {"content": text}
        headers = {'content-type': 'application/json'}
        url = "https://pasty.lus.pm/api/v2/pastes/"
        paste = requests.post(url, json=params, headers=headers)
        key = paste.json()["id"]
    except Exception:
        await message.edit_text("`API is down try again later`")
        await asyncio.sleep(2)
        await message.delete()
        return
    else:
        url = f"https://pasty.lus.pm/{key}"
        reply_text = f"**Pasted to: [Pasty]({url})\nRaw link: [Raw]({url}/raw)**"
        delete = (True if len(message.command) > 1
                  and message.command[1] in ["d", "del"]
                  and message.reply_to_message.from_user.is_self else False)
        if delete:
            await asyncio.gather(
                app.send_message(message.chat.id,
                                 reply_text,
                                 disable_web_page_preview=True),
                message.reply_to_message.delete(),
                message.delete(),
            )
        else:
            await message.edit_text(
                reply_text,
                disable_web_page_preview=True,
            )
Esempio n. 15
0
def neko(client: Client, message: Message):
    reply = message.reply_to_message

    if reply.text is None:
        return

    message.delete()

    result = requests.post(
        "{}/api/documents".format(BASE),
        data=dict(content=reply.text.encode("UTF-8"))).json()

    message.reply(
        "{}/{}.py".format(BASE, result["result"]["key"]),
        reply_to_message_id=reply.message_id,
    )
Esempio n. 16
0
async def quotly(_, message: Message):
    if not message.reply_to_message:
        await message.edit("Reply to any users text message")
        return
    await message.edit("```Making a Quote```")
    await message.reply_to_message.forward("@QuotLyBot")
    is_sticker = False
    progress = 0
    while not is_sticker:
        try:
            msg = await UserBot.get_history("@QuotLyBot", 1)
            check = msg[0]["sticker"]["file_id"]
            is_sticker = True
        except:
            await sleep(0.5)
            progress += random.randint(0, 10)
            try:
                await message.edit(
                    "```Making a Quote```\nProcessing {}%".format(progress))
            except:
                await message.edit("ERROR SUUUU")
    if msg_id := msg[0]['message_id']:
        await asyncio.gather(
            message.delete(),
            UserBot.forward_messages(message.chat.id, "@QuotLyBot", msg_id))
Esempio n. 17
0
async def mark_chat_unread(_, message: Message):
    await asyncio.gather(
        message.delete(),
        UserBot.send(
            functions.messages.MarkDialogUnread(peer=await
                                                UserBot.resolve_peer(
                                                    message.chat.id),
                                                unread=True)))
Esempio n. 18
0
async def reply_and_delete(message: Message, text: str):
    await asyncio.gather(
        message.delete(),
        message.reply(text,
                      quote=False,
                      reply_to_message_id=getattr(message.reply_to_message,
                                                  "message_id", None),
                      disable_web_page_preview=True))
Esempio n. 19
0
async def rtfd(_, message: Message):
    """Tell to RTFD (rude)"""
    await asyncio.gather(
        message.delete(),
        message.reply_photo("https://i.imgur.com/a08Ju2e.png",
                            quote=False,
                            caption=RTFD,
                            reply_to_message_id=getattr(
                                message.reply_to_message, "message_id", None)))
Esempio n. 20
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)),
    )
Esempio n. 21
0
async def screenshot(_, message: Message):
    await asyncio.gather(
        message.delete(),
        UserBot.send(
            functions.messages.SendScreenshotNotification(
                peer=await UserBot.resolve_peer(message.chat.id),
                reply_to_msg_id=0,
                random_id=UserBot.rnd_id(),
            )),
    )
Esempio n. 22
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,
    )
Esempio n. 23
0
def startAuction(client: Client, message: Message) -> None:
    if bool(runningAuctions):
        return
    sender: User = message.from_user
    group = message.chat
    administrators = [admin.user.id for admin in group.iter_members(filter="administrators")]
    cond1 = sender.id not in administrators
    cond2 = client.get_me().id not in administrators
    if cond1 or cond2:
        return
    message.delete()
    messageWords: List[str] = message.text.split(' ')
    if len(messageWords) != 2:
        return
    for auction in auctions:
        if auction.name == messageWords[1]:
            runningAuction = auction.start(group)
            _timeOut(runningAuction)
            break
Esempio n. 24
0
async def dot_auto_forwarding(_, message: Message):
    """
    Listen for messages sent in reply with a dot and forward
    the replied message to the current chat instead of your dot reply.
    """
    if json_settings.data.get("dot_auto_forward"):
        asyncio.gather(
            message.reply_to_message.forward(message.chat.id, disable_notification=True),
            message.delete(),
        )
Esempio n. 25
0
async def generate_qr(bot: UserBot, message: Message):
    if qr_text := await UserBot.extract_command_text(message):
        img = qrcode.make(qr_text)

        with open('downloads/qr.png', 'wb') as f:
            img.save(f)

        await asyncio.gather(
            bot.send_photo(message.chat.id, 'downloads/qr.png'),
            message.delete()
        )
Esempio n. 26
0
async def fmt(_, message: Message):
    """Tell to format code"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            FMT,
            quote=False,
            parse_mode="html",
            disable_web_page_preview=True,
            reply_to_message_id=getattr(message.reply_to_message, "message_id",
                                        None),
        ))
Esempio n. 27
0
async def give_pats(_, message: Message):
    URL = "https://some-random-api.ml/animu/pat"
    async with aiohttp.ClientSession() as session:
        async with session.get(URL) as request:
            if request.status == 404:
                return await message.edit("`no Pats for u :c")
            result = await request.json()
            url = result.get("link", None)
            await asyncio.gather(
                message.delete(),
                UserBot.send_video(GetChatID(message), url, reply_to_message_id=ReplyCheck(message))
            )
Esempio n. 28
0
async def help(bot: Assistant, message: Message):
    """Show this message"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            HELP,
            quote=False,
            reply_to_message_id=getattr(
                message.reply_to_message,
                "message_id", None
            ),
            )
    )
Esempio n. 29
0
async def help(bot: Assistant, message: Message):
    """Show this message"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            HELP,
            quote=False,
            reply_to_message_id=getattr(message.reply_to_message, "message_id",
                                        None),
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Remove Help",
                                     f"remove.{message.from_user.id}")
            ]]),
        ))
Esempio n. 30
0
async def commit_graph(_, message: Message):
    if len(message.command) < 2:
        await message.edit(
            "Please provide a github profile username to generate the graph!"
        )
        await sleep(2)
        await message.delete()
        return
    else:
        git_user = message.command[1]

    url = f"https://ghchart.rshah.org/{git_user}"
    file_name = f"{randint(1, 999)}{git_user}"

    resp = await AioHttp.get_raw(url)
    f = await aiofiles.open(f"{file_name}.svg", mode="wb")
    await f.write(resp)
    await f.close()

    try:
        drawing = svg2rlg(f"{file_name}.svg")
        renderPM.drawToFile(drawing, f"{file_name}.png")
    except UnboundLocalError:
        await message.edit("Username does not exist!")
        await sleep(2)
        await message.delete()
        return

    await asyncio.gather(
        UserBot.send_photo(
            chat_id=message.chat.id,
            photo=f"{file_name}.png",
            caption=git_user,
            reply_to_message_id=ReplyCheck(message),
        ),
        message.delete(),
    )

    for file in iglob(f"{file_name}.*"):
        os.remove(file)