-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
416 lines (336 loc) · 14.3 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import discord
import os
import random
import asyncio
import json
from datetime import datetime, timedelta
from dotenv import load_dotenv
from discord.ext import commands
# Initialize the bot's start time
start_time = datetime.now()
# Load environment variables
load_dotenv()
# Retrieve the bot token from the environment variable
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.guilds = True
intents.members = True
intents.presences = True
# Initialize the bot
bot = discord.Bot(intents=intents)
# Load or create user_data.json
if os.path.exists('users.json'):
with open('users.json', 'r') as f:
user_data = json.load(f)
else:
user_data = {}
# Save user_data to JSON file
def save_user_data():
with open('users.json', 'w') as f:
json.dump(user_data, f, indent=4)
# Define XP requirements for each level
xp_requirements = [20, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 675, 725, 800, 875, 950, 1000, 1200, 1500, 1750, 2000]
# Dictionary to keep track of the last XP gain time for each user
last_xp_time = {}
# Function to add XP
def add_xp(user_id, author_name, xp, display_name, author_avatar, server_id, message_time=None):
user_id = str(user_id)
server_id = str(server_id)
current_time = datetime.now()
# Check if user has received XP in the last minute
if user_id in last_xp_time:
if current_time - last_xp_time[user_id] < timedelta(minutes=1):
return
last_xp_time[user_id] = current_time
if message_time is None:
message_time = current_time.isoformat()
else:
# Ensure message_time is in correct format
try:
datetime.fromisoformat(message_time)
except ValueError:
message_time = current_time.isoformat()
if user_id not in user_data:
user_data[user_id] = {
'global': {
'xp': 0,
'level': 1,
'name': author_name,
'avatar': str(author_avatar),
'first_login': message_time,
'last_login': message_time,
'used_display_names': {server_id: [{
'display_name': display_name,
'first_seen': message_time,
'last_seen': message_time
}]}
},
'servers': {
server_id: {
'xp': 0,
'level': 1
}
}
}
else:
user_data[user_id]['global']['name'] = author_name
user_data[user_id]['global']['avatar'] = str(author_avatar)
if 'first_login' not in user_data[user_id]['global']:
user_data[user_id]['global']['first_login'] = message_time
if 'last_login' not in user_data[user_id]['global'] or message_time > user_data[user_id]['global']['last_login']:
user_data[user_id]['global']['last_login'] = message_time
if server_id not in user_data[user_id]['global']['used_display_names']:
user_data[user_id]['global']['used_display_names'][server_id] = []
found = False
for display_name_entry in user_data[user_id]['global']['used_display_names'][server_id]:
if display_name_entry['display_name'] == display_name:
display_name_entry['last_seen'] = message_time
found = True
break
if not found:
user_data[user_id]['global']['used_display_names'][server_id].append({
'display_name': display_name,
'first_seen': message_time,
'last_seen': message_time
})
if server_id not in user_data[user_id]['servers']:
user_data[user_id]['servers'][server_id] = {
'xp': 0,
'level': 1
}
# Add XP globally
user_data[user_id]['global']['xp'] += xp
# Add XP for the specific server
user_data[user_id]['servers'][server_id]['xp'] += xp
# Check for global level up
while user_data[user_id]['global']['level'] <= len(xp_requirements) and user_data[user_id]['global']['xp'] >= xp_requirements[user_data[user_id]['global']['level'] - 1]:
user_data[user_id]['global']['level'] += 1
# Check for server level up
while user_data[user_id]['servers'][server_id]['level'] <= len(xp_requirements) and user_data[user_id]['servers'][server_id]['xp'] >= xp_requirements[user_data[user_id]['servers'][server_id]['level'] - 1]:
user_data[user_id]['servers'][server_id]['level'] += 1
save_user_data()
def is_owner(ctx):
"""Checks if the message author is the bot owner."""
return ctx.author.id == 706119023422603335 or ctx.author.id == 1152272215459504188
async def change_status():
"""Changes the bot's status periodically."""
await bot.wait_until_ready()
playing_statuses = [
'with fire',
'with pycord',
'with Python',
'a game',
'with Linux',
]
watching_statuses = [
"YouTube",
"a Movie",
"you",
]
listening_statuses = [
"Music",
"a Podcast",
"Radio",
"Darknet Diaries"
]
while not bot.is_closed():
activity_type = random.choice(["playing", "watching", "listening"])
if activity_type == "playing":
status = random.choice(playing_statuses)
activity = discord.Game(name=status)
elif activity_type == "watching":
status = random.choice(watching_statuses)
activity = discord.Activity(type=discord.ActivityType.watching, name=status)
elif activity_type == "listening":
status = random.choice(listening_statuses)
activity = discord.Activity(type=discord.ActivityType.listening, name=status)
await bot.change_presence(activity=activity)
print(f"Status changed to {activity_type} {status}")
await asyncio.sleep(300)
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
guilds_data = []
print('Guilds:')
for guild in bot.guilds:
members_data = []
async for member in guild.fetch_members(limit=None):
member_data = {
'id': member.id,
'name': member.name,
'is_bot': member.bot,
'display_name': member.display_name,
'top_role': member.top_role.id,
'joined_at': member.joined_at.isoformat() if member.joined_at else None
}
members_data.append(member_data)
guild_data = {
'guild_id': guild.id,
'guild_name': guild.name,
'member_count': guild.member_count,
'owner_id': guild.owner_id,
'description': guild.description,
'preferred_locale': guild.preferred_locale,
'verification_level': str(guild.verification_level),
'explicit_content_filter': str(guild.explicit_content_filter),
'mfa_level': str(guild.mfa_level),
'features': guild.features,
'members': members_data
}
guilds_data.append(guild_data)
with open('guilds.json', 'w') as f:
json.dump(guilds_data, f, indent=4)
print(f'- {guild.name} (ID: {guild.id})')
print(f' - Member count: {guild.member_count}')
await bot.change_presence(status=discord.Status.online)
bot.loop.create_task(change_status())
# add level counting
@bot.event
async def on_message(message):
if message.author.bot:
return
add_xp(message.author.id, message.author.name, 10, message.author.display_name, message.author.avatar, message.guild.id)
@bot.slash_command(name="help", description="Get help from the Bot")
async def help(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard",
description="Commands:",
color=0x00b0f4
)
embed.add_field(name="/help", value="Shows this message", inline=False)
embed.add_field(name="/tools", value="Get a list of the tools of the bot", inline=False)
embed.add_field(name="/games", value="Get a list of the games of the bot", inline=False)
embed.add_field(name="/modtools", value="Get a list of the tools for moderators of the bot", inline=False)
embed.add_field(name="/github", value="Shows link to the bot's GitHub repository", inline=False)
embed.add_field(name="/uptime", value="Shows the Uptime of the bot", inline=False)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name='github', description="Shows link to the bot's GitHub repository")
async def github(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard Github",
description="This is a discord bot, coded in Python!\nGitHub: https://github.com/arbs09/python-discordbot",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name="uptime", description="Check the bot's uptime")
async def uptime(ctx: discord.ApplicationContext):
current_time = datetime.now()
uptime = current_time - start_time
weeks, remainder = divmod(int(uptime.total_seconds()), 604800)
days, remainder = divmod(remainder, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
embed = discord.Embed(
title="PyGuard Uptime",
description=f"{weeks} weeks, {days} days, {hours} hours, {minutes} minutes, {seconds} seconds",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name='changestatus', description="changes the status of the bot")
async def changestatus(ctx: discord.ApplicationContext):
if not is_owner(ctx):
return
embed = discord.Embed(
title="PyGuard Status Change",
description="Status manually changed!",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
await change_status()
@bot.slash_command(name="games", description="Get a list of the games of the bot")
async def games(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard",
description="Games:",
color=0x00b0f4
)
embed.add_field(name="/slots", value="Play slots", inline=False)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name='slots', description="Shows link to the bot's GitHub repository")
async def slots(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard Slots",
description="This game is currently a work in progress",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name="tools", description="Get a list of the tools of the bot")
async def tools(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard",
description="Tools:",
color=0x00b0f4
)
embed.add_field(name="/getuserid", value="Get your discord user id", inline=False)
embed.add_field(name="/getgloballevel", value="Check your global level and XP", inline=False)
embed.add_field(name="/locallevel", value="Check your local server level and XP", inline=False)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name='getuserid', description="Get the ID of the user running the command")
async def get_user_id(ctx: discord.ApplicationContext):
user_id = ctx.author.id
embed = discord.Embed(
title="Your User ID:",
description=f"{user_id}",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name="getgloballevel", description="Check your global level and XP")
async def getgloballevel(ctx: discord.ApplicationContext):
user_id = str(ctx.author.id)
noxpembed = discord.Embed(
title="PyGuard Global Level",
description=f"{ctx.author.mention}, you have no XP yet.",
color=0x00b0f4
)
if user_id in user_data:
user_level = user_data[user_id]['global']['level']
user_xp = user_data[user_id]['global']['xp']
embed = discord.Embed(
title="PyGuard Global Level",
description=f"{ctx.author.mention}, you are at level {user_level} with {user_xp} XP globally.",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
else:
await ctx.respond(embed=noxpembed, ephemeral=True)
@bot.slash_command(name="locallevel", description="Check your local server level and XP")
async def locallevel(ctx: discord.ApplicationContext):
user_id = str(ctx.author.id)
server_id = str(ctx.guild.id)
noxpembed = discord.Embed(
title="PyGuard Local Level",
description=f"{ctx.author.mention}, you have no XP yet in this server.",
color=0x00b0f4
)
if user_id in user_data and server_id in user_data[user_id]['servers']:
user_level = user_data[user_id]['servers'][server_id]['level']
user_xp = user_data[user_id]['servers'][server_id]['xp']
embed = discord.Embed(
title="PyGuard Local Level",
description=f"{ctx.author.mention}, you are at level {user_level} with {user_xp} XP in this server.",
color=0x00b0f4
)
await ctx.respond(embed=embed, ephemeral=True)
else:
await ctx.respond(embed=noxpembed, ephemeral=True)
@bot.slash_command(name="modtools", description="Get a list of the tools for moderators of the bot")
async def modtools(ctx: discord.ApplicationContext):
embed = discord.Embed(
title="PyGuard",
description="Mod tools:",
color=0x00b0f4
)
embed.add_field(name="/cleanup", value="Clear messages in a channel", inline=False)
await ctx.respond(embed=embed, ephemeral=True)
@bot.slash_command(name='cleanup', description="Clear messages in a channel")
async def clear(ctx: discord.ApplicationContext, amount: int):
if not ctx.author.guild_permissions.manage_messages:
await ctx.respond("You don't have permission to use this command.", ephemeral=True)
return
if amount > 100:
await ctx.respond("You can only delete up to 100 messages at a time.", ephemeral=True)
return
deleted = await ctx.channel.purge(limit=amount)
await ctx.respond(f'Deleted {len(deleted)} messages.', ephemeral=True)
TARGET_LINKS = ["deadshot.io", "venge.io", "othergame1.io", "othergame2.io"]
bot.run(TOKEN)