Skip to content

Commit b083124

Browse files
authored
Merge pull request #3 from PyBotDevs/improve-code-quality-again
Improve a bunch of code quality
2 parents dff489c + 67992e2 commit b083124

File tree

1 file changed

+53
-102
lines changed

1 file changed

+53
-102
lines changed

main.py

Lines changed: 53 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
1-
### Modules ###
1+
# Imports
22
import os
33
import time
44
import os.path
55
import discord
66
import datetime
7-
from keep_alive import keep_alive
87
import requests
98
import json
109
from discord.ext import commands
1110
from discord.ext.commands import *
1211
from discord.ext import tasks
13-
### Modules end ###
12+
from keep_alive import keep_alive
1413

15-
### Startup/variables ###
14+
# Startup and Variables
1615
ids = [
1716
816941773032390676,
1817
738290097170153472,
@@ -21,42 +20,32 @@
2120
]
2221
console = False
2322
log = True
24-
if os.name == 'nt':
25-
os.system('cls')
26-
else:
27-
os.system('clear')
23+
if os.name == 'nt': os.system('cls')
24+
else: os.system('clear')
2825
print('Checking for rate limit errors...')
2926
r = requests.head(url="https://discord.com/api/v1")
3027
try:
3128
print(f"Rate limit error found: {int(r.headers['Retry-After']) / 60} minutes left")
3229
raise(SystemExit)
33-
except:
34-
print("No rate limit found.")
30+
except: print("No rate limit found.")
3531
time.sleep(1)
3632
intents = discord.Intents.all()
3733
errHandlerVer = 'v2.4'
3834
botVer = 'v1.0'
39-
if os.name == 'nt':
40-
os.system('cls')
41-
else:
42-
os.system('clear')
35+
if os.name == 'nt': os.system('cls')
36+
else: os.system('clear')
4337
owner = '@notsniped'
4438
homedir = os.path.expanduser("~")
4539
client = commands.Bot(command_prefix="+", intents=intents)
4640
global startTime
4741
startTime = time.time()
4842
client.remove_command('help')
49-
### Startup\\variables end ###
50-
51-
### Command variables ###
5243
theme_color = 0xffbd59
5344
color_success = 0x77b255
5445
color_fail = 0xc92424
5546
rootdir = 'C://Users//dhruvbhat//OneDrive//Desktop//increment.io'
5647
loggerHandler_path = 'botLog/log.txt'
5748
errorHandler_path = 'botLog/errors.txt'
58-
### Functions and classes ###
59-
6049
correctnumber = {}
6150

6251
class colors:
@@ -65,48 +54,40 @@ class colors:
6554
green = '\033[92m'
6655
end = '\033[0m'
6756

68-
with open('database/count.json', 'r') as f:
69-
global count
70-
count = json.load(f)
71-
with open('database/configuration/countchannel.json', 'r') as f:
72-
global countchannel
73-
countchannel = json.load(f)
74-
with open('database/configuration/warning.json', 'r') as f:
75-
global warnmsg
76-
warnmsg = json.load(f)
77-
with open('database/configuration/autoreactions.json', 'r') as f:
78-
global autoreactions
79-
autoreactions = json.load(f)
57+
with open('database/count.json', 'r') as f: count = json.load(f)
58+
with open('database/configuration/countchannel.json', 'r') as f: countchannel = json.load(f)
59+
with open('database/configuration/warning.json', 'r') as f: warnmsg = json.load(f)
60+
with open('database/configuration/autoreactions.json', 'r') as f: autoreactions = json.load(f)
8061

8162
def savedata():
82-
with open('database/count.json', 'w+') as f:
83-
json.dump(count, f)
84-
with open('database/configuration/countchannel.json', 'w+') as f:
85-
json.dump(countchannel, f)
86-
with open('database/configuration/autoreactions.json', 'w+') as f:
87-
json.dump(autoreactions, f)
63+
with open('database/count.json', 'w+') as f: json.dump(count, f)
64+
with open('database/configuration/countchannel.json', 'w+') as f: json.dump(countchannel, f)
65+
with open('database/configuration/autoreactions.json', 'w+') as f: json.dump(autoreactions, f)
8866

8967
def get_time():
9068
now = datetime.datetime.now()
9169
return now.strftime("%H:%M:%S")
9270

