Discord notifications
Slash commands read data when invoked. SDK listeners receive detected changes while your application runs. Only resources required by listeners are polled.
A notification Cog
This extension demonstrates all ten polling resources. Save it alongside the Bot from Using Cogs:
from __future__ import annotations
from typing import TYPE_CHECKING
import discord
from discord.ext import commands
from dankmemer import (
Blog,
Changelog,
Drop,
FishingEvent,
GlobalBoost,
LotteryResult,
MerchantRotation,
StoreDailyGift,
StoreSale,
)
from dankmemer.ext.dpy import dank_cog
if TYPE_CHECKING:
from .bot import DankBot
class AlertsCog(commands.Cog):
def __init__(self, bot: DankBot) -> None:
self.bot = bot
async def cog_load(self) -> None:
dank_cog.bind(self, self.bot.dank)
async def cog_unload(self) -> None:
dank_cog.unbind(self)
async def send_alert(self, text: str) -> None:
await self.bot.wait_until_ready()
channel = self.bot.get_channel(self.bot.alert_channel_id)
if not isinstance(channel, (discord.TextChannel, discord.Thread)):
raise RuntimeError(
"ALERT_CHANNEL_ID must identify an accessible text channel or thread"
)
await channel.send(text[:2000], allowed_mentions=discord.AllowedMentions.none())
@dank_cog.listen(subscription_id="alerts.drop_started")
async def on_drop_started(self, drop: Drop) -> None:
await self.send_alert(
f"Drop {drop.id} ends <t:{int(drop.ends_at.timestamp())}:R>."
)
@dank_cog.listen(subscription_id="alerts.drop_updated")
async def on_drop_updated(self, before: Drop, after: Drop) -> None:
await self.send_alert(
f"Drop {after.id} changed; its current per-user limit is {after.limit_per_user}."
)
@dank_cog.listen(subscription_id="alerts.drop_ended")
async def on_drop_ended(self, drop: Drop) -> None:
await self.send_alert(f"Drop {drop.id} is no longer reported active.")
@dank_cog.listen(subscription_id="alerts.lottery")
async def on_lottery_result(self, result: LotteryResult) -> None:
await self.send_alert(
f"Lottery drawn <t:{int(result.drawn_at.timestamp())}:f>: {result.winnings:,} winnings."
)
@dank_cog.listen(subscription_id="alerts.gifts")
async def on_store_daily_gift(self, gift: StoreDailyGift) -> None:
await self.send_alert(f"Today's {gift.category} gift: {gift.metadata.render}")
@dank_cog.listen(subscription_id="alerts.merchant")
async def on_merchant_rotation(self, rotation: MerchantRotation) -> None:
await self.send_alert(
f"Merchant offers for {rotation.date:%Y-%m-%d}: {len(rotation.trades)} trades."
)
@dank_cog.listen(subscription_id="alerts.sales")
async def on_store_sale_started(self, sale: StoreSale) -> None:
await self.send_alert(f"{sale.name} is on sale for {sale.price:g}: {sale.url}")
@dank_cog.listen(subscription_id="alerts.fishing")
async def on_fishing_event_started(self, event: FishingEvent) -> None:
await self.send_alert(
f"Fishing event: {event.name}. Ends <t:{int(event.ends_at.timestamp())}:R>."
)
@dank_cog.listen(subscription_id="alerts.streaming")
async def on_stream_trending_game(self, game: str) -> None:
await self.send_alert(f"The API's current streaming game: {game}")
@dank_cog.listen(subscription_id="alerts.boosts")
async def on_global_boosts_changed(
self, before: tuple[GlobalBoost, ...], after: tuple[GlobalBoost, ...]
) -> None:
boosts = ", ".join(f"{boost.type} ×{boost.multiplier:g}" for boost in after)
await self.send_alert(f"Active global boosts: {boosts or 'none'}.")
@dank_cog.listen(subscription_id="alerts.blogs")
async def on_blog_published(self, blog: Blog) -> None:
await self.send_alert(f"New blog: {blog.title}\n{blog.url}")
@dank_cog.listen(subscription_id="alerts.changelogs")
async def on_changelog_published(self, changelog: Changelog) -> None:
await self.send_alert(f"New changelog: {changelog.title}\n{changelog.url}")
async def setup(bot: DankBot) -> None:
cog = AlertsCog(bot)
try:
await bot.add_cog(cog)
except BaseException:
dank_cog.unbind(cog)
raise
@dank_cog.listen lets other Cogs receive the same events. bind connects
methods to bot.dank at load; unbind removes them at unload. Keep the
handlers your application needs: this whole example requests ten resources,
while just the three drop handlers request drops only, through one poller.
Default schedules in Which requests run remain at least 60 seconds apart.
Drop start and end describe observed membership in the active collection.
drop_ended receives the last observed record and can arrive after its end
time. Local timers do not manufacture ended events. drop_updated receives
the previous and current records for an ID. To notify only on end-time changes,
test before.ends_at != after.ends_at in that handler.
Lottery notifications follow drawing timestamps. Hourly polling continues with
minute-spaced checks when a result is delayed. Merchant and gift identities use
their reported UTC day. Publication handlers recover new entries ahead of their
checkpoint and deliver oldest first. Streaming uses the observed UTC day because
the endpoint supplies no date. For same-day streaming changes, also register
stream_trending_game_updated and choose interval polling. See Event reference.
Run commands and notifications together
Save the three command Cogs from Slash command recipes alongside alerts_cog.py.
Replace mybot/launcher.py with:
import asyncio
import os
from dankmemer import DankMemer
from .bot import DankBot
async def main() -> None:
dank = DankMemer(os.environ["DANK_MEMER_API_TOKEN"])
bot = DankBot(dank, alert_channel_id=int(os.environ["ALERT_CHANNEL_ID"]))
async with bot:
for extension in ("items_cog", "fishing_cog", "activities_cog", "alerts_cog"):
await bot.load_extension(f"{__package__}.{extension}")
await bot.start(os.environ["DISCORD_BOT_TOKEN"])
if __name__ == "__main__":
asyncio.run(main())
Run python -m mybot.launcher. Extensions load before the Bot starts the SDK
and connects to Discord. Publish slash commands manually using
Command syncing. All four share a client and item catalog.
The notification Cog owns polling demand; command Cogs read when invoked.
This launcher replaces
the introductory DankCog to avoid overlapping commands and notifications.
Notifications at startup
The first successful read normally remembers existing data. To announce it too:
from dankmemer import DankMemer, EventConfig
dank = DankMemer(token, events=EventConfig(emit_initial=True))
Active collections can announce several records on the first read. Lottery and merchant handlers can announce the currently returned result. Update and ended events need an earlier accepted record. See Events and polling for publication behaviour.
Sending failures and durable replay
Wait for Discord readiness inside callbacks. Ensure the notification channel exists and the bot can view and send there. The example raises for an inaccessible channel; Discord send failures also propagate to the SDK’s delivery handling.
Best-effort failures are logged and consumed. Durable failures keep the saved
call and pause its subscription. Correct the problem, inspect
last_delivery_errors, then call dank.retry_pending(subscription_id).
Persistent event delivery provides a complete persistent Discord launcher.
Durable delivery can repeat a message after a crash between sending and saving completion. A subscription ID maps pending work to a handler; it does not make a Discord send and database acknowledgement atomic. An application delivery record can help track actions, but must also account for that crash window.
Normal function decorators
Inside the function-based launcher, add:
from dankmemer import LotteryResult
@dank.event
async def on_lottery_result(result: LotteryResult) -> None:
await bot.wait_until_ready()
channel = bot.get_channel(alert_channel_id)
if isinstance(channel, (discord.TextChannel, discord.Thread)):
await channel.send(f"Latest lottery winnings: {result.winnings:,}")
For another consumer, use @dank.listen("lottery_result"). Cog methods use
dank_cog; normal functions use the client dank. See
Primary handlers and additional listeners for replacement behaviour and
What subscription IDs identify for durable consumer names.