Skip to content

Instantly share code, notes, and snippets.

@daisylb
Created November 18, 2020 00:05
Show Gist options
  • Save daisylb/24d55d609bee64c7891a7ee8713c5b7d to your computer and use it in GitHub Desktop.
Save daisylb/24d55d609bee64c7891a7ee8713c5b7d to your computer and use it in GitHub Desktop.
Discord backstage invite webapp for PyConline AU 2020
from flask import Flask, redirect
import requests
from hmac import compare_digest as constant_time_compare
from walter.config import Config
import waitress
app = Flask(__name__)
with Config("PyCon AU", "Discord inviter") as config:
DISCORD_MAIN_CHANNEL = config("DISCORD_MAIN_CHANNEL")
DISCORD_BOT_TOKEN = config("DISCORD_BOT_TOKEN")
PRETIX_ORGANIZER = config("PRETIX_ORGANIZER")
PRETIX_EVENT = config("PRETIX_EVENT")
PRETIX_CHECKIN_LIST = config("PRETIX_CHECKIN_LIST")
PRETIX_SECRET = config("PRETIX_SECRET")
PRETIX_QUESTION_ID = config("PRETIX_QUESTION_ID", cast=int)
DEBUG = config("DEBUG", cast=bool, default=False)
PORT = config("PORT", cast=int, default=8000)
@app.route("/<secret>")
def hello_world(secret):
res = requests.post(
f"https://discord.com/api/v6/channels/{DISCORD_MAIN_CHANNEL}/invites",
json={"max_uses": 1, "unique": True},
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}",},
)
res.raise_for_status()
invite_code = res.json()["code"]
success = False
try:
ticket = requests.post(
f"https://pretix.eu/api/v1/organizers/{PRETIX_ORGANIZER}/events/{PRETIX_EVENT}/checkinlists/{PRETIX_CHECKIN_LIST}/positions/{secret}/redeem/",
json={"answers": {str(PRETIX_QUESTION_ID): invite_code},},
headers={"Authorization": f"Token {PRETIX_SECRET}"},
)
if ticket.status_code == 201:
success = True
return redirect(f"https://discord.gg/{invite_code}")
elif (
ticket.status_code == 400 and ticket.json()["reason"] == "already_redeemed"
):
old_invite_code = next(
x["answer"]
for x in ticket.json()["position"]["answers"]
if x["question"] == PRETIX_QUESTION_ID
)
return redirect(f"https://discord.gg/{old_invite_code}")
else:
ticket.raise_for_status()
finally:
if not success:
requests.delete(
f"https://discord.com/api/v6/invites/{invite_code}",
headers={"Authorization": f"Bot {DISCORD_BOT_TOKEN}",},
).raise_for_status()
if __name__ == "__main__":
if DEBUG:
app.run(debug=DEBUG, port=PORT)
else:
waitress.serve(app, listen=f"0.0.0.0:{PORT}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment