Add separate text/markdown reply mode, add help, fix some commands

This commit is contained in:
octospacc 2023-11-18 01:27:42 +01:00
parent aeb981629e
commit 88d33da92c
11 changed files with 95 additions and 79 deletions

1
.gitignore vendored Normal file → Executable file
View File

@ -1,4 +1,3 @@
StartWinDog
Database.json Database.json
Dump.txt Dump.txt
/Config.py /Config.py

0
.gitlab-ci.yml Normal file → Executable file
View File

0
LICENSE.md Normal file → Executable file
View File

38
LibWinDog/Config.py Normal file → Executable file
View File

@ -6,11 +6,11 @@
MastodonUrl = '' MastodonUrl = ''
MastodonToken = '' MastodonToken = ''
TGID = 1637713483 TelegramId = 1637713483
TGToken = '' TelegramToken = ''
TGAdmins = [ 123456789, ] TelegramAdmins = [ 123456789, ]
TGWhitelist = [ 123456789, ] TelegramWhitelist = [ 123456789, ]
TGRestrict = False TelegramRestrict = False
DefaultLang = 'en' DefaultLang = 'en'
Debug = False Debug = False
@ -19,3 +19,31 @@ CmdPrefixes = '.!/'
# False: ASCII output; True: ANSI Output (must be escaped) # False: ASCII output; True: ANSI Output (must be escaped)
ExecAllowed = {'date': False, 'fortune': False, 'neofetch': True, 'uptime': False} ExecAllowed = {'date': False, 'fortune': False, 'neofetch': True, 'uptime': False}
WebUserAgent = f'WinDog v.Staging' WebUserAgent = f'WinDog v.Staging'
Endpoints = {
"start": cStart,
"help": cHelp,
#"config": cConfig,
"source": cSource,
"ping": cPing,
"echo": cEcho,
#"repeat": cRepeat,
"wish": percenter,
"level": percenter,
#"hug": multifun,
#"pat": multifun,
#"poke": multifun,
#"cuddle": multifun,
#"floor": multifun,
#"hands": multifun,
#"sessocto": multifun,
"hash": cHash,
"eval": cEval,
"exec": cExec,
#"format": cFormat,
#"frame": cFrame,
"web": cWeb,
"translate": cTranslate,
"unsplash": cUnsplash,
"safebooru": cSafebooru,
}

0
Locale/en.json Normal file → Executable file
View File

0
Locale/it.json Normal file → Executable file
View File

59
ModWinDog/Mods.py Normal file → Executable file
View File

