Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a reminder command #28

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions cogs/reminder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import asyncio
from datetime import datetime, timedelta

import dateparser
import discord
from discord.ext import Message, app_commands, commands

# Reminder command


class Reminder(commands.Cog):
"""Class for reminder command"""

def __init__(self, bot):
self.bot = bot

def countdown(self, trigger_time: datetime) -> str:
"""Calculate days, hours and minutes to a date.

Args:
trigger_time: The date.

Returns:
A string with the days, hours and minutes.
"""
countdown_time: timedelta = trigger_time - datetime.now()

days, hours, minutes = (
countdown_time.days,
countdown_time.seconds // 3600,
countdown_time.seconds // 60 % 60,
)

# Return seconds if only seconds are left.
if days == 0 and hours == 0 and minutes == 0:
seconds: int = countdown_time.seconds % 60
return f"{seconds} second" + ("s" if seconds != 1 else "")

# TODO: Explain this.
return ", ".join(
f"{x} {y}{'s' * (x != 1)}"
for x, y in (
(days, "day"),
(hours, "hour"),
(minutes, "minute"),
)
if x
)

@app_commands.command(name="reminder", desription="Nastav si připomínku!")
@app_commands.describe(topic="Co ti mám připomenout?", time="Kdy ti to mám připomenout?")
async def reminder(self, interaction: discord.Interaction, time: str, topic: str) -> Message:
"""Reminder command"""
trigger_time: datetime = dateparser.parse(time)
await interaction.response.send_message(
f"Za {self.countdown(trigger_time)} ti připomenu {topic}!", ephemeral=True
)
await asyncio.sleep(trigger_time.timestamp() - datetime.now().timestamp())
await interaction.followup.send(f"{interaction.user.mention} připomínám ti {topic}!", ephemeral=True)
5 changes: 2 additions & 3 deletions cogs/sync_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,8 @@ async def sync(
else:
synced = await self.bot.tree.sync()

await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}",
)
await ctx.send(f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}")

return

ret = 0
Expand Down
2 changes: 2 additions & 0 deletions cogs/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async def pomoc(self, interaction: discord.Interaction) -> Message:
)
async def rozcestnik(self, interaction: discord.Interaction) -> Message:
embed = EmbedFromJSON().add_fields_from_json("rozcestnik")

return await interaction.response.send_message(
embed=embed,
file=EmbedFromJSON.PICTURE,
Expand Down Expand Up @@ -74,6 +75,7 @@ async def birthday(self, ctx):
self.bot.MY_BIRTHDAY,
"%d.%m.%Y",
).replace(year=today.year)

days_until_birthday = (bot_birthday.date() - today).days
await ctx.send(
f"Moje narozeniny jsou 27. prosince 2020 a zbývá přesně {days_until_birthday} dní do mých narozenin!",
Expand Down
11 changes: 11 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ ___

</div>

### Contributors

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->

<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->

<!-- ALL-CONTRIBUTORS-LIST:END -->

### A protože...

...se tento bot jmenuje Jáchym, zanechávám hlášku z filmu!
Expand Down
12 changes: 4 additions & 8 deletions src/db_folder/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,7 @@ async def commit_many_values(self, sql: str, values: list[tuple[int, str]]) -> N
await cursor.executemany(sql, values)
await conn.commit()

async def fetch_all_values(
self,
sql: str,
value: tuple | None = None,
) -> list[tuple]:
async def fetch_all_values(self, sql: str, value: Optional[tuple] = None) -> list[tuple]:
async with self.poll.acquire() as conn:
cursor = await conn.cursor()
await cursor.execute(sql, value)
Expand Down Expand Up @@ -77,9 +73,7 @@ async def fetch_all_polls(self, bot: "Jachym") -> AsyncIterator[Poll and Message

for message_id, channel_id, question, date, _ in polls:
try:
message = await bot.get_partial_messageable(channel_id).fetch_message(
message_id,
)
message = await bot.get_partial_messageable(channel_id).fetch_message(message_id)

except (discord.errors.NotFound, discord.errors.Forbidden):
await self.remove(message_id)
Expand All @@ -106,6 +100,7 @@ def __init__(self, pool: aiomysql.pool.Pool):
async def add_options(self, discord_poll: Poll):
sql = "INSERT INTO `VoteButtons`(message_id, answers) VALUES (%s, %s)"
values = [(discord_poll.message_id, vote_option) for vote_option in discord_poll.options]

await self.commit_many_values(sql, values)

async def add_user(self, discord_poll: Poll, user: int, index: int):
Expand All @@ -123,4 +118,5 @@ async def fetch_all_users(self, poll: Poll, index: int) -> set[int]:

values = (poll.message_id, index)
users_voted_for = await self.fetch_all_values(sql, values)

return {user for user_tuple in users_voted_for for user in user_tuple}
5 changes: 2 additions & 3 deletions src/jachym.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ async def _fetch_pools_from_database(self) -> None:
poll_database = PollDatabase(self.pool)

async for poll, message in poll_database.fetch_all_polls(self):
self.add_view(
PollView(poll=poll, embed=message.embeds[0], db_poll=self.pool),
)
self.add_view(PollView(poll=poll, embed=message.embeds[0], db_poll=self.pool))

self.active_discord_polls.add(poll)

logger.success(f"There are now {len(self.active_discord_polls)} active pools!")
Expand Down
1 change: 1 addition & 0 deletions src/ui/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def __init__(
emoji=emoji,
custom_id=custom_id,
)

self.poll = poll
self.embed = embed
self._index = index
Expand Down