-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
283 lines (257 loc) · 11.5 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# TOKEN DEL BOT
TOKEN = ""
# Archivo donde registrara logs (Quien ha usado, o intentado usar el bot, etc.)
LOG_FILE = "logs.txt"
# Archivos que contienen los codigos
CODES_FILE = "plata.txt", "diamante.txt", "oro.txt"
# Role ID
ROLE_ID = 867366769392091157
# Tiempo de espera para volver a usar el bot
COOLDOWN = 60
# imports
import asyncio
import discord
from discord.ext import commands
import random
import aiofiles
import time
from datetime import datetime
from colorama import Fore, init
init(autoreset=True)
gen_role = None
# command_prefix= simbolo para usar el bot
bot = commands.Bot(command_prefix="-", intents=discord.Intents.all(), case_insensitive=True) # prefix here
async def getEmbed(type, arg=None): # change colours if you want to here
if type == 0:
embed = discord.Embed(title="Envia el codigo.", description="Revisa tus DMs.", colour=discord.Colour.green())
return embed
elif type == 1:
embed = discord.Embed(title="Este es el codigo generado.", description=arg, colour=discord.Colour.blue())
return embed
elif type == 2:
embed = discord.Embed(title="Fuera de stock.", description="Los codigos estan fuera de stock.", colour=discord.Colour.red())
return embed
elif type == 3:
embed = discord.Embed(title="Tiempo de espera agotado.", description=f"Hay un tiempo de espera, quedan **{arg}**.", colour=discord.Colour.red())
return embed
elif type == 4:
embed = discord.Embed(title="No hay permisos.", description=f"No tienes permisos para usar este comando, se ha avisado al dueño.", colour=discord.Colour.red())
return embed
async def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%dh %2dm %2ds" % (hour, minutes, seconds)
async def log(event, user=None, info=None): # logging in log.txt if you want to edit them
now = datetime.now()
timedata = f"{now.strftime('%Y-%m-%d %H:%M:%S')}"
writeable = ""
if event == "generated":
writeable += "[ GENERADO ] "
elif event == "cooldown":
writeable += "[ TIEMPO DE ESPERA ] "
elif event == "no stock":
writeable += "[ SIN STOCK ] "
elif event == "no dms":
writeable += "[ NO DMS ] "
elif event == "bootup":
writeable += "\n[ BOT INICIADO ] "
elif event == "ping":
writeable += "[ PING ] "
elif event == "no perms":
writeable += "[ SIN PERMISOS ] "
elif event == "userinfo":
writeable += "[ INFORMACION DEL USUARIO ] "
elif event == "error":
writeable += "[ ERROR CRITICO ] "
writeable += timedata
try:
writeable += f" ID: {user.id} User: {user.name}#{user.discriminator} // "
except:
writeable += f" // "
if event == "generated":
info = info.strip('\n')
writeable += f"El usuario recibió el código con éxito: {info}"
elif event == "cooldown":
writeable += f"No se pudo enviar un código al usuario porque está en un tiempo de reutilización de {info}."
elif event == "no stock":
writeable += f"No se pudo enviar el código al usuario porque no hay stock."
elif event == "no dms":
writeable += f"No se pudo enviar un código al usuario porque sus DM estaban deshabilitados."
elif event == "bootup":
writeable += "El bot fue encendido."
elif event == "ping":
writeable += "El usuario usó el comando ping."
elif event == "no perms":
writeable += f"El usuario no tiene los permisos significativos para el comando {info} ."
elif event == "userinfo":
writeable += f"El usuario usó el comando userinfo en: {info}"
elif event == "error":
writeable += info
async with aiofiles.open(LOG_FILE, mode="a") as file:
await file.write(f"\n{writeable}")
if writeable.startswith("[ SIN STOCK ]"):
print(Fore.LIGHTYELLOW_EX + writeable.strip('\n'))
elif writeable.startswith("[ ERROR CRITICO ]"):
for x in range(3):
print(Fore.LIGHTRED_EX + writeable.strip('\n'))
elif writeable.startswith("[ BOT INICIADO ]"):
print(Fore.LIGHTGREEN_EX + writeable.strip('\n'))
@bot.event
async def on_ready():
global gen_role
try:
open(LOG_FILE, "x").close()
except:
pass
try:
open(CODES_FILE, "x").close()
except:
pass
await log("bootup")
for guild in bot.guilds:
role = guild.get_role(ROLE_ID)
if role != None:
gen_role = role
break
if gen_role == None:
await log("error", user=None, info=f"No se puede encontrar el rol ({ROLE_ID}) desde {bot.guilds[0].name}. Saliendo en 5 segundos.")
await asyncio.sleep(5)
exit()
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
time_retry = await convert(error.retry_after)
await ctx.send(content = ctx.author.mention, embed = await getEmbed(3, time_retry))
await log("cooldown", ctx.author, time_retry)
elif isinstance(error, commands.MissingRole):
await ctx.send(content = ctx.author.mention, embed = await getEmbed(4))
await log("no perms", ctx.author, "generate")
@bot.command()
@commands.cooldown(1, COOLDOWN) # 1 is codes per cooldown // 86400 is the cooldown time (is in second)
@commands.has_role(ROLE_ID) # role for gen perms
@commands.guild_only()
async def generate(ctx):
try:
dm_msg = await ctx.author.send("Procesando información...")
except:
embed = discord.Embed(title="DMs estan desactivados!", description="Debes activarlos para recibir el codigo.", colour=discord.Colour.red())
await ctx.send(content=ctx.author.mention, embed=embed)
await log("no dms", ctx.author)
return
async with aiofiles.open("oro.txt", mode="r") as file: # name of codes file
file_lines = await file.readlines()
try:
code = random.choice(file_lines)
except:
await dm_msg.edit(embed=await getEmbed(type=2), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=2), content=ctx.author.mention)
bot.get_command("viporo").reset_cooldown(ctx)
await log("no stock", ctx.author)
return
else:
file_lines.remove(code)
async with aiofiles.open("oro.txt", mode="w") as file: # name of codes file
for line in file_lines:
if file_lines[-1] != line:
await file.write(line)
else:
await file.write(line.strip("\n"))
await dm_msg.edit(embed=await getEmbed(type=1,arg=code), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=0), content=ctx.author.mention)
await log("generated", ctx.author, code)
@bot.command()
@commands.cooldown(1, COOLDOWN) # 1 is codes per cooldown // 86400 is the cooldown time (is in second)
@commands.has_role(ROLE_ID) # role for gen perms
@commands.guild_only()
async def generate(ctx):
try:
dm_msg = await ctx.author.send("Procesando información...")
except:
embed = discord.Embed(title="DMs estan desactivados!", description="Debes activarlos para recibir el codigo.", colour=discord.Colour.red())
await ctx.send(content=ctx.author.mention, embed=embed)
await log("no dms", ctx.author)
return
async with aiofiles.open("diamante.txt", mode="r") as file: # name of codes file
file_lines = await file.readlines()
try:
code = random.choice(file_lines)
except:
await dm_msg.edit(embed=await getEmbed(type=2), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=2), content=ctx.author.mention)
bot.get_command("vipdiamante").reset_cooldown(ctx)
await log("no stock", ctx.author)
return
else:
file_lines.remove(code)
async with aiofiles.open("diamante.txt", mode="w") as file: # name of codes file
for line in file_lines:
if file_lines[-1] != line:
await file.write(line)
else:
await file.write(line.strip("\n"))
await dm_msg.edit(embed=await getEmbed(type=1,arg=code), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=0), content=ctx.author.mention)
await log("generated", ctx.author, code)
@bot.command()
@commands.cooldown(1, COOLDOWN) # 1 is codes per cooldown // 86400 is the cooldown time (is in second)
@commands.has_role(ROLE_ID) # role for gen perms
@commands.guild_only()
async def generate(ctx):
try:
dm_msg = await ctx.author.send("Procesando información...")
except:
embed = discord.Embed(title="DMs estan desactivados!", description="Debes activarlos para recibir el codigo.", colour=discord.Colour.red())
await ctx.send(content=ctx.author.mention, embed=embed)
await log("no dms", ctx.author)
return
async with aiofiles.open("plata.txt", mode="r") as file: # name of codes file
file_lines = await file.readlines()
try:
code = random.choice(file_lines)
except:
await dm_msg.edit(embed=await getEmbed(type=2), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=2), content=ctx.author.mention)
bot.get_command("vipplata").reset_cooldown(ctx)
await log("no stock", ctx.author)
return
else:
file_lines.remove(code)
async with aiofiles.open("plata.txt", mode="w") as file: # name of codes file
for line in file_lines:
if file_lines[-1] != line:
await file.write(line)
else:
await file.write(line.strip("\n"))
await dm_msg.edit(embed=await getEmbed(type=1,arg=code), content=ctx.author.mention)
await ctx.send(embed=await getEmbed(type=0), content=ctx.author.mention)
await log("generated", ctx.author, code)
@bot.command()
async def userinfo(ctx, *, user : discord.Member = None):
if user == None:
user = ctx.author
if gen_role in user.roles:
des = f"Generador: `🟢`"
else:
des = f"Generador: `🔴`"
embed = discord.Embed(color=discord.Colour.blue(), description=des, title=" ")
embed.set_author(name=f"{user.name}#{user.discriminator}", icon_url=user.default_avatar_url)
await ctx.send(embed=embed, content=ctx.author.mention)
await log("userinfo", user=ctx.author, info=f"{user.name}#{user.discriminator}")
@bot.command()
async def ping(ctx):
embed = discord.Embed(title="Response Times", color=discord.Colour.blue()) # colour of ping command
embed.add_field(name="API", value=f"`Loading...`")
embed.add_field(name="Websocket", value=f"`{int(bot.latency * 1000)}ms`")
time_before = time.time()
edit = await ctx.send(embed=embed, content=f"{ctx.author.mention}")
time_after = time.time()
difference = int((time_after - time_before) * 1000)
embed = discord.Embed(title="Response Times", color=discord.Colour.green()) # colour of ping command
embed.add_field(name="API", value=f"`{difference}ms`")
embed.add_field(name="Websocket", value=f"`{int(bot.latency * 1000)}ms`")
await edit.edit(embed=embed, content=f"{ctx.author.mention}")
await log("ping", ctx.author)
bot.run(TOKEN)