def check_afk(update: Update, context: CallbackContext, user_id: int, fst_name: str, userc_id: int): chat = update.effective_chat if sql.is_afk(user_id): user = sql.check_afk_status(user_id) if int(userc_id) == int(user_id): return time = humanize.naturaldelta(datetime.now() - user.time) if not user.reason: res = f"{fst_name} is *afk*.\nLast seen: `{time} ago`" else: res = f"{fst_name} is *afk*.\nReason: `{user.reason}`\nLast seen: `{time} ago`" delmsg = update.effective_message.reply_text( res, parse_mode=ParseMode.MARKDOWN, ) cleartime = get_clearcmd(chat.id, "afk") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def youtube(update: Update, context: CallbackContext): bot = context.bot message = update.effective_message chat = update.effective_chat yt = message.text[len("/youtube "):] if yt: search = VideosSearch(yt, limit=1) result = search.result() try: url = result["result"][0]["link"] title = result["result"][0]["title"] except: return message.reply_text("Failed to find song or video", ) buttons = [[ InlineKeyboardButton("🎵", callback_data=f"youtube;audio;{url}"), InlineKeyboardButton("🎥", callback_data=f"youtube;video;{url}"), InlineKeyboardButton("🚫", callback_data=f"youtube;cancel;" ""), ]] msg = "*Preparing to upload file:*\n" msg += f"`{title}`\n" delmsg = message.reply_text(msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: delmsg = message.reply_text("Specify a song or video") cleartime = get_clearcmd(chat.id, "youtube") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def lyrics(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat query = message.text[len("/lyrics ") :] song = "" if query: song = Song.find_song(query) if song: if song.lyrics: msg = song.format() else: msg = "Couldn't find any lyrics for that song!" else: msg = "Song not found!" if len(msg) > 4090: with open("lyrics.txt", "w") as f: msg = f.write(f"{reply}\n\n\nOwO UwU OmO") with open("lyrics.txt", "rb") as f: msg = "Message length exceeded max limit! Sending as a text file." else: msg = "You haven't specified which song to look for!" delmsg = message.reply_text( text = msg, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "lyrics") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def magisk(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat link = "https://raw.githubusercontent.com/topjohnwu/magisk-files/master/" magisk_dict = { "*Stable*": "stable.json", "\n" "*Canary*": "canary.json", }.items() msg = "*Latest Magisk Releases:*\n\n" for magisk_type, release_url in magisk_dict: data = get(link + release_url).json() msg += ( f"{magisk_type}:\n" f'• Manager - [{data["magisk"]["version"]} ({data["magisk"]["versionCode"]})]({data["magisk"]["link"]}) \n' ) delmsg = message.reply_text( text = msg, parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "magisk") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def no_longer_afk(update: Update, context: CallbackContext): user = update.effective_user message = update.effective_message chat = update.effective_chat if not user: # ignore channels return res = sql.rm_afk(user.id) if res: if message.new_chat_members: # dont say msg return firstname = update.effective_user.first_name try: options = [ "{} is here!", "{} is back!", "{} is now in the chat!", "{} is awake!", "{} is back online!", "{} is finally here!", "Welcome back! {}", "Where is {}?\nIn the chat!", ] chosen_option = random.choice(options) delmsg = update.effective_message.reply_text( chosen_option.format(firstname)) cleartime = get_clearcmd(chat.id, "afk") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) except: return
def afk(update: Update, context: CallbackContext): args = update.effective_message.text.split(None, 1) user = update.effective_user chat = update.effective_chat if not user: # ignore channels return if user.id in [777000, 1087968824]: return notice = "" if len(args) >= 2: reason = args[1] if len(reason) > 100: reason = reason[:100] notice = "\nYour afk reason was shortened to 100 characters." else: reason = "" sql.set_afk(update.effective_user.id, reason) fname = update.effective_user.first_name try: delmsg = update.effective_message.reply_text( "{} is now away!{}".format(fname, notice)) cleartime = get_clearcmd(chat.id, "afk") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) except BadRequest: pass
def orangefox(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat device = message.text[len("/orangefox ") :] btn = "" if device: link = get(f"https://api.orangefox.download/v3/releases/?codename={device}&sort=date_desc&limit=1") if link.status_code == 404: msg = f"OrangeFox recovery is not avaliable for {device}" else: page = loads(link.content) file_id = page["data"][0]["_id"] link = get(f"https://api.orangefox.download/v3/devices/get?codename={device}") page = loads(link.content) oem = page["oem_name"] model = page["model_name"] full_name = page["full_name"] maintainer = page["maintainer"]["username"] link = get(f"https://api.orangefox.download/v3/releases/get?_id={file_id}") page = loads(link.content) dl_file = page["filename"] build_type = page["type"] version = page["version"] changelog = page["changelog"][0] size = str(round(float(page["size"]) / 1024 / 1024, 1)) + "MB" dl_link = page["mirrors"]["NL"] date = datetime.fromtimestamp(page["date"]) md5 = page["md5"] msg = f"*Latest OrangeFox Recovery for the {full_name}*\n\n" msg += f"• Manufacturer: `{oem}`\n" msg += f"• Model: `{model}`\n" msg += f"• Codename: `{device}`\n" msg += f"• Build type: `{build_type}`\n" msg += f"• Maintainer: `{maintainer}`\n" msg += f"• Version: `{version}`\n" msg += f"• Changelog: `{changelog}`\n" msg += f"• Size: `{size}`\n" msg += f"• Date: `{date}`\n" msg += f"• File: `{dl_file}`\n" msg += f"• MD5: `{md5}`\n" btn = [[InlineKeyboardButton(text=f"Download", url = dl_link)]] else: msg = 'Give me something to fetch, like:\n`/orangefox a3y17lte`' delmsg = message.reply_text( text = msg, reply_markup = InlineKeyboardMarkup(btn), parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "orangefox") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
async def zombies(event): chat = await event.get_chat() chat_id = event.chat_id admin = chat.admin_rights creator = chat.creator if not await user_is_admin(user_id=event.sender_id, message=event): delmsg = "Only Admins are allowed to use this command" elif not admin and not creator: delmsg = "I am not an admin here!" else: count = 0 arg = event.pattern_match.group(1).lower() if not arg: msg = "**Searching for zombies...**\n" msg = await event.reply(msg) async for user in event.client.iter_participants(event.chat): if user.deleted: count += 1 if count == 0: delmsg = await msg.edit( "No deleted accounts found. Group is clean") else: delmsg = await msg.edit( f"Found **{count}** zombies in this group\nClean them by using - `/zombies clean`" ) elif arg == "clean": msg = "**Cleaning zombies...**\n" msg = await event.reply(msg) async for user in event.client.iter_participants(event.chat): if user.deleted and not await user_is_admin(user_id=user, message=event): count += 1 await event.client.kick_participant(chat, user) if count == 0: delmsg = await msg.edit( "No deleted accounts found. Group is clean") else: delmsg = await msg.edit(f"Cleaned `{count}` zombies") else: delmsg = await event.reply( "Wrong parameter. You can use only `/zombies clean`") cleartime = get_clearcmd(chat_id, "zombies") if cleartime: await sleep(cleartime.time) await delmsg.delete()
def getfw(update: Update, context: CallbackContext): args = context.args message = update.effective_message chat = update.effective_chat btn = "" if len(args) == 2: temp, csc = args model = f'sm-' + temp if not temp.upper().startswith('SM-') else temp fota = get( f'http://fota-cloud-dn.ospserver.net/firmware/{csc.upper()}/{model.upper()}/version.xml' ) if fota.status_code != 200: msg = f"Couldn't check for {temp.upper()} and {csc.upper()}, please refine your search or try again later!" else: url1 = f'https://samfrew.com/model/{model.upper()}/region/{csc.upper()}/' url2 = f'https://www.sammobile.com/samsung/firmware/{model.upper()}/{csc.upper()}/' url3 = f'https://sfirmware.com/samsung-{model.lower()}/#tab=firmwares' url4 = f'https://samfw.com/firmware/{model.upper()}/{csc.upper()}/' fota = get( f'http://fota-cloud-dn.ospserver.net/firmware/{csc.upper()}/{model.upper()}/version.xml' ) page = BeautifulSoup(fota.content, 'lxml') os = page.find("latest").get("o") msg = "" if page.find("latest").text.strip(): pda, csc2, phone = page.find("latest").text.strip().split('/') msg += f'*Latest firmware for {model.upper()} and {csc.upper()} is:*\n' msg += f'• PDA: `{pda}`\n• CSC: `{csc2}`\n' if phone: msg += f'• Phone: `{phone}`\n' if os: msg += f'• Android: `{os}`\n' msg += '\n' msg += f'*Downloads for {model.upper()} and {csc.upper()}*\n' btn = [[InlineKeyboardButton(text=f"samfrew.com", url = url1)]] btn += [[InlineKeyboardButton(text=f"sammobile.com", url = url2)]] btn += [[InlineKeyboardButton(text=f"sfirmware.com", url = url3)]] btn += [[InlineKeyboardButton(text=f"samfw.com", url = url4)]] else: msg = 'Give me something to fetch, like:\n`/getfw SM-N975F DBT`' delmsg = message.reply_text( text = msg, reply_markup = InlineKeyboardMarkup(btn), parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "getfw") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def plet(update: Update, context: CallbackContext): chat = update.effective_chat message = update.effective_message if not message.reply_to_message: msg = message.text.split(None, 1)[1] else: msg = message.reply_to_message.text # the processed photo becomes too long and unreadable + the telegram doesn't support any longer dimensions + you have the lulz. if (len(msg)) > 39: message.reply_text("thonk yourself") return tracking = Image.open( BytesIO( base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAAAYAAAOACAYAAAAZzQIQAAAALElEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAPwZV4AAAfA8WFIAAAAASUVORK5CYII=" ))) # base64 encoded empty image(but longer) for character in msg: if character not in thonkifydict: msg = msg.replace(character, "") x = 0 y = 896 image = Image.new("RGBA", [x, y], (0, 0, 0)) for character in msg: value = thonkifydict.get(character) addedimg = Image.new("RGBA", [x + value.size[0] + tracking.size[0], y], (0, 0, 0)) addedimg.paste(image, [0, 0]) addedimg.paste(tracking, [x, 0]) addedimg.paste(value, [x + tracking.size[0], 0]) image = addedimg x = x + value.size[0] + tracking.size[0] maxsize = 1024, 896 if image.size[0] > maxsize[0]: image.thumbnail(maxsize, Image.ANTIALIAS) # put processed image in a buffer and then upload cause async with BytesIO() as buffer: buffer.name = "image.png" image.save(buffer, "PNG") buffer.seek(0) delmsg = context.bot.send_sticker(chat_id=message.chat_id, sticker=buffer) cleartime = get_clearcmd(chat.id, "fun") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def wall(update: Update, context: CallbackContext): chat_id = update.effective_chat.id msg = update.effective_message args = context.args msg_id = update.effective_message.message_id bot = context.bot query = " ".join(args) if not query: msg.reply_text("Please enter a query!") return else: caption = query term = query.replace(" ", "%20") json_rep = r.get( f"https://wall.alphacoders.com/api2.0/get.php?auth={WALL_API}&method=search&term={term}" ).json() if not json_rep.get("success"): msg.reply_text(f"An error occurred! Report this @{SUPPORT_CHAT}") else: wallpapers = json_rep.get("wallpapers") if not wallpapers: msg.reply_text("No results found! Refine your search.") return else: index = randint(0, len(wallpapers) - 1) # Choose random index wallpaper = wallpapers[index] wallpaper = wallpaper.get("url_image") wallpaper = wallpaper.replace("\\", "") delmsg_preview = bot.send_photo( chat_id, photo=wallpaper, caption="Preview", reply_to_message_id=msg_id, timeout=60, ) delmsg = bot.send_document( chat_id, document=wallpaper, filename="wallpaper", caption=caption, reply_to_message_id=msg_id, timeout=60, ) cleartime = get_clearcmd(chat_id, "wall") if cleartime: context.dispatcher.run_async(delete, delmsg_preview, cleartime.time) context.dispatcher.run_async(delete, delmsg, cleartime.time)
async def purge_messages(event): start = time.perf_counter() if event.from_id is None: return if not await user_is_admin(user_id=event.sender_id, message=event) and event.from_id not in [ 1087968824 ]: await event.reply("Only Admins are allowed to use this command") return if not await user_can_purge(user_id=event.sender_id, message=event): await event.reply("You don't have the permission to delete messages") return if not await can_delete_messages(message=event): await event.reply("Can't seem to purge the message") return reply_msg = await event.get_reply_message() if not reply_msg: await event.reply( "Reply to a message to select where to start purging from.") return messages = [] message_id = reply_msg.id delete_to = event.message.id messages.append(event.reply_to_msg_id) for msg_id in range(message_id, delete_to + 1): messages.append(msg_id) if len(messages) == 100: await event.client.delete_messages(event.chat_id, messages) messages = [] try: await event.client.delete_messages(event.chat_id, messages) except: pass time_ = time.perf_counter() - start text = f"Purged Successfully in {time_:0.2f} Second(s)" delmsg = await event.respond(text, parse_mode="markdown") cleartime = get_clearcmd(event.chat_id, "purge") if cleartime: await sleep(cleartime.time) await delmsg.delete()
def wiki(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat msg = "" definition = message.text[len("/wiki ") :] if definition: res = "" search = message.text try: res = wikipedia.summary(search) except DisambiguationError: msg = 'Disambiguated pages found! Adjust your query accordingly' except PageError: msg = 'An error happened getting the wiki page, try again with other term' if res: msg = f"*{search}*\n\n" msg += f"`{res}`\n\n" msg += f"Read more: https://en.wikipedia.org/wiki/{definition}" if len(msg) > 4000: with open("result.txt", "w") as f: f.write(f"{result}\n\nUwU OwO OmO UmU") with open("result.txt", "rb") as f: delmsg = context.bot.send_document( document=f, filename=f.name, reply_to_message_id=update.message.message_id, chat_id=update.effective_chat.id, parse_mode=ParseMode.HTML, ) try: for f in glob.glob("result.txt"): os.remove(f) except Exception: pass else: msg = 'Give me something to get from Wikipedia, like:\n`/wiki Madrid`' delmsg = message.reply_text( text = msg, parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "wiki") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def convert(update: Update, context: CallbackContext): chat = update.effective_chat args = update.effective_message.text.split(" ") if len(args) == 4: try: orig_cur_amount = float(args[1]) except ValueError: update.effective_message.reply_text("Invalid amount of currency") return orig_cur = args[2].upper() new_cur = args[3].upper() request_url = (f"https://www.alphavantage.co/query" f"?function=CURRENCY_EXCHANGE_RATE" f"&from_currency={orig_cur}" f"&to_currency={new_cur}" f"&apikey={CASH_API_KEY}") response = requests.get(request_url).json() try: current_rate = float(response["Realtime Currency Exchange Rate"] ["5. Exchange Rate"]) except KeyError: update.effective_message.reply_text("Currency not supported.") return new_cur_amount = round(orig_cur_amount * current_rate, 5) delmsg = update.effective_message.reply_text( f"{orig_cur_amount} {orig_cur} = {new_cur_amount} {new_cur}") elif len(args) == 1: delmsg = update.effective_message.reply_text( "Check extras module help for `/cash` usage", parse_mode=ParseMode.MARKDOWN) else: delmsg = update.effective_message.reply_text( f"*Invalid Args!!:* Required 3 but passed {len(args) -1}", parse_mode=ParseMode.MARKDOWN, ) cleartime = get_clearcmd(chat.id, "cash") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def phh(update: Update, context: CallbackContext): args = context.args message = update.effective_message chat = update.effective_chat index = int(args[0]) if len(args) > 0 and args[0].isdigit() else 0 text = getphh(index) delmsg = message.reply_text( text, parse_mode = ParseMode.HTML, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "phh") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def ud(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat text = message.text[len("/ud ") :] results = requests.get( f"https://api.urbandictionary.com/v0/define?term={text}" ).json() try: reply_text = f'*{text}*\n\n{results["list"][0]["definition"]}\n\n_{results["list"][0]["example"]}_' except: reply_text = "No results found." delmsg = message.reply_text(reply_text, parse_mode=ParseMode.MARKDOWN) cleartime = get_clearcmd(chat.id, "ud") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def checkfw(update: Update, context: CallbackContext): args = context.args message = update.effective_message chat = update.effective_chat if len(args) == 2: temp, csc = args model = f'sm-' + temp if not temp.upper().startswith('SM-') else temp fota = get( f'http://fota-cloud-dn.ospserver.net/firmware/{csc.upper()}/{model.upper()}/version.xml' ) if fota.status_code != 200: msg = f"Couldn't check for {temp.upper()} and {csc.upper()}, please refine your search or try again later!" else: page = BeautifulSoup(fota.content, 'lxml') os = page.find("latest").get("o") if page.find("latest").text.strip(): msg = f'*Latest released firmware for {model.upper()} and {csc.upper()} is:*\n' pda, csc, phone = page.find("latest").text.strip().split('/') msg += f'• PDA: `{pda}`\n• CSC: `{csc}`\n' if phone: msg += f'• Phone: `{phone}`\n' if os: msg += f'• Android: `{os}`\n' msg += '' else: msg = f'*No public release found for {model.upper()} and {csc.upper()}.*\n\n' else: msg = 'Give me something to fetch, like:\n`/checkfw SM-N975F DBT`' delmsg = message.reply_text( text = msg, parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "checkfw") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def miui(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat device = message.text[len("/miui ") :] markup = [] if device: link = "https://raw.githubusercontent.com/XiaomiFirmwareUpdater/miui-updates-tracker/master/data/latest.yml" yaml_data = load(get(link).content, Loader=Loader) data = [i for i in yaml_data if device in i['codename']] if not data: msg = f"Miui is not avaliable for {device}" else: for fw in data: av = fw['android'] branch = fw['branch'] method = fw['method'] link = fw['link'] fname = fw['name'] version = fw['version'] size = fw['size'] btn = fname + ' | ' + branch + ' | ' + method + ' | ' + version + ' | ' + av + ' | ' + size markup.append([InlineKeyboardButton(text = btn, url = link)]) device = fname.split(" ") device.pop() device = " ".join(device) msg = f"The latest firmwares for the *{device}* are:" else: msg = 'Give me something to fetch, like:\n`/miui whyred`' delmsg = message.reply_text( text = msg, reply_markup = InlineKeyboardMarkup(markup), parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "miui") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def tts(update: Update, context: CallbackContext): args = context.args message = update.effective_message chat = update.effective_chat delmsg = "" if message.reply_to_message: delmsg = message.reply_to_message.text if args: delmsg = " ".join(args).lower() current_time = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S") filename = datetime.now().strftime("%d%m%y-%H%M%S%f") update.message.chat.send_action(ChatAction.RECORD_AUDIO) lang = "ml" tts = gTTS(delmsg, lang) tts.save("k.mp3") with open("k.mp3", "rb") as f: linelist = list(f) linecount = len(linelist) if linecount == 1: update.message.chat.send_action(ChatAction.RECORD_AUDIO) lang = "en" tts = gTTS(delmsg, lang) tts.save("k.mp3") with open("k.mp3", "rb") as speech: delmsg = update.message.reply_voice(speech, quote=False) os.remove("k.mp3") else: delmsg = message.reply_text( "Reply a message or give something like:\n`/tts <message>`", parse_mode = ParseMode.MARKDOWN ) cleartime = get_clearcmd(chat.id, "tts") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def ping(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat start_time = time.time() msg = message.reply_text("Pinging...") end_time = time.time() telegram_ping = str(round((end_time - start_time) * 1000, 3)) + " ms" uptime = get_readable_time((time.time() - StartTime)) delmsg = msg.edit_text( "*PONG!!*\n" f"Time Taken: `{telegram_ping}`\n" f"Bot uptime: `{uptime}`", parse_mode=ParseMode.MARKDOWN, ) cleartime = get_clearcmd(chat.id, "ping") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def list_notes(update: Update, context: CallbackContext): bot = context.bot user = update.effective_user chat_id = update.effective_chat.id note_list = sql.get_all_chat_notes(chat_id) notes = len(note_list) + 1 msg = "Get note by `/notenumber` or `#notename` \n\n *ID* *Note* \n" msg_pm = f"*Notes from {update.effective_chat.title}* \nGet note by `/notenumber` or `#notename` in group \n\n *ID* *Note* \n" for note_id, note in zip(range(1, notes), note_list): if note_id < 10: note_name = f"{note_id:2}. `{(note.name.lower())}`\n" else: note_name = f"{note_id}. `{(note.name.lower())}`\n" if len(msg) + len(note_name) > MAX_MESSAGE_LENGTH: update.effective_message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) msg = "" msg_pm = "" msg += note_name msg_pm += note_name if not note_list: try: update.effective_message.reply_text("No notes in this chat!") except BadRequest: update.effective_message.reply_text("No notes in this chat!", quote=False) elif len(msg) != 0: setting = getprivatenotes(chat_id) if setting == True: bot.send_message(user.id, msg_pm, parse_mode=ParseMode.MARKDOWN) else: delmsg = update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def speedtestxyz_callback(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat query = update.callback_query if query.from_user.id in DEV_USERS: delmsg = message.edit_text("Running a speedtest....") speed = speedtest.Speedtest() speed.get_best_server() speed.download() speed.upload() context.dispatcher.run_async(delete, delmsg, 30) msg = "*SpeedTest Results:*" if query.data == "speedtest_image": speedtest_image = speed.results.share() delmsg = message.reply_photo( photo=speedtest_image, caption=msg, parse_mode = ParseMode.MARKDOWN, ) elif query.data == "speedtest_text": result = speed.results.dict() msg += f"\nDownload: `{convert(result['download'])}Mb/s`\nUpload: `{convert(result['upload'])}Mb/s`\nPing: `{result['ping']}`" delmsg = message.reply_text( text = msg, parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "speedtest") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) else: query.answer("You are required to be a developer user to use this command.")
def covid(update: Update, context: CallbackContext): bot = context.bot chat = update.effective_chat message = update.effective_message country = message.text[len("/covid ") :] covid = Covid() if country: try: country_data = covid.get_status_by_country_name(country) except: return message.reply_text("Wrong country name!") msg = f"*Corona Virus Info*\n\n" msg += f"• Country: `{country}`\n" msg += f"• Confirmed: `{country_data['confirmed']}`\n" msg += f"• Active: `{country_data['active']}`\n" msg += f"• Deaths: `{country_data['deaths']}`\n" msg += f"• Recovered: `{country_data['recovered']}`\n" msg += ( "Last update: " f"`{datetime.utcfromtimestamp(country_data['last_update'] // 1000).strftime('%Y-%m-%d %H:%M:%S')}`\n" ) msg += f"__Data provided by__ [Johns Hopkins University](https://j.mp/2xf6oxF)" else: msg = "Please specify a country" delmsg = message.reply_text( text=msg, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, ) cleartime = get_clearcmd(chat.id, "covid") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def twrp(update: Update, context: CallbackContext): message = update.effective_message chat = update.effective_chat device = message.text[len("/twrp ") :] btn = "" if device: link = get(f"https://eu.dl.twrp.me/{device}") if link.status_code == 404: msg = f"TWRP is not avaliable for {device}" else: page = BeautifulSoup(link.content, "lxml") download = page.find("table").find("tr").find("a") dl_link = f"https://eu.dl.twrp.me{download['href']}" dl_file = download.text size = page.find("span", {"class": "filesize"}).text date = page.find("em").text.strip() msg = f"*Latest TWRP for the {device}*\n\n" msg += f"• Size: `{size}`\n" msg += f"• Date: `{date}`\n" msg += f"• File: `{dl_file}`\n\n" btn = [[InlineKeyboardButton(text=f"Download", url = dl_link)]] else: msg = 'Give me something to fetch, like:\n`/twrp a3y17lte`' delmsg = message.reply_text( text = msg, reply_markup = InlineKeyboardMarkup(btn), parse_mode = ParseMode.MARKDOWN, disable_web_page_preview = True, ) cleartime = get_clearcmd(chat.id, "twrp") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def gettime(update: Update, context: CallbackContext): chat = update.effective_chat message = update.effective_message try: query = message.text.strip().split(" ", 1)[1] except: message.reply_text( "Provide a country name/abbreviation/timezone to find.") return send_message = message.reply_text( f"Finding timezone info for <b>{query}</b>", parse_mode=ParseMode.HTML) query_timezone = query.lower() if len(query_timezone) == 2: result = generate_time(query_timezone, ["countryCode"]) else: result = generate_time(query_timezone, ["zoneName", "countryName"]) if not result: delmsg = send_message.edit_text( f"Timezone info not available for <b>{query}</b>\n" '<b>All Timezones:</b> <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">List here</a>', parse_mode=ParseMode.HTML, disable_web_page_preview=True, ) return delmsg = send_message.edit_text(result, parse_mode=ParseMode.HTML, disable_web_page_preview=True) cleartime = get_clearcmd(chat.id, "time") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def clearcmd(update: Update, context: CallbackContext): chat = update.effective_chat message = update.effective_message args = context.args msg = "" commands = [ "afk", "cash", "checkfw", "covid", "filters", "fun", "getfw", "github", "imdb", "info", "lyrics", "magisk", "miui", "notes", "orangefox", "phh", "ping", "purge", "reverse", "speedtest", "time", "tr", "tts", "twrp", "ud", "wall", "weather", "welcome", "wiki", "youtube", "zombies", ] if len(args) == 0: commands = sql.get_allclearcmd(chat.id) if commands: msg += "*Command - Time*\n" for cmd in commands: msg += f"`{cmd.cmd} - {cmd.time} secs`\n" else: msg = f"No deletion time has been set for any command in *{chat.title}*" elif len(args) == 1: cmd = args[0].lower() if cmd == "list": msg = "The commands available are:\n" for cmd in commands: msg += f"• `{cmd}`\n" elif cmd == "restore": delcmd = sql.del_allclearcmd(chat.id) msg = "Removed all commands from list" else: cmd = sql.get_clearcmd(chat.id, cmd) if cmd: msg = f"`{cmd.cmd}` output is set to be deleted after *{cmd.time}* seconds in *{chat.title}*" else: if cmd not in commands: msg = "Invalid command. Check module help for more details" else: msg = f"This command output hasn't been set to be deleted in *{chat.title}*" elif len(args) == 2: cmd = args[0].lower() time = args[1] if cmd in commands: if time == "restore": sql.del_clearcmd(chat.id, cmd) msg = f"Removed `{cmd}` from list" elif (5 <= int(time) <= 300): sql.set_clearcmd(chat.id, cmd, time) msg = f"`{cmd}` output will be deleted after *{time}* seconds in *{chat.title}*" else: msg = "Time must be between 5 and 300 seconds" else: msg = "Specify a valid command. Use `/clearcmd list` to see available commands" else: msg = "I don't understand what are you trying to do. Check module help for more details" message.reply_text(text=msg, parse_mode=ParseMode.MARKDOWN)
def deletion(update: Update, context: CallbackContext, delmsg): chat = update.effective_chat cleartime = get_clearcmd(chat.id, "tr") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
def info(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message chat = update.effective_chat user_id = extract_user(update.effective_message, args) if user_id: user = bot.get_chat(user_id) elif not message.reply_to_message and not args: user = message.from_user elif not message.reply_to_message and ( not args or (len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not message.parse_entities([MessageEntity.TEXT_MENTION]))): delmsg = message.reply_text("I can't extract a user from this.") cleartime = get_clearcmd(chat.id, "info") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time) return else: return rep = message.reply_text("<code>Appraising...</code>", parse_mode=ParseMode.HTML) text = (f"<b>User info:</b>\n" f"ID: <code>{user.id}</code>\n" f"First Name: {html.escape(user.first_name)}") if user.last_name: text += f"\nLast Name: {html.escape(user.last_name)}" if user.username: text += f"\nUsername: @{html.escape(user.username)}" text += f"\nPermalink: {mention_html(user.id, 'link')}" if chat.type != "private" and user_id != bot.id: _stext = "\nPresence: <code>{}</code>" afk_st = is_afk(user.id) if afk_st: text += _stext.format("AFK") else: status = status = bot.get_chat_member(chat.id, user.id).status if status: if status == "left": text += _stext.format("Not here") if status == "kicked": text += _stext.format("Banned") elif status == "member": text += _stext.format("Detected") elif status in {"administrator", "creator"}: text += _stext.format("Admin") try: spamwtc = sw.get_ban(int(user.id)) if spamwtc: text += "\n\n<b>This person is Spamwatched!</b>" text += f"\nReason: <pre>{spamwtc.reason}</pre>" text += "\nAppeal at @SpamWatchSupport" else: pass except: pass # don't crash if api is down somehow... disaster_level_present = False if user.id == OWNER_ID: text += "\n\nUser level: <b>god</b>" disaster_level_present = True elif user.id in DEV_USERS: text += "\n\nUser level: <b>developer</b>" disaster_level_present = True elif user.id in SUDO_USERS: text += "\n\nUser level: <b>sudo</b>" disaster_level_present = True elif user.id in SUPPORT_USERS: text += "\n\nUser level: <b>support</b>" disaster_level_present = True elif user.id in WHITELIST_USERS: text += "\n\nUser level: <b>whitelist</b>" disaster_level_present = True # if disaster_level_present: # text += ' [<a href="https://t.me/OnePunchUpdates/155">?</a>]'.format( # bot.username) try: user_member = chat.get_member(user.id) if user_member.status == "administrator": result = requests.post( f"https://api.telegram.org/bot{TOKEN}/getChatMember?chat_id={chat.id}&user_id={user.id}" ) result = result.json()["result"] if "custom_title" in result.keys(): custom_title = result["custom_title"] text += f"\n\nTitle:\n<b>{custom_title}</b>" except BadRequest: pass for mod in USER_INFO: try: mod_info = mod.__user_info__(user.id).strip() except TypeError: mod_info = mod.__user_info__(user.id, chat.id).strip() if mod_info: text += "\n\n" + mod_info if INFOPIC: try: profile = context.bot.get_user_profile_photos( user.id).photos[0][-1] _file = bot.get_file(profile["file_id"]) _file.download(f"{user.id}.png") delmsg = message.reply_document( document=open(f"{user.id}.png", "rb"), caption=(text), parse_mode=ParseMode.HTML, ) os.remove(f"{user.id}.png") # Incase user don't have profile pic, send normal text except IndexError: delmsg = message.reply_text(text, parse_mode=ParseMode.HTML, disable_web_page_preview=True) else: delmsg = message.reply_text(text, parse_mode=ParseMode.HTML, disable_web_page_preview=True) rep.delete() cleartime = get_clearcmd(chat.id, "info") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)
async def imdb(e): chat = await e.get_chat() chat_id = e.chat_id try: movie_name = e.pattern_match.group(1) remove_space = movie_name.split(" ") final_name = "+".join(remove_space) page = requests.get("https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name + "&s=all") lnk = str(page.status_code) soup = bs4.BeautifulSoup(page.content, "lxml") odds = soup.findAll("tr", "odd") mov_title = odds[0].findNext("td").findNext("td").text mov_link = ("http://www.imdb.com/" + odds[0].findNext("td").findNext("td").a["href"]) page1 = requests.get(mov_link) soup = bs4.BeautifulSoup(page1.content, "lxml") if soup.find("div", "poster"): poster = soup.find("div", "poster").img["src"] else: poster = "" if soup.find("div", "title_wrapper"): pg = soup.find("div", "title_wrapper").findNext("div").text mov_details = re.sub(r"\s+", " ", pg) else: mov_details = "" credits = soup.findAll("div", "credit_summary_item") if len(credits) == 1: director = credits[0].a.text writer = "Not available" stars = "Not available" elif len(credits) > 2: director = credits[0].a.text writer = credits[1].a.text actors = [] for x in credits[2].findAll("a"): actors.append(x.text) actors.pop() stars = actors[0] + "," + actors[1] + "," + actors[2] else: director = credits[0].a.text writer = "Not available" actors = [] for x in credits[1].findAll("a"): actors.append(x.text) actors.pop() stars = actors[0] + "," + actors[1] + "," + actors[2] if soup.find("div", "inline canwrap"): story_line = soup.find("div", "inline canwrap").findAll("p")[0].text else: story_line = "Not available" info = soup.findAll("div", "txt-block") if info: mov_country = [] mov_language = [] for node in info: a = node.findAll("a") for i in a: if "country_of_origin" in i["href"]: mov_country.append(i.text) elif "primary_language" in i["href"]: mov_language.append(i.text) if soup.findAll("div", "ratingValue"): for r in soup.findAll("div", "ratingValue"): mov_rating = r.strong["title"] else: mov_rating = "Not available" delmsg = await e.reply( "<a href=" + poster + ">​</a>" "<b>Title : </b><code>" + mov_title + "</code>\n<code>" + mov_details + "</code>\n<b>Rating : </b><code>" + mov_rating + "</code>\n<b>Country : </b><code>" + mov_country[0] + "</code>\n<b>Language : </b><code>" + mov_language[0] + "</code>\n<b>Director : </b><code>" + director + "</code>\n<b>Writer : </b><code>" + writer + "</code>\n<b>Stars : </b><code>" + stars + "</code>\n<b>IMDB Url : </b>" + mov_link + "\n<b>Story Line : </b>" + story_line, link_preview=True, parse_mode="HTML", ) except IndexError: delmsg = await e.reply("Please enter a valid movie name !") cleartime = get_clearcmd(chat_id, "imdb") if cleartime: await sleep(cleartime.time) await delmsg.delete()
def weather(update: Update, context: CallbackContext): bot = context.bot chat = update.effective_chat message = update.effective_message city = message.text[len("/weather ") :] if city: APPID = WEATHER_API result = None timezone_countries = { timezone: country for country, timezones in c_tz.items() for timezone in timezones } if "," in city: newcity = city.split(",") if len(newcity[1]) == 2: city = newcity[0].strip() + "," + newcity[1].strip() else: country = get_tz((newcity[1].strip()).title()) try: countrycode = timezone_countries[f"{country}"] except KeyError: weather.edit("`Invalid country.`") return city = newcity[0].strip() + "," + countrycode.strip() url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={APPID}" request = get(url) result = json.loads(request.text) if request.status_code != 200: msg = "No weather information for this location!" else: cityname = result["name"] longitude = result["coord"]["lon"] latitude = result["coord"]["lat"] curtemp = result["main"]["temp"] feels_like = result["main"]["feels_like"] humidity = result["main"]["humidity"] min_temp = result["main"]["temp_min"] max_temp = result["main"]["temp_max"] country = result["sys"]["country"] sunrise = result["sys"]["sunrise"] sunset = result["sys"]["sunset"] wind = result["wind"]["speed"] weath = result["weather"][0] desc = weath["main"] icon = weath["id"] condmain = weath["main"] conddet = weath["description"] if icon <= 232: # Rain storm icon = "⛈" elif icon <= 321: # Drizzle icon = "🌧" elif icon <= 504: # Light rain icon = "🌦" elif icon <= 531: # Cloudy rain icon = "⛈" elif icon <= 622: # Snow icon = "��" elif icon <= 781: # Atmosphere icon = "🌪" elif icon <= 800: # Bright icon = "☀�" elif icon <= 801: # A little cloudy icon = "⛅�" elif icon <= 804: # Cloudy icon = "��" ctimezone = tz(c_tz[country][0]) time = ( datetime.now(ctimezone) .strftime("%A %d %b, %H:%M") .lstrip("0") .replace(" 0", " ") ) fullc_n = c_n[f"{country}"] dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] kmph = str(wind * 3.6).split(".") mph = str(wind * 2.237).split(".") def fahrenheit(f): temp = str(((f - 273.15) * 9 / 5 + 32)).split(".") return temp[0] def celsius(c): temp = str((c - 273.15)).split(".") return temp[0] def sun(unix): xx = ( datetime.fromtimestamp(unix, tz=ctimezone) .strftime("%H:%M") .lstrip("0") .replace(" 0", " ") ) return xx msg = f"*{cityname}, {fullc_n}*\n" msg += f"`Longitude: {longitude}`\n" msg += f"`Latitude: {latitude}`\n\n" msg += f"• **Time:** `{time}`\n" msg += f"• **Temperature:** `{celsius(curtemp)}°C\n`" msg += f"• **Feels like:** `{celsius(feels_like)}°C\n`" msg += f"• **Condition:** `{condmain}, {conddet}` " + f"{icon}\n" msg += f"• **Humidity:** `{humidity}%`\n" msg += f"• **Wind:** `{kmph[0]} km/h`\n" msg += f"• **Sunrise**: `{sun(sunrise)}`\n" msg += f"• **Sunset**: `{sun(sunset)}`" else: msg = "Please specify a city or country" delmsg = message.reply_text( text=msg, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, ) cleartime = get_clearcmd(chat.id, "weather") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)