forked from poketwo/poketwo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
198 lines (153 loc) · 5.61 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
import asyncio
from importlib import reload
import aiohttp
import discord
import uvloop
from aioredis_lock import LockTimeoutError, RedisLock
from discord.ext import commands
from expiringdict import ExpiringDict
import cogs
import helpers
uvloop.install()
DEFAULT_DISABLED_MESSAGE = (
"The bot's currently disabled. It may be refreshing for some quick updates, or down for another reason. "
"Try again later and check the #status channel in the official server for more details."
)
CONCURRENCY_LIMITED_COMMANDS = {
"auction",
"market",
"evolve",
"favorite",
"favoriteall",
"nickall",
"nickname",
"reindex",
"release",
"releaseall",
"select",
"unfavorite",
"unfavoriteall",
"unmega",
"buy",
"dropitem",
"embedcolor",
"moveitem",
"open",
"redeemspawn",
"trade",
}
async def determine_prefix(bot, message):
cog = bot.get_cog("Bot")
return await cog.determine_prefix(message.guild)
class ClusterBot(commands.AutoShardedBot):
class BlueEmbed(discord.Embed):
def __init__(self, **kwargs):
color = kwargs.pop("color", helpers.constants.BLUE)
super().__init__(**kwargs, color=color)
class Embed(discord.Embed):
def __init__(self, **kwargs):
color = kwargs.pop("color", helpers.constants.PINK)
super().__init__(**kwargs, color=color)
def __init__(self, **kwargs):
self.cluster_name = kwargs.pop("cluster_name")
self.cluster_idx = kwargs.pop("cluster_idx")
self.config = kwargs.pop("config", None)
if self.config is None:
self.config = __import__("config")
self.menus = ExpiringDict(max_len=300, max_age_seconds=300)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
super().__init__(**kwargs, loop=loop, command_prefix=determine_prefix)
# Load extensions
self.load_extension("jishaku")
for i in cogs.default:
self.load_extension(f"cogs.{i}")
self.add_check(
commands.bot_has_permissions(
read_messages=True,
send_messages=True,
embed_links=True,
attach_files=True,
read_message_history=True,
add_reactions=True,
external_emojis=True,
).predicate
)
self.activity = discord.Game("p!help • poketwo.net")
self.http_session = aiohttp.ClientSession()
# Run bot
self.loop.create_task(self.do_startup_tasks())
self.run(kwargs["token"])
async def get_context(self, message, *, cls=helpers.context.PoketwoContext):
return await super().get_context(message, cls=cls)
# Easy access to things
@property
def mongo(self):
return self.get_cog("Mongo")
@property
def redis(self):
return self.get_cog("Redis").pool
@property
def data(self):
return self.get_cog("Data").instance
@property
def sprites(self):
return self.get_cog("Sprites")
@property
def log(self):
return self.get_cog("Logging").log
# Other stuff
async def send_dm(self, user, *args, **kwargs):
# This code can wait until Messageable + Object comes out.
# user_data = await self.mongo.fetch_member_info(discord.Object(uid))
# if (priv := user_data.private_message_id) is None:
# priv = await self.http.start_private_message(uid)
# priv = int(priv["id"])
# self.loop.create_task(
# self.mongo.update_member(uid, {"$set": {"private_message_id": priv}})
# )
if not isinstance(user, discord.abc.Snowflake):
user = discord.Object(user)
dm = await self.create_dm(user)
return await dm.send(*args, **kwargs)
async def do_startup_tasks(self):
self.log.info(f"Starting with shards {self.shard_ids} and total {self.shard_count}")
await self.wait_until_ready()
self.log.info(f"Logged in as {self.user}")
async def on_ready(self):
self.log.info(f"Ready called.")
async def on_shard_ready(self, shard_id):
self.log.info(f"Shard {shard_id} ready")
async def on_message(self, message: discord.Message):
message.content = (
message.content.replace("—", "--").replace("'", "′").replace("‘", "′").replace("’", "′")
)
await self.process_commands(message)
async def invoke(self, ctx):
if ctx.command is None:
return
if not (
ctx.command.name in CONCURRENCY_LIMITED_COMMANDS
or (ctx.command.root_parent and ctx.command.root_parent.name in CONCURRENCY_LIMITED_COMMANDS)
):
return await super().invoke(ctx)
try:
async with RedisLock(self.redis, f"command:{ctx.author.id}", 60, 1):
return await super().invoke(ctx)
except LockTimeoutError:
await ctx.reply("You are currently running another command. Please wait and try again later.")
async def before_identify_hook(self, shard_id, *, initial=False):
async with RedisLock(self.redis, f"identify:{shard_id % 16}", 5, None):
await asyncio.sleep(5)
async def close(self):
self.log.info("shutting down")
await super().close()
async def reload_modules(self):
reload(cogs)
reload(helpers)
for i in dir(helpers):
if not i.startswith("_"):
reload(getattr(helpers, i))
for i in cogs.default:
self.reload_extension(f"cogs.{i}")
await self.do_startup_tasks()