Skip to content

Commit

Permalink
Bot commands improvement & improvement deployment pipeline (#43)
Browse files Browse the repository at this point in the history
- automated versioning increments for image tags

Bot commands improvement
- changed most commands to be ephemeral so only the user sees the
interaction with the bot since theyre configuration changes
- add more configuration options for configuring the welcoming message
for newcomers
- added monitoring/information command /ping and /info to get live
health status of the bot
  • Loading branch information
SonOfLope authored Aug 26, 2023
1 parent 31e08dc commit d592cab
Show file tree
Hide file tree
Showing 6 changed files with 207 additions and 77 deletions.
98 changes: 83 additions & 15 deletions .github/workflows/deployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,78 @@ name: Docker

on:
push:
branches:
- master
tags:
- "v*.*.*"
- 'v*.*.*'

jobs:
build:
environment: deployment
jobs:
build-and-tag-on-merge:
if: ${{ github.ref == 'refs/heads/master'}}
environment : deployment
runs-on: ubuntu-latest
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- name: Check Out Repo
uses: actions/checkout@v2

- id: release
uses: rymndhng/release-on-push-action@master
with:
bump_version_scheme: patch
tag_prefix: v

- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2

- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}

- name: Cache Docker layers
uses: actions/cache@v3
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
restore-keys: ${{ runner.os }}-buildx

- name: Build and push
id: docker_build
uses: docker/build-push-action@v3
with:
context: .
file: ./Dockerfile
push: true
tags: |
${{ secrets.DOCKER_HUB_REPOSITORY }}:latest
${{ secrets.DOCKER_HUB_REPOSITORY }}:${{ steps.release.outputs.version }}
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new

- name: Refresh Cache
run: |
rm -rf /tmp/.buildx-cache
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}

build-on-release:
if: ${{ startsWith(github.ref, 'refs/tags/') }}
environment : deployment
runs-on: ubuntu-latest
steps:
- name: Check Out Repo
uses: actions/checkout@v2

- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2

- name: Login to Docker Hub
uses: docker/login-action@v2
with:
Expand All @@ -28,25 +82,39 @@ jobs:

- name: Get Tag Version
id: tag
run: "echo ::set-output name=version::${GITHUB_REF#refs/*/}"
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
- name: Cache Docker layers
uses: actions/cache@v3
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: ${{ runner.os }}-buildx

- name: Get Tag Version
id: tag2
run: |
VERSION=${GITHUB_REF#refs/tags/v}
echo "Version to be used: $VERSION"
echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: Build and push
id: docker_build
uses: docker/build-push-action@v3
with:
context: ./
context: .
file: ./Dockerfile
push: true
tags: |
${{ secrets.DOCKER_HUB_REPOSITORY }}:${{ env.VERSION }}
${{ secrets.DOCKER_HUB_REPOSITORY }}:latest
${{ secrets.DOCKER_HUB_REPOSITORY }}:${{ steps.tag.outputs.version }}
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache
- name: Image digest
cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new

- name: Refresh Cache
run: |
rm -rf /tmp/.buildx-cache
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
run: echo ${{ steps.docker_build.outputs.digest }}
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
20 changes: 19 additions & 1 deletion events.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
member_roles_are_default,\
send_delayed_dm

from discord import TextChannel

from text_format import\
make_mention

Expand All @@ -27,7 +29,23 @@ async def on_member_join(member):
welcome_chan = _get_welcome_chan(guild, trema_db)

welcome_msg = trema_db.get_server_welcome_msg(guild_id)
welcome_msg = make_mention(welcome_msg, member)
mention_dict = {
'{member}': member.mention,
'{username}': member.name,
'{server}': guild.name,
'{everyone}': '@everyone',
'{here}': '@here'
}
for role in guild.roles:
placeholder = f'{{&{role.name}}}'
mention_dict[placeholder] = role.mention

for channel in guild.channels:
if isinstance(channel, TextChannel):
placeholder = f'{{#{channel.name}}}'
mention_dict[placeholder] = channel.mention

welcome_msg = make_mention(welcome_msg, mention_dict)
await welcome_chan.send(welcome_msg)

# A reminder if the new member does not select a role
Expand Down
Binary file added img/logo-cedille.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
118 changes: 85 additions & 33 deletions slash_commands.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import asyncio
from discord import\
Color,\
Embed,\
Option,\
SlashCommandGroup
SlashCommandGroup,\
File

from discord_util import\
get_channel_name

from datetime import datetime

_MEMBER_MENTIONABLE = "[@-]"
_REQUEST_VALUE = "$"
_SLASH = "/"
_SPACE = " "


def create_slash_cmds(trema_bot, trema_db):
def create_slash_cmds(trema_bot, trema_db, start_time):
config = _create_config_cmds(trema_db)
_create_config_reminder_cmds(trema_db, config)
_create_information_cmds(trema_bot, start_time)
trema_bot.add_application_command(config)


Expand All @@ -27,8 +31,6 @@ def _create_config_cmds(trema_db):
@config.command(name="aide",
description="Informations sur les commandes /config")
async def aide(ctx):

await ctx.respond(content="Aide demandé", ephemeral=True)

embed_title = _make_cmd_full_name(ctx.command)
instructions =\
Expand All @@ -44,15 +46,13 @@ async def aide(ctx):
title=embed_title,
description=instructions,
color=Color.blue())
await ctx.send(embed=help_embed)
await ctx.respond(embed=help_embed, ephemeral=True)

