1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
|
#!/usr/bin/env python3
from datetime import date, datetime, timedelta
import json
import os
import subprocess
import sys
import tanken
# Path where our data is stored persistent on disk
state_file = os.environ["GSB_STATE_FILE"]
if os.path.isfile(state_file):
with open(state_file, "r") as state_f:
state = json.load(state_f)
else:
# Dict containing the whole state of geldschieberbot
# balance - dict of dicts associating two persons to an amount
# name2num, num2name - dicts associating numbers to names and vice versa
# cars - dict associating car names to their service charge
# scheduled_cmds - dict associating names to cmds, their schedule, and the last execution
# changes - dict associating users with their changes
state = {
"balance": {},
"name2num": {},
"num2name": {},
"cars": {},
"scheduled_cmds": {},
"changes": {},
}
# check if a legacy file layout is present
store_dir = os.path.dirname(state_file)
if os.path.isfile(os.path.join(store_dir, "balance.json")):
with open(os.path.join(store_dir, "balance.json"), "r") as f:
state["balance"] = json.load(f)
with open(os.path.join(store_dir, "registration.json"), "r") as f:
state["name2num"] = json.load(f)
for _name in state["name2num"]:
state["num2name"][state["name2num"][_name]] = _name
with open(os.path.join(store_dir, "last_change.json"), "r") as f:
state["changes"] = json.load(f)
for _num in state["changes"]:
_name = state["num2name"][_num]
state["changes"][_name] = state["changes"][_num]
del state["changes"][_num]
balance = state["balance"]
name2num = state["name2num"]
num2name = state["num2name"]
available_cars = state["cars"]
scheduled_cmds = state["scheduled_cmds"]
changes = state["changes"]
group_id = os.environ["GSB_GROUP_ID"]
send_cmd = os.environ["GSB_SEND_CMD"]
group_send_cmd = send_cmd + group_id
dry_run = False
"""Run without changing the stored state"""
quiet = False
"""Run without sending messages"""
record_changes = True
"""Should changes be recorded"""
def record(recipient, donor, amount):
"""Apply changes to the balance"""
# Only change anything if this is not a dry run
if dry_run:
return
balance[donor][recipient] += amount
balance[recipient][donor] -= amount
def to_cent(euro):
if '.' in euro:
euro = euro.split('.')
else:
euro = euro.split(',')
if len(euro) > 2:
raise TypeError
euro[0] = int(euro[0])
if len(euro) < 2:
euro.append(0)
else:
if len(euro[1]) == 1:
euro[1] = int(euro[1]) * 10
else:
euro[1] = int(euro[1])
amount = euro[0] * 100 + euro[1]
if amount < 0:
raise ValueError
return amount
def to_euro(cents):
return f"{cents/100:.2f}"
def send(msg, attachment=None, cmd=send_cmd):
if not quiet:
if attachment:
cmd += f' -a {attachment}'
subprocess.run(cmd.split(' '), input=msg.encode(), check=False)
def create_summary(user):
msg = ''
cars_summary = ""
total = 0
cars_total = 0
p_balances = balance[user] # failes if user is not in balance
for person in p_balances:
amount = p_balances[person]
if amount == 0:
continue
if person in available_cars:
cars_total -= amount
cars_summary += f'\t{"<-" if amount < 0 else "->"} {person} {to_euro(abs(amount))}\n'
else:
total -= amount
msg += f'\t{"<-" if amount < 0 else "->"} {person} {to_euro(abs(amount))}\n'
if not msg:
msg = '\tAll fine :)'
else:
msg += f'\tBalance: {to_euro(total)}'
ret_summary = f'{user}:\n{msg}'
if cars_summary:
cars_summary += f'\tLiability: {to_euro(cars_total)}'
ret_summary += f'\n\tCars:\n{cars_summary}'
return ret_summary
def create_total_summary() -> str:
msg = 'Summary:'
cars_summary = ''
for person in balance:
p_summary = create_summary(person)
if person in available_cars:
cars_summary += f'\n{p_summary}'
else:
msg += f'\n{p_summary}'
if cars_summary:
msg += f'\nCars:{cars_summary}'
return msg
def create_members() -> str:
r = ""
for m in name2num:
r += m + ": " + name2num[m] + "\n"
return r
def add_to_balance(name):
nb = {}
for m in balance:
balance[m][name] = 0
nb[m] = 0
balance[name] = nb
def remove_from_balance(name):
del balance[name]
for m in balance:
del balance[m][name]
def create_help():
return """
Usage: send a message starting with '!' followed by a command
Commands:
ls | list - print all registered members
help - print this help message
reg name - register the sender with the name: name
sum [name] - print summary of specific users
full-sum - print summary of all users
split amount person [persons] - split amount between the sender and persons
teil amount person [persons] - split amount between the sender and persons
schieb amount recipient - give money to recipient
gib amount recipient - give money to recipient
zieh amount donor - get money from donor
nimm amount donor - get money from donor
transfer amount source destination - transfer amount of your balance from source to destination
cars [cmd] - interact with the available cars
cars [list | ls] - list available cars and their service charge
cars add car-name service-charge - add new car
cars new car-name service-charge - add new car
cars remove car-name - remove new car
cars pay car-name amount - pay a bill for the specified car
tanken amount [person] [car] [info] - calculate fuel costs, service charge and add them to the person's and car's balance respectively
fuck [change] - rewind last or specific change
list-changes [n] [first] - list the last n changes starting at first
export-state - send the state file
weekly name cmd - repeat cmd each week
monthly name cmd - repeat cmd each month
yearly name cmd - repeat cmd each year
cancel name - stop repeating cmd
Happy Geldschieben!
"""
cmds = {}
def register(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if len(args) != 2:
return {'err': f'not in form "{args[0]} name"'}
name = args[1]
try:
to_cent(name)
return {'err': 'pure numerical names are not allowed'}
except (ValueError, TypeError):
pass
if name in name2num:
return {'err': f'{name} already registered'}
if sender in num2name:
return {'err': 'you are already registered'}
num2name[sender] = name
name2num[name] = sender
add_to_balance(name)
# add changes list
changes[name] = []
return {'msg': f'Happy geldschiebing {name}!'}
cmds["reg"] = register
cmds["register"] = register
def summary(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if len(args) == 1:
if not sender in num2name:
return {'err': 'You must register first to print your summary'}
name = num2name[sender]
return {'msg': f'Summary:\n{create_summary(name)}'}
msg = "Summary:\n"
for name in args[1:]:
if name in name2num or name in available_cars:
msg += create_summary(name) + "\n"
else:
return {'err': f'name "{name}" not registered'}
return {'msg': msg}
cmds["sum"] = summary
cmds["summary"] = summary
def full_summary(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if len(args) == 1:
return {'msg': create_total_summary()}
else:
return {'err': f'{args[0][1:]} takes no arguments'}
cmds["full-sum"] = full_summary
cmds["full-summary"] = full_summary
def list_users(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
return {'msg': create_members()}
cmds["ls"] = list_users
cmds["list"] = list_users
def usage(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
return {'msg': create_help()}
cmds["help"] = usage
cmds["usage"] = usage
def split(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if not sender in num2name:
return {'err': 'you must register first'}
if len(args) < 3:
return {'err': f'not in form "{args[0]} amount [name]+"'}
try:
amount = to_cent(args[1])
persons = args[2:]
except (ValueError, TypeError):
# support !split name amount
if len(args) == 3:
try:
amount = to_cent(args[2])
persons = [args[1]]
except (ValueError, TypeError):
return {'err': 'amount must be a positive number'}
else:
return {'err': 'amount must be a positive number'}
recipient = num2name[sender]
# persons + sender
npersons = len(persons) + 1
amount_per_person = int(amount / npersons)
output = f"Split {to_euro(amount)} between {npersons} -> {to_euro(amount_per_person)} each\n"
change = [args]
for p in persons:
if p in name2num:
if p == recipient:
output += (f'{p}, you will be charged multiple times. '
'This may not be what you want\n')
else:
record(recipient, p, amount_per_person)
change.append([recipient, p, amount_per_person])
else:
output += f"{p} not known. Please take care manually\n"
if record_changes and not dry_run:
changes[recipient].append(change)
output += "New Balance:\n"
output += create_summary(recipient)
return {'msg': output}
cmds["split"] = split
cmds["teil"] = split
def transaction(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if len(args) != 3:
return {'err': f'not in form "{args[0]} amount recipient"'}
if not sender in balance:
if sender not in num2name:
return {'err': 'you must register first'}
sender = num2name[sender]
if args[1] in balance:
recipient, amount = args[1:3]
elif args[2] in balance:
amount, recipient = args[1:3]
else:
return {'err': 'recipient not known'}
if sender == recipient:
return {'err': 'you can not transfer money to or from yourself'}
try:
amount = to_cent(amount)
except (ValueError, TypeError):
return {'err': 'amount must be a positive number'}
if args[0] in ["!zieh", "!nimm"]:
amount *= -1
if record_changes and not dry_run:
changes[sender].append([args, [sender, recipient, amount]])
record(sender, recipient, amount)
p_balance = balance[sender][recipient]
output = ("New Balance: {} {} {} {}\n".format(
sender, ("->" if p_balance > 0 else "<-"), to_euro(abs(p_balance)),
recipient))
return {'msg': output}
cmds["schieb"] = transaction
cmds["gib"] = transaction
cmds["zieh"] = transaction
cmds["nimm"] = transaction
def transfer(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if len(args) < 4:
return {'err': f'not in form "{args[0]} amount source destination"'}
if not sender in num2name:
return {'err': 'you must register first'}
sender = num2name[sender]
try:
amount_raw = args[1]
amount_cent = to_cent(amount_raw)
except (ValueError, TypeError):
return {'err': 'amount must be a positive number'}
source, destination = args[2:4]
if source not in balance:
return {'err': f'source "{source}" not known'}
if destination not in balance:
return {'err': f'destination "{destination}" not known'}
output = ""
global record_changes
saved_record_changes = record_changes
record_changes = False
change = [args]
ret = transaction(sender, ["!zieh", source, amount_raw], "")
if 'err' in ret:
# No changes yet we can fail
return {'err': ret['err']}
output += ret['msg']
# Sender <- X Source
change.append((sender, source, -amount_cent))
ret = transaction(sender, ["!schieb", destination, amount_raw], "")
err = ret.get('err', None)
if err:
output += err + "\nThe balance may be in a inconsistent state please take care manually"
return {'msg': output}
output += ret['msg']
# Sender -> X Destination
change.append((sender, destination, amount_cent))
ret = transaction(source, ["!zieh", destination, amount_raw], "")
err = ret.get('err', None)
if err:
output += err + "\nThe balance may be in a inconsistent state please take care manually"
return {'msg': output}
output += ret['msg']
# Destination -> X Source
change.append((destination, source, amount_cent))
record_changes = saved_record_changes
if err is None and record_changes and not dry_run:
changes[sender].append(change)
return {'msg': output}
cmds["transfer"] = transfer
def cars(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
# list cars
if len(args) < 2 or args[1] in ["ls", "list"]:
if len(available_cars) == 0:
return {'msg': 'No cars registered yet.'}
ret_msg = ""
if len(args) > 2:
cars_to_list = args[2:]
else:
cars_to_list = available_cars
for car in cars_to_list:
if car in available_cars:
ret_msg += f"{car} - service charge {available_cars[car]}ct/km\n"
ret_msg += create_summary(car) + "\n"
else:
return {'err': f'"{car}" is no available car\n'}
return {'msg': ret_msg[:-1]}
# add car
if args[1] in ["add", "new"]:
if len(args) < 4:
return {
'err':
f'not in form "{args[0]} {args[1]} car-name service-charge"'
}
car = args[2]
if car in available_cars:
return {'err': f'"{car}" already registered'}
if car in balance:
return {
'err':
f'A user named "{car}" already exists. Please use a different name for this car'
}
try:
service_charge = to_cent(args[3])
except (ValueError, TypeError):
return {'err': 'service-charge must be a positive number'}
available_cars[car] = service_charge
add_to_balance(car)
return {'msg': f'added "{car}" as an available car'}
# remove car
if args[1] in ["rm", "remove"]:
if len(args) < 3:
return {'err': f'not in form "{args[0]} {args[1]} car-name"'}
car = args[2]
if car not in available_cars:
return {'err': f'A car with the name "{car}" does not exists'}
del available_cars[car]
remove_from_balance(car)
return {'msg': f'removed "{car}" from the available cars'}
# pay bill
if args[1] in ["pay"]:
if len(args) < 4:
return {
'err': f'not in form "{args[0]} {args[1]} car-name amount"'
}
if not sender in num2name:
return {'err': 'you must register first'}
sender_name = num2name[sender]
car = args[2]
if car not in available_cars:
return {'err': f'car "{car}" not known'}
try:
amount = to_cent(args[3])
amount_euro = to_euro(amount)
except (ValueError, TypeError):
return {'err': 'amount must be a positive number'}
output = ""
global record_changes
saved_record_changes = record_changes
record_changes = False
change = [args]
total_available_charge = 0
available_charges = []
for person in balance[car]:
_amount = balance[car][person]
if _amount < 0:
total_available_charge -= _amount
available_charges.append((person, _amount))
proportion = -1
if amount < total_available_charge:
proportion = -1 * (amount / total_available_charge)
ret = transaction(sender, f'!gib {car} {amount_euro}'.split(), '')
assert 'err' not in ret
output += f"{sender_name} payed {amount_euro}\n"
# transfer money
output += f"Transferring {proportion * -100:.2f}% of everybody's charges\n"
for person, _amount in available_charges:
if person == sender_name or _amount >= 0:
continue
to_move = int(_amount * proportion)
to_move_euro = to_euro(to_move)
ret = transfer(sender, ['transfer', to_move_euro, car, person], '')
assert 'err' not in ret
output += "Transfer {} from {} to {}\n".format(
to_move_euro, person, sender_name)
output += "New Balances:\n"
output += create_summary(sender_name) + "\n"
output += create_summary(car)
record_changes = saved_record_changes
if record_changes and not dry_run:
changes[sender_name].append(change)
return {'msg': output}
return {'err': f'unknown car subcommand "{args[1]}".'}
cmds["cars"] = cars
def _tanken(sender, args, msg) -> dict[str, str]:
if len(args) < 2:
return {'err': f'not in form "{args[0]} amount [person] [car] [info]"'}
try:
amount = to_cent(args[1])
except (ValueError, TypeError):
return {'err': 'amount must be a number'}
# find recipient
if len(args) > 2 and args[2] in name2num:
recipient = args[2]
elif sender in num2name:
recipient = num2name[sender]
else:
return {'err': 'recipient unknown'}
# find car
car = None
if len(args) > 2 and args[2] in available_cars:
car = args[2]
elif len(args) > 3 and args[3] in available_cars:
car = args[3]
service_charge = 0
if car:
service_charge = available_cars[car]
parts, err = tanken.tanken(msg[1:], amount, service_charge)
if err:
return {'err': err}
output = ""
change = [args]
for pname, values in parts.items():
output += pname + ": {}km = fuel: {}, service charge: {}\n".format(
values["distance"], to_euro(values["cost"]),
to_euro(values["service_charge"]))
# record service charges
if pname not in name2num:
output += pname + " not known."
if car:
person_to_charge = pname
if pname not in name2num:
person_to_charge = recipient
output += f" {recipient} held accountable for service charge."
record(car, person_to_charge, values["service_charge"])
change.append([car, person_to_charge, values["service_charge"]])
# recipient paid the fuel -> don't charge them
if pname == recipient:
continue
if pname in name2num:
record(recipient, pname, values["cost"])
change.append([recipient, pname, values["cost"]])
else:
output += " Please collect fuel cost manually\n"
if record_changes and not dry_run:
changes[num2name[sender]].append(change)
output += "New Balance:\n"
output += create_summary(recipient)
if car:
output += "\nCar "
output += create_summary(car)
return {'msg': output}
cmds["tanken"] = _tanken
def fuck(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if not sender in num2name:
return {'err': 'you must register first'}
name = num2name[sender]
nchanges = len(changes[name])
if nchanges == 0:
return {'msg': 'Nothing to rewind'}
change_to_rewind = -1
if len(args) >= 2:
try:
change_to_rewind = int(args[1]) - 1
except ValueError:
return {'err': 'change to rewind must be a number'}
if change_to_rewind > nchanges:
return {'err': 'change to rewind is bigger than there are changes'}
# pop last item
last_changes = changes[name].pop(change_to_rewind)
args, last_changes = last_changes[0], last_changes[1:]
output = name + ": sorry I fucked up!\nRewinding:\n"
output += ' '.join(args) + "\n"
for change in last_changes:
if not change[0] in cmds:
output += "{} {} {} {}\n".format(change[0],
("->" if change[2] < 0 else "<-"),
to_euro(abs(change[2])),
change[1])
record(change[1], change[0], change[2])
for change in last_changes:
if change[0] in cmds:
ret = cmds[change[0]](sender, change, "")
if 'err' in ret:
output += "ERROR: " + ret['err']
else:
output += ret['msg']
return {'msg': output}
cmds["fuck"] = fuck
cmds["rewind"] = fuck
cmds["undo"] = fuck
def list_changes(sender, args, msg) -> dict[str, str]:
if not sender in num2name:
return {'err': 'you must register first'}
sender_name = num2name[sender]
changes_to_list = 5
if len(args) >= 2:
try:
changes_to_list = int(args[1])
except ValueError:
return {'err': 'the amount of changes to list must be a number'}
nchanges = len(changes[sender_name])
if nchanges == 0:
return {'msg': 'Nothing to list'}
first_to_list = max(nchanges - changes_to_list, 0)
if len(args) == 3:
try:
first_to_list = int(args[2]) - 1
except ValueError:
return {'err': 'the first change to list must be a number'}
if first_to_list > nchanges:
return {
'err':
'the first change to list is bigger than there are changes'
}
msg = ""
i = 0
for i, change in enumerate(changes[sender_name]):
if i < first_to_list:
continue
if i >= first_to_list + changes_to_list:
# i is used to track how many changes we listed
# This change will not be listed so decrement i before extiting the loop.
i -= 1
break
msg += f'Change {i + 1}:\n'
msg += f'\t{" ".join(change[0])}\n'
for sender, recipient, amount in change[1:]:
msg += "\t{} {} {} {}\n".format(sender,
("->" if amount < 0 else "<-"),
to_euro(abs(amount)), recipient)
# prepend message header because we want to know how much changes we actually listed
msg = f'Changes from {sender_name} {first_to_list + 1}-{i + 1}\n' + msg
return {'msg': msg}
cmds["list-changes"] = list_changes
def export_state(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if not sender in num2name:
return {'err': 'you must register first'}
msg = f'State from {datetime.now().date().isoformat()}'
return {'msg': msg, 'attachment': state_file}
cmds["export-state"] = export_state
def schedule(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
if not sender in num2name:
return {'err': 'you must register first'}
sender_name = num2name[sender]
if len(args) < 3:
return {'err': f'not in form "{args[0]} name cmd"'}
name = args[1]
cmd = args[2:]
if name in scheduled_cmds:
return {'err': f'there is already a scheduled command named "{name}"'}
# Test the command
global dry_run
old_dry_run, dry_run = dry_run, True
ret = cmds[cmd[0]](sender, cmd, '')
dry_run = old_dry_run
if 'err' in ret:
return {'err': 'the command "{}" failed and will not be recorded'}
scheduled_cmd = {
"schedule": args[0][1:],
"last_time": None,
"sender": sender,
"cmd": cmd
}
scheduled_cmds[name] = scheduled_cmd
output = 'Recorded the {} command "{}" as "{}"\n'.format(
args[0][1:], ' '.join(cmd), name)
output += "Running {} command {} for {} initially\n".format(
scheduled_cmd["schedule"], name, sender_name)
ret = cmds[cmd[0]](sender, cmd, "")
if 'err' in ret:
output += 'ERROR: ' + ret['err']
else:
output += ret['msg']
changes[sender_name][0].append(["cancel", name])
now = datetime.now().date()
scheduled_cmd["last_time"] = now.isoformat()
return {'msg': output}
cmds["weekly"] = schedule
cmds["monthly"] = schedule
cmds["yearly"] = schedule
def cancel(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
cmd_name = args[1]
if not cmd_name in scheduled_cmds:
return {'err': f'"{cmd_name}" is not a scheduled command'}
cmd = scheduled_cmds[cmd_name]
if not cmd["sender"] == sender:
return {'err': 'only the original creator can cancel this command'}
del scheduled_cmds[cmd_name]
return {'msg': f'Cancelled the {cmd["schedule"]} cmd "{cmd_name}"'}
cmds["cancel"] = cancel
def thanks(sender, args, msg) -> dict[str, str]: # pylint: disable=unused-argument
sender_name = num2name.get(sender, sender)
msg = f'You are welcome. It is a pleasure to work with you, {sender_name}.'
nick = None if len(args) == 1 else args[1]
if nick:
msg = f"{msg}\nBut don't call me {nick}."
return {'msg': msg}
cmds["thanks"] = thanks
def main():
if len(sys.argv) > 1 and sys.argv[1] in ["-d", "--dry-run"]:
global dry_run
dry_run = True
print("Dry Run no changes will apply!")
# Read cmds from stdin
for l in sys.stdin.read().splitlines():
try:
message = json.loads(l)["envelope"]
except:
print(datetime.now(), l, "not valid json")
continue
sender_number = message["source"]
if not "dataMessage" in message or not message[
"dataMessage"] or not message["dataMessage"]["message"]:
continue
else:
message = message["dataMessage"]
if message["groupInfo"] and message["groupInfo"][
"groupId"] != group_id:
continue
body = [l.strip() for l in message["message"].lower().splitlines()]
if len(body) == 0:
continue
args = body[0].split(' ')
if args[0].startswith("!"):
cmd = args[0][1:]
if cmd in cmds:
ret = cmds[cmd](sender_number, args, body)
if 'err' in ret:
send(f'ERROR: {ret["err"]}')
else:
if not 'msg' in ret:
print(ret)
send(ret['msg'], attachment=ret.get('attachment', None))
else:
send('ERROR: unknown cmd. Enter !help for a list of commands.')
# Handle scheduled commands
global record_changes
record_changes = False
now = datetime.now().date()
week_delta = timedelta(days=7)
for name, cmd in scheduled_cmds.items():
last_time = cmd["last_time"]
if hasattr(date, "fromisoformat"):
last_time = date.fromisoformat(last_time)
else:
last_time = date(*map(int, last_time.split("-")))
d = last_time
while True:
if cmd["schedule"] == "yearly":
d = date(d.year + 1, d.month, d.day)
elif cmd["schedule"] == "monthly":
if d.day > 28:
d = date(d.year, d.month, 28)
if d.month == 12:
d = date(d.year + 1, 1, d.day)
else:
d = date(d.year, d.month + 1, d.day)
else:
d = d + week_delta
if d <= now:
send("Running {} command {} for {} triggered on {}\n".
format(cmd["schedule"], name, num2name[cmd["sender"]],
d.isoformat()))
ret = cmds[cmd["cmd"][0]](cmd["sender"], cmd["cmd"], "")
if 'err' in ret:
send("ERROR: " + ret['err'])
else:
send(ret['msg'])
cmd["last_time"] = d.isoformat()
else:
break
with open(state_file, "w") as f:
json.dump(state, f)
if __name__ == "__main__":
main()
|