Skip to content

Commit 5840934

Browse files
authored
Merge pull request #95 from SpectrixDev/v4
Massive rewrite in progress
2 parents a2e224a + 3d5b729 commit 5840934

23 files changed

+453
-423
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# why are you reading the stupid gitignore rather just star the repo smh
22
*.json
3+
config.json
34
/databases
45
/servers
56
*.vs

bot.py

Lines changed: 92 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,101 @@
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
23
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)
3225

3326
async def on_ready(self):
34-
print("=======================\nConnected\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)
3656

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}")
4159

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):
4488
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):
5592
pass
93+
94+
await super().close()
5695

57-
async def on_guild_remove(self):
58-
await self.update_activity()
5996

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("\nAll Cogs Loaded\n===============\nLogging into Discord...")
70-
super().run(config['tokens']['token'])
71-
except Exception as e:
72-
print(f"\n###################\nPOSSIBLE 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"])

cogs/Bigemote.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io
44
import os
55
import unicodedata
6+
import logging
67

78
import aiohttp
89
from discord.ext import commands

cogs/Chatbot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import datetime, time, json, apiai, random, discord, asyncio, os
1+
import datetime, time, json, apiai, random, discord, asyncio, os, logging
22
from time import ctime
33
from discord.ext import commands
44

@@ -7,7 +7,7 @@
77
ai = apiai.ApiAI(config["tokens"]["dialogflowtoken"])
88

99
class Chatbot(commands.Cog):
10-
"""Very important part of Spectrum. Also lets the users run commands by mentioning the bot. The whole chatbot isn't here obviously lol"""
10+
"""Kinda old, outdated, scuffed. Too lazy to update it honestly, it still works, its just nobody uses it. Was made for fun while initially learning py"""
1111

1212
def __init__(self, bot):
1313
self.bot = bot
@@ -85,7 +85,7 @@ async def devChat(self, ctx, *, chatMsg):
8585
fulfillment = result.get('fulfillment')
8686
speech = fulfillment.get('speech')
8787
emb = (discord.Embed(colour=0x36393e))
88-
emb.set_author(name="DevChat for SpectrumV2 Chatbot", icon_url=config["styling"]["gifLogo"])
88+
emb.set_author(name="DevChat for SpectrumV2 Chatbot", icon_url=config["styling"]["logo"])
8989
emb.add_field(name="resolvedQuery", value=f"```{resolvedQuery}```", inline=False)
9090
emb.add_field(name="intentName", value=f"`{intentName}`")
9191
emb.add_field(name="score", value=f"`{score}`")

cogs/ErrorHandler.py

Lines changed: 0 additions & 48 deletions
This file was deleted.

cogs/Fun.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import discord, asyncio, random, json
1+
import discord, asyncio, random, json, logging
22
from discord.ext import commands
33
from discord.ext.commands import clean_content
44

5-
with open("databases/thesacredtexts.json") as f:
5+
6+
with open("config.json") as f:
67
config = json.load(f)
78

89
class Fun(commands.Cog):
@@ -15,7 +16,7 @@ async def combine(self, ctx, name1: clean_content, name2: clean_content):
1516
name2letters = name2[round(len(name2) / 2):]
1617
ship = "".join([name1letters, name2letters])
1718
emb = (discord.Embed(color=0x36393e, description = f"{ship}"))
18-
emb.set_author(name=f"{name1} + {name2}", icon_url=config["styling"]["gifLogo"])
19+
emb.set_author(name=f"{name1} + {name2}", icon_url=config["styling"]["logo"])
1920
await ctx.send(embed=emb)
2021

2122
@commands.command()

0 commit comments

Comments
 (0)