diff --git a/requirements.txt b/requirements.txt index 961573218..65ed4cf6e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -42,3 +42,4 @@ urbandict==0.5 wget wikipedia youtube_dl>=2020.09.20 +covid diff --git a/userge/plugins/fun/kang.py b/userge/plugins/fun/kang.py index 5aab2cebe..92c0fb1ea 100644 --- a/userge/plugins/fun/kang.py +++ b/userge/plugins/fun/kang.py @@ -11,36 +11,27 @@ import io import os import random - -import aiohttp import emoji + from PIL import Image -from pyrogram.errors import YouBlockedUser from pyrogram.raw.functions.messages import GetStickerSet from pyrogram.raw.types import InputStickerSetShortName +from pyrogram.errors import YouBlockedUser, StickersetInvalid -from userge import Config, Message, userge +from userge import userge, Message, Config @userge.on_cmd( - "kang", - about={ - "header": "kangs stickers or creates new ones", - "flags": {"-s": "without link", "-d": "without trace"}, - "usage": "Reply {tr}kang [emoji('s)] [pack number] to a sticker or " - "an image to kang it to your userbot pack.", - "examples": [ - "{tr}kang", - "{tr}kang -s", - "{tr}kang -d", - "{tr}kang ๐Ÿค”", - "{tr}kang 2", - "{tr}kang ๐Ÿค” 2", - ], - }, - allow_channels=False, - allow_via_bot=False, -) + "kang", about={ + 'header': "kangs stickers or creates new ones", + 'flags': { + '-s': "without link", + '-d': "without trace"}, + 'usage': "Reply {tr}kang [emoji('s)] [pack number] to a sticker or " + "an image to kang it to your userbot pack.", + 'examples': ["{tr}kang", "{tr}kang -s", "{tr}kang -d", + "{tr}kang ๐Ÿค”", "{tr}kang 2", "{tr}kang ๐Ÿค” 2"]}, + allow_channels=False, allow_via_bot=False) async def kang_(message: Message): """ kang a sticker """ user = await userge.get_me() @@ -62,13 +53,14 @@ async def kang_(message: Message): return emoji_ = replied.sticker.emoji is_anim = replied.sticker.is_animated - if not replied.sticker.file_name.endswith(".tgs"): + if not replied.sticker.file_name.endswith('.tgs'): resize = True else: await message.edit("`Unsupported File!`") return await message.edit(f"`{random.choice(KANGING_STR)}`") - photo = await userge.download_media(message=replied, file_name=Config.DOWN_PATH) + photo = await userge.download_media(message=replied, + file_name=Config.DOWN_PATH) else: await message.edit("`I can't kang that...`") return @@ -89,29 +81,34 @@ async def kang_(message: Message): emoji_ = "๐Ÿค”" u_name = user.username - u_name = "@" + u_name if u_name else user.first_name or user.id + if u_name: + u_name = "@" + u_name + else: + u_name = user.first_name or user.id packname = f"a{user.id}_by_userge_{pack}" custom_packnick = Config.CUSTOM_PACK_NAME or f"{u_name}'s kang pack" packnick = f"{custom_packnick} Vol.{pack}" - cmd = "/newpack" + cmd = '/newpack' if resize: photo = resize_photo(photo) if is_anim: packname += "_anim" packnick += " (Animated)" - cmd = "/newanimated" - async with aiohttp.ClientSession() as ses: - async with ses.get(f"http://t.me/addstickers/{packname}") as res: - htmlstr = (await res.text()).split("\n") - if ( - " A Telegram user has created " - "the Sticker Set." - ) not in htmlstr: - async with userge.conversation("Stickers", limit=30) as conv: + cmd = '/newanimated' + exist = False + try: + exist = await message.client.send( + GetStickerSet( + stickerset=InputStickerSetShortName( + short_name=packname))) + except StickersetInvalid: + pass + if exist is not False: + async with userge.conversation('Stickers', limit=30) as conv: try: - await conv.send_message("/addsticker") + await conv.send_message('/addsticker') except YouBlockedUser: - await message.edit("first **unblock** @Stickers") + await message.edit('first **unblock** @Stickers') return await conv.get_response(mark_read=True) await conv.send_message(packname) @@ -124,11 +121,8 @@ async def kang_(message: Message): if is_anim: packname += "_anim" packnick += " (Animated)" - await message.edit( - "`Switching to Pack " - + str(pack) - + " due to insufficient space`" - ) + await message.edit("`Switching to Pack " + str(pack) + + " due to insufficient space`") await conv.send_message(packname) msg = await conv.get_response(mark_read=True) if msg.text == "Invalid pack selected.": @@ -143,43 +137,36 @@ async def kang_(message: Message): await conv.send_message("/publish") if is_anim: await conv.get_response(mark_read=True) - await conv.send_message(f"<{packnick}>") + await conv.send_message(f"<{packnick}>", parse_mode=None) await conv.get_response(mark_read=True) await conv.send_message("/skip") await conv.get_response(mark_read=True) await conv.send_message(packname) await conv.get_response(mark_read=True) - if "-d" in message.flags: + if '-d' in message.flags: await message.delete() else: - out = ( - "__kanged__" - if "-s" in message.flags - else f"[kanged](t.me/addstickers/{packname})" - ) - await message.edit( - f"**Sticker** {out} __in a Different Pack__**!**" - ) + out = "__kanged__" if '-s' in message.flags else \ + f"[kanged](t.me/addstickers/{packname})" + await message.edit(f"**Sticker** {out} __in a Different Pack__**!**") return await conv.send_document(photo) rsp = await conv.get_response(mark_read=True) if "Sorry, the file type is invalid." in rsp.text: - await message.edit( - "`Failed to add sticker, use` @Stickers " - "`bot to add the sticker manually.`" - ) + await message.edit("`Failed to add sticker, use` @Stickers " + "`bot to add the sticker manually.`") return await conv.send_message(emoji_) await conv.get_response(mark_read=True) - await conv.send_message("/done") + await conv.send_message('/done') await conv.get_response(mark_read=True) else: await message.edit("`Brewing a new Pack...`") - async with userge.conversation("Stickers") as conv: + async with userge.conversation('Stickers') as conv: try: await conv.send_message(cmd) except YouBlockedUser: - await message.edit("first **unblock** @Stickers") + await message.edit('first **unblock** @Stickers') return await conv.get_response(mark_read=True) await conv.send_message(packnick) @@ -187,42 +174,33 @@ async def kang_(message: Message): await conv.send_document(photo) rsp = await conv.get_response(mark_read=True) if "Sorry, the file type is invalid." in rsp.text: - await message.edit( - "`Failed to add sticker, use` @Stickers " - "`bot to add the sticker manually.`" - ) + await message.edit("`Failed to add sticker, use` @Stickers " + "`bot to add the sticker manually.`") return await conv.send_message(emoji_) await conv.get_response(mark_read=True) await conv.send_message("/publish") if is_anim: await conv.get_response(mark_read=True) - await conv.send_message(f"<{packnick}>") + await conv.send_message(f"<{packnick}>", parse_mode=None) await conv.get_response(mark_read=True) await conv.send_message("/skip") await conv.get_response(mark_read=True) await conv.send_message(packname) await conv.get_response(mark_read=True) - if "-d" in message.flags: + if '-d' in message.flags: await message.delete() else: - out = ( - "__kanged__" - if "-s" in message.flags - else f"[kanged](t.me/addstickers/{packname})" - ) + out = "__kanged__" if '-s' in message.flags else \ + f"[kanged](t.me/addstickers/{packname})" await message.edit(f"**Sticker** {out}**!**") if os.path.exists(str(photo)): os.remove(photo) -@userge.on_cmd( - "stkrinfo", - about={ - "header": "get sticker pack info", - "usage": "reply {tr}stkrinfo to any sticker", - }, -) +@userge.on_cmd("stkrinfo", about={ + 'header': "get sticker pack info", + 'usage': "reply {tr}stkrinfo to any sticker"}) async def sticker_pack_info_(message: Message): """ get sticker pack info """ replied = message.reply_to_message @@ -235,23 +213,20 @@ async def sticker_pack_info_(message: Message): await message.edit("`Fetching details of the sticker pack, please wait..`") get_stickerset = await message.client.send( GetStickerSet( - stickerset=InputStickerSetShortName(short_name=replied.sticker.set_name) - ) - ) + stickerset=InputStickerSetShortName( + short_name=replied.sticker.set_name))) pack_emojis = [] for document_sticker in get_stickerset.packs: if document_sticker.emoticon not in pack_emojis: pack_emojis.append(document_sticker.emoticon) - out_str = ( - f"**Sticker Title:** `{get_stickerset.set.title}\n`" - f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" - f"**Archived:** `{get_stickerset.set.archived}`\n" - f"**Official:** `{get_stickerset.set.official}`\n" - f"**Masks:** `{get_stickerset.set.masks}`\n" - f"**Animated:** `{get_stickerset.set.animated}`\n" - f"**Stickers In Pack:** `{get_stickerset.set.count}`\n" + out_str = f"**Sticker Title:** `{get_stickerset.set.title}\n`" \ + f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" \ + f"**Archived:** `{get_stickerset.set.archived}`\n" \ + f"**Official:** `{get_stickerset.set.official}`\n" \ + f"**Masks:** `{get_stickerset.set.masks}`\n" \ + f"**Animated:** `{get_stickerset.set.animated}`\n" \ + f"**Stickers In Pack:** `{get_stickerset.set.count}`\n" \ f"**Emojis In Pack:**\n{' '.join(pack_emojis)}" - ) await message.edit(out_str) @@ -260,7 +235,7 @@ def resize_photo(photo: str) -> io.BytesIO: image = Image.open(photo) maxsize = 512 scale = maxsize / max(image.width, image.height) - new_size = (int(image.width * scale), int(image.height * scale)) + new_size = (int(image.width*scale), int(image.height*scale)) image = image.resize(new_size, Image.LANCZOS) resized_photo = io.BytesIO() resized_photo.name = "sticker.png" @@ -279,5 +254,4 @@ def resize_photo(photo: str) -> io.BytesIO: "Ay look over there (โ˜‰๏ฝกโ˜‰)!โ†’\nWhile I kang this...", "Roses are red violets are blue, kanging this sticker so my pacc looks cool", "Imprisoning this sticker...", - "Mr.Steal Your Sticker is stealing this sticker... ", -) + "Mr.Steal Your Sticker is stealing this sticker... ") \ No newline at end of file diff --git a/userge/plugins/utils/covid.py b/userge/plugins/utils/covid.py index 445863b9a..a7da99a61 100644 --- a/userge/plugins/utils/covid.py +++ b/userge/plugins/utils/covid.py @@ -7,85 +7,49 @@ # Author: Sumanjay (https://github.com/cyberboysumanjay) (@cyberboysumanjay) # All rights reserved. -import aiohttp +from covid import Covid -from userge import Message, userge +from userge import userge, Message, pool -@userge.on_cmd( - "covid", - about={ - "header": "see covid details", - "description": "The current real time situation of the COVID-19 patients reported in worldwide", - "usage": "{tr}covid for global\n{tr}covid [country]", - "countries": "Sri Lanka, USA, Spain, Italy, France, Germany, UK, Turkey, Iran', China, " - "Russia, Brazil, Belgium, Canada, Netherlands, Switzerland, India, " - "Portugal, Ecuador, Peru, Ireland, Sweden, Saudi Arabia, Austria, " - "Israel, Japan, Chile, Singapore, Mexico, Pakistan, " - "Poland, S. Korea, Romania, UAE......", - }, -) +@userge.on_cmd("covid", about={ + 'header': "see covid details", + 'description': "The current real time situation of the COVID-19 patients reported in worldwide", + 'flags': {'-l': "list countries"}, + 'usage': "{tr}covid [flag | country]", + 'examples': ["{tr}covid -l", "{tr}covid", "{tr}covid india"]}) async def covid(message: Message): - def fill(nw_c, nw_d, ac_c, cr_c, t_c, t_d, t_r, name, rank): - output_l = f""" - COVID-19 โ˜  Patients Reported in {name} - - ๐Ÿ˜• **New Cases** : `{nw_c}` - ๐Ÿ˜ญ **New Deaths** : `{nw_d}` - - ๐Ÿ˜” **Active Cases** : `{ac_c}` - ๐Ÿ˜ฅ **Critical Cases** : `{cr_c}` - - ๐Ÿ˜” **Total Cases** : `{t_c}` - ๐Ÿ˜ญ **Total Deaths** : `{t_d}` - ๐Ÿ˜ **Total Recovered** : `{t_r}` - - ๐Ÿ˜‡ **Recovery Rate** : `{round((t_r/t_c)*100,2)}` - """ - if rank is not None: - output_l = output_l + f"๐Ÿ›‘ **Danger Rank** : `{rank}`" - return output_l - - input_ = message.input_str.strip().title() - - if len(input_) == 0: + await message.edit("`fetching covid ...`") + covid_ = await pool.run_in_thread(Covid)("worldometers") + country = message.input_str + result = "" + if '-l' in message.flags: + result += "Covid Supported Countries\n\n`" + result += '` , `'.join(sorted((c for c in covid_.list_countries() if c))) + result += "`" + elif country: try: - async with aiohttp.ClientSession() as ses: - async with ses.get("https://sjprojectsapi.herokuapp.com/covid/") as res: - data = await res.json() - global_data = data["results"][0] - nw_c = global_data["total_new_cases_today"] - nw_d = global_data["total_new_deaths_today"] - ac_c = global_data["total_active_cases"] - cr_c = global_data["total_serious_cases"] - t_c = global_data["total_cases"] - t_d = global_data["total_deaths"] - t_r = global_data["total_recovered"] - - output = fill(nw_c, nw_d, ac_c, cr_c, t_c, t_d, t_r, "the world", None) - await message.edit(output, disable_web_page_preview=True) - except Exception: - await message.edit("Covid API is currently down!\nPlease Try Again Later") + data = covid_.get_status_by_country_name(country) + except ValueError: + await message.err(f"invalid country name <{country}>!") + return + result += f"Covid Status for {data['country']}\n\n" + result += f"**new cases** : `{data['new_cases']}`\n" + result += f"**new deaths** : `{data['new_deaths']}`\n\n" + result += f"**critical** : `{data['critical']}`\n" + result += f"**active** : `{data['active']}`\n" + result += f"**confirmed** : `{data['confirmed']}`\n" + result += f"**deaths** : `{data['deaths']}`\n" + result += f"**recovered** : `{data['recovered']}`\n\n" + result += f"**total tests** : `{data['total_tests']}`\n" + result += f"**total tests per million** : `{data['total_tests_per_million']}`\n" + result += f"**total cases per million** : `{data['total_cases_per_million']}`\n" + result += f"**total deaths per million** : `{data['total_deaths_per_million']}`\n" + result += f"**population** : `{data['population']}`\n" else: - try: - async with aiohttp.ClientSession() as ses: - async with ses.get( - "https://sjprojectsapi.herokuapp.com/covid/?country=" + input_ - ) as res: - data = await res.json() - country_data = data["countrydata"][0] - nw_c = country_data["total_new_cases_today"] - nw_d = country_data["total_new_deaths_today"] - ac_c = country_data["total_active_cases"] - cr_c = country_data["total_serious_cases"] - t_c = country_data["total_cases"] - t_d = country_data["total_deaths"] - t_r = country_data["total_recovered"] - rank = country_data["total_danger_rank"] - - output = fill(nw_c, nw_d, ac_c, cr_c, t_c, t_d, t_r, input_, rank) - await message.edit(output, disable_web_page_preview=True) - except Exception: - await message.edit( - "Either the country name is not correct or country is not in our database!" - ) + result += f"Covid Status in the world\n\n" + result += f"**total active cases** : `{covid_.get_total_active_cases()}`\n" + result += f"**total confirmed cases** : `{covid_.get_total_confirmed_cases()}`\n" + result += f"**total deaths** : `{covid_.get_total_deaths()}`\n" + result += f"**total recovered** : `{covid_.get_total_recovered()}`\n" + await message.edit_or_send_as_file(result) \ No newline at end of file diff --git a/userge/plugins/utils/currency.py b/userge/plugins/utils/currency.py index e1888cd82..200b43939 100644 --- a/userge/plugins/utils/currency.py +++ b/userge/plugins/utils/currency.py @@ -6,22 +6,21 @@ # # All rights reserved. -import aiohttp +import json from emoji import get_emoji_regexp -from userge import Config, Message, userge +import aiohttp + +from userge import userge, Message, Config CHANNEL = userge.getCLogger(__name__) +LOG = userge.getLogger(__name__) -@userge.on_cmd( - "cr", - about={ - "header": "use this to convert currency & get exchange rate", - "description": "Convert currency & get exchange rates.", - "examples": "{tr}cr 1 BTC USD", - }, -) +@userge.on_cmd("cr", about={ + 'header': "use this to convert currency & get exchange rate", + 'description': "Convert currency & get exchange rates.", + 'examples': "{tr}cr 1 BTC USD"}) async def cur_conv(message: Message): """ this function can get exchange rate results @@ -32,12 +31,10 @@ async def cur_conv(message: Message): "HERE " "& add it to Heroku config vars (CURRENCY_API)", disable_web_page_preview=True, - parse_mode="html", - del_in=0, - ) + parse_mode="html", del_in=0) return - filterinput = get_emoji_regexp().sub("", message.input_str) + filterinput = get_emoji_regexp().sub(u'', message.input_str) curcon = filterinput.upper().split() if len(curcon) == 3: @@ -48,23 +45,24 @@ async def cur_conv(message: Message): if amount.isdigit(): async with aiohttp.ClientSession() as ses: - async with ses.get( - "https://free.currconv.com/api/v7/convert?" - f"apiKey={Config.CURRENCY_API}&q=" - f"{currency_from}_{currency_to}&compact=ultra" - ) as res: - data = await res.json() - result = data[f"{currency_from}_{currency_to}"] + async with ses.get("https://free.currconv.com/api/v7/convert?" + f"apiKey={Config.CURRENCY_API}&q=" + f"{currency_from}_{currency_to}&compact=ultra") as res: + data = json.loads(await res.text()) + try: + result = data[f'{currency_from}_{currency_to}'] + except KeyError: + LOG.info(data) + await message.err("invalid response from api !") + return result = float(amount) / float(result) result = round(result, 5) await message.edit( "**CURRENCY EXCHANGE RATE RESULT:**\n\n" - f"`{amount}` **{currency_to}** = `{result}` **{currency_from}**" - ) + f"`{amount}` **{currency_to}** = `{result}` **{currency_from}**") await CHANNEL.log("`cr` command executed sucessfully") else: await message.edit( r"`This seems to be some alien currency, which I can't convert right now.. (โŠ™_โŠ™;)`", - del_in=0, - ) + del_in=0) \ No newline at end of file diff --git a/userge/plugins/utils/filters.py b/userge/plugins/utils/filters.py index f26b33539..53056293c 100644 --- a/userge/plugins/utils/filters.py +++ b/userge/plugins/utils/filters.py @@ -11,43 +11,21 @@ import asyncio from typing import Dict -from userge import Message, filters, get_collection, userge +from userge import userge, Message, filters, get_collection FILTERS_COLLECTION = get_collection("filters") CHANNEL = userge.getCLogger(__name__) FILTERS_DATA: Dict[int, Dict[str, int]] = {} -FILTERS_CHATS = filters.create( - lambda _, __, query: query.chat and query.chat.id in FILTERS_DATA -) - -_SUPPORTED_TYPES = ( - ":audio:", - ":video:", - ":photo:", - ":document:", - ":sticker:", - ":animation:", - ":voice:", - ":video_note:", - ":media:", - ":game:", - ":contact:", - ":location:", - ":venue:", - ":web_page:", - ":poll:", - ":via_bot:", - ":forward_date:", - ":mentioned:", - ":service:", - ":media_group_id:", - ":game_high_score:", - ":pinned_message:", - ":new_chat_title:", - ":new_chat_photo:", - ":delete_chat_photo:", -) +FILTERS_CHATS = filters.create(lambda _, __, query: query.chat and query.chat.id in FILTERS_DATA) + +_SUPPORTED_TYPES = (":audio:", ":video:", ":photo:", ":document:", + ":sticker:", ":animation:", ":voice:", ":video_note:", + ":media:", ":game:", ":contact:", ":location:", + ":venue:", ":web_page:", ":poll:", ":via_bot:", + ":forward_date:", ":mentioned:", ":service:", + ":media_group_id:", ":game_high_score:", ":pinned_message:", + ":new_chat_title:", ":new_chat_photo:", ":delete_chat_photo:") def _filter_updater(chat_id: int, name: str, message_id: int) -> None: @@ -65,7 +43,7 @@ def _filter_deleter(chat_id: int, name: str) -> None: def _get_filters_for_chat(chat_id: int) -> str: - out = "" + out = '' if chat_id in FILTERS_DATA: for name, mid in FILTERS_DATA[chat_id].items(): if not isinstance(mid, int): @@ -76,29 +54,25 @@ def _get_filters_for_chat(chat_id: int) -> str: async def _init() -> None: async for flt in FILTERS_COLLECTION.find(): - if "mid" not in flt: + if 'mid' not in flt: continue - _filter_updater(flt["chat_id"], flt["name"], flt["mid"]) + _filter_updater(flt['chat_id'], flt['name'], flt['mid']) @userge.on_cmd( - "filters", - about={ - "header": "List all saved filters in current chat", - "flags": {"-all": "List all saved filters in every chats"}, - }, - allow_channels=False, - allow_bots=False, -) + "filters", about={ + 'header': "List all saved filters in current chat", + 'flags': {'-all': "List all saved filters in every chats"}}, + allow_channels=False, allow_bots=False) async def filters_active(message: Message) -> None: """ list filters in current chat """ - out = "" - if "-all" in message.flags: + out = '' + if '-all' in message.flags: await message.edit("`getting filters ...`") for chat_id in FILTERS_DATA: out += f"**{(await message.client.get_chat(chat_id)).title}**\n" out += _get_filters_for_chat(chat_id) - out += "\n" + out += '\n' if out: out = "**--Filters saved in every chats:--**\n\n" + out else: @@ -112,34 +86,27 @@ async def filters_active(message: Message) -> None: @userge.on_cmd( - "delfilter", - about={ - "header": "Deletes a filter by name", - "flags": { - "-all": "remove all filters in this chat", - "-every": "remove all filters in every chats", - }, - "usage": "{tr}delfilter [filter name | filter type]\n{tr}delfilter -all", - }, - allow_channels=False, - allow_bots=False, -) + "delfilter", about={ + 'header': "Deletes a filter by name", + 'flags': { + '-all': "remove all filters in this chat", + '-every': "remove all filters in every chats"}, + 'usage': "{tr}delfilter [filter name | filter type]\n{tr}delfilter -all"}, + allow_channels=False, allow_bots=False) async def delete_filters(message: Message) -> None: """ delete filter in current chat """ - if "-every" in message.flags: + if '-every' in message.flags: FILTERS_DATA.clear() await asyncio.gather( FILTERS_COLLECTION.drop(), - message.edit("`Cleared All Filters in Every Chat !`", del_in=5), - ) + message.edit("`Cleared All Filters in Every Chat !`", del_in=5)) return - if "-all" in message.flags: + if '-all' in message.flags: if message.chat.id in FILTERS_DATA: del FILTERS_DATA[message.chat.id] await asyncio.gather( - FILTERS_COLLECTION.delete_many({"chat_id": message.chat.id}), - message.edit("`Cleared All Filters in This Chat !`", del_in=5), - ) + FILTERS_COLLECTION.delete_many({'chat_id': message.chat.id}), + message.edit("`Cleared All Filters in This Chat !`", del_in=5)) else: await message.err("Couldn't find filters in this chat!") return @@ -147,8 +114,7 @@ async def delete_filters(message: Message) -> None: if not filter_: out = "`Wrong syntax`\nNo arguements" elif await FILTERS_COLLECTION.find_one_and_delete( - {"chat_id": message.chat.id, "name": filter_} - ): + {'chat_id': message.chat.id, 'name': filter_}): out = "`Successfully deleted filter:` **{}**".format(filter_) _filter_deleter(message.chat.id, filter_) else: @@ -157,27 +123,22 @@ async def delete_filters(message: Message) -> None: @userge.on_cmd( - r"addfilter ([^\s\|][^\|]*)(?:\s?\|\s?([\s\S]+))?", - about={ - "header": "Adds a filter by name", - "options": { - "{fname}": "add first name", - "{lname}": "add last name", - "{flname}": "add full name", - "{uname}": "username", - "{chat}": "chat name", - "{count}": "chat members count", - "{mention}": "mention user", - }, - "usage": "{tr}addfilter [filter name | filter type] | [content | reply to msg]", - "types": list(_SUPPORTED_TYPES), - "buttons": "[name][buttonurl:link] - add a url button\n" - "[name][buttonurl:link:same] - " - "add a url button to same row", - }, - allow_channels=False, - allow_bots=False, -) + r"addfilter ([^\s\|][^\|]*)(?:\s?\|\s?([\s\S]+))?", about={ + 'header': "Adds a filter by name", + 'options': { + '{fname}': "add first name", + '{lname}': "add last name", + '{flname}': "add full name", + '{uname}': "username", + '{chat}': "chat name", + '{count}': "chat members count", + '{mention}': "mention user"}, + 'usage': "{tr}addfilter [filter name | filter type] | [content | reply to msg]", + 'types': list(_SUPPORTED_TYPES), + 'buttons': "[name][buttonurl:link] - add a url button\n" + "[name][buttonurl:link:same] - " + "add a url button to same row"}, + allow_channels=False, allow_bots=False) async def add_filter(message: Message) -> None: """ add filter to current chat """ filter_ = message.matches[0].group(1).strip() @@ -188,26 +149,21 @@ async def add_filter(message: Message) -> None: if not (content or (replied and replied.media)): await message.err("No Content Found !") return - if ( - filter_.startswith(":") - and filter_.endswith(":") - and filter_ not in _SUPPORTED_TYPES - ): + if (filter_.startswith(':') and filter_.endswith(':') + and filter_ not in _SUPPORTED_TYPES): await message.err(f"invalid media type [ {filter_} ] !") return await message.edit("`adding filter ...`") message_id = await CHANNEL.store(replied, content) _filter_updater(message.chat.id, filter_, message_id) result = await FILTERS_COLLECTION.update_one( - {"chat_id": message.chat.id, "name": filter_}, - {"$set": {"mid": message_id}}, - upsert=True, - ) + {'chat_id': message.chat.id, 'name': filter_}, + {"$set": {'mid': message_id}}, upsert=True) out = "`{} filter -> {}`" if result.upserted_id: - out = out.format("Added", filter_) + out = out.format('Added', filter_) else: - out = out.format("Updated", filter_) + out = out.format('Updated', filter_) await message.edit(text=out, del_in=3, log=__name__) @@ -219,26 +175,23 @@ async def chat_filter(message: Message) -> None: try: for name in FILTERS_DATA[message.chat.id]: reply = False - if name.startswith(":") and name.endswith(":"): - media_type = name.strip(":") + if name.startswith(':') and name.endswith(':'): + media_type = name.strip(':') if getattr(message, media_type, None): reply = True elif message.text: - input_text = message.text.strip() - if ( - input_text == name - or input_text.startswith(f"{name} ") - or input_text.endswith(f" {name}") - or f" {name} " in input_text - ): + l_name = name.lower() + input_text = message.text.strip().lower() + if (input_text == l_name + or input_text.startswith(f"{l_name} ") + or input_text.endswith(f" {l_name}") + or f" {l_name} " in input_text): reply = True if reply: - await CHANNEL.forward_stored( - client=message.client, - message_id=FILTERS_DATA[message.chat.id][name], - chat_id=message.chat.id, - user_id=message.from_user.id, - reply_to_message_id=message.message_id, - ) + await CHANNEL.forward_stored(client=message.client, + message_id=FILTERS_DATA[message.chat.id][name], + chat_id=message.chat.id, + user_id=message.from_user.id, + reply_to_message_id=message.message_id) except RuntimeError: - pass + pass \ No newline at end of file diff --git a/userge/plugins/utils/translate.py b/userge/plugins/utils/translate.py index ae739c1e0..32c48bb53 100644 --- a/userge/plugins/utils/translate.py +++ b/userge/plugins/utils/translate.py @@ -6,60 +6,65 @@ # # All rights reserved. +import time from json import dumps - from emoji import get_emoji_regexp -from googletrans import LANGUAGES, Translator -from userge import Config, Message, userge +from googletrans import Translator, LANGUAGES + +from userge import userge, Message, Config, pool -@userge.on_cmd( - "tr", - about={ - "header": "Translate the given text using Google Translate", - "supported languages": dumps(LANGUAGES, indent=4, sort_keys=True), - "usage": "from english to sinhala\n" - "{tr}tr -en -si i am userge\n\n" - "from auto detected language to sinhala\n" - "{tr}tr -si i am userge\n\n" - "from auto detected language to preferred\n" - "{tr}tr i am userge\n\n" - "reply to message you want to translate from english to sinhala\n" - "{tr}tr -en -si\n\n" - "reply to message you want to translate from auto detected language to sinhala\n" - "{tr}tr -si\n\n" - "reply to message you want to translate from auto detected language to preferred\n" - "{tr}tr", - }, - del_pre=True, -) +@userge.on_cmd("tr", about={ + 'header': "Translate the given text using Google Translate", + 'supported languages': dumps(LANGUAGES, indent=4, sort_keys=True), + 'usage': "from english to sinhala\n" + "{tr}tr -en -si i am userge\n\n" + "from auto detected language to sinhala\n" + "{tr}tr -si i am userge\n\n" + "from auto detected language to preferred\n" + "{tr}tr i am userge\n\n" + "reply to message you want to translate from english to sinhala\n" + "{tr}tr -en -si\n\n" + "reply to message you want to translate from auto detected language to sinhala\n" + "{tr}tr -si\n\n" + "reply to message you want to translate from auto detected language to preferred\n" + "{tr}tr"}, del_pre=True) async def translateme(message: Message): - translator = Translator() text = message.filtered_input_str flags = message.flags if message.reply_to_message: text = message.reply_to_message.text or message.reply_to_message.caption if not text: await message.err( - text="Give a text or reply to a message to translate!\nuse `.help tr`" - ) + text="Give a text or reply to a message to translate!\nuse `.help tr`") return if len(flags) == 2: src, dest = list(flags) elif len(flags) == 1: - src, dest = "auto", list(flags)[0] + src, dest = 'auto', list(flags)[0] else: - src, dest = "auto", Config.LANG - text = get_emoji_regexp().sub("", text) - await message.edit("Translating...") + src, dest = 'auto', Config.LANG + text = get_emoji_regexp().sub(u'', text) + await message.edit("`Translating ...`") try: - reply_text = translator.translate(text, dest=dest, src=src) + reply_text = await _translate_this(text, dest, src) except ValueError: await message.err(text="Invalid destination language.\nuse `.help tr`") return - source_lan = LANGUAGES[f"{reply_text.src.lower()}"] - transl_lan = LANGUAGES[f"{reply_text.dest.lower()}"] + source_lan = LANGUAGES[f'{reply_text.src.lower()}'] + transl_lan = LANGUAGES[f'{reply_text.dest.lower()}'] output = f"**Source ({source_lan.title()}):**`\n{text}`\n\n\ **Translation ({transl_lan.title()}):**\n`{reply_text.text}`" await message.edit_or_send_as_file(text=output, caption="translated") + + +@pool.run_in_thread +def _translate_this(text: str, dest: str, src: str): + for i in range(10): + try: + return Translator().translate(text, dest=dest, src=src) + except AttributeError: + if i == 9: + raise + time.sleep(0.3) \ No newline at end of file