from pyrogram import Client, Filters, InlineKeyboardButton, InlineKeyboardMarkup import os blacklist = ['drive.google.com', 'tor.checker.in'] HOME = InlineKeyboardMarkup([ [InlineKeyboardButton(text='Format - PDF', callback_data='format')], [InlineKeyboardButton(text='Page - Full', callback_data="page")], # [InlineKeyboardButton(text='Landscape', callback_data="orientation")], [InlineKeyboardButton(text='show additional options ˅', callback_data="options")], [InlineKeyboardButton(text='▫️ start render ▫️', callback_data="render")], [InlineKeyboardButton(text='cancel', callback_data="cancel")] ]) format_for_logging = "Request from {name} aka @{user}\n\nQuery : {link}\n\nSettings Used : \n {settings}" @Client.on_message(Filters.command(["start"])) async def start(client, message): await client.send_message( chat_id=message.chat.id, text=f"Please Send Any Link", reply_to_message_id=message.message_id ) @Client.on_message(Filters.command(["feedback"])) async def feedback(client, message): await client.send_message( chat_id=message.chat.id, text=f"for suggetions and feedbacks contact @STARKTM1", reply_to_message_id=message.message_id )
def action_ask(client: Client, message: Message) -> bool: # Ask how to deal with the report message try: # Basic data cid = message.chat.id mid = message.message_id aid = message.from_user.id fid = message.forward_from_message_id channel_id = message.forward_from_chat.id report_message = get_message(client, channel_id, fid) r_message = report_message.reply_to_message report_text = get_text(report_message) record = get_report_record(report_message) # Init action = "" # Rollback if is_exchange_channel(None, message): data = receive_text_data(report_message) if not data: return True data_action = data["action"] data_action_type = data["type"] if data_action == "backup": if data_action_type == "data": action = "rollback" # Recall ERROR elif is_error_channel(None, message): action = "recall" # Actions about LOGGING elif re.search(f"^{lang('project')}{lang('colon')}", report_text): if record["status"] == lang("status_redact"): action = "" elif record["project"] in glovar.receivers["except"]: if r_message or record["type"] in {lang("gam"), lang("ser")}: action = "error" elif record["project"] == "WARN": if r_message or record["type"] in {lang("gam"), lang("ser")}: action = "bad" elif record["project"] == "MANAGE" and record["status"] != lang( "status_delete"): if record["status"] == lang("status_mole"): action = "error" elif record["status"] == lang("status_innocent"): action = "bad" elif record["status"] in { lang("status_error"), lang("status_unban") }: action = "mole" elif record["status"] == lang("status_bad"): action = "innocent" elif not r_message or record["status"] == lang("status_delete"): action = "redact" else: action = "delete" # Check the action if not action: return True # Generate key key = random_str(8) while glovar.actions.get(key): key = random_str(8) # Log data glovar.actions[key] = { "lock": False, "time": get_now(), "mid": 0, "aid": aid, "action": action, "message": report_message, "record": record } if action == "rollback": data = receive_text_data(report_message) glovar.actions[key]["sender"] = data["from"] glovar.actions[key]["type"] = data["data"] # Generate the report message's text text = ( f"{lang('admin')}{lang('colon')}{mention_id(aid)}\n" f"{lang('action')}{lang('colon')}{code(lang(f'action_{action}'))}\n" f"{lang('status')}{lang('colon')}{code(lang('status_wait'))}\n") # Generate the report message's markup data_proceed = button_data(action, "proceed", key) data_cancel = button_data(action, "cancel", key) markup_list = [[ InlineKeyboardButton(text=lang("proceed"), callback_data=data_proceed) ], [ InlineKeyboardButton(text=lang("cancel"), callback_data=data_cancel) ]] if action not in {"delete", "redact", "recall", "rollback"}: if r_message and not r_message.empty: data_delete = button_data(action, "delete", key) markup_list[0].append( InlineKeyboardButton(text=lang("delete"), callback_data=data_delete)) else: data_delete = button_data("redact", "delete", key) markup_list[0].append( InlineKeyboardButton(text=lang("redact"), callback_data=data_delete)) markup = InlineKeyboardMarkup(markup_list) # Send the report message result = send_message(client, cid, text, mid, markup) # Save data if result: glovar.actions[key]["mid"] = result.message_id glovar.records[key] = {} for item in glovar.actions[key]: if item in {"lock", "time", "mid"}: glovar.records[key][item] = deepcopy( glovar.actions[key][item]) save("records") else: glovar.actions.pop(key, {}) return True except Exception as e: logger.warning(f"Check error error: {e}", exc_info=True) return False
def taco_mention_callback(bot, message): """ callback for taco-transfer by mention """ cid = get_cid(message) store_name(message.from_user) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, bot, None) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format( message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) mentioned_users = list() for entity in message.entities: if entity.type == 'mention': user = message.text[entity.offset:entity.offset + entity.length].lower() mentioned_users.append(user) mentioned_users = list(set(mentioned_users)) if len(mentioned_users) > 1: if chat.less is True: text = only_one_receiver_phrase.split('\n')[0] else: text = only_one_receiver_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = [mid] chat.save() return sender = message.from_user receiver_username: str = ensure_no_at_sign(mentioned_users[0]) try: receiver = bot.get_chat_member(chat_id=cid, user_id=receiver_username).user except Exception: """ here should be except UserNotParticipant, but it still raises this exception """ if chat.less is True: text = user_not_present_phrase.split('\n')[0] else: text = user_not_present_phrase mid = bot.send_message(chat_id=cid, text=text.format( ensure_username(receiver_username)), reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = [mid] chat.save() return give_tacos(bot, message, sender, receiver)
async def display_settings(c, m, cb=False): chat_id = m.from_user.id if cb else m.chat.id as_file = await c.db.is_as_file(chat_id) as_round = await c.db.is_as_round(chat_id) watermark_text = await c.db.get_watermark_text(chat_id) sample_duration = await c.db.get_sample_duration(chat_id) watermark_color_code = await c.db.get_watermark_color(chat_id) screenshot_mode = await c.db.get_screenshot_mode(chat_id) font_size = await c.db.get_font_size(chat_id) sv_btn = [ InlineKeyboardButton("Sample Video Duration", 'rj'), InlineKeyboardButton(f"{sample_duration}s", 'set+sv') ] wc_btn = [ InlineKeyboardButton("Watermark Color", 'rj'), InlineKeyboardButton(f"{Config.COLORS[watermark_color_code]}", 'set+wc') ] fs_btn = [ InlineKeyboardButton("Watermark Font Size", 'rj'), InlineKeyboardButton(f"{Config.FONT_SIZES_NAME[font_size]}", 'set+fs') ] as_file_btn = [InlineKeyboardButton("Upload Mode", 'rj')] wm_btn = [InlineKeyboardButton("Watermark", 'rj')] sm_btn = [InlineKeyboardButton("Screenshot Generation Mode", 'rj')] if as_file: as_file_btn.append( InlineKeyboardButton("📁 Uploading as Document.", 'set+af')) else: as_file_btn.append( InlineKeyboardButton("🖼️ Uploading as Image.", 'set+af')) if watermark_text: wm_btn.append(InlineKeyboardButton(f"{watermark_text}", 'set+wm')) else: wm_btn.append(InlineKeyboardButton("No watermark exists!", 'set+wm')) if screenshot_mode == 0: sm_btn.append( InlineKeyboardButton("Equally spaced screenshots", 'set+sm')) else: sm_btn.append(InlineKeyboardButton("Random screenshots", 'set+sm')) settings_btn = [as_file_btn, wm_btn, wc_btn, fs_btn, sv_btn, sm_btn] if cb: try: await m.edit_message_reply_markup( InlineKeyboardMarkup(settings_btn)) except: pass return await m.reply_text(text=f"Here You can configure my behavior.", quote=True, reply_markup=InlineKeyboardMarkup(settings_btn))
from pyrogram import Client, Filters, InlineKeyboardMarkup, InlineKeyboardButton from ..config import CACHE, ADMINS, ADMINS_LIST_UPDATE_DELAY, callback_regex, admin_is_chatting, \ user_is_chatting, LIVE_CHAT_STATUSES, STATUS_BUSY, STATUS_FREE, SUPPORT_REQUEST_SENT, SUPPORT_NOTIFICATION, \ ADMIN_JOINS_CHAT, USER_CLOSES_CHAT, JOIN_CHAT_BUTTON, USER_INFO, USER_LEAVES_CHAT, ADMIN_MESSAGE, USER_MESSAGE, \ TOO_FAST, CHAT_BUSY, LEAVE_CURRENT_CHAT, USER_JOINS_CHAT, NAME, CANNOT_REQUEST_SUPPORT, YES, NO, user_banned, CLOSE_CHAT_BUTTON, BACK_BUTTON, UPDATE_BUTTON, bot, \ ADMIN_ACCEPTED_CHAT import time from ..database.query import get_user from .antiflood import BANNED_USERS from .start import back_start import logging from ..methods import MethodWrapper ADMINS_FILTER = Filters.user(list(ADMINS.keys())) BUTTONS = InlineKeyboardMarkup( [[InlineKeyboardButton(BACK_BUTTON, "back_start")], [InlineKeyboardButton(UPDATE_BUTTON, "update_admins_list")]]) wrapper = MethodWrapper(bot) @Client.on_callback_query( Filters.regex("sos") & ~BANNED_USERS & ~user_banned()) def begin_chat(client, query): cb_wrapper = MethodWrapper(query) if query.from_user.id in ADMINS: cb_wrapper.answer(CANNOT_REQUEST_SUPPORT) else: CACHE[query.from_user.id] = ["AWAITING_ADMIN", time.time()] queue = LIVE_CHAT_STATUSES for admin_id, admin_name in ADMINS.items(): status = CACHE[admin_id][0]
async def pm_button(client, query): if not PM_PERMIT: return if query.from_user.id in AdminSettings and not re.match( "engine_pm_apr", query.data) and not re.match( r"engine_pm_blk", query.data): await client.answer_callback_query(query.id, "No, you can't click by yourself", show_alert=False) return if re.match(r"engine_pm_block", query.data): await app.send_sticker(query.from_user.id, sticker='CAADAgAD1QQAAp7kTAry1JrL3zVXSxYE') await app.send_message( query.from_user.id, "Sorry, No cash.\nAlso you are getting reported to **SpamWatch**, OwO" ) await app.block_user(query.from_user.id) elif re.match(r"engine_pm_nope", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Hello, please wait for a reply from my master, thank you") buttons = InlineKeyboardMarkup([[ InlineKeyboardButton( "Approve", callback_data=f"engine_pm_apr-{query.from_user.id}"), InlineKeyboardButton( "Block", callback_data=f"engine_pm_blk-{query.from_user.id}") ]]) pm_bot_mention = mention_markdown(query.from_user.id, query.from_user.first_name) pm_bot_message = f"[{OwnerName}](tg://user?id={Owner}), {pm_bot_mention} want to contact you~" await setbot.send_message(NOTIFY_ID, pm_bot_message, reply_markup=buttons) set_req(query.from_user.id, True) elif re.match("engine_pm_report", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Hello, if you want to report any bugs, please vist in @NanaBotSupport" ) elif re.match("engine_pm_none", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Alright then,\nIf you want anything from me, please contact my again. Thank you" ) elif re.match("engine_pm_apr", query.data): target = query.data.split("-")[1] await query.message.edit_text(f"[Approved for PM]({target})") await app.send_message( target, "Hello, this is **Nana**, my master approved you to PM.") set_whitelist(int(target), True) elif re.match(r"engine_pm_blk", query.data): target = query.data.split("-")[1] await query.message.edit_text("That user was blocked ~") await app.send_message( target, "Hello, this is **Nana**, my master has decide to block you.\nSorry for this!" ) await app.block_user(target) else: await setbot.edit_inline_text(query.inline_message_id, "🙆")
def instagram(client, message): bekle = message.reply("Bekleyin...") metin = message.text hesap_isim = metin.split() hesap_isim_duzen = " ".join(hesap_isim[1:]) if len(hesap_isim) <= 1: bekle.edit("Lütfen bir hesap ismi giriniz") else: br = webdriver.Chrome( executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options) br.get(f"https://www.instagram.com/{hesap_isim_duzen}/?hl=tr") wait = WebDriverWait(br, 20) pp = br.find_elements_by_tag_name("img") if len(pp) == 0: bekle.edit( f"**{hesap_isim_duzen}** isimli bir hesap bulunmamaktadır") else: liste = [] for i in pp: liste.append(i.get_attribute("src")) random_sayi = random.randint(1, 100000) liste = liste[0] urllib.request.urlretrieve(liste, f"pp{random_sayi}.png") client.send_photo(message.chat.id, f"pp{random_sayi}.png") os.remove(f"pp{random_sayi}.png") gonderi = wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="react-root"]/section/main/div/header/section/ul/li[1]/a/span' ))) takipci = wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a/span' ))) takip = wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="react-root"]/section/main/div/header/section/ul/li[3]/a/span' ))) mesaj1 = "**{}** isimli hesabın:\n\nGönderi sayısı: **{}**\nTakipçi sayısı: **{}**\nTakip sayısı: **{}**".format( hesap_isim_duzen, gonderi.text, takipci.text, takip.text) bekle.edit( mesaj1, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( "Grubumuza Katılın", url="https://t.me/joinchat/PNPv9RJrHf8F0KlPCaC4-Q") ]]))
["E", "F", "G"], # Second row ["H", "I"], # Third row ["J"] # Fourth row ], resize_keyboard=True # Make the keyboard smaller ) ) app.send_message( "haskell", # Edit this "This is a InlineKeyboardMarkup example", reply_markup=InlineKeyboardMarkup( [ [ # First row # Generates a callback query when pressed InlineKeyboardButton("Button", callback_data="data"), # Opens a web URL InlineKeyboardButton("URL", url="https://docs.pyrogram.ml"), ], [ # Second row # Opens the inline interface of a bot in another chat with a pre-defined query InlineKeyboardButton("Choose chat", switch_inline_query="pyrogram"), # Same as the button above, but the inline interface is opened in the current chat InlineKeyboardButton("Inline here", switch_inline_query_current_chat="pyrogram"), ] ] ) ) app.stop()
def updateMsgs(client, message, redis): type = message.chat.type userID = message.from_user.id chatID = message.chat.id username = message.from_user.username if username is None: username = "******" userFN = message.from_user.first_name title = message.chat.title rank = isrank(redis, userID, chatID) text = message.text ADDed = """◀️꒐ بواسطه ⌁ {} ✅꒐ {} بالفعل مفعله في المجموعة""" ADD = """◀️꒐ بواسطه ⌁ {} ✅꒐ تم تفعيل {} في المجموعة""" unADDed = """◀️꒐ بواسطه ⌁ {} ❎꒐ {} بالفعل معطله في المجموعة""" unADD = """◀️꒐ بواسطه ⌁ {} ❎꒐ تم تعطيل {} في المجموعة""" if (rank is not False or rank is not 0 or rank != "vip"): if text == "تفعيل الالعاب": R = text.split(" ")[1] get = redis.sismember("{}Nbot:gpgames".format(BOT_ID), chatID) BY = "<a href=\"tg://user?id={}\">{}</a>".format(userID, userFN) if get: save = redis.srem("{}Nbot:gpgames".format(BOT_ID), chatID) Bot( "sendMessage", { "chat_id": chatID, "text": ADD.format(BY, R), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True }) else: Bot( "sendMessage", { "chat_id": chatID, "text": ADDed.format(BY, R), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True }) if text == "تعطيل الالعاب": R = text.split(" ")[1] BY = "<a href=\"tg://user?id={}\">{}</a>".format(userID, userFN) get = redis.sismember("{}Nbot:gpgames".format(BOT_ID), chatID) if get: Bot( "sendMessage", { "chat_id": chatID, "text": unADDed.format(BY, R), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True }) else: save = redis.sadd("{}Nbot:gpgames".format(BOT_ID), chatID) Bot( "sendMessage", { "chat_id": chatID, "text": unADD.format(BY, R), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True }) games = {"rps.py": "🧱📃✂️", "xo.py": "❌ ⭕️"} if text and re.search("^الالعاب$|^العاب$", text) and not redis.sismember( "{}Nbot:gpgames".format(BOT_ID), chatID): tx = "🕹꒐ اليك الالعاب المقدمه من (<a href=\"http://t.me/zx_xx\">TshakeTeam</a>)" onlyfiles = [f for f in listdir("files") if isfile(join("files", f))] array = [] if not onlyfiles: return False for f in onlyfiles: if f in games: array.append( [InlineKeyboardButton(games[f], callback_data=f + "play")]) kb = InlineKeyboardMarkup(array) Bot( "sendMessage", { "chat_id": chatID, "text": tx, "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True, "reply_markup": kb }) if text and re.search("^نقاطي$", text): points = (redis.hget("{}Nbot:{}:points".format(BOT_ID, chatID), userID) or 0) Bot( "sendMessage", { "chat_id": chatID, "text": "🔢꒐ نقاطك :- ({})".format(points), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True })
def allGP(client, message, redis): type = message.chat.type userID = message.from_user.id chatID = message.chat.id username = message.from_user.username if username is None: username = "******" userFN = message.from_user.first_name title = message.chat.title rank = isrank(redis, userID, chatID) text = message.text if redis.sismember("{}Nbot:lang:ar".format(BOT_ID), chatID): lang = "ar" elif redis.sismember("{}Nbot:lang:en".format(BOT_ID), chatID): lang = "en" else: lang = "ar" moduleCMD = "lang." + lang + "-cmd" moduleREPLY = "lang." + lang + "-reply" c = importlib.import_module(moduleCMD) r = importlib.import_module(moduleREPLY) redis.hincrby("{}Nbot:{}:msgs".format(BOT_ID, chatID), userID) if text: if re.search(c.ShowO, text) and (rank is not False or rank is not 0 or rank != "vip"): reply_markup = getOR(rank, r, userID) Bot( "sendMessage", { "chat_id": chatID, "text": r.Showall, "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True, "reply_markup": reply_markup }) if text == c.ID and not redis.sismember( "{}Nbot:IDSend".format(BOT_ID), chatID) and not message.reply_to_message: Ch = True if redis.sismember("{}Nbot:IDpt".format(BOT_ID), chatID): t = IDrank(redis, userID, chatID, r) msgs = (redis.hget("{}Nbot:{}:msgs".format(BOT_ID, chatID), userID) or 0) edits = (redis.hget("{}Nbot:{}:edits".format(BOT_ID, chatID), userID) or 0) rate = int(msgs) * 100 / 20000 if redis.hget("{}Nbot:SHOWid".format(BOT_ID), chatID): tx = redis.hget("{}Nbot:SHOWid".format(BOT_ID), chatID) else: tx = r.IDnPT if not redis.sismember("{}Nbot:IDSendPH".format(BOT_ID), chatID): get = Bot("getUserProfilePhotos", { "user_id": userID, "offset": 0, "limit": 1 }) if get["ok"] == False: Ch = True elif get["result"]["total_count"] == 0: Ch = True else: Ch = False file_id = get["result"]["photos"][0][0]["file_id"] Bot( "sendPhoto", { "chat_id": chatID, "photo": file_id, "caption": tx.format(us=("@" + username or "None"), id=userID, rk=t, msgs=msgs, edits=edits, rate=str(rate) + "%"), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if Ch == True: Bot( "sendMessage", { "chat_id": chatID, "text": tx.format(us=("@" + username or "None"), id=userID, rk=t, msgs=msgs, edits=edits, rate=str(rate) + "%"), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if not redis.sismember("{}Nbot:IDSendPH".format(BOT_ID), chatID) and not redis.sismember( "{}Nbot:IDpt".format(BOT_ID), chatID): get = Bot("getUserProfilePhotos", { "user_id": userID, "offset": 0, "limit": 1 }) if get["ok"] == False: Ch = True elif get["result"]["total_count"] == 0: Ch = True else: Ch = False reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton(r.RIDPHs, callback_data=json.dumps( ["ShowDateUser", "", userID])) ]]) file_id = get["result"]["photos"][0][0]["file_id"] Bot( "sendPhoto", { "chat_id": chatID, "photo": file_id, "caption": r.RID.format(userID), "reply_to_message_id": message.message_id, "parse_mode": "html", "reply_markup": reply_markup }) if Ch == True and not redis.sismember("{}Nbot:IDpt".format(BOT_ID), chatID): reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton(r.RIDPHs, callback_data=json.dumps( ["ShowDateUser", "", userID])) ]]) Bot( "sendMessage", { "chat_id": chatID, "text": r.RID.format(userID), "reply_to_message_id": message.message_id, "parse_mode": "html", "reply_markup": reply_markup }) if text == c.ID and not redis.sismember( "{}Nbot:IDSend".format(BOT_ID), chatID) and message.reply_to_message: us = message.reply_to_message.from_user.id Bot( "sendMessage", { "chat_id": chatID, "text": us, "reply_to_message_id": message.message_id, "parse_mode": "html" }) if re.search(c.idus, text) and not redis.sismember( "{}Nbot:IDSend".format(BOT_ID), chatID): user = text.split("@")[1] try: getUser = client.get_users(user) us = getUser.id Bot( "sendMessage", { "chat_id": chatID, "text": us, "reply_to_message_id": message.message_id, "parse_mode": "html" }) except Exception as e: print(e) if re.search(c.ShowSudos, text): tx = (redis.get("{}Nbot:SHOWsudos".format(BOT_ID)) or "") Bot( "sendMessage", { "chat_id": chatID, "text": tx, "reply_to_message_id": message.message_id, "parse_mode": "html" }) if text == c.mymsgs: get = redis.hget("{}Nbot:{}:msgs".format(BOT_ID, chatID), userID) Bot( "sendMessage", { "chat_id": chatID, "text": r.yourmsgs.format((get or 0)), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if text == c.link: get = (redis.hget("{}Nbot:links".format(BOT_ID), chatID) or GetLink(chatID) or "none") Bot( "sendMessage", { "chat_id": chatID, "text": r.showGPlk.format(get), "reply_to_message_id": message.message_id, "parse_mode": "html", "disable_web_page_preview": True }) if text == c.myedits: get = redis.hget("{}Nbot:{}:edits".format(BOT_ID, chatID), userID) Bot( "sendMessage", { "chat_id": chatID, "text": r.youredits.format((get or 0)), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if text == c.myaddcontact: get = redis.hget("{}Nbot:{}:addcontact".format(BOT_ID, chatID), userID) Bot( "sendMessage", { "chat_id": chatID, "text": r.youraddcontact.format((get or 0)), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if not redis.sismember("{}Nbot:ReplySendBOT".format(BOT_ID), chatID): if redis.hexists("{}Nbot:TXreplys".format(BOT_ID), text): tx = redis.hget("{}Nbot:TXreplys".format(BOT_ID), text) Bot( "sendMessage", { "chat_id": chatID, "text": tx.format(fn=Name(userFn), us=("@" + username or "none"), id=userID, rk=IDrank(redis, userID, chatID, r), cn=title), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if redis.hexists("{}Nbot:STreplys".format(BOT_ID), text): ID = redis.hget("{}Nbot:STreplys".format(BOT_ID), text) Bot( "sendSticker", { "chat_id": chatID, "sticker": ID, "reply_to_message_id": message.message_id }) if redis.hexists("{}Nbot:GFreplys".format(BOT_ID), text): ID = redis.hget("{}Nbot:GFreplys".format(BOT_ID), text) Bot( "sendanimation", { "chat_id": chatID, "animation": ID, "reply_to_message_id": message.message_id }) if redis.hexists("{}Nbot:{}:VOreplys".format(BOT_ID, chatID), text): ID = redis.hget("{}Nbot:VOreplys".format(BOT_ID), text) Bot( "sendvoice", { "chat_id": chatID, "voice": ID, "reply_to_message_id": message.message_id }) if not redis.sismember("{}Nbot:ReplySend".format(BOT_ID), chatID): if redis.hexists("{}Nbot:{}:TXreplys".format(BOT_ID, chatID), text): tx = redis.hget("{}Nbot:{}:TXreplys".format(BOT_ID, chatID), text) Bot( "sendMessage", { "chat_id": chatID, "text": tx.format(fn=Name(userFN), us=("@" + username or "n"), id=userID, rk=IDrank(redis, userID, chatID, r), cn=title), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if redis.hexists("{}Nbot:{}:STreplys".format(BOT_ID, chatID), text): ID = redis.hget("{}Nbot:{}:STreplys".format(BOT_ID, chatID), text) Bot( "sendSticker", { "chat_id": chatID, "sticker": ID, "reply_to_message_id": message.message_id }) if redis.hexists("{}Nbot:{}:GFreplys".format(BOT_ID, chatID), text): ID = redis.hget("{}Nbot:{}:GFreplys".format(BOT_ID, chatID), text) Bot( "sendanimation", { "chat_id": chatID, "animation": ID, "reply_to_message_id": message.message_id }) if redis.hexists("{}Nbot:{}:VOreplys".format(BOT_ID, chatID), text): ID = redis.hget("{}Nbot:{}:VOreplys".format(BOT_ID, chatID), text) Bot( "sendvoice", { "chat_id": chatID, "voice": ID, "reply_to_message_id": message.message_id })
def btn(text, value, type = 'callback_data'): return InlineKeyboardButton(text, **{type: value})
async def inline_query_handler(client, query): string = query.query.lower() answers = [] if query.from_user.id not in AdminSettings: await client.answer_inline_query( query.id, results=answers, switch_pm_text="Sorry, this bot only for {}".format(OwnerName), switch_pm_parameter="createown") return if string == "": await client.answer_inline_query( query.id, results=answers, switch_pm_text="Need help? Click here", switch_pm_parameter="help_inline") return # Notes if string.split()[0] == "note": if not DB_AVAILABLE: await client.answer_inline_query( query.id, results=answers, switch_pm_text="Your database isn't avaiable!", switch_pm_parameter="help_inline") return if len(string.split()) == 1: allnotes = notes_db.get_all_selfnotes_inline(query.from_user.id) if not allnotes: await client.answer_inline_query( query.id, results=answers, switch_pm_text="You dont have any notes!", switch_pm_parameter="help_inline") return if len(list(allnotes)) >= 30: rng = 30 else: rng = len(list(allnotes)) for x in range(rng): note = allnotes[list(allnotes)[x]] noteval = note["value"] notetype = note["type"] # notefile = note["file"] if notetype != Types.TEXT: continue note, button = parse_button(noteval) button = build_keyboard(button) answers.append( InlineQueryResultArticle( title="Note #{}".format(list(allnotes)[x]), description=note, input_message_content=InputTextMessageContent(note), reply_markup=InlineKeyboardMarkup(button))) await client.answer_inline_query(query.id, results=answers, switch_pm_text="Yourself notes", switch_pm_parameter="help_inline") return q = string.split(None, 1) notetag = q[1] noteval = notes_db.get_selfnote(query.from_user.id, notetag) if not noteval: await client.answer_inline_query(query.id, results=answers, switch_pm_text="Note not found!", switch_pm_parameter="help_inline") return note, button = parse_button(noteval.get('value')) button = build_keyboard(button) answers.append( InlineQueryResultArticle( title="Note #{}".format(notetag), description=note, input_message_content=InputTextMessageContent(note), reply_markup=InlineKeyboardMarkup(button))) try: await client.answer_inline_query(query.id, results=answers, cache_time=5) except errors.exceptions.bad_request_400.MessageEmpty: exc_type, exc_obj, exc_tb = sys.exc_info() log_errors = traceback.format_exception(etype=exc_type, value=exc_obj, tb=exc_tb) button = InlineKeyboardMarkup([[ InlineKeyboardButton("🐞 Report bugs", callback_data="report_errors") ]]) text = "An error has accured!\n\n```{}```\n".format( "".join(log_errors)) await setbot.send_message(Owner, text, reply_markup=button) return # Stylish converter elif string.split()[0] == "stylish": if len(string.split()) == 1: await client.answer_inline_query( query.id, results=answers, switch_pm_text="Insert any text to convert it!", switch_pm_parameter="help_inline") return text = string.split(None, 1)[1] upside = upsidedown_text_inline(text) answers.append( InlineQueryResultArticle( title=upside, description="Upside-down Text", input_message_content=InputTextMessageContent(upside))) over = text_style_generator(text, CHAR_OVER) answers.append( InlineQueryResultArticle( title=over, description="Overline Text", input_message_content=InputTextMessageContent(over))) under = text_style_generator(text, CHAR_UNDER) answers.append( InlineQueryResultArticle( title=under, description="Underline Text", input_message_content=InputTextMessageContent(under))) strike = text_style_generator(text, CHAR_STRIKE) answers.append( InlineQueryResultArticle( title=strike, description="Strike Text", input_message_content=InputTextMessageContent(strike))) points = text_style_generator(text, CHAR_POINTS) answers.append( InlineQueryResultArticle( title=points, description="Points Text", input_message_content=InputTextMessageContent(points))) smallcaps_conv = formatting_text_inline(text, smallcaps) answers.append( InlineQueryResultArticle( title=smallcaps_conv, description="Smallcaps Text", input_message_content=InputTextMessageContent(smallcaps_conv))) super_script = formatting_text_inline(text, superscript) answers.append( InlineQueryResultArticle( title=super_script, description="Superscript Text", input_message_content=InputTextMessageContent(super_script))) sub_script = formatting_text_inline(text, subscript) answers.append( InlineQueryResultArticle( title=sub_script, description="Subscript Text", input_message_content=InputTextMessageContent(sub_script))) wide_text = formatting_text_inline(text, wide) answers.append( InlineQueryResultArticle( title=wide_text, description="Wide Text", input_message_content=InputTextMessageContent(wide_text))) bubbles_text = formatting_text_inline(text, bubbles) answers.append( InlineQueryResultArticle( title=bubbles_text, description="Bubbles Text", input_message_content=InputTextMessageContent(bubbles_text))) bubblesblack_text = formatting_text_inline(text, bubblesblack) answers.append( InlineQueryResultArticle( title=bubblesblack_text, description="Bubbles Black Text", input_message_content=InputTextMessageContent( bubblesblack_text))) smoth_text = formatting_text_inline(text, smothtext) answers.append( InlineQueryResultArticle( title=smoth_text, description="Smoth Text", input_message_content=InputTextMessageContent(smoth_text))) graffiti_text = formatting_text_inline(text, graffiti) answers.append( InlineQueryResultArticle( title=graffiti_text, description="Graffiti Text", input_message_content=InputTextMessageContent(graffiti_text))) graffitib_text = formatting_text_inline(text, graffitib) answers.append( InlineQueryResultArticle( title=graffitib_text, description="Graffiti Bold Text", input_message_content=InputTextMessageContent(graffitib_text))) handwriting_text = formatting_text_inline(text, handwriting) answers.append( InlineQueryResultArticle( title=handwriting_text, description="Handwriting Text", input_message_content=InputTextMessageContent( handwriting_text))) handwritingb_text = formatting_text_inline(text, handwritingb) answers.append( InlineQueryResultArticle( title=handwritingb_text, description="Handwriting Bold Text", input_message_content=InputTextMessageContent( handwritingb_text))) await client.answer_inline_query( query.id, results=answers, switch_pm_text="Converted to stylish text", switch_pm_parameter="help_inline") # PM_PERMIT elif string.split()[0] == "engine_pm": button = [[ InlineKeyboardButton("Ask for Money", callback_data="engine_pm_block"), InlineKeyboardButton("Contact me", callback_data="engine_pm_nope") ], [ InlineKeyboardButton("Report", callback_data="engine_pm_report"), InlineKeyboardButton("Passing by", callback_data="engine_pm_none") ]] random.shuffle(button) answers.append( InlineQueryResultArticle( title="Engine pm", description="Filter pm", input_message_content=InputTextMessageContent( welc_txt, parse_mode="markdown"), reply_markup=InlineKeyboardMarkup(button))) await client.answer_inline_query(query.id, results=answers, cache_time=0) elif string.split()[0] == "speedtest": buttons = [[ InlineKeyboardButton("Image", callback_data="speedtest_image"), InlineKeyboardButton("Text", callback_data="speedtest_text") ]] answers.append( InlineQueryResultArticle( title="Speed Test", description="test your speed", input_message_content=InputTextMessageContent( "Select SpeedTest Mode", parse_mode="markdown"), reply_markup=InlineKeyboardMarkup(buttons))) await client.answer_inline_query(query.id, results=answers, cache_time=0) elif string.split()[0] == "alive": repo = git.Repo(os.getcwd()) master = repo.head.reference commit_id = master.commit.hexsha commit_link = f"[{commit_id[:7]}](https://github.com/pokurt/Nana-Remix/commit/{commit_id})" try: me = await app.get_me() except ConnectionError: me = None text = f"**[Nana-Remix](https://github.com/pokurt/Nana-Remix) Running on {commit_link}:**\n" if not me: text += f" - **Bot**: `stopped (v{USERBOT_VERSION})`\n" else: text += f" - **Bot**: `alive (v{USERBOT_VERSION})`\n" text += f" - **Pyrogram**: `{__version__}`\n" text += f" - **Python**: `{python_version()}`\n" text += f" - **Database**: `{DB_AVAILABLE}`\n" buttons = [[ InlineKeyboardButton("stats", callback_data="alive_message") ]] answers.append( InlineQueryResultArticle( title="Alive", description="Nana Userbot", input_message_content=InputTextMessageContent( text, parse_mode="markdown", disable_web_page_preview=True), reply_markup=InlineKeyboardMarkup(buttons))) await client.answer_inline_query(query.id, results=answers, cache_time=0) elif string.split()[0] == "anime": search = string.split(None, 1)[1] variables = {'search': search} json = requests.post(url, json={ 'query': anime_query, 'variables': variables }).json()['data'].get('Media', None) if json: msg = f"**{json['title']['romaji']}** (`{json['title']['native']}`)\n**Type**: {json['format']}\n**Status**: {json['status']}\n**Episodes**: {json.get('episodes', 'N/A')}\n**Duration**: {json.get('duration', 'N/A')} Per Ep.\n**Score**: {json['averageScore']}\n**Genres**: `" for x in json['genres']: msg += f"{x}, " msg = msg[:-2] + '`\n' msg += "**Studios**: `" for x in json['studios']['nodes']: msg += f"{x['name']}, " msg = msg[:-2] + '`\n' info = json.get('siteUrl') trailer = json.get('trailer', None) if trailer: trailer_id = trailer.get('id', None) site = trailer.get('site', None) if site == "youtube": trailer = 'https://youtu.be/' + trailer_id description = json.get('description', 'N/A').replace('<i>', '').replace( '</i>', '').replace('<br>', '') msg += shorten(description, info) image = json.get('bannerImage', None) if trailer: buttons = [[ InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer) ]] else: buttons = [[InlineKeyboardButton("More Info", url=info)]] if image: answers.append( InlineQueryResultPhoto( caption=msg, photo_url=image, parse_mode="markdown", title=f"{json['title']['romaji']}", description=f"{json['format']}", reply_markup=InlineKeyboardMarkup(buttons))) await client.answer_inline_query(query.id, results=answers, cache_time=0) else: answers.append( InlineQueryResultArticle( title=f"{json['title']['romaji']}", description=f"{json['averageScore']}", input_message_content=InputTextMessageContent( msg, parse_mode="markdown", disable_web_page_preview=True), reply_markup=InlineKeyboardMarkup(buttons))) await client.answer_inline_query(query.id, results=answers, cache_time=0) return
async def pm_button(client, query): if query.from_user.id in AdminSettings and not re.match( r"engine_pm_apr", query.data) and not re.match( r"engine_pm_blk", query.data): await client.answer_callback_query(query.id, "No, you can't click by yourself", show_alert=False) return if re.match(r"engine_pm_block", query.data): await setbot.edit_inline_text(query.inline_message_id, "💩") # await app.send_message(query.from_user.id, "I dont share any hack or any illegal things, if you PM me for this, then you are retard and does not have a brain.\nContact your admin and ask that illegal things, not me\n\nGood bye you f*****g retard!") await app.block_user(query.from_user.id) elif re.match(r"engine_pm_nope", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Hello, please wait for a reply from my master\nI've notify my master to reply your PM, thank you" ) await setbot.send_message( NOTIFY_ID, f"Hi [{OwnerName}](tg://user?id={Owner}), {mention_markdown(query.from_user.id, query.from_user.first_name)} want to contact you~", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( "Approve", callback_data=f"engine_pm_apr-{query.from_user.id}"), InlineKeyboardButton( "Block", callback_data=f"engine_pm_blk-{query.from_user.id}") ]])) set_req(query.from_user.id, True) from nana.modules.lydia import lydia_status if lydia_status: await app.send_message( query.from_user.id, "During the wait for permission from my master, why do not we have a little chat?" ) elif re.match(r"engine_pm_report", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Hello, if you want to report any bugs for my bots, please report in @NanaBotSupport\nThank you" ) elif re.match(r"engine_pm_none", query.data): await setbot.edit_inline_text(query.inline_message_id, "👍") await app.send_message( query.from_user.id, "Alright then,\nIf you want anything from me, please contact my again. Thank you" ) elif re.match(r"engine_pm_donate", query.data): await setbot.edit_inline_text(query.inline_message_id, "❤️") await app.send_message( query.from_user.id, "Cool, thank you for donate me\nYou can select payment in here https://ayrahikari.github.io/donations.html\n\nIf you've donated me, please PM me again, thanks" ) elif re.match(r"engine_pm_apr", query.data): target = query.data.split("-")[1] await query.message.edit_text(f"[Approved for PM]({target})") await app.send_message( target, "Hello, this is Nana, my master approved you to PM.") set_whitelist(int(target), True) elif re.match(r"engine_pm_blk", query.data): target = query.data.split("-")[1] await query.message.edit_text("That user was blocked~") await app.send_message( target, "Hello, this is Nana, my master has decide to block you.\nSorry for this!" ) await app.block_user(target) else: await setbot.edit_inline_text(query.inline_message_id, "🙆♀️")
async def help_user(bot, update): await bot.send_message( Config.LOG_CHANNEL, f"New User [{update.from_user.first_name}](tg://user?id={chat.id}) started." ) # logger.info(update) TRChatBase(update.from_user.id, update.text, "/help") await bot.send_message( chat_id=update.chat.id, text=Translation.HELP_USER, parse_mode="html", disable_web_page_preview=True, reply_to_message_id=update.message_id, reply_markup=InlineKeyboardMarkup( [ [InlineKeyboardButton('1⃣', url='https://t.me/ChEkUtHaN')], [InlineKeyboardButton('2⃣', url='https://t.me/BotUpdatez')], ] ) ) @pyrogram.Client.on_message(pyrogram.Filters.command(["me"])) async def get_me_info(bot, update): # logger.info(update) TRChatBase(update.from_user.id, update.text, "/me") chat_id = str(update.from_user.id) chat_id, plan_type, expires_at = GetExpiryDate(chat_id) await bot.send_message( chat_id=update.chat.id, text=Translation.CURENT_PLAN_DETAILS.format(chat_id, plan_type, expires_at), parse_mode="html", disable_web_page_preview=True,
async def youtube_music(_client, message): args = message.text.split(None, 1) if len(args) == 1: await message.edit("Send URL here!") return teks = args[1] try: video = pafy.new(teks) except ValueError: await message.edit("Invaild URL!") return try: audios = [audio for audio in video.audiostreams] audios.sort(key=lambda a: (int(a.quality.strip('k')) * -1)) music = audios[0] text = "[](https://i.ytimg.com/vi/{}/0.jpg)🎬 **Title:** [{}]({})\n".format( video.videoid, escape_markdown(video.title), video.watchv_url) text += "👤 **Author:** `{}`\n".format(video.author) text += "🕦 **Duration:** `{}`\n".format(video.duration) origtitle = re.sub(r'[\\/*?:"<>|\[\]]', "", str(music.title + "." + music._extension)) musictitle = re.sub(r'[\\/*?:"<>|\[\]]', "", str(music.title)) musicdate = video._ydl_info['upload_date'][:4] titletext = "**Downloading music...**\n" await message.edit(titletext + text, disable_web_page_preview=False) r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/maxresdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/hqdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/sddefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/mqdefault.jpg", stream=True) if r.status_code != 200: r = requests.get( f"https://i.ytimg.com/vi/{video.videoid}/default.jpg", stream=True) if r.status_code != 200: avthumb = False if r.status_code == 200: avthumb = True with open("nana/cache/thumb.jpg", "wb") as stk: shutil.copyfileobj(r.raw, stk) try: os.remove(f"nana/downloads/{origtitle}") except FileNotFoundError: pass # music.download(filepath="nana/downloads/{}".format(origtitle)) if "manifest.googlevideo.com" in music.url: download = await download_url(music._info['fragment_base_url'], origtitle) else: download = await download_url(music.url, origtitle) if download == "Failed to download file\nInvaild file name!": return await message.edit(download) titletext = "**Converting music...**\n" await message.edit(titletext + text, disable_web_page_preview=False) try: subprocess.Popen("ffmpeg", stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception as err: if "The system cannot find the file specified" in str( err) or "No such file or directory" in str(err): await message.edit( "You need to install ffmpeg first!\nCheck your assistant for more information!" ) await setbot.send_message( message.from_user.id, "Hello 🙂\nYou need to install ffmpeg to make audio works better, here is guide how to install it:\n\n**If you're using linux**, go to your terminal, type:\n`sudo apt install ffmpeg`\n\n**If you're using Windows**, download ffmpeg here:\n`https://ffmpeg.zeranoe.com/builds/`\nAnd then extract (if was archive), and place ffmpeg.exe to workdir (in current dir)\n\n**If you're using heroku**, type this in your workdir:\n`heroku buildpacks:add https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git`\nOr if you not using heroku term, follow this guide:\n1. Go to heroku.com\n2. Go to your app in heroku\n3. Change tabs/click Settings, then search for Buildpacks text\n4. Click button Add build pack, then type `https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest`\n5. Click Save changes, and you need to rebuild your heroku app to take changes!\n\nNeed help?\nGo @nanabotsupport and ask there" ) return if avthumb: os.system( f'ffmpeg -loglevel panic -i "nana/downloads/{origtitle}" -i "nana/cache/thumb.jpg" -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title="Album cover" -metadata:s:v comment="Cover (Front)" -metadata title="{music.title}" -metadata author="{video.author}" -metadata album="{video.author}" -metadata album_artist="{video.author}" -metadata genre="{video._category}" -metadata date="{musicdate}" -acodec libmp3lame -aq 4 -y "nana/downloads/{musictitle}.mp3"' ) else: os.system( f'ffmpeg -loglevel panic -i "nana/downloads/{origtitle}" -metadata title="{music.title}" -metadata author="{video.author}" -metadata album="{video.author}" -metadata album_artist="{video.author}" -metadata genre="{video._category}" -metadata date="{musicdate}" -acodec libmp3lame -aq 4 -y "nana/downloads/{musictitle}.mp3"' ) try: os.remove("nana/downloads/{}".format(origtitle)) except FileNotFoundError: pass titletext = "**Uploading...**\n" await message.edit(titletext + text, disable_web_page_preview=False) getprev = requests.get(video.thumb, stream=True) with open("nana/cache/prev.jpg", "wb") as stk: shutil.copyfileobj(getprev.raw, stk) await app.send_audio(message.chat.id, audio=f"nana/downloads/{musictitle}.mp3", thumb="nana/cache/prev.jpg", title=music.title, caption=f"🕦 `{video.duration}`", reply_to_message_id=message.message_id) try: os.remove("nana/cache/prev.jpg") except FileNotFoundError: pass try: os.remove("nana/cache/thumb.jpg") except FileNotFoundError: pass titletext = "**Done! 🤗**\n" await message.edit(titletext + text, disable_web_page_preview=False) except Exception as err: if "command not found" in str(err) or "is not recognized" in str(err): await message.edit( "You need to install ffmpeg first!\nCheck your assistant for more information!" ) await setbot.send_message( message.from_user.id, "Hello 🙂\nYou need to install ffmpeg to make audio works better, here is guide " "how to install it:\n\n**If you're using linux**, go to your terminal, " "type:\n`sudo apt install ffmpeg`\n\n**If you're using Windows**, download " "ffmpeg here:\n`https://ffmpeg.zeranoe.com/builds/`\nAnd then extract (if was " "archive), and place ffmpeg.exe to workdir (in current dir)\n\n**If you're using " "heroku**, type this in your workdir:\n`heroku buildpacks:add " "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git`\nOr if you " "not using heroku term, follow this guide:\n1. Go to heroku.com\n2. Go to your " "app in heroku\n3. Change tabs/click Settings, then search for Buildpacks " "text\n4. Click button Add build pack, then type " "`https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest`\n5. Click Save " "changes, and you need to rebuild your heroku app to take changes!\n\nNeed " "help?\nGo to @NanaBotSupport and ask there") return exc_type, exc_obj, exc_tb = sys.exc_info() errors = traceback.format_exception(etype=exc_type, value=exc_obj, tb=exc_tb) await message.edit( "**An error has accured!**\nCheck your assistant for more information!" ) button = InlineKeyboardMarkup([[ InlineKeyboardButton("🐞 Report bugs", callback_data="report_errors") ]]) await setbot.send_message(message.from_user.id, "**An error has accured!**\n```{}```".format( "".join(errors)), reply_markup=button) logging.exception("Execution error")
async def check_progress_for_dl(aria2, gid, event, previous_message): #g_id = event.reply_to_message.from_user.id try: file = aria2.get_download(gid) complete = file.is_complete is_file = file.seeder if not complete: if not file.error_message: msg = "" # sometimes, this weird https://t.me/c/1220993104/392975 # error creeps up # TODO: temporary workaround downloading_dir_name = "N/A" try: # another derp -_- # https://t.me/c/1220993104/423318 downloading_dir_name = str(file.name) except: pass # if is_file is None: msgg = f"Conn: {file.connections} <b>|</b> GID: <code>{gid}</code>" else: msgg = f"P: {file.connections} | S: {file.num_seeders} <b>|</b> GID: <code>{gid}</code>" msg = f"\n`{downloading_dir_name}`" msg += f"\n<b>Speed</b>: {file.download_speed_string()}" msg += f"\n<b>Status</b>: {file.progress_string()} <b>of</b> {file.total_length_string()} <b>|</b> {file.eta_string()} <b>|</b> {msgg}" #msg += f"\nSize: {file.total_length_string()}" #if is_file is None : #msg += f"\n<b>Conn:</b> {file.connections}, GID: <code>{gid}</code>" #else : #msg += f"\n<b>Info:</b>[ P : {file.connections} | S : {file.num_seeders} ], GID: <code>{gid}</code>" #msg += f"\nStatus: {file.status}" #msg += f"\nETA: {file.eta_string()}" #msg += f"\nGID: <code>{gid}</code>" inline_keyboard = [] ikeyboard = [] ikeyboard.append( InlineKeyboardButton( "Cancel 🚫", callback_data=(f"cancel {gid}").encode("UTF-8"))) inline_keyboard.append(ikeyboard) reply_markup = InlineKeyboardMarkup(inline_keyboard) #msg += reply_markup #LOGGER.info(msg) if msg != previous_message: await event.edit(msg, reply_markup=reply_markup) previous_message = msg else: msg = file.error_message await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await event.edit(f"`{msg}`") return False await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await check_progress_for_dl(aria2, gid, event, previous_message) else: LOGGER.info( f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒" ) await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await event.edit( f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒" ) return True except aria2p.client.ClientException: await event.edit( f"Download Canceled :\n<code>{file.name} ({file.total_length_string()})</code>" ) except MessageNotModified as ep: LOGGER.info(ep) except FloodWait as e: LOGGER.info(e) time.sleep(e.x) except RecursionError: file.remove(force=True) await event.edit("Download Auto Canceled :\n\n" "Your Torrent/Link is Dead.".format(file.name)) return False except Exception as e: LOGGER.info(str(e)) #await event.edit(f'Download cancelled due to {e}') if "not found" in str(e) or "'file'" in str(e): await event.edit( f"Download Canceled :\n<code>{file.name} ({file.total_length_string()})</code>" ) return False else: LOGGER.info(str(e)) await event.edit( "<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e))) return False
async def echo(bot, update): if update.from_user.id not in AUTH_USERS: await update.delete() return # LOGGER.info(update) # await bot.send_chat_action( # chat_id=update.chat.id, # action="typing" # ) LOGGER.info(update.from_user) url = update.text if url.count("|") == 2: shomar = random.randint(1, 10000) # youtube_dl extractors youtube_dl_url, custom_file_name, youtube_dl_format = url.split(" | ") tg_send_type = "file" if ") FullHD" in custom_file_name: await bot.send_message( text=Translation.DOWNLOAD_START, chat_id=update.chat.id, reply_to_message_id=update.message_id, ) description = "@BachehayeManoto FullHD" custom_file_name = custom_file_name + ".mp4" tmp_directory_for_each_user = DOWNLOAD_LOCATION + "/" + str(shomar) if not os.path.isdir(tmp_directory_for_each_user): os.makedirs(tmp_directory_for_each_user) download_directory = tmp_directory_for_each_user + "/" + custom_file_name command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(TG_MAX_FILE_SIZE), "--embed-subs", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory ] command_to_exec.append("--no-warnings") # command_to_exec.append("--quiet") command_to_exec.append("--restrict-filenames") LOGGER.info(command_to_exec) start = datetime.now() process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() LOGGER.info(e_response) LOGGER.info(t_response) ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output." if e_response and ad_string_to_replace in e_response: error_message = e_response.replace(ad_string_to_replace, "") await bot.edit_message_text(chat_id=update.chat.id, message_id=update.message_id + 1, text=error_message) return False if t_response: # LOGGER.info(t_response) end_one = datetime.now() time_taken_for_download = (end_one - start).seconds file_size = TG_MAX_FILE_SIZE + 1 download_directory_dirname = os.path.dirname( download_directory) download_directory_contents = os.listdir( download_directory_dirname) for download_directory_c in download_directory_contents: current_file_name = os.path.join( download_directory_dirname, download_directory_c) file_size = os.stat(current_file_name).st_size if file_size > TG_MAX_FILE_SIZE: await bot.edit_message_text( chat_id=update.chat.id, text=Translation.RCHD_TG_API_LIMIT.format( time_taken_for_download, humanbytes(file_size)), message_id=update.message_id + 1) else: is_w_f = False images = await generate_screen_shots( current_file_name, tmp_directory_for_each_user, is_w_f, "", 300, 9) LOGGER.info(images) await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.chat.id, message_id=update.message_id + 1) # get the correct width, height, and duration for videos greater than 10MB # ref: message from @BotSupport width = 0 height = 0 duration = 0 start_time = time.time() # try to upload file if tg_send_type == "file": await bot.send_document( chat_id=update.chat.id, document=download_directory, #thumb=thumb_image_path, caption=description, parse_mode="HTML", # reply_markup=reply_markup, reply_to_message_id=update.message_id + 1, progress=progress_for_pyrogram, progress_args=(Translation.UPLOAD_START, update, start_time)) else: LOGGER.info("Did this happen? :\\") end_two = datetime.now() time_taken_for_upload = (end_two - end_one).seconds media_album_p = [] if images is not None: i = 0 #caption = "© @AnyDLBot" if is_w_f: caption = "/upgrade to Plan D to remove the watermark\n© @AnyDLBot" for image in images: if os.path.exists(image): if i == 0: media_album_p.append( InputMediaPhoto(media=image, caption=caption, parse_mode="html")) else: media_album_p.append( InputMediaPhoto(media=image)) i = i + 1 await bot.send_media_group( chat_id=update.chat.id, disable_notification=True, reply_to_message_id=update.message_id + 1, media=media_album_p) # try: shutil.rmtree(tmp_directory_for_each_user) except: pass await bot.edit_message_text( text= "Downloaded in {} seconds. \nUploaded in {} seconds.". format(time_taken_for_download, time_taken_for_upload), chat_id=update.chat.id, message_id=update.message_id + 1, disable_web_page_preview=True) if ") HD" in custom_file_name: await bot.send_message( text=Translation.DOWNLOAD_START, chat_id=update.chat.id, reply_to_message_id=update.message_id, ) description = "@BachehayeManoto HD" custom_file_name = custom_file_name + ".mp4" tmp_directory_for_each_user = DOWNLOAD_LOCATION + "/" + str(shomar) if not os.path.isdir(tmp_directory_for_each_user): os.makedirs(tmp_directory_for_each_user) download_directory = tmp_directory_for_each_user + "/" + custom_file_name command_to_exec = [ "youtube-dl", "-c", "--max-filesize", str(TG_MAX_FILE_SIZE), "--embed-subs", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory ] command_to_exec.append("--no-warnings") # command_to_exec.append("--quiet") command_to_exec.append("--restrict-filenames") LOGGER.info(command_to_exec) start = datetime.now() process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() LOGGER.info(e_response) LOGGER.info(t_response) ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output." if e_response and ad_string_to_replace in e_response: error_message = e_response.replace(ad_string_to_replace, "") await bot.edit_message_text(chat_id=update.chat.id, message_id=update.message_id + 1, text=error_message) return False if t_response: # LOGGER.info(t_response) end_one = datetime.now() time_taken_for_download = (end_one - start).seconds file_size = TG_MAX_FILE_SIZE + 1 download_directory_dirname = os.path.dirname( download_directory) download_directory_contents = os.listdir( download_directory_dirname) for download_directory_c in download_directory_contents: current_file_name = os.path.join( download_directory_dirname, download_directory_c) file_size = os.stat(current_file_name).st_size if file_size > TG_MAX_FILE_SIZE: await bot.edit_message_text( chat_id=update.chat.id, text=Translation.RCHD_TG_API_LIMIT.format( time_taken_for_download, humanbytes(file_size)), message_id=update.message_id + 1) else: is_w_f = False images = await generate_screen_shots( current_file_name, tmp_directory_for_each_user, is_w_f, "", 300, 9) LOGGER.info(images) await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.chat.id, message_id=update.message_id + 1) # get the correct width, height, and duration for videos greater than 10MB # ref: message from @BotSupport width = 0 height = 0 duration = 0 start_time = time.time() # try to upload file if tg_send_type == "file": await bot.send_document( chat_id=update.chat.id, document=download_directory, #thumb=thumb_image_path, caption=description, parse_mode="HTML", # reply_markup=reply_markup, reply_to_message_id=update.message_id + 1, progress=progress_for_pyrogram, progress_args=(Translation.UPLOAD_START, update, start_time)) else: LOGGER.info("Did this happen? :\\") end_two = datetime.now() time_taken_for_upload = (end_two - end_one).seconds media_album_p = [] if images is not None: i = 0 #caption = "© @AnyDLBot" if is_w_f: caption = "/upgrade to Plan D to remove the watermark\n© @AnyDLBot" for image in images: if os.path.exists(image): if i == 0: media_album_p.append( InputMediaPhoto(media=image, caption=caption, parse_mode="html")) else: media_album_p.append( InputMediaPhoto(media=image)) i = i + 1 await bot.send_media_group( chat_id=update.chat.id, disable_notification=True, reply_to_message_id=update.message_id + 1, media=media_album_p) # try: shutil.rmtree(tmp_directory_for_each_user) except: pass await bot.edit_message_text( text= "Downloaded in {} seconds. \nUploaded in {} seconds.". format(time_taken_for_download, time_taken_for_upload), chat_id=update.chat.id, message_id=update.message_id + 1, disable_web_page_preview=True) else: youtube_dl_username = None youtube_dl_password = None file_name = None if "|" in url: url_parts = url.split("|") if len(url_parts) == 2: url = url_parts[0] file_name = url_parts[1] elif len(url_parts) == 4: url = url_parts[0] file_name = url_parts[1] youtube_dl_username = url_parts[2] youtube_dl_password = url_parts[3] else: for entity in update.entities: if entity.type == "text_link": url = entity.url elif entity.type == "url": o = entity.offset l = entity.length url = url[o:o + l] if url is not None: url = url.strip() if file_name is not None: file_name = file_name.strip() # https://stackoverflow.com/a/761825/4723940 if youtube_dl_username is not None: youtube_dl_username = youtube_dl_username.strip() if youtube_dl_password is not None: youtube_dl_password = youtube_dl_password.strip() LOGGER.info(url) LOGGER.info(file_name) else: for entity in update.entities: if entity.type == "text_link": url = entity.url elif entity.type == "url": o = entity.offset l = entity.length url = url[o:o + l] if HTTP_PROXY is not None: command_to_exec = [ "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j", url, "--proxy", HTTP_PROXY ] else: command_to_exec = [ "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j", url ] if youtube_dl_username is not None: command_to_exec.append("--username") command_to_exec.append(youtube_dl_username) if youtube_dl_password is not None: command_to_exec.append("--password") command_to_exec.append(youtube_dl_password) # logger.info(command_to_exec) process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() # logger.info(e_response) t_response = stdout.decode().strip() # logger.info(t_response) # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239 if e_response and "nonnumeric port" not in e_response: # logger.warn("Status : FAIL", exc.returncode, exc.output) error_message = e_response.replace( "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.", "") if "This video is only available for registered users." in error_message: error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD await update.reply_text( text=Translation.NO_VOID_FORMAT_FOUND.format( str(error_message)), quote=True, parse_mode="html", disable_web_page_preview=True) return False if t_response: # logger.info(t_response) x_reponse = t_response if "\n" in x_reponse: x_reponse, _ = x_reponse.split("\n") response_json = json.loads(x_reponse) save_ytdl_json_path = DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".json" with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: json.dump(response_json, outfile, ensure_ascii=False) # logger.info(response_json) inline_keyboard = [] duration = None if "duration" in response_json: duration = response_json["duration"] if "formats" in response_json: for formats in response_json["formats"]: format_id = formats.get("format_id") format_string = formats.get("format_note") if format_string is None: format_string = formats.get("format") format_ext = formats.get("ext") approx_file_size = "" if "filesize" in formats: approx_file_size = humanbytes(formats["filesize"]) cb_string_video = "{}-{}-{}".format( "video", format_id, format_ext) cb_string_file = "{}-{}-{}".format("file", format_id, format_ext) if format_string is not None and not "audio only" in format_string: ikeyboard = [ InlineKeyboardButton( "S " + format_string + " video " + approx_file_size + " ", callback_data=( cb_string_video).encode("UTF-8")), InlineKeyboardButton( "D " + format_ext + " " + approx_file_size + " ", callback_data=(cb_string_file).encode("UTF-8")) ] """if duration is not None: cb_string_video_message = "{}|{}|{}".format( "vm", format_id, format_ext) ikeyboard.append( pyrogram.InlineKeyboardButton( "VM", callback_data=( cb_string_video_message).encode("UTF-8") ) )""" else: # special weird case :\ ikeyboard = [ InlineKeyboardButton( "SVideo [" + "] ( " + approx_file_size + " )", callback_data=( cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile [" + "] ( " + approx_file_size + " )", callback_data=(cb_string_file).encode("UTF-8")) ] inline_keyboard.append(ikeyboard) if duration is not None: cb_string_64 = "{}-{}-{}".format("audio", "64k", "mp3") cb_string_128 = "{}-{}-{}".format("audio", "128k", "mp3") cb_string = "{}-{}-{}".format("audio", "320k", "mp3") inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8")), InlineKeyboardButton( "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8")) ]) inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8")) ]) else: format_id = response_json["format_id"] format_ext = response_json["ext"] cb_string_file = "{}-{}-{}".format("file", format_id, format_ext) cb_string_video = "{}-{}-{}".format("video", format_id, format_ext) inline_keyboard.append([ InlineKeyboardButton( "SVideo", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile", callback_data=(cb_string_file).encode("UTF-8")) ]) cb_string_file = "{}={}={}".format("file", format_id, format_ext) cb_string_video = "{}={}={}".format("video", format_id, format_ext) inline_keyboard.append([ InlineKeyboardButton( "video", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "file", callback_data=(cb_string_file).encode("UTF-8")) ]) reply_markup = InlineKeyboardMarkup(inline_keyboard) # logger.info(reply_markup) thumbnail = DEF_THUMB_NAIL_VID_S thumbnail_image = DEF_THUMB_NAIL_VID_S if "thumbnail" in response_json: if response_json["thumbnail"] is not None: thumbnail = response_json["thumbnail"] thumbnail_image = response_json["thumbnail"] thumb_image_path = DownLoadFile( thumbnail_image, DOWNLOAD_LOCATION + "/" + str(update.from_user.id) + ".jpg", 128, None, # bot, Translation.DOWNLOAD_START, update.message_id, update.chat.id) await update.reply_text( text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" + Translation.SET_CUSTOM_USERNAME_PASSWORD, quote=True, reply_markup=reply_markup, parse_mode="html", disable_web_page_preview=True) else: # fallback for nonnumeric port a.k.a seedbox.io inline_keyboard = [] cb_string_file = "{}={}={}".format("file", "LFO", "NONE") cb_string_video = "{}={}={}".format("video", "OFL", "ENON") inline_keyboard.append([ InlineKeyboardButton( "SVideo", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile", callback_data=(cb_string_file).encode("UTF-8")) ]) reply_markup = InlineKeyboardMarkup(inline_keyboard) await update.reply_text( text=Translation.FORMAT_SELECTION.format(""), quote=True, reply_markup=reply_markup, parse_mode="html", disable_web_page_preview=True)
async def catch_youtube_dldata(c, q): cb_data = q.data.strip() # Callback Data Check yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation filext = "%(title)s.%(ext)s" userdir = os.path.join(os.getcwd(), "downloads", str(q.message.chat.id)) if not os.path.isdir(userdir): os.makedirs(userdir) await q.edit_message_reply_markup( InlineKeyboardMarkup([[ InlineKeyboardButton("جاري التحميل من يوتيوب...", callback_data="down") ]])) filepath = os.path.join(userdir, filext) # await q.edit_message_reply_markup([[InlineKeyboardButton("جاري المعالجة..")]]) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl ] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio(media=filename, caption=os.path.basename(filename), title=os.path.basename(filename)) if cb_data.startswith("video"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo(media=filename, duration=dur, caption=os.path.basename(filename), supports_streaming=True) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument( media=filename, caption=os.path.basename(filename), ) if cb_data.startswith("docvideo"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument( media=filename, caption=os.path.basename(filename), ) if med: loop.create_task(send_file(c, q, med, filename)) else: print("med not found")
async def rename_doc(bot, update): if update.from_user.id in Config.BANNED_USERS: await bot.delete_messages( chat_id=update.chat.id, message_ids=update.message_id, revoke=True ) return TRChatBase(update.from_user.id, update.text, "/echo") update_channel = Config.UPDATE_CHANNEL if update_channel: try: user = await bot.get_chat_member(update_channel, update.chat.id) if user.status == "kicked": await update.reply_text("🤠Sorry Mate, You're **B A N N E D **") return except UserNotParticipant: #await update.reply_text(f"Join @{update_channel} To Use Me") await update.reply_text( text="**Join My Updates Channel to use ME 😎 ðŸ¤**", reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton(text="Join My Updates Channel", url=f"https://t.me/{update_channel}")] ]) ) return except Exception: await update.reply_text("Oops,I Think You're Already Member,Please Revoke By Leaving The Channel.") return TRChatBase(update.from_user.id, update.text, "change") if (" " in update.text) and (update.reply_to_message is not None): cmd, file_name = update.text.split(" ", 1) if len(file_name) > 70: await update.reply_text( Translation.IFLONG_FILE_NAME.format( alimit="70", num=len(file_name) ) ) return description = Translation.CUSTOM_CAPTION_UL_FILE download_location = Config.DOWNLOAD_LOCATION + "/" a = await bot.send_message( chat_id=update.chat.id, text=Translation.DOWNLOAD_START, reply_to_message_id=update.message_id ) c_time = time.time() the_real_download_location = await bot.download_media( message=update.reply_to_message, file_name=download_location, progress=progress_for_pyrogram, progress_args=( Translation.DOWNLOAD_START, a, c_time ) ) if the_real_download_location is not None: try: await bot.edit_message_text( text=Translation.SAVED_RECVD_DOC_FILE, chat_id=update.chat.id, message_id=a.message_id ) except: pass if "IndianMovie" in the_real_download_location: await bot.edit_message_text( text=Translation.RENAME_403_ERR, chat_id=update.chat.id, message_id=a.message_id ) return new_file_name = download_location + file_name os.rename(the_real_download_location, new_file_name) await bot.edit_message_text( text=Translation.UPLOAD_START, chat_id=update.chat.id, message_id=a.message_id ) logger.info(the_real_download_location) thumb_image_path = Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) + ".jpg" if not os.path.exists(thumb_image_path): mes = await thumb(update.from_user.id) if mes != None: m = await bot.get_messages(update.chat.id, mes.msg_id) await m.download(file_name=thumb_image_path) thumb_image_path = thumb_image_path else: thumb_image_path = None else: width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") # resize image # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(thumb_image_path).convert("RGB").save(thumb_image_path) img = Image.open(thumb_image_path) # https://stackoverflow.com/a/37631799/4723940 # img.thumbnail((90, 90)) img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails c_time = time.time() await bot.send_document( chat_id=update.chat.id, document=new_file_name, thumb=thumb_image_path, caption=file_name + description, # reply_markup=reply_markup, reply_to_message_id=update.reply_to_message.message_id, progress=progress_for_pyrogram, progress_args=( Translation.UPLOAD_START, a, c_time ) ) try: os.remove(new_file_name) os.remove(thumb_image_path) except: pass await bot.edit_message_text( text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG, chat_id=update.chat.id, message_id=a.message_id, disable_web_page_preview=True ) else: await bot.send_message( chat_id=update.chat.id, text=Translation.REPLY_TO_DOC_FOR_RENAME_FILE, reply_to_message_id=update.message_id )
def callback(_, callback_query): if "MenùPrincipale" in callback_query.data: callback_query.edit_message_text( f"Ciao **{callback_query.from_user.first_name}**, benvenuto in Beapple!", reply_markup=InlineKeyboardMarkup([ [ # First row InlineKeyboardButton( # Generates a callback query when pressed "Chi siamo?", callback_data=f"ChiSiamo") ], [ InlineKeyboardButton( # Generates a callback query when pressed "I nostri servizi", callback_data=f"servizi") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Acquista Online", url="https://www.beapple.it/store/") ], [ InlineKeyboardButton("Contattaci", url="https://www.beapple.it/mappa/") ] ]), ) if "ChiSiamo" in callback_query.data: callback_query.edit_message_text( "La nostra azienda ha una storia sulla carta relativamente breve e al contempo ha **esperienza decennale**.\nBeapple proviene dalla confluenza di passioni, formazione, propositi e lungimiranza di tre ragazzi che nel **2017** hanno deciso di dar vita a questo progetto.\n\nAd oggi conta più di **12 mila clienti**, ha rapporti continui con centinaia di aziende in tutta Italia e promuove l’economia locale in ogni posto dove si trova.\nQuello che vogliamo essere è un **punto di riferimento**. Come possiamo esserlo per i nostri genitori, così vogliamo esserlo per chiunque si affidi a noi.\n\nPer più informazioni riguardanti il nostro team premi [qui 👈](https://www.beapple.it/#team)", reply_markup=InlineKeyboardMarkup([[ # First row InlineKeyboardButton( # Generates a callback query when pressed "Torna Indietro 🔙", callback_data=f"MenùPrincipale") ]])) if "servizi" in callback_query.data and "servizio" not in callback_query.data: callback_query.edit_message_text( "Scegli il servizio del quale vuoi avere più informazioni!", reply_markup=InlineKeyboardMarkup([ [ # First row InlineKeyboardButton( # Generates a callback query when pressed "Riparazioni Espresse", callback_data=f"servizio|RipEspresse") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Vendita Computer, Tablet e Cellulari", callback_data=f"servizio|ricondizionamento") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Sviluppo Siti Web", callback_data=f"servizio|sitiWeb") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Sistemi Software", callback_data=f"servizio|sistemiSoftware") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Microsaldatura", callback_data=f"servizio|microsaldatura") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Torna Indietro 🔙", callback_data=f"MenùPrincipale") ] ])) if "servizio" in callback_query.data: servizio = { "RipEspresse": "Qualsiasi terminale è **riparabile**: telefoni, tablet, computer, di tutte le marche, di ogni età 😃!\n\nPer richiederci un preventivo premi [qui 👈](https://www.beapple.it/mappa/)\nPer vedere il listino prezzi premi [qui 👈](https://www.beapple.it/prezzi/)", "ricondizionamento": "Abbiamo disponibili **Tablet, Computer 💻 e Telefoni 📱** nuovi e ricondizionati.\nL'esperienza nel settore ci permette di avere **prezzi scontati** fissi di circa il 10% rispetto ai listini classici 😱!\nCon una efficientissima catena di valore del prodotto siamo diventati tra i **primi rivenditori in Italia 🇮🇹** di telefoni ricondizionati.\n\nPer richiederci una quotazione premi [qui 👈](https://www.beapple.it/mappa/)", "sitiWeb": "Abbiamo sviluppato e manteniamo **decine di siti web 🌐 in tutta italia**. Grazie ai nostri consigli e al web designing ogni giorno i nostri clienti ricevono **centinaia di migliaia di visite 📈**.", "sistemiSoftware": "Grazie all'esperienza di sviluppo del nostro gestionale abbiamo acquisito capacità di consulenza per **sviluppo di programmi** che facilitino la **gestione dati**.", "microsaldatura": "Siamo uno dei pochi centri in Italia che svolge **microsaldatura e riparazione di schede madri**.\nCon **tempistiche molto strette** abbiamo all'attivo la felicità di moltissimi clienti 👥 che credevano persi per sempre i loro dati." } callback_query.edit_message_text( servizio[callback_query.data.split("|")[1]], reply_markup=InlineKeyboardMarkup([[ # First row InlineKeyboardButton( # Generates a callback query when pressed "Torna Indietro 🔙", callback_data=f"servizi") ]])) if "attiva" in callback_query.data and "disattiva" not in callback_query.data: userId = callback_query.data.split("|")[1] if userId in registrati: callback_query.answer( "Il servizio è già attivo, riceverai le news!") return callback_query.answer("Il servizio è stato attivato!") registrati.append(userId) SaveJson("registrati.json", registrati) if userId in registrati: stato = "Attivo ✅" else: stato = "Disattivo ❌" callback_query.edit_message_text( f"{callback_query.from_user.first_name} da qui potrai scegliere se ricevere o no le news\nAttualmente il servizio è **{stato}**", reply_markup=InlineKeyboardMarkup([ [ # First row InlineKeyboardButton( # Generates a callback query when pressed "Attiva Servizio di News", callback_data=f"attiva|{callback_query.from_user.id}") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Disattiva Servizio di News", callback_data=f"disattiva|{callback_query.from_user.id}" ) ] ])) if "disattiva" in callback_query.data: userId = callback_query.data.split("|")[1] if userId not in registrati: callback_query.answer("Il servizio è già disabilitato!") return callback_query.answer("Hai disattivato il servizio di news!") registrati.remove(userId) SaveJson("registrati.json", registrati) if userId in registrati: stato = "Attivo ✅" else: stato = "Disattivo ❌" callback_query.edit_message_text( f"{callback_query.from_user.first_name} da qui potrai scegliere se ricevere o no le news\nAttualmente il servizio è **{stato}**", reply_markup=InlineKeyboardMarkup([ [ # First row InlineKeyboardButton( # Generates a callback query when pressed "Attiva Servizio di News", callback_data=f"attiva|{callback_query.from_user.id}") ], [ InlineKeyboardButton( # Generates a callback query when pressed "Disattiva Servizio di News", callback_data=f"disattiva|{callback_query.from_user.id}" ) ] ]))
def recall(client: Client, message: Message) -> bool: # Recall messages try: # Basic data hid = glovar.host_id aid = message.from_user.id mid = message.message_id recall_mid, cid = get_guest(message) command_type = get_command_type(message) # Admin info text if glovar.host_id < 0: text = f"{lang('admin')}{lang('colon')}{mention_id(aid)}\n" else: text = "" # Check the chat ID if cid: # Base text text += ( f"{lang('chat_id')}{lang('colon')}{code(cid)}\n" f"{lang('action')}{lang('colon')}{code(lang('action_recall'))}\n" ) # Check the command if not command_type: text += f"{lang('description')}{lang('colon')}{code(lang('description_choose_recall'))}\n" data_host = button_data("recall", "host", str(cid)) data_all = button_data("recall", "all", str(cid)) data_cancel = button_data("cancel", None, None) markup = InlineKeyboardMarkup( [[ InlineKeyboardButton(text=lang("message_host"), callback_data=data_host), InlineKeyboardButton(text=lang("message_all"), callback_data=data_all) ], [ InlineKeyboardButton(text=lang("cancel"), callback_data=data_cancel) ]]) elif command_type in {"all", "host", "single"}: # If the host want to recall single message, bot should found which message to recall if command_type == "single" and not recall_mid: # Get the message's id from message's inline button's data callback_data_list = get_callback_data( message.reply_to_message) if (callback_data_list and callback_data_list[0]["a"] == "recall" and callback_data_list[0]["t"] == "single"): recall_mid = callback_data_list[0]["d"] # Edit the origin report message, delete the reply markup thread(edit_message_reply_markup, (client, hid, message.reply_to_message.message_id, None)) # If the data cannot be found, send a error message else: text += ( f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n" f"{lang('reason')}{lang('colon')}{code(lang('command_origin'))}\n" ) markup = None thread(send_message, (client, hid, text, mid, markup)) return True text += recall_messages(client, cid, command_type, recall_mid) markup = None else: text += ( f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n" f"{lang('reason')}{lang('colon')}{code(lang('command_usage'))}\n" ) markup = None else: text += ( f"{lang('status')}{lang('colon')}{code(lang('status_failed'))}\n" f"{lang('reason')}{lang('colon')}{code(lang('command_usage'))}\n" ) markup = None # Send the report message thread(send_message, (client, hid, text, mid, markup)) return True except Exception as e: logger.warning(f"Recall error: {e}", exc_info=True) return False
def terminate_user_succeed(client: Client, uid: int) -> bool: # Verification succeed result = False try: # Basic data now = get_now() # Pass in all waiting groups wait_group_list = list(g for g in glovar.user_ids[uid]["wait"] if not is_should_qns(g)) for gid in wait_group_list: unrestrict_user(client, gid, uid) # Forgive in all failed groups failed_group_list = list(glovar.user_ids[uid]["failed"]) for gid in failed_group_list: if is_class_d_user(uid): continue if not glovar.configs[gid].get("forgive"): continue unban_user(client, gid, uid) glovar.user_ids[uid]["failed"][gid] = 0 # Unrestrict in all restricted groups restricted_group_list = list(glovar.user_ids[uid]["restricted"]) for gid in restricted_group_list: if is_class_d_user(uid): continue if not glovar.configs[gid].get("forgive"): continue unrestrict_user(client, gid, uid) glovar.user_ids[uid]["restricted"].discard(gid) # Unban in all banned groups banned_group_list = list(glovar.user_ids[uid]["banned"]) for gid in banned_group_list: if is_class_d_user(uid): continue if not glovar.configs[gid].get("forgive"): continue unban_user(client, gid, uid) glovar.user_ids[uid]["banned"].discard(gid) # Modify the status glovar.user_ids[uid]["answer"] = "" glovar.user_ids[uid]["limit"] = 0 glovar.user_ids[uid]["try"] = 0 if glovar.user_ids[uid]["wait"]: gid = min(glovar.user_ids[uid]["wait"], key=glovar.user_ids[uid]["wait"].get) [glovar.user_ids[uid]["wait"].pop(g, 0) for g in wait_group_list] glovar.user_ids[uid]["succeeded"][gid] = now # Delete the hint not all(is_flooded(gid) for gid in wait_group_list) and delete_hint(client) # Remove from CAPTCHA group delay(60, remove_captcha_group, [client, uid]) # Ask help welcome welcome_ids = [ wid for wid in wait_group_list if wid not in glovar.user_ids[uid]["manual"] ] glovar.user_ids[uid]["manual"] -= set(wait_group_list) save("user_ids") ask_help_welcome(client, uid, welcome_ids) # Update the score not any(is_flooded(gid) for gid in wait_group_list) and update_score(client, uid) # Send debug message send_debug(client=client, gids=wait_group_list, action=lang("action_verified"), uid=uid, time=now) # Remove failed status failed_user(client, uid, "remove") # Collect data name = glovar.user_ids[uid]["name"] mid = glovar.user_ids[uid]["mid"] # Reset message id glovar.user_ids[uid]["mid"] = 0 save("user_ids") if not mid: return True # Get the captcha status text text = ( f"{lang('user_name')}{lang('colon')}{mention_text(name, uid)}\n" f"{lang('user_id')}{lang('colon')}{code(uid)}\n" f"{lang('description')}{lang('colon')}{code(lang('description_succeed'))}\n" ) # Get the captcha status markup if glovar.more: markup = InlineKeyboardMarkup([[ InlineKeyboardButton(text=glovar.more_text, url=glovar.more_link) ]]) else: markup = None # Edit the message question_type = glovar.user_ids[uid]["type"] if question_type in glovar.question_types["image"]: thread(target=edit_message_photo, args=(client, glovar.captcha_group_id, mid, "assets/succeed.png", None, text, markup)) elif question_type in glovar.question_types["text"]: thread(target=edit_message_text, args=(client, glovar.captcha_group_id, mid, text, markup)) result = True except Exception as e: logger.warning(f"Terminate user succeed error: {e}", exc_info=True) return result
async def check_progress_for_dl(aria2, gid, event, previous_message): try: file = aria2.get_download(gid) complete = file.is_complete is_file = file.seeder if not complete: if not file.error_message: msg = "" # sometimes, this weird https://t.me/c/1220993104/392975 # error creeps up # TODO: temporary workaround downloading_dir_name = "N/A" try: # another derp -_- # https://t.me/c/1220993104/423318 downloading_dir_name = str(file.name) except: pass # msg = f"\n<b>Downloading File:</b> `{downloading_dir_name}`" msg += f"\n<b>Progress:</b> <i>{file.progress_string()}</i>" msg += f"\n<b>Speed:</b> <i>{file.download_speed_string()}</i>" msg += f"\n<b>Total Size:</b> <i>{file.total_length_string()}</i>" if file.seeder is None : msg += f"\n<b>Connections:</b> <i>{file.connections}</i>" else : msg += f"\n<b>Peers:</b> <i>{file.connections}</i> | <b>Seeds:</b> <i>{file.num_seeders}</i>" msg += f"\n<b>Status:</b> <i>{file.status}</i>" msg += f"\n<b>ETA:</b> <i>{file.eta_string()}</i>" msg += f"\n<b>GID:</b> <code>{gid}</code>" inline_keyboard = [] ikeyboard = [] ikeyboard.append(InlineKeyboardButton("😔 Cancel This Process 😔", callback_data=(f"cancelfile {gid}").encode("UTF-8"))) inline_keyboard.append(ikeyboard) reply_markup = InlineKeyboardMarkup(inline_keyboard) #msg += reply_markup LOGGER.info(msg) if msg != previous_message: await event.edit(msg, reply_markup=reply_markup) previous_message = msg else: msg = file.error_message await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await event.edit(f"`{msg}`") return False await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await check_progress_for_dl(aria2, gid, event, previous_message) else: await asyncio.sleep(EDIT_SLEEP_TIME_OUT) await event.edit(f"File Downloaded Successfully: `{file.name}`") return True except Exception as e: LOGGER.info(str(e)) if " not found" in str(e) or "'file'" in str(e): await event.edit("Download Canceled") return False elif " depth exceeded" in str(e): file.remove(force=True) await event.edit("Download Auto Canceled\nYour Torrent/Link is Dead.") return False else: LOGGER.info(str(e)) await event.edit("<u>error</u> :\n`{}` \n\n#error".format(str(e))) return
def get_invite_link(client: Client, the_type: str, gid: int, manual: bool = False) -> bool: # Get a new invite link glovar.locks["channel"].acquire() try: # Basic data now = get_now() # Read the config cid = glovar.configs[gid]["channel"] channel_text = glovar.configs[gid]["channel_text"] channel_button = glovar.configs[gid]["channel_button"] mid, time = glovar.message_ids[gid]["channel"] # Check the config if not cid: return False # Check the link time if not manual and now - time < glovar.time_channel: return False # Generate link link = export_chat_invite_link(client, gid) # Check the link if link is False: glovar.configs[gid]["channel"] = 0 save("configs") glovar.message_ids[gid]["channel"] = (0, 0) save("message_ids") delete_message(client, cid, mid) return False elif not link: return False # Update the link glovar.configs[gid]["channel_link"] = link save("configs") # Generate text and markup text = channel_text markup = InlineKeyboardMarkup( [[InlineKeyboardButton(text=channel_button, url=link)]]) # Edit message if the_type == "edit" and mid: result = edit_message_text(client, cid, mid, text, markup) if result: glovar.message_ids[gid]["channel"] = (mid, now) save("message_ids") return True # Send new message result = send_message(client, cid, text, None, markup) if result: glovar.message_ids[gid]["channel"] = (result.message_id, now) save("message_ids") mid and delete_message(client, cid, mid) return True except Exception as e: logger.warning(f"New invite link error: {e}", exc_info=True) finally: glovar.locks["channel"].release() return False
async def echo(bot, update: Message): if update.from_user.id not in AUTH_USERS: await update.delete() return # LOGGER.info(update) # await bot.send_chat_action( # chat_id=update.chat.id, # action="typing" # ) LOGGER.info(update.from_user) url, _, youtube_dl_username, youtube_dl_password = get_link(update) if HTTP_PROXY is not None: command_to_exec = [ "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j", url, "--proxy", HTTP_PROXY ] else: command_to_exec = [ "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j", url ] if youtube_dl_username is not None: command_to_exec.append("--username") command_to_exec.append(youtube_dl_username) if youtube_dl_password is not None: command_to_exec.append("--password") command_to_exec.append(youtube_dl_password) # logger.info(command_to_exec) t_response, e_response = await run_shell_command(command_to_exec) # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239 if e_response and "nonnumeric port" not in e_response: # logger.warn("Status : FAIL", exc.returncode, exc.output) error_message = e_response.replace(Translation.YTDL_ERROR_MESSAGE, "") if Translation.ISOAYD_PREMIUM_VIDEOS in error_message: error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD await update.reply_text(text=Translation.NO_VOID_FORMAT_FOUND.format( str(error_message)), quote=True, parse_mode="html", disable_web_page_preview=True) return False if t_response: # logger.info(t_response) x_reponse = t_response if "\n" in x_reponse: x_reponse, _ = x_reponse.split("\n") response_json = json.loads(x_reponse) save_ytdl_json_path = DOWNLOAD_LOCATION + \ "/" + str(update.from_user.id) + ".json" with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: json.dump(response_json, outfile, ensure_ascii=False) # logger.info(response_json) inline_keyboard = [] duration = None if "duration" in response_json: duration = response_json["duration"] if "formats" in response_json: for formats in response_json["formats"]: format_id = formats.get("format_id") format_string = formats.get("format_note") if format_string is None: format_string = formats.get("format") format_ext = formats.get("ext") approx_file_size = "" if "filesize" in formats: approx_file_size = humanbytes(formats["filesize"]) cb_string_video = "{}|{}|{}".format("video", format_id, format_ext) cb_string_file = "{}|{}|{}".format("file", format_id, format_ext) if format_string and "audio only" not in format_string: ikeyboard = [ InlineKeyboardButton( f"S {format_string} video {format_ext} ", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( f"D {format_string} video {approx_file_size} ", callback_data=(cb_string_file).encode("UTF-8")) ] else: # special weird case :\ ikeyboard = [ InlineKeyboardButton( "SVideo [" + "] ( " + approx_file_size + " )", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile [" + "] ( " + approx_file_size + " )", callback_data=(cb_string_file).encode("UTF-8")) ] inline_keyboard.append(ikeyboard) if duration is not None: cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3") cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3") cb_string = "{}|{}|{}".format("audio", "320k", "mp3") inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8")), InlineKeyboardButton( "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8")) ]) inline_keyboard.append([ InlineKeyboardButton( "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8")) ]) else: format_id = response_json["format_id"] format_ext = response_json["ext"] cb_string_file = "{}|{}|{}".format("file", format_id, format_ext) cb_string_video = "{}|{}|{}".format("video", format_id, format_ext) inline_keyboard.append([ InlineKeyboardButton( "SVideo", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile", callback_data=(cb_string_file).encode("UTF-8")) ]) cb_string_file = "{}={}={}".format("file", format_id, format_ext) cb_string_video = "{}={}={}".format("video", format_id, format_ext) inline_keyboard.append([ InlineKeyboardButton( "video", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "file", callback_data=(cb_string_file).encode("UTF-8")) ]) reply_markup = InlineKeyboardMarkup(inline_keyboard) # logger.info(reply_markup) thumbnail = DEF_THUMB_NAIL_VID_S thumbnail_image = DEF_THUMB_NAIL_VID_S if "thumbnail" in response_json: if response_json["thumbnail"] is not None: thumbnail = response_json["thumbnail"] thumbnail_image = response_json["thumbnail"] thumb_image_path = DownLoadFile( thumbnail_image, DOWNLOAD_LOCATION + "/" + str(update.from_user.id) + ".jpg", 128, None, # bot, Translation.DOWNLOAD_START, update.message_id, update.chat.id) await update.reply_photo( photo=thumb_image_path, quote=True, caption=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" + Translation.SET_CUSTOM_USERNAME_PASSWORD, reply_markup=reply_markup, parse_mode="html") else: # fallback for nonnumeric port a.k.a seedbox.io inline_keyboard = [] cb_string_file = "{}={}={}".format("file", "LFO", "NONE") cb_string_video = "{}={}={}".format("video", "OFL", "ENON") inline_keyboard.append([ InlineKeyboardButton( "SVideo", callback_data=(cb_string_video).encode("UTF-8")), InlineKeyboardButton( "DFile", callback_data=(cb_string_file).encode("UTF-8")) ]) reply_markup = InlineKeyboardMarkup(inline_keyboard) await update.reply_photo( photo=DEF_THUMB_NAIL_VID_S, quote=True, caption=Translation.FORMAT_SELECTION.format(""), reply_markup=reply_markup, parse_mode="html", reply_to_message_id=update.message_id)
def nf(client, message,redis): type = message.chat.type userID = message.from_user.id chatID = message.chat.id title = message.chat.title rank = isrank(redis,userID,chatID) text = message.text c = importlib.import_module("lang.arcmd") r = importlib.import_module("lang.arreply") group = redis.sismember("{}Nbot:groups".format(BOT_ID),chatID) rank = isrank(redis,userID,chatID) if group is True and message.outgoing != True: if message.left_chat_member: if message.left_chat_member.id == int(BOT_ID): redis.srem("{}Nbot:groups".format(BOT_ID),chatID) redis.sadd("{}Nbot:disabledgroups".format(BOT_ID),chatID) NextDay_Date = datetime.datetime.today() + datetime.timedelta(days=1) redis.hset("{}Nbot:disabledgroupsTIME".format(BOT_ID),chatID,str(NextDay_Date)) if message.pinned_message and userID != int(BOT_ID): if redis.sismember("{}Nbot:Lpin".format(BOT_ID),chatID) and GPranks(userID,chatID) != "creator": ID = redis.hget("{}Nbot:pinmsgs".format(BOT_ID),chatID) Bot("unpinChatMessage",{"chat_id":chatID,"message_id":message.pinned_message.message_id}) if message.new_chat_members: if (rank is False or rank is 0) and GPranks(userID,chatID) == "member" and re.search("is_bot=True",str(message.new_chat_members)): if redis.sismember("{}Nbot:Lbots".format(BOT_ID),chatID): for mb in message.new_chat_members: first_name = mb.first_name username = mb.username isbot = mb.is_bot mbID = mb.id if isbot: Bot("kickChatMember",{"chat_id":chatID,"user_id":mb.id}) if message.new_chat_members and redis.sismember("{}Nbot:bancheck".format(BOT_ID),chatID): if redis.hget("{}Nbot:bancheck:t".format(BOT_ID),chatID): for mb in message.new_chat_members: userFn = mb.first_name username = mb.username isbot = mb.is_bot userId = mb.id if isbot:return False Bot("restrictChatMember",{"chat_id": chatID,"user_id": userId,"can_send_messages": 0,"can_send_media_messages": 0,"can_send_other_messages": 0, "can_send_polls": 0,"can_change_info": 0,"can_add_web_page_previews": 0,"can_pin_messages": 0,"can_invite_users": 0,}) kb = InlineKeyboardMarkup([[InlineKeyboardButton(r.no, callback_data=json.dumps(["kickcheck","",userId])),InlineKeyboardButton(r.yes, callback_data=json.dumps(["delcheck","",userId]))]]) T ="<a href=\"tg://user?id={}\">{}</a>".format(userId,Name(userFn)) random.shuffle(kb.inline_keyboard[0]) Bot("sendMessage",{"chat_id":chatID,"text":r.checkmem.format(T),"reply_to_message_id":message.message_id,"parse_mode":"html","reply_markup":kb}) else: for mb in message.new_chat_members: userFn = mb.first_name username = mb.username isbot = mb.is_bot userId = mb.id if isbot:return False q,aw,r1,r2 = eq() Bot("restrictChatMember",{"chat_id": chatID,"user_id": userId,"can_send_messages": 0,"can_send_media_messages": 0,"can_send_other_messages": 0, "can_send_polls": 0,"can_change_info": 0,"can_add_web_page_previews": 0,"can_pin_messages": 0,"can_invite_users": 0,}) kb = InlineKeyboardMarkup([[InlineKeyboardButton(aw, callback_data=json.dumps(["certain","",userId])),InlineKeyboardButton(r1, callback_data=json.dumps(["kickcheck","",userId])),InlineKeyboardButton(r2, callback_data=json.dumps(["kickcheck","",userId]))]]) random.shuffle(kb.inline_keyboard[0]) T ="<a href=\"tg://user?id={}\">{}</a>".format(userId,Name(userFn)) Bot("sendMessage",{"chat_id":chatID,"text":r.checkmem2.format(T,q),"reply_to_message_id":message.message_id,"parse_mode":"html","reply_markup":kb}) if redis.sismember("{}Nbot:Ljoin".format(BOT_ID),chatID):#17 Bot("deleteMessage",{"chat_id":chatID,"message_id":message.message_id}) if message.new_chat_members and not redis.sismember("{}Nbot:welcomeSend".format(BOT_ID),chatID): wl = (redis.hget("{}Nbot:welcome".format(BOT_ID),chatID) or "") userId = message.new_chat_members[0].id userFn = message.new_chat_members[0].first_name T ="<a href=\"tg://user?id={}\">{}</a>".format(userId,Name(userFn)) Bot("sendMessage",{"chat_id":chatID,"text":wl.format(us=T),"reply_to_message_id":message.message_id,"parse_mode":"html"}) if message.new_chat_members: userId = message.new_chat_members[0].id if userID != userId: redis.hincrby("{}Nbot:{}:addcontact".format(BOT_ID,chatID),userID) if message.new_chat_members: chatID = message.chat.id userId = message.new_chat_members[0].id if redis.sismember("{}Nbot:restricteds".format(BOT_ID),userId): Bot("restrictChatMember",{"chat_id": chatID,"user_id": userId,"can_send_messages": 0,"can_send_media_messages": 0,"can_send_other_messages": 0, "can_send_polls": 0,"can_change_info": 0,"can_add_web_page_previews": 0,"can_pin_messages": 0,"can_invite_users": 0,}) if redis.sismember("{}Nbot:bans".format(BOT_ID),userId): Bot("kickChatMember",{"chat_id":chatID,"user_id":userId})
async def catch_youtube_dldata(c, q): cb_data = q.data.strip() #print(q.message.chat.id) # Callback Data Check yturl = cb_data.split("||")[-1] format_id = cb_data.split("||")[-2] thumb_image_path = "/app/downloads" + \ "/" + str(q.message.chat.id) + ".jpg" print(thumb_image_path) if os.path.exists(thumb_image_path): width = 0 height = 0 metadata = extractMetadata(createParser(thumb_image_path)) #print(metadata) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") img = Image.open(thumb_image_path) if cb_data.startswith(("audio", "docaudio", "docvideo")): img.resize((320, height)) else: img.resize((90, height)) img.save(thumb_image_path, "JPEG") # print(thumb_image_path) if not cb_data.startswith(("video", "audio", "docaudio", "docvideo")): print("no data found") raise ContinuePropagation filext = "%(title)s.%(ext)s" userdir = os.path.join(os.getcwd(), "downloads", str(q.message.chat.id)) if not os.path.isdir(userdir): os.makedirs(userdir) await q.edit_message_reply_markup( InlineKeyboardMarkup( [[InlineKeyboardButton("Yuklanyapti...", callback_data="down")]])) filepath = os.path.join(userdir, filext) # await q.edit_message_reply_markup([[InlineKeyboardButton("Tayyorlanmoqda..")]]) audio_command = [ "youtube-dl", "-c", "--prefer-ffmpeg", "--extract-audio", "--audio-format", "mp3", "--audio-quality", format_id, "-o", filepath, yturl, ] video_command = [ "youtube-dl", "-c", "--embed-subs", "-f", f"{format_id}+bestaudio", "-o", filepath, "--hls-prefer-ffmpeg", yturl ] loop = asyncio.get_event_loop() med = None if cb_data.startswith("audio"): filename = await downloadaudiocli(audio_command) med = InputMediaAudio(media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), title=os.path.basename(filename)) if cb_data.startswith("video"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaVideo(media=filename, duration=dur, width=width, height=height, thumb=thumb_image_path, caption=os.path.basename(filename), supports_streaming=True) if cb_data.startswith("docaudio"): filename = await downloadaudiocli(audio_command) med = InputMediaDocument( media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), ) if cb_data.startswith("docvideo"): filename = await downloadvideocli(video_command) dur = round(duration(filename)) med = InputMediaDocument( media=filename, thumb=thumb_image_path, caption=os.path.basename(filename), ) if med: loop.create_task(send_file(c, q, med, filename)) else: print("med not found")
def delete(client, message, redis): type = message.chat.type userID = message.from_user.id userFN = message.from_user.first_name chatID = message.chat.id rank = isrank(redis, userID, chatID) if message.text: text = message.text elif message.caption: text = message.caption else: text = 0 c = importlib.import_module("lang.arcmd") r = importlib.import_module("lang.arreply") if redis.sismember("{}Nbot:restricteds".format(BOT_ID), userID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if redis.sismember("{}Nbot:bans".format(BOT_ID), userID): Bot("kickChatMember", {"chat_id": chatID, "user_id": userID}) if redis.sismember(f"{BOT_ID}Nbot:{chatID}:muteusers", userID) and (rank is False or rank is 0): message.delete() if text: if text == c.kickme and not redis.sismember( "{}Nbot:kickme".format(BOT_ID), chatID): GetGprank = GPranks(userID, chatID) if GetGprank == "member": reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton(r.yes, callback_data=json.dumps( ["kickme-yes", "", userID])), InlineKeyboardButton(r.no, callback_data=json.dumps( ["kickme-no", "", userID])), ]]) Bot( "sendMessage", { "chat_id": chatID, "text": r.kickme, "reply_to_message_id": message.message_id, "parse_mode": "html", "reply_markup": reply_markup }) if re.findall( "[Hh][Tt][Tt][Pp][Ss]:/|[Hh][Tt][Tt][Pp]://|.[Ii][Rr]|.[Cc][Oo][Mm]|.[Oo][Rr][Gg]|.[Ii][Nn][Ff][Oo]|[Ww][Ww][Ww]|.[Tt][Kk]|.[Mm][Ee]", text): if redis.sismember("{}Nbot:Llink".format(BOT_ID), chatID): #1 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Llink:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if re.findall('@', text): if redis.sismember("{}Nbot:Lusername".format(BOT_ID), chatID): #2 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lusername:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.forward_date: if redis.sismember("{}Nbot:Lfwd".format(BOT_ID), chatID): #18 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lfwd:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if re.findall('#', text): if redis.sismember("{}Nbot:Ltag".format(BOT_ID), chatID): #3 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Ltag:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if re.findall("[a-zA-Z0-9$@$!%*?&#^-_. +]+", text): if redis.sismember("{}Nbot:Lenglish".format(BOT_ID), chatID): #4 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lenglish:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if re.findall("[ا-ي٠-٩]", text): if redis.sismember("{}Nbot:Larabic".format(BOT_ID), chatID): #5 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Larabic:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) Nlongtext = (redis.get("{}Nbot:Nlongtext".format(BOT_ID)) or 250) if len(text) >= Nlongtext: if redis.sismember("{}Nbot:Llongtext".format(BOT_ID), chatID): #2 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Llongtext:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) li = redis.smembers("{}Nbot:{}:blockTEXTs".format(BOT_ID, chatID)) for word in li: if re.findall(word, text): Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) break # text ^ if message.entities: if redis.sismember("{}Nbot:Lmarkdown".format(BOT_ID), chatID): #6 for entitie in message.entities: if entitie.type is "text_link": Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lmarkdown:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) break if message.via_bot: if redis.sismember("{}Nbot:Linline".format(BOT_ID), chatID): #7 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Linline:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.reply_markup: if redis.sismember("{}Nbot:Linline".format(BOT_ID), chatID): Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Linline:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.sticker: if redis.sismember("{}Nbot:Lsticker".format(BOT_ID), chatID): #8 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lsticker:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) elif redis.sismember("{}Nbot:{}:blockSTICKERs".format(BOT_ID, chatID), message.sticker.file_id): Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if message.animation: if redis.sismember("{}Nbot:Lgifs".format(BOT_ID), chatID): #9 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lgifs:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) elif redis.sismember( "{}Nbot:{}:blockanimations".format(BOT_ID, chatID), message.animation.file_id): Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if message.audio: if redis.sismember("{}Nbot:Lmusic".format(BOT_ID), chatID): #10 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lmusic:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.voice: if redis.sismember("{}Nbot:Lvoice".format(BOT_ID), chatID): #11 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lvoice:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.video: if redis.sismember("{}Nbot:Lvideo".format(BOT_ID), chatID): #12 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lvideo:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.document: if redis.sismember("{}Nbot:Lfiles".format(BOT_ID), chatID): #13 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lfiles:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.photo: if redis.sismember("{}Nbot:Lphoto".format(BOT_ID), chatID): #14 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lphoto:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) elif redis.sismember("{}Nbot:{}:blockphotos".format(BOT_ID, chatID), message.photo.file_id): Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if message.contact: if redis.sismember("{}Nbot:Lcontact".format(BOT_ID), chatID): #15 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lcontact:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.new_chat_members: if message.new_chat_members[0].is_bot: if redis.sismember("{}Nbot:Lbots".format(BOT_ID), chatID): #16 first_name = message.new_chat_members[0].first_name username = message.new_chat_members[0].username Bot("kickChatMember", { "chat_id": chatID, "user_id": message.new_chat_members[0].id }) Bot( "sendMessage", { "chat_id": chatID, "text": r.kickbotadd.format(username, first_name), "reply_to_message_id": message.message_id, "parse_mode": "html" }) if redis.sismember("{}Nbot:Ljoin".format(BOT_ID), chatID): #17 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if message.forward_date: if redis.sismember("{}Nbot:Lfwd".format(BOT_ID), chatID): #18 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lfwd:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if message.video_note: if redis.sismember("{}Nbot:Lnote".format(BOT_ID), chatID): #19 Bot("deleteMessage", { "chat_id": chatID, "message_id": message.message_id }) if redis.sismember("{}Nbot:Lnote:res".format(BOT_ID), chatID): Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userId, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) if redis.sismember("{}Nbot:Lflood".format(BOT_ID), chatID): Max_msg = int((redis.hget("{}Nbot:max_msg".format(BOT_ID), chatID) or 10)) Time_ck = int((redis.hget("{}Nbot:time_ck".format(BOT_ID), chatID) or 3)) User_msg = int( (redis.get("{}Nbot:{}:{}:flood".format(BOT_ID, chatID, userID)) or 1)) if User_msg > Max_msg: GetGprank = GPranks(userID, chatID) if GetGprank == "member": BY = "<a href=\"tg://user?id={}\">{}</a>".format( userID, Name(userFN)) if redis.hexists("{}Nbot:floodset".format(BOT_ID), chatID): get = redis.hget("{}Nbot:floodset".format(BOT_ID), chatID) else: get = "res" if get == "res": Bot( "restrictChatMember", { "chat_id": chatID, "user_id": userID, "can_send_messages": 0, "can_send_media_messages": 0, "can_send_other_messages": 0, "can_send_polls": 0, "can_change_info": 0, "can_add_web_page_previews": 0, "can_pin_messages": 0, "can_invite_users": 0, }) redis.sadd("{}Nbot:{}:restricteds".format(BOT_ID, chatID), userID) Bot( "sendMessage", { "chat_id": chatID, "text": r.TKflood.format(BY, Max_msg, Time_ck), "parse_mode": "html" }) if get == "ban": Bot("kickChatMember", { "chat_id": chatID, "user_id": userID }) redis.sadd("{}Nbot:{}:bans".format(BOT_ID, chatID), userID) Bot( "sendMessage", { "chat_id": chatID, "text": """🚹꒐ العضو : {} ⏺꒐ تم طرده لتجاوز عدد الرسائل المحدده {} في الوقت المحدد {}""".format( BY, Max_msg, Time_ck), "parse_mode": "html" }) redis.setex("{}Nbot:{}:{}:flood".format(BOT_ID, chatID, userID), Time_ck, User_msg + 1)
def give_tacos(bot, message, sender, receiver): cid = get_cid(message) tacos = Tacos.get(Tacos.chat == cid) chat = Chats.get(Chats.cid == message.chat.id) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format( message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) sender_name = store_name(sender) receiver_name = store_name(receiver) if receiver.is_bot: if chat.less is True: text = no_bots_allowed_phrase.split('\n')[0] else: text = no_bots_allowed_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = [mid] chat.save() return sender_id = str(sender.id) receiver_id = str(receiver.id) if sender_id == receiver_id: if chat.less is True: text = self_tacoing_phrase.split('\n')[0] else: text = self_tacoing_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html').message_id chat.mids = [mid] chat.save() return tacos_sent = len(re.findall(taco_emoji, message.text)) txt = message.text if message.entities is not None: for entity in message.entities: txt = txt[:entity.offset] + txt[entity.offset + entity.length:] txt = txt.replace(taco_emoji, '') user_comment = txt.lstrip(' ') if tacos.taco_balance is None: amounts = dict() amounts.update({sender_id: default_taco_amount}) amounts.update({receiver_id: default_taco_amount}) else: amounts = tacos.taco_balance if sender_id not in amounts.keys(): amounts.update({sender_id: default_taco_amount}) if receiver_id not in amounts.keys(): amounts.update({receiver_id: default_taco_amount}) if tacos_sent > amounts.get(sender_id): if chat.less is True: text = balance_low_phrase.split('\n')[0] else: text = balance_low_phrase if chat.autohide: msg = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html') time = datetime.datetime.now() + datetime.timedelta( minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: msg = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html') chat.mids = [msg.message_id] chat.save() return amounts.update({sender_id: amounts.get(sender_id) - tacos_sent}) amounts.update({receiver_id: amounts.get(receiver_id) + tacos_sent}) if chat.less is True: comment = '' else: if tacos_sent < 3: comment = taco_transfer_comment_low elif tacos_sent > 9: comment = taco_transfer_comment_high else: comment = taco_transfer_comment_medium.format(receiver_name) if "@" in sender_name: sender_link = "https://t.me/{}".format(sender_name[1:]) else: sender_link = "tg://user?id={}".format(sender_id) if "@" in receiver_name: receiver_link = "https://t.me/{}".format(receiver_name[1:]) else: receiver_link = "tg://user?id={}".format(receiver_id) if tacos_sent == 1: phrase = taco_transfer_phrase.replace('tacos', 'taco') else: phrase = taco_transfer_phrase if len(user_comment) > 0: phrase += '<b>And said:</b>\n>>><code>{}</code>'.format(user_comment) if chat.autohide: msg = bot.send_message(chat_id=cid, text=phrase.format(sender_link, sender_name, tacos_sent, receiver_link, receiver_name, comment), parse_mode='html', disable_web_page_preview=True) time = datetime.datetime.now() + datetime.timedelta( minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: msg = bot.send_message(chat_id=cid, text=phrase.format(sender_link, sender_name, tacos_sent, receiver_link, receiver_name, comment), reply_markup=ok_keyboard, parse_mode='html', disable_web_page_preview=True) chat.mids = [msg.message_id] chat.save() tacos.taco_balance = amounts tacos.save()
async def broadcast_(c, m): all_users = await c.db.get_all_users() broadcast_msg = m.reply_to_message while True: broadcast_id = ''.join([random.choice(string.ascii_letters) for i in range(3)]) if not c.broadcast_ids.get(broadcast_id): break out = await m.reply_text( text = f"Broadcast initiated! You will be notified with log file when all the users are notified.", reply_markup = InlineKeyboardMarkup( [ [ InlineKeyboardButton("Cancel Broadcast", callback_data=f"cncl_bdct+{broadcast_id}"), InlineKeyboardButton("View broadcast status", callback_data=f"sts_bdct+{broadcast_id}") ] ] ) ) start_time = time.time() total_users = await c.db.total_users_count() done = 0 failed = 0 success = 0 c.broadcast_ids[broadcast_id] = dict( total = total_users, current = done, failed = failed, success = success ) async with aiofiles.open('broadcast.txt', 'w') as broadcast_log_file: async for user in all_users: sts, msg = await send_msg( user_id = int(user['id']), message = broadcast_msg ) if msg is not None: await broadcast_log_file.write(msg) if sts == 200: success += 1 else: failed += 1 if sts == 400: await c.db.delete_user(user['id']) done += 1 if c.broadcast_ids.get(broadcast_id) is None: break else: c.broadcast_ids[broadcast_id].update( dict( current = done, failed = failed, success = success ) ) if c.broadcast_ids.get(broadcast_id): c.broadcast_ids.pop(broadcast_id) completed_in = datetime.timedelta(seconds=int(time.time()-start_time)) await asyncio.sleep(3) await out.delete() if failed == 0: await m.reply_text( text=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", quote=True ) else: await m.reply_document( document='broadcast.txt', caption=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", quote=True ) await aiofiles.os.remove('broadcast.txt')