· 4 years ago · Aug 11, 2021, 05:00 PM
1import smtplib, ssl
2from email.mime.multipart import MIMEMultipart
3from email.mime.text import MIMEText
4from email.mime.base import MIMEBase
5from email import encoders
6import discord
7from discord.ext import commands
8import sqlite3
9import re
10import os
11import random
12import requests
13from dotenv import load_dotenv
14load_dotenv()
15#password = os.getenv calls the .env file and looks for the name in quotes (the env file should have multiple lines each one saying something like "" Emailpass = FAKEP@ssWORD ""
16password = os.getenv("TOKENNAME")
17#ehlo is not needed normally for this version, unless you are using a weird setup like i am
18ehlo = "youremail@gmail.com"
19
20
21#the conn section creates a data base (required to prevent the same user from trying to verify multiple times)
22conn = sqlite3.connect('bot.db')
23c = conn.cursor()
24c.execute("""CREATE TABLE IF NOT EXISTS users(
25 userid INT,
26 guildid INT,
27 email TEXT,
28 code INT,
29 verified INT);
30""")
31c.execute("""CREATE TABLE IF NOT EXISTS guilds(
32 guildid INT PRIMARY KEY,
33 domains TEXT,
34 onjoin INT,
35 role TEXT);
36""")
37conn.commit()
38
39def get_guild(guildid):
40 return c.execute("SELECT * FROM guilds WHERE guildid=?", (guildid,)).fetchone()
41
42def new_guild(guildid, domains="", onjoin=0, role="Verified"):
43 c.execute("INSERT INTO guilds VALUES (?, ?, ?, ?)", (guildid, domains, onjoin, role))
44 conn.commit()
45
46def get_user_guild(guildid, userid):
47 return c.execute("SELECT * FROM users WHERE guildid=? AND userid=?", (guildid, userid)).fetchone()
48
49def get_users_guilds(userid):
50 return c.execute("SELECT * FROM users WHERE userid=?", (userid,)).fetchall()
51
52def get_emails_guilds(guildid, email):
53 return c.execute("SELECT * FROM users WHERE guildid=? AND email=? AND verified=1", (guildid, email)).fetchall()
54
55def get_users_codes(userid, code):
56 return c.execute("SELECT * FROM users WHERE userid=? AND code=?", (userid, code)).fetchall()
57#the user will get the message exactly as typed so mention the possible emails they can use
58def verify_msg(guildname, domains):
59 if domains == "":
60 return "{} hasn't setup this bot yet.".format(guildname)
61 else:
62 return "To verify yourself on {}, **reply here with your @gmail.com email address**.".format(guildname, domains)
63
64def new_user(userid, guildid, email="", code=0, verified=0):
65 c.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?)", (userid, guildid, email, code, verified))
66 conn.commit()
67
68def verify_user(userid, guildid):
69 c.execute("UPDATE users SET verified=1 WHERE userid=? AND guildid=?", (userid, guildid))
70 conn.commit()
71
72def get_domains(guildid):
73 return get_guild(guildid)[1]
74
75def add_domain(domain, guildid):
76 d_get = get_domains(guildid)
77 prevdomains = []
78 if d_get != "":
79 prevdomains = get_domains(guildid).split('|')
80 if domain not in prevdomains:
81 prevdomains.append(domain)
82 c.execute("UPDATE guilds SET domains=? WHERE guildid=?", ('|'.join(prevdomains), guildid))
83 conn.commit()
84
85def remove_domain(domain, guildid):
86 prevdomains = get_domains(guildid).split('|')
87 if domain in prevdomains:
88 prevdomains.remove(domain)
89 c.execute("UPDATE guilds SET domains=? WHERE guildid=?", ('|'.join(prevdomains), guildid))
90 conn.commit()
91
92def change_role(role, guildid):
93 c.execute("UPDATE guilds SET role=? WHERE guildid=?", (role, guildid))
94 conn.commit()
95
96def enable_onjoin(guildid):
97 c.execute("UPDATE guilds SET onjoin=? WHERE guildid=?", (1, guildid))
98 conn.commit()
99
100def disable_onjoin(guildid):
101 c.execute("UPDATE guilds SET onjoin=? WHERE guildid=?", (0, guildid))
102 conn.commit()
103
104def insert_code(code, userid, guildid):
105 c.execute("UPDATE users SET code=? WHERE userid=? AND guildid=?", (code, userid, guildid))
106 conn.commit()
107
108def insert_email(email, userid, guildid):
109 c.execute("UPDATE users SET email=? WHERE userid=? AND guildid=?", (email, userid, guildid))
110 conn.commit()
111
112def email_check(email):
113 regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"
114 if re.search(regex, email):
115 return True
116 else:
117 return False
118
119
120intents = discord.Intents.default()
121intents.members = True
122
123client = commands.Bot(command_prefix = '.', intents=intents)
124
125@client.event
126async def on_ready():
127 print('We have logged in as {0.user}'.format(client))
128 await client.change_presence(activity=discord.Game(name='Verify Bot | Ping @tenecki with issues'))
129
130@client.event
131async def on_member_join(member):
132 check_on_join = get_guild(member.guild.id)
133 if check_on_join == None:
134 new_guild(member.guild.id)
135 elif check_on_join[2] == 1:
136 user_prev_verify = get_user_guild(member.guild.id, member.id)
137 if user_prev_verify == None:
138 await member.send(verify_msg(member.guild, check_on_join[1]))
139 new_user(member.id, member.guild.id)
140 elif user_prev_verify[4] == 0:
141 await member.send(verify_msg(member.guild, check_on_join[1]))
142 elif user_prev_verify[4] == 1:
143 role = discord.utils.get(member.guild.roles, name=check_on_join[3])
144 if role:
145 if role not in member.roles:
146 await member.add_roles(role)
147 else:
148 await member.guild.create_role(name=check_on_join[3])
149 role = discord.utils.get(member.guild.roles, name=check_on_join[3])
150 await member.add_roles(role)
151#from address is your email that the user will get the verification message from
152#
153@client.event
154async def on_message(message):
155 if message.author == client.user:
156 return
157 message_content = message.content.strip()
158 if (message.guild == None) and email_check(message_content):
159 users_guilds = get_users_guilds(message.author.id)
160 if len(users_guilds) >= 1:
161 guild_list = [i[1] for i in users_guilds if i[4] == 0]
162 verif_list = []
163 for i in guild_list:
164 email_guild = get_emails_guilds(i, message_content)
165 if len(email_guild) > 0:
166 continue
167 guild_domains = get_domains(i)
168 if len(guild_domains) == 0:
169 continue
170 guild_domains = guild_domains.split('|')
171 if message_content.split("@")[1] in guild_domains:
172 verif_list.append(i)
173 if len(verif_list) >= 1:
174 random_code = random.randint(100000, 999999)
175 for i in verif_list:
176 insert_code(random_code, message.author.id, i)
177 insert_email(message_content, message.author.id, i)
178 content= random_code
179 fromaddr = "youremail@gmail.com"
180 try:
181 toaddr = (message_content)
182 msg = MIMEMultipart()
183 msg['From'] = fromaddr
184 msg['To'] = toaddr
185 msg['Subject'] = "YOUR subjest"
186 body = 'Please use the following generated code to verify your status as A BLANK' + " : " +(str(content))
187 msg.attach(MIMEText(body, 'plain'))
188 p = MIMEBase('application', 'octet-stream')
189 msg.attach(p)
190 s = smtplib.SMTP('smtp.gmail.com', 587)
191 s.starttls()
192 s.login(fromaddr, password)
193 text = msg.as_string()
194 s.sendmail(fromaddr, toaddr, text)
195 await message.channel.send("Email sent. **Reply here with your verification code**. If you haven't received it, check your spam folder.")
196 except smtplib.SMTPResponseException as e:
197 error_code = e.smtp_code
198 error_message = e.smtp_error
199 print("Error code:"+error_code)
200 print("Message:"+error_message)
201 if (error_code==422):
202 print("Recipient Mailbox Full")
203 elif(error_code==431):
204 print("Server out of space")
205 elif(error_code==447):
206 print("Timeout. Try reducing number of recipients")
207 elif(error_code==510 or error_code==511):
208 print("One of the addresses in your TO, CC or BBC line doesn't exist. Check again your recipients' accounts and correct any possible misspelling.")
209 elif(error_code==512):
210 print("Check again all your recipients' addresses: there will likely be an error in a domain name (like mail@domain.coom instead of mail@domain.com)")
211 elif(error_code==541 or error_code==554):
212 print("Your message has been detected and labeled as spam. You must ask the recipient to whitelist you")
213 elif(error_code==550):
214 print("Though it can be returned also by the recipient's firewall (or when the incoming server is down), the great majority of errors 550 simply tell that the recipient email address doesn't exist. You should contact the recipient otherwise and get the right address.")
215 elif(error_code==553):
216 print("Check all the addresses in the TO, CC and BCC field. There should be an error or a misspelling somewhere.")
217 else:
218 print(error_code+": "+error_message)
219 else:
220 await message.channel.send("Invalid email.")
221 else:
222 await message.channel.send("You have not joined a server.")
223 elif (len(message_content) == 6) and message_content.isdigit():
224 verif_code = int(message_content)
225 prev_codes_f = get_users_codes(message.author.id, verif_code)
226 prev_codes_g = [i for i in prev_codes_f if i[4] == 0]
227 prev_codes = []
228 for i in prev_codes_g:
229 user_emails = get_emails_guilds(i[1], i[2])
230 if len(user_emails) >= 1:
231 continue
232 else:
233 prev_codes.append(i)
234 if len(prev_codes) >= 1:
235 for i in prev_codes:
236 verify_user(message.author.id, i[1])
237 curr_guild = client.get_guild(i[1])
238 guild_db = get_guild(i[1])
239 role = discord.utils.get(curr_guild.roles, name=guild_db[3])
240 if role:
241 member = curr_guild.get_member(message.author.id)
242 if role not in member.roles:
243 await member.add_roles(role)
244 else:
245 await curr_guild.create_role(name=guild_db[3])
246 role = discord.utils.get(curr_guild.roles, name=guild_db[3])
247 member = curr_guild.get_member(message.author.id)
248 await member.add_roles(role)
249 await message.channel.send("You have been verified on " + client.get_guild(i[1]).name + ".")
250 else:
251 await message.channel.send("Incorrect code.")
252 elif message.guild == None:
253 await message.channel.send("Invalid email.")
254 await client.process_commands(message)
255
256@client.event
257async def on_guild_join(guild):
258 check_on_join = get_guild(guild.id)
259 if check_on_join == None:
260 new_guild(guild.id)
261
262@client.command()
263async def rolechange(ctx, role=None):
264 if role and ctx.guild and ctx.author.guild_permissions.administrator:
265 role = role.strip()
266 check_on_join = get_guild(ctx.guild.id)
267 if check_on_join == None:
268 new_guild(ctx.guild.id)
269 check_on_join = get_guild(ctx.guild.id)
270 role_d = discord.utils.get(ctx.guild.roles, name=check_on_join[3])
271 if role_d:
272 await role_d.edit(name=role)
273 change_role(role, ctx.guild.id)
274 await ctx.send("```Verified role: " + get_guild(ctx.guild.id)[3] + "```")
275 else:
276 role_d2 = discord.utils.get(ctx.guild.roles, name=role)
277 if role_d2:
278 change_role(role, ctx.guild.id)
279 await ctx.send("```Verified role: " + get_guild(ctx.guild.id)[3] + ".```")
280 else:
281 await ctx.guild.create_role(name=role)
282 change_role(role, ctx.guild.id)
283 await ctx.send("```Verified role: " + get_guild(ctx.guild.id)[3] + ".```")
284
285@client.command()
286async def domainadd(ctx, domain=None):
287 if domain and ctx.guild and ctx.author.guild_permissions.administrator:
288 domain = domain.strip()
289 check_on_join = get_guild(ctx.guild.id)
290 if check_on_join == None:
291 new_guild(ctx.guild.id)
292 add_domain(domain, ctx.guild.id)
293 await ctx.send("```Current email domains: " + get_domains(ctx.guild.id) + "```")
294
295@client.command()
296async def domainremove(ctx, domain=None):
297 if domain and ctx.guild and ctx.author.guild_permissions.administrator:
298 domain = domain.strip()
299 check_on_join = get_guild(ctx.guild.id)
300 if check_on_join == None:
301 new_guild(ctx.guild.id)
302 remove_domain(domain, ctx.guild.id)
303 await ctx.send("```Current email domains: " + get_domains(ctx.guild.id) + "```")
304
305@client.command()
306async def enableonjoin(ctx):
307 if ctx.guild and ctx.author.guild_permissions.administrator:
308 check_on_join = get_guild(ctx.guild.id)
309 if check_on_join == None:
310 new_guild(ctx.guild.id)
311 enable_onjoin(ctx.guild.id)
312 await ctx.send("```Verify when a user joins? True```")
313
314@client.command()
315async def disableonjoin(ctx):
316 if ctx.guild and ctx.author.guild_permissions.administrator:
317 check_on_join = get_guild(ctx.guild.id)
318 if check_on_join == None:
319 new_guild(ctx.guild.id)
320 disable_onjoin(ctx.guild.id)
321 await ctx.send("```Verify when a user joins? False```")
322
323@client.command()
324async def vstatus(ctx):
325 if ctx.guild:
326 check_on_join = get_guild(ctx.guild.id)
327 if check_on_join == None:
328 new_guild(ctx.guild.id)
329 check_on_join = get_guild(ctx.guild.id)
330 on_join = bool(check_on_join[2])
331 await ctx.send("```" +
332 "Ping: " + "{0}ms".format(round(client.latency * 1000)) + "\n" +
333 "User commands: " + "\n" +
334 " .verify -> Sends a DM to the user to verify their email" + "\n" +
335 " .vstatus -> This help message" + "\n\n" +
336 "Admin commands: " + "\n" +
337 " - A domain must be added before users can be verified." + "\n" " - Use .rolechange instead of server settings to change the name of the verified role." + "\n" +
338 " .enableonjoin -> Enables verifying users on join" + "\n" +
339 " .disableonjoin -> Disables verifying users on join" + "\n" +
340 " .domainadd domain -> Adds an email domain" + "\n" +
341 " .domainremove domain -> Removes an email domain" + "\n" +
342 " .rolechange role -> Changes the name of the verified role" + "\n\n" +
343 "Domains: " + check_on_join[1] + "\n" +
344 "Verify when a user joins? (default=False): " + str(on_join) + "\n" +
345 "Verified role (default=Verified): " + check_on_join[3] + "```", delete_after=5)
346
347@client.command()
348async def vping(ctx):
349 await ctx.send("{0}ms".format(round(client.latency * 1000), delete_after=5))
350
351@client.command()
352async def verify(ctx):
353 if ctx.guild:
354 check_on_join = get_guild(ctx.guild.id)
355 if check_on_join == None:
356 new_guild(ctx.guild.id)
357 check_on_join = get_guild(ctx.guild.id)
358 user_prev_verify = get_user_guild(ctx.guild.id, ctx.author.id)
359 if user_prev_verify == None:
360 new_user(ctx.author.id, ctx.guild.id)
361 await ctx.author.send(verify_msg(ctx.guild, check_on_join[1]))
362 elif user_prev_verify[4] == 0:
363 await ctx.author.send(verify_msg(ctx.guild, check_on_join[1]))
364#ANOTHER ENV ENTRY!!!
365client.run(os.environ.get('TOKEN'))
366