-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
211 lines (182 loc) · 7.14 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
import discord
from discord.ext import commands
from constants import BOT_TOKEN
from views.delete import ConfirmDeleteModal
from views.poll import PollView
from helpers.db_funcs import add_poll, load_poll_data, connect_db
from helpers.discord_funcs import get_server_id
import logging
import os
logging.basicConfig(
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
)
logger = logging.getLogger(__name__)
# Heroku includes a 'DYNO' environment variable.
if "DYNO" in os.environ:
import sys
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.INFO)
logger.addHandler(stream_handler)
intents = discord.Intents.default()
intents.message_content = True # Ensure the bot can read message content
bot = commands.Bot(command_prefix="/", intents=intents)
# Find and load previous polls that contain a Poll ID.
# This is necessary to ensure that the bot can recover from a restart.
# Search through the previous 100 messages in each channel the bot can see.
async def load_previous_polls(bot: commands.Bot) -> None:
for channel in bot.get_all_channels():
if not isinstance(channel, discord.TextChannel):
continue
try:
async for message in channel.history(limit=100):
if message.author == bot.user:
# Check if the message content contains the Poll ID
if "Poll ID: " in message.content:
poll_id = get_poll_id_from_message(message.content)
poll_data = await load_poll_data(poll_id)
if poll_data:
logger.info(
f"Loaded poll {poll_id} in channel \
{channel.name}"
)
view = PollView(poll_data[0], message.author.id)
await view.init_poll_view() # Ensure initialization
await message.edit(
content=view.format_poll(), view=view
)
except discord.Forbidden:
logging.error(
f"Permission error while accessing channel {channel.name}"
)
except Exception as e:
logging.error(
f"Error loading previous polls in channel {channel.name}: {e}"
)
def get_poll_id_from_message(content: str) -> int:
# Extract the Poll ID from discord message content
prefix = "Poll ID: "
start = content.find(prefix) + len(prefix)
poll_id = content[start:]
logging.debug(f"Extracted Poll ID {poll_id}")
return int(poll_id)
async def get_message_from_poll_id(poll_id: int) -> discord.Message | None:
for channel in bot.get_all_channels():
if not isinstance(channel, discord.TextChannel):
continue
async for message in channel.history(limit=100):
if message.author == bot.user:
if "Poll ID: " in message.content:
if poll_id == get_poll_id_from_message(message.content):
logging.debug(
f"Found message for Poll ID {poll_id}: \
{message.content}"
)
return message
return None
@bot.event
async def on_ready() -> None:
logging.info(f"Logged in as {bot.user}!")
try:
await connect_db()
logging.info("Connected to database successfully.")
except Exception as e:
logging.error(f"Failed to connect to database: {e}")
try:
await bot.tree.sync()
logging.info("Slash commands synced successfully.")
except Exception as e:
logging.error(f"Failed to sync slash commands: {e}")
await load_previous_polls(bot)
logging.info("Loaded previous polls successfully.")
@bot.tree.command(name="createpoll") # type: ignore
async def create_poll(
interaction: discord.Interaction, question: str, options: str
) -> None:
options_list = [
opt.strip() for opt in options.split(",") if opt.strip() != ""
]
if len(options_list) < 2:
await interaction.response.send_message(
"You need at least two options to create a poll.", ephemeral=True
)
return
# Give the bot more time to respond to the interaction
await interaction.response.defer()
discord_server_id = get_server_id(interaction)
try:
poll_id = await add_poll(question, options_list, discord_server_id)
if poll_id is None:
logging.error("Failed to create poll")
raise ValueError("Failed to create poll")
view = PollView(poll_id, interaction.user.id)
await view.init_poll_view() # Ensure initialization completes
await interaction.followup.send(
f"**{question}** Poll ID: {poll_id}", view=view
)
except discord.Forbidden:
if interaction.guild:
logging.error(
f"Permission error while creating poll in guild \
{interaction.guild.name}"
)
await interaction.followup.send(
"I don't have permission to create a poll in this channel.",
ephemeral=True,
)
except Exception as e:
if interaction.guild:
logging.error(
f"Error creating poll in guild {interaction.guild.name}: {e}"
)
await interaction.followup.send(
"An error occurred while creating the poll.",
ephemeral=True,
)
@bot.tree.command(name="deletepoll") # type: ignore
async def delete_poll(
interaction: discord.Interaction,
poll_id: int,
) -> None:
is_admin = interaction.user.guild_permissions.administrator # type: ignore
if not is_admin:
await interaction.response.send_message(
"You must be an administrator to delete a poll.", ephemeral=True
)
return
message = await get_message_from_poll_id(poll_id)
if message is None:
await interaction.response.send_message(
"Poll not found or already deleted.", ephemeral=True
)
return
try:
modal = ConfirmDeleteModal(poll_id, message) # type: ignore
await interaction.response.send_modal(modal)
except discord.Forbidden:
if interaction.guild:
logging.error(
f"Permission error while deleting poll in guild \
{interaction.guild.name}"
)
await interaction.followup.send(
"I don't have permission to delete this poll.",
ephemeral=True,
)
except Exception as e:
if interaction.guild:
logging.error(
f"Error deleting poll in guild {interaction.guild.name}: {e}"
)
await interaction.followup.send(
"An error occurred while deleting the poll.",
ephemeral=True,
)
# Error handling
@bot.event
async def on_command_error(ctx, error) -> None: # type: ignore
if isinstance(error, commands.CommandNotFound):
return # Ignore commands that are not found
else:
logging.error(f"An error occurred: {error}")
raise error # other errors to be handled by the default handler
bot.run(BOT_TOKEN)