Initalize repo

This commit is contained in:
BaerbelBox
2022-03-31 15:21:47 +02:00
parent 557f3e9b31
commit 7cf65ef092
98 changed files with 15860 additions and 0 deletions

75
.gitignore vendored Normal file
View File

@@ -0,0 +1,75 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
config.txt
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#pycharm
.idea/
.idea/workspace.xml
.idea/misc.xml
*.iml
.idea/misc.xml
*.xml
Model/ConnectionDetails.py
FaustBotVEnv/
# Custom
config.txt
.pid
out.txt
faust_bot.db
/venv/

View File

@@ -0,0 +1,18 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from FaustBot.Model.HanDatabaseProvider import HanDatabaseProvider
import csv
HanDBProvider = HanDatabaseProvider()
wordList = open("HangmanLog")
wordListWords = csv.reader(wordList, delimiter=';', quotechar='|')
randomChoicePool = []
for word in wordListWords:
print(word)
print(word[1].strip())
no = False
for char in ['ä','ü','ö','ß']:
if char.upper() in word[1].strip().upper():
no = True
if not no:
HanDBProvider.addWord(word[1].strip())

46
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at #faust-bot on the freenode irc network. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -0,0 +1,165 @@
import _thread
import queue
import socket
import time
from threading import Condition
from FaustBot.Communication.JoinObservable import JoinObservable
from FaustBot.Communication.KickObservable import KickObservable
from FaustBot.Communication.LeaveObservable import LeaveObservable
from FaustBot.Communication.MagicNumberObservable import MagicNumberObservable
from FaustBot.Communication.NickChangeObservable import NickChangeObservable
from FaustBot.Communication.NoticeObservable import NoticeObservable
from FaustBot.Communication.PingObservable import PingObservable
from FaustBot.Communication.PrivmsgObservable import PrivmsgObservable
from FaustBot.Model.ConnectionDetails import ConnectionDetails
from FaustBot.StringBuffer import StringBuffer
class Connection(object):
send_queue = queue.Queue()
details = None
irc = None
def sender(self):
while True:
msg = self.send_queue.get()
if msg[-1] != b'\n':
msg = msg + b'\n'
self.irc.send(msg)
time.sleep(1)
def send_channel(self, text):
"""
Send to channel
:return:
"""
self.raw_send("PRIVMSG " + self.details.get_channel() + " :" + text[0:])
def send_to_user(self, user, text):
"""
Send to user
:return:
"""
self.raw_send('PRIVMSG ' + user + ' :' + text)
def send_back(self, text, data):
"""
Send message to the channel the command got received in
:param message:
:param data: needed because of concurrency, there can't be a global variable holding where messages came from
:return:
"""
if data['channel'] == self.details.get_nick():
self.send_to_user(data['nick'], text)
else:
self.send_channel(text)
def raw_send(self, message):
self.send_queue.put(message.encode() + '\r\n'.encode())
def receive(self):
"""
receive from Network
"""
try:
data = self.irc.recv(4096)
if len(data) == 0:
return False
except socket.timeout:
return False
data = data.decode('UTF-8', errors='replace')
#print('received: \n' + data)
data_lines = self._receiver_buffer.append(data)
if data is None:
return False
# print('splited: ')
for data in data_lines:
# print(data)
data = data.rstrip()
self.data = data
splited = data.split(' ')
if not len(splited) >= 2:
continue
command = splited[1]
# print(command)
if data.split(' ')[0] == 'PING':
self.ping_observable.input(data, self)
elif command == 'JOIN':
self.join_observable.input(data, self)
elif command == 'PART' or command == 'QUIT':
self.leave_observable.input(data, self)
elif command == 'KICK':
self.kick_observable.input(data, self)
elif command == 'NICK':
self.nick_change_observable.input(data, self)
elif command == 'NOTICE':
self.notice_observable.input(data, self)
elif command == 'PRIVMSG':
self.priv_msg_observable.input(data, self)
else:
try:
int(command)
self.magic_number_observable.input(data, self)
except Exception:
pass
return True
def is_idented(self, user: str):
self.send_to_user('NickServ', 'ACC ' + user)
with self.condition_lock:
while user not in self.idented_look_up:
self.condition_lock.wait()
is_idented = self.idented_look_up[user]
del self.idented_look_up[user]
return is_idented
def is_op(self, user):
"""
Checks wether the given user is an op in this connections' channel or not.
:param user: the user to check
:return: return true if the user is an op, else false
"""
# add call to raw send with WHO
# manualy receive data until answer received
# then evaluate and return
# this way we'll block the bot until is_op is finished
return False
def last_data(self):
return self.data
def establish(self):
"""
establish the connection
"""
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.irc.connect((self.details.get_server(), self.details.get_port()))
#print(self.irc.recv(512))
self.irc.send("NICK ".encode() + self.details.get_nick().encode() + "\r\n".encode())
self.irc.send("USER botty botty botty :Botty \n".encode())
self.irc.send("JOIN ".encode() + self.details.get_channel().encode() + '\r\n'.encode())
self.irc.send("WHO ".encode() + self.details.get_channel().encode() + '\r\n'.encode())
self.irc.send("MODE ".encode()+self.details.get_nick().encode()+" -R".encode()+'\r\n'.encode())
if (self.details.get_pwd() != ''):
self.send_to_user("NICKSERV","identify "+self.details.get_nick()+" " +self.details.get_pwd()+' ')
_thread.start_new_thread(self.sender, ())
def __init__(self, set_details: ConnectionDetails):
self.details = set_details
self.ping_observable = PingObservable()
self.priv_msg_observable = PrivmsgObservable()
self.join_observable = JoinObservable()
self.leave_observable = LeaveObservable()
self.kick_observable = KickObservable()
self.nick_change_observable = NickChangeObservable()
self.notice_observable = NoticeObservable()
self.magic_number_observable = MagicNumberObservable()
self.condition_lock = Condition()
self.idented_look_up = {}
self.data = None
self._receiver_buffer = StringBuffer()

View File

@@ -0,0 +1,9 @@
__author__ = 'Daniela'
class DebugPrint(object):
def print(self, message):
"""
:param message: What to print to debug output
:return:
"""

View File

@@ -0,0 +1,24 @@
import _thread
from FaustBot.Communication.Observable import Observable
class JoinObservable(Observable):
def input(self, raw_data, connection):
# ":nick!user@host" "JOIN" "#channel"
# additional ignored arguments are put into "ign". This could be used
# for http://ircv3.net/specs/extensions/extended-join-3.1.html in the
# future.
prefix, cmd, channel, *ign = raw_data.split(' ')
hostmask = prefix.lstrip(':')
nick, userhost = hostmask.split('!')
user, host = userhost.split('@')
data = {'raw': raw_data, 'nick': nick, 'user': user, 'host': host,
'channel': channel, 'raw_nick': hostmask}
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_join, (observer, data, connection))

View File

@@ -0,0 +1,20 @@
import _thread
from FaustBot.Communication.Observable import Observable
class KickObservable(Observable):
def input(self, raw_data, connection):
data = {}
print(raw_data)
data['raw'] = raw_data
data['op'] = raw_data.split('!')[0][1:]
data['channel'] = raw_data.split('KICK ')[1].split(' :')[0].split(' ')[0]
data['nick'] = raw_data.split('KICK ')[1].split(' :')[0].split(' ')[1]
data['raw_op'] = raw_data.split(' KICK')[0][1:]
data['reason'] = raw_data.split('KICK ')[1].split(' :')[1]
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_kick, (observer, data, connection))

View File

@@ -0,0 +1,18 @@
import _thread
from FaustBot.Communication.Observable import Observable
class LeaveObservable(Observable):
def input(self, raw_data, connection):
data = {}
leave_or_part = "PART" if raw_data.find('PART') != -1 else "QUIT"
data['raw'] = raw_data
data['nick'] = raw_data.split('!')[0][1:]
data['channel'] = raw_data.split(leave_or_part + ' ')[1].split(' :')[0]
data['raw_nick'] = raw_data.split(' ' + leave_or_part)[0][1:]
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_leave, (observer, data, connection))

View File

@@ -0,0 +1,21 @@
import _thread
from FaustBot.Communication.Observable import Observable
class MagicNumberObservable(Observable):
def input(self, raw_data, connection):
data = {}
data['raw'] = raw_data
prefix, numeric, rest = data['raw'].split(' ',2)
data['number'] = numeric
data['arguments'] = rest
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
try:
_thread.start_new_thread(observer.__class__.update_on_magic_number, (observer, data, connection))
except Exception:
import traceback
print (traceback.format_exc())

View File

@@ -0,0 +1,14 @@
import _thread
from FaustBot.Communication.Observable import Observable
class NickChangeObservable(Observable):
def input(self, raw_data, connection):
data = {'raw': raw_data, 'old_nick': raw_data.split('!')[0][1:],
'new_nick': raw_data.split('NICK ')[1].split(':')[1], 'raw_nick': raw_data.split(' NICK')[0][1:]}
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_nick_change, (observer, data, connection))

View File

@@ -0,0 +1,14 @@
import _thread
from FaustBot.Communication.Observable import Observable
class NoticeObservable(Observable):
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_notice, (observer, data, connection))
def input(self, raw_data, connection):
data = {'raw_data': raw_data, 'nick': raw_data.split('!')[0][1:], 'raw_nick': raw_data.split(' NOTICE ')[0][1:],
'message': raw_data.split(':')[2]}
self.notify_observers(data, connection)

View File

@@ -0,0 +1,23 @@
class Observable(object):
def __init__(self):
self._observers = []
def add_observer(self, observer):
self._observers.append(observer)
print("appended(" + str(observer.__class__) + ")")
def get_observer(self):
return self._observers
# data has to be a dictionary matching the structure of the query
def notify_observers(self, data, connection):
# here implement some data handling. Fill self._data with the data received
raise NotImplementedError("Some Observable doesn't know what to do with its input data")
def input(self, raw_data, connection):
# here implement some data handling. Fill self._data with the data received
raise NotImplementedError("Some Observable doesn't know what to do with its input data")
def rm_observer(self, observer):
self._observers.remove(observer)

View File

@@ -0,0 +1,20 @@
import _thread
from FaustBot.Communication.Observable import Observable
class PingObservable(Observable):
def input(self, raw_data, connection):
data = {'raw': raw_data, 'server': ''}
if raw_data.find('PING') == 0:
data['server'] = raw_data.split('PING ')[1]
else:
return
# hier kann noch gecheckt werden, ob data wirklich ein server ist, der ping haben will, oder sonstwas
# finde heraus, wer zurückgepingt werden muss, und ob das überhaupt ein ping-request ist oder ein user sich
# einen spass erlaubt hat
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_ping, (observer, data, connection))

View File

@@ -0,0 +1,37 @@
import _thread
from FaustBot.Communication.Observable import Observable
from FaustBot import Modules
from FaustBot.Model.BlockedUsers import BlockProvider
class PrivmsgObservable(Observable):
def __init__(self):
Observable.__init__(self)
self.user_list = None
def define_user_list(self, user_list):
self.user_list = user_list
def input(self, raw_data, connection):
data = {'raw': raw_data, 'nick': raw_data.split('!')[0][1:],
'channel': raw_data.split('PRIVMSG ')[1].split(' :')[0],
'raw_nick': raw_data.split(' PRIVMSG')[0][1:]}
# 12 = :<raw_nick> PRIVMSG <channel> :<message>
data['message'] = raw_data[data['raw_nick'].__len__() + data['channel'].__len__() + 12:]
data['command'] = 'irgendwas, das mit . oder .. anfängt oder so... oder das sollen module checken?'
if self.user_list is None:
return
if data['nick'] not in self.user_list.userList.keys():
return
blocklist = BlockProvider()
if blocklist.is_blocked(data['nick']):
self.notify_whitelisted_observers(data, connection)
return
self.notify_observers(data, connection)
def notify_observers(self, data, connection):
for observer in self._observers:
_thread.start_new_thread(observer.__class__.update_on_priv_msg, (observer, data, connection))
def notify_whitelisted_observers(self,data,connection):
for observer in self._observers:
if observer.__class__.__name__ in ['ActivityObserver']:
_thread.start_new_thread(observer.__class__.update_on_priv_msg, (observer, data, connection))

View File

@@ -0,0 +1 @@
__author__ = 'Pups'

101
FaustBot/FaustBot.py Normal file
View File

@@ -0,0 +1,101 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.Config import Config
from FaustBot.Model.ConnectionDetails import ConnectionDetails
from FaustBot.Modules import ActivityObserver, IdentNickServObserver, GiveCookieObserver, LoveAndPeaceObserver, \
FreeHugsObserver, WhoObserver, Kicker, ModulePrototype, PingAnswerObserver, SeenObserver, TitleObserver, \
UserList, WikiObserver, GiveDrinkObserver, GiveFoodObserver, ComicObserver, HelpObserver, \
IntroductionObserver, HangmanObserver, DuckObserver, AllSeenObserver, JokeObserver,TellObserver, WordRunObserver,\
GiveIceObserver, GiveDrinkToObserver, Greeter, MathRunObserver, PartyObserver, PrideObserver, SnacksObserver, \
BlockObserver
from FaustBot.Modules.CustomUserModules import GlossaryModule, ICDObserver, ModmailObserver
from FaustBot.Modules.ModuleType import ModuleType
class FaustBot(object):
def __init__(self, config_path: str):
self._config = Config(config_path)
connection_details = ConnectionDetails(self.config)
self._connection = Connection(connection_details)
@property
def config(self):
return self._config
def _setup(self):
self._connection.establish()
user_list = UserList.UserList()
self._connection.priv_msg_observable.define_user_list(user_list)
self.add_module(user_list)
self.add_module(ActivityObserver.ActivityObserver())
self.add_module(WhoObserver.WhoObserver(user_list))
self.add_module(AllSeenObserver.AllSeenObserver(user_list))
self.add_module(PingAnswerObserver.ModulePing())
self.add_module(Kicker.Kicker(user_list, self._config.idle_time))
self.add_module(SeenObserver.SeenObserver())
self.add_module(TitleObserver.TitleObserver())
self.add_module(WikiObserver.WikiObserver())
self.add_module(ModmailObserver.ModmailObserver())
self.add_module(ICDObserver.ICDObserver())
self.add_module(GlossaryModule.GlossaryModule(self._config))
self.add_module(IdentNickServObserver.IdentNickServObserver())
self.add_module(GiveDrinkObserver.GiveDrinkObserver())
self.add_module(GiveCookieObserver.GiveCookieObserver())
self.add_module(LoveAndPeaceObserver.LoveAndPeaceObserver())
self.add_module(FreeHugsObserver.FreeHugsObserver())
self.add_module(GiveFoodObserver.GiveFoodObserver())
self.add_module(ComicObserver.ComicObserver())
self.add_module(HangmanObserver.HangmanObserver())
self.add_module(HelpObserver.HelpObserver())
self.add_module(IntroductionObserver.IntroductionObserver(user_list))
self.add_module(DuckObserver.DuckObserver())
self.add_module(JokeObserver.JokeObserver())
self.add_module(TellObserver.TellObserver())
self.add_module(WordRunObserver.WordRunObserver())
self.add_module(GiveIceObserver.GiveIceObserver())
self.add_module(GiveDrinkToObserver.GiveDrinkToObserver())
self.add_module(Greeter.Greeter())
self.add_module(MathRunObserver.MathRunObserver())
self.add_module(PartyObserver.PartyObserver())
self.add_module(PrideObserver.PrideObserver())
self.add_module(SnacksObserver.SnacksObserver())
self.add_module(BlockObserver.BlockObserver())
def run(self):
self._setup()
running = True
while running:
if not self._connection.receive():
return
def add_module(self, module: ModulePrototype):
if module.__class__.__name__ in self._config.blacklist:
print(module.__class__.__name__+ " not loaded because of blacklisting")
return
for module_type in module.get_module_types():
observable = self._get_observable_by_module_type(module_type)
observable.add_observer(module)
module.config = self._config
def _get_observable_by_module_type(self, module_type: str):
if module_type == ModuleType.ON_JOIN:
return self._connection.join_observable
if module_type == ModuleType.ON_LEAVE:
return self._connection.leave_observable
if module_type == ModuleType.ON_KICK:
return self._connection.kick_observable
if module_type == ModuleType.ON_MSG:
return self._connection.priv_msg_observable
if module_type == ModuleType.ON_NICK_CHANGE:
return self._connection.nick_change_observable
if module_type == ModuleType.ON_PING:
return self._connection.ping_observable
if module_type == ModuleType.ON_NOTICE:
return self._connection.notice_observable
if module_type == ModuleType.ON_MAGIC_NUMBER:
return self._connection.magic_number_observable

