1
- import discord , asyncio , time , datetime , random , json , aiohttp , logging , os
1
+ import discord , asyncio , json , os , time , datetime , aiohttp , pathlib
2
+ from datetime import datetime
2
3
from discord .ext import commands
3
- from time import ctime
4
- from os import listdir
5
- from os .path import isfile , join
6
-
7
- with open ("databases/thesacredtexts.json" ) as f :
8
- config = json .load (f )
9
-
10
- class Spectrum_Bot (commands .AutoShardedBot ):
11
- def __init__ (self ):
12
- super ().__init__ (command_prefix = commands .when_mentioned_or ("$" ),
13
- owner_id = 276707898091110400 ,
14
- case_insensitive = True )
15
-
16
- async def update_activity (self ):
17
- await self .change_presence (
18
- activity = discord .Activity (
19
- name = f"@Spectrum help | { len (self .guilds )} guilds!" ,
20
- type = 1 ,
21
- url = "https://www.twitch.tv/SpectrixYT" ))
22
- print ("Updated presence" )
23
- payload = {"server_count" : len (self .guilds )}
24
- url = "https://discordbots.org/api/bots/320590882187247617/stats"
25
- headers = {"Authorization" : config ["tokens" ]["dbltoken" ]}
26
- async with aiohttp .ClientSession () as aioclient :
27
- await aioclient .post (
28
- url ,
29
- data = payload ,
30
- headers = headers )
31
- print (f"Posted payload to Discord Bot List:\n { payload } " )
4
+ from collections import Counter
5
+
6
+ BOOT = datetime .utcnow ().strftime ("%Y-%m-%d_%H-%M-%S" )
7
+
8
+ class Spectrum (commands .AutoShardedBot ):
9
+ def __init__ (self , config : dict ):
10
+ super ().__init__ (
11
+ command_prefix = commands .when_mentioned_or (config ["prefix" ]),
12
+ case_insensitive = True ,
13
+ description = "deez" # nopep8
14
+ )
15
+ self .config = config
16
+ self .owners = set (config .get ("owners" , {}))
17
+ self .uptime = datetime .now ()
18
+ self .debug_mode = config .get ("debug_mode" , True )
19
+ self .command_usage = Counter ()
20
+ self .db = None
21
+ self .remove_command ('help' )
22
+
23
+ async def is_owner (self , user ):
24
+ return user .id in self .owners or await super ().is_owner (user )
32
25
33
26
async def on_ready (self ):
34
- print ("=======================\n Connected\n =========" )
35
- await self .update_activity ()
27
+ await self .update ()
28
+ print ("--" * 15 )
29
+ print (f"{ self .user } is ready\n " )
30
+ print (f"ID: { self .user .id } " )
31
+ print (f"Created_At: { self .user .created_at } " )
32
+ print (f"User Count: { len (set (self .get_all_members ()))} " )
33
+ print (f"Channels: { len (set (self .get_all_channels ()))} " )
34
+ print (f"Guilds: { len (self .guilds )} " )
35
+ print (f"Debug: { str (self .debug_mode )} " )
36
+ print (f"--" * 15 )
37
+
38
+ async def on_resumed (self ):
39
+ print ("Resumed.." )
40
+
41
+ async def login (self , * args , ** kwargs ):
42
+ print ("BOOT @ %s" % BOOT )
43
+ print ("Connecting to discord..." )
44
+
45
+ self .session = aiohttp .ClientSession (json_serialize = json .dumps )
46
+ adapter = discord .AsyncWebhookAdapter (self .session )
47
+ self .webhook = discord .Webhook .from_url (self .config ["webhook_url" ], adapter = adapter )
48
+
49
+ extensions = [x .as_posix ().replace ("/" , "." ).replace (".py" , "" ) for x in pathlib .Path ("cogs" ).iterdir () if x .is_file ()]
50
+ extensions .append ("jishaku" )
51
+
52
+ for ext in extensions :
53
+ try :
54
+ self .load_extension (ext )
55
+ print ("Loaded extension: %s " % ext )
36
56
37
- async def on_message (self , message ):
38
- if message .author .bot :
39
- return
40
- await self .process_commands (message )
57
+ except commands .ExtensionFailed as e :
58
+ print (f"Extension { ext } failed to load: { e } " )
41
59
42
- async def on_guild_join (self , guild ):
43
- await self .update_activity ()
60
+ except commands .ExtensionNotFound :
61
+ print ("Extension %s cannot be found" % ext )
62
+
63
+ except commands .NoEntryPointError :
64
+ print ("Extension %s has no setup function" % ext )
65
+ await super ().login (* args , ** kwargs )
66
+
67
+ async def update (self ):
68
+ activity = discord .Activity (
69
+ type = 3 ,
70
+ name = f"scat" ,
71
+ url = "https://www.twitch.tv/SpectrixYT"
72
+ )
73
+ await self .change_presence (activity = activity )
74
+
75
+ if self .config .get ("dbl_token" ) and not self .debug_mode :
76
+ payload = {"server_count" : len (self .guilds )}
77
+ headers = {"Authorization" : self .config ["dbl_token" ]}
78
+ url = "https://top.gg/api/bots/%d/stats" % self .user .id
79
+ async with self .session .post (url , json = payload , headers = headers ) as resp : # nopep8
80
+ try :
81
+ data = await resp .json ()
82
+ print ("Recieved %s %s %d %s" , resp .method , resp ._url , resp .status , data )
83
+ except (TypeError , ValueError ):
84
+ print ("Recieved %s %s %d" , resp .method , resp ._url , resp .status )
85
+
86
+
87
+ async def close (self ):
44
88
try :
45
- embed = discord .Embed (color = discord .Color (value = 0x36393e ))
46
- embed .set_author (name = "Here's some stuff to get you started:" )
47
- embed .add_field (name = "Prefix" , value = "`$`, or **just mention me!**" )
48
- embed .add_field (name = "Command help" , value = "[Documentation](https://spectrix.me/spectrum/)" )
49
- embed .add_field (name = "Support Server" , value = "[Join, it's quite fun here](https://discord.gg/Kghqehz)" )
50
- embed .add_field (name = "Upvote" , value = "[Click here](https://discordbots.org/bot/320590882187247617/vote)" )
51
- embed .set_thumbnail (url = config ["styling" ]["gifLogo" ])
52
- embed .set_footer (text = f"Thanks to you, Spectrum is now on { len (self .guilds )} servers! <3" , icon_url = config ["styling" ]["normalLogo" ])
53
- await guild .system_channel .send (content = "**Hello World! Thanks for inviting me! :wave: **" , embed = embed )
54
- except :
89
+ await self .session .close ()
90
+ await self .db .close ()
91
+ except (RuntimeError , AttributeError ):
55
92
pass
93
+
94
+ await super ().close ()
56
95
57
- async def on_guild_remove (self ):
58
- await self .update_activity ()
59
96
60
- def initiate_start (self ):
61
- self .remove_command ("help" )
62
- lst = [f for f in listdir ("cogs/" ) if isfile (join ("cogs/" , f ))]
63
- no_py = [s .replace ('.py' , '' ) for s in lst ]
64
- startup_extensions = ["cogs." + no_py for no_py in no_py ]
65
- try :
66
- for cogs in startup_extensions :
67
- self .load_extension (cogs )
68
- print (f"Loaded { cogs } " )
69
- print ("\n All Cogs Loaded\n ===============\n Logging into Discord..." )
70
- super ().run (config ['tokens' ]['token' ])
71
- except Exception as e :
72
- print (f"\n ###################\n POSSIBLE FATAL ERROR:\n { e } \n \n \
73
- THIS MEANS THE BOT HAS NOT STARTED CORRECTLY!" )
74
-
75
- if __name__ == '__main__' :
76
- Spectrum_Bot ().initiate_start ()
97
+ if __name__ == "__main__" :
98
+ with open ("config.json" ) as file :
99
+ config = json .load (file )
100
+ h = Spectrum (config = config )
101
+ h .run (config ["bot_token" ])
0 commit comments