]> git.somenet.org - pub/jan/mattermost.git/blob - ics_to_channel/main.py
[somebot] requirements.txt for all modules.
[pub/jan/mattermost.git] / ics_to_channel / main.py
1 #!/usr/bin/env python3
2 # Someone's Mattermost scripts.
3 #   Copyright (c) 2016-2020 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
4 #   published under MIT-License
5 #
6 # Send event-reminders to configured channels.
7 #
8
9 import datetime
10 import pytz
11 import pprint
12 import time
13 import traceback
14
15 import icalendar
16 import requests
17 import mattermost
18
19 import config
20
21 def process_ics(mm, now, alias, ics_config):
22     c = icalendar.Calendar.from_ical(requests.get(ics_config[0]).text)
23     for ev in c.subcomponents:
24         if isinstance(ev,icalendar.cal.Event):
25             spam_mm = False
26             for remind in ev.subcomponents:
27                 if isinstance(ev.get("DTSTART").dt,datetime.datetime):
28                     event_datetime = ev.get("DTSTART").dt
29                     alarm_datetime = ev.get("DTSTART").dt+remind.get("TRIGGER").dt
30
31                     # convert to now's tz
32                     event_datetime = (event_datetime-datetime.datetime.utcoffset(event_datetime)+datetime.datetime.utcoffset(now)).replace(second=0, tzinfo=now.tzinfo)
33                     alarm_datetime = (alarm_datetime-datetime.datetime.utcoffset(alarm_datetime)+datetime.datetime.utcoffset(now)).replace(second=0, tzinfo=now.tzinfo)
34
35                 else:
36                     # why the diffrent handling of "full-day" events?!
37                     event_datetime = datetime.datetime.combine(ev.get("DTSTART").dt, datetime.datetime.min.time()).replace(second=0, tzinfo=now.tzinfo)
38                     alarm_datetime = (datetime.datetime.combine(ev.get("DTSTART").dt, datetime.datetime.min.time())+remind.get("TRIGGER").dt).replace(second=0, tzinfo=now.tzinfo)
39
40                 seconds_to_reminder_time = (now-alarm_datetime).total_seconds()
41
42                 if seconds_to_reminder_time >= 0 and seconds_to_reminder_time < 300:
43                     spam_mm = True
44
45             if spam_mm:
46                 for channel_id in ics_config[1]:
47                     pprint.pprint(mm.create_post(channel_id, "``BOT-AUTODELETE-FAST`` #termin_reminder Datasource: "+alias+"\nUpcoming event at: **``"+str(event_datetime)+"``**\n### ``"+str(ev.get("SUMMARY"))+"``\n"+str(ev.get("DESCRIPTION"))))
48
49
50
51 mm = mattermost.MMApi(config.mm_api_url)
52 mm.login(config.mm_user, config.mm_user_pw)
53
54 TS_START = time.time()
55 now = datetime.datetime.now(tz=pytz.timezone("Europe/Vienna")).replace(second=0, microsecond=0)
56
57 for alias, ics_config in config.ics_config.items():
58     try:
59         process_ics(mm, now, alias, ics_config)
60     except:
61         traceback.print_exc()
62     print("* ["+("%07.6g"%round(time.time() - TS_START, 5))+"] COMPLETED: "+alias)
63
64 mm.logout()