-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
386 lines (322 loc) · 13.4 KB
/
bot.py
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
380
381
382
383
384
385
386
import discord
import aiosqlite
import configparser
from msghelper import MessageHelper
from reddithelper import RedditPost, FlairFinder
config = configparser.ConfigParser()
config.read('config.ini')
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(debug_guilds=[config['DISCORD']['guildid']], intents=intents)
database_file = "trademission.db"
fields = ['username', 'station_name', 'system_name', 'quantity',\
'commodity', 'carrier_name', 'profit', 'pad_size', 'mission_type']
table_trademission_sql = """
CREATE TABLE IF NOT EXISTS trademissions (
message_id TEXT UNIQUE,
username VARCHAR,
station_name VARCHAR,
system_name VARCHAR,
quantity VARCHAR,
commodity VARCHAR,
carrier_name VARCHAR,
profit VARCHAR,
pad_size TEXT,
mission_type TEXT
);
"""
async def conn(db_file=database_file):
"""
Create database connection and file
"""
try:
return await aiosqlite.connect(db_file)
except Exception as e:
print(e)
exit()
async def create_table(sql_conn, create_table_sql=table_trademission_sql):
"""
Create table with specified table statement
"""
try:
c = await sql_conn.cursor()
await c.execute(create_table_sql)
except Exception as e:
print(e)
exit()
async def insert_data(sql_conn, data, table='trademissions'):
"""
Sqlite UPSERT funcionality
Attempt insert, if message_id already exists:
update every passed field instead
"""
fields = ','.join(data.keys())
values_count = ",".join(["?"] * len(data.values()))
values = [v for v in data.values()]
conflict = list()
for d in data:
if d != 'message_id':
conflict.append(f'{d}="{data[d]}"')
conflict = ','.join(conflict)
insert_stmt = f"""
INSERT INTO {table} ({fields})
VALUES({values_count})
ON CONFLICT(message_id)
DO UPDATE SET {conflict};
"""
cur = await sql_conn.cursor()
await cur.execute(insert_stmt, values)
await sql_conn.commit()
async def select_data(sql_conn, message_id, table='trademissions'):
"""
Query specified table for specific row based off message_id
Returns sqlite.Row object which is a dict of 'column_name': 'value'
"""
cur = await sql_conn.cursor()
cur.row_factory = aiosqlite.Row
await cur.execute(f"SELECT * FROM {table} where message_id = ?", [message_id])
return await cur.fetchone()
async def delete_data(sql_conn, message_id, table='trademissions'):
"""
Delete row from DB based off message_id
"""
cur = await sql_conn.cursor()
await cur.execute(f"DELETE FROM {table} where message_id = ?", [message_id])
async def can_we_enable(data):
"""
Tests to see if all fields have values
Used in the workflow of enabling the Submit button in the TradeView
"""
try:
if all([data[f] for f in fields]):
return True
except KeyError:
return False
return False
async def update_select_view(view):
"""
If the mission_type (select fields) has been selected
set it to the Default, so it stays selected between modal loads
"""
if view.data['mission_type'] == 'unloading':
view.children[0].options[0].default = True
view.children[0].options[1].default = False
elif view.data['mission_type'] == 'loading':
view.children[0].options[0].default = False
view.children[0].options[1].default = True
return view
class TradeModal(discord.ui.Modal):
"""
Modal containing the fields for related Trade data:
commodity, carrier_name, profit, quantity (demand|supply)
Expects the view to be passed in so it can be checked/altered
"""
def __init__(self, view, *args, **kwargs) -> None:
self.view = view
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(
label = 'Commodity',
placeholder = 'Gold',
custom_id = 'commodity',
value = self.view.data['commodity']
)
)
self.add_item(discord.ui.InputText(
label = 'Carrier Name',
placeholder = 'Carrier Name (XYZ-123)',
custom_id = 'carrier_name',
value = self.view.data['carrier_name']
)
)
self.add_item(discord.ui.InputText(
label = 'Profit per ton',
placeholder = '12k or 1m',
custom_id = 'profit',
value = self.view.data['profit']
)
)
self.add_item(discord.ui.InputText(
label = 'Demand | Supply',
placeholder = '21k',
custom_id = 'quantity',
value = self.view.data['quantity']
)
)
async def callback(self, interaction):
self.view.data['message_id'] = str(interaction.message.id)
self.view.data['username'] = f'{interaction.user.name}#{interaction.user.discriminator}'
self.view.data['commodity'] = self.children[0].value.title()
self.view.data['carrier_name'] = self.children[1].value
self.view.data['profit'] = self.children[2].value
self.view.data['quantity'] = self.children[3].value
if await can_we_enable(self.view.data):
self.view.children[3].disabled = False
self.view = await update_select_view(self.view)
await interaction.response.edit_message(view=self.view)
class StationSystemModal(discord.ui.Modal):
"""
Modal containing the fields for the:
station_name, system_name, pad_size
Expects the view to be passed in so it can be checked/altered
"""
def __init__(self, view, *args, **kwargs) -> None:
self.view = view
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(
label = 'System',
placeholder = 'Wally Bei',
custom_id = 'system_name',
value = self.view.data['system_name']
)
)
self.add_item(discord.ui.InputText(
label = 'Station',
placeholder = 'Malerba',
custom_id = 'station_name',
value = self.view.data['station_name']
)
)
self.add_item(discord.ui.InputText(
label = 'Pad Size',
placeholder = 'L or M or S',
custom_id = 'pad_size',
value = self.view.data['pad_size']
)
)
async def callback(self, interaction):
self.view.data['message_id'] = str(interaction.message.id)
self.view.data['username'] = f'{interaction.user.name}#{interaction.user.discriminator}'
self.view.data['system_name'] = self.children[0].value
self.view.data['station_name'] = self.children[1].value
self.view.data['pad_size'] = self.children[2].value.upper()
if await can_we_enable(self.view.data):
self.view.children[3].disabled = False
self.view = await update_select_view(self.view)
await interaction.response.edit_message(view=self.view)
class ConfirmationView(discord.ui.View):
"""
View for displaying confirmation options while displaying:
reddit title, reddit body, discord message
Expects a data dict to be passed and a msg dict containing atleast a msg['dm']
"""
def __init__(self, msg, data, *args, **kwargs):
self.msg = msg
self.data = data
super().__init__(*args, **kwargs)
@discord.ui.button(label="Post to Reddit", row=0, style=discord.ButtonStyle.green)
async def spost_button_callback(self, button, interaction):
rp = RedditPost(self.msg, self.data['mission_type'])
submission = await rp.create_post()
crossposts = await rp.crosspost(submission)
xposts = [f'https://www.reddit.com{c.permalink}' for c in crossposts if c != None]
embed = discord.Embed(title="Successfully posted to Reddit", color=discord.Color.green())
embed.add_field(name='Main Post', value=submission.url, inline=False)
embed.add_field(name='CrossPosts', value=','.join(xposts), inline=False)
embed.add_field(name='Discord Paste', value=self.msg['dm'], inline=False)
await insert_data(await conn(), self.data)
await interaction.response.edit_message(content=None, embed=embed, view=None)
self.stop()
@discord.ui.button(label="Save (no Reddit)", row=0, style=discord.ButtonStyle.blurple)
async def save_button_callback(self, button, interaction):
await insert_data(await conn(), self.data)
embed = discord.Embed(title="Trade Mission Saved, no post to Reddit", color=discord.Color.blue())
embed.add_field(name='Discord Paste', value=self.msg['dm'], inline=False)
await interaction.response.edit_message(content=None, embed=embed, view=None)
self.stop()
@discord.ui.button(label="Delete", row=0, style=discord.ButtonStyle.red)
async def cancel_button_callback(self, button, interaction):
embed = discord.Embed(title="Trade Mission Deleted", color=discord.Color.blue())
await delete_data(await conn(), str(interaction.message.id))
await interaction.response.edit_message(content=None, embed=embed, view=None)
self.stop()
class TradeView(discord.ui.View):
"""
Main trade view containing the:
select menu, station|system modal, trade data modal
If self.data is not set, create a dict with default keys set to ''
"""
def __init__(self, embed=discord.Embed(), *args, **kwargs):
super().__init__(*args, **kwargs)
try:
self.data = self.data
except AttributeError:
self.data = dict.fromkeys(fields, '')
@discord.ui.select(
placeholder="Pick your Trade Mission Type",
row = 0,
options=[
discord.SelectOption(
label="Unload", value='unloading', default=False
),
discord.SelectOption(
label="Load", value='loading', default=False
),
],
)
async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction):
self.data['message_id'] = str(interaction.message.id)
self.data['mission_type'] = select.values[0]
self.data['username'] = f'{interaction.user.name}#{interaction.user.discriminator}'
if await can_we_enable(self.data):
self.children[3].disabled = False
view = await update_select_view(self)
await interaction.response.edit_message(view=view)
@discord.ui.button(label="Station | System", row=1, custom_id='station_system')
async def system_button_callback(self, button, interaction):
await interaction.response.send_modal(StationSystemModal(title='Station | System Info', view=self))
@discord.ui.button(label="Trade Data", row=1, custom_id='mission_data')
async def mission_button_callback(self, button, interaction):
await interaction.response.send_modal(TradeModal(title='Trade Data', view=self))
@discord.ui.button(label="Submit Trade", row=2, custom_id='submit', style=discord.ButtonStyle.green, disabled=True)
async def save_button_callback(self, button, interaction):
msg = MessageHelper(self.data)
self.msg = {}
self.msg['dm'] = await msg.build_discord_message()
self.msg['rb'] = await msg.build_reddit_body()
self.msg['rt'] = await msg.build_reddit_title()
embed = discord.Embed(title="Review the Data!", color=discord.Color.orange())
embed.add_field(name='Discord Paste', value=self.msg['dm'], inline=False)
embed.add_field(name='Reddit Title', value=self.msg['rt'], inline=False)
embed.add_field(name='Reddit Body', value=self.msg['rb'], inline=False)
await interaction.response.edit_message(content=None, embed=embed, view=ConfirmationView(msg=self.msg, data=self.data))
@discord.ui.button(label="Delete", row=2, custom_id='cancel', style=discord.ButtonStyle.red)
async def quit_button_callback(self, button, interaction):
embed = discord.Embed(title="Trade Mission Deleted", color=discord.Color.blue())
await delete_data(await conn(), str(interaction.message.id))
await interaction.response.edit_message(content=None, embed=embed, view=None)
self.stop()
trade = bot.create_group("trade", "Trade related commands")
@trade.command(description='Create Trade Mission')
async def mission(ctx: discord.ApplicationContext):
"""
/trade mission
"""
await ctx.respond("Fill out the Trade Mission Forms", view=TradeView(), ephemeral=True)
@trade.command(description='Flair lookup for a subreddit')
async def flairs(ctx: discord.ApplicationContext, subreddit):
"""
/trade flairs $subreddit
"""
ff = FlairFinder(subreddit.lower())
flair_data = await ff.find_flairs()
data = '```\n'
for flair in flair_data:
data += f'{flair} :: {flair_data[flair]}\n'
data += '```'
embed = discord.Embed(title=f"Flairs for {subreddit}", color=discord.Color.green())
embed.add_field(name='Flair Name | Flair ID', value=data, inline=False)
await ctx.respond(embed=embed, view=None, ephemeral=True)
@bot.event
async def on_ready():
"""
Make sure the table is created when bot starts
"""
await create_table(await conn())
@bot.event
async def on_disconnect():
"""
Close sqlite connection on disconnect, prevent locks
"""
conn = await conn()
conn.close()
bot.run(config['DISCORD']['bottoken'])