Try fix /web; Add /translate

This commit is contained in:
octospacc 2023-07-18 01:06:45 +02:00
parent 49c2e23d49
commit bd12ea209e
2 changed files with 23 additions and 12 deletions

View File

@ -106,28 +106,38 @@ def cExec(update:Update, context:CallbackContext) -> None:
CharEscape(choice(Locale.__('eval')), 'MARKDOWN_SPEECH'), CharEscape(choice(Locale.__('eval')), 'MARKDOWN_SPEECH'),
reply_to_message_id=update.message.message_id) reply_to_message_id=update.message.message_id)
# This is now broken with the new infer escape system...
def cWeb(Context, Data=None) -> None: def cWeb(Context, Data=None) -> None:
if Data.Body: if Data.Body:
try: try:
QueryUrl = UrlParse.quote(Data.Body) QueryUrl = UrlParse.quote(Data.Body)
Req = HttpGet(f'https://html.duckduckgo.com/html?q={QueryUrl}') Req = HttpGet(f'https://html.duckduckgo.com/html?q={QueryUrl}')
#Caption = f'[🦆🔎 "*{CharEscape(Data.Body, "MARKDOWN")}*"](https://duckduckgo.com/?q={CharEscape(QueryUrl, "MARKDOWN")})\n\n' #Caption = f'[🦆🔎 "*{CharEscape(Data.Body, "MARKDOWN")}*"](https://duckduckgo.com/?q={CharEscape(QueryUrl, "MARKDOWN")})\n\n'
Caption = '[🦆🔎 "*{Data.Body}*"](https://duckduckgo.com/?q={QueryUrl})\n\n' Caption = f'[🦆🔎 "*{Data.Body}*"](https://duckduckgo.com/?q={QueryUrl})\n\n'
Index = 0 Index = 0
for Line in Req.read().decode().replace('\t', ' ').splitlines(): for Line in Req.read().decode().replace('\t', ' ').splitlines():
if ' class="result__a" ' in Line and ' href="//duckduckgo.com/l/?uddg=' in Line: if ' class="result__a" ' in Line and ' href="//duckduckgo.com/l/?uddg=' in Line:
Index += 1 Index += 1
#Link = CharEscape(UrlParse.unquote(Line.split(' href="//duckduckgo.com/l/?uddg=')[1].split('&rut=')[0]), 'MARKDOWN')
#Title = CharEscape(UrlParse.unquote(Line.split('</a>')[0].split('</span>')[-1].split('>')[1]), 'MARKDOWN')
Link = UrlParse.unquote(Line.split(' href="//duckduckgo.com/l/?uddg=')[1].split('&amp;rut=')[0]) Link = UrlParse.unquote(Line.split(' href="//duckduckgo.com/l/?uddg=')[1].split('&amp;rut=')[0])
Title = UrlParse.unquote(Line.split('</a>')[0].split('</span>')[-1].split('>')[1]) Title = HtmlUnescape(Line.split('</a>')[0].split('</span>')[-1].split('>')[1])
Domain = Link.split('://')[1].split('/')[0] Domain = Link.split('://')[1].split('/')[0]
#Caption += f'{Index}\. [{Title}]({Link}) \[`{Domain}`\]\n\n' Caption += f'{Index}&period; {Title} --- {Link} --- `{Domain}`\n\n'
Caption += f'{Index}. [{Title}]({Link}) [`{Domain}`]\n\n'
SendMsg(Context, {"Text": Caption}) SendMsg(Context, {"Text": Caption})
except Exception: except Exception:
raise raise
def cTranslate(Context, Data=None) -> None:
if Data.Body:
try:
Lang = Data.Tokens[1]
# TODO: Use many different public Lingva instances in rotation to avoid overloading a specific one
Result = json.loads(HttpGet(f'https://lingva.ml/api/v1/auto/{Lang}/{UrlParse.quote(Lang.join(Data.Body.split(Lang)[1:]))}').read())["translation"]
SendMsg(Context, {"Text": Result})
except Exception:
raise
else:
pass
def cUnsplash(Context, Data=None) -> None: def cUnsplash(Context, Data=None) -> None:
try: try:
Req = HttpGet(f'https://source.unsplash.com/random/?{UrlParse.quote(Data.Body)}') Req = HttpGet(f'https://source.unsplash.com/random/?{UrlParse.quote(Data.Body)}')

View File

