2
0
mirror of https://github.com/Nick80835/microbot synced 2025-08-22 18:19:16 +00:00
microbot/ubot/modules/scrapers.py

269 lines
12 KiB
Python
Raw Normal View History

import io
import re
import pafy
from gtts import gTTS
2020-06-17 14:29:34 -04:00
from PIL import Image
2020-07-26 09:05:35 -04:00
from ubot.fixes.fast_telethon import upload_file
2020-09-13 13:50:36 -04:00
from ubot import ldr
2020-07-21 09:44:28 -04:00
@ldr.add("dadjoke", help="Fetches the most funny shit you've ever read.")
async def dadjoke(event):
async with ldr.aioclient.get("https://icanhazdadjoke.com/", headers={"Accept": "application/json"}) as response:
if response.status == 200:
dad_joke = (await response.json())["joke"]
else:
2020-06-17 16:55:50 -04:00
await event.reply(f"An error occurred: **{response.status}**")
return
await event.reply(dad_joke)
2020-07-21 09:44:28 -04:00
@ldr.add("fact", help="Fetches random facts.")
async def randomfact(event):
async with ldr.aioclient.get("https://uselessfacts.jsph.pl/random.json", params={"language": "en"}) as response:
if response.status == 200:
random_fact = (await response.json())["text"].replace("`", "'")
else:
2020-06-17 16:55:50 -04:00
await event.reply(f"An error occurred: **{response.status}**")
return
await event.reply(random_fact)
2020-07-21 09:44:28 -04:00
@ldr.add("fakeword", help="Fetches random fake words.")
2020-07-19 17:07:30 -04:00
async def fakeword(event):
async with ldr.aioclient.get("https://www.thisworddoesnotexist.com/api/random_word.json") as response:
if response.status == 200:
random_word_json = (await response.json())["word"]
word = random_word_json["word"]
definition = random_word_json["definition"]
example = random_word_json["example"]
else:
await event.reply(f"An error occurred: **{response.status}**")
return
await event.reply(f"**{word}:** __{definition}__\n\n**Example:** __{example}__")
2020-07-21 09:44:28 -04:00
@ldr.add("pokemon", pattern_extra="(s|)", help="Fetches Pokemon sprites, requires a name or ID as an argument.")
2020-06-17 14:29:34 -04:00
async def pokemon_image(event):
if not event.args:
await event.reply("Specify a Pokémon name!")
return
async with ldr.aioclient.get("https://pokeapi.co/api/v2/pokemon/" + event.args) as response:
if response.status == 200:
sprite_url = (await response.json())["sprites"]["front_shiny" if event.other_args[0] else "front_default"]
2020-06-17 14:29:34 -04:00
else:
2020-06-17 16:55:50 -04:00
await event.reply(f"An error occurred: **{response.status}**")
2020-06-17 14:29:34 -04:00
return
2020-06-17 20:52:05 -04:00
if not sprite_url:
await event.reply("That Pokémon config doesnt have an available sprite!")
return
2020-06-17 14:29:34 -04:00
async with ldr.aioclient.get(sprite_url) as response:
if response.status == 200:
sprite_io = await response.read()
else:
2020-06-17 16:55:50 -04:00
await event.reply(f"An error occurred: **{response.status}**")
2020-06-17 14:29:34 -04:00
return
await event.reply(file=await ldr.run_async(pokemon_image_sync, sprite_io))
def pokemon_image_sync(sprite_io):
2020-06-17 14:29:34 -04:00
sticker_image = Image.open(io.BytesIO(sprite_io))
2020-06-17 14:42:11 -04:00
sticker_image = sticker_image.crop(sticker_image.getbbox())
final_width = 512
final_height = 512
if sticker_image.width > sticker_image.height:
final_height = 512 * (sticker_image.height / sticker_image.width)
elif sticker_image.width < sticker_image.height:
final_width = 512 * (sticker_image.width / sticker_image.height)
sticker_image = sticker_image.resize((int(final_width), int(final_height)), Image.NEAREST)
2020-06-17 14:29:34 -04:00
sticker_io = io.BytesIO()
sticker_image.save(sticker_io, "WebP", quality=99)
sticker_io.seek(0)
sticker_io.name = "sticker.webp"
return sticker_io
2020-06-17 14:29:34 -04:00
2020-07-21 09:44:28 -04:00
@ldr.add("tts", help="Text to speech.")
async def text_to_speech(event):
text, reply = await event.get_text(return_msg=True)
if not text:
await event.reply("Give me text or reply to text to use TTS.")
return
tts_bytesio = io.BytesIO()
tts_bytesio.name = "tts.mp3"
try:
tts = gTTS(text, lang="EN")
tts.write_to_fp(tts_bytesio)
tts_bytesio.seek(0)
except AssertionError:
await event.reply('The text is empty.\nNothing left to speak after pre-precessing, tokenizing and cleaning.')
return
except RuntimeError:
await event.reply('Error loading the languages dictionary.')
return
2020-10-22 11:14:35 -04:00
await event.client.send_file(event.chat, file=tts_bytesio, voice_note=True, reply_to=reply)
2020-07-21 09:44:28 -04:00
@ldr.add("ip", help="IP lookup.")
async def ip_lookup(event):
ip = await event.get_text()
if not ip:
await event.reply("Provide an IP!")
return
async with ldr.aioclient.get(f"http://ip-api.com/json/{ip}") as response:
if response.status == 200:
lookup_json = await response.json()
else:
await event.reply(f"An error occurred when looking for **{ip}**: **{response.status}**")
return
fixed_lookup = {}
for key, value in lookup_json.items():
special = {"lat": "Latitude", "lon": "Longitude", "isp": "ISP", "as": "AS", "asname": "AS name"}
if key in special:
fixed_lookup[special[key]] = str(value)
continue
key = re.sub(r"([a-z])([A-Z])", r"\g<1> \g<2>", key)
key = key.capitalize()
if not value:
value = "None"
fixed_lookup[key] = str(value)
text = ""
for key, value in fixed_lookup.items():
text = text + f"**{key}:** {value}\n"
await event.reply(text)
2020-07-21 09:44:28 -04:00
@ldr.add("corona", help="Fetches Coronavirus stats, takes an optional country name as an argument.")
async def corona(event):
if event.args:
2020-09-12 15:35:37 -04:00
async with ldr.aioclient.get(f"https://disease.sh/v3/covid-19/countries/{event.args}", headers={"accept": "application/json"}) as response:
if response.status == 200:
response = await response.json()
else:
await event.reply(f"An error occurred, response code: **{response.status}**")
return
2020-09-12 15:35:37 -04:00
response_list = [
f"Corona stats for **{response['country']}**\n",
f"**Cases**\n {response['cases']} total\n {response['todayCases']} today\n {response['active']} active\n {round(response['cases'] / response['population'] * 100, 2)}% of population",
2020-09-25 19:30:21 -04:00
f"**Tests**\n {response['tests']} total\n {round(response['cases'] / response['tests'] * 100, 2) if response['tests'] != 0 else 0.0}% positive\n {round(response['tests'] / response['population'] * 100, 2)}% of population",
f"**Deaths**\n {response['deaths']} total\n {response['todayDeaths']} today\n {round(response['deaths'] / response['cases'] * 100, 2) if response['cases'] != 0 else 0.0}% of cases\n {round(response['deaths'] / response['population'] * 100, 2)}% of population",
2020-09-12 15:35:37 -04:00
f"**Recoveries**\n {response['recovered']} total"
]
await event.reply("\n".join(response_list))
else:
2020-09-12 15:35:37 -04:00
async with ldr.aioclient.get("https://disease.sh/v3/covid-19/all", headers={"accept": "application/json"}) as response:
if response.status == 200:
response = await response.json()
else:
await event.reply(f"`An error occurred, response code: `**{response.status}**")
return
2020-09-12 15:35:37 -04:00
response_list = [
2020-10-10 19:38:21 -04:00
"Global Corona stats\n",
2020-09-12 15:35:37 -04:00
f"**Cases**\n {response['cases']} total\n {response['todayCases']} today\n {response['active']} active\n {round(response['cases'] / response['population'] * 100, 2)}% of population",
2020-09-25 19:30:21 -04:00
f"**Tests**\n {response['tests']} total\n {round(response['cases'] / response['tests'] * 100, 2) if response['tests'] != 0 else 0.0}% positive\n {round(response['tests'] / response['population'] * 100, 2)}% of population",
f"**Deaths**\n {response['deaths']} total\n {response['todayDeaths']} today\n {round(response['deaths'] / response['cases'] * 100, 2) if response['cases'] != 0 else 0.0}% of cases\n {round(response['deaths'] / response['population'] * 100, 2)}% of population",
2020-09-12 15:35:37 -04:00
f"**Recoveries**\n {response['recovered']} total"
]
await event.reply("\n".join(response_list))
2020-09-12 16:00:07 -04:00
@ldr.add_inline_article("corona", default="corona")
async def corona_inline(event):
2020-09-12 16:00:07 -04:00
if event.args:
async with ldr.aioclient.get(f"https://disease.sh/v3/covid-19/countries/{event.args}", headers={"accept": "application/json"}) as response:
if response.status == 200:
response = await response.json()
else:
return
response_list = [
f"Corona stats for **{response['country']}**\n",
f"**Cases**\n {response['cases']} total\n {response['todayCases']} today\n {response['active']} active\n {round(response['cases'] / response['population'] * 100, 2)}% of population",
2020-09-25 19:30:21 -04:00
f"**Tests**\n {response['tests']} total\n {round(response['cases'] / response['tests'] * 100, 2) if response['tests'] != 0 else 0.0}% positive\n {round(response['tests'] / response['population'] * 100, 2)}% of population",
f"**Deaths**\n {response['deaths']} total\n {response['todayDeaths']} today\n {round(response['deaths'] / response['cases'] * 100, 2) if response['cases'] != 0 else 0.0}% of cases\n {round(response['deaths'] / response['population'] * 100, 2)}% of population",
2020-09-12 16:00:07 -04:00
f"**Recoveries**\n {response['recovered']} total"
]
2020-10-10 19:38:21 -04:00
return [{"title": "Corona Stats", "description": response['country'], "text": "\n".join(response_list)}]
2020-09-12 16:00:07 -04:00
else:
async with ldr.aioclient.get("https://disease.sh/v3/covid-19/all", headers={"accept": "application/json"}) as response:
if response.status == 200:
response = await response.json()
else:
return
response_list = [
2020-10-10 19:38:21 -04:00
"Global Corona stats\n",
2020-09-12 16:00:07 -04:00
f"**Cases**\n {response['cases']} total\n {response['todayCases']} today\n {response['active']} active\n {round(response['cases'] / response['population'] * 100, 2)}% of population",
2020-09-25 19:30:21 -04:00
f"**Tests**\n {response['tests']} total\n {round(response['cases'] / response['tests'] * 100, 2) if response['tests'] != 0 else 0.0}% positive\n {round(response['tests'] / response['population'] * 100, 2)}% of population",
f"**Deaths**\n {response['deaths']} total\n {response['todayDeaths']} today\n {round(response['deaths'] / response['cases'] * 100, 2) if response['cases'] != 0 else 0.0}% of cases\n {round(response['deaths'] / response['population'] * 100, 2)}% of population",
2020-09-12 16:00:07 -04:00
f"**Recoveries**\n {response['recovered']} total"
]
2020-10-10 19:38:21 -04:00
return [{"title": "Corona Stats", "description": "Global", "text": "\n".join(response_list)}]
2020-09-12 16:00:07 -04:00
@ldr.add("yt", userlocking=True)
async def youtube_cmd(event):
video = pafy.new(event.args)
2020-07-26 11:50:27 -04:00
video_stream = video.getbest(preftype="mp4")
2020-07-23 10:03:34 -04:00
try:
2020-12-22 10:51:59 -05:00
await event.reply(file=video_stream.url)
except:
2020-12-22 10:51:59 -05:00
await event.reply(f"Download failed, the video was probably over 20MB, use other bots for this shit: [URL]({video_stream.url})")
@ldr.add("yta", userlocking=True)
async def youtube_audio_cmd(event):
video = pafy.new(event.args)
2020-09-26 18:28:05 -04:00
audio_stream = video.getbestaudio(preftype="m4a")
try:
2020-09-26 18:28:05 -04:00
async with ldr.aioclient.get(audio_stream.url) as response:
if response.status == 200:
2020-12-22 10:51:59 -05:00
if int(response.headers["content-length"]) >= 20000000:
await event.reply("Fuck off.")
return
2020-09-26 18:28:05 -04:00
audio_data = io.BytesIO(await response.read())
audio_data.name = "audio.m4a"
else:
raise Exception
file_handle = await upload_file(event.client, audio_data)
await event.reply(file=file_handle)
except:
2020-09-26 18:28:05 -04:00
await event.reply(f"Download failed: [URL]({audio_stream.url})")