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
|
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
import tanken
"""Dict of dicts associating a second person to an amount"""
balance = {}
name2num = {}
num2name = {}
"""Dict associating users with their last change"""
last_change = {}
group_id = "GELD!!!"
send_cmd = "signal-cli -u irgendwer send -g irgendwem"
def record(sender, recipient, donor, amount):
"""Apply change to the balance and save it"""
balance[donor][recipient] -= amount
balance[recipient][donor] += amount
last_change[sender] = [recipient, donor, amount]
def to_cent(euro):
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])
return euro[0] * 100 + euro[1]
def to_euro(cents):
return str(cents/100)
def send(msg):
subprocess.run(send_cmd.split(' '), input=msg.encode())
def create_summary(user):
summary = ""
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
total -= amount
summary += "\t{} {} {}\n".format("<-" if amount < 0 else "->", person, to_euro(abs(amount)))
if summary == "":
summary = "\tAll fine :)\n"
else:
summary += "\tBalance: {}".format(to_euro(total))
summary = user + ":\n" + summary
return summary
def create_total_summary():
summary = "Summary:"
for person in balance:
summary += '\n'
summary += "* " + create_summary(person)
return summary
def create_members():
r = ""
for m in name2num:
r += m + ": " + name2num[m] + "\n"
return r
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 a summary
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
tanken amount person [info] - calculate fuel costs and add them to the balance
fuck - rewind last change
Happy Geldschieben!
"""
def handle_input(inp):
messages = inp.split("\n\n")
for message in messages:
lines = message.split('\n')
# A message with Body must have at least 4 lines
if len(lines) < 4:
continue
lines[0].lower()
w = lines[0].split(' ')
# Broken message
if len(w) < 4:
print("Broken msg:")
print(message)
continue
# TODO support linked devices
sender_number = w[-3]
body_found = False
body = []
# message is not in the group with group_id
not_in_group = True
for idx, line in enumerate(lines[1:]):
# Collect body till we find Group ID:
# THIS COULD BREAK VERY EASILY
if line[0:6] == "Body: ":
body.append(line[6:])
body_found = True
elif body_found:
if not line == "Group info:":
body.append(line)
else:
not_in_group = lines[idx+1].strip() == "Id: " + group_id
break
if not_in_group:
continue
w = body[0].lower().split(' ')
cmd = w[0]
# supported commands are:
# "!reg" register a name for this number
# "!sum" send a summary to the group
# "!list" "!ls" list members
# "!help" print all commands
# "!split" "!teil" split amount between group
# "!schieb" "!gib" give money to somebody
# "!zieh" "!nimm" add debt of somebody
# "!tanken" calculate fuel cost parts
# "!fuck" rewind last change
if cmd == "!reg":
if len(w) != 2:
send('ERROR: not in form "!reg name"')
continue
if w[1] in name2num:
send("ERROR: name already registered")
elif sender_number in num2name:
send("ERROR: you are already registered")
else:
num2name[sender_number] = w[1]
name2num[w[1]] = sender_number
# add to balance
nm = {}
for m in balance:
balance[m][w[1]] = 0
nm[m] = 0
balance[w[1]] = nm
elif cmd == "!sum":
if len(w) == 1:
send(create_total_summary())
elif len(w) == 2:
if w[1] in name2num:
send("Summary:\n" + create_summary(w[1]))
else:
send("ERROR: name not registered")
else:
send('ERROR: not in form "!sum [name]"')
elif cmd == "!list" or cmd == "!ls":
send(create_members())
elif cmd == "!help":
send(create_help())
elif cmd == "!split" or cmd == "!teil":
if not sender_number in num2name:
send('ERROR: you must register first')
continue
if len(w) < 3:
send('ERROR: not in form "!{} [amount] [name]+"'.format(cmd))
continue
try:
amount = to_cent(w[1])
except:
send("ERROR: amount musst be a number")
continue
# -2 because amount and cmd; +1 because the sender is part of the group
persons = len(w) - 2 + 1
amount_per_person = int(amount/persons)
if sender_number in num2name:
recipient = num2name[sender_number]
else:
send("ERROR: you must register first")
continue
msg = "Split {} between {} -> {} each\n".format(to_euro(amount),
persons,
to_euro(amount_per_person))
for p in w[2:]:
if not p in name2num:
msg += p + " not known. Please take care manually\n"
else:
record(sender_number, recipient, p, amount_per_person)
msg += "New Balance:\n"
msg += create_summary(recipient)
send(msg)
elif cmd in ["!schieb", "!gib", "!zieh", "!nimm"]:
if len(w) != 3:
send('ERROR: not in form "!{} amount recipient"'.format(cmd))
continue
if not sender_number in num2name:
send('ERROR: you must register first')
continue
if w[1] in name2num:
recipient = w[1]
amount = w[2]
elif w[2] in name2num:
recipient = w[2]
amount = w[1]
else:
send('ERROR: recipient not known')
continue
sender = num2name[sender_number]
try:
amount = to_cent(amount)
except:
send("ERROR: amount musst be a number")
continue
if amount < 0:
send("ERROR: amount must be positiv")
continue
if cmd in ["!zieh", "!nimm"]:
amount *= -1
record(sender_number, sender, recipient, amount)
p_balance = balance[sender][recipient]
send("New Balance: {} {} {} {}\n".format(sender,
("->" if p_balance > 0 else "<-"),
to_euro(abs(p_balance)),
recipient))
elif cmd == "!tanken":
if len(w) < 3:
send('ERROR: !tanken not in form "!tanken amount person [info]"')
continue
try:
amount = to_cent(w[1])
except:
send("ERROR: amount musst be a number")
continue
if w[2] in name2num:
recipient = w[2]
elif sender_number in name2num:
recipient = num2name[sender_number]
else:
send("ERROR: recipient unknown")
continue
parts, err = tanken.tanken(body[1:], amount)
if err != None:
send("ERROR: " + err)
continue
msg = ""
for p in parts.items():
msg += p[0] + ": {}km = {}\n".format(p[1][0], to_euro(p[1][1]))
if p[0] != recipient:
if p[0] in name2num:
record(sender_number, recipient, p[0], p[1][1])
else:
msg += p[0] + " not known. Please take care manually\n"
msg += "New Balance:\n"
msg += create_summary(recipient)
send(msg)
elif cmd == "!fuck":
if not sender_number in num2name:
send("ERROR: you must register first")
continue
if not sender_number in last_change:
send("Nothing to rewind")
continue
changes = last_change[sender_number]
msg = num2name[sender_number] + ": sorry I fucked up!\n Rewinding:\n"
for change in changes:
msg += "{} -> {} {}\n".format(*change)
record(sender_number, change[1], change[0], change[2])
send(msg)
def main():
global group_id
group_id = os.environ["GSB_GROUP_ID"]
store_path = os.environ["GSB_STORE_PATH"]
balance_path = store_path + "/balance.json"
registration_path = store_path + "/registration.json"
last_change_path = store_path + "/last_change.json"
global send_cmd
send_cmd = os.environ["GSB_SEND_CMD"]
global balance
if os.path.isfile(balance_path):
balance = json.load(open(balance_path, "r"))
global name2num
global num2name
if os.path.isfile(registration_path):
name2num = json.load(open(registration_path, "r"))
for name in name2num:
num2name[name2num[name]] = name
global last_change
if os.path.isfile(last_change_path):
last_change = json.load(open(last_cahnge_path, "r"))
handle_input(sys.stdin.read())
with open(balance_path, "w") as f:
json.dump(balance, f)
with open(registration_path, "w") as f:
json.dump(name2num, f)
with open(last_change_path, "w") as f:
json.dump(last_change, f)
if __name__ == "__main__":
main()
|