@ -5,6 +5,7 @@
# ================================== # # ================================== #
import json, hashlib, re, time, subprocess import json, hashlib, re, time, subprocess
from magic import Magic
from os import listdir from os import listdir
from os.path import isfile from os.path import isfile
from random import choice, randint from random import choice, randint
@ -21,7 +22,7 @@ from urllib import parse as UrlParse
from urllib.request import urlopen, Request from urllib.request import urlopen, Request
# <https://daringfireball.net/projects/markdown/syntax#backslash> # <https://daringfireball.net/projects/markdown/syntax#backslash>
MdEscapes = '\\`*_{}[]()<>#=+-.!|' MdEscapes = '\\`*_{}[]()<>#+-.!|='
Db = {"Chats": {}} Db = {"Chats": {}}
Locale = {"Fallback": {}} Locale = {"Fallback": {}}
@ -53,6 +54,7 @@ Endpoints = {
#"eval": cEval, #"eval": cEval,
#"exec": cExec, #"exec": cExec,
"web": cWeb, "web": cWeb,
"translate": cTranslate,
"unsplash": cUnsplash, "unsplash": cUnsplash,
"safebooru": cSafebooru, "safebooru": cSafebooru,
} }
@ -124,7 +126,7 @@ def InferMdEscape(Raw:str, Plain:str) -> str:
return Chs return Chs
def MarkdownCode(Text:str, Block:bool) -> str: def MarkdownCode(Text:str, Block:bool) -> str:
return '```\n' + CharEscape(Text.strip(), 'MARKDOWN') + '\n```' return '```\n' + Text.strip().replace('`', '\`') + '\n```'
def MdToTxt(Md:str) -> str: def MdToTxt(Md:str) -> str:
return BeautifulSoup(markdown(Md), 'html.parser').get_text(' ') return BeautifulSoup(markdown(Md), 'html.parser').get_text(' ')
@ -227,13 +229,13 @@ def SendMsg(Context, Data):
TextMarkdown = CharEscape(HtmlUnescape(Data['Text']), InferMdEscape(HtmlUnescape(Data['Text']), TextPlain)) TextMarkdown = CharEscape(HtmlUnescape(Data['Text']), InferMdEscape(HtmlUnescape(Data['Text']), TextPlain))
if isinstance(Manager, mastodon.Mastodon): if isinstance(Manager, mastodon.Mastodon):
if InDict(Data, 'Media'): if InDict(Data, 'Media'):
Media = Manager.media_post(Data['Media']) Media = Manager.media_post(Data['Media'], Magic(mime=True).from_buffer(Data['Media']))
while Media['url'] == 'null': while Media['url'] == 'null':
Media = Manager.media(Media) Media = Manager.media(Media)
if InDict(Data, 'Text'): if InDict(Data, 'Text'):
Manager.status_post( Manager.status_post(
status=(TextPlain + '\n\n@' + Event['account']['acct']), status=(TextPlain + '\n\n@' + Event['account']['acct']),
media_ids=(Media if Data['Media'] else None), media_ids=(Media if InDict(Data, 'Media') else None),
in_reply_to_id=Event['status']['id'], in_reply_to_id=Event['status']['id'],
visibility=('direct' if Event['status']['visibility'] == 'direct' else 'unlisted'), visibility=('direct' if Event['status']['visibility'] == 'direct' else 'unlisted'),
) )
@ -241,7 +243,7 @@ def SendMsg(Context, Data):
if InDict(Data, 'Media'): if InDict(Data, 'Media'):
Event.message.reply_photo( Event.message.reply_photo(
Data['Media'], Data['Media'],
caption=(TextMarkdown if Data['Text'] else None), caption=(TextMarkdown if InDict(Data, 'Text') else None),
parse_mode='MarkdownV2', parse_mode='MarkdownV2',
reply_to_message_id=Event.message.message_id, reply_to_message_id=Event.message.message_id,
) )
@ -267,7 +269,6 @@ def Main() -> None:
#dispatcher.add_handler(CommandHandler('time', cTime)) #dispatcher.add_handler(CommandHandler('time', cTime))
dispatcher.add_handler(CommandHandler('eval', cEval)) dispatcher.add_handler(CommandHandler('eval', cEval))
dispatcher.add_handler(CommandHandler('exec', cExec)) dispatcher.add_handler(CommandHandler('exec', cExec))
#dispatcher.add_handler(CommandHandler('web', cWeb))
for Cmd in ('hug', 'pat', 'poke', 'cuddle', 'floor', 'hands', 'sessocto'): for Cmd in ('hug', 'pat', 'poke', 'cuddle', 'floor', 'hands', 'sessocto'):
dispatcher.add_handler(CommandHandler(Cmd, multifun)) dispatcher.add_handler(CommandHandler(Cmd, multifun))