From 87d07ac5b9a4529199cb3f807e4ceff982c588c2 Mon Sep 17 00:00:00 2001 From: Benji Dial Date: Thu, 5 Sep 2024 21:16:43 -0400 Subject: new new version --- post-poll.py | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 post-poll.py (limited to 'post-poll.py') diff --git a/post-poll.py b/post-poll.py new file mode 100644 index 0000000..8a5bc98 --- /dev/null +++ b/post-poll.py @@ -0,0 +1,79 @@ +from os import environ +import argparse +import discord +import sqlite3 +import time + +ap = argparse.ArgumentParser() +ap.add_argument('database', help='the file with the database') +ap.add_argument('channel', help='the discord id of the channel to post to') +ap.add_argument('hours', help='the number of hours to have the poll open for') + +a = ap.parse_args() + +hours = int(a.hours) + +if 'TOKEN' not in environ: + print('please set an environment variable TOKEN with the bot token') + exit(1) + +token = environ['TOKEN'] + +dbcon = sqlite3.connect(a.database) + +cur = dbcon.cursor() + +last_number = cur.execute(''' + SELECT poll_number FROM polls + ORDER BY poll_number DESC + LIMIT 1 +''').fetchone() + +poll_number = last_number[0] + 1 if last_number else 1 + +rows = cur.execute(''' + SELECT name, emoji FROM entries + WHERE status == 0 + ORDER BY last_poll_number, sort_number + LIMIT 2 +''').fetchall() + +if len(rows) < 2: + print('there aren\'t two entries available') + exit(0) + +def media(name, emoji): + emoji_obj = {'id': emoji} if emoji.isascii() and emoji.isdigit() else {'name': emoji} + return {'text': name, 'emoji': emoji_obj} + +result = discord.post(discord.session(token), f'/channels/{a.channel}/messages', { + 'poll': { + 'question': {'text': f'Poll #{poll_number}'}, + 'answers': [{ + 'poll_media': media(rows[0][0], rows[0][1]) + }, { + 'poll_media': media(rows[1][0], rows[1][1]) + }], + 'duration': hours + } +}) + +posted = int(time.time()) +expires = posted + hours * 3600 +channel_id = result['channel_id'] +message_id = result['id'] + +cur.execute('INSERT INTO polls VALUES(?, ?, ?, ?, ?, ?, ?, NULL, NULL)', + (poll_number, rows[0][0], rows[1][0], posted, expires, channel_id, message_id)) + +cur.executemany(''' + UPDATE entries + SET status = 1, last_poll_number = ? + WHERE name = ? + LIMIT 1 +''', [ + (poll_number, rows[0][0]), + (poll_number, rows[1][0]) +]) + +dbcon.commit() -- cgit v1.2.3