View File

@@ -0,0 +1,38 @@
import sqlite3
class BlockProvider(object):
_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS blockedusers (id INTEGER PRIMARY KEY, \
user TEXT)'
_IS_BLOCKED = 'SELECT user FROM blockedusers'
_BLOCK = 'INSERT INTO blockedusers (id, user) VALUES (?, ?)'
_DELETE_BLOCK = 'DELETE FROM blockedusers WHERE user = ?'
def __init__(self):
self._database_connection = sqlite3.connect('faust_bot.db')
cursor = self._database_connection.cursor()
cursor.execute(BlockProvider._CREATE_TABLE)
self._database_connection.commit()
def is_blocked(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(BlockProvider._IS_BLOCKED)
answer = cursor.fetchall()
for ans in answer:
if user.lower().find(ans[0])!=-1:
return True
return False
def block(self, user: str):
data = (None, user.lower())
cursor = self._database_connection.cursor()
cursor.execute(BlockProvider._BLOCK, data)
self._database_connection.commit()
def delete_block(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(BlockProvider._DELETE_BLOCK, (user.lower(),))
self._database_connection.commit()
def __exit__(self):
self._database_connection.close()

78
FaustBot/Model/Config.py Normal file
View File

@@ -0,0 +1,78 @@
class Config(object):
CONFIG_PATH = 'config_path'
def __init__(self, path):
"""
:param path:
"""
self._config_dict = {}
if path:
self._config_dict[Config.CONFIG_PATH] = path
self.read_config(path)
def __getitem__(self, item: str):
if item in self._config_dict:
return self._config_dict[item]
else:
return None
def __setitem__(self, key: str, value: str):
print (key +' '+ value+'\n\r')
self._config_dict[key] = value
def read_config(self, path: str, append=True):
f = open(path, 'r')
if not append:
self._config_dict = {}
for l in f.readlines():
kv_pair = l.split(':')
if len(kv_pair) == 2:
self._config_dict[kv_pair[0].strip()] = kv_pair[1][:-1].strip()
mods = self._config_dict['mods'].split(',')
self._config_dict['mods'] = []
for mod in mods:
self._config_dict['mods'].append(mod.strip())
# If no idle_time value is given, we set it to five hours ( == 18000 seconds )
if 'idle_time' not in self._config_dict:
self._config_dict['idle_time'] = 18000
self._config_dict['idle_time'] = int(self._config_dict['idle_time'])
if 'blacklist' not in self._config_dict:
self._config_dict['blacklist'] = []
else:
blacklist=self._config_dict['blacklist'].split(',')
self._config_dict['blacklist'] = []
for module in blacklist:
self._config_dict['blacklist'].append(module.strip())
@property
def lang(self):
return self._config_dict["lang"]
@lang.setter
def lang(self, value):
self._config_dict["lang"] = value
@property
def mods(self):
return self._config_dict["mods"]
@mods.setter
def mods(self, value):
self._config_dict["mods"] = value
@property
def idle_time(self):
return self._config_dict["idle_time"]
@idle_time.setter
def idle_time(self, value: int):
self._config_dict["idle_time"] = value
@property
def blacklist(self):
return self._config_dict['blacklist']
@property
def pwd(self):
return self._config_dict['pwd']

View File

@@ -0,0 +1,38 @@
class ConnectionDetails(object):
def get_server(self):
"""
:return: the server to connect to
"""
return self._data['server']
def get_nick(self):
"""
:return: own nick
"""
return self._data['nick']
def get_channel(self):
"""
:return: the channel connected into
"""
return self._data['channel']
def get_port(self):
return int(self._data['port'])
def get_lang(self):
return self._data['lang']
def change_lang(self, lang):
self._data['lang'] = lang
def get_mods(self):
return self._data['mods']
def get_pwd(self):
if self._data['pwd'] is None:
return ''
return self._data['pwd']
def __init__(self, config):
self._data = config

View File

@@ -0,0 +1,47 @@
import sqlite3
class GlossaryProvider(object):
_CREATE_GLOSSARY_TABLE = 'CREATE TABLE IF NOT EXISTS glossary (id INTEGER PRIMARY KEY, \
abbreviation TEXT, explanation TEXT)'
_GET_EXPLANATION = 'SELECT id, explanation FROM glossary WHERE abbreviation = ?'
_SAVE_OR_OVERWRITE = 'REPLACE INTO glossary (id, abbreviation, explanation) VALUES (?, ?, ?)'
_DELETE_EXPLANATION = 'DELETE FROM glossary WHERE abbreviation = ?'
def __init__(self):
self._database_connection = sqlite3.connect('faust_bot.db')
cursor = self._database_connection.cursor()
cursor.execute(GlossaryProvider._CREATE_GLOSSARY_TABLE)
self._database_connection.commit()
def get_explanation(self, abbreviation: str):
"""
:param abbreviation:
:return:
"""
cursor = self._database_connection.cursor()
cursor.execute(GlossaryProvider._GET_EXPLANATION, (abbreviation.lower(),))
return cursor.fetchone()
def save_or_replace(self, abbreviation: str, explanation: str):
"""
:param abbreviation:
:param explanation:
:return:
"""
existing = self.get_explanation(abbreviation)
_id = existing[0] if existing is not None else None
data = (_id, abbreviation.lower(), explanation)
cursor = self._database_connection.cursor()
cursor.execute(GlossaryProvider._SAVE_OR_OVERWRITE, data)
self._database_connection.commit()
def delete_explanation(self, abbreviation: str):
cursor = self._database_connection.cursor()
cursor.execute(GlossaryProvider._DELETE_EXPLANATION, (abbreviation.strip(),))
self._database_connection.commit()
def __exit__(self, exc_type, exc_value, traceback):
self._database_connection.close()

View File

@@ -0,0 +1,57 @@
import sqlite3
class HanDatabaseProvider(object):
_CREATE_HANDB_TABLE = 'CREATE TABLE IF NOT EXISTS handb (id INTEGER PRIMARY KEY, \
hanword TEXT)'
_GET_RANDOM_WORD = 'SELECT hanword FROM handb ORDER BY RANDOM() LIMIT 1'
_INSERT_WORD = 'REPLACE INTO handb(id, hanword) VALUES (?,?)'
_DELETE_WORD = 'DELETE FROM handb WHERE hanword = ?'
_GET_WORD = 'SELECT id, hanword FROM handb WHERE hanword = ?'
def __init__(self):
self._database_connection = sqlite3.connect('faust_bot.db')
cursor = self._database_connection.cursor()
cursor.execute(HanDatabaseProvider._CREATE_HANDB_TABLE)
self._database_connection.commit()
def get_random_word(self):
"""
:param abbreviation:
:return:
"""
cursor = self._database_connection.cursor()
cursor.execute(HanDatabaseProvider._GET_RANDOM_WORD)
return cursor.fetchone()
def get_hanWord(self, HanWord):
"""
:param abbreviation:
:return:
"""
cursor = self._database_connection.cursor()
cursor.execute(HanDatabaseProvider._GET_WORD, (HanWord.upper(),))
return cursor.fetchone()
def addWord(self, HanWord):
"""
:param abbreviation:
:param explanation:
:return:
"""
existing = self.get_hanWord(HanWord)
_id = existing[0] if existing is not None else None
data = (_id, HanWord)
cursor = self._database_connection.cursor()
cursor.execute(HanDatabaseProvider._INSERT_WORD, data)
self._database_connection.commit()
def delete_hanWord(self, HanWord):
cursor = self._database_connection.cursor()
cursor.execute(HanDatabaseProvider._DELETE_WORD, (HanWord.strip(),))
self._database_connection.commit()
def __exit__(self, exc_type, exc_value, traceback):
self._database_connection.close()

View File

@@ -0,0 +1,36 @@
import sqlite3
class IntroductionProvider(object):
_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS introduction (id INTEGER PRIMARY KEY, \
user TEXT, intro TEXT)'
_GET_INTRO = 'SELECT id, intro FROM introduction WHERE user = ?'
_SAVE_OR_OVERWRITE = 'REPLACE INTO introduction (id, user, intro) VALUES (?, ?, ?)'
_DELETE_INTRO = 'DELETE FROM introduction WHERE user = ?'
def __init__(self):
self._database_connection = sqlite3.connect('faust_bot.db')
cursor = self._database_connection.cursor()
cursor.execute(IntroductionProvider._CREATE_TABLE)
self._database_connection.commit()
def get_intro(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(IntroductionProvider._GET_INTRO, (user.lower(),))
return cursor.fetchone()
def save_or_replace(self, user: str, intro: str):
existing = self.get_intro(user)
_id = existing[0] if existing is not None else None
data = (_id, user.lower(), intro)
cursor = self._database_connection.cursor()
cursor.execute(IntroductionProvider._SAVE_OR_OVERWRITE, data)
self._database_connection.commit()
def delete_intro(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(IntroductionProvider._DELETE_INTRO, (user.lower(),))
self._database_connection.commit()
def __exit__(self):
self._database_connection.close()

View File

@@ -0,0 +1,9 @@
class RemoteUser(object):
"""
Holds information about another user on IRC (nick!user@host)
"""
def __init__(self, nick, user, host):
self.nick = nick
self.user = user
self.host = host

View File

@@ -0,0 +1,36 @@
import sqlite3
class ScoreProvider(object):
_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS score (id INTEGER PRIMARY KEY, \
user TEXT, score INTEGER)'
_GET_SCORE = 'SELECT id, score FROM score WHERE user = ?'
_SAVE_OR_OVERWRITE = 'REPLACE INTO score (id, user, score) VALUES (?, ?, ?)'
_DELETE_SCORE = 'DELETE FROM score WHERE user = ?'
def __init__(self):
self._database_connection = sqlite3.connect('faust_bot.db')
cursor = self._database_connection.cursor()
cursor.execute(ScoreProvider._CREATE_TABLE)
self._database_connection.commit()
def get_score(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(ScoreProvider._GET_SCORE, (user.lower(),))
return cursor.fetchone()
def save_or_replace(self, user: str, score: int):
existing = self.get_score(user)
_id = existing[0] if existing is not None else None
data = (_id, user.lower(), score)
cursor = self._database_connection.cursor()
cursor.execute(ScoreProvider._SAVE_OR_OVERWRITE, data)
self._database_connection.commit()
def delete_score(self, user: str):
cursor = self._database_connection.cursor()
cursor.execute(ScoreProvider._DELETE_SCORE, (user.lower(),))
self._database_connection.commit()
def __exit__(self):
self._database_connection.close()

View File

@@ -0,0 +1,18 @@
class TextProvider(object):
"""
Provides different Texts
"""
def get_random_fortune(self):
"""
:return: a random sentence
"""
return "Das macht Spa<70>"
def get_definiton(self, name):
"""
:param name: name of definition to get
:return: the definition
"""
return "Konnte Definition nicht finden"

View File

@@ -0,0 +1,107 @@
import sqlite3
import time
class UserProvider(object):
"""
Provides information about the users
"""
def __init__(self):
self.database_connection = sqlite3.connect('faust_bot.db')
cursor = self.database_connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY , name TEXT)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS user_stats(id INTEGER PRIMARY KEY, characters INT)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS last_seen (id INTEGER PRIMARY KEY, last_seen REAL)''')
self.database_connection.commit()
def get_characters(self, name):
"""
:param name: name of user whom characters are to get
:return: total number of characters written
"""
cursor = self.database_connection.cursor()
id = self._get_id(name)
if id is None:
return 0
for characters in cursor.execute("SELECT characters FROM user_stats WHERE id = ?", (id,)):
return characters[0]
return 0
def get_activity(self, name):
"""
:param name: name of user whom activity to get
:return: last activity by user
"""
cursor = self.database_connection.cursor()
id = self._get_id(name)
if id is None:
return 0
for time in cursor.execute("SELECT last_seen FROM last_seen WHERE id = ?", (id,)):
return time[0]
return 0
def add_characters(self, name, number):
"""
:param name: User to Add Characters to
:param number: Number of Characters to add
:return: nothing
"""
cursor = self.database_connection.cursor()
id = self._get_id(name)
if id is None:
self._create_user(name)
id = self._get_id(name)
for chars in cursor.execute("SELECT characters FROM user_stats WHERE id = ?", (id,)):
chars = chars[0]
chars += number
cursor.execute("UPDATE user_stats SET characters = ? WHERE id = ?", (chars, id,))
self.database_connection.commit()
return None
def set_active(self, name):
"""
:param name: set this user active at the moment
:return: Nothing
"""
cursor = self.database_connection.cursor()
id = self._get_id(name)
ntime = time.time()
if id is None:
self._create_user(name)
id = self._get_id(name)
cursor.execute("UPDATE last_seen SET last_seen = ? WHERE id = ?", (ntime, id,))
self.database_connection.commit()
def permission(self, user, percent):
"""
:param user: user to ask permission for
:param percent: percent needed for permission
:return: True or False
http://stackoverflow.com/questions/1682920/determine-if-a-user-is-idented-on-irc
"""
return True
def _get_id(self, name):
cursor = self.database_connection.cursor()
try:
for id in cursor.execute("SELECT id FROM user WHERE name = ?", (name,)):
return id[0]
except:
return None
def _create_user(self, name):
cursor = self.database_connection.cursor()
cursor.execute("INSERT INTO user(name) VALUES (?)", (name,))
id = self._get_id(name)
cursor.execute("INSERT INTO user_stats(id, characters) VALUES (?, 0)", (id,))
cursor.execute("INSERT INTO last_seen (id, last_seen) VALUES (?, 0)", (id,))
self.database_connection.commit()
def __exit__(self, exc_type, exc_value, traceback):
self.database_connection.close()

View File

@@ -0,0 +1 @@
__author__ = 'Pups'

23
FaustBot/Model/i18n.py Normal file
View File

@@ -0,0 +1,23 @@
import sqlite3
class i18n(object):
def get_text(self, name, replacements=None, lang='de-DE'):
"""
:param replacements:
:param name: name of text
:param lang: language to get text in
:return: the text
"""
if replacements is None:
replacements = {}
database_connection = sqlite3.connect('faust_bot.db')
cursor = database_connection.cursor()
ltext = ""
print(replacements)
for longText in cursor.execute("SELECT longText FROM i18n WHERE lang = ? AND ident = ?", (lang, name,)):
ltext = longText[0]
for (key, value) in replacements.items():
ltext = ltext.replace('$' + key, value)
return ltext

View File

@@ -0,0 +1,40 @@
# from ..FaustBot import ModuleType
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.JoinObserverPrototype import JoinObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from ..Modules.NickChangeObserverPrototype import NickChangeObserverPrototype
from ..Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class ActivityObserver(PrivMsgObserverPrototype, JoinObserverPrototype, NickChangeObserverPrototype):
"""
A Class only reacting to pings
"""
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_join(self, data, connection: Connection):
users = UserProvider()
if data['channel'] == connection.details.get_channel():
users.set_active(data['nick'])
def update_on_priv_msg(self, data, connection: Connection):
users = UserProvider()
if data['channel'] == connection.details.get_channel():
users.set_active(data['nick'])
users.add_characters(data['nick'], len(data['message']))
def update_on_nick_change(self, data, connection: Connection):
users = UserProvider()
users.set_active(data['new_nick'])
@staticmethod
def get_module_types():
return [ModuleType.ON_MSG, ModuleType.ON_JOIN, ModuleType.ON_NICK_CHANGE]

View File

@@ -0,0 +1,41 @@
import datetime
import time
from collections import defaultdict
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from ..Model.i18n import i18n
from FaustBot.Modules.UserList import UserList
class AllSeenObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".seen"]
@staticmethod
def help():
return ".seen <nick> - um abzufragen wann <nick> zuletzt hier war"
def __init__(self, user_list: UserList):
super().__init__()
self.user_list = user_list
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.allseen') == -1:
return
if not self._is_idented_mod(data, connection):
return
User_afk = defaultdict(int)
for who in self.user_list.userList.keys():
user_provider = UserProvider()
activity = user_provider.get_activity(who)
delta = time.time() - activity
User_afk[who] = delta
print(who)
print(delta)
for w in sorted(User_afk, key=User_afk.get):
output = (w+":\t"+str(datetime.timedelta(seconds=User_afk[w])))
connection.send_back(output, data)
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,130 @@
from FaustBot.Communication.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from FaustBot.Modules.JoinObserverPrototype import JoinObserverPrototype
from FaustBot.Model.Config import Config
from enum import Enum
from datetime import datetime
"""
This Module contains multiple classes to handle spam.
Goal of this module is to provide an easy to use AntiSpam-Module, which can be activated if needed.
It should support multiple modes regarding the aggressivity of the anti-spam-handling.
"""
class AntiSpamLevel(Enum):
"""
Which action to be done if spam is detected.
"""
OFF = 0 # No action is taken if spam is detected.
WARN = 1 # Warns the user by messaging him/her without any further steps.
WARN_KICK = 2 # Warns the user first, then kicks him/her.
KICK = 3 # Kicks the user without any further warning.
WARN_KICK_BAN = 4 # Like WARN_KICK but also bans the user directly.
KICK_BAN = 5 # Like KICK, but also bans the user directly.
class AntiSpamAggressivity(Enum):
"""
Settings to detect spam.
a: Amount of seconds between two similiar messages to detect them as spam
b: Amount of (non similiar) messages to be received with time-distance c, to detect them as spam
c: Time between messages of b:
d: Trustfactor
"""
LOW = (3, 7, 0.5, 15) # (a, b, c, d)
MEDIUM = (5, 5, 0.7, 10)
HIGH = (7, 3, 1.0, 5)
ULTRA = (10, 3, 1.0, 2)
class AntiSpamEntry(object):
"""
Entry collecting information about possible spammers.
"""
def __init__():
super().__init__()
self.user = ""
self.warn_count = 0
self.msg = ""
self.timestamp = datetime.now()
@property
def user(self):
return self.user
@user.setter
def user(self, user)
self.user = user
@property
def warn_count(self):
return self.warn_count
@warn_count.setter
def warn_count(self, warn_count)
self.warn_count = warn_count
def inc_warn_count(self)
self.warn_count += 1
@property
def msg(self):
return self.msg
@msg.setter
def msg(self, msg):
self.msg = msg
@property
def timestamp(self):
return self.timestamp
@timestamp.setter
def timestamp(self, timestamp):
self.timestamp = timestamp
class AntiSpamObserver(PrivMsgObserverPrototype, JoinObserverPrototype):
@staticmethod
def cmd():
raise NotImplementedError("TBD!")
@staticmethod
def help():
raise NotImplementedError("TBD!")
@staticmethod
def get_module_types():
return [ModuleType.ON_JOIN,
ModuleType.ON_PRIVMSG]
def __init__(self, config : Config):
super().__init__()
self._msg_map = dict()
self._anti_spam_level = AntiSpamLevel.OFF
self._anti_spam_aggressivity = AntiSpamAggressivity.LOW
def update_on_priv_msg(self, data, connection: Connection):
if _bot_name in data['channel']: # TBD! _bot_name should be fetched from the config!
self._handle_command(data, connection)
if self._anti_spam_level == AntiSpamLevel.OFF:
return
def update_on_join(self, data: dict, connection: Connection):
raise NotImplementedError("TBD!")
def _is_spam(self, user: str, msg: str)
pass
def _handle_command(self, data: dict, connection: Connection)
pass
def _is_idented_mod(self, data: dict, connection: Connection):
"""
Check wether the issuer of a module control command is a moderator or not
"""
return data['nick'] in self._config.mods and connection.is_idented(data['nick']

View File

@@ -0,0 +1,50 @@
import datetime
import time
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from ..Model.i18n import i18n
from FaustBot.Model.BlockedUsers import BlockProvider
class BlockObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [""]
@staticmethod
def help():
return ""
def update_on_priv_msg(self, data, connection: Connection):
if not self._is_idented_mod(data, connection):
return
if data['message'].find('.block ') != -1:
self.block(data, connection)
if data['message'].find ('.unblock')!=-1:
self.unblock(data, connection)
if data['message'].find('.isblocked') != -1:
self.isBlocked(data, connection)
def block(self,data,connection):
blocklist = BlockProvider()
blocklist.block(self.isolateTarget(data))
connection.send_back("blocked: "+ self.isolateTarget(data), data)
def unblock(self,data,connection):
blocklist = BlockProvider()
blocklist.delete_block(self.isolateTarget(data))
connection.send_back("unblocked: "+ self.isolateTarget(data), data)
def isBlocked(self,data,connection):
blocklist= BlockProvider()
answ = blocklist.is_blocked(self.isolateTarget(data))
if answ:
connection.send_back(self.isolateTarget(data) + " ist geblocked", data)
return
connection.send_back(self.isolateTarget(data)+" ist nicht geblocked", data)
def isolateTarget(self,data):
return data['message'].split(' ')[1]
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,43 @@
import random
import urllib
import requests
import html
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from FaustBot.Modules.TitleObserver import TitleObserver
from FaustBot.Modules.ComicScraper import ComicScraper
from comics import *
class ComicObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return ['.comic']
@staticmethod
def help():
return '.comic liefer einen Link zu einem zufälligen Comic.'
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.comic') == -1:
return
#Join list of comics that have a web based random functionality and those that need a scraper
all_comics=comics+scraper_comics
#Choose from the joined list
comic = random.choice(all_comics)
#Check which type of comic it is: If it's one that doesn't need a scraper, get the url and return it.
#If it needs a scraper, use ComicScraper to scrape the comic.
#If you want to add custom comic scrapers: Look at ComicScraper.py and insert your functionality.
if not comic in scraper_comics:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
req = urllib.request.Request(comic, None, headers)
resource = urllib.request.urlopen(req)
title = TitleObserver.getTitle(TitleObserver(), resource)
connection.send_back(resource.geturl() + " " + title, data)
else:
connection.send_back(ComicScraper.getRandomComic(comic),data);

View File

@@ -0,0 +1,41 @@
import random
import urllib
import requests
import html
#Comic scraper scrapes comics from urls that have no website based random functionality. Comic URLs have to be in comics.py
class ComicScraper():
#Scrapers for specific websites follow here:
#scraper for Betamonkeys
def scrapeBetamonkeys(url):
#get latest comic id from the website, then generate a random number within the range of 1 and the latest comic.
#Finally generate a new comic url from that. I know this is dirty - But it works for a comic i guess ;)
r = requests.get(url)
comic_id_latest=r.content.decode("utf-8").split("http://betamonkeys.co.uk/wp-content/stripshow_comics/betamonkeys")[1].split(".png")[0]
random_comic_number=str(random.randint(1,int(comic_id_latest)))
random_comic_url="http://betamonkeys.co.uk/wp-content/stripshow_comics/betamonkeys"+random_comic_number+".png"
return random_comic_url+ " Betamonkeys "+ random_comic_number + " | Betamonkeys"
#scraper for Nichtlustig
def scrapeNichtlustig(url):
#TODO: Write a scraper for Nichtlustig!
return "Bisher kein Scraper für Nichtlustig."
#your custom scraper here
#def scrapeYourCustomComic(url):
#return "Your custom scraped URL"
#Main scraping function. Takes url, decides scraping method to use. If no scraping method is found: return "No parser found"
def getRandomComic(url):
if "betamonkeys.co.uk" in url:
return ComicScraper.scrapeBetamonkeys(url)
if "nichtlustig.de" in url:
return ComicScraper.scrapeNichtlustig(url)
else:
return "No parser found for comic URL: "+url

View File

@@ -0,0 +1,94 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.Config import Config
from FaustBot.Model.GlossaryProvider import GlossaryProvider
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from FaustBot.Modules.WikiObserver import WikiObserver
class GlossaryModule(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [GlossaryModule._ADD_EXPLANATION,
GlossaryModule._REMOVE_EXPLANATION,
GlossaryModule._QUERY_EXPLANATION]
@staticmethod
def help():
return None
_QUERY_EXPLANATION = '.?'
_REMOVE_EXPLANATION = '.?-'
_ADD_EXPLANATION = '.?+'
def __init__(self, config: Config):
super().__init__()
self._config = config
def update_on_priv_msg(self, data, connection: Connection):
msg = data['message']
if not -1 == msg.find(GlossaryModule._REMOVE_EXPLANATION):
self._remove_query(data, connection)
elif not -1 == msg.find(GlossaryModule._ADD_EXPLANATION):
self._add_query(data, connection)
elif not -1 == msg.find(GlossaryModule._QUERY_EXPLANATION):
self._answer_query(data, connection)
def _answer_query(self, data, connection: Connection):
"""
:param data:
:param connection:
:return:
"""
glossary_provider = GlossaryProvider()
split = data['message'].split(GlossaryModule._QUERY_EXPLANATION)
if not len(split) == 2:
return
answer = glossary_provider.get_explanation(split[1].strip())
if answer is None or answer[1] is None or answer[1].strip() == '':
if split[1].strip() == '':
return
# connection.send_back("Tut mir leid, " + data['nick'] + ". Für " + split[1].strip() +
# " habe ich noch keinen Eintrag. Aber Wikipedia sagt dazu:", data)
wikiObserver = WikiObserver()
wikiObserver.config = self.config
data2 = data.copy()
data2['message'] = '.w '+split[1]+" \r\n"
wikiObserver.update_on_priv_msg(data2, connection)
else:
connection.send_back(data['nick'] + ": " + split[1] + " - " + answer[1], data)
def _remove_query(self, data, connection: Connection):
"""
:param data:
:param connection:
:return:
"""
if not self._is_idented_mod(data, connection):
connection.send_back("Dir fehlen die Berechtigungen zum Löschen von Einträgen, " + data['nick'] + ".", data)
return
glossary_provider = GlossaryProvider()
split = data['message'].split(GlossaryModule._REMOVE_EXPLANATION)
if not len(split) == 2:
return
glossary_provider.delete_explanation(split[1])
connection.send_back("Der Eintrag zu " + split[1] + " wurde gelöscht, " + data['nick'] + ".", data)
def _add_query(self, data, connection: Connection):
"""
:param data:
:param connection:
:return:
"""
if not self._is_idented_mod(data, connection):
connection.send_back("Dir fehlen leider die Rechte zum Hinzufügen von Einträgen, " + data['nick'] + ".",
data)
return
msg = data['message'].split(GlossaryModule._ADD_EXPLANATION)[1].strip()
split = msg.split(' ', 1)
glossary_provider = GlossaryProvider()
glossary_provider.save_or_replace(split[0], split[1])
connection.send_back(data['nick'] + ": der Eintrag zu " + split[0] + " wurde gespeichert.", data)
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,42 @@
import csv
import re
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class ICDObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def get_icd(self, code):
if code == "C64" or code == "P20":
return ""
icd10_codes = open('care_icd10_de.csv', 'r',encoding='utf8')
icd10 = csv.reader(icd10_codes, delimiter=';', quotechar='"')
for row in icd10:
if row[0] == code:
return code +' - ' + row[1]
return 0
def update_on_priv_msg(self, data, connection: Connection):
if data['channel'] != connection.details.get_channel():
return
regex = r'\b(\w\d{2}\.?\d?\d?)\b'
codes = re.findall(regex, data['message'])
for code in codes:
code = code.capitalize()
text = self.get_icd(code)
if text == 0:
if code.find('.') != -1:
code += '-'
else:
code += '.-'
text = self.get_icd(code)
if text != 0:
connection.send_back(text, data)

View File

@@ -0,0 +1,21 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class ModmailObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".modmail"]
@staticmethod
def help():
return ".modmail <msg> - Sendet allen Moderatoren <msg> per PN"
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.modmail') == -1:
return
mods = connection.details.get_mods()
print(mods)
message = data['message'].split('.modmail ')[1]
for mod in mods:
connection.send_to_user(mod, data['nick'] + ' meldet: ' + message)

View File

@@ -0,0 +1,88 @@
from FaustBot.Modules.ModuleType import ModuleType
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from random import randint
from collections import defaultdict
class DuckObserver(PrivMsgObserverPrototype, PingObserverPrototype):
@staticmethod
def cmd():
return ['.freunde', '.schiessen', '.starthunt','.stophunt','.ducks']
@staticmethod
def help():
return 'duck game'
@staticmethod
def get_module_types():
return [ModuleType.ON_MSG, ModuleType.ON_PING]
def __init__(self):
super().__init__()
self.active = 0
self.duck_alive = 0
self.ducks_hunt = defaultdict(int)
self.ducks_befriend = defaultdict(int)
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.starthunt') != -1:
if not self._is_idented_mod(data, connection):
connection.send_back("Dir fehlen leider die Rechte zum Starten der Jagd, " + data['nick'] + ".",data)
return
self.active = 1
connection.send_channel("Jagd eröffnet")
return
if data['message'].find('.stophunt') != -1:
if not self._is_idented_mod(data, connection):
connection.send_back("Dir fehlen leider die Rechte zum Stoppen der Jagd, " + data['nick'] + ".",
data)
return
self.active = 0
self.duck_alive = 0
connection.send_channel("Jagd beended")
return
if data['message'].find('.ducks') != -1:
connection.send_channel(data['nick'] + " hat schon " + str(self.ducks_befriend[data['nick']]) + " befreundete Enten und " + str(self.ducks_hunt[data['nick']]) + " getötete Enten.")
if data['message'].find('.freunde') != -1:
self.befriend(data, connection)
if data['message'].find('.schiessen') != -1:
self.shoot(data, connection)
def befriend(self, data, connection):
if self.duck_alive == 1:
if randint(1, 100) > 97:
connection.send_channel(data['nick'] + " probiert eine Ente zu befreunden aber sie will nicht.")
else:
self.duck_alive = 0
self.ducks_befriend[data['nick']] += 1
connection.send_channel(data['nick'] + " hat schon " + str(self.ducks_befriend[data['nick']]) + " befreundete Enten und " + str(self.ducks_hunt[data['nick']]) + " getötete Enten.")
return
if (self.duck_alive == 0 and self.active == 1):
connection.send_channel(data['nick']+ " probiert eine nicht existente Ente zu befreunden")
if self.active == 0:
connection.send_channel("Es läuft derzeit keine Entenjagd.")
def shoot(self, data, connection):
if self.duck_alive == 1:
if randint(1,100) >97:
connection.send_channel(data['nick'] + " trifft daneben")
else:
self.duck_alive = 0
self.ducks_hunt[data['nick']] += 1
connection.send_channel(data['nick'] + " hat schon " + str(self.ducks_befriend[data['nick']]) + " befreundete Enten und " + str(self.ducks_hunt[data['nick']]) + " getötete Enten.")
return
if (self.duck_alive == 0 and self.active == 1):
connection.send_channel(data['nick']+ " schiesst ins Nichts")
if self.active == 0:
connection.send_channel("Es läuft derzeit keine Entenjagd.")
def update_on_ping(self, data, connection: Connection):
if self.active == 0:
return
if 1 == randint(1,11):
if self.duck_alive == 0:
connection.send_channel("*. *. *. * <<w°)> *. *. * Quack!")
self.duck_alive = 1
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,17 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class FreeHugsObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".hug"]
@staticmethod
def help():
return ".hug - verteilt Umarmungen"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.hug') == -1:
return
connection.send_back('\001ACTION knuddelt ' + data['nick'] + '.\001', data)

View File

@@ -0,0 +1,23 @@
import random
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
kekse = ['einen Schokoladenkeks', 'einen Vanillekeks', 'einen Doppelkeks', 'keinen Keks',
'einen Keks', 'einen Erdbeerkeks', 'einen Schokoladen-Cheesecake-Keks',
'einen Glückskeks', 'einen Scherzkeks', 'einen Unglückskeks']
class GiveCookieObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".cookie"]
@staticmethod
def help():
return ".cookie - verteilt kekse; oder auch nicht"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.cookie') == -1:
return
connection.send_back('\001ACTION schenkt ' + data['nick'] + ' ' + random.choice(kekse) + '.\001', data)

View File

@@ -0,0 +1,20 @@
import random
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from getraenke import getraenke
class GiveDrinkObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".drink"]
@staticmethod
def help():
return ".drink - schenkt Getränke aus"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.drink') == -1:
return
connection.send_back('\001ACTION schenkt ' + data['nick'] + ' ' + random.choice(getraenke) + ' ein.\001', data)

View File

@@ -0,0 +1,98 @@
import random
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from getraenkeOnlyGoodOnes import getraenkegoodones
from getraenke import getraenke
from essen import essen
from icecreamlist import icecream
from extras import giveextras
from snacks import snacks
kekse = ['einen Schokoladenkeks', 'einen Vanillekeks', 'einen Doppelkeks',
'einen Keks', 'einen Erdbeerkeks', 'einen Schokoladen-Cheesecake-Keks',
'einen Glückskeks', 'einen Scherzkeks', 'einen Unglückskeks']
class GiveDrinkToObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".givedrink"]
@staticmethod
def help():
return ".givedrink NUTZER - schenkt jemand anders ein Getränke aus"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.give') == -1:
return
receiver = data['message'].split()[1]
if receiver == data['nick']:
type = data['message'].split()[2]
if type is not None:
if type.lower() == "kaffee":
connection.send_back('Fehler 418 Ich bin eine Teekanne', data)
return
connection.send_back('Bitte nutze .drink um dir selbst ein Getränk zu besorgen', data)
return
if len(data['message'].split()) < 3:
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(getraenkegoodones) + '. Schöne Grüße von ' + data[
'nick'] + '\001', data)
return
type = data['message'].split()[2]
if type is not None:
matchingDrinks = []
for drink in getraenkegoodones:
if type.lower() in drink.lower():
matchingDrinks.append(drink)
if matchingDrinks:
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(matchingDrinks) + '. Schöne Grüße von ' + data[
'nick'] + '\001', data)
return
if type.lower() == "drink":
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(getraenke) + '. Schöne Grüße von ' +
data[
'nick'] + '\001', data)
return
if type.lower() == "food":
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(essen) + '. Schöne Grüße von ' +
data[
'nick'] + '\001', data)
return
if type.lower() == "cookie":
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(kekse) + '. Schöne Grüße von ' +
data[
'nick'] + '\001', data)
return
if type.lower() == "snack":
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(snacks) + '. Schöne Grüße von ' +
data[
'nick'] + '\001', data)
return
if type.lower() == "massage":
connection.send_back(
'\001ACTION knetet ' + receiver + ' feste den Rücken durch. ' +
data[
'nick'] + ' meinte ich solle dir was gutes tun. \001', data)
return
for drink in getraenke+essen+icecream+giveextras+snacks:
if type.lower() in drink.lower():
matchingDrinks.append(drink)
if matchingDrinks:
connection.send_back(
'\001ACTION serviert ' + receiver + ' ' + random.choice(matchingDrinks) + '. Schöne Grüße von ' +
data[
'nick'] + '\001', data)
return
else:
connection.send_back(
'Tut mir leid ' + data['nick'] + ', '+ type+' haben wir nicht auf der Karte!', data)
return
connection.send_back('\001ACTION serviert ' + receiver + ' ' + random.choice(getraenkegoodones) + '. Schöne Grüße von '+data['nick']+'\001', data)

View File

@@ -0,0 +1,20 @@
import random
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from essen import essen
class GiveFoodObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".food"]
@staticmethod
def help():
return ".food - gibt etwas zu essen aus"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.food') == -1:
return
connection.send_back('\001ACTION tischt ' + data['nick'] + ' ' + random.choice(essen) + ' auf.\001', data)

View File

@@ -0,0 +1,20 @@
import random
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from icecreamlist import icecream
class GiveIceObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".ice"]
@staticmethod
def help():
return ".ice - schenkt Eis"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.ice') == -1:
return
connection.send_back('\001ACTION serviert ' + data['nick'] + ' ' + random.choice(icecream) + '.\001', data)

View File

@@ -0,0 +1,36 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.i18n import i18n
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class GoogleObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.g') == -1:
return
i18n_server = i18n()
lang = i18n_server.get_text('google_lang')
t = i18n_server.get_text('google_tld')
q = data['message'].split(' ')
query = ''
for word in q:
if word.strip() != '.g':
query += word + ' '
# g = google.search(query, tld=t, lang=lang, num=1, start=0, stop=0, pause=2.0)
# s = next(g)
# print(s)
# Connection.singleton().send_channel(g)
# if g has nonzero results:
# Connection.singleton().send_channel(data['nick'] + ', ' + i18n_server.get_text('google_fail'))
# return
# Connection.singleton().send_channel(data['nick'] + ' ' + gefundenes erstes result)
# Connection.singleton().send_channel(title von dem link)
pass

View File

@@ -0,0 +1,31 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.JoinObserverPrototype import JoinObserverPrototype
import time
from collections import defaultdict
class Greeter(JoinObserverPrototype):
"""
A Class only reacting to pings
"""
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def __init__(self):
super().__init__()
self.names = defaultdict(int)
def update_on_join(self, data, connection: Connection):
if data['channel'] == connection.details.get_channel():
if int(time.time()) - self.names[data['nick']] > 28800:
if data['nick'].find("Neuling") != -1:
connection.send_back("Herzlich Willkommen bei uns "+data['nick'],data)
self.names[data['nick']] = int(time.time())
return
connection.send_back("Hallo " + data['nick'], data)
self.names[data['nick']] = int(time.time())

View File

@@ -0,0 +1,294 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from FaustBot.Model.ScoreProvider import ScoreProvider
from FaustBot.Model.HanDatabaseProvider import HanDatabaseProvider
from collections import defaultdict
from threading import Lock
import csv
import random
import time
import datetime
class HangmanObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return ['.guess', '.word', '.stop', '.hint', '.score', '.spielregeln']
@staticmethod
def help():
return 'hangman game'
def __init__(self):
super().__init__()
HangmanObserver.lock = Lock()
self.word = ''
self.guesses = ['-', '/', ' ', '_','.']
self.tries_left = 0
self.wrong_guessed = []
self.worder = ''
self.wrongly_guessedWords = []
self.time = time.time()
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.guess ') != -1:
self.guess(data, connection)
return
if data['message'].find('.word ') != -1:
self.take_word(data, connection)
if data['message'].find('.han') != -1 and not data['message'].find('.handelete')!= -1 and not data['message'].find('hanadd'
) != -1:
self.start_solo_game(data, connection)
if data['message'].find('hanadd') != -1:
self.han_user_add(data, connection)
if data['message'].find('.stop') != -1 and not data['message'].find('.stophunt') != -1 \
and not data['message'].find('.stopMath') != -1:
connection.send_channel("Spiel gestoppt. Das Wort war: " + self.word + " in: "+self.timeRelapsedString())
self.word = ''
self.guesses = []
self.tries_left = 0
self.wrong_guessed = []
self.worder = ''
self.wrongly_guessedWords = []
self.worder = ''
if data['message'].find('.hint') != -1:
self.hint(data, connection)
if data['message'].find('.score') != -1:
self.print_score(data, connection)
if data['message'].find('.spielregeln') != -1:
self.rules(data, connection)
if data['message'].find('.look') != -1:
self.look(data, connection)
if data['message'].find('.resetscore') != -1:
self.reset(data,connection)
if data['message'].find('.handelete') != -1:
self.delete_HanWord(data, connection)
def delete_HanWord(self,data,connection):
if not self._is_idented_mod(data, connection):
connection.send_back(
"Du hast keine Berechtigung Wörter zu löschen " + data['nick'], data)
return
if data['message'].split(' ')[1] is not None:
self.deleteHanWord(data['message'].split(' ')[1].upper())
connection.send_back("Das Wort "+data['message'].split(' ')[1].upper()+" wurde gelöscht, " + data['nick'], data)
def reset(self,data,connection):
score_provider = ScoreProvider()
score_provider.delete_score(data['nick'])
connection.send_back("Dein Score wurde gelöscht "+data['nick'], data)
def look(self,data, connection):
if self.worder != '':
connection.send_channel("Das Wort kommt von: "+self.worder )
connection.send_channel(self.prepare_word(data))
self.hint(data,connection)
def print_score(self, data, connection):
punkte = self.getScore(data['nick'])
connection.send_back(data['nick']+" hat einen Hangman-Score von: " + str(punkte), data)
def hint(self, data, connection):
wrongGuessesString = ""
if len(self.wrong_guessed) == 0 and len(self.wrongly_guessedWords) == 0:
wrongGuessesString = "Noch keine falschen Buchstaben."
if len(self.wrong_guessed) > 0:
wrongGuessesString += "Falsch geratene Buchstaben bis jetzt: "
for w in self.wrong_guessed:
if w == self.wrong_guessed[0]:
wrongGuessesString += w
else:
wrongGuessesString += ", " + w
# Append wrongly guessed words
for w in self.wrongly_guessedWords:
if w == self.wrongly_guessedWords[0]:
if len(self.wrong_guessed) > 0:
wrongGuessesString += " | "
wrongGuessesString += "Falsche Wörter: " + w
else:
wrongGuessesString += ", " + w
if self.worder == "":
wrongGuessesString = ""
else:
connection.send_back(wrongGuessesString, data)
def start_solo_game(self, data, connection):
if self.word == '':
self.time = time.time()
self.word = self.getRandomHanWord()
self.guesses = ['-', '/', ' ', '_','.']
self.wrong_guessed = []
self.tries_left = 11
self.wrongly_guessedWords = []
connection.send_channel("Automatisch gewähltes Wort")
self.worder = "Botty"
connection.send_channel(self.prepare_word(data))
else:
connection.send_back("Sorry es läuft bereits ein Wort", data)
def guess(self, data, connection):
if data['channel'] != connection.details.get_channel():
connection.send_back("Sorry kein raten im Query", data)
return
guess = data['message'].split(' ')[1].upper()
if self.tries_left < 1:
connection.send_channel("Flüstere mir ein neues Wort mit .word WORT")
return
word_unique_chars = len(set(self.word))
if guess == self.word:
score = word_unique_chars * self.count_missing_unique()
self.addToScore(data['nick'], int(score))
self.word = ''
self.worder = ''
connection.send_channel("Das ist korrekt: " + guess + " gelöst hat: "+data["nick"]+ " in: "+self.timeRelapsedString())
self.giveExtraPointsInTime(data["nick"])
return
if guess in self.word:
if guess not in self.guesses:
score = word_unique_chars / 2
self.addToScore(data['nick'], int(score))
self.guesses.append(guess)
else:
self.tries_left -= 1
punishment_factor = 1
if guess in self.guesses:
punishment_factor = 2
self.addToScore(data['nick'], -1)
#(int((word_unique_chars / 20) * punishment_factor * 10))
# append thread safe wrongly guessed characters and words
HangmanObserver.lock.acquire()
try:
if guess not in self.wrong_guessed:
if len(guess) == 1:
self.wrong_guessed.append(guess)
else:
self.wrongly_guessedWords.append(guess)
finally:
HangmanObserver.lock.release()
connection.send_channel(self.prepare_word(data))
def take_word(self, data, connection):
if self.word == '':
self.time =time.time()
if data['message'].split(' ')[1] is not None:
self.addHanWord(data['message'].split(' ')[1].upper())
log = open('HangmanLog', 'a')
log.write(data['nick'] + ' ; ' + data['message'].split(' ')[1].upper() + '\n')
log.close()
self.word = data['message'].split(' ')[1].upper()
self.guesses = ['-', '/', ' ', '_','.']
self.wrong_guessed = []
self.tries_left = 11
self.wrongly_guessedWords = []
connection.send_back("Danke für das Wort, es ist nun im Spiel!", data)
connection.send_channel("Das Wort ist von: "+data['nick'])
self.worder = data['nick']
connection.send_channel(self.prepare_word(data))
else:
connection.send_back("Sorry es läuft bereits ein Wort", data)
def han_user_add(self, data, connection):
if data['message'].split(' ')[1] is not None:
self.addHanWord(data['message'].split(' ')[1].upper())
connection.send_channel("Das Wort "+data['message'].split(' ')[1].upper() +" wurde von "+ data['nick']+ " hinzugefügt")
def prepare_word(self, data):
outWord = ""
failedChars = 0
for char in self.word:
if char in self.guesses:
outWord += char + " "
else:
outWord += "_ "
failedChars += 1
if failedChars == 0:
if len(self.word) > 0:
outWord = "Das ist korrekt: " + self.word + " gelöst hat: "+data["nick"]+ " in : "+self.timeRelapsedString()
self.giveExtraPointsInTime(data["nick"])
self.addToScore(data['nick'], 5)
self.word = ''
self.worder = ''
return outWord
else:
outWord = "Bitte gib ein neues Wort mit .word im Query an."
return outWord
if self.tries_left == 0:
self.addToScore(self.worder,11)
outWord = "Das richtige Wort wäre gewesen: " + self.word + " in: "+self.timeRelapsedString()
self.word = ''
self.worder = ''
return outWord
outWord += "Verbleibende Rateversuche: "+str(self.tries_left)
return outWord
def count_missing(self):
missing_chars = 0
for char in self.word:
if char not in self.guesses:
missing_chars += 1
return missing_chars
def count_missing_unique(self):
return len(set(self.word) - set(self.guesses))
def rules(self, data, connection):
if data['channel'] == connection.details.get_channel():
connection.send_back("Spielregeln bitte im Query abfragen",data)
return
connection.send_back("""Wort starten mit ".word Wort" im Query mit dem Bot""", data)
connection.send_back("""Raten mit ".guess Buchstabe" im Channel""", data)
connection.send_back("""Geraten werden können einzelne Buchstaben oder das ganze Wort.""", data)
connection.send_back("""Alle dürfen durcheinander raten. Es gibt keine Reihenfolge.""", data)
connection.send_back("""".hint" gibt alle bereits falsch geratenen Buchstaben aus.""", data)
connection.send_back("""Bei 2 verbleibenden Versuchen darf nach einem Tipp vom Steller des Wortes gefragt
werden.""", data)
connection.send_back("""Wer ein Wort errät, darf das nächste stellen.""", data)
connection.send_back("""Wird ein Wort nicht gelöst, darf derjenige, der es gestellt hat, nochmal.""", data)
connection.send_back("""Zulässig sind alle Wörter, die deutsch oder im deutschen Sprachraum geläufig sind.""", data)
def getScore(self, nick:str):
score_provider = ScoreProvider()
score = score_provider.get_score(nick)
if score is not None:
return score[1]
else:
return 0
def writeScore(self, nick:str, score:int):
score_provider = ScoreProvider()
score_provider.save_or_replace(nick, score)
def addToScore(self, nick:str, add_score: int):
score = self.getScore(nick)
self.writeScore(nick, score + add_score)
def addHanWord(self, hanWord:str):
hanDB = HanDatabaseProvider()
hanDB.addWord(hanWord.strip().upper())
def getRandomHanWord(self):
hanDB = HanDatabaseProvider()
word = hanDB.get_random_word()
if word is not None:
return word[0].upper()
else:
return "dummywort".upper()
def deleteHanWord(self, hanWord:str):
hanDB = HanDatabaseProvider()
hanDB.delete_hanWord(hanWord.strip().upper())
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])
def timeRelapsedString(self):
delta = time.time()-self.time
return str(datetime.timedelta(seconds= delta))
def giveExtraPointsInTime(self, nick):
delta = time.time()-self.time
if delta <30:
self.addToScore(nick, 5)
if delta <60:
self.addToScore(nick, 5)

View File

@@ -0,0 +1,32 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class HelpObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".help"]
@staticmethod
def help():
return ".help - zeigt Hilftexte aller Module an"
def update_on_priv_msg(self, data, connection: Connection):
msg = data["message"]
if not msg.startswith(".help"):
return
if data["channel"] == connection.details.get_channel():
all_cmd = []
for observer in connection.priv_msg_observable.get_observer():
cmds = observer.cmd()
if cmds is not None:
all_cmd.extend(cmds)
msg = ", ".join(all_cmd)
msg = "Bekannte Befehle: " + msg + ". Für Details per Query .help ."
connection.send_back(msg, data)
else:
all_help = [m.help() for m in connection.priv_msg_observable.get_observer()]
for help_msg in all_help:
if help_msg is not None:
connection.send_back(help_msg, data)

View File

@@ -0,0 +1,27 @@
import re
from FaustBot.Communication import Connection
from FaustBot.Modules.NoticeObserverPrototype import NoticeObserverPrototype
class IdentNickServObserver(NoticeObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_notice(self, data, connection: Connection):
# b':NickServ!NickServ@services. NOTICE FaustBotDev :corvidae ACC 3 \r\n'
if not data['nick'].lower() == 'nickserv':
return
with connection.condition_lock:
if re.match(r'.*? ACC [0-3].*', data['message']):
msg_parts = data['message'].split(' ')
if msg_parts[2] == '3':
connection.idented_look_up[msg_parts[0]] = True
else:
connection.idented_look_up[msg_parts[0]] = False
connection.condition_lock.notify_all()

View File

@@ -0,0 +1,54 @@
from FaustBot.Communication import Connection
from FaustBot.Model.Introduction import IntroductionProvider
from FaustBot.Modules import UserList
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class IntroductionObserver(PrivMsgObserverPrototype):
def __init__(self, user_list: UserList):
super().__init__()
self.userList = user_list
@staticmethod
def cmd():
return [".me"]
@staticmethod
def help():
return ".me - kann von registrierten Nutzern verwendet werden um eine Vorstellung zu speichern"
def update_on_priv_msg(self, data, connection: Connection):
msg = data["message"]
nick = data["nick"]
if not msg.startswith(".me") and not msg.startswith(".me-"):
return
if not self.authenticated(nick, connection):
connection.send_back("Für die Nutzung von .me ist es zwingend erforderlich, einen registrierten Nick zu "
"haben sowie eingeloggt zu sein. Wie dies geht, erfährst du unter "
"https://freenode.net/kb/answer/registration", data)
return
intro_provider = IntroductionProvider()
msg = msg.split('.me')[1].strip()
if len(msg) == 0:
intro = intro_provider.get_intro(nick)
text = ""
if intro is not None:
text = nick + " ist " + intro[1]
else:
text = nick + " für dich gibt es noch keinen Eintrag, vielleicht magst du ja mittels .me <intro> noch " \
"einen hinzufügen? "
connection.send_back(text, data)
elif len(msg) == 1 and '-' in msg:
intro_provider.delete_intro(nick)
connection.send_back(nick + " dein Intro wurde gelöscht!", data)
else:
intro = msg.strip()
intro_provider.save_or_replace(nick, intro)
connection.send_back(
nick + ": Dein Intro wurde gespeichert! Mittels .me- kannst du deinen Eintrag wieder löschen.", data)
text = nick + " ist " + intro_provider.get_intro(nick)[1]
connection.send_back(text, data)
def authenticated(self, nick: str, connection: Connection):
return nick in self.userList.userList and \
connection.is_idented(nick)

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class JoinObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_JOIN]
def __init__(self):
super().__init__()
def update_on_join(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,209 @@
import random
import time
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
jokes = [['Was ist orange und geht über die Berge?'
,'Eine Wanderine.']
,['Was ist orange und schaut durchs Schlüsselloch?'
,'Eine Spannderine.']
,['Was ist violett und sitzt in der Kirche ganz vorne?'
,'Eine Frommbeere.']
,['Was ist grün und liegt im Sarg?'
,'Ein Sterbschen.']
,['Was ist bunt und läuft über den Tisch davon?'
,'Ein Fluchtsalat.']
,['Was ist braun und schwimmt im Wasser?'
,'Ein U-Brot.']
,['Was ist schwarz/weiß und hüpft von Eisscholle zu Eisscholle?'
,'Ein Springuin.']
,['Was ist rot und sitzt auf dem WC?'
,'Eine Klomate!']
,['Was ist braun und fährt einen verschneiten Hang hinunter?'
,'Ein Snowbrot.']
,['Was ist braun und späht durchs Schlafzimmerfenster?'
,'Ein Spannzapfen.']
,['Was ist weiß und springt im Wald umher?'
,'Ein Jumpignon.']
,['Was ist braun, süß und rennt durch den Wald?'
,'Eine Joggolade.']
,['Was ist braun und sitzt hinter Gittern?'
,'Eine Knastanie.']
,['Was ist rot, rund und hat ein Maschinengewehr?'
,'Ein Rambodischen.']
,['Was ist braun, knusprig und läuft mit dem Korb durch den Wald?'
,'Brotkäppchen.']
,['Was ist braun, klebrig und läuft in der Wüste umher?'
,'Ein Karamel.']
,['Was ist rot, sitzt in einer Konservendose und spielt Musik?'
,'Ein Radioli.']
,['Was ist grün und radelt durch die Gegend?'
,'Eine Velone.']
,['Was ist orange, tiefergelegt und hat einen Spoiler?'
,'Ein Mantarinchen']
,['Was ist gelb, krumm und schwimmt auf dem Wasser?'
,'Eine Schwanane']
,['Was ist orange und steckt traurig in der Erde?'
,'Ein Trübchen.']
,['Was ist orange, sauer und kann keine Minute ruhig sitzen?'
,'Eine Zappelsine.']
,['Was ist haarig und wird in der Pfanne frittiert?'
,'Bartkartoffeln.']
,['Was ist gesund und kräftig und spielt den Beleidigten?'
,'Ein Schmollkornbrot.']
,['Was steht im Schlafzimmer des Metzgers neben dem Bett?'
,'Ein Schlachttischlämpchen.']
,['Was ist grün, sauer und versteckt sich vor der Polizei?'
,'Ein Essig-Schurke.']
,['Was ist orange, rund und versteckt sich vor der Polizei?'
,'Ein Vandalinchen.']
,['Was ist grün und schaut durchs Schlüsselloch?'
,'Ein Spionat']
,['Was ist groß, grau und telefoniert aus Afrika?'
,'Ein Telefant.']
,['Was ist gelb und flattert im Wind?'
,'Eine Fahnane.']
,['Was ist grün und klopft an die Tür?'
,'Ein Klopfsalat.']
,['Was ist braun, sehr zäh und fliegt umher?'
,'Eine Ledermaus.']
,['Was macht "Muh" und hilft beim Anziehen?'
,'Ein Kuhlöffel.']
,['Was ist viereckig, hat Noppen und einen Sprachfehler?'
,'Ein Legosteniker.']
,['Was ist gelb und immer bekifft?'
,'Ein Bong-Frites.']
,['Was ist grün, glücklich und hüpft von Grashalm zu Grashalm?'
,'Eine Freuschrecke.']
,['Was ist ist braun, hat einen Beutel und hängt am Baum?'
,'Ein Hänguruh.']
,['Was ist orange-rot und riskiert alles?'
,'Eine Mutorange']
,['Was ist gelb, ölig und und sitzt in der Kirche in der ersten Reihe?'
,'Eine Frommfrites']
,['Was ist grün und irrt durch Istanbul?'
,'Ein Gürke']
,['Was ist hellbraun und hangelt sich von Tortenstück zu Tortenstück?'
,'Ein Tarzipan.']
,['Was ist braun und klebt an der Wand?'
,'Ein Klebkuchen']
,['Was ist rot und läuft die Straße auf und ab?'
,'Eine Hagenutte.']
,['Was ist weiss und läuft die Straße auf und ab?'
,'Schneeflittchen.']
,['Was ist grün und läuft die Straße auf und ab?'
,'Eine Frosch-tituierte.']
,['Was ist braun und trägt Strapse?'
,'Ein Haselnüttchen.']
,['Was ist gelb und steht frankiert und abgestempelt am Strassenrand?'
,'Eine Postituierte.']
,['Was leuchtet und geht fremd?'
,'Ein Schlampion.']
,['Was ist gelb und rutscht den Hang hinunter?'
,'Ein Cremeschlitten.']
,['Was ist weiss und tanzt ums Feuer?'
,'Rumpelpilzchen.']
,['Was ist weiss und liegt schnarchend auf der Wiese?'
,'Ein Schlaf.']
,['Was ist gelb, saftig und sitzt bei jedem Fussballspiel vor dem Fernseher?'
,'Eine Fananas.']
,['Was ist rosa und schwimmt im Wasser?'
,'Eine Meerjungsau.']
,['Was ist durchsichtig, stinkt und es ist ihm alles egal?'
,'Ein Schnurz.']
,['Was ist unordentlich und gibt Licht?'
,'Eine Schlampe.']
,['Was ist blöd, süß und bunt?'
,'Ein Dummibärchen.']
,['Was trägt einen Frack und hilft im Haushalt?'
,'Ein Diener Schnitzel.']
,['Was ist silbrig, sticht und hat Spass daran?'
,'Eine Sadistel.']
,['Was ist gelb und kann schießen?'
,'Eine Banone']
,['Was kommt nach Elch?'
,'Zwölch']
,['Was liegt am Strand und spricht undeutlich?'
,'Eine Nuschel']
,['Was hüpft über die Wiese und raucht?'
,'Ein Kaminchen']
,['Was ist knusprig und liegt unterm Baum?'
,'Schattenplätzle']
,['Kleines Schwein das nach Hilfe schreit?'
,'Ein Notrufsäule']
,['Was liegt am Strand und hat Schnupfen?'
,'Eine Niesmuschel']
,['Was ist ein Cowboy ohne Pferd?'
,'Ein Sattelschlepper']
,['Was ist grün und trägt Kopftuch?'
,'Eine Gürkin']
,['Was ist rot und sitzt unterm Tisch?'
,'Ne Paprikantin']
,['Was ist schwarz-weiß und kommt nicht vom Fleck?'
,'Ein Klebra']
,['Was ist rosa, quiekt und wird zum Hausbau verwendet?'
,'Ein Ziegelschwein']
,['Wer ist bei jeder Wanderung betrunken?'
,'Der Schlucksack']
,['Was ist rot und wiehert?'
,'Die Pferdbeere']
,['Was ist weiß, blau, grün und steht auf der Wiese?'
,'Eine Schlumpfdotterblume']
,['Was kaut und hat immer Verspätung?'
,'Die Essbahn']
,['Was fährt unter der Erde und macht Muh?'
,'Die Kuhbahn']
,['Was wühlt den Himmel auf?'
,'Ein Pflugzeug']
,['Welche Frucht wächst im Gerichtssaal?'
,'Advokado']
,['Wie nennt man einen “scharfen” Mann mit Kilt?'
,'Chilischotte']
,['Was lebt im Meer und kann gut rechnen?'
,'Der Octoplus']
,['Was ist tiefergelegt und schwimmt unter wasser?'
,'Der Tunefisch']
,['Was ist unter der Erde und stinkt?'
,'Eine Furzel']
,['Von was wird man nachts beobachtet?'
,'Vom Spannbettlaken']
,['Wo wohnen die meisten Katzen?'
,'Im Miezhaus']
,['Warum ging der Luftballon kaputt?'
,'Aus Platzgründen']
,['Wie nennt man einen ausgehungerten Frosch?'
,'Magerquak']
,['Was macht ein Dieb im Zirkus?'
,'Clown']
,['Was macht ein Clown im Büro?'
,'Faxen']
,['Wie nennt man eine Zauberin in der Wüste?'
,'Sand Witch']
,['Wo betrinkt sich eine Mücke?'
,'In Sekt']
,['Warum können Seeräuber keine Kreise berechnen?'
,'Weil sie pi raten']
,['Was sitzt in der Savanne und wäscht sich?'
,'Die Hygiäne']
,['Was sitzt im Dschungel und spielt unfair?'
,'Mogli']
,['Wie nennt man den Paarungsruf von Leutstofflampen?'
,'Neonröhren']]
class JokeObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".joke"]
@staticmethod
def help():
return ".joke erzählt einen Flachwitz"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.joke') == -1:
return
joke = random.choice(jokes)
connection.send_back(joke[0], data)
time.sleep(30)
connection.send_back(joke[1], data)

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class KickObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_KICK]
def __init__(self):
super().__init__()
def update_on_kick(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,53 @@
import random
import time
from collections import defaultdict
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.UserList import UserList
from getraenke import getraenke
from essen import essen
from icecreamlist import icecream
from ..Modules.PingObserverPrototype import PingObserverPrototype
class Kicker(PingObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def __init__(self, user_list: UserList, idle_time: int):
super().__init__()
self.idle_time = idle_time
self.user_list = user_list
self.warned_users = defaultdict(int)
def update_on_ping(self, data, connection: Connection):
for user in self.user_list.userList.keys():
offline_time = Kicker.get_offline_time(user)
if offline_time < self.idle_time:
self.warned_users[user] = 0
host = self.user_list.userList.get(user).host
if offline_time > self.idle_time \
and not user == connection.details.get_nick() \
and 'freenode/staff' not in host and 'freenode/utility-bot' not in host:
if self.warned_users[user] % 30 == 0:
connection.send_channel(
'\001ACTION serviert ' + user + ' ' + random.choice(getraenke+essen+icecream) + '.\001')
self.warned_users[user] += 1
if self.warned_users[user] % 29 == 0:
connection.raw_send("KICK " + connection.details.get_channel() + " " + user +
" :Zu lang geidlet, komm gerne wieder!")
@staticmethod
def get_offline_time(nick):
who = nick
user_provider = UserProvider()
activity = user_provider.get_activity(who)
delta = time.time() - activity
return delta

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class LeaveObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_LEAVE]
def __init__(self):
super().__init__()
def update_on_leave(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,18 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class LoveAndPeaceObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".peace"]
@staticmethod
def help():
return ".peace - sorgt für Frieden"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.peace') == -1:
return
connection.send_back('\001ACTION hüpft durch den Raum, schmeißt Blumen um sich und singt: \"Love and '
'Peace, wir haben uns alle lieb..!\".\001', data)

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class MagicNumberObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to server actions
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_MAGIC_NUMBER]
def __init__(self):
super().__init__()
def update_on_magic_number(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,76 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from random import randrange
from time import sleep
class MathRunObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return ['.s', '.startMath', '.stopMath']
@staticmethod
def help():
return 'startMath startet eine Reihe von Aufgaben. StopMath beendet sie.'
def __init__(self):
super().__init__()
self.players = {}
self.solutionForGame = 0
self.type = 0
self.running = False
self.oldSolution = 0
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.s ') != -1 :
self.solution(data, connection)
if data['message'].find('.startMath') != -1:
self.start_math(data, connection)
def solution(self, data, connection):
nick = data["nick"]
solutionByPlayer = data['message'].split()[1]
if solutionByPlayer is None:
connection.send_back("Sorry du hast keine Lösung angegeben " + nick, data)
return
if solutionByPlayer == str(self.solutionForGame):
connection.send_channel("Korrekte Lösung " + nick)
if nick not in self.players:
self.players[nick] = 0
self.players[nick] += 1
self.oldSolution = self.solutionForGame
self.start_math(data, connection)
return
if solutionByPlayer == str(self.oldSolution):
connection.send_channel("Korrekte Lösung für das Problem davor " + nick)
if nick not in self.players:
self.players[nick] = 0
self.players[nick] += 1
return
connection.send_channel("Sorry die Lösung ist falsch "+nick )
def start_math(self, data, connection):
summand1 = randrange(1,100)
summand2 = randrange(1,11)
operation = randrange(1,3)
if operation == 1:
self.solutionForGame = summand1 - summand2
connection.send_channel(str(summand1) +" - "+str(summand2) +" = ?")
if operation == 2:
self.solutionForGame = summand1 + summand2
connection.send_channel(str(summand1) +" + "+str(summand2) +" = ?")
if not self.running:
self.running = True
self.stop_Timer(data, connection)
def stop_math(self, data, connection):
for player in self.players.keys():
connection.send_channel(player + " hat\t" + str(self.players[player]) + "\t Punkte")
connection.send_channel("Spiel beendet")
self.players = {}
self.solutionForGame = 0
self.type = 0
self.running = False
def stop_Timer(self, data, connection):
sleep(120)
self.stop_math(data, connection)

View File

@@ -0,0 +1,23 @@
class ModulePrototype(object):
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def get_module_types():
raise NotImplementedError("This method needs to be implemented by a subclass!")
@staticmethod
def help():
raise NotImplementedError("Needs to be implemented by subclasses")
def __init__(self):
self._config = None
@property
def config(self):
return self._config
@config.setter
def config(self, value):
self._config = value

View File

@@ -0,0 +1,12 @@
from enum import Enum
class ModuleType(Enum):
ON_JOIN = 'ON_JOIN'
ON_KICK = 'ON_KICK'
ON_LEAVE = 'ON_LEAVE'
ON_PING = 'ON_PING'
ON_NICK_CHANGE = 'ON_NICK_CHANGE'
ON_MSG = 'ON_MSG'
ON_NOTICE = 'ON_NOTICE'
ON_MAGIC_NUMBER = 'ON_MAGIC_NUMBER'

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class NickChangeObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_NICK_CHANGE]
def __init__(self):
super().__init__()
def update_on_nick_change(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,23 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class NoticeObserverPrototype(ModulePrototype):
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_NOTICE]
def __init__(self):
super().__init__()
def update_on_notice(self, data, connection: Connection):
raise NotImplementedError('Needs to be implemented by csubclasses!')

View File

@@ -0,0 +1,17 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class PartyObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".party"]
@staticmethod
def help():
return ".party - sorgt für Konfetti"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.party') == -1:
return
connection.send_back('\001ACTION schmeißt mit Konfetti aus buntem Esspapier um sich.\001', data)

View File

@@ -0,0 +1,21 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
class ModulePing(PingObserverPrototype):
"""
A Class only reacting to pings
"""
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_ping(self, data, connection: Connection):
# print('Module Ping')
msg = 'PONG ' + data['server']
connection.raw_send(msg)

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class PingObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_PING]
def __init__(self):
super().__init__()
def update_on_ping(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,17 @@
from FaustBot.Communication import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class PrideObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".pride"]
@staticmethod
def help():
return ".party - sorgt für sehr viele Pride Flags"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.pride') == -1:
return
connection.send_back('\001ACTION schmückt den Channel mit ganz vielen großen Pride Flaggen.\001', data)

View File

@@ -0,0 +1,27 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.ModulePrototype import ModulePrototype
from FaustBot.Modules.ModuleType import ModuleType
class PrivMsgObserverPrototype(ModulePrototype):
"""
The Prototype of a Class who can react to every action
"""
@staticmethod
def cmd():
raise NotImplementedError()
@staticmethod
def help():
raise NotImplementedError("Need sto be implemented by subclasses!")
@staticmethod
def get_module_types():
return [ModuleType.ON_MSG]
def __init__(self):
super().__init__()
def update_on_priv_msg(self, data, connection: Connection):
raise NotImplementedError("Some module doesn't do anything")

View File

@@ -0,0 +1,34 @@
import datetime
import time
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from ..Model.i18n import i18n
class SeenObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".seen"]
@staticmethod
def help():
return ".seen <nick> - um abzufragen wann <nick> zuletzt hier war"
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.seen ') == -1:
return
if not self._is_idented_mod(data, connection):
return
who = data['message'].split(' ')[1]
user_provider = UserProvider()
activity = user_provider.get_activity(who)
output = data['nick']+": Ich habe "+who+" zuletzt am "+str(datetime.datetime.fromtimestamp(activity).strftime("%d.%m.%Y um %H:%M:%S"))+ ' Uhr gesehen'
if not self._is_idented_mod(data, connection):
connection.send_channel(output)
return
connection.send_back(output, data)
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,20 @@
import random
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from snacks import snacks
class SnacksObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".snack"]
@staticmethod
def help():
return ".snack - teilt Snacks aus"
def update_on_priv_msg(self, data: dict, connection: Connection):
if data['message'].find('.snack') == -1:
return
connection.send_back('\001ACTION serviert ' + data['nick'] + ' ' + random.choice(snacks) + '.\001', data)

View File

@@ -0,0 +1,20 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class TellObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.tell') != -1 and self._is_idented_mod(data, connection):
connection.send_channel(data['message'][6:])
def _is_idented_mod(self, data: dict, connection: Connection):
return data['nick'] in self._config.mods and connection.is_idented(data['nick'])

View File

@@ -0,0 +1,53 @@
import html
import re
import urllib
from urllib import request
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class TitleObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def update_on_priv_msg(self, data, connection: Connection):
regex = "(?P<url>https?://[^\s]+)"
url = re.search(regex, data['message'])
if url is not None:
url = url.group()
print(url)
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
url = url
req = urllib.request.Request(url, None, headers)
resource = urllib.request.urlopen(req)
title = self.getTitle(resource)
print(title)
title = title[:350]
connection.send_back(title, data)
except Exception as exc:
print(exc)
pass
def getTitle(self, resource):
encoding = resource.headers.get_content_charset()
# der erste Fall kann raus, wenn ein anderer Channel benutzt wird
if resource.geturl().find('rehakids.de') != -1:
encoding = 'windows-1252'
if not encoding:
encoding = 'utf-8'
content = resource.read().decode(encoding, errors='replace')
title_re = re.compile("<title>(.+?)</title>")
title = title_re.search(content).group(1)
title = html.unescape(title)
title = title.replace('\n', ' ').replace('\r', '')
title = title.replace("&lt;", "<")
title = title.replace("&gt;", ">")
title = title.replace("&amp;", "&")
return title

View File

@@ -0,0 +1,56 @@
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.JoinObserverPrototype import JoinObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from ..Modules.KickObserverPrototype import KickObserverPrototype
from ..Modules.LeaveObserverPrototype import LeaveObserverPrototype
from ..Modules.NickChangeObserverPrototype import NickChangeObserverPrototype
class UserList(JoinObserverPrototype, KickObserverPrototype, LeaveObserverPrototype, NickChangeObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def __init__(self):
super().__init__()
self.userList = {}
@staticmethod
def get_module_types():
return [ModuleType.ON_JOIN, ModuleType.ON_KICK, ModuleType.ON_LEAVE, ModuleType.ON_NICK_CHANGE]
def update_on_kick(self, data, connection):
if data['nick'] in self.userList:
del self.userList[data['nick']]
# print(self.userList)
def update_on_leave(self, data, connection):
if data['nick'] in self.userList:
del self.userList[data['nick']]
# print(self.userList)
def update_on_join(self, data, connection):
self.userList[data['nick']] = RemoteUser(data['nick'], data['user'], data['host'])
# print(self.userList)
def update_on_nick_change(self, data, connection):
if data['old_nick'] in self.userList:
remuser = self.userList[data['old_nick']]
del self.userList[data['old_nick']]
else:
# shouldn't happen but let's be safe.
remuser = RemoteUser('UN.KNOWN', 'UN.KNOWN', 'UN.KNOWN')
remuser.nick = data['new_nick']
self.userList[data['new_nick']] = remuser
# print(self.userList)
def clear_list(self):
self.userList = {}
def add_user(self, remuser):
self.userList[remuser.nick] = remuser

View File

@@ -0,0 +1,51 @@
from FaustBot.Communication import Connection
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from FaustBot.Modules.UserList import UserList
import time
class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def __init__(self, user_list: UserList):
super().__init__()
self.user_list = user_list
self.pings_seen = 1
self.pending_whos = []
@staticmethod
def get_module_types():
return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING]
def update_on_magic_number(self, data, connection):
if data['number'] == '352': # RPL_WHOREPLY
self.input_who(data, connection)
elif data['number'] == '315': # RPL_ENDOFWHO
#make sure other thread runs to its end.
time.sleep(10)
self.end_who()
def input_who(self, data, connection: Connection):
# target #channel user host server nick status :0 gecos
target, channel, user, host, server, nick, *ign = data['arguments'].split(' ')
self.pending_whos.append(RemoteUser(nick, user, host))
def end_who(self):
self.user_list.clear_list()
for remuser in self.pending_whos:
self.user_list.add_user(remuser)
self.pending_whos = []
def update_on_ping(self, data, connection: Connection):
if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden
connection.raw_send('WHO ' + connection.details.get_channel())
self.pings_seen += 1

View File

@@ -0,0 +1,45 @@
from wikipedia import wikipedia
from FaustBot.Model.i18n import i18n
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class WikiObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return [".w"]
@staticmethod
def help():
return ".w <term> - fragt Wikipediaartikel zu <term> ab"
def update_on_priv_msg(self, data, connection):
if data['message'].find('.w ') == -1:
return
i18n_server = i18n()
w = wikipedia.set_lang(i18n_server.get_text('wiki_lang', lang=self.config.lang))
q = data['message'].split(' ')
query = ''
for word in q:
if word.strip() != '.w':
query += word + ' '
w = wikipedia.search(query)
if w.__len__() == 0: # TODO BUG BELOW, ERROR MESSAGE NOT SHOWN!
connection.send_back(data['nick'] + ', ' +
i18n_server.get_text('wiki_fail',
lang=self.config.lang),
data)
return
try:
page = wikipedia.WikipediaPage(w.pop(0))
except wikipedia.DisambiguationError as error:
print('disambiguation page')
page = wikipedia.WikipediaPage(error.args[1][0])
connection.send_back(data['nick'] + ' ' + page.url, data)
index = 51 + page.summary[50:350].rfind('. ')
if index == 50 or index > 230:
index = page.summary[0:350].rfind(' ')
connection.send_back(page.summary[0:index], data)
else:
connection.send_back(page.summary[0:index], data)

View File

@@ -0,0 +1,97 @@
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
from collections import defaultdict
from time import sleep
class WordRunObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return ['.a', '.add', '.begin', '.end']
@staticmethod
def help():
return 'hangman game'
def __init__(self):
super().__init__()
self.player = {}
self.gamestatus = 0
"""
0 = Kein Spiel
1 = Spiel mit Silbe am Anfang
2 = Spiel mit Silbe am Ende
"""
self.syllable = ""
def update_on_priv_msg(self, data, connection: Connection):
if data['message'].find('.a ') != -1 or data['message'].find('.add ') != -1:
self.add(data, connection)
if data['message'].find('.begin ') != -1:
self.begin_word(data, connection)
if data['message'].find('.end ') != -1:
self.end_word(data, connection)
def add(self, data, connection):
if self.gamestatus == 0:
connection.send_channel("Es läuft derzeit kein Wordrun, bitte einen neuen mit .begin <Silbe> oder .end <silbe> erstellen!")
return
if self.gamestatus == 1 or self.gamestatus == 2:
self.check_word(data["nick"], data['message'], connection)
def begin_word(self, data, connection):
if self.gamestatus != 0:
connection.send_channel("Es läuft bereits ein Spiel")
return
self.gamestatus = 1
self.handle_game(data,connection)
def end_word(self, data, connection):
if self.gamestatus != 0:
connection.send_channel("Es läuft bereits ein Spiel")
return
self.gamestatus = 2
self.handle_game(data,connection)
def check_word(self,player , message, connection):
for word in message.split():
if word == '.a':
continue
if self.gamestatus == 1:
if word.upper().startswith(self.syllable.upper()):
self.add_to_dict(player, word, connection)
if self.gamestatus == 2:
if word.upper().endswith(self.syllable.upper()):
self.add_to_dict(player, word, connection)
def add_to_dict(self, nick, word, connection):
for p in self.player.keys():
for w in self.player[p]:
if w.upper() == word.upper():
connection.send_channel("Das Wort "+word+" wurde bereits von "+p+ " genannt")
return
if nick not in self.player:
self.player[nick] = []
self.player[nick].append(word)
def handle_game(self, data, connection):
self.syllable = data["message"].split()[1]
if self.gamestatus == 1:
connection.send_channel("Das Wort muss mit " + self.syllable + "- beginnen")
if self.gamestatus == 2:
connection.send_channel("Das Wort muss mit -" + self.syllable + " enden")
sleep(150)
connection.send_channel("Noch 30 Sekunden")
sleep(30)
player_score = defaultdict(int)
s = "Folgende Ergebnisse: "
for p in self.player.keys():
for w in self.player[p]:
print(p+" "+w)
player_score[p] += 1
for p in self.player.keys():
s = s + p + " : "+str(player_score[p])+ "; "
connection.send_channel(s)
self.gamestatus = 0
self.player = {}

View File

@@ -0,0 +1 @@
__author__ = 'Pups'

28
FaustBot/StringBuffer.py Normal file
View File

@@ -0,0 +1,28 @@
class StringBuffer:
def __init__(self):
self._buffer = str()
def append(self, to_append):
self._buffer = self._buffer + to_append
return self.get()
def get(self):
ready = list()
# Python do-while-loop
idx = self._buffer.find('\n')
while idx is not -1:
data = self._buffer[0:idx] #
data = data.strip()
if len(data) >= 1:
ready.append(data)
self._buffer = self._buffer[idx + 1:]
idx = self._buffer.find('\n')
return ready
@property
def buffer(self):
return self._buffer
@buffer.setter
def buffer(self, new_value):
self._buffer = new_value

0
FaustBot/__init__.py Normal file
View File

27
HangmanLog Normal file
View File

@@ -0,0 +1,27 @@
Yana ; TEST
Yana ; TEST
Yana ; TUTU
Yana ; TEST
Yana ; TEST
Yana ; TEST
Yana ; OTTO
Yana ; FURZKISSEN
Yana ; TESTBOT
Yana ; TESTBOT
Yana ; TESTBOT
Yana ; TESTBOT
Yana ; TESTBOT
Yana ; PUPSSALAT
Yana ; OYMORON
Yana ; FEHLER
Yana ; SCHLECHT
Thiago86 ; KRUZIFIX
Yana ; TEST
Yana ; TEST
Yana ; TEST
Yana ; TEST
Yana ; TEST
Yana ; TEST
Neuling78 ; GURKENESSIG
Yana ; TEST
Yana ; TEST

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

17
Main.py Normal file
View File

@@ -0,0 +1,17 @@
#!/bin/python
"""
mainfile, initializes everything
"""
# function declarations
from argparse import ArgumentParser
from FaustBot.FaustBot import FaustBot
if __name__ == "__main__":
arg_parser = ArgumentParser(description="FautBot - ")
arg_parser.add_argument('--config', required=True, type=str, help="Path to the configuration file")
args = arg_parser.parse_args()
bot = FaustBot(args.config)
bot.run()

74
README.md Normal file
View File

@@ -0,0 +1,74 @@
# PhoenixBotty
IRC Bot, derived from Pallaber Bot, Architectonic rework
Designed for non-technical channels
## Usage
### Requirements
- Python 3.5
- pip
- wikipedia package (can be installed using pip; tested with version 1.4.0)
- virtualenv (optional)
### Running the Bot
The direct way:
```bash
# Install all dependencies
pip install -r requirements.txt
# First load all needed strings into the database
# Per default german is used. If you want another language you need to
# add an language file and modify the script.
# Later it will be refactored, so it uses arguments
python ReadInternationalization.py
# Create a configuration file by having a look at config-example.txt
# Start the bot using the given config file.
python Main.py --config ./config.txt
```
Using [faust-bot-run.sh](https://github.com/SophieBartmann/Faust-Bot/blob/master/faust-bot-run.sh). This script creates and uses a virtual environment, therefore the optional requirement virtualenv is required
```bash
# Make the script executable
chmod u+x ./faust-bot-run.sh
# To display all possible options
./script -h
> Simple script to manage a single faust-bot instance.
> -h displays this help message
> -s starts the bot, if it is not running yet
> -e exits/stops the bot
> -r restarts the bot
> -u updates the bots code
# Start the bot.
# The script creates an virtualenv, installs all pip dependencies and starts the Bot in the background
# The pid of the Bot-process is saved in .pid.
# Stdout is redirected to out.txt
./script -s
```
## Contribution
Have a look into our issues. Some are explizitly marked as `help wanted` or `For Beginners`. If you're new to programming the last one would be a good point to begin with. Of course you're also free to choose your own issue or task to work on.
If you have any question you're also welcome to join us in `#faust-bot` on freenode.
Before creating a pull request please test your code. Untested, obviously buggy code will - of course - be rejected.
Since we're programming in python please hold on [PEP-08](https://www.python.org/dev/peps/pep-0008/).
### Branching
Currently we use the [main-branch](https://github.com/SophieBartmann/Faust-Bot/edit/master/README.md) for development and the stable version is represented with the [stable-branch](https://github.com/SophieBartmann/Faust-Bot/tree/stable). Please create an own feature-branch if you want to contribute. This will make it easier to merge.
## Copyright
```
Faust-Bot. A simple, extensible IRC bot.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
```
The `care_icd10_de.csv` was taken from the [CARE2X - Integrated Hospital Info System Project on Sourceforge](https://sourceforge.net/projects/care2002/).

View File

@@ -0,0 +1,29 @@
import sqlite3
filepointer = open('de-de.lang', "r")
schema = 'de-de'
database_connection = sqlite3.connect('faust_bot.db')
cursor = database_connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS i18n (ident TEXT , lang TEXT, longText TEXT)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS explain(ident TEXT PRIMARY KEY, longText INT)''')
database_connection.commit()
cursor = database_connection.cursor()
cursor.execute('DELETE FROM i18n WHERE lang = ?', (schema,))
database_connection.commit()
ident = None
long = None
switch = True
cursor = database_connection.cursor()
for line in filepointer:
if switch:
ident = line.rstrip()
else:
long = line.rstrip()
print("Blatsch")
cursor.execute("INSERT INTO i18n(ident, lang, longText) VALUES(?,?,?)",(ident, schema, long,))
database_connection.commit()
switch = False if switch else True
database_connection.close()

12
Test_UserProvider.py Normal file
View File

@@ -0,0 +1,12 @@
from FaustBot.Model.UserProvider import UserProvider
user = UserProvider()
user.add_characters("Bla", 100)
user.set_active("Bla")
user.set_active("Mah")
print(user.get_characters("Bla"))
print(user.get_activity("Bla"))
print(user.get_characters("Blubb"))
print(user.get_activity("Blubb"))
print(user.get_characters("Mah"))
print(user.get_activity("Mah"))

1
_config.yml Normal file
View File

@@ -0,0 +1 @@
theme: jekyll-theme-time-machine

11289
care_icd10_de.csv Normal file

File diff suppressed because one or more lines are too long

9
comics.py Normal file
View File

@@ -0,0 +1,9 @@
# Random-URLs (NOT: Random URLs ;) ) for comics which have a website based random functionality
comics = [ 'https://c.xkcd.com/random/comic/',
'http://www.commitstrip.com/?random=1',
'https://satwcomic.com/random']
# URLs for comics which do not have a website based random functionality and therefore need a scraper module in Modules/ComicScraper.py
# Note: Comics in this List without a scraper in Modules/ComicScraper.py will not be scraped and return a No-Scraper-Info in IRC.
# If you want to add a comic website here then you will probably have to add scraping functionality to the ComicScraper for it.
scraper_comics =[ 'http://betamonkeys.co.uk/category/comics/feed/']

7
config-example.txt Normal file
View File

@@ -0,0 +1,7 @@
server: irc.freenode.org
port: 6667
nick: PhoenixBottyDev
channel: #faust-bot
lang: de-de
mods: Yana,MadamePluto
blacklist: Kicker,

12
de-de.lang Normal file
View File

@@ -0,0 +1,12 @@
seen
$asker: Ich habe $user zuletzt um $time gesehen!
wiki_fail
in Wikipedia finde ich dazu nichts. Magst du einen Artikel dazu schreiben?
wiki_lang
de
google_fail
dazu konnte ich leider nichts finden. Hast du dich vielleicht vertippt?
google_tld
de
google_lang
de

33
essen.py Normal file
View File

@@ -0,0 +1,33 @@
essen = ['einen Wirsingeintopf', 'einen Lahmacun', 'eine Portion Kartoffelbrei',
'Spinat', 'Astronautenfutter', 'ein Snickers', 'einen Mars-Riegel', 'eine Brezel',
'eine Portion Gagh', 'ein Filet Mignon', 'einen Döner', 'ein Teller Spaghetti Bolognese',
'ein Teller Spaghetti mit Käsesahnesoße', 'einen Obstteller', 'eine Hand voll Gummibärchen',
'ein gummiartiges Hühnchen', 'eine Schale mit Kartoffelchips', 'zwei Käsebrote',
'Okonomiyaki', 'zwei Stück Erdbeertorte', 'feuriges Chili con Carne', 'ein fluffiges Rührei',
'eine leckere Pizza', 'einen frischen Gurkensalat', 'einen großen Chefsalat',
'eine übelriechende Käsesuppe', 'Fischstäbchen und Kartoffelbrei', 'ungarisches Gulasch',
'Spaghetti mit Soja-Bolognese', 'ein original französisches Ratatouille', 'einen sahnigen Schokopudding',
'arme Ritter', 'einen Festtagsbraten mit Klößen', 'Pommes mit Majo', 'leckeren Kartoffelauflauf',
'Krabben-Cocktail', 'einen Toast Hawaii', 'indisches Lamm Curry', 'einen Gyrosteller mit Tsatsiki',
'ein Pilz-Risotto', 'ein hart gekochtes Ei', 'vier Pralinen mit Nougatfüllung', 'eine kalte Bockwurst',
'ein paar Mini-Frühlingsrollen', 'einen Glückskeks mit dem Spruch \"Du wirst heute nicht satt.\" ',
'würziges Kassler mit Sauerkraut', 'ein Schälchen Apfelmus', 'Bratkartoffeln', 'asiatisches Wokgemüse',
'einen fruchtigen Lolli', 'einen Teller mit süßem Milchreis', 'eine Lasagne', 'chinesisch gebratene Nudeln',
'ein Thunfisch-Baguette', 'fünf mexikanische Tacos', 'einen Blaubeermuffin mit Sahne', 'eine Hand voll alte Erdnüsse',
'ein Durianeis am Stiel','eine Mango', 'einen Erdnussbutterriegel',
'eine Schachtel Lebkuchen', 'eine Portion Falafel mit Hummus', 'ein feuriges Chilli con Soja',
'einen Teller getrocknete Jackfruchtstücke', 'eine Packung Choco-Fresh','ein Teller Spagetti Gorgonzola Sosse',
'fein geschnittene Karottenstückchen mit laktosefreiem Frischkäse','ein halbes Grillhuhn',
'eine Dose Surströmming','einen Steckerlfisch', 'einen Big King','ein Teller voll Buritos',
'eine Portion handgerolltes Sushi','ein Butterbrot', 'eine Schnittlauch Brezel','einen Teller szegediner Gulasch',
'eine Portion Avocado Maki','eine Spinatlasagne','ein Teller vegetarisch gefüllte Paprika',
'ein Teller gefüllte Zucchini','ein Schinken-Käse-Omlett','ein Chop Suey',
'ein großes Stück Turducken','einen Teller Spageti Aglio e Olio','Nudeln mit Pesto',
'ein Teller Paella','einen Berg Pfannkuchen','ein Teller Belgische Waffeln mit Schokosoße',
'eine Waffel mit Puderzucker', 'Grießbrei mit Amarena Kirschen',
'einen Kaiserschmarrn mit Apfelmus', 'Palatschinken mit Marillenmarmelade und Staubzucker',
'eine Tüte Maiswaffeln','eine Packung Schoko Keksi'
]

6
extras.py Normal file
View File

@@ -0,0 +1,6 @@
giveextras=['eine Rolle Toilettenpapier', 'eine Schmerztablette', 'eine Packung Girlanden',
'...äh serviert ist das falsche Wort, gibt sollte das heißen, eine Decke.',
'eine Tafel Schokolade', 'eine Tüte Chips', 'eine Wärmflasche in Teddy Bezug',
'ein Gartenteich voll Kraft', 'ein Fass Kraft', 'eine Tonne Kraft',
'einen knuddelverrückten Kraft-Glücksbringer','ein Kubikmeter Kraft',
'viel Kraft... sehr viel', 'eine Packung bunte Taschentücher']

124
faust-bot-run.sh Normal file
View File

@@ -0,0 +1,124 @@
#!/bin/bash
# Directory of the virtual environment
VENV="./FaustBotVEnv"
venv() {
if [ ! -d "$VENV" ]; then
echo "[=== creating virtual environment "
virtualenv --python=/usr/bin/python3 $VENV
echo "[=== activating virtual environment "
source $VENV/bin/activate
echo "[=== installing dependencies "
pip install -r requirements.txt
else
echo "[=== activating virtual environment "
source $VENV/bin/activate
fi
}
help() {
echo "Simple script to manage a single faust-bot instance."
echo " -h displays this help message"
echo " -s starts the bot, if it is not running yet"
echo " -e exits/stops the bot"
echo " -r restarts the bot"
echo " -u updates the bots code"
}
start() {
venv
echo "[=== checking if bot is already running "
if [ -f ".pid" ]; then
echo "[=== bot is already running "
echo "[=== aborting start "
else
echo "[=== bot is not running "
echo "[=== check if out.txt exists "
if [ -f "out.txt" ]; then
echo "[=== removing existing out.txt "
rm out.txt
else
echo "[=== no out.txt found "
fi
echo "[=== checking if database already exists "
if [ -f "faust_bot.db" ]; then
echo "[=== database already exists "
else
echo "[=== no database "
echo "[=== preparing database "
python ReadInternationalization.py
fi
echo "[=== starting faust-bot "
echo "[=== redirecting output to nohup.out "
nohup python -u Main.py --config config.txt > out.txt &
echo "[=== pid of bot process can be found in .pid "
echo $! > .pid
fi
}
stop() {
echo "[=== checking if bot is running "
if [ ! -f ".pid" ]; then
echo "[=== bot is not running "
else
echo "[=== bot is running "
echo "[=== killing bot process "
kill $(cat .pid)
echo "[=== removing .pid file "
rm .pid
fi
}
update() {
echo "[=== stopping the bot to update it "
stop
echo "[=== stashing local changes "
git stash --all
echo "[=== update the code "
git pull origin main
echo "[=== reapply done local changes "
git stash pop
echo "[=== restarting bot instance "
start
}
clean() {
echo "[=== cleaning files "
echo "[=== stopping the bot "
stop
echo "[=== removing output file "
rm out.txt
echo "[=== removing venv "
rm -rf $VENV
}
OPTIND=1
while getopts "hseruc" opt; do
case $opt in
h)
help
exit
;;
s)
start
;;
e)
stop
;;
r)
stop
start
;;
u)
update
;;
c)
clean
;;
\?)
echo "Invalid option: -$OPTARG" >&2
help
;;
esac
done