@config.command(name="canalaccueil",
description="Changer le canal d'accueil des nouveaux membres")
async def config_welcome_chan(ctx,
id_accueil: Option(str,
"Identifiant du canal où les nouveaux membres reçoivent le message d'accueil")):

await ctx.respond(content="Configuration du canal d'accueil des nouveaux membres", ephemeral=True)

guild = ctx.guild
guild_id = ctx.guild_id
Expand Down Expand Up @@ -89,38 +89,61 @@ async def config_welcome_chan(ctx,
response_embed = _make_config_confirm_embed(
embed_title, updated_value, prev_value)

await ctx.send(embed=response_embed)
await ctx.respond(embed=response_embed, ephemeral=True)

@config.command(name="msgaccueil",
description=f"{_MEMBER_MENTIONABLE} Changer le message affiché lorsqu'un membre arrive dans le serveur")
async def config_welcome_msg(ctx,
message: Option(str, f"{_MEMBER_MENTIONABLE} Nouveau message d'accueil.")):
async def config_welcome_msg(ctx):

await ctx.respond(content="Configuration du message d'accueil", ephemeral=True)

guild_id = ctx.guild_id
embed_title = _make_cmd_full_name(ctx.command) + _SPACE + message
prev_value = trema_db.get_server_welcome_msg(guild_id)

if message == _REQUEST_VALUE:
response_embed =\
_make_config_display_embed(embed_title, prev_value)


await ctx.respond("Veuillez vérifier vos messages privés pour des instructions supplémentaires.", ephemeral=True)

user = ctx.author
dm_channel = user.dm_channel
if dm_channel is None:
dm_channel = await user.create_dm()

embed = Embed(
title="Configuration du message d'accueil",
description=f"Le message d'accueil actuel est: `{prev_value}`\n\n"
"Pour personnaliser ce message, vous pouvez utiliser les mentions suivantes:\n"
"- `{member}` pour mentionner le nouveau membre\n"
"- `{username}` pour mentionner un username\n"
"- `{server}` pour le nom du serveur\n"
"- `{channel}` pour le nom du canal\n"
"- `{&role}` pour mentionner un rôle par son nom\n"
"- `{#channel}` pour un lien vers un canal\n"
"- `{everyone}` pour `@everyone`\n"
"- `{here}` pour `@here`\n\n"
"Veuillez entrer le nouveau message d'accueil.",
color=Color.blue()
)

await dm_channel.send(embed=embed)

# Wait for user input in DM
def check(m):
return m.author.id == user.id and m.channel.id == dm_channel.id

try:
user_message = await ctx.bot.wait_for('message', timeout=60.0, check=check)
except asyncio.TimeoutError:
await dm_channel.send("Temps écoulé. Opération annulée.")
else:
trema_db.set_server_welcome_msg(guild_id, message)
confirmed_msg = trema_db.get_server_welcome_msg(guild_id)
new_value = user_message.content
trema_db.set_server_welcome_msg(guild_id, new_value)
embed_title = "Message d'accueil mis à jour"
response_embed = _make_config_confirm_embed(
embed_title, confirmed_msg, prev_value)

await ctx.send(embed=response_embed)
embed_title, new_value, prev_value)
await dm_channel.send(embed=response_embed)

