fix: Make subscribing and unsubscribing work

This commit is contained in:
PapaTutuWawa 2020-09-17 15:47:55 +02:00
parent 1b36a13993
commit c40390dd5c

View File

@ -77,6 +77,8 @@ class WarningBot:
# Configuration stuff # Configuration stuff
self._data_dir = '' self._data_dir = ''
self._client_store = ''
self._warning_store = ''
self._load_config() self._load_config()
@ -88,27 +90,6 @@ class WarningBot:
self._jid, self._jid,
aioxmpp.make_security_layer(self._password)) aioxmpp.make_security_layer(self._password))
# First we check if the entered Landkreis is valid
self._channels = []
channels = {}
channel_file = os.path.join(self._data_dir, 'channels.json')
if not os.path.exists(channel_file):
log.debug('Requesting search channels')
req = requests.get(MiscDataSources.channels())
channels = json.loads(req.text)
self._channels = list(map(lambda key: channels[key].get('NAME', ''),
channels.keys()))
try:
with open(channel_file, 'w') as f:
f.write(json.dumps(self._channels))
except Exception as err:
log.error('Failed to cache channel data:')
log.error(str(err))
else:
with open(channel_file, 'r') as f:
self._channels = json.loads(f.read())
async with self._client.connected() as stream: async with self._client.connected() as stream:
logging.info('Client connected to server') logging.info('Client connected to server')
@ -145,6 +126,9 @@ class WarningBot:
await periodic await periodic
def __is_message_valid(self, msg): def __is_message_valid(self, msg):
'''
Returns True on messages we want to handle. False otherwise.
'''
if msg.type_ != aioxmpp.MessageType.CHAT: if msg.type_ != aioxmpp.MessageType.CHAT:
return False return False
@ -158,6 +142,9 @@ class WarningBot:
return True return True
def __make_msg(self, to, body): def __make_msg(self, to, body):
'''
Wrapper for creating a message object to enqueue or send.
'''
msg = aioxmpp.Message( msg = aioxmpp.Message(
type_=aioxmpp.MessageType.CHAT, type_=aioxmpp.MessageType.CHAT,
to=to) to=to)
@ -191,13 +178,15 @@ class WarningBot:
if not landkreis in self._warn_clients.keys(): if not landkreis in self._warn_clients.keys():
self._warn_clients[landkreis] = [] self._warn_clients[landkreis] = []
self._warn_clients[landkreis].append(str(msg.from_)) self._warn_clients[landkreis].append(str(msg.from_.bare()))
# TODO: Flush self._warn_clients to disk
self._client.enqueue(self.__make_msg( self._client.enqueue(self.__make_msg(
to=msg.from_, to=msg.from_,
body=f'Du erhälst nun Nachrichten zu {landkreis} von mir')) body=f'Du erhälst nun Nachrichten zu {landkreis} von mir'))
with open(self._client_store, 'w') as cf:
cf.write(json.dumps(self._warn_clients))
# Send all known warnings for the landkreis to the user # Send all known warnings for the landkreis to the user
for warning in self._warnings0: for warning in self._warnings0:
if landkreis in warning.landkreise: if landkreis in warning.landkreise:
@ -215,19 +204,22 @@ class WarningBot:
return return
landkreis = ' '.join(cmd_parts[1:]) landkreis = ' '.join(cmd_parts[1:])
if not landreis in self._warn_clients.keys(): if not landkreis in self._warn_clients:
self._client.enqueue(self.__make_msg( self._client.enqueue(self.__make_msg(
to=msg.from_, to=msg.from_,
body=f'Du hast {landkreis} nicht abonniert')) body=f'Du hast {landkreis} nicht abonniert'))
return return
if str(msg.from_) in self._warn_clients[landkreis]: if str(msg.from_.bare()) in self._warn_clients[landkreis]:
filter_ = lambda x: x != str(msg.from_) filter_ = lambda x: x != str(msg.from_.bare())
self._warn_clients[landkreis] = list(filter(filter_, self._warn_clients[landkreis] = list(filter(filter_,
self._warn_clients[landkreis])) self._warn_clients[landkreis]))
self._client.enqueue(self.__make_msg( self._client.enqueue(self.__make_msg(
to=msg.from_, to=msg.from_,
body=f'Du erhälst keine Nachrichten zu {landkreis} mehr von mir')) body=f'Du erhälst keine Nachrichten zu {landkreis} mehr von mir'))
if len(self._warn_clients[landkreis]) == 0:
del self._warn_clients[landkreis]
else: else:
self._client.enqueue(self.__make_msg( self._client.enqueue(self.__make_msg(
to=msg.from_, to=msg.from_,
@ -237,6 +229,10 @@ class WarningBot:
self._client.enqueue(self.__make_msg( self._client.enqueue(self.__make_msg(
to=msg.from_, to=msg.from_,
body=body)) body=body))
else:
self._client.enqueue(self.__make_msg(
to=msg.from_,
body='Diesen Befehl kenne ich nicht... Mit "help" kannst du alle Befehle sehen, die ich kenne.'))
async def _periodic_requests(self): async def _periodic_requests(self):
''' '''
@ -322,12 +318,34 @@ class WarningBot:
self._recipients = config['General']['Recipients'].split(',') self._recipients = config['General']['Recipients'].split(',')
self._refresh_timeout = int(config['General']['Timeout']) self._refresh_timeout = int(config['General']['Timeout'])
# Warning data # Persistent data
client_file = os.path.join(self._data_dir, 'clients.json') # Subscribed clients
if os.path.exists(client_file): self._client_store = os.path.join(self._data_dir, 'clients.json')
with open(client_file, 'r') as cf: if os.path.exists(self._client_store):
with open(self._client_store, 'r') as cf:
self._warn_clients = json.loads(cf.read()) self._warn_clients = json.loads(cf.read())
# Landkreise
self._channels = []
channels = {}
channel_file = os.path.join(self._data_dir, 'channels.json')
if not os.path.exists(channel_file):
log.debug('Requesting search channels')
req = requests.get(MiscDataSources.channels())
channels = json.loads(req.text)
self._channels = list(map(lambda key: channels[key].get('NAME', ''),
channels.keys()))
try:
with open(channel_file, 'w') as f:
f.write(json.dumps(self._channels))
except Exception as err:
log.error('Failed to cache channel data:')
log.error(str(err))
else:
with open(channel_file, 'r') as f:
self._channels = json.loads(f.read())
# Bot Config # Bot Config
self._jid = aioxmpp.JID.fromstr(config['Bot']['JID']) self._jid = aioxmpp.JID.fromstr(config['Bot']['JID'])
self._password = config['Bot']['Password'] self._password = config['Bot']['Password']