48
getraenke.py Normal file
View File

@@ -0,0 +1,48 @@
getraenke = ['einen Kaffee','eine Limonade','einen Kakao','einen Tee',
'einen Kräutertee','eine Cola',
'kaltes Wasser','kalten Eistee','einen Raktajino',
'frischen Mate', 'eine Club Mate','ein Glas Gurkenwasser',
'einen Apfelsaft','einen Traubensaft',
'einen Muckefuck','einen Kiwismoothie', 'einen Spinatsmoothie',
'einen Orangensaft','einen Coconut Kiss','ein Glas Milch',
'einen Erdbeersmoothie','einen Kirschsaft',
'einen Latte Macchiato','eine Tasse heiße Schokolade',
'ein Glas Sauerkrautwasser','einen Topf Kinderpunsch',
'einen Mango-Melone-Smoothie','ein Glas Hoffnung',
'einen frischen Pfefferminztee','eine Eisschokolade',
'einen Eiskaffee','einen kalten Milchshake',
'eine kalte Afri Cola','einen Sojamilch Milchkaffee',
'einen Soja Latte Macchiato',
'einen Fraktal Allmachtstrank', 'einen Heiltrank',
'einen großen Becher Blumenwasser', 'einen Erdbeershake',
'einen Blaubeersmoothie', 'eine Tasse Pfefferminztee',
'ein kaltes Spezi', 'eine Tasse Hanftee',
'eine Karaffe Sprudelwasser',
'einen kleinen Becher Kirsch-Banane-Nektar',
'eine Mio Mio Mate',
'eine Fritz!Cola', 'ein Ginger-Ale', 'ein Glas laktosefreie Milch',
'einen Lebertran', 'eine Caprisonne',
'einen Kürbissaft', 'einen Kefir',
'einen Ayran', 'ein Glas Nihilismus', 'eine Sprite',
'eine Fanta', 'einen Purple Flurp',
'ein leckeres Wasser', 'einen Robby Bubble', 'ein Glas warme Milch',
'ein Glas Schlamm', 'ein Glas Regenwasser', 'ein halbes Glas Kokosnussmilch',
'ein Glas Ingwerwasser','eine Tasse lauwarmen Sencha',
'ein Glas Chai Latte mit Sojamilch','ein Tässchen kalten Sencha',
'einen Cappuccino','eine Tasse Cashew-Milch',
'eine Karaffe Hoffnung', 'eine Kanne Zuversicht','ein Glas Zuversicht',
'einen Soja-Chai-Latte (Kids Temperature)','eine Flasche Paulaner Spezi',
'einen Pappbecher Soja-Kakao','eine Flasche Bionade Holunder',
'einen Eiskalten Terere', 'eine Runde Wasser für alle',
'einen kalt gezogenen grünen Tee','ein Glas Brackwasser',
'einen Pappbecher frischen Kaffee mit Sojamilch','einen Becher des Lieblingsgetränkes',
'ein Glas frisch gepressten Traubensaft','ein Glas mit zimmerwarmer Hafermilchschokolade',
'ein sehr großes Glas mit Fassbrause','einen Bubble Tea in einem billigen Plastikbecher',
'eine Tasse Rooibostee', 'einen Rainbow-Cocktail', 'einen Virgin Sunrise',
'eine Apfelschorle','einen Birnensaft','einen Mangosaft',
'ein Glas Holunderblütensirup', 'eine Sauerkirschlimo', 'ein Glas gefrorenes Wasser',
'eine bunte Tasse fairtrade Bohnenkaffee','einen Maracujasaft','ein Glas Luft',
'ein Glas fairtrade Limonade','eine Cola Light', 'ein Glas Fanta light',
'ein Glas Sprite light', 'ein Glas Spezi light','eine dampfende Tasse Winterpunsch-Tee',
'eine bunte Tasse Rooibos Schoko-Chai','eine Tasse Rooibos Chai'
]

36
getraenkeOnlyGoodOnes.py Normal file
View File

@@ -0,0 +1,36 @@
getraenkegoodones = ['einen Kaffee in einer Tasse aus blauem Porzellan','eine Limonade in einem Cocktailglas mit Schirmchen',
'einen Kakao in einer großen lila Tasse mit Löffel','einen losen Tee in einem Gaiwan',
'eine Cola mit einer Scheibe Zitrone in einem Glas mit Schirmchen',
'kaltes Wasser','kalten selbstgemachten Eistee',
'frischen Mate in einem Kürbis mit einem verschnörkelten Strohhalm',
'eine Flasche Club Mate','einen frisch gepressten Apfelsaft','einen frisch gepressten Traubensaft',
'einen Kiwismoothie', 'einen frisch gepressten Orangensaft','einen Coconut Kiss in einem hohen Cocktailglas mit einer Scheibe Ananas am Rand',
'ein Glas Milch', 'einen Erdbeersmoothie', 'einen Latte Macchiato mit einem Keks neben der Tasse',
'eine Tasse heiße Schokolade aus Schokostückchen','einen Mango-Melone-Smoothie','ein Glas feinster Hoffnung',
'einen frischen Pfefferminztee','eine Eisschokolade mit Sahne','einen Eiskaffee mit Sahne',
'einen kalten Milchshake mit deinem Lieblingseis',
'eine kalte Afri Cola','einen Sojamilch-Milchkaffee mit einem Keks neben der Tasse',
'einen Soja Latte Macchiato mit einem Keks neben der Tasse',
'einen Blaubeersmoothie','ein kaltes Spezi mit einer Scheibe Zitrone am Rand', 'eine Karaffe kaltes Sprudelwasser',
'einen großen Becher Kirsch-Banane-Nektar',
'eine Flasche Mio Mio Mate',
'eine Fritz!Cola', 'eine Sprite mit Zitrone am Glas',
'eine Fanta mit Orange am Glas', 'ein leckeres Wasser', 'ein edles Glas Kokosnussmilch',
'eine Tasse lauwarmen Sencha','ein Glas Chai Latte mit Sojamilch','ein Tässchen kalten Sencha',
'einen Cappuccino mit einem Keks neben der Tasse','eine Tasse Cashew-Milch mit einem Schokokeks neben der Tasse',
'eine Karaffe Hoffnung','ein Glas Zuversicht','eine Flasche Paulaner Spezi',
'eine edle Tasse Soja-Kakao','eine Flasche Bionade Holunder',
'einen eiskalten Tehere',
'einen kalt gezogenen grünen Tee',
'eine edle Tasse frischen Kaffee mit Sojamilch','ein Glas frisch gepressten Traubensaft',
'ein Wasser in einem Glas mit einem schönen Schirmchen','einen geschäumten Matcha in einer Teeschale',
'ein verziertes Glas mit kalter Hafermilchschokolade','eine große Flasche Fassbrause mit Ploppverschluss',
'einen frisch aufgeschlagenen Matcha in einer Teeschale',
'eine Tasse Glück in einer großen Tasse mit Füchsen drauf',
'einen Bubble Tea in einem verschnörkelten Glas mit großem Strohhalm','einen Rührkuchen',
'einen veganen glutenfreien Karottenkuchen', "einen saftigen Schokokuchen", "eine Kirschtorte",
"einen Apfelkuchen", "einen Pudding-Streuselkuchen", "einen Rhabarberstreuselkuchen",
'ein Glas kalten Rooibos Tee mit Vanille verfeinert','eine bunt karierte Tasse Kaffee', 'einen Rainbow Cocktail in einem hohen Glas mit Schirmchen',
'eine Apfelschorle mit frisch gepresstem Apfelsaft', 'eine bunt gestreifte Tasse Tee'
]

31
icecreamlist.py Normal file
View File

@@ -0,0 +1,31 @@
icecream = [
'drei Kugeln Schokoladeneis', 'eine Tüte Stracciatellaeis',
'einen Becher Himbeereis', 'ein Schälchen Mango-Erdbeer-Eis',
'ein Schälchen Heidelbeer-Pfirsich-Eis', 'ein Wassermeloneneis am Stiel',
'eine Tüte Erdbeereis', 'Erdbeereis mit frischen Erdbeeren','zwei Kugeln Bananeneis',
'einen Becher Joghurteis', '6 Kugeln Heidelbeereis in einer glutenfreien Tüte',
'Erdbeer-Joghurt-Eis mit bunten Streuseln', 'ein Kokoseis',
'einen Eimer Schlumpfeis', 'eine Kugel Vanilleeis',
'ein Pfefferminzeis mit zwei Schokotäfelchen', 'ein laktosefreies Karamelleis',
'eine Tüte Pistazieneis', 'ein Apfelsorbet', 'ein Zitronensorbet',
'viel Mangosorbet', 'ein Melonensorbet', 'ein Waldmeistersorbet',
'ein Waldbeersorbet', 'ein Mango-Himbeereis', 'ein Banane-Heidelbeereis',
'einen Bananensplit', 'einen Nussbecher', 'ein Biene-Maja-Eis',
'einen Erdbeerbecher', 'Frozen-Yoghurt mit Früchten der Saison',
'einen erfrischenden Früchtebecher', 'Frozen-Yoghurt mit Streuseln',
'einen Schokobecher mit Schokosoße', 'einen Rocher-Becher', 'ein Capri',
'einen Raffaelo-Becher', '5 Eispralinen', 'ein Calippo', 'ein Big-Sandwich',
'ein Mini-Milk', 'ein fröhlich knisterndes Kaktus-Eis', 'ein Nucki Nuss',
'ein Cornetto Schoko vegan', 'ein Cornetto Schoko', 'ein Cornetto Erdbeer vegan',
'ein Cornetto Erdbeer', 'Spaghettieis', 'einen Haufen Eiswürfel', 'ein Bum Bum',
'ein warmes Kirscheis', 'ein Eis', 'ein Kaffeeeis', 'einen Apfelslushy',
'einen Kiwislushy', 'einen Kirschslushy', 'einen Eiszapfenslushy', 'ein Softeis',
'ein Durianeis am Stiel', 'ein Himbeereis', 'einen Eiskaffee',
'einen gefrorenen Keks', 'eine Packung Ben and Jerry\'s Cookie Dough',
'ein Walnusseis', 'ein Pistazieneis', 'ein Haselnusseis',
'ein Schwimmbecken voll Brombeereis','ein Glas Wasser mit binären Eiswürfeln',
'einen Coppa del Nonno', 'ein veganes Zitroneneis', 'ein grünes Wassereis', 'ein Jolly',
'ein Twinni', 'ein Tschisi', 'einen Plattfuß', 'ein Supertwister', 'ein Twister',
'ein Fruchtzwerg-Eis am Stiel','einen Honigmeloneneisbecher', 'ein Honigmeloneneis',
'ein Schoko Waffeleis vegan von Valsoia'
]

6
requirements.txt Normal file
View File

@@ -0,0 +1,6 @@
# FaustBot/Modules/ComicObserver.py: 3
# FaustBot/Modules/ComicScraper.py: 3
requests == 2.4.3
# FaustBot/Modules/WikiObserver.py: 1
wikipedia == 1.4.0

6
snacks.py Normal file
View File

@@ -0,0 +1,6 @@
snacks=[ 'eine handvoll Salzbrezeln','ein Schälchen Chips','5 M&Ms','ein Päckchen gesalzene Nüsse',
'ein paar Apfelschnitze','eine Tüte salziges Popcorn','ein Täfelchen Schokolade','ein kleines Stück Käsekuchen',
'ein kleines Stück Kuchen nach Wahl','ein kleines Schälchen Schokoladen Keksi', 'eine Hand voll Trockenfrüchte',
'ein gesunder Riegel','eine Tüte Luft', '5 Schokobons', 'eine Schale Nachos','einen kinderriegel',
'eine schwarze Lindor Schokokugel', 'eine Kino Portion süßes Popcorn', 'eine Schale Wasabi Erdnüsse',
'eine kleine Schale Pistazien','eine Handvoll Macadamia-Nüsse','ein Glaß voller Salzstangen']