@config.command(name="msgdepart",
description=f"{_MEMBER_MENTIONABLE} Changer le message affiché lorsqu'un membre quitte le serveur")
async def config_leave_msg(ctx,
message: Option(str, f"{_MEMBER_MENTIONABLE} Nouveau message de départ.")):

await ctx.respond(content="Configuration du message de départ d'un membre", ephemeral=True)

guild_id = ctx.guild_id
embed_title = _make_cmd_full_name(ctx.command) + _SPACE + message
prev_value = trema_db.get_server_leave_msg(guild_id)
Expand All @@ -135,7 +158,7 @@ async def config_leave_msg(ctx,
response_embed = _make_config_confirm_embed(
embed_title, confirmed_msg, prev_value)

await ctx.send(embed=response_embed)
await ctx.respond(embed=response_embed, ephemeral=True)

return config

Expand All @@ -149,8 +172,6 @@ def _create_config_reminder_cmds(trema_db, config_group):
async def config_reminder_msg(ctx,
message: Option(str, f"{_MEMBER_MENTIONABLE} Message de rappel aux membres sans rôles.")):

await ctx.respond(content="Configuration du message de rappel", ephemeral=True)

guild_id = ctx.guild_id
embed_title = _make_cmd_full_name(ctx.command) + _SPACE + message
prev_value = trema_db.get_server_reminder_msg(guild_id)
Expand All @@ -165,15 +186,13 @@ async def config_reminder_msg(ctx,
response_embed = _make_config_confirm_embed(
embed_title, confirmed_msg, prev_value)

await ctx.send(embed=response_embed)
await ctx.respond(embed=response_embed, ephemeral=True)

@rappel.command(name="delai",
description="Changer le délai d'envoi du rappel (minutes) aux membres sans rôles.")
async def config_reminder_delay(ctx,
delai: Option(str, "Délai du rappel (minutes) aux membres sans rôles")):

await ctx.respond(content="Configuration du délai de rappel", ephemeral=True)

guild_id = ctx.guild_id
embed_title = _make_cmd_full_name(ctx.command) + _SPACE + delai
prev_value = trema_db.get_server_reminder_delay(guild_id) / 60
Expand All @@ -199,8 +218,41 @@ async def config_reminder_delay(ctx,
response_embed = _make_config_confirm_embed(
embed_title, confirmed_delay, prev_value)

await ctx.send(embed=response_embed)
await ctx.respond(embed=response_embed, ephemeral=True)

def _create_information_cmds(trema_bot, start_time):
@trema_bot.command(name="ping", description="Répond avec pong")
async def ping(ctx):
latency = round(trema_bot.latency * 1000)
uptime = datetime.now() - start_time
uptime_str = str(uptime).split('.')[0] # remove the microseconds part
server_count = len(trema_bot.guilds)

response_embed = Embed(
title="Pong!",
color=Color.green()
)
response_embed.add_field(name="Latency", value=f"{latency}ms")
response_embed.add_field(name="Uptime", value=uptime_str)
response_embed.add_field(name="Trëma server Count", value=str(server_count))

await ctx.respond(embed=response_embed)


@trema_bot.command(name="info", description="Informations sur Trëma")
async def info(ctx):
embed_title = _make_cmd_full_name(ctx.command)
instructions =\
"Trëma est un bot Discord dedié à accueillir et guider les membres du serveur.\n\n"\
+ "Trëma est développé par le club CEDILLE de l'ÉTS."

help_embed = Embed(
title=embed_title,
description=instructions,
color=Color.blue())
help_embed.set_thumbnail(url="https://cedille.etsmtl.ca/images/cedille-logo-orange.png")

await ctx.respond(embed=help_embed)

def _make_cmd_full_name(cmd):
names = list()
Expand All @@ -217,7 +269,7 @@ def _make_cmd_full_name(cmd):
def _make_config_confirm_embed(title, updated_value, prev_value):
confirm_embed = Embed(
title=title,
description=f"Nouvelle valeur: {updated_value}\nValeur précédente: {prev_value}",
description=f"Nouvelle valeur:\n`{updated_value}`\n\nValeur précédente:\n`{prev_value}`",
color=Color.green())
return confirm_embed

Expand Down
Loading

0 comments on commit d592cab

Please sign in to comment.