@ -21,7 +21,7 @@ def multifun(update:Update, context:CallbackContext) -> None:
ReplyToMsg = update.message.message_id ReplyToMsg = update.message.message_id
if update.message.reply_to_message: if update.message.reply_to_message:
ReplyFromUID = update.message.reply_to_message.from_user.id ReplyFromUID = update.message.reply_to_message.from_user.id
if ReplyFromUID == TGID and 'bot' in Locale.__(Key): if ReplyFromUID == TelegramId and 'bot' in Locale.__(Key):
Text = CharEscape(choice(Locale.__(f'{Key}.bot')), 'MARKDOWN_SPEECH') Text = CharEscape(choice(Locale.__(f'{Key}.bot')), 'MARKDOWN_SPEECH')
elif ReplyFromUID == update.message.from_user.id and 'self' in Locale.__(Key): elif ReplyFromUID == update.message.from_user.id and 'self' in Locale.__(Key):
FromUName = CharEscape(update.message.from_user.first_name, 'MARKDOWN') FromUName = CharEscape(update.message.from_user.first_name, 'MARKDOWN')
@ -54,12 +54,16 @@ def cStart(Context, Data=None) -> None:
# Module: Help # Module: Help
# ... # ...
def cHelp(Context, Data=None) -> None: def cHelp(Context, Data=None) -> None:
SendMsg(Context, {"Text": choice(Locale.__('help'))}) #SendMsg(Context, {"Text": choice(Locale.__('help'))})
Commands = ''
for Cmd in Endpoints.keys():
Commands += f'* /{Cmd}\n'
SendMsg(Context, {"TextPlain": f'Available Endpoints (WIP):\n{Commands}'})
# Module: Source # Module: Source
# Provides a copy of the bot source codes and/or instructions on how to get it. # Provides a copy of the bot source codes and/or instructions on how to get it.
def cSource(Context, Data=None) -> None: def cSource(Context, Data=None) -> None:
pass SendMsg(Context, {"TextPlain": "{https://gitlab.com/octospacc/WinDog}"})
# Module: Config # Module: Config
# ... # ...
@ -93,7 +97,11 @@ def cEcho(Context, Data=None) -> None:
def cHash(Context, Data=None) -> None: def cHash(Context, Data=None) -> None:
if len(Data.Tokens) >= 3 and Data.Tokens[1] in hashlib.algorithms_available: if len(Data.Tokens) >= 3 and Data.Tokens[1] in hashlib.algorithms_available:
Alg = Data.Tokens[1] Alg = Data.Tokens[1]
SendMsg(Context, {"Text": hashlib.new(Alg, Alg.join(Data.Body.split(Alg)[1:]).strip().encode()).hexdigest()}) Hash = hashlib.new(Alg, Alg.join(Data.Body.split(Alg)[1:]).strip().encode()).hexdigest()
SendMsg(Context, {
"TextPlain": Hash,
"TextMarkdown": MarkdownCode(Hash, True),
})
else: else:
SendMsg(Context, {"Text": choice(Locale.__('hash.usage')).format(Data.Tokens[0], hashlib.algorithms_available)}) SendMsg(Context, {"Text": choice(Locale.__('hash.usage')).format(Data.Tokens[0], hashlib.algorithms_available)})
@ -104,20 +112,18 @@ def cEval(Context, Data=None) -> None:
# Module: Exec # Module: Exec
# Execute a system command and return stdout/stderr. # Execute a system command and return stdout/stderr.
def cExec(update:Update, context:CallbackContext) -> None: def cExec(Context, Data=None) -> None:
Cmd = HandleCmd(update) if len(Data.Tokens) >= 2 and Data.Tokens[1].lower() in ExecAllowed:
if not Cmd: return Cmd = Data.Tokens[1].lower()
Toks = Cmd.Tokens
if len(Cmd.Tokens) >= 2 and Cmd.Tokens[1].lower() in ExecAllowed:
Cmd = Toks[1].lower()
Out = subprocess.run(('sh', '-c', f'export PATH=$PATH:/usr/games; {Cmd}'), stdout=subprocess.PIPE).stdout.decode() Out = subprocess.run(('sh', '-c', f'export PATH=$PATH:/usr/games; {Cmd}'), stdout=subprocess.PIPE).stdout.decode()
# <https://stackoverflow.com/a/14693789> # <https://stackoverflow.com/a/14693789>
Caption = (re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', Out)) #if ExecAllowed[Cmd] else Out) Caption = (re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', Out))
update.message.reply_markdown_v2(MarkdownCode(Caption, True), reply_to_message_id=update.message.message_id) SendMsg(Context, {
"TextPlain": Caption,
"TextMarkdown": MarkdownCode(Caption, True),
})
else: else:
update.message.reply_markdown_v2( SendMsg(Context, {"Text": choice(Locale.__('eval'))})
CharEscape(choice(Locale.__('eval')), 'MARKDOWN_SPEECH'),
reply_to_message_id=update.message.message_id)
# Module: Format # Module: Format
# Reformat text using an handful of rules # Reformat text using an handful of rules
@ -131,22 +137,20 @@ def cFrame(Context, Data=None) -> None:
# Module: Web # Module: Web
# Provides results of a DuckDuckGo search. # Provides results of a DuckDuckGo search.
# 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'🦆🔎 "*{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 = 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 = HtmlUnescape(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] Caption += f'[{Index}] {Title} : {{{Link}}}\n\n'
Caption += f'{Index}&period; *{HtmlEscapeFull(Title)}*: {Link} &#91;`{Domain}`&#93;\n\n' SendMsg(Context, {"TextPlain": f'{Caption}...'})
SendMsg(Context, {"Text": f'{Caption}...'})
except Exception: except Exception:
raise raise
else: else:
@ -160,7 +164,7 @@ def cTranslate(Context, Data=None) -> None:
Lang = Data.Tokens[1] Lang = Data.Tokens[1]
# TODO: Use many different public Lingva instances in rotation to avoid overloading a specific one # 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"] 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}) SendMsg(Context, {"TextPlain": Result})
except Exception: except Exception:
raise raise
else: else:
@ -171,7 +175,12 @@ def cTranslate(Context, Data=None) -> None:
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)}')
SendMsg(Context, {"Text": MarkdownCode(Req.geturl().split('?')[0], True), "Media": Req.read()}) ImgUrl = Req.geturl().split('?')[0]
SendMsg(Context, {
"TextPlain": f'{{{ImgUrl}}}',
"TextMarkdown": MarkdownCode(ImgUrl, True),
"Media": Req.read(),
})
except Exception: except Exception:
raise raise
@ -198,7 +207,11 @@ def cSafebooru(Context, Data=None) -> None:
ImgId = ImgUrl.split('?')[-1] ImgId = ImgUrl.split('?')[-1]
break break
if ImgUrl: if ImgUrl:
SendMsg(Context, {"Text": (f'`{ImgId}`\n' + MarkdownCode(ImgUrl, True)), "Media": HttpGet(ImgUrl).read()}) SendMsg(Context, {
"TextPlain": f'[{ImgId}]\n{{{ImgUrl}}}',
"TextMarkdown": f'\\[`{ImgId}`\\]\n{MarkdownCode(ImgUrl, True)}',
"Media": HttpGet(ImgUrl).read(),
})
else: else:
pass pass
except Exception: except Exception:

View File

@ -1,7 +0,0 @@
#!/bin/bash
ScriptPath=$(realpath $0)
ScriptDir=$(dirname $ScriptPath)
cd $ScriptDir
python3 WinDog.py

