Created
January 5, 2018 22:43
-
-
Save tylerkerr/3ec6a5f70fb0071cc2547a3b476a4181 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask import request | |
from requests import post | |
from slackclient import SlackClient | |
from datetime import datetime | |
import re | |
import os | |
import json | |
app = Flask(__name__) | |
@app.route('/bart', methods=['POST']) | |
def bartapp(): | |
if request.form.get('token', None) != os.environ.get('SLACK_SECRET'): | |
return 'what are you talking about' | |
slashcommand = request.form.get('command', None) | |
channel = request.form.get('channel_name', None) | |
srcuid = request.form.get('user_id', None) | |
srcname = request.form.get('user_name', None) | |
text = request.form.get('text', None) | |
cmdlog = '#' + channel, '@' + srcname, slashcommand, text | |
writelog(cmdlog) | |
try: | |
command = text.split(' ') | |
if len(command) != 2: | |
description = ' '.join(command[2:]) | |
description = '"_' + description + '_"' | |
targetname = command[0] | |
targetuid = getuid(targetname) | |
if command[1][0] == '+': | |
command[1] = command[1][1:] | |
amount = int(command[1]) | |
if amount == 0: | |
return "can't bart zero!" | |
if targetuid == srcuid: | |
return "can't bart yourself!" | |
except: | |
return 'syntax: bart user ±amount [optional desc]' | |
transferisvalid = validatetransfer(srcuid, targetuid, amount) | |
if amount == 1 or amount == -1: | |
amountword = 'point' | |
else: | |
amountword = 'points' | |
if transferisvalid: | |
srcprebalance = getbalance(srcuid) | |
targetprebalance = getbalance(targetuid) | |
if amount > 0: | |
value = amount * givemult | |
if value == 1: | |
valueword = 'point' | |
else: | |
valueword = 'points' | |
updatebalance(targetuid, value) | |
updatebalance(srcuid, amount * -1) | |
msg = "👼 <@{}> [{}] has spent {} {} to give <@{}> [{}] {} {}!"\ | |
.format(srcuid, getbalance(srcuid), amount, amountword, targetuid, | |
getbalance(targetuid), value, valueword) | |
elif amount < 0: | |
value = amount * takemult | |
updatebalance(targetuid, value) | |
updatebalance(srcuid, amount) | |
msg = "😈 <@{}> [{}] has spent {} {} to delete {} of <@{}>'s [{}] points!"\ | |
.format(srcuid, getbalance(srcuid), abs(amount), amountword, abs(value), | |
targetuid, getbalance(targetuid)) | |
sendlog = '{} [{} -> {}] > {} [{} -> {}]'\ | |
.format(srcname, srcprebalance, getbalance(srcuid), targetname, | |
targetprebalance, getbalance(targetuid)) | |
writelog(sendlog) | |
chat(msg) | |
try: | |
chat(description) | |
except: | |
pass | |
usermsg = '[{} -> {}]'.format(srcprebalance, getbalance(srcuid)) | |
return usermsg | |
def getbalance(uid: str): | |
uidfile = os.path.join(bartdb, uid) | |
if not os.path.isfile(uidfile): | |
makeuser(uid) | |
with open(uidfile, 'r') as uf: | |
balance = int(uf.read()) | |
return balance | |
def writelog(logline: str): | |
logfile = os.path.join(bartdb, 'ledger.log') | |
writeline = datetime.now().isoformat() + ' ' + str(logline) + '\n' | |
with open(logfile, 'a') as lf: | |
lf.write(writeline) | |
def validatetransfer(fromuid: str, touid: str, amount: int): | |
frombalance = getbalance(fromuid) | |
tobalance = getbalance(touid) | |
if amount > 0: | |
if frombalance >= amount: | |
return True | |
else: | |
return False | |
elif amount < 0: | |
if frombalance >= abs(amount) and tobalance >= abs(amount): | |
return True | |
else: | |
return False | |
def updatebalance(uid: str, amount: int): | |
uidfile = os.path.join(bartdb, uid) | |
newbalance = getbalance(uid) + amount | |
with open(uidfile, 'w') as uf: | |
uf.write(str(newbalance)) | |
def makeuser(uid: str): | |
print('making user', uid) | |
uidfile = os.path.join(bartdb, uid) | |
with open(uidfile, 'w') as uf: | |
uf.write(str(startingbalance)) | |
def chat(text: str): | |
chaturl = 'https://hooks.slack.com/services/T0DCWQSBV/B8MRQ1JKU/' + os.environ.get('SLACK_URL') | |
payload = {"text": text, "response_type": "in_channel"} | |
post(chaturl, json=payload) | |
def remapusers(): | |
slack_client = SlackClient(os.environ.get('SLACK_API_TOKEN')) | |
members = slack_client.api_call("users.list")['members'] | |
global usermap | |
usermap = {} | |
for memb in members: | |
if memb['is_bot'] is False and memb['name'] != 'slackbot': | |
usermap[memb['name']] = memb['id'] | |
usermap['garf'] = 'U0GARFMAN' # TESTING | |
usermapfile = os.path.join(bartdb, 'usermap.json') | |
with open(usermapfile, 'w') as um: | |
json.dump(usermap, um, ensure_ascii=False) | |
def getuid(name): | |
cleanname = re.sub('@', '', name) | |
if cleanname in usermap: | |
return usermap[cleanname] | |
else: | |
print('remap') | |
remapusers() | |
if cleanname in usermap: | |
return usermap[cleanname] | |
else: | |
print('no such user:', name) | |
raise ValueError('no such user') | |
def init(): | |
global bartdb | |
bartdb = os.path.join(os.getcwd(), 'bartdb') | |
if not os.path.isdir(bartdb): | |
os.mkdir(bartdb) | |
global usermap | |
usermapfile = os.path.join(bartdb, 'usermap.json') | |
if not os.path.isfile(usermapfile): | |
remapusers() | |
else: | |
with open(usermapfile, 'r') as um: | |
usermap = json.load(um) | |
global startingbalance | |
startingbalance = 128 | |
global givemult | |
givemult = 10 | |
global takemult | |
takemult = 1 | |
def main(): | |
init() | |
app.run(host='127.0.0.1', port=4999, debug=False) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment