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 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 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 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 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 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 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"]["DL"] 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)
def wiki(update: Update, context: CallbackContext): chat = update.effective_chat msg = ( update.effective_message.reply_to_message if update.effective_message.reply_to_message else update.effective_message ) res = "" if msg == update.effective_message: search = msg.text.split(" ", maxsplit=1)[1] else: search = msg.text try: res = wikipedia.summary(search) except DisambiguationError as e: delmsg = update.message.reply_text( "Disambiguated pages found! Adjust your query accordingly.\n<i>{}</i>".format( e ), parse_mode=ParseMode.HTML, ) except PageError as e: delmsg = update.message.reply_text( "<code>{}</code>".format(e), parse_mode=ParseMode.HTML ) if res: result = f"<b>{search}</b>\n\n" result += f"<i>{res}</i>\n" result += f"""<a href="https://en.wikipedia.org/wiki/{search.replace(" ", "%20")}">Read more...</a>""" if len(result) > 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: delmsg = update.message.reply_text( result, parse_mode=ParseMode.HTML, disable_web_page_preview=True ) cleartime = get_clearcmd(chat.id, "wiki") 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 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)
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 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)
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 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 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 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 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"Service uptime: `{uptime}`", parse_mode=ParseMode.MARKDOWN, ) cleartime = get_clearcmd(chat.id, "ping") 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 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 get(update: Update, context: CallbackContext, notename, show_none=True, no_format=False): bot = context.bot user = update.effective_user chat_id = update.effective_message.chat.id note_chat_id = update.effective_chat.id note = sql.get_note(note_chat_id, notename) message = update.effective_message # type: Optional[Message] if note: if MessageHandlerChecker.check_user(update.effective_user.id): return # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if JOIN_LOGGER: try: bot.forward_message(chat_id=chat_id, from_chat_id=JOIN_LOGGER, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": raise message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(note_chat_id, notename) else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": raise message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(note_chat_id, notename) else: VALID_NOTE_FORMATTERS = [ "first", "last", "fullname", "username", "id", "chatname", "mention", ] valid_format = escape_invalid_curly_brackets( note.value, VALID_NOTE_FORMATTERS) if valid_format: if not no_format: if "%%%" in valid_format: split = valid_format.split("%%%") if all(split): text = random.choice(split) else: text = valid_format else: text = valid_format else: text = valid_format text = text.format( first=escape_markdown(message.from_user.first_name), last=escape_markdown(message.from_user.last_name or message.from_user.first_name), fullname=escape_markdown( " ".join([ message.from_user.first_name, message.from_user. last_name ] if message.from_user.last_name else [message.from_user.first_name])), username="******" + message.from_user.username if message.from_user.username else mention_markdown( message.from_user.id, message.from_user.first_name), mention=mention_markdown(message.from_user.id, message.from_user.first_name), chatname=escape_markdown( message.chat.title if message.chat.type != "private" else message.from_user.first_name), id=message.from_user.id, ) else: text = "" keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(note_chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: setting = getprivatenotes(chat_id) if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): if setting: bot.send_message( user.id, text, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard, ) else: delmsg = bot.send_message( chat_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async( delete, delmsg, cleartime.time) elif note.msgtype in (sql.Types.STICKER, sql.Types.STICKER): if setting: ENUM_FUNC_MAP[note.msgtype]( user.id, note.file, reply_to_message_id=reply_id, reply_markup=keyboard, ) else: delmsg = ENUM_FUNC_MAP[note.msgtype]( chat_id, note.file, reply_to_message_id=reply_id, reply_markup=keyboard, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async( delete, delmsg, cleartime.time) else: if setting: ENUM_FUNC_MAP[note.msgtype]( user.id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, reply_markup=keyboard, ) else: delmsg = ENUM_FUNC_MAP[note.msgtype]( chat_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, reply_markup=keyboard, ) cleartime = get_clearcmd(chat_id, "notes") if cleartime: context.dispatcher.run_async( delete, delmsg, cleartime.time) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(note_chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted. Ask in " f"@{SUPPORT_CHAT} if you can't figure out why!") LOGGER.exception( "Could not parse message #%s in chat %s", notename, str(note_chat_id), ) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def deletion(update: Update, context: CallbackContext, delmsg): chat = update.effective_chat cleartime = get_clearcmd(chat.id, "welcome") 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 in {"left", "kicked"}: text += _stext.format("Not here") 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)
def youtube_callback(update: Update, context: CallbackContext): bot = context.bot message = update.effective_message chat = update.effective_chat query = update.callback_query media = query.data.split(";") media_type = media[1] media_url = media[2] if media_type == "audio": deltext = message.edit_text("Processing song...") opts = { "format": "bestaudio/best", "addmetadata": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "128", } ], "outtmpl": "%(title)s.%(etx)s", "quiet": True, "logtostderr": False, } codec = "mp3" with YoutubeDL(opts) as rip: rip_data = rip.extract_info(media_url) try: delmsg = bot.send_audio( chat_id = chat.id, audio = open(f"{rip_data['title']}.{codec}", "rb"), duration = int(rip_data['duration']), title = str(rip_data['title']), parse_mode = ParseMode.HTML ) context.dispatcher.run_async(delete, deltext, 0) except: delmsg = message.edit_text( "Song is too large for processing, or any other error happened. Try again later" ) elif media_type == "video": deltext = message.edit_text("Processing video...") opts = { "format": "best", "addmetadata": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegVideoConvertor", "preferedformat": "mp4", } ], "outtmpl": "%(title)s.mp4", "quiet": True, "logtostderr": False, } codec = "mp4" with YoutubeDL(opts) as rip: rip_data = rip.extract_info(media_url) try: delmsg = bot.send_video( chat_id = chat.id, video = open(f"{rip_data['title']}.{codec}", "rb"), duration = int(rip_data['duration']), caption = rip_data['title'], supports_streaming = True, parse_mode = ParseMode.HTML ) context.dispatcher.run_async(delete, deltext, 0) except: delmsg = message.edit_text( "Video is too large for processing, or any other error happened. Try again later" ) else: delmsg = message.edit_text("Canceling...") context.dispatcher.run_async(delete, delmsg, 1) try: os.remove(f"{rip_data['title']}.{codec}") except Exception: pass cleartime = get_clearcmd(chat.id, "youtube") if cleartime: context.dispatcher.run_async(delete, delmsg, cleartime.time)