async def yt_search(video_q): """ For .yt command, do a YouTube search from Telegram. """ query = video_q.pattern_match.group(1) result = '' if not YOUTUBE_API_KEY: await video_q.edit("`Error: YouTube API key missing!\ Add it to environment vars or config.env.`") return opts, query = parse_arguments(query, ['limit' 'order']) limit = opts.get('limit', 5) order = opts.get('order', 'relevance') await video_q.edit("Processing search query...") full_response = youtube_search(query, order, limit) videos_json = full_response[1] i = 1 for video in videos_json: result += f"{i}. [{unescape(video['snippet']['title'])}](https://www.youtube.com/watch?v={video['id']['videoId']}) \n" i += 1 reply_text = f"**Search Query:**\n`{query}`\n\n**Result:**\n{result}" await video_q.edit(reply_text)
async def gsearch(q_event): """ For .google command, do a Google search. """ reply_message = await q_event.get_reply_message() query = q_event.pattern_match.group(1) opts, query = parse_arguments(query, ['page', 'limit']) page = opts.get('page', 1) gsearch = GoogleSearch() query = query or reply_message.text gresults = gsearch.search(query, page) msg = "" limit = opts.get('limit', 5) for i in range(limit): try: title = gresults["titles"][i] link = gresults["links"][i] desc = gresults["descriptions"][i] msg += f"[{title}]({link}) \n" msg += f"`{desc}`\n\n" except IndexError: break await q_event.edit("**Search Query:**\n`" + query + "`\n\n**Results:**\n" + msg, link_preview=False) if BOTLOG: await q_event.client.send_message( BOTLOG_CHATID, "Google Search query `" + query + "` was executed successfully", )
async def img_sampler(event): """ For .img command, search and return images matching the query. """ await event.edit("Processing query...") query = event.pattern_match.group(1) opts, query = parse_arguments(query, ['limit', 'format']) limit = opts.get('limit', 3) fmt = opts.get('format', 'jpg') response = google_images_download.googleimagesdownload() # creating list of arguments arguments = { "keywords": query, "limit": limit, "format": fmt, "no_directory": "no_directory" } # passing the arguments to the function await event.edit("Downloading images...") paths = response.download(arguments) lst = paths[0][query] await event.edit(f"Sending {limit} images...") await event.client.send_file(event.chat_id, lst) shutil.rmtree(os.path.dirname(os.path.abspath(lst[0]))) await event.delete()
async def spamscan_score(e): """ Test a single user against the spamscan algorithm """ args, user = parse_arguments(e.pattern_match.group(1), ['forward']) args['forward'] = args.get('forward', True) args['user'] = user replied_user = await get_user_from_event(e, **args) if not replied_user: await e.edit("**Failed to get information for user**") return await e.edit( f"**Calculating spam score for** {make_mention(replied_user.user)}") score = await score_user(e, replied_user) score_total = sum([i for i in score.values()]) output = f"**Spam score for** {make_mention(replied_user.user)}({replied_user.user.id}): **{score_total}**\n\n" if score_total > 0: output += "**Reasons:**\n" for reason in score.keys(): output += f"{reason}\n" await e.edit(output)
async def kutt_it(e): reply_message = await e.get_reply_message() params = e.pattern_match.group(1) or "" args, params = parse_arguments(params, ['reuse']) urls = extract_urls(params) urls.extend(extract_urls(reply_message.text or "")) print(urls) if not urls: await e.edit("Need a URL to convert", delete_in=3) return reuse = args.get('reuse', False) await e.edit("Kutting...") shortened = {} for url in urls: payload = {'target': url, 'reuse': reuse} headers = {'X-API-Key': KUTT_IT_API_KEY} resp = requests.post(API_ENDPOINT + "url/submit", json=payload, headers=headers) json = resp.json() if resp.status_code == 200: shortened[url] = json['shortUrl'] else: shortened[url] = None message = "" for item in shortened.items(): message += f"Original URL: {item[0]} \nShortened URL: {item[1]} \n" await e.edit(message, link_preview=False)
async def list_subscriptions(event): if not is_mongo_alive() or not is_redis_alive(): await event.edit("`Database connections failing!`", delete_in=3) return params = event.pattern_match.group(1) or "" args, _ = parse_arguments(params, ['all']) fetch_all = args.get('all', False) await event.edit("Fetching subscriptions...") if fetch_all: subs = list(await get_subs(None)) else: subs = list(await get_subs(event.chat_id)) message = "**Subscribed patterns** \n" if len(subs) < 1: message += "No subscriptions yet." else: for sub in subs: gbl = '(g)' if sub['global'] else '' pattern = sub['pattern'] pattern = pattern[:25] + (pattern[25:] and '..') message += f"`{sub['name']}{gbl}`: `{pattern}` \n" await event.edit(message.strip())
async def add_subscription(e): """ Add a subscription pattern. Whenever this pattern is matched in the current chat you will be notified """ params = e.pattern_match.group(1) if not is_mongo_alive() or not is_redis_alive(): await e.edit("`Database connections failing!`", delete_in=3) return args, pattern = parse_arguments(params, ['global']) parts = pattern.split(' ') if not len(parts) >= 2: await e.edit("A name and pattern are required.", delete_in=3) return name = parts[0] pattern = ' '.join(parts[1:]) await e.edit(f"Subscribing to pattern `{pattern}`") gbl = args.get('global', False) if await add_sub(e.chat_id, name, pattern, gbl=gbl) is True: if not args.get('silent'): await e.edit(f"Added subscription `{name}` for pattern `{pattern}`", delete_in=3) else: await e.edit("A subscription with that name already exists", delete_in=3)
async def follow_url(event): reply_message = await event.get_reply_message() message_text = event.pattern_match.group(1) or "" opts, message_text = parse_arguments(message_text, ['full']) await event.edit("Fetching links...") urls = [] if message_text: urls.extend(extract_urls(message_text)) elif reply_message: urls.extend(extract_urls(reply_message.text)) else: await event.edit("No URLs found :(") return base_domain = not opts.get('full', False) await event.edit("Following links...") follows = [] for url in urls: followed = await resolve_url(url, base_domain) follows.append((url, followed)) message = [] for follow in follows: message.append( f"**Original URL:** {follow[0]} \n**Followed URL:** {follow[1]}") message = '\n \n'.join(message) await event.edit(message, link_preview=False)
async def who(event: NewMessage.Event): """ For .user command, get info about a user. """ if event.fwd_from: return args, user = parse_arguments( event.pattern_match.group(1), ['id', 'forward', 'general', 'bot', 'misc', 'all', 'mention']) args['forward'] = args.get('forward', True) args['user'] = user replied_user = await get_user_from_event(event, **args) if not replied_user: await event.edit("**Failed to get information for user**") return user_info = await fetch_info(replied_user, **args) message_id_to_reply = event.message.reply_to_msg_id if not message_id_to_reply: pass await event.edit(str(user_info), parse_mode="markdown")
async def speech_to_text(e): opts = e.pattern_match.group(1) or "" args, _ = parse_arguments(opts, ['lang']) lang = args.get('lang', DEFAULT_LANG) await e.edit("**Transcribing...**") message = await e.get_reply_message() file = message.audio or message.voice if not file: await e.edit("**No audio file specified**", delete_in=3) return file = await bot.download_file(file) content = io.BytesIO(file) audio = types.RecognitionAudio(content=file) config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.OGG_OPUS, sample_rate_hertz=16000, language_code=lang) response = STTClient.long_running_recognize(config, audio) op_result = response.result() result = op_result.results[0].alternatives[0] output = f"**Transcript:** {result.transcript}\n\n**Confidence:** __{round(result.confidence, 5)}__" await e.edit(output)
async def exec(self, event): args, count = parse_arguments(event.pattern_match.group(1), ['silent', 'me']) from_user = '******' if args.get('me') else None reply_message = await event.message.get_reply_message() chat = await event.get_input_chat() messages = [] # Delete the command message await event.delete() if reply_message: # If a message was replied to we'll delete all messages since that one async for msg in bot.iter_messages(chat, min_id=reply_message.id, from_user=from_user): messages.append(msg) messages.append(reply_message) else: # Otherwise we'll purge the last N messages, where N is `count` count = int(count) async for msg in bot.iter_messages(chat, from_user=from_user): if len(messages) >= count: break messages.append(msg) if len(messages) > 0: await bot.delete_messages(chat, messages) if not args.get('silent'): await event.respond(f"Purged {len(messages)} messages")
async def exec(self, event): await event.delete() dbchat = Chat.query.get(event.chat.id) bancommand = dbchat.ban_command args, maybe_user = parse_arguments(event.pattern_match.group(1), [ 'user', 'reason' ]) parts = re.split(r'\s+', maybe_user, 1) args['user'] = args.get('user') or parts[0] if len(parts) > 1 and not args.get('reason'): args['reason'] = parts[1] else: args['reason'] = '' reason = args.get('reason') try: user_full = await get_user_from_event(event, **args) except BaseException: await log_message("**Failed to get information for user**\n" \ f"Command: `{event.message.message}`") return if event.reply_to_msg_id: reply = event.reply_to_msg_id await event.respond(f"{bancommand} {reason}", reply_to=reply) else: user_full = await get_user_from_event(event) await event.respond(f"{bancommand} {user_full.user.id} {reason}")
async def fedban_all(msg): if not is_mongo_alive(): await msg.edit("`Database connections failing!`") return reply_message = await msg.get_reply_message() params = msg.pattern_match.group(1) or "" args, text = parse_arguments(params, ['reason']) banid = None if reply_message: banid = reply_message.from_id banreason = args.get('reason', '[spam]') else: banreason = args.get('reason', '[fban]') if text.isnumeric(): banid = int(text) elif msg.message.entities: ent = await bot.get_entity(text) if ent: banid = ent.id if not banid: return await msg.edit("**No user to fban**", delete_in=3) failed = dict() count = 1 fbanlist = [i['chat_id'] for i in await get_fban()] for bangroup in fbanlist: async with bot.conversation(bangroup) as conv: await conv.send_message(f"/fban {banid} {banreason}") resp = await conv.get_response() await bot.send_read_acknowledge(conv.chat_id) if "New FedBan" not in resp.text: failed[bangroup] = str(conv.chat_id) else: count += 1 await msg.reply("**Fbanned in " + str(count) + " feds!**", delete_in=3) # Sleep to avoid a floodwait. # Prevents floodwait if user is a fedadmin on too many feds await asyncio.sleep(0.2) if failed: failedstr = "" for i in failed.keys(): failedstr += failed[i] failedstr += " " await msg.reply(f"**Failed to fban in {failedstr}**", delete_in=3) else: await msg.reply("**Fbanned in all feds!**", delete_in=3) msg.delete()
async def exec(self, event): msg: Message = event.message args, user = parse_arguments( event.pattern_match.group(1), ['id', 'all', 'general', 'bot', 'misc', 'search']) response = None if user: response = await self._info_from_user(event, **args) elif msg.is_reply: response = await self._info_from_reply(event, **args) if response: await event.respond(str(response))
async def github_info(e): if not github: await e.edit("Github information has not been set up", delete_in=3) return message = e.pattern_match.group(1) reply_message = await e.get_reply_message() if message: message = message.strip() args, message = parse_arguments(message, [ 'general', 'owner', 'all' ]) else: args = {} if not message: if reply_message: message = reply_message.message.strip() else: await e.edit(str(Bold("Can't fetch repo information with no repo"))) return repos = re.findall(GITHUB_REPO_RE, message) if repos: await e.edit(f"Fetching information for {len(repos)} repo(s)...") valid_repos: List[str] = [] invalid_repos: List[str] = [] for user, repo in repos: try: r: Repository = github.get_repo(f"{user}/{repo}") repo = await build_repo_message(r, args) valid_repos.append(str(repo)) except UnknownObjectException: invalid_repos.append(f"{user}/{repo}") pass message = "" if valid_repos: message += '\n\n'.join(valid_repos) if invalid_repos: message += '\n'.join(invalid_repos) await e.edit(message) else: await e.edit("No GitHub repos found") return
async def chat_info(e): params = e.pattern_match.group(1) or "" args, chat = parse_arguments(params, ['id', 'general', 'admins', 'bots', 'all']) args['chat'] = chat if isinstance(e.chat, User): from .userinfo import fetch_info as fetch_user_info replied_user = await e.client(GetFullUserRequest(e.chat.id)) response = await fetch_user_info(replied_user, **args) else: full_chat: ChatFull = await get_chat_from_event(e, **args) await e.edit("**Fetching chat info...**") response = await fetch_info(e, full_chat, **args) await e.edit(str(response))
async def let_me_google_that_for_you(e): providers = list(PROVIDERS.keys()) params = e.pattern_match.group(1) or "" args, message = parse_arguments(params, providers) provider = PROVIDERS['lmgtfy'] for p in providers: if args.get(p): provider = PROVIDERS[p] reply_message = await e.get_reply_message() query = message if message else reply_message.text query = urllib.parse.quote_plus(query) message = provider['message'] url = provider['source'].format(query) await e.edit(f"[{message}]({url})")
async def exec(self, event): await event.delete() gban_chats = Chat.query.filter(Chat.gbans_enabled == True).all() args, maybe_user = parse_arguments(event.pattern_match.group(1), ['user', 'reason']) parts = re.split(r'\s+', maybe_user, 1) args['user'] = args.get('user') or parts[0] if len(parts) > 1 and not args.get('reason'): args['reason'] = parts[1] else: args['reason'] = 'spam [gban]' reason = args.get('reason') try: user_full = await get_user_from_event(event, **args) except BaseException: await log_message("**Failed to get information for user**\n" \ f"Command: `{event.message.message}`") return usermodel = User.query.get(user_full.id) if usermodel: usermodel.gbanned = True usermodel.gban_reason = reason usermodel.commit() if "spam" in reason: with suppress(BaseException): spamwatch.add_ban(user_full.user.id, reason) reply_message = await event.get_reply_message() if (event.chat_id != SPAMWATCH_CHAT_ID) and reply_message: await reply_message.forward_to(SPAMWATCH_CHAT_ID) for fbchat in gban_chats: bancommand = fbchat.gban_command await event.client.send_message( fbchat.id, f"{bancommand} {user_full.user.id} {reason}") await log_message( f"User `{user_full.user.id}` banned in {len(gban_chats)} chats.")
async def doc_search(e): params = e.pattern_match.group(1) args, lib = parse_arguments(params, ['version']) lib = lib.strip() version = int(args.get('version', 3)) python_url = f"https://docs.python.org/{version}/library/{lib}.html" pip_url = f"https://pypi.org/project/{lib}/" await e.edit(f"Searching docs for `{lib}`...") if requests.get(python_url).status_code == 200: response = f"[Python {version} documentation for {lib}]({python_url})" await e.edit(response) elif requests.get(pip_url).status_code == 200: readthedocs_url = f"https://readthedocs.org/projects/{lib}/" if requests.get(readthedocs_url).status_code == 200: response = f"[Documentation for {lib} on Read the Docs]({readthedocs_url})" await e.edit(response) else: await e.edit(f"No docs found for `{lib}`...", delete_in=3)
async def cleanup(e: NewMessage.Event) -> None: """Command to remove Deleted Accounts from a group or network.""" params = e.pattern_match.group(1) or "" chat: Channel = await e.get_chat() keyword_args, _ = parse_arguments(params, ['limit', 'silent']) count_only = keyword_args.get('count', False) silent = keyword_args.get('silent', False) if not chat.creator and not chat.admin_rights: count_only = True waiting_message = None if silent: await e.message.delete() else: waiting_message = await e.edit('**Starting cleanup. This might take a while.**') response = await _cleanup_chat(e, count=count_only, progress_message=e.message) if not silent: await e.edit(str(response)) if waiting_message: await waiting_message.delete()
async def spamscan_classify(e): """ Feed the algorithm by classifying a user either as spam or ham """ args, user = parse_arguments(e.pattern_match.group(1), ['forward', 'reason']) reason = args.get('reason', 'spam[gban]') args['forward'] = args.get('forward', True) args['user'] = user await e.edit(CLASSIFYING_MESSAGE.format("**Fetching user information.**")) replied_user = await get_user_from_event(e, **args) if not replied_user: await e.edit("**Failed to get information for user**", delete_in=3) return me = await bot.get_me() if replied_user.user == me: await e.edit("**Can't flag yourself as spam**", delete_in=3) return hashes = await gather_profile_pic_hashes(e, replied_user.user) if hashes: await e.edit(CLASSIFYING_MESSAGE.format("**Adding profile pic hashes to DB**")) for hsh in hashes: await add_file_hash(hsh, 'profile pic') if spamwatch: await e.edit(CLASSIFYING_MESSAGE.format("**Checking spamwatch.**")) gbanned = spamwatch.get_ban(replied_user.user.id) if not gbanned: await e.edit(CLASSIFYING_MESSAGE.format("**Adding to SpamWatch.**")) try: spamwatch.add_ban(replied_user.user.id, reason) except UnauthorizedError: pass await e.edit(f"**Flagged** {make_mention(replied_user.user)} **as spam**\n" f"**Reason:** {reason}")
async def translateme(trans): """ For .trt command, translate the given text using Google Translate. """ translator = Translator() textx = await trans.get_reply_message() message = trans.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await trans.edit("`Give a text or reply " "to a message to translate!`") return opts, message = parse_arguments(message, ['to', 'from']) dest_lang = opts.get('to', LANG) src_lang = opts.get('from', 'auto') trans.edit("Translating...") try: reply_text = translator.translate(deEmojify(message), dest=dest_lang, src=src_lang) except ValueError: await trans.edit("Invalid destination language.") return source_lan = LANGUAGES[f'{reply_text.src.lower()}'] transl_lan = LANGUAGES[f'{reply_text.dest.lower()}'] reply_text = f"**Source ({source_lan.title()}):**`\n{message}`**\n\ \nTranslation ({transl_lan.title()}):**`\n{reply_text.text}`" await trans.client.send_message(trans.chat_id, reply_text) await trans.delete() if BOTLOG: await trans.client.send_message( BOTLOG_CHATID, f"Translate query {message} was executed successfully", )
async def register_command(e): reply_message = await e.get_reply_message() params = e.pattern_match.group(1) args, params = parse_arguments(params, ['update']) update = args.get('update', False) command, _, text = params.partition(' ') command, text = command, text if text else None await e.edit(f"Registering command `{command}`...") message = reply_message if reply_message else e.message text = reply_message.text if reply_message else text if message.sticker: sticker = { 'id': message.sticker.id, 'access_hash': message.sticker.access_hash } status = await add_command(command, text, sticker=sticker) elif message.photo: print(message.photo) photo_path = await save_file(message.photo) status = await add_command(command, text, photo_path) elif message.gif: gif_path = await save_file(message.gif) status = await add_command(command, text, gif_path) elif message.document: doc_path = await save_file(message.document) status = await add_command(command, text, doc_path, False, True) else: status = await add_command(command, text) if status: await e.edit(f"Registered command `{command}`", delete_in=3) else: await e.edit(f"Failed to register command `{command}`", delete_in=3)
async def grep_messages(e): params = e.pattern_match.group(1) args, pattern = parse_arguments(params, [ 'regex', 'chatlimit', 'msglimit', 'groups', 'channels', 'users', 'archived', 'ids', 'quiet', 'from' ]) use_regex = args.get('regex', False) quiet = args.get('quiet', False) chatlimit = int(args['chatlimit']) if args.get('chatlimit') else None msglimit = int(args['msglimit']) if args.get('msglimit') else None reverse = args.get('reverse', False) from_user = int(args.get('from')) if str( args.get('from')).isnumeric() else args.get('from') groups = args.get('groups', True) channels = args.get('channels', True) users = args.get('users', True) archived = args.get('archived', False) # ids = args.get('ids', "").split(r",\s?") ids = None if not pattern: e.edit("Give me something to grep", delete_in=3) return matches = {} chat_count = 0 async for dialog in e.client.iter_dialogs(archived=archived): if dialog.is_group and not groups: continue if dialog.is_channel and not channels: continue if dialog.is_user and not users: continue chat_count += 1 if chat_count > chatlimit: break if not quiet: try: await e.edit(f"Searching {dialog.title}...") except MessageNotModifiedError: pass if use_regex: async for message in e.client.iter_messages(dialog.id, limit=msglimit, reverse=reverse, from_user=from_user, ids=ids): if re.match(pattern, message.text): if not matches.get(dialog.title): matches.update({dialog.title: {}}) matches[dialog.title].update(message) else: async for message in e.client.iter_messages(dialog.id, limit=msglimit, reverse=reverse, from_user=from_user, ids=ids, search=pattern): if not matches.get(dialog.title): matches.update({dialog.title: []}) print(message.text + "\n") matches[dialog.title].append(message) print(matches) message = "**Search results** \n" for chat in matches.keys(): message += f" **{chat}** \n" for msg in matches[chat]: message += f" [{msg.post_author}](tg://user?id={msg.from_id}) \n" message += f" {msg.text}" message += '\n' await e.edit(message)
async def color_props(e): params = e.pattern_match.group(1) or "" args, color = parse_arguments(params, ['format', 'extended']) reply_message = await e.get_reply_message() if not color: await e.edit("Please provide a color...", delete_in=3) return if args.get('format') == 'rgb': r, g, b = re.findall(r'[\-.0-9]+', color) parsed = spectra.rgb(r, g, b) elif args.get('format') == 'lab': l, a, b = re.findall(r'[\-.0-9]+', color) parsed = spectra.lab(l, a, b) elif args.get('format') == 'lch': l, c, h = re.findall(r'[\-.0-9]+', color) parsed = spectra.lch(l, c, h) elif args.get('format') == 'hsl': h, s, l = re.findall(r'[\-.0-9]+', color) parsed = spectra.hsl(h, s, l) elif args.get('format') == 'hsv': h, s, v = re.findall(r'[\-.0-9]+', color) parsed = spectra.hsv(h, s, v) elif args.get('format') == 'xyz': x, y, z = re.findall(r'[\-.0-9]+', color) parsed = spectra.xyz(x, y, z) elif args.get('format') == 'cmy': c, m, y = re.findall(r'[\-.0-9]+', color) parsed = spectra.cmy(c, m, y) elif args.get('format') == 'cmyk': c, m, y, k = re.findall(r'[\-.0-9]+', color) parsed = spectra.cmyk(c, m, y, k) else: parsed = spectra.html(color) rgb = [round(x * 255) for x in parsed.to('rgb').clamped_rgb] hsl = parsed.to('hsl').values hsv = parsed.to('hsv').values formats = { 'hex': parsed.hexcode, 'rgb': values__to_str(rgb), 'hsl': values__to_str(hsl), 'hsv': values__to_str(hsv) } if args.get('extended'): formats.update({ 'lab': values__to_str(parsed.to('lab').values), 'lch': values__to_str(parsed.to('lch').values), 'xyz': values__to_str(parsed.to('xyz').values), 'cmyk': values__to_str(parsed.to('cmyk').values) }) message = "" for fmt in formats.items(): message += f"**{fmt[0]}**: `{fmt[1]}` \n" swatch = make_swatch(tuple(rgb)) await e.delete() await e.client.send_file(e.chat_id, swatch, caption=message, reply_to=reply_message)
async def download_video(v_url): """ For .ytdl command, download videos from YouTube. """ query = v_url.pattern_match.group(1) opts, url = parse_arguments(query, ['res']) quality = opts.get('res', None) await v_url.edit("**Fetching...**") video = YouTube(url) if quality: video_stream = video.streams.filter(progressive=True, subtype="mp4", res=quality).first() else: video_stream = video.streams.filter(progressive=True, subtype="mp4").first() if video_stream is None: all_streams = video.streams.filter(progressive=True, subtype="mp4").all() available_qualities = "" for item in all_streams[:-1]: available_qualities += f"{item.resolution}, " available_qualities += all_streams[-1].resolution await v_url.edit("**A stream matching your query wasn't found. " "Try again with different options.\n**" "**Available Qualities:**\n" f"{available_qualities}") return video_size = video_stream.filesize / 1000000 if video_size >= 50: await v_url.edit( ("**File larger than 50MB. Sending the link instead.\n**" f"Get the video [here]({video_stream.url})\n\n" "**If the video plays instead of downloading, " "right click(or long press on touchscreen) and " "press 'Save Video As...'(may depend on the browser) " "to download the video.**")) return await v_url.edit("**Downloading...**") video_stream.download(filename=video.title) url = f"https://img.youtube.com/vi/{video.video_id}/maxresdefault.jpg" resp = get(url) with open('thumbnail.jpg', 'wb') as file: file.write(resp.content) await v_url.edit("**Uploading...**") await bot.send_file(v_url.chat_id, f'{safe_filename(video.title)}.mp4', caption=f"{video.title}", thumb="thumbnail.jpg") os.remove(f"{safe_filename(video.title)}.mp4") os.remove('thumbnail.jpg') await v_url.delete()
async def text_to_speech(e): """ For .tts command, a wrapper for Google Text-to-Speech. """ textx = await e.get_reply_message() message = e.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await e.edit("`Give a text or reply to a " "message for Text-to-Speech!`") return opts, message = parse_arguments(message, ['slow', 'fast', 'lang', 'gender', 'file']) lang = opts.get('lang', DEFAULT_LANG) voice = opts.get('voice', DEFAULT_VOICE) gender = GENDERS.get(opts.get('gender', "neutral"), SsmlVoiceGender.NEUTRAL) if opts.get('slow'): speed = 0.5 elif opts.get('fast'): speed = 2.0 else: speed = 1.0 synthesis_input = tts.types.SynthesisInput(text=message) voice = tts.types.VoiceSelectionParams(name=voice, language_code=lang, ssml_gender=gender) audio_config = tts.types.AudioConfig( audio_encoding=tts.enums.AudioEncoding.MP3, speaking_rate=speed) try: response = TTSClient.synthesize_speech(synthesis_input, voice, audio_config) except AssertionError: await e.edit('The text is empty.\n' 'Nothing left to speak after pre-precessing, ' 'tokenizing and cleaning.') return except ValueError as err: await e.edit('Language is not supported.') return except RuntimeError: await e.edit('Error loading the languages dictionary.') return await e.delete() with open("k.mp3", "wb") as file: file.write(response.audio_content) audio = MP3("k.mp3") await e.client.send_file( e.chat_id, "k.mp3", reply_to=textx, attributes=[ DocumentAttributeAudio(voice=True, waveform=bytes(response.audio_content), duration=int(audio.info.length)) ]) if BOTLOG: await e.client.send_message( BOTLOG_CHATID, "tts of `" + message + "` executed successfully!")