Start Matrix support, more refactoring, cleaner /help and /translate

This commit is contained in:
2024-06-17 00:32:03 +02:00
parent d687cbd51e
commit 09cf925850
19 changed files with 236 additions and 189 deletions

View File

@@ -4,16 +4,18 @@
# ================================== #
# If you have modified the bot's code, you should set this
ModifiedSourceUrl = ''
ModifiedSourceUrl = ""
MastodonUrl = ''
MastodonToken = ''
# Only for the platforms you want to use, uncomment the below credentials and fill with your own:
TelegramId = 1637713483
TelegramToken = "0123456789:abcdefghijklmnopqrstuvwxyz123456789"
TelegramAdmins = [ 123456789, 634314973, ]
TelegramWhitelist = [ 123456789, 634314973, ]
TelegramRestrict = False
# MastodonUrl = "https://mastodon.example.com"
# MastodonToken = ""
# MatrixUrl = "https://matrix.example.com"
# MatrixUsername = "username"
# MatrixPassword = "hunter2"
# TelegramToken = "1234567890:abcdefghijklmnopqrstuvwxyz123456789"
AdminIds = [ "123456789@telegram", "634314973@telegram", "admin@activitypub@mastodon.example.com", ]
@@ -25,29 +27,8 @@ CmdPrefixes = ".!/"
ExecAllowed = {"date": False, "fortune": False, "neofetch": True, "uptime": False}
WebUserAgent = "WinDog v.Staging"
# TODO deprecate this in favour of new module API
Endpoints = (Endpoints | {
"start": cStart,
#"config": cConfig,
"source": cSource,
"ping": cPing,
"echo": cEcho,
"broadcast": cBroadcast,
#"repeat": cRepeat,
"wish": percenter,
"level": percenter,
"hug": multifun,
"pat": multifun,
"poke": multifun,
"cuddle": multifun,
"floor": multifun,
"hands": multifun,
"sessocto": multifun,
#"encode": cEncode,
#"decode": cDecode,
#"time": cTime,
"eval": cEval,
"exec": cExec,
#"format": cFormat,
#"frame": cFrame,
ModuleGroups = (ModuleGroups | {
"Basic": "",
"Geek": "",
})

8
LibWinDog/Database.py Normal file
View File

@@ -0,0 +1,8 @@
from peewee import *
Db = SqliteDatabase("Database.sqlite")
class BaseModel(Model):
class Meta:
database = Db

View File

@@ -1,36 +1,45 @@
# ================================== #
# WinDog multi-purpose chatbot #
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
MastodonUrl, MastodonToken = None, None
import mastodon
from bs4 import BeautifulSoup
def MastodonSender(event, manager, Data, Destination, TextPlain, TextMarkdown) -> None:
if InDict(Data, 'Media'):
Media = manager.media_post(Data['Media'], Magic(mime=True).from_buffer(Data['Media']))
while Media['url'] == 'null':
Media = manager.media(Media)
if TextPlain:
manager.status_post(
status=(TextPlain + '\n\n@' + event['account']['acct']),
media_ids=(Media if InDict(Data, 'Media') else None),
in_reply_to_id=event['status']['id'],
visibility=('direct' if event['status']['visibility'] == 'direct' else 'unlisted'),
)
def MastodonMain() -> None:
def MastodonMain() -> bool:
if not (MastodonUrl and MastodonToken):
return
return False
Mastodon = mastodon.Mastodon(api_base_url=MastodonUrl, access_token=MastodonToken)
class MastodonListener(mastodon.StreamListener):
def on_notification(self, event):
if event['type'] == 'mention':
Msg = BeautifulSoup(event['status']['content'], 'html.parser').get_text(' ').strip().replace('\t', ' ')
if not Msg.split('@')[0]:
Msg = ' '.join('@'.join(Msg.split('@')[1:]).strip().split(' ')[1:]).strip()
if Msg[0] in CmdPrefixes:
cmd = ParseCmd(Msg)
if cmd:
cmd.messageId = event['status']['id']
if cmd.Name in Endpoints:
Endpoints[cmd.Name]({"Event": event, "Manager": Mastodon}, cmd)
OnMessageReceived()
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()
if message[0] in CmdPrefixes:
command = ParseCmd(message)
if command:
command.messageId = event['status']['id']
if command.Name in Endpoints:
Endpoints[command.Name]({"Event": event, "Manager": Mastodon}, command)
Mastodon.stream_user(MastodonListener(), run_async=True)
return True
def MastodonSender(event, manager, data, destination, textPlain, textMarkdown) -> None:
if InDict(data, 'Media'):
Media = manager.media_post(data['Media'], Magic(mime=True).from_buffer(data['Media']))
while Media['url'] == 'null':
Media = manager.media(Media)
if textPlain or Media:
manager.status_post(
status=(textPlain + '\n\n@' + event['account']['acct']),
media_ids=(Media if InDict(data, 'Media') else None),
in_reply_to_id=event['status']['id'],
visibility=('direct' if event['status']['visibility'] == 'direct' else 'unlisted'),
)
RegisterPlatform(name="Mastodon", main=MastodonMain, sender=MastodonSender, managerClass=mastodon.Mastodon)

View File

@@ -1,8 +0,0 @@
def MatrixMain() -> None:
pass
def MatrixSender() -> None:
pass
#RegisterPlatform(name="Matrix", main=MatrixMain, sender=MatrixSender)

View File

@@ -0,0 +1,34 @@
# ================================== #
# WinDog multi-purpose chatbot #
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
MatrixUrl, MatrixUsername, MatrixPassword = None, None, None
import nio
import simplematrixbotlib as MatrixBotLib
from threading import Thread
def MatrixMain() -> bool:
if not (MatrixUrl and MatrixUsername and MatrixPassword):
return False
MatrixBot = MatrixBotLib.Bot(MatrixBotLib.Creds(MatrixUrl, MatrixUsername, MatrixPassword))
@MatrixBot.listener.on_message_event
@MatrixBot.listener.on_custom_event(nio.events.room_events.RoomMessageFile)
async def MatrixMessageListener(room, message) -> None:
pass
#print(message)
#match = MatrixBotLib.MessageMatch(room, message, MatrixBot)
#OnMessageReceived()
#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()
return True
def MatrixSender() -> None:
pass
#RegisterPlatform(name="Matrix", main=MatrixMain, sender=MatrixSender)

View File

@@ -0,0 +1 @@
simplematrixbotlib

View File

@@ -1,26 +1,28 @@
# ================================== #
# WinDog multi-purpose chatbot #
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
TelegramToken = None
import telegram, telegram.ext
from telegram import ForceReply, Bot
from telegram.utils.helpers import escape_markdown
from telegram.ext import CommandHandler, MessageHandler, Filters, CallbackContext
def TelegramCmdAllowed(update:telegram.Update) -> bool:
if not TelegramRestrict:
return True
if TelegramRestrict.lower() == 'whitelist':
if update.message.chat.id in TelegramWhitelist:
return True
return False
def TelegramHandleCmd(update:telegram.Update):
TelegramQueryHandle(update)
if TelegramCmdAllowed(update):
return ParseCmd(update.message.text)
else:
def TelegramMain() -> bool:
if not TelegramToken:
return False
updater = telegram.ext.Updater(TelegramToken)
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text | Filters.command, TelegramHandler))
updater.start_polling()
return True
def TelegramQueryHandle(update:telegram.Update, context:CallbackContext=None) -> None:
def TelegramHandler(update:telegram.Update, context:CallbackContext=None) -> None:
if not (update and update.message):
return
OnMessageReceived()
cmd = ParseCmd(update.message.text)
if cmd:
cmd.messageId = update.message.message_id
@@ -70,13 +72,5 @@ def TelegramSender(event, manager, Data, Destination, TextPlain, TextMarkdown) -
elif TextPlain:
event.message.reply_text(TextPlain, reply_to_message_id=replyToId)
def TelegramMain() -> None:
if not TelegramToken:
return
updater = telegram.ext.Updater(TelegramToken)
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text | Filters.command, TelegramQueryHandle))
updater.start_polling()
RegisterPlatform(name="Telegram", main=TelegramMain, sender=TelegramSender, eventClass=telegram.Update)

View File

@@ -1,3 +1,8 @@
# ================================== #
# WinDog multi-purpose chatbot #
# Licensed under AGPLv3 by OctoSpacc #
# ================================== #
def WebMain() -> None:
pass