93-
### Functions and classes end ###
94-
95-
## Events ###
71+
# Events
9672
@client.event
9773
async def on_ready():
98-
if os.name == 'nt':
99-
os.system('cls')
100-
else:
101-
os.system('clear')
102-
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=f"the epic comeback. (+help) | {str(len(client.guilds))} guilds"))
74+
if os.name == 'nt': os.system('cls')
75+
else: os.system('clear')
76+
await client.change_presence(
77+
activity=discord.Activity(
78+
type=discord.ActivityType.playing,
79+
name=f"the epic comeback. (+help) | {str(len(client.guilds))} guilds"
80+
)
81+
)
10382
print('Bot is online')
10483
print('==================')
10584
print('------------------')
10685
print('Bot Info')
10786
print(f'Bot version: {colors.cyan}{botVer}{colors.end}')
10887
print(f'Error handler version: {colors.cyan}{errHandlerVer}{colors.end}')
109-
print(f'Username: {colors.green}{client.user.name}{colors.end}\nId: {colors.green}{client.user.id}{colors.end}\nDeveloper name: {colors.green}{owner}{colors.end}')
88+
print(f"Username: {colors.green}{client.user.name}{colors.end}")
89+
print(f"Bot id: {colors.green}{client.user.id}{colors.end}")
90+
print(f"Developer name: {colors.green}{owner}{colors.end}")
11091
print('==================')
11192
print('Bot config:')
11293
print('------------------')
@@ -117,18 +98,13 @@ async def on_ready():
11798
print('------------------')
11899
print(f'Server count: {str(len(client.guilds))}')
119100
print('------------------')
120-
if bool(log) == True:
121-
print(f'Logging: {colors.green}{log}{colors.end}')
122-
print('==================')
123-
else:
124-
print(f'Logging: {colors.red}{log}{colors.end}')
125-
print('==================')
126-
pass
101+
if log: print(f'Logging: {colors.green}{log}{colors.end}')
102+
else: print(f'Logging: {colors.red}{log}{colors.end}')
103+
print('==================')
127104
print('Bot admins')
128105
print('------------------')
129106
print(colors.cyan)
130-
for id in ids:
131-
print(id)
107+
for id in ids: print(id)
132108
print(colors.end)
133109
print('==================')
134110
print('System info')
@@ -153,7 +129,7 @@ async def on_ready():
153129
print('Bot file size: ' + os.path.getsize(str(os.getcwd() + '\\main.py')))
154130
print('------------------')
155131

156-
# Error handler #
132+
# Error Handler
157133
@client.event
158134
async def on_command_error(ctx, error):
159135
now = datetime.datetime.now()
@@ -164,75 +140,64 @@ async def on_command_error(ctx, error):
164140
f.write(f'[{current_time}/WARN] Ignoring exception at CommandNotFound. Details: This command does not exist.\n')
165141
f.close()
166142
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at CommandNotFound. Details: This command does not exist.{colors.end}')
167-
else:
168-
pass
143+
else: pass
169144
if isinstance(error, discord.ext.commands.CommandOnCooldown):
170145
await ctx.send(f':warning: This command is currently on cooldown, try after **{str(datetime.timedelta(seconds=int(round(error.retry_after))))}**', delete_after=5)
171146
if os.name == 'nt':
172147
with open(errorHandler_path, 'a') as f:
173148
f.write(f'[{current_time}/WARN] Ignoring exception at CommandOnCooldown. Details: This command is currently on cooldown.\n')
174149
f.close()
175150
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at CommandOnCooldown. Details: This command is currently on cooldown.{colors.end}')
176-
else:
177-
pass
151+
else: pass
178152
if isinstance(error, discord.ext.commands.MissingRequiredArgument):
179153
await ctx.send(':x: Your command has missing required argument(s).', delete_after=3)
180154
if os.name == 'nt':
181155
with open(errorHandler_path, 'a') as f:
182156
f.write(f'[{current_time}/WARN] Ignoring exception at MissingRequiredArgument. Details: The command can\'t be executed because required arguments are missing.\n')
183157
f.close()
184158
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at MissingRequiredArgument. Details: The command can\'t be executed because required arguments are missing.{colors.end}')
185-
else:
186-
pass
159+
else: pass
187160
if isinstance(error, discord.ext.commands.MissingPermissions):
188161
await ctx.send(':x: You don\'t have permissions to use this command.', delete_after=3)
189162
if os.name == 'nt':
190163
with open(errorHandler_path, 'a') as f:
191164
f.write(f'[{current_time}/WARN] Ignoring exception at MissingPermissions. Details: The user doesn\'t have the required permissions.\n')
192165
f.close()
193166
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at MissingPermissions. Details: The user doesn\'t have the required permissions.{colors.end}')
194-
else:
195-
pass
167+
else: pass
196168
if isinstance(error, discord.ext.commands.BadArgument):
197169
await ctx.send(':x: Invalid argument.', delete_after=3)
198170
if os.name == 'nt':
199171
with open(errorHandler_path, 'a') as f:
200172
f.write(f'[{current_time}/WARN] Ignoring exception at BadArgument.\n')
201173
f.close()
202174
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at BadArgument.{colors.end}')
203-
else:
204-
pass
175+
else: pass
205176
if isinstance(error, discord.ext.commands.BotMissingPermissions):
206177
await ctx.send(':x: I don\'t have permissions to do this. Kindly manage my role permissions to get this feature working.')
207178
if os.name == 'nt':
208179
with open(errorHandler_path, 'a') as f:
209180
f.write(f'[{current_time}/WARN] Ignoring exception at BotMissingPermissions.\n Details: The bot doesn\'t have the required permissions.\n')
210181
f.close()
211182
print(f'{colors.red}[{current_time}/WARN] Ignoring exception at BotMissingPremissions. Details: The bot doesn\'t have the required permissions.{colors.end}')
212-
else:
213-
pass
214-
# Error handler end #
183+
else: pass
215184

