forked from SFTtech/cyberbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
bernd: Base commit with minimal viable version
- Loading branch information
Richard von Seck
committed
Oct 1, 2017
0 parents
commit b89df73
Showing
13 changed files
with
460 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2017 | ||
Paul Tolstoi | ||
Richard von Seck | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
this software and associated documentation files (the "Software"), to deal in | ||
the Software without restriction, including without limitation the rights to | ||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | ||
the Software, and to permit persons to whom the Software is furnished to do so, | ||
subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | ||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
[![Bernd Lauert](bernd.jpg)](http://krautchan.net) | ||
================================================== | ||
|
||
**Bernd Lauert** | ||
---------------- | ||
A matrix chatbot, designed for the [*StuStaNet | ||
e.V.*](http://http://vereinsanzeiger.stustanet.de/) administrator chatroom | ||
(#admins:stusta.de), written in python. | ||
|
||
**Requirements**: | ||
|
||
All required python modules are listed in the requirements.txt | ||
file. Furthermore the bot needs read and write permissions in the installation | ||
folder for correct execution. | ||
|
||
**Execution**: | ||
|
||
Specify the login credentials for the bot, as well as target rooms to join, in | ||
the provided *config.ini* file. When specifying target rooms, both room aliases | ||
(`#alias:server.org`) and internal IDs (`!suchalongidwehavehere:server.org`) are | ||
possible. If specifying multiple rooms, the IDs need to be separated by a | ||
semicolon (';'). Quotes should be generally omitted in the file. | ||
|
||
After the bot has been configured, issue: | ||
|
||
```sh | ||
python bernd -c <config_file> | ||
``` | ||
|
||
**Structure**: | ||
|
||
The bot itself only uses the basic functionality of the `matrix_bot_api` module | ||
to establish a matrix connection. All higher functionality is implemented in | ||
*plugin files*. These plugins need to be located in the *plugins* folder. | ||
|
||
Every plugin needs to define a `register_to(bot)` function, which is called upon | ||
plugin loading, and a `HELP_DESC` variable, containing a string with a short | ||
textual description of its features. | ||
|
||
For interaction with matrix services, respective modules need to be imported. | ||
Consider this short example of an echo plugin for demonstration purposes: | ||
|
||
```python | ||
from matrix_bot_api.mcommand_handler import MCommandHandler | ||
|
||
# Define a HELP_DESC, which describes the new functionality | ||
HELP_DESC = ("!echo\t\t-\tEcho back the given string\n") | ||
|
||
# plugin loading function, executed upon startup | ||
def register_to(bot): | ||
|
||
# Callback functions, registered with MCommandHandler/MRegexHandler are | ||
# provided with a matrix room object, in which the event has been received, | ||
# and the event data itself. Events in matrix are JSON objects and can be | ||
# easily accessed as follows: json_value = event['json_key'] | ||
def echo_callback(room, event): | ||
args = event['content']['body'].split() | ||
args.pop(0) | ||
|
||
# Interaction with matrix is conducted through the room object. Consider | ||
# the documentation of matrix_client.client/api for further information | ||
room.send_text(event['sender'] + ': ' + ' '.join(args)) | ||
|
||
# Add a command handler waiting for the echo command | ||
# This command handler reacts upon the command "!echo" and then invokes | ||
# the echo_callback function defined above | ||
echo_handler = MCommandHandler("echo", echo_callback) | ||
|
||
# register the handler with the running bot | ||
bot.add_handler(echo_handler) | ||
``` | ||
|
||
Newly written plugins are loaded automatically once they are placed in the | ||
plugins folder and fulfill all specified requirements. | ||
|
||
**Commands**: | ||
|
||
As the functionality of the bot depends heavily on the installed plugins, use | ||
the `!help` command, in order to display the currently available features. The | ||
displayed configuration is automatically generated at bot startup from the | ||
plugin description texts. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import argparse | ||
import configparser | ||
import importlib | ||
|
||
from matrix_bot_api.matrix_bot_api import MatrixBotAPI | ||
from pathlib import Path | ||
|
||
def main(): | ||
|
||
# Interpret command line arguments | ||
cmd = argparse.ArgumentParser() | ||
cmd.add_argument("-c", "--config", default="/etc/prism/config.py") | ||
args = cmd.parse_args() | ||
|
||
# Read the configuration file | ||
config = configparser.ConfigParser() | ||
config.sections() | ||
config.read(args.config) | ||
|
||
username = config['BotMatrixId']['USERNAME'] | ||
password = config['BotMatrixId']['PASSWORD'] | ||
server = config['BotMatrixId']['SERVER'] | ||
rooms = config['BotMatrixId']['ROOMS'].split(';') | ||
|
||
print("Bernd steht langsam auf...") | ||
|
||
# Create an instance of the MatrixBotAPI | ||
# The room argument is provided with empty list, as the original bot API | ||
# doesn't support string arguments but room objects, which we can't create | ||
# without an existing bot object. We add our room later. This argument also | ||
# prevents the bot from accepting random room invites. | ||
bot = MatrixBotAPI(username, password, server, []) | ||
|
||
# With an established connection and existing bot object, we tell the bot | ||
# manually to join or specified rooms | ||
for roomid in rooms: | ||
print("Trying to join room {}".format(roomid)) | ||
try: | ||
bot.handle_invite(roomid, None) | ||
except matrix_client.errors.MatrixRequestError: | ||
print("Failed to join room {}".format(roomid)) | ||
|
||
# Import all defined plugins | ||
plugin_path = Path(__file__).resolve().parent.parent / "plugins" | ||
print("Loading plugins from: {}".format(plugin_path)) | ||
|
||
help_desc = [] | ||
|
||
for filename in plugin_path.glob("*.py"): | ||
if (plugin_path / filename).exists(): | ||
|
||
modname = 'plugins.%s' % filename.stem | ||
loader = importlib.machinery.SourceFileLoader( | ||
modname, str(filename)) | ||
|
||
module = loader.load_module(modname) | ||
help_desc.append(module.HELP_DESC) # collect plugin help texts | ||
|
||
# skip help module, collect all help texts before registering | ||
if (modname == 'plugins.help'): | ||
help_module = module | ||
help_modname = modname | ||
else: | ||
module.register_to(bot) | ||
print(" [+] {} loaded".format(modname)) | ||
|
||
# Build the help message from the collected plugin description fragments | ||
help_desc.sort(reverse=True) | ||
|
||
line = '' | ||
for i in range(80): | ||
line += '-' | ||
help_desc.insert(0, line) | ||
|
||
help_desc.insert(0, '\nBernd Lauert Commands and Capabilities') | ||
help_txt = "\n".join(help_desc) | ||
|
||
with open('help_text', 'w') as f: | ||
f.write(help_txt) | ||
|
||
# load the help module after all help texts have been collected | ||
help_module.register_to(bot) | ||
print(" [+] {} loaded".format(help_modname)) | ||
|
||
# Start polling | ||
bot.start_polling() | ||
|
||
print("Bernd Lauert nun.") | ||
|
||
# Infinitely read stdin to stall main thread while bot runs in other threads | ||
while True: | ||
try: | ||
w = input("press q+<enter> or ctrl+d to quit\n") | ||
if (w == 'q'): | ||
return 0 | ||
except EOFError: | ||
return 0 | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[BotMatrixId] | ||
# Matrix username | ||
USERNAME = userbot | ||
# Password | ||
PASSWORD = userpass | ||
# URL Homeserver | ||
SERVER = https://matrix.org | ||
# Rooms to join (Single string, rooms delimited by ';') | ||
ROOMS = !thisisaprettylonginternalid:matrix.org |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
from matrix_bot_api.mregex_handler import MRegexHandler | ||
|
||
HELP_DESC = '(automatic)\t\tThe bot closes opened brackets without a counterpart' | ||
|
||
def register_to(bot): | ||
|
||
BRACKET_SYNTAX = False | ||
""" | ||
If this variable is set, syntactically correct closing of brackets is | ||
needed in order to prevent reporting by this plugin. If this variable is | ||
false, the plugin will simply print unclosed brackets, independent of | ||
placement. | ||
""" | ||
|
||
def bracket_callback(room, event): | ||
brackets = { | ||
'(': ')', '[': ']', '{': '}', '<': '>', | ||
'„': '“', | ||
'“': '”', '‘': '’', '‹': '›', '«': '»', | ||
'(': ')', '[': ']', '{': '}', '⦅': '⦆', | ||
'⦅': '⦆', '〚': '〛', '⦃': '⦄', | ||
'「': '」', '〈': '〉', '《': '》', '【': '】', '〔': '〕', '⦗': '⦘', | ||
'『': '』', '〖': '〗', '〘': '〙', | ||
'⟦': '⟧', '⟨': '⟩', '⟪': '⟫', '⟮': '⟯', '⟬': '⟭', '⌈': '⌉', | ||
'⌊': '⌋', '⦇': '⦈', '⦉': '⦊', | ||
'❛': '❜', '❝': '❞', '❨': '❩', '❪': '❫', '❴': '❵', '❬': '❭', | ||
'❮': '❯', '❰': '❱', | ||
'❲': '❳', '﴾': '﴿', | ||
'〈': '〉', '⦑': '⦒', '⧼': '⧽', | ||
'﹙': '﹚', '﹛': '﹜', '﹝': '﹞', | ||
'⁽': '⁾', '₍': '₎', | ||
'⦋': '⦌', '⦍': '⦎', '⦏': '⦐', '⁅': '⁆', | ||
'⸢': '⸣', '⸤': '⸥', | ||
} | ||
rbrackets = { v : k for k, v in brackets.items() } # reversed mapping | ||
|
||
smileys = [':(', ':\'(', ':-(', '<3', '+o(', ':\'-(', ';(', ';-(', | ||
'>.<', '>.>', '<.<' ':<', ':-<', '(:', ';)', ';-)'] | ||
|
||
result = [] # List of missing brackets, reported to chatroom | ||
stack = [] # Temporary stack of bracket counterparts | ||
message = event['content']['body'] | ||
|
||
# Remove smileys from calculation | ||
for smiley in smileys: | ||
message = message.replace(smiley, '') | ||
|
||
# Process filtered message for possible missing closed brackets | ||
for character in message: | ||
char = brackets.get(character) | ||
|
||
if len(result) > 0: | ||
if (BRACKET_SYNTAX): | ||
# Only allow syntactically correct bracket ordering | ||
if character == result[-1]: | ||
result.pop() | ||
continue | ||
else: | ||
# Return missing closed brackets, syntax correct or not | ||
for r in result: | ||
if (r == character): | ||
result.remove(r) | ||
break | ||
|
||
if char is not None: | ||
result.append(char) | ||
|
||
|
||
if len(result) > 0: | ||
result.reverse() | ||
room.send_text("".join(result)) | ||
|
||
return False | ||
|
||
bracket_handler = MRegexHandler('^(.*)$', bracket_callback) | ||
bot.add_handler(bracket_handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from matrix_bot_api.mcommand_handler import MCommandHandler | ||
|
||
HELP_DESC = "!digital++\t-\tIncrease the digitalization counter (Lindner Style)" | ||
|
||
def register_to(bot): | ||
|
||
def get_rank_string(n): | ||
|
||
small_ranks = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth', | ||
'sixth', 'seventh', 'eighth', 'ninth', 'tenth', | ||
'eleventh'] | ||
|
||
if (n >= 0 and n <= 11): | ||
return small_ranks[n] | ||
else: | ||
return str(n)+"th" | ||
|
||
def digital_callback(room, event): | ||
|
||
try: | ||
with open('digital_counter', 'r+') as f: | ||
n = int(f.read(1024)) | ||
f.seek(0) | ||
n += 1 | ||
f.write(str(n)) | ||
except FileNotFoundError: | ||
with open('digital_counter', 'x') as f: | ||
n = 0 | ||
f.write(str(n)) | ||
|
||
first = get_rank_string(n) | ||
second = get_rank_string(n+1) | ||
room.send_text("Digital {}, Bedenken {}.".format(first, second)) | ||
|
||
digital_handler = MCommandHandler("digital\+\+", digital_callback) | ||
bot.add_handler(digital_handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
from matrix_bot_api.mcommand_handler import MCommandHandler | ||
|
||
HELP_DESC = ("!echo\t\t-\tEcho back the given string\n" | ||
"!all\t\t\t-\tHighlight all people in the channel") | ||
|
||
def register_to(bot): | ||
|
||
# Echo back the given command | ||
def echo_callback(room, event): | ||
args = event['content']['body'].split() | ||
args.pop(0) | ||
|
||
room.send_text(event['sender'] + ': ' + ' '.join(args)) | ||
|
||
# Highlight all room members | ||
def all_callback(room, event): | ||
memb = room.get_joined_members() | ||
room.send_text(' '.join(memb)) | ||
|
||
# Add a command handler waiting for the echo command | ||
echo_handler = MCommandHandler("echo", echo_callback) | ||
bot.add_handler(echo_handler) | ||
|
||
# Add a command handler waiting for the all command | ||
all_handler = MCommandHandler("all", all_callback) | ||
bot.add_handler(all_handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from matrix_bot_api.mregex_handler import MRegexHandler | ||
from random import randint | ||
|
||
HELP_DESC = "(automatic)\t\tThe bot will greet back people, posting salutations" | ||
|
||
def register_to(bot): | ||
|
||
# Somebody said hi, let's say Hi back | ||
def hi_callback(room, event): | ||
greetings = ['hey', 'hi', 'ohai', 'heyho', 'cheerio', 'wazzuuuuuup', | ||
'greetings', 'yo', 'howdy', 'hiya'] | ||
jabberings = ['how are ya?', 'how\'s it going?', 'how\'s life?', | ||
'nice to see you', 'it\'s been a while', 'alright, mate?', | ||
'what\'s up?'] | ||
|
||
greeting = greetings[randint(0, len(greetings)-1)] | ||
jabbering = jabberings[randint(0, len(jabberings)-1)] | ||
|
||
room.send_text(greeting + ' ' + event['sender'] + '. ' + jabbering) | ||
|
||
# Add a regex handler waiting for the word Hi | ||
hi_handler = MRegexHandler("([sS]er(v[ua])?s)|" + | ||
"(([oO]?)((bend)|([hH](ey|i|ai|ello|allo))))", | ||
hi_callback) | ||
bot.add_handler(hi_handler) |
Oops, something went wrong.