Bots

Command routing over REST + Gateway, with voice conveniences
from IPython.display import Audio

import wave
dc = DiscordClient()
gld = await dc.guild('1327046393453613076')
chs = await gld.channels()
vch = chs[3]
intents = Intent.GUILDS | Intent.GUILD_VOICE_STATES | Intent.GUILD_MESSAGES | Intent.MESSAGE_CONTENT

Bot combines DiscordClient (REST) and GatewayClient (events) with a command router. @bot.cmd registers a handler under the function’s name. def echo answers !echo. A handler takes the Message and a string holding everything after the command name, empty if nothing.

_on_msg ignores messages from the bot itself. Without that, a bot that answers its own messages loops forever. It splits the message into command name and args: !echo hello world passes "hello world" as args.


source

Bot

def Bot(
    intents, **kw
):

Discord bot with command routing

bot = Bot(intents)
await bot.start()

You can register commands after bot.start(). @bot.cmd adds the function to a dict, and the message handler looks commands up on each message.

@bot.cmd
async def echo(msg, args): await (await msg.channel()).send(f'You said: {args}')
bot
Bot(cmds=['echo'])

The router catches errors in command handlers and appends them to bot.errors. You can inspect that list after the fact, for example in solveit. @bot.on_error registers a handler for real-time handling, such as notifying the user in Discord. Both work at the same time.


source

Bot.on_error

def on_error(
    f
):
@bot.on_error
async def handle_err(msg, e): print('error')
@bot.cmd
def err(msg): raise Exception('test')
bot.errors
[]

Voice reuses VoiceClient. Bot adds join_voice and leave_voice to manage its lifecycle. A bot can be in one voice channel at a time.


source

Bot.leave_voice

async def leave_voice():

Leave the current voice channel


source

Bot.join_voice

async def join_voice(
    channel
):

Join a voice channel and return VoiceClient

vc = await bot.join_voice(vch)
vc
VoiceClient(self.ch=Channel(id=1327046393453613080, name='General', type=2))
voice json 11 {'user_ids': ['346450717025894400']}
voice json 18 {'user_id': '346450717025894400', 'flags': 2}
voice json 20 {'user_id': '346450717025894400', 'platform': 0}
voice json 15 {'any': 100}
vc.start_recording()
'/tmp/recording.mp3'
pth = vc.stop_recording()
await bot.leave_voice()
# Audio(pth)