Skip to content

Commit

Permalink
Add echo example
Browse files Browse the repository at this point in the history
  • Loading branch information
vadim-su committed Nov 10, 2024
1 parent 71baa21 commit e0725e3
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 1 deletion.
1 change: 1 addition & 0 deletions examples/echo/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
Empty file added examples/echo/__init__.py
Empty file.
51 changes: 51 additions & 0 deletions examples/echo/echo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""A simple echo bot that echoes messages back to the channel."""

import asyncio
import os

from dotenv import load_dotenv

from asyncord.client.messages.models.requests.messages import CreateMessageRequest
from asyncord.client.rest import RestClient
from asyncord.client_hub import ClientHub
from asyncord.gateway.events.base import ReadyEvent
from asyncord.gateway.events.messages import MessageCreateEvent

load_dotenv()
API_TOKEN = os.getenv('API_TOKEN')


async def on_ready(event: ReadyEvent) -> None: # noqa: RUF029
"""Prints a message when the bot is ready."""
print(f'{event.user.username} has connected to Discord!') # noqa: T201


async def on_message(message: MessageCreateEvent, client: RestClient) -> None:
"""Echoes the message back to the channel."""
if message.author.bot:
# Ignore messages from bots
# Also, it helps to prevent infinite loops to read the bot's own messages
return

# Prepare the message resource
message_res = client.channels.messages(message.channel_id)

# Message sending logic
await message_res.create(
CreateMessageRequest(
content=message.content + ' :smile:',
),
)


async def main(api_token: str) -> None:
"""Main function to run the bot."""
async with ClientHub.connect(api_token) as client:
# Dispatcher detects the event type by the first argument
# and calls the handler with the event object
client.dispatcher.add_handler(on_ready)
client.dispatcher.add_handler(on_message)


if __name__ == '__main__':
asyncio.run(main(API_TOKEN))
9 changes: 9 additions & 0 deletions examples/echo/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[project]
name = "echo"
version = "0.1.0"
description = "Add your description here"
requires-python = ">=3.12.0"
dependencies = ["asyncord", "python-dotenv>=1.0.1"]

[tool.uv.sources]
asyncord = { workspace = true }
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,6 @@ max-args = 7
[tool.ruff.format]
preview = true
quote-style = "single"

[tool.uv.workspace]
members = ["examples/echo"]
32 changes: 31 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e0725e3

Please sign in to comment.