-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.py
More file actions
114 lines (99 loc) · 4.93 KB
/
main.py
File metadata and controls
114 lines (99 loc) · 4.93 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
import asyncio
from datetime import datetime
import os
import discord
import time
from commands.game_commands import GameCommands
from commands.tile_commands import TileCommands
import config
from discord import app_commands
from commands.setup_commands import SetupCommands
from commands.player_commands import PlayerCommands
from commands.search_commands import SearchCommands
# from helpers import ImageCache
from helpers import ImageCache
from helpers.GamestateHelper import GamestateHelper
from listeners.ButtonListener import ButtonListener
from discord.ext import commands
import logging
logging.basicConfig(level=logging.INFO)
# import threading
class DiscordBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_ready(self):
self.loop.create_task(self.start_timer())
async def setup_hook(self) -> None:
print("Bot is starting")
await self.add_cog(SetupCommands(self))
await self.add_cog(TileCommands(self))
await self.add_cog(PlayerCommands(self))
await self.add_cog(ButtonListener(self))
await self.add_cog(GameCommands(self))
await self.add_cog(SearchCommands(self))
await self.add_cog(AdminCommands(self))
await self.tree.sync()
start_time = time.perf_counter()
print("Starting to load images")
ImageCache.ImageCacheHelper("images/resources")
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Total elapsed time for image load: {elapsed_time:.2f} seconds")
print("Bot is now ready.")
async def start_timer(self):
while True:
await self.checkGameTimers()
await asyncio.sleep(600 * 2)
async def checkGameTimers(self):
guild = bot.get_guild(1254475918873985094)
start_time = time.perf_counter()
if guild is None:
return
for x in range(0, 999):
gameName = f"aeb{x}"
if not os.path.exists(f"{config.gamestate_path}/{gameName}_saveFile.json"):
continue
game = GamestateHelper(None, gameName)
if len(game.gamestate.get("activePlayerColor", [])) > 0 and "lastPingTime" in game.gamestate:
current_time_seconds = time.time()
oldPingTime = game.gamestate["lastPingTime"]
if current_time_seconds - oldPingTime > 3600 * 12:
actions_channel = discord.utils.get(guild.channels, name=f"{game.game_id}-actions")
if actions_channel is not None and isinstance(actions_channel, discord.TextChannel):
player = game.getPlayerObjectFromColor(game.gamestate["activePlayerColor"][0])
message = f"{player['player_name']}, this is a gentle reminder that it is your turn."
await actions_channel.send(message)
game.updatePingTime()
else:
if "20MinReminder" in game.gamestate and len(game.gamestate["20MinReminder"]) > 0 and game.gamestate["activePlayerColor"][0] == game.gamestate["20MinReminder"][0]:
player = game.getPlayerObjectFromColor(game.gamestate["activePlayerColor"][0])
message = f"{player['player_name']}, this is a gentle reminder to end your turn."
actions_channel = discord.utils.get(guild.channels, name=f"{game.game_id}-actions")
if actions_channel is not None and isinstance(actions_channel, discord.TextChannel):
await actions_channel.send(message)
game.initilizeKey("20MinReminder")
end_time = time.perf_counter()
elapsed_time = end_time - start_time
button_log_channel = discord.utils.get(guild.channels, name="button-log")
if button_log_channel is not None and isinstance(button_log_channel, discord.TextChannel):
asyncio.create_task(button_log_channel.send(f"Took {elapsed_time:.2f} seconds to run the auto-ping"))
async def shutdown(self) -> None:
await self.close()
class AdminCommands(commands.Cog):
def __init__(self, bot: DiscordBot):
self.bot = bot
@app_commands.command(name='shutdown', description='Shuts down the bot.')
async def shutdown_command(self, interaction: discord.Interaction):
userID = str(interaction.user.id)
if userID != "488681163146133504" and userID != "265561667293675521":
await interaction.response.send_message("You are not authorised to use this command.")
return
await interaction.response.send_message("Shutting down the bot...")
await self.bot.shutdown()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = DiscordBot(command_prefix="$", intents=discord.Intents.all())
bot.run(config.token)