3
StartWinDog.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
cd "$( dirname "$( realpath "$0" )" )"
python3 ./WinDog.py

View File

@ -28,40 +28,13 @@ MdEscapes = '\\`*_{}[]()<>#+-.!|='
Db = {"Chats": {}} Db = {"Chats": {}}
Locale = {"Fallback": {}} Locale = {"Fallback": {}}
for Dir in ('Lib', 'Mod'): for Dir in ('Mod', 'Lib'):
for File in listdir(f'./{Dir}WinDog'): for File in listdir(f'./{Dir}WinDog'):
File = f'./{Dir}WinDog/{File}' File = f'./{Dir}WinDog/{File}'
if isfile(File): if isfile(File):
with open(File, 'r') as File: with open(File, 'r') as File:
exec(File.read()) exec(File.read())
Endpoints = {
"start": cStart,
"help": cHelp,
#"config": cConfig,
"source": cSource,
"ping": cPing,
"echo": cEcho,
"wish": percenter,
"level": percenter,
#"hug": multifun,
#"pat": multifun,
#"poke": multifun,
#"cuddle": multifun,
#"floor": multifun,
#"hands": multifun,
#"sessocto": multifun,
"hash": cHash,
"eval": cEval,
#"exec": cExec,
"format": cFormat,
"frame": cFrame,
"web": cWeb,
"translate": cTranslate,
"unsplash": cUnsplash,
"safebooru": cSafebooru,
}
def SetupLocale() -> None: def SetupLocale() -> None:
global Locale global Locale
for File in listdir('./Locale'): for File in listdir('./Locale'):
@ -142,11 +115,11 @@ def HtmlEscapeFull(Raw:str) -> str:
return New return New
def CmdAllowed(update) -> bool: def CmdAllowed(update) -> bool:
if not TGRestrict: if not TelegramRestrict:
return True return True
else: else:
if TGRestrict.lower() == 'whitelist': if TelegramRestrict.lower() == 'whitelist':
if update.message.chat.id in TGWhitelist: if update.message.chat.id in TelegramWhitelist:
return True return True
return False return False
@ -234,15 +207,23 @@ def SendMsg(Context, Data):
Manager = Context['Manager'] if 'Manager' in Context else None Manager = Context['Manager'] if 'Manager' in Context else None
else: else:
[Event, Manager] = [Context, Context] [Event, Manager] = [Context, Context]
if InDict(Data, 'Text'):
if InDict(Data, 'TextPlain') or InDict(Data, 'TextMarkdown'):
TextPlain = InDict(Data, 'TextPlain')
TextMarkdown = InDict(Data, 'TextMarkdown')
if not TextPlain:
TextPlain = TextMarkdown
elif InDict(Data, 'Text'):
# our old system attemps to always receive Markdown and retransform when needed
TextPlain = MdToTxt(Data['Text']) TextPlain = MdToTxt(Data['Text'])
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'], Magic(mime=True).from_buffer(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 TextPlain:
Manager.status_post( Manager.status_post(
status=(TextPlain + '\n\n@' + Event['account']['acct']), status=(TextPlain + '\n\n@' + Event['account']['acct']),
media_ids=(Media if InDict(Data, 'Media') else None), media_ids=(Media if InDict(Data, 'Media') else None),
@ -253,15 +234,14 @@ 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 InDict(Data, 'Text') else None), caption=(TextMarkdown if TextMarkdown else TextPlain if TextPlain else None),
parse_mode='MarkdownV2', parse_mode=('MarkdownV2' if TextMarkdown else None),
reply_to_message_id=Event.message.message_id,
)
elif InDict(Data, 'Text'):
Event.message.reply_markdown_v2(
TextMarkdown,
reply_to_message_id=Event.message.message_id, reply_to_message_id=Event.message.message_id,
) )
elif TextMarkdown:
Event.message.reply_markdown_v2(TextMarkdown, reply_to_message_id=Event.message.message_id)
elif TextPlain:
Event.message.reply_text(TextPlain,reply_to_message_id=Event.message.message_id)
def Main() -> None: def Main() -> None:
SetupDb() SetupDb()
@ -269,12 +249,12 @@ def Main() -> None:
#Private['Chats'].update({update.message.chat.id:{}}) #Private['Chats'].update({update.message.chat.id:{}})
updater = Updater(TGToken) updater = Updater(TelegramToken)
dispatcher = updater.dispatcher dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('config', cConfig)) dispatcher.add_handler(CommandHandler('config', cConfig))
#dispatcher.add_handler(CommandHandler('time', cTime)) #dispatcher.add_handler(CommandHandler('time', cTime))
dispatcher.add_handler(CommandHandler('exec', cExec)) #dispatcher.add_handler(CommandHandler('repeat', cRepeat))
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))

2
requirements.txt Normal file → Executable file
View File

@ -10,4 +10,4 @@ beautifulsoup4
Markdown Markdown
# Telegram support # Telegram support
python-telegram-bot python-telegram-bot==13.4.1