ticketfrei/trigger.py

73 lines
2 KiB
Python
Raw Normal View History

#!/usr/bin/env python
import os
import pytoml as toml
2017-06-25 17:15:38 +00:00
class Trigger(object):
"""
This class provides a filter to test a string against.
"""
def __init__(self, config):
self.config = config
2017-06-25 17:15:38 +00:00
try:
self.goodlistpath = config['trigger']['goodlist_path']
except KeyError:
self.goodlistpath = 'goodlists'
self.goodlist = self.get_lists(self.goodlistpath)
2017-06-25 17:15:38 +00:00
try:
self.blacklistpath = config['trigger']['blacklist_path']
except KeyError:
self.blacklistpath = 'blacklists'
self.blacklist = self.get_lists(self.blacklistpath)
2017-06-17 23:01:11 +00:00
def get_lists(self, path):
"""
2017-06-25 17:15:38 +00:00
pass a folder with text files in it. each line in the files becomes a
filter word.
:param path: path to folder whose files shall be added to the set
:return: set of trigger words.
"""
trigger_words = set()
for filename in os.listdir(path):
2017-06-25 17:15:38 +00:00
with open(os.path.join(path, filename), "r+") as listfile:
for word in listfile:
word = word.strip()
if word:
trigger_words.add(word)
return trigger_words
2017-06-25 17:15:38 +00:00
def is_ok(self, message):
"""
checks if a string contains no bad words and at least 1 good word.
2017-06-25 17:15:38 +00:00
:param message: A given string. Tweet or Toot, cleaned from html.
:return: If the string passes the test
"""
2017-06-25 17:15:38 +00:00
ret = False
for word in message.lower().split():
if word in self.goodlist:
ret = True
if word in self.blacklist:
return False
return ret
2017-06-17 20:32:20 +00:00
if __name__ == "__main__":
with open("ticketfrei.cfg", "r") as configfile:
config = toml.load(configfile)
2017-06-25 17:15:38 +00:00
print("testing the trigger")
trigger = Trigger(config)
2017-06-25 17:15:38 +00:00
print("Printing words which trigger the bot:")
for i in trigger.goodlist:
2017-06-25 17:15:38 +00:00
print(i)
print()
2017-06-25 17:15:38 +00:00
print("Printing words which block a bot:")
for i in trigger.blacklist:
2017-06-25 17:15:38 +00:00
print(i)