ticketfrei/trigger.py

74 lines
2.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2017-06-25 19:12:26 +00:00
import os
import re
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:
2017-06-25 19:12:26 +00:00
goodlistpath = config['trigger']['goodlist_path']
2017-06-25 17:15:38 +00:00
except KeyError:
2017-06-25 19:12:26 +00:00
goodlistpath = 'goodlists'
# load goodlists
self.goodlist = []
for filename in os.listdir(goodlistpath):
with open(os.path.join(goodlistpath, filename), "r+") as listfile:
for pattern in listfile:
pattern = pattern.strip()
if pattern:
2017-06-25 21:50:58 +00:00
self.goodlist.append(re.compile(pattern, re.IGNORECASE))
2017-06-25 17:15:38 +00:00
try:
2017-06-25 19:12:26 +00:00
blacklistpath = config['trigger']['blacklist_path']
2017-06-25 17:15:38 +00:00
except KeyError:
2017-06-25 19:12:26 +00:00
blacklistpath = 'blacklists'
2017-06-17 23:01:11 +00:00
2017-06-25 19:12:26 +00:00
# load blacklists
self.blacklist = set()
for filename in os.listdir(blacklistpath):
with open(os.path.join(blacklistpath, filename), "r+") as listfile:
2017-06-25 17:15:38 +00:00
for word in listfile:
word = word.strip()
if word:
2017-06-25 19:12:26 +00:00
self.blacklist.add(word)
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 19:12:26 +00:00
for pattern in self.goodlist:
2017-06-25 21:50:58 +00:00
if pattern.search(message) is not None:
2017-06-25 19:12:26 +00:00
break
else:
# no pattern matched
return False
2017-06-25 17:15:38 +00:00
for word in message.lower().split():
if word in self.blacklist:
return False
2017-06-25 19:12:26 +00:00
return True
2017-06-17 20:32:20 +00:00
if __name__ == "__main__":
2018-03-23 12:19:39 +00:00
import backend
config = backend.get_config()
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)