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 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)
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 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)
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)
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)
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 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 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 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 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 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 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": 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: raise 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": 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: raise 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 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)
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... god_mode_level_present = False if user.id == OWNER_ID: text += "\n\nUser level: <b>God</b>" god_mode_level_present = True elif user.id in DEV_USERS: text += "\n\nUser level: <b>Developer</b>" god_mode_level_present = True elif user.id in SUDO_USERS: text += "\n\nUser level: <b>Sudo</b>" god_mode_level_present = True elif user.id in SUPPORT_USERS: text += "\n\nUser level: <b>Support</b>" god_mode_level_present = True elif user.id in WHITELIST_USERS: text += "\n\nUser level: <b>Whitelist</b>" god_mode_level_present = True if god_mode_level_present: text += ' [<a href="https://t.me/NamikazeMinatoChannel/5">?</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)