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
|
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()
|