216185
snipe_message_author = {}
217186
snipe_message_content = {}
218187

219188
@client.event
220189
async def on_message(message):
221190
global count
222-
if str(message.channel.id) in count: pass
223-
else:
191+
if str(message.channel.id) not in count:
224192
count[str(message.channel.id)] = 1
225193
savedata()
226-
if str(message.guild.id) in countchannel: pass
227-
else:
194+
if str(message.guild.id) not in countchannel:
228195
countchannel[str(message.guild.id)] = 0
229196
savedata()
230-
if str(message.guild.id) in warnmsg: pass
231-
else:
197+
if str(message.guild.id) not in warnmsg:
232198
warnmsg[str(message.guild.id)] = 0
233199
savedata()
234-
if str(message.guild.id) in autoreactions: pass
235-
else:
200+
if str(message.guild.id) not in autoreactions:
236201
autoreactions[str(message.guild.id)] = 1
237202
savedata()
238203
if not message.author.bot:
@@ -241,23 +206,15 @@ async def on_message(message):
241206
if int(message.content) == count[str(message.channel.id)]:
242207
count[str(message.channel.id)] += 1
243208
if autoreactions[str(message.guild.id)] == 1: await message.add_reaction('☑')
244-
else: pass
245209
savedata()
246210
else:
247211
if autoreactions[str(message.guild.id)] == 1: await message.add_reaction('❌')
248-
else: pass
249212
await message.reply(f'**Wrong!** The next number is `{count[str(message.channel.id)]}`', mention_author = False, delete_after = 3)
250213
except:
251214
if autoreactions[str(message.guild.id)] == 1: await message.add_reaction('⚠')
252-
else: pass
253-
else: pass
254-
else: pass
255215
await client.process_commands(message)
256216

257-
### Events end ###
258-
259-
### Commands ###
260-
217+
# Commands
261218
@client.command()
262219
async def uptime(ctx):
263220
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
@@ -289,18 +246,14 @@ async def serverstats(ctx):
289246
emb12.set_thumbnail(url=servericon)
290247
await ctx.send(embed = emb12)
291248

292-
## Moderation Commands End ##
293-
294-
## Count Commands ##
295-
249+
# Count Commands
296250
@client.command()
297251
@commands.has_permissions(administrator = True)
298252
async def setchannel(ctx):
299-
channel_to_set = ctx.channel.id
300253
try:
301-
countchannel[str(ctx.guild.id)] = channel_to_set
302-
savedata()
303-
await ctx.send(f':white_check_mark: <#{channel_to_set}> set as counting channel.')
254+
countchannel[str(ctx.guild.id)] = ctx.channel.id
255+
savedata()
256+
await ctx.send(f':white_check_mark: <#{channel_to_set}> set as counting channel.')
304257
except: await ctx.send(':x: Unable to set count channel. Try again later.')
305258

306259
@client.command()
@@ -322,20 +275,18 @@ async def reactions(ctx, setting:str):
322275

323276
@client.command(aliases=['setnum'])
324277
async def setnumber(ctx, arg1:int):
325-
if arg1 < 1: raise(discord.ext.commands.BadArgument)
326-
else:
327-
count[str(ctx.channel.id)] = arg1
328-
savedata()
329-
await ctx.reply(f':white_check_mark: Count set to `{count[str(ctx.channel.id)]}`')
278+
if arg1 < 1: raise(discord.ext.commands.BadArgument)
279+
else:
280+
count[str(ctx.channel.id)] = arg1
281+
savedata()
282+
await ctx.reply(f':white_check_mark: Count set to `{count[str(ctx.channel.id)]}`')
330283

331284
@client.command(aliases=['resetnumber', 'reset', 'resetnum'])
332285
async def resetcount(ctx):
333286
count[str(ctx.channel.id)] = 1
334287
savedata()
335288
await ctx.reply(':white_check_mark: Count successfully reset back to `1`')
336289

337-
## Count Commands End ##
338-
339-
### Commands end ###
290+
# Client initialization
340291
keep_alive()
341292
client.run('') # Insert your bot token here

0 commit comments

Comments
 (0)