Skip to content
This repository has been archived by the owner on Dec 2, 2022. It is now read-only.

Commit

Permalink
Save bot activity (#8)
Browse files Browse the repository at this point in the history
* Restore bot activity on restart
* Fix some formatting
* Escape postgresql values
  • Loading branch information
nathanaelhoun authored Feb 3, 2021
1 parent 8c9e150 commit 690a821
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 19 deletions.
23 changes: 20 additions & 3 deletions bot/cogs/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,25 @@ def __init__(self, bot):

@commands.Cog.listener()
async def on_ready(self):
"""Print that we are connected"""
# TODO : and set a bot activity
print(STR.CONNECTION_SUCCESSFUL.format(self.bot.user))
"""Restore bot activity"""

print("I'm alive! Connected as {}.".format(self.bot.user))

print("Restoring bot activity... ", end="")
rows = self.bot.database.execute(
"""
SELECT value
FROM system
WHERE key = 'activity';
"""
)

if len(rows) == 0:
print("No bot activity found.")
else:
game = discord.Game(rows[0][0])
await self.bot.change_presence(status=discord.Status.online, activity=game)
print("Restored '{}'.".format(rows[0][0]))

@commands.Cog.listener()
async def on_message(self, ctx: commands.Context):
Expand All @@ -25,6 +41,7 @@ async def on_message(self, ctx: commands.Context):
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error):
"""Send a message when a common command error is detected"""

if isinstance(error, commands.NoPrivateMessage):
await ctx.send(STR.ERR_PRIVATE_CHANNEL)

Expand Down
10 changes: 9 additions & 1 deletion bot/cogs/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,20 @@ async def ping2(self, ctx: commands.Context):
async def activity(self, ctx: commands.Context, new_activity: str):
"""Set a new activity for the bot"""

# TODO : Check if admin
game = discord.Game(new_activity)
await self.bot.change_presence(status=discord.Status.online, activity=game)
await ctx.send(STR.ACTIVITY_NEW.format(new_activity, ctx.message.author))

sql = """
INSERT INTO system VALUES
('activity', %s)
ON CONFLICT (key)
DO UPDATE SET value = EXCLUDED.value;
"""
self.bot.database.insert(sql, (new_activity,))


def setup(bot):
"""Add this class to the bot"""

bot.add_cog(Fun(bot))
24 changes: 14 additions & 10 deletions bot/cogs/score.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def __init__(self, bot):
@commands.group()
async def score(self, ctx: commands.Context):
"""Manage scores for the members of the guild"""

if ctx.invoked_subcommand is None:
await ctx.send(STR.ERR_NO_SUBCOMMAND)

Expand Down Expand Up @@ -83,27 +84,30 @@ async def modify_points(self, ctx: commands.Context, value: int):
await ctx.send(STR.ERR_MISSING_REQUIRED_ARGUMENT)
return

values_sql = ""
sql = """
INSERT INTO score VALUES
"""
data_sql = []
members_name = ""

for member in members:
if members_name != "":
values_sql += ", "
sql += ", "
members_name += ", "

values_sql += "({}, {}, {})".format(ctx.guild.id, member.id, value)
sql += "(%s, %s, %s) "
data_sql.append(ctx.guild.id)
data_sql.append(member.id)
data_sql.append(value)
members_name += member.display_name

sql = """
INSERT INTO score VALUES
{}
sql += """
ON CONFLICT (sco_guild_id, sco_member_id)
DO UPDATE SET sco_value = score.sco_value + EXCLUDED.sco_value;
""".format(
values_sql
)
"""

try:
self.bot.database.insert(sql)
self.bot.database.insert(sql, data_sql)

message = STR.SCORE_ADD_SUCCESSFULLY.format(
Pluralizer(value), members_name, ctx.author.display_name
Expand Down
3 changes: 3 additions & 0 deletions bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

print("Ready to launch client. ", end="")
print("Running client...")

try:
client.run(os.getenv("BOT_TOKEN"))
finally:
Expand All @@ -41,3 +42,5 @@
print("Disconnecting from database... ", end="")
db.disconnect()
print("done! ")

print("Goodbye!")
5 changes: 3 additions & 2 deletions bot/postgresql_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,13 @@ def execute(self, sql: str):
# cursor.close() # for the future
return values

def insert(self, sql: str):
def insert(self, sql: str, params=None):
"""Execute an insert sql query and return the status"""

self.cursor_connect()
status = -1
try:
status = self._cursor.execute(sql)
status = self._cursor.execute(sql, params)
except psycopg2.Error as err:
print(err)

Expand Down
3 changes: 0 additions & 3 deletions bot/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@ class Strings:
EM_OK = ":ok: "
EM_SUCCESS = ":white_check_mark: "

# General
CONNECTION_SUCCESSFUL = "Je suis vivant ! Connecté en tant que {}"

ERR_NO_COMMAND = "Cette commande n'existe pas. Tapez `&help` et je vous aiderai !"
ERR_NO_SUBCOMMAND = EM_WARNING + "Sous-commande non valide"
ERR_BOT_MISSING_PERMISSIONS = (
Expand Down
7 changes: 7 additions & 0 deletions database_creation.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-- DELETE ALL
DROP TABLE score;
DROP TABLE system;

-- CREATE ALL

Expand All @@ -8,4 +9,10 @@ CREATE TABLE score (
sco_member_id BIGINT,
sco_value INT DEFAULT 0 NOT NULL,
PRIMARY KEY (sco_guild_id, sco_member_id)
);

CREATE TABLE system (
key VARCHAR(16) NOT NULL,
value VARCHAR(256) NOT NULL,
PRIMARY KEY (key)
);

0 comments on commit 690a821

Please sign in to comment.