This repository was archived by the owner on Dec 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmodmail.py
More file actions
193 lines (154 loc) Β· 6.19 KB
/
modmail.py
File metadata and controls
193 lines (154 loc) Β· 6.19 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
import discord
import json
import os
import sys
from discord.ext.commands import command, Bot, Cog
from asyncio import sleep
CONFIG_PATH = "config.json"
default_config = {
"token": "[ add bot token here ]",
"developers": [],
"replacements": {},
"prefix": "^",
"mod_role": 0,
"blacklist": [],
"server": 0,
"mail_channel": 0,
"from_field": 1,
}
class ModmailBot(Cog):
def __init__(self, bot, config):
self.bot = bot
self.config = config
self.last_user = None
@Cog.listener("on_ready")
async def on_ready(self):
print(f"Signed in as {self.bot.user} ({self.bot.user.id})")
@Cog.listener("on_message")
async def on_message(self, message):
if not isinstance(message.channel, discord.DMChannel) or message.author.id == self.bot.user.id:
# not a DM, or it's just the bot itself
return
channel = self.bot.get_channel(self.config["mail_channel"])
if not channel:
print("Mail channel not found! Reconfigure bot!")
main_guild = self.bot.get_guild(self.config["server"])
if not main_guild:
print("Main Server ID is incorrect! Reconfigure bot!")
author = message.author
else:
author = main_guild.get_member(message.author.id)
if not author:
author = message.author
content = message.clean_content
embed = discord.Embed()
embed.set_author(name="{} ({}#{})".format(author.display_name, author.name, author.discriminator),
icon_url=author.avatar_url)
embed.timestamp = message.created_at
embed.set_footer(text='User ID: {}'.format(author.id))
embed.color = author.color
embed.add_field(name="Message", value=content[:1000] or "blank")
if len(content[1000:]) > 0:
embed.add_field(name="(Continued)", value=content[1000:])
await channel.send(content=f"{message.author.id}", embed=embed)
try:
await message.add_reaction('π¬')
except discord.ext.commands.errors.CommandInvokeError:
await message.channel.send('π¬')
self.last_user = author
async def _shutdown(self):
await self.bot.logout()
await self.bot.close()
self.bot.loop.stop()
@command()
async def dm(self, ctx, user : discord.User, *, msg):
if ctx.channel.id != self.config["mail_channel"]:
return
main_guild = self.bot.get_guild(self.config["server"])
if not main_guild:
print("Main Server ID is incorrect! Reconfigure bot!")
return ctx.send('Main Server Unavailable')
else:
if str(ctx.message.author.id) in config['replacements']:
author = main_guild.get_member(config['replacements'][str(ctx.message.author.id)])
if not author:
author = self.bot.user
try:
await ctx.message.add_reaction('π')
except:
await ctx.send('π')
else:
author = main_guild.get_member(ctx.message.author.id)
if not author:
author = self.bot.user
embed = discord.Embed()
if self.config["from_field"]:
embed.set_author(name="{} ({}#{})".format(author.display_name, author.name, author.discriminator),
icon_url=author.avatar_url)
else:
embed.set_author(name="Moderator Response", icon_url=ctx.channel.guild.icon)
embed.timestamp = ctx.message.created_at
embed.color = author.color
embed.add_field(name="Message", value=msg[:1000] or "blank", inline=False)
if len(msg) > 1000:
embed.add_field(name="(Continued)", value=msg[1000:], inline=False)
if ctx.message.attachments:
embed.add_field(name="Attachments", value=", ".join([i.url for i in ctx.message.attachments]))
await user.send(embed=embed)
try:
await ctx.message.add_reaction('π¬')
except:
await ctx.send('π¬')
self.last_user = user
@command(aliases=['r'])
async def reply(self, ctx, *, msg):
if self.last_user is None:
await ctx.send("No user to reply to!")
return
await self.dm.callback(self, ctx, user=self.last_user, msg=msg)
@command()
async def reee(self, ctx, user : discord.User, times : int, *, msg):
if ctx.author.id not in config["developers"]:
return
with ctx.typing():
for i in range(times):
if self.config["from_field"]:
await user.send(f"From {ctx.author.display_name}: {msg}")
else:
await user.send(msg)
await sleep(1.25)
await ctx.message.add_reaction('π¬')
@command()
async def shutdown(self, ctx):
if ctx.author.id not in config["developers"]:
return
await ctx.send('Shutting down...')
await self._shutdown()
@command()
async def restart(self, ctx):
if ctx.author.id not in config["developers"]:
return
await ctx.send('Restarting...')
await self._shutdown()
script = sys.argv[0]
if script.startswith(os.getcwd()):
script = script[len(os.getcwd()):].lstrip(os.sep)
if script.endswith('__main__.py'):
args = [sys.executable, '-m', script[:-len('__main__.py')].rstrip(os.sep).replace(os.sep, '.')]
else:
args = [sys.executable, script]
os.execv(sys.executable, args + sys.argv[1:])
def write_config(config: dict):
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent="\t")
def read_config():
with open(CONFIG_PATH) as f:
return json.load(f)
if not os.path.exists(CONFIG_PATH):
write_config(default_config)
print("No config detected; a new one has been written! Please edit config.json then run the bot again.")
sys.exit(1)
config = read_config()
bot = Bot(config["prefix"], description="A ModMail Bot.")
bot.add_cog(ModmailBot(bot, config))
bot.run(config["token"])