Async and Discord bots¶
Async (discord.py and friends)¶
AsyncOxfordAPI has all the same methods, but you await them, so your bot doesn't freeze
while it waits for the API. It needs pip install "oxrpy[async]".
import asyncio
import discord
from oxrpy import AsyncOxfordAPI
api = AsyncOxfordAPI(OXFD_SERVER_KEY)
class Bot(discord.Client):
async def setup_hook(self):
asyncio.create_task(api.run_forever()) # handlers run alongside the bot
bot = Bot(intents=discord.Intents.default())
@api.on("Kill")
async def on_kill(kill): # handlers can be async or normal functions
channel = bot.get_channel(KILL_FEED_CHANNEL_ID)
await channel.send(f'{kill["KillerUsername"]} downed {kill["VictimUsername"]}')
@bot.event
async def on_message(message):
if message.content == "!players":
players = await api.get_players() or []
await message.channel.send(f"{len(players)} players online")
bot.run(DISCORD_TOKEN)
Following logs works with async for:
Use async with AsyncOxfordAPI(key) as api:, or call await api.aclose() when you're done,
to close the connection cleanly.