-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbazaarbot.py
More file actions
219 lines (179 loc) · 8.85 KB
/
Copy pathbazaarbot.py
File metadata and controls
219 lines (179 loc) · 8.85 KB
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
import os
import discord
import asyncio
from discord import ui
from discord.ext import commands
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Get configuration from environment variables
TOKEN = os.getenv('DISCORD_TOKEN')
SETUP_CHANNEL_ID = int(os.getenv('SETUP_CHANNEL_ID', 0))
LISTINGS_CHANNEL_ID = int(os.getenv('LISTINGS_CHANNEL_ID', 0))
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
# Define the modal object for creating listings
class ListingModal(ui.Modal, title='Create a listing'):
subject = ui.TextInput(label='Subject', placeholder='Title of your listing', required=True)
description = ui.TextInput(label='Description', placeholder='Describe the item, it\'s condition, etc.',style=discord.TextStyle.long, required=True)
price = ui.TextInput(label='Price', placeholder='Desired price in USD, or trade value', required=True)
async def on_submit(self, interaction: discord.Interaction):
channel = bot.get_channel(LISTINGS_CHANNEL_ID)
if not channel:
await interaction.response.send_message("Error: Listings channel not found.", ephemeral=True, delete_after=20)
return
thread = await channel.create_thread(
name=self.subject.value,
type=discord.ChannelType.public_thread,
auto_archive_duration=10080, # 7 Days
reason="New sale listing created"
)
embed = discord.Embed(
title=self.subject.value,
description=self.description.value,
color=discord.Color.teal(),
timestamp=interaction.created_at
)
embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.display_avatar.url)
price_value = self.price.value.strip()
if price_value.isdigit():
price_value = f"${price_value}"
embed.add_field(name="Asking for", value=price_value, inline=False)
# Send the embed to the thread
await thread.send(embed=embed)
await interaction.response.send_message(f"Listing created: {thread.mention}", ephemeral=True, delete_after=300)
# Create a view for the create listing button
class ListingView(ui.View):
def __init__(self):
super().__init__(timeout=None) # Make the view persistent
@ui.button(label="Create Listing", style=discord.ButtonStyle.primary, custom_id="create_listing")
async def create_listing(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_modal(ListingModal())
@bot.event
async def on_ready():
print(f"{bot.user.name} has connected to Discord!")
print(f"Bot ID: {bot.user.id}")
# Sync commands with Discord
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Failed to sync commands: {e}")
# Initial setup message handling
await setup_message()
@bot.event
async def on_message(message):
# Process commands first
await bot.process_commands(message)
# Delete messages posted into the setup channel by non-owners
if message.channel.id == SETUP_CHANNEL_ID and message.author != bot.user:
if message.author != message.guild.owner:
try:
await message.delete()
except discord.Forbidden:
print(f"Error: Bot does not have permission to delete messages in {message.channel.name}")
except Exception as e:
print(f"Error deleting message: {e}")
# Setup an introduction message in the setup channel
async def setup_message():
setup_channel = bot.get_channel(SETUP_CHANNEL_ID)
if not setup_channel:
print(f"Error: Could not find setup channel with ID {SETUP_CHANNEL_ID}")
return
setup_content = (
"# Welcome to the Bazaar!\n"
"-# 'Lamp Oil, Rope, Bombs... you want it? It's yours my friend! As long as you have enough rubies.'\n\n"
f"This is our own tiny marketplace. Use this bot to create listings for things you are interested in selling or trading. Click the \"Create Listing\" button below to begin, or go to the <#{LISTINGS_CHANNEL_ID}> channel to see posted listings.\n\n"
"Rules:\n"
"1. For now, listings should be roughly local to the Oklahoma City area.\n"
"2. Listings should be for physical items only.\n"
"3. Nothing illegal, controversial, or morally ambiguous.\n"
"4. If an item has been sold, please use the \"/sold\" command inside the thread to delete it.\n"
)
# Find the most recent message from the bot in the setup channel
existing_message = None
async for message in setup_channel.history(limit=50):
if message.author == bot.user:
existing_message = message
break
# Update existing message or post a new one
try:
if existing_message:
await existing_message.edit(content=setup_content, view=ListingView())
print(f"Updated existing setup message in channel {setup_channel.name}")
else:
await setup_channel.send(content=setup_content, view=ListingView())
print(f"Created new setup message in channel {setup_channel.name}")
except discord.HTTPException as e:
print(f"Error sending/updating message: {e}")
# Ensure persistent views are loaded when the bot restarts
@bot.event
async def setup_hook():
bot.add_view(ListingView())
# Command to delete sold listings
@bot.tree.command(name="sold", description="Mark your bazaar listing as sold and delete the thread")
async def sold(interaction: discord.Interaction):
# Check if the command is used in a thread
if not isinstance(interaction.channel, discord.Thread):
await interaction.response.send_message("This command can only be used in listing threads.", ephemeral=True, delete_after=15)
return
# Check if the thread is in the correct channel
if interaction.channel.parent_id != LISTINGS_CHANNEL_ID:
await interaction.response.send_message("This command can only be used in listing threads.", ephemeral=True, delete_after=15)
return
# Get the first message in the thread which should contain the embed
first_message = None
async for message in interaction.channel.history(oldest_first=True, limit=1):
first_message = message
break
if not first_message:
await interaction.response.send_message("Could not find the listing information.", ephemeral=True, delete_after=15)
return
if not first_message.embeds:
await interaction.response.send_message("Could not find the listing information.", ephemeral=True, delete_after=15)
return
embed = first_message.embeds[0]
# Check if user is the author of the listing
if not embed.author or embed.author.name != interaction.user.display_name:
await interaction.response.send_message("Only the original poster can mark this listing as sold.", ephemeral=True, delete_after=15)
return
# Inform the user the thread will be deleted
await interaction.response.send_message("Marking this listing as sold. This thread will be deleted in 5 seconds.")
await asyncio.sleep(5)
# Find and delete the system message that created the thread
thread_name = interaction.channel.name
parent_channel = interaction.channel.parent
async for message in parent_channel.history(limit=100):
print(f"Message type: {message.type}, Content: {message.content[:50]}...")
# Then the rest of the code
if parent_channel:
try:
async for message in parent_channel.history(limit=100):
if (message.type == discord.MessageType.thread_created and
thread_name in message.content):
try:
await message.delete()
print(f"Successfully deleted system message for thread: {thread_name}")
break
except Exception as e:
print(f"Failed to delete thread creation message: {e}")
break
except Exception as e:
print(f"Error finding/deleting thread creation message: {e}")
await interaction.channel.delete()
# Run the bot
if __name__ == "__main__":
if not TOKEN:
print("Error: DISCORD_TOKEN not found in environment variables")
exit(1)
if SETUP_CHANNEL_ID == 0:
print("Error: SETUP_CHANNEL_ID not properly configured")
exit(1)
if LISTINGS_CHANNEL_ID == 0:
print("Error: LISTINGS_CHANNEL_ID not properly configured")
exit(1)
if SETUP_CHANNEL_ID == LISTINGS_CHANNEL_ID:
print("Error: SETUP_CHANNEL_ID and LISTINGS_CHANNEL_ID cannot be the same")
exit(1)
bot.run(TOKEN)