def format_weather_response(weather_res): try: logger.info(f"request to format {weather_res}") temp_in_celcius = weather_res['main']['temp'] - 273.15 humidity = weather_res['main']['humidity'] pressure = weather_res['main']['pressure'] sky = weather_res['weather'][0]['description'] city = weather_res['name'] country = weather_res['sys']['country'] wind = weather_res['wind']['speed'] if 'rain' in weather_res: rain = weather_res['rain']['1h'] else: rain = 0 cloud_coverage = weather_res['clouds']['all'] # print("\n\n", re.findall("", pattern_string)) return f""" Temp in `{city},{country}` is `{temp_in_celcius:.2f}°C`, {sky} Humidity `{humidity}`% Pressure `{pressure}` Pa Wind `{wind}` meter/sec `{rain}` cm rain in last 1 hour `{cloud_coverage}`% Cloud coverage """ except KeyError as e: logger.exception(f"Error in formatting {e}") pass except Exception as e: print("Error", weather_res) logger.exception(f"Error in formatting {e}")
async def messages(event): logger.info("called messages plugin") pattern_string = event.pattern_match.string message = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] logger.info(f"message to send {message}") await event.respond(messages_mapper[message])
async def sendQute(event): logger.info("quotes plugin called") quotes_api_url = "https://opinionated-quotes-api.gigalixirapp.com/v1/quotes" data = requests.get(quotes_api_url).json() quote = data['quotes'][0]['quote'] author = data['quotes'][0]['author'] await event.reply(f'`{quote}`\n - __{author}__')
async def omnifn(event): logger.info("omni plugin called") appid = environ.get("wolfram_appid", None) if not appid: await event.respond("no appid provided") return pattern_string = event.pattern_match.string query_string = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] if not query_string: await event.respond("please provide (a query to search)") query_params = query_string.replace(" ", "+") url = f"https://api.wolframalpha.com/v2/query?input={query_params}" res = requests.get(url, { "format": "plaintext", "output": "JSON", "appid": appid }) res_json = res.json() pods = res_json['queryresult']['pods'] result_pod = '' for o in pods: if o['title'] == "Result": result_pod = o # print(result_pod) await event.respond(result_pod['subpods'][0]['plaintext'])
async def clean(event): logger.info("cleanup plugin called") pattern_string = event.pattern_match.string limit = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] id = await event.get_input_chat() logger.info(f"deleting {limit} messages from {id}") m = await bot.get_messages(id, limit=int(limit)) await bot.delete_messages(id, m) await event.respond("cleanup done")
async def generate(event): logger.info("generator plugin called") category = event.pattern_match.string.split(" ")[1] if not category: logger.info("No category found to generate") return url = urls[category] if category == "word": res = requests.get(url) soup = BeautifulSoup(res.text, 'html.parser') word = soup.find(id="definition-word").text definition = soup.find(id="definition-definition").text example = soup.find(id="definition-example").text await event.respond(f"""**{word}**\n{definition}\n\n__{example}__""", parse_mode="md") elif category == "waifu": fullurl = f"""{url}example-{randint(1, 99999)}.jpg""" await event.respond(file=fullurl) elif category == "art": fullurl = f"""{url}?random={random()}""" try: await event.respond(file=types.InputMediaPhotoExternal(fullurl)) except Exception as ex: print("Error Occurred", ex) await event.respond("Error") elif category == "cat": fullurl = f"{url}?random={random()}" await event.respond(file=types.InputMediaPhotoExternal(fullurl)) elif category == "person": fullurl = f"{url}?random={random()}" await event.respond(file=types.InputMediaPhotoExternal(fullurl)) # Doesn't work # elif category == "lyrics": # # print(event.pattern_match.string) # try: # mood = event.pattern_match.string.split(" ")[2] # genre = event.pattern_match.string.split(" ")[3] # message = event.pattern_match.string.split(" ")[4] # res = requests.post(url, data={"lyricMood": mood, "lyricsGenre": genre, "message": message}, headers={ # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36", # "Origin": "https://theselyricsdonotexist.com"}) # print(res) # await event.respond("Done") # except Exception as ex: # print("Error Occurred", ex) # await event.respond("Error") else: await event.respond("Cannot generate selected entity")
async def memes(event): logger.info("meme plugin is called") await event.delete() pattern_string = event.pattern_match.string meme_name = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] logger.info(f"file to send {file_path_mapping.get(meme_name)}") file_to_send = file_path_mapping.get(meme_name) if meme_name == "help": await event.respond(open(file_to_send).read(), reply_to=event.reply_to_msg_id) else: try: await event.respond("", reply_to=event.reply_to_msg_id, file=file_to_send) except Exception: await event.respond("No U")
async def getWeather(event): logger.info("weather plugin called") pattern_string = event.pattern_match.string city_to_find = pattern_string[pattern_string.find("(")+1:pattern_string.find(")")] logger.info(f"city to find - {city_to_find}") openweather_url = "https://api.openweathermap.org/data/2.5/weather" openweather_api_key = environ.get("openweather_api_key", None) params = { "q" : city_to_find, "appid": openweather_api_key } res = requests.get(openweather_url, params=params).json() temp_in_celcius = res['main']['temp'] - 273.15 humidity = res['main']['humidity'] pressure = res['main']['pressure'] sky = res['weather'][0]['description'] city = res['name'] country = res['sys']['country'] # print("\n\n", re.findall("", pattern_string)) await event.respond(f"Temp in `{city},{country}` is `{temp_in_celcius:.2f}°C`, {sky}\nHumidity `{humidity}`%\nPressure `{pressure}` Pa")
async def getUser(event): logger.info("user plugin is called") pattern_string = event.pattern_match.string entity = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] logger.info(f"entity to search - {entity}") try: info = await bot(GetFullUserRequest(entity)) await event.respond(f""" Username - `{info.user.username}` {"User is a bot" if info.user.bot else "user is not a bot"} {"User is restricted for " + info.user.restriction_reason if info.user.restricted else "User is not restricted"} Name - {info.user.first_name} {info.user.last_name if info.user.last_name else ""} Status - `{info.about}` id - {info.user.id} {info.common_chats_count} groups common with me {"I have blocked this user" if info.blocked else "I have not blocked this user"} """) except Exception: await event.respond(f"Cannot find entity with `{entity}`")
async def id(event): logger.info("group info plugin called") try: id = event.message.to_id.channel_id logger.info(f"sending group id - {id}") await event.respond(f"groupid - {id}") except AttributeError: id = event.message.to_id.user_id logger.info("sending user id - {id}") await event.respond(f"userid - {id}")
async def server(event): logger.info("server plugin called") pattern_string = event.pattern_match.string command = pattern_string[pattern_string.find("(")+1:pattern_string.find(")")] logger.info(f"command to execute - {command}") parametrize = command.split(" ") pipe = subprocess.check_output(parametrize, stderr=subprocess.PIPE) message = pipe.decode('utf-8') if command in allowed_commands: logger.info("command is in allowed_commands") await event.respond(f"```{message}```")
async def anim(event): logger.info("anim plugin called") matched = parse(event.pattern_match.string) before = matched[0] after = matched[1] logger.info(f"before string - {before}") logger.info(f"after string - {after}") if before and after: try: reply_to_user = event.message.to_id.user_id except AttributeError: reply_to_user = event.message.to_id.channel_id sent = await event.respond(after, reply_to=event.reply_to_msg_id) logger.info(f"replying to {sent.id}") for i in range(0, 2): await bot.edit_message(reply_to_user, sent.id, before) await sleep(0.5) await bot.edit_message(reply_to_user, sent.id, after) await sleep(0.5)
async def fn(event): logger.info("group info plugin called") try: id = event.message.to_id.channel_id logger.info(f"sending group id - {id}") await event.respond(f"groupid - {id}") except AttributeError: id = event.message.to_id.user_id logger.info(f"sending user id - {id}") await event.respond(f"userid - {id}") except Exception as e: logger.exception(f"Error while fetching records {e}") return
async def get_weather(event): logger.info("weather plugin called") query = event.pattern_match.string.split(" ") logger.info(f"weather query - {query}") city_to_find = query[1] try: is_forecast = query[2] or None except IndexError: is_forecast = None # print(is_forecast) logger.info(f"city to find - {city_to_find}") # Prepare request openweather_api_key = environ.get("openweather_api_key", None) params = {"q": city_to_find, "appid": openweather_api_key} if is_forecast is None: logger.info(f"Sending current weather info") openweather_url = "https://api.openweathermap.org/data/2.5/weather" weather_res = get_response(openweather_url, params) tg_response = format_weather_response(weather_res) await event.respond(tg_response)
async def wall(event): logger.info("Wallpaper plugin called") try: category = event.pattern_match.string.split(" ")[1] except IndexError: return await event.respond( f"select a category:```\ntoplist\nrandom\nhot\nlatest```") url = f"https://wallhaven.cc/{category}" try: tonsfw = '010' if event.pattern_match.string.split( " ")[2] == "nsfw" else "000" except IndexError: tonsfw = '000' try: # 120 is the limit of max pages res = requests.get(url, { "page": randint(2, 40), "purity": tonsfw }, headers=USER_AGENT) logger.info(f"url generated {res.url}") soup = BeautifulSoup(res.text, 'html.parser') try: page = soup.find("section", {"class": "thumb-listing-page"}) ls = page.findChildren("li") selectedls = choice(ls) thumbinfo = selectedls.findChild("div", {"class": "thumb-info"}) imageid = selectedls.findChild().get("data-wallpaper-id") url = f"https://w.wallhaven.cc/full/{imageid[:2]}/wallhaven-{imageid}." isPng = thumbinfo.findChild("span", {"class": "png"}, recursive=True) if isPng is None: url = url + "jpg" else: url = url + "png" logger.info(f"url is {url}") await event.respond(file=types.InputMediaPhotoExternal(url)) except Exception as e: await event.respond( f"Error occurred while sending, please try once again if file is too large\n here's full url to download manually{url}" ) logger.exception(e) pass except Exception as e: logger.exception(e)
async def myname(event): logger.info("waiting plugin called") await animated_response(event)
async def google(event): logger.info("google plugin called") pattern_string = event.pattern_match.string query_string = pattern_string[pattern_string.find("(") + 1:pattern_string.find(")")] logger.info(f"query string to search {query_string}") query_params = query_string.replace(" ", "+") res = requests.get('https://www.google.com/search', {"q": query_params}, headers=USER_AGENT) soup = BeautifulSoup(res.text, 'html.parser') # first try to find div tag with attribute data-tts and data-tts-text try: tts_text = soup.findAll("div", { "data-tts": True, "data-tts-text": True }) # there should be only one element present: try: msg = tts_text[0].text await event.respond(msg) logger.info("found record with attribute type tts_text") return # don't execute this method further except IndexError as e: pass # that means try another method: attr_kc_text = soup.findAll( "div", {"data-attrid": re.compile(r"^kc:/\w+/\w+:\w+")}) # if there's any such tag if attr_kc_text: # it's probably in the second child of div tag with this attribute: try: msg = attr_kc_text[0].findChild().findChild( "div", { "role": "heading" }).text await event.respond(msg) logger.info( "found record with attribute type kc:/x/x in second div") return except AttributeError as a: msg = attr_kc_text[0].findChild("div", { "role": "heading" }).findChild().text await event.respond(msg) logger.info( "found record with attribute type kc:/x/x in first div") return # don't execute this method further # else search for another attribute type attr_hc_text = soup.findAll( "div", {"data-attrid": re.compile(r"^hw:/\w+/\w+:\w+")}) # if it's present if attr_hc_text: # same logic msg = attr_hc_text[0].findChild().findChild().text await event.respond(msg) logger.info( "found record with attribute type hw:/x/x in second div") return # don't execute this method further # Well, everything up above failed, try another methods: # Let's see if it's a time-related card rso = soup.find(id="rso") card = rso.findChildren("div", {"class": "card-section"}, recursive=True) try: time = card[0].findChild().text await event.respond(time) logger.info("found record as time card") return except Exception: pass # it's not a time card either except Exception: logger.info("couldn't find anything") await event.respond( "can't find anything on that, please report this query to Spark")
async def help(event): logger.info("help plugin called") commands = open("./plugins/data/commands").read() await event.respond(commands)
async def myname(event): logger.info("myname plugin is called") if event.is_group: logger.info(f"incoming message is {event.raw_text.lower()}") group_id = event.message.to_id.channel_id await bot.forward_messages('me', event.message.id, group_id)
async def fn(event): logger.info("tag plugin is called") await event.delete() await event.respond(event.raw_text, reply_to=event.reply_to_msg_id)
from userbot import bot from plugins import All_PLUGINS import importlib from userbot import logger for plugin in All_PLUGINS: logger.info("importing " + plugin) importlib.import_module("plugins." + plugin) logger.info("All plugins loaded, starting bot") bot.start() logger.info("bot started") bot.run_until_disconnected()
async def insult(event): logger.info("insults plugin called") file = open("./plugins/data/insults").readlines() insult = choice(file) logger.info(f"chosen insult - {insult}") await event.respond(insult, reply_to=event.reply_to_msg_id)