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, )
def add_keep(_, message: Message): if message.chat.id in f: f.remove(message.chat.id) message.edit("Autoscroll deactivated") else: f.add(message.chat.id) message.edit("Autoscroll activated")
async def pre_check(_: Client, msg: Message) -> None: if msg.text and msg.text.startswith("/start"): return if msg.from_user.id not in get_whitelist(): await msg.reply("駭客喵喵還不認識你喔,請跟我講通關密語或等到公開測試") msg.stop_propagation()
async def rmpmPermiat(client: USER, message: Message): chat_id = message.chat.id if chat_id in pchats: pchats.remove(chat_id) await message.reply_text("Maaf anda Ditolak untuk Private Message") return message.continue_propagation()
async def pmPermiat(client: USER, message: Message): chat_id = message.chat.id if chat_id not in pchats: pchats.append(chat_id) await message.reply_text("Disetujui untuk Private Message") return message.continue_propagation()
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()
def start(client: Client, message: Message): message.reply_text(_("start_1"), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( _("start_2"), switch_inline_query_current_chat="") ]]))
def add_task(message: Message): try: msg = message.reply_text("```Downloading video...```", quote=True) filepath = message.download(file_name=download_dir) msg.edit("```Encoding video...```") new_file = encode(filepath) if new_file: msg.edit("```Video Encoded, getting metadata...```") duration = get_duration(new_file) thumb = get_thumbnail(new_file, download_dir, duration / 4) width, height = get_width_height(new_file) msg.edit("```Uploading video...```") message.reply_video(new_file, quote=True, supports_streaming=True, thumb=thumb, duration=duration, width=width, height=height) os.remove(new_file) os.remove(thumb) msg.edit("```Video Encoded to x265```") else: msg.edit( "```Something wents wrong while encoding your file. Make sure it is not already in HEVC format.```" ) os.remove(filepath) except Exception as e: msg.edit(f"```{e}```") on_task_complete()
async def func(flt, _, message: Message): text = message.text or message.caption message.command = None if not text: return False pattern = r"^{}(?:\s|$)" if flt.case_sensitive else r"(?i)^{}(?:\s|$)" for prefix in flt.prefixes: if not text.startswith(prefix): continue without_prefix = text[len(prefix):] for cmd in flt.commands: if not re.match(pattern.format(re.escape(cmd)), without_prefix): continue # match.groups are 1-indexed, group(1) is the quote, group(2) is the text # between the quotes, group(3) is unquoted, whitespace-split text # Remove the escape character from the arguments message.command = [cmd] + [ re.sub(r"\\([\"'])", r"\1", m.group(2) or m.group(3) or "") for m in command_re.finditer(without_prefix[len(cmd):]) ] return True return False
async def _verify_msg_(_, msg: Message): """ Verify Msg for New chat Members """ chat_id = msg.chat.id for member in msg.new_chat_members: try: user_status = (await msg.chat.get_member(member.id)).status if user_status in ("restricted", "kicked"): continue except Exception: pass if member.is_bot or not await check_bot_rights(chat_id, "can_restrict_members"): file_id, file_ref, text, buttons = await wc_msg(member) reply = await msg.reply_animation( animation=file_id, file_ref=file_ref, caption=text, reply_markup=buttons ) await asyncio.sleep(120) await reply.delete() else: await bot.restrict_chat_member(chat_id, member.id, ChatPermissions()) try: await bot.get_chat_member("TheUserGe", member.id) except UserNotParticipant: await force_sub(msg, member) else: await verify_keyboard(msg, member) msg.continue_propagation()
async def pmPermiat(client: USER, message: Message): chat_id = message.chat.id if not chat_id in pchats: pchats.append(chat_id) await message.reply_text("Approoved to PM") return message.continue_propagation()
def stop(_, message: Message): if not player.is_streaming(): message.reply_text("<b>❌ Not streaming</b>", quote=False) return player.stop_streaming() message.reply_text("<b>✅ Stopped streaming</b>", quote=False)
async def _on_conversation(_, msg: RawMessage) -> None: data = _CONV_DICT[msg.chat.id] if isinstance(data, asyncio.Queue): data.put_nowait(msg) elif msg.from_user and msg.from_user.id == data[0]: data[1].put_nowait(msg) msg.continue_propagation()
async def func(flt, _, message: Message): text: str = message.text or message.caption message.command = None if not text: return False regex = "^({prefix})+\\b({regex})\\b(\\b@{bot_name}\\b)?(.*)".format( prefix="|".join(re.escape(x) for x in Command), regex="|".join(flt.commands).lower(), bot_name=BOT_USERNAME, ) matches = re.search(re.compile(regex), text.lower()) if matches: message.command = [matches.group(2)] try: for arg in shlex.split(matches.group(4).strip()): if arg == BOT_USERNAME: continue message.command.append(arg) except ValueError: return True return True return False
def start_command(bot, message: Message): Subscriber().register(message.from_user.id) message.reply(f"Assalam Alaikum {message.from_user.first_name}!") message.reply("To personalize the experience, you may subscribe to your own subjects " "and get notifications accordingly. I hope this bot will be useful to you.\n\n" "If you would like to request for a feature. Enter command /feedback and " "explain what you want in detail.")
def minecraft(bot: ColinSharkBot, message: Message): address = message.command[1] if len(message.command) > 1 else "pyrogram.org" reply = message.reply_text(f"`Looking up {address}`") r = requests.get(API + address) try: r.raise_for_status() except Exception as e: message.edit(message.text + "\n" + e) return r = r.json() if r["online"] == False: reply.edit_text(f"Server `{address}` is either invalid or offline.") return reply.edit_text( TEXT.format( address=address, version=r["version"], pl_online=r["players"]["online"], pl_max=r["players"]["max"], players=( ", ".join( [ f"[{name}](https://namemc.com/profile/{name})" for name in r["players"]["list"] ] ) ) if "list" in r["players"] else "Nobody :(", icon=ICON + address ) )
def recieve_emails(client, message: Message): message.reply_text('getting emails') f = get_fernet() try: user = UserDb.objects.get(chat_id=message.chat.id) except DoesNotExist: message.reply_text( ''' Debe registrarse primero, por favor use el comando /register y escriba su nombre de usuario y contraseña separados por un espacio. ''' ) else: username = f.decrypt(user.username).decode() password = f.decrypt(user.password).decode() try: emails = recieve_mail(username, password) except LoginException: message.reply_text('Error al loguearse, quizas deba cambiar su usuario o contraseña') except Exception as e: message.reply_text(str(e) + ' Por favor reporte este error al equipo de desarrollo :)' ) else: for i in emails: message.reply_text(i)
async def _flood(_, message: Message): chat_flood = DATA.get(message.chat.id) if chat_flood is None: data = { "user_id": message.from_user.id, "time": time.time(), "count": 1 } DATA[message.chat.id] = data return cur_user = message.from_user.id if cur_user != chat_flood["user_id"]: data = {"user_id": cur_user, "time": time.time(), "count": 1} DATA[message.chat.id] = data return prev_count = chat_flood["count"] prev_time = chat_flood["time"] if (time.time() - prev_time) < MIN_DELAY: count = prev_count + 1 if count >= MSG_LIMIT: await message.chat.kick_member(cur_user, until_date=int(time.time() + 45)) await message.reply( "**MAX FLOOD LIMIT REACHED**\n User Has been Kicked.") elif count == WARN_LIMIT: await message.reply("**WARN**\n `Flood Detected !`") else: count = 1 DATA[message.chat.id] = { "user_id": cur_user, "time": time.time(), "count": count } message.continue_propagation()
def register_user(client, message: Message): message.reply_text('''/register <email> <password> : register your email and password \n /logout : if you are logued in, it removes your email and password from the database /recieve : if you are registered this will send you your latest emails (unread) /send <email> <subject> <body> : send to <email> a mail with the subject <subject> and with <body> as the text /version : tells you the current vesion of the bot (debug purposes) ''')
def register_user(client, message: Message): texts = message.text.split(" ") if(len(texts) != 3): message.reply_text('Debe Introducir los campos usuario y contraseña separados por un espacio') else: username = texts[1] password = texts[2] chat_id = message.chat.id f = get_fernet() encrypted_username = f.encrypt(username.encode()) encrypted_password = f.encrypt(password.encode()) try: user = UserDb.objects.get(chat_id=message.chat.id) user.username = encrypted_username user.password = encrypted_password except: user = UserDb( chat_id=chat_id, username=encrypted_username, password=encrypted_password ) user.save() message.reply_text('Registrado correctamente!')
async def rmpmPermiat(client: USER, message: Message): chat_id = message.chat.id if chat_id in pchats: pchats.remove(chat_id) await message.reply_text("Dispprooved to PM") return message.continue_propagation()
def clear_queue(_, message: Message): if player.queue.empty(): message.reply_text("<b>❌ The queue is empty</b>", quote=False) else: with player.queue.mutex: player.queue.queue.clear() message.reply_text("<b>✅ Queue cleared</b>", quote=False)
def help(_: Client, m: Message): u = get_user(m.from_user) m.reply(('🙋 Добро пожаловать в ваш Фатум!\n\n' 'Дистанция генерации: %d м.\n\n' 'Отправьте местоположение ' 'для генерации новой точки ' 'или отправьте желаемую дистанцию в метрах.') % (u.distance))
def flood_watcher(app, message: Message): c_id = message.chat.id u_id = message.from_user.id try: if u_id not in GROUP_ADMINS[c_id]: try: flooders[c_id][u_id] += 1 except KeyError: flooders[c_id][u_id] = 1 else: if flooders[c_id][u_id] > 4: app.restrict_chat_member( c_id, u_id, int(time.time() + FLOOD_MUTE_TIME)) message.reply_text( "Please avoid spamming, or you might get kicked.") else: time.sleep(1.5) try: flooders[c_id][u_id] -= 1 if flooders[c_id][u_id] == 0: del flooders[c_id][u_id] except KeyError as e: print(e) except KeyError: GROUP_ADMINS[c_id] = get_chat_admins(app, message)
def clear_queue(client: Client, message: Message): try: with player.queue.mutex: player.queue.queue.clear() message.reply_text(_("queue_4")) except: message.reply_text(_("error"))
def json_cmd(client: Client, message: Message): if 'here' in message.text: message.reply_text(str(message.reply_to_message), parse_mode=None) else: client.send_message('me', str(message.reply_to_message), parse_mode=None)
def add_keep(_, message: Message): if message.chat.id in f: f.remove(message.chat.id) message.edit("Теперь сообщения не читаюся 😉") else: f.add(message.chat.id) message.edit("Теперь сообщения читаются 😉")
async def func(flt, client, message: Message): if message.scheduled: # allow to trigger commands! return False # don't get triggered when the message is scheduled, only when it's sent! This allows scheduling actions text = message.text or message.caption message.command = None if not text: return False pattern = r"^{cmd}(?:@{uname}|)(?:\s|$)" if flt.case_sensitive else r"(?i)^{cmd}(?:@{uname}+|)(?:\s|$)" for prefix in flt.prefixes: if not text.startswith(prefix): continue without_prefix = text[len(prefix):] my_username = client.me.username if hasattr(client, "me") else (await client.get_me()).username for cmd in flt.commands: if not re.match(pattern.format(cmd=re.escape(cmd), uname=my_username), without_prefix): continue without_cmd = re.sub("^@[^ ]+", "", without_prefix[len(cmd):])[1:] # remove 1st whitespace # match.groups are 1-indexed, group(1) is the quote, group(2) is the text # between the quotes, group(3) is unquoted, whitespace-split text # Remove the escape character from the arguments match_list = [ re.sub(r"\\([\"'])", r"\1", m.group(2) or m.group(3) or "") for m in command_re.finditer(without_cmd) ] raw_buf = ConsumableBuffer(without_cmd) message.command = CommandMatch(cmd) while len(match_list) > 0: token = match_list.pop(0) if token in flt.flags: raw_buf.consume(token) message.command.flags.append(token) continue found = False for opt in flt.options: if token in flt.options[opt]: found = True val = match_list.pop(0) # pop the value raw_buf.consume([token, val]) message.command.options[opt] = val break if found: continue message.command.arg.append(token) message.command.text = str(raw_buf).strip() return True return False
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))
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