Add Copilot image scraping, update and fix telegram async, improve shared API

This commit is contained in:
2024-06-19 01:40:33 +02:00
parent 09cf925850
commit 4c403e516b
21 changed files with 386 additions and 98 deletions

11
LibWinDog/Platforms/Mastodon/Mastodon.py Normal file → Executable file
View File

@ -3,6 +3,13 @@
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
""" # windog config start #
# MastodonUrl = "https://mastodon.example.com"
# MastodonToken = ""
# end windog config # """
MastodonUrl, MastodonToken = None, None
import mastodon
@ -15,7 +22,7 @@ def MastodonMain() -> bool:
class MastodonListener(mastodon.StreamListener):
def on_notification(self, event):
if event['type'] == 'mention':
OnMessageReceived()
#OnMessageParsed()
message = BeautifulSoup(event['status']['content'], 'html.parser').get_text(' ').strip().replace('\t', ' ')
if not message.split('@')[0]:
message = ' '.join('@'.join(message.split('@')[1:]).strip().split(' ')[1:]).strip()
@ -24,7 +31,7 @@ def MastodonMain() -> bool:
if command:
command.messageId = event['status']['id']
if command.Name in Endpoints:
Endpoints[command.Name]({"Event": event, "Manager": Mastodon}, command)
Endpoints[command.Name]["handler"]({"Event": event, "Manager": Mastodon}, command)
Mastodon.stream_user(MastodonListener(), run_async=True)
return True

0
LibWinDog/Platforms/Mastodon/requirements.txt Normal file → Executable file
View File

14
LibWinDog/Platforms/Matrix/Matrix.py Normal file → Executable file
View File

@ -3,6 +3,14 @@
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
""" # windog config start #
# MatrixUrl = "https://matrix.example.com"
# MatrixUsername = "username"
# MatrixPassword = "hunter2"
# end windog config # """
MatrixUrl, MatrixUsername, MatrixPassword = None, None, None
import nio
@ -19,12 +27,10 @@ def MatrixMain() -> bool:
pass
#print(message)
#match = MatrixBotLib.MessageMatch(room, message, MatrixBot)
#OnMessageReceived()
#OnMessageParsed()
#if match.is_not_from_this_bot() and match.command("windogtest"):
# pass #await MatrixBot.api.send_text_message(room.room_id, " ".join(arg for arg in match.args()))
def runMatrixBot() -> None:
MatrixBot.run()
Thread(target=runMatrixBot).start()
Thread(target=lambda:MatrixBot.run()).start()
return True
def MatrixSender() -> None:

0
LibWinDog/Platforms/Matrix/requirements.txt Normal file → Executable file
View File

103
LibWinDog/Platforms/Telegram/Telegram.py Normal file → Executable file
View File

@ -3,10 +3,18 @@
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
""" # windog config start #
# TelegramToken = "1234567890:abcdefghijklmnopqrstuvwxyz123456789"
# end windog config # """
TelegramToken = None
import telegram, telegram.ext
from telegram import ForceReply, Bot
from telegram import ForceReply, Bot #, Update
#from telegram.helpers import escape_markdown
#from telegram.ext import Application, filters, CommandHandler, MessageHandler, CallbackContext
from telegram.utils.helpers import escape_markdown
from telegram.ext import CommandHandler, MessageHandler, Filters, CallbackContext
@ -15,20 +23,38 @@ def TelegramMain() -> bool:
return False
updater = telegram.ext.Updater(TelegramToken)
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text | Filters.command, TelegramHandler))
dispatcher.add_handler(MessageHandler(Filters.text | Filters.command, TelegramHandlerWrapper))
updater.start_polling()
#app = Application.builder().token(TelegramToken).build()
#app.add_handler(MessageHandler(filters.TEXT | filters.COMMAND, TelegramHandler))
#app.run_polling(allowed_updates=Update.ALL_TYPES)
return True
def TelegramHandler(update:telegram.Update, context:CallbackContext=None) -> None:
if not (update and update.message):
def TelegramHandlerWrapper(update:telegram.Update, context:CallbackContext=None) -> None:
Thread(target=lambda:TelegramHandlerCore(update, context)).start()
def TelegramHandlerCore(update:telegram.Update, context:CallbackContext=None) -> None:
if not update.message:
return
OnMessageReceived()
data = SimpleNamespace()
data.room_id = f"{update.message.chat.id}@telegram"
data.message_id = f"{update.message.message_id}@telegram"
data.text_plain = update.message.text
data.text_markdown = update.message.text_markdown_v2
data.text_auto = GetWeightedText(data.text_markdown, data.text_plain)
data.command = ParseCommand(data.text_plain)
data.user = SimpleNamespace()
data.user.name = update.message.from_user.first_name
data.user.tag = update.message.from_user.username
data.user.id = f"{update.message.from_user.id}@telegram"
OnMessageParsed(data)
cmd = ParseCmd(update.message.text)
if cmd:
cmd.command = data.command
cmd.messageId = update.message.message_id
cmd.TextPlain = cmd.Body
cmd.TextMarkdown = update.message.text_markdown_v2
cmd.Text = GetWeightedText((cmd.TextMarkdown, cmd.TextPlain))
cmd.Text = GetWeightedText(cmd.TextMarkdown, cmd.TextPlain)
if cmd.Tokens[0][0] in CmdPrefixes and cmd.Name in Endpoints:
cmd.User = SimpleNamespace(**{
"Name": update.message.from_user.first_name,
@ -41,36 +67,57 @@ def TelegramHandler(update:telegram.Update, context:CallbackContext=None) -> Non
"Body": update.message.reply_to_message.text,
"TextPlain": update.message.reply_to_message.text,
"TextMarkdown": update.message.reply_to_message.text_markdown_v2,
"Text": GetWeightedText((update.message.reply_to_message.text_markdown_v2, update.message.reply_to_message.text)),
"Text": GetWeightedText(update.message.reply_to_message.text_markdown_v2, update.message.reply_to_message.text),
"User": SimpleNamespace(**{
"Name": update.message.reply_to_message.from_user.first_name,
"Tag": update.message.reply_to_message.from_user.username,
"Id": f'{update.message.reply_to_message.from_user.id}@telegram',
}),
})
Endpoints[cmd.Name]({"Event": update, "Manager": context}, cmd)
if Debug and Dumper:
Text = update.message.text
Text = (Text.replace('\n', '\\n') if Text else '')
with open('Dump.txt', 'a') as File:
File.write(f'[{time.ctime()}] [{int(time.time())}] [{update.message.chat.id}] [{update.message.message_id}] [{update.message.from_user.id}] {Text}\n')
Endpoints[cmd.Name]["handler"]({"Event": update, "Manager": context}, cmd)
def TelegramSender(event, manager, Data, Destination, TextPlain, TextMarkdown) -> None:
if Destination:
manager.bot.send_message(Destination, text=TextPlain)
def TelegramSender(event, manager, data, destination, textPlain, textMarkdown) -> None:
if destination:
manager.bot.send_message(destination, text=textPlain)
else:
replyToId = (Data["ReplyTo"] if ("ReplyTo" in Data and Data["ReplyTo"]) else event.message.message_id)
if InDict(Data, 'Media'):
event.message.reply_photo(
Data['Media'],
caption=(TextMarkdown if TextMarkdown else TextPlain if TextPlain else None),
parse_mode=('MarkdownV2' if TextMarkdown else None),
reply_to_message_id=replyToId,
)
elif TextMarkdown:
event.message.reply_markdown_v2(TextMarkdown, reply_to_message_id=replyToId)
elif TextPlain:
event.message.reply_text(TextPlain, reply_to_message_id=replyToId)
replyToId = (data["ReplyTo"] if ("ReplyTo" in data and data["ReplyTo"]) else event.message.message_id)
if InDict(data, "Media") and not InDict(data, "media"):
data["media"] = {"bytes": data["Media"]}
if InDict(data, "media"):
#data["media"] = SureArray(data["media"])
#media = (data["media"][0]["bytes"] if "bytes" in data["media"][0] else data["media"][0]["url"])
#if len(data["media"]) > 1:
# media_list = []
# media_list.append(telegram.InputMediaPhoto(
# media[0],
# caption=(textMarkdown if textMarkdown else textPlain if textPlain else None),
# parse_mode=("MarkdownV2" if textMarkdown else None)))
# for medium in media[1:]:
# media_list.append(telegram.InputMediaPhoto(medium))
# event.message.reply_media_group(media_list, reply_to_message_id=replyToId)
#else:
# event.message.reply_photo(
# media,
# caption=(textMarkdown if textMarkdown else textPlain if textPlain else None),
# parse_mode=("MarkdownV2" if textMarkdown else None),
# reply_to_message_id=replyToId)
#event.message.reply_photo(
# (DictGet(media[0], "bytes") or DictGet(media[0], "url")),
# caption=(textMarkdown if textMarkdown else textPlain if textPlain else None),
# parse_mode=("MarkdownV2" if textMarkdown else None),
# reply_to_message_id=replyToId)
#for medium in media[1:]:
# event.message.reply_photo((DictGet(medium, "bytes") or DictGet(medium, "url")), reply_to_message_id=replyToId)
for medium in SureArray(data["media"]):
event.message.reply_photo(
(DictGet(medium, "bytes") or DictGet(medium, "url")),
caption=(textMarkdown if textMarkdown else textPlain if textPlain else None),
parse_mode=("MarkdownV2" if textMarkdown else None),
reply_to_message_id=replyToId)
elif textMarkdown:
event.message.reply_markdown_v2(textMarkdown, reply_to_message_id=replyToId)
elif textPlain:
event.message.reply_text(textPlain, reply_to_message_id=replyToId)
RegisterPlatform(name="Telegram", main=TelegramMain, sender=TelegramSender, eventClass=telegram.Update)

2
LibWinDog/Platforms/Telegram/requirements.txt Normal file → Executable file
View File

@ -1 +1 @@
python-telegram-bot==13.4.1
python-telegram-bot==13.15

0
LibWinDog/Platforms/Web.py Normal file → Executable file
View File