funapi / routes /jokes /getJoke.py
imperialwool's picture
123
6d79162
raw
history blame
3.21 kB
import re
from .. import helpers
from . import getSources
from random import randint
from requests import get as reqget
from random import choice as randchoice
def getJoke(request):
lang = helpers.getFromRequest(request, "lang")
if not lang: return {"status": "error", "details": { "error_code": 133, "error_details": "No lang provided" }}, 400
elif lang.lower() not in ['ru']: return {"status": "error", "details": { "error_code": 133, "error_details": "Lang not supported" }}, 400
else: lang = lang.lower()
source = helpers.getFromRequest(request, "source")
availableSources = getSources.getSources(None)
if not source or source not in availableSources[lang]: source = randchoice(availableSources[lang])
try:
if source == "nekdo":
site = reqget("https://nekdo.ru/random/").text
joke = randchoice(re.findall('<div class=\"text\"(.*)</div>', site)).replace('</div>', '').replace('</a>', '').replace('<br>', '\n')
joke = re.sub('(<a href="/(\S*)/">| id="(\d*)">)','', joke).strip()
elif source == "baneks":
site = reqget("https://baneks.ru/random").text
joke = site.partition('<p>')[2].partition('</p>')[0].replace('<br />', '').strip()
elif source == "anekdot":
links = ["https://www.anekdot.ru/random/anekdot/", "https://www.anekdot.ru/random/story/", "https://www.anekdot.ru/random/aphorism/"]
site = reqget(randchoice(links)).text
joke = site.partition('<div class=\"text\">')[2].partition('</div>')[0].replace('<br>', '\n').strip()
elif source == "shytok":
site = reqget("https://shytok.net/sluchainye-anekdoty.html").text
joke = site.partition('<div class="text2">')[2].partition('<div class="star">')[0].partition('<br>')[2].replace('</div>', '').replace('<br>', '').replace('<br />', '\n').strip()
elif source == "anekdotytoday":
site = reqget(f"https://anekdotytoday.net/poisk/getanekdot_poisk.php?teg=new&fteg={randint(0,4952)}").text
joke = site.partition('<p>')[2].partition('</p>')[0].replace('<br/>', '').strip()
elif source == "4tob":
site = reqget("https://4tob.ru/anekdots/{}".format(randint(1,3628))).content
joke = site.decode().partition('<div class="text">')[2].partition("</div>")[0].replace("<br>", "\n").replace("<br />", "\n").replace("<p>", "").replace("</p>", "").strip()
elif source == "anepedia":
site = reqget("https://www.anepedia.mobi/%D0%A1%D0%BB%D1%83%D1%87%D0%B0%D0%B9%D0%BD%D1%8B%D0%B9_%D0%B0%D0%BD%D0%B5%D0%BA%D0%B4%D0%BE%D1%82").content.decode()
joke = re.sub(r'<a\b[^>]*>', '', site.partition('<div align="left" class="bodytext">')[2].partition("<img src")[0]).replace("</a>", "").replace("<br />", "\n").replace("<br/>", "\n").replace("<br>", "\n").strip()
else: return {"status": "error", "details": { "error_code": 133, "error_details": "Invalid source" }}, 400
return {"status": "pass", "details": {"code": 200, "result": joke, "source": source}}
except Exception as e:
return {"status": "error", "details": {"error_code": 500, "error_details": str(e)}}, 500