-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.py
More file actions
138 lines (110 loc) · 5.35 KB
/
Copy pathmain.py
File metadata and controls
138 lines (110 loc) · 5.35 KB
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
from core.startup import SubClassBotPlugServices
from inspect import cleandoc
from os import chdir, mkdir, environ
from pathlib import Path
import aiofiles.os
import aiohttp
import discord
import dotenv
import logging
import re
import socket
import yaml
# Go to project root directory
chdir(Path(__file__).parent.resolve())
# Load environment variables
dotenv.load_dotenv("dev.env")
# Logging
logging.basicConfig(format='%(levelname)s %(asctime)s [%(pathname)s:%(lineno)d - %(module)s.%(funcName)s()]: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.INFO)
# Check if TOKEN is set
if "TOKEN" in environ and (environ.get("TOKEN") == "INSERT_DISCORD_TOKEN") or (environ.get("TOKEN") is None) or (environ.get("TOKEN") == ""):
raise Exception("Please insert a valid Discord bot token")
# Intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
# Subclass this bot
class InitBot(SubClassBotPlugServices):
def __init__(self, *args, **kwargs):
# Create socket instance and bind socket to 45769
self._lock_socket_instance(45769)
super().__init__(*args, **kwargs)
# Prepare temporary directory
if environ.get("TEMP_DIR") is not None:
if Path(environ.get("TEMP_DIR")).exists():
for file in Path(environ.get("TEMP_DIR", "temp")).iterdir():
file.unlink()
else:
mkdir(environ.get("TEMP_DIR"))
else:
environ["TEMP_DIR"] = "temp"
mkdir(environ.get("TEMP_DIR"))
# Initialize SDK clients
self.loop.create_task(self.start_services())
logging.info("Services initialized successfully")
# HTTP Client
self.aiohttp_instance = aiohttp.ClientSession(loop=self.loop)
logging.info("HTTP client session initialized successfully")
def _lock_socket_instance(self, port):
try:
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.bind(('localhost', port))
logging.info("Socket bound to port %s", port)
except socket.error as e:
logging.error("Failed to bind socket port: %s, reason: %s", port, str(e))
raise e
async def on_ready(self):
await self.change_presence(activity=discord.Game(f"Preparing the bot for it's first use..."))
#https://stackoverflow.com/a/65780398 - for multiple statuses
await self.change_presence(activity=discord.Game(f"@ me to get started!"))
logging.info("%s is ready and online!", self.user)
# Shutdown the bot
async def close(self):
# Close services
await self.stop_services()
logging.info("Services stopped successfully")
# Remove temp files
if Path(environ.get("TEMP_DIR", "temp")).exists():
for file in Path(environ.get("TEMP_DIR", "temp")).iterdir():
await aiofiles.os.remove(file)
# Close socket
self._socket.close()
await super().close()
bot = InitBot(command_prefix=environ.get("BOT_PREFIX", "$"), intents = intents)
###############################################
# ON USER MESSAGE
###############################################
@bot.event
async def on_message(message: discord.Message):
# https://discord.com/channels/881207955029110855/1146373275669241958
await bot.process_commands(message)
if message.author == bot.user:
return
# Check if the bot was only mentioned without any content or image attachments
# On generative ask command, the same logic is used but it will just invoke return and the bot will respond with this
if bot.user.mentioned_in(message) \
and not message.attachments \
and not re.sub(f"<@{bot.user.id}>", '', message.content).strip():
await message.channel.send(
cleandoc(f"""Hello <@{message.author.id}>! I am **{bot.user.name}** ✨
I am an AI bot and I can also make your server fun and entertaining! 🎉
You just pinged me, but what can I do for you? 🤔
- You can ask me anything by typing **/ask** and get started or by mentioning me again but with a message
- You can access most of my useful commands with **/**slash commands or use `{bot.command_prefix}help` to see the list prefixed commands I have.
- You can access my apps by **tapping and holding any message** or **clicking the three-dots menu** and click **Apps** to see the list of apps I have
You can ask me questions, such as:
- **@{bot.user.name}** How many R's in the word strawberry?
- **/ask** `prompt:`Can you tell me a joke?
- Hey **@{bot.user.name}** can you give me quotes for today?
If you have any questions, you can visit my [documentation or contact me here](https://zavocc.github.io)"""))
with open('commands.yaml', 'r') as file:
cog_commands = yaml.safe_load(file)
for command in cog_commands:
try:
bot.load_extension(f'cogs.{command}')
except Exception as e:
logging.error("cogs.%s failed to load, skipping... The following error of the cog: %s", command, e)
continue
bot.run(environ.get('TOKEN'))