Metadata-Version: 2.4
Name: riscord-bot
Version: 0.4.2
Summary: Official async Riscord bot client
License: All rights reserved.
Project-URL: Documentation, https://riscord.ir/developers/docs
Project-URL: Changelog, https://riscord.ir/downloads/riscord-bot-changelog.md
Project-URL: Homepage, https://riscord.ir
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Framework :: AsyncIO
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: python-socketio[asyncio_client]<6,>=5.11
Requires-Dist: aiohttp<4,>=3.10
Dynamic: license-file

# Riscord bot SDK — Python

Requires Python 3.11 or newer. Install with `python -m pip install riscord-bot`. Versioned source archives remain available from [Developer Docs](https://riscord.ir/developers/docs); install a downloaded archive with `python -m pip install ./riscord-bot-python-0.3.0.tar.gz`.

[SDK release notes](https://riscord.ir/downloads/riscord-bot-changelog.md)

Create and install a bot through `https://riscord.ir/developers`, request View Channel and Send Messages, generate its token and set the `RISCORD_BOT_TOKEN` environment variable. Never commit the token.

```python
import asyncio, os
from riscord import Client

bot = Client(os.environ['RISCORD_BOT_TOKEN'])

@bot.command('hello')
async def hello(interaction):
    await interaction.reply('Hello!', private=True)

async def main():
    await bot.register_commands([{'name':'hello','description':'Say hello','contexts':['server','dm']}])
    try:
        await bot.run()
    finally:
        await bot.close()

asyncio.run(main())
```

Defer slow work with `await interaction.defer(private=True)` before replying; later replies retain that audience. `show_modal({customId,title,fields})` opens a form. Use `@bot.on('interaction')` for buttons, selects and submitted forms and inspect `interaction.kind` and `interaction.data`.

Embeds work in public and private replies, channel messages and DMs. Use dictionaries or the chainable `Embed` builder:

```python
from riscord import Embed

card = (Embed(title='Your queue', description='Something good is up next.', color=0xA693FF)
        .add_field('Tracks', '3', inline=True)
        .set_footer('Pick a track and settle in.'))
await interaction.reply(embeds=[card], private=True)
await interaction.edit_reply(embeds=[Embed(title='All caught up', color=0x81D8A0)])
followup = await interaction.follow_up('Want another?', client_id=f'next-{interaction.id}')
await interaction.edit_followup(followup['id'], 'One more?')
```

The first successful reply stays the target of `edit_reply` and `delete_reply`; sending followups does not replace it. After a defer, `edit_reply` sends the first reply. `edit_followup(message_id, ...)` and `delete_followup(message_id)` address a specific reply. A failed request does not change the stored audience. Keep `client_id` stable when retrying your own operations. The API allows up to 10 embeds, 25 fields per embed and 6,000 combined embed text characters. Embed image/icon URLs use HTTP(S); `imageUrl` and `fileUrl` attachments must come from `upload`.

`send` and `send_dm` can omit content for an embed or attachment. Upload a file, then use the returned URL:

```python
uploaded = await bot.upload(b'hello\n', 'hello.txt', 'text/plain')
await bot.send(channel_id, fileUrl=uploaded['url'], client_id='hello-file-1')
await bot.edit(channel_id, message_id, embeds=[card])  # Other fields stay as they were.
await bot.edit_dm(conversation_id, message_id, components=[])  # Explicitly remove controls.
await bot.delete_dm(conversation_id, message_id)
page = await bot.history(channel_id, before=older_cursor, limit=50)
older_cursor = page['nextCursor']
```

`edit(channel_id, message_id, content, components)` still accepts positional content and controls. Omitted fields are preserved; `embeds=[]` and `components=[]` clear those fields. Passing `None` explicitly for the legacy positional controls argument also clears controls. History returns `messages` in chronological order and a `nextCursor` for older messages, or `None` when there are no more. Reading history needs Message Content permission.

Command options support `string`, `integer`, `number`, `boolean`, `user`, `channel`, `role` and `mentionable`. Strings and numbers can have static `choices`; use `minLength`/`maxLength` for strings or `minValue`/`maxValue` for numbers. For example:

```python
{'name': 'volume', 'description': 'Pick a volume', 'type': 'number',
 'required': True, 'minValue': 0, 'maxValue': 2,
 'choices': [{'name': 'Normal', 'value': 1}, {'name': 'Louder', 'value': 1.5}]}
```

There are up to 25 options per command and 25 choices per option. Required is a boolean; integers and numeric bounds stay within ±9,007,199,254,740,991. User/channel/role/mentionable values are string IDs. Dynamic autocomplete and nested subcommands are not available yet.

`channels(server_id)`, `members(server_id, cursor=...)`, `roles(server_id)` and `member(server_id, user_id)` provide permission-scoped server resources. Roles are returned in `items`; a member lookup adds `joinedAt`, `roleIds` and `roles`, without private profile details. Role IDs contain explicit assignments; the default server role is implicit. `set_role` adds/removes an allowed lower role. `moderate(server_id, user_id, action, ...)` supports `kick`, `ban`, `unban`, `timeout` and `clear-timeout`; `unban` and `clear_timeout` are shortcuts. The server enforces installation consent, permissions and hierarchy.

`open_dm`, `delete`, and the other methods expose the corresponding API operations. For message options, `client_id` is a Python keyword argument; component/command JSON follows the documented camelCase wire schema. IDs remain strings.

Only registered text commands, mentions and the bot's DMs are delivered without broader Message Content permission. SDKs ignore automated messages, reconnect with bounded replay and honor retry delays. Deduplication is bounded and memory-only; persist operation IDs for external effects that must survive restarts.

For voice playback, request View Channel, Connect and Speak when installing the bot, and allow them in the target server voice channel. Install a separate FFmpeg executable with the `libopus` encoder and SRTP support and add it to `PATH`; the SDK does not download an encoder. Chat and interactions do not need FFmpeg.

```python
await bot.connect()
voice = await bot.join_voice('VOICE_CHANNEL_ID')
try:
    await voice.play('./music.ogg')
    await voice.play('https://example.com/direct-audio.ogg')
finally:
    await voice.leave()
```

`join_voice(channel_id)` requires a connected bot gateway and returns a `VoiceConnection`. `play(source, ffmpeg='ffmpeg')` accepts a trusted local audio file or direct HTTP(S) audio URL and waits until playback finishes. A new `play` replaces the previous track; call it in an `asyncio` task if your handler must keep accepting other work. `stop()` ends playback while keeping the bot in the channel; `leave()` releases the connection. Cancelling the playback task also stops its encoder. `playing`, `closed`, `channel_id` and `server_id` expose connection state.

With SDK 0.4.1 and the updated API, a moderator can move the bot without ending its voice lease. `channel_id` updates automatically; an active `play()` stays pending while the encoder restarts in the destination with fresh media credentials. Seekable files and direct audio URLs resume from FFmpeg progress, with elapsed-time fallback. Live or non-seekable sources may not resume accurately. Explicit stop, replacement, leave and gateway disconnect still cancel playback. Older APIs retain their original disconnect-on-move behavior.

Voice is send-only and self-deafened; the SDK never receives or records channel audio. Each playback gets fresh Opus/SRTP media parameters and stays within the server's audio bitrate limit. The SDK renews the lease every ten seconds and stops playback on a lost lease, gateway disconnect or `bot.close()`. Reconnecting the gateway does not rejoin voice automatically. With SDK 0.4.2 and the updated API, one client can own a separate voice channel in each server, with independent playback. Joining again replaces only that server’s connection. Older APIs retain one connection across all servers. Stale playback cleanup cannot stop its replacement.

To follow the person using `/play`, read `interaction.voice_channel_id` and pass it to `bot.join_voice`. It is the caller's connected voice channel in the interaction's server at delivery time, or `None` if disconnected, in a different server/DM call, or the room is not visible to both caller and bot. Installation channel restrictions apply, and joining still needs Connect and Speak. This field needs the updated API; older servers leave it `None`.

Use sources you control. FFmpeg fetches URLs from the bot's machine, so do not pass arbitrary member-provided paths or URLs to `play`. Website pages that require a media extractor are not direct audio URLs. Encoder errors omit raw process output because it can contain private source URLs or transport keys. Set `RISCORD_AUDIO_SOURCE` alongside the bot token, then run `examples/music.py` for a complete `/play` bot; no fixed channel environment variable is needed. Registering that example replaces the bot's command list.

The public [Developer Docs](https://riscord.ir/developers/docs) cover the API contract, limits and migration guidance.

## Local Rich Presence

`RPCClient` connects a game or app running on the same Windows PC to Riscord. Use the application ID from the Developer Portal; it never needs or sends a bot token. Riscord uses the registered application name and avatar instead of a caller-provided identity.

```python
import asyncio
import time
from riscord import RPCClient

async def main():
    async with RPCClient('APPLICATION_ID') as rpc:
        await rpc.set_activity({
            'details': 'Exploring the coast',
            'state': 'Chapter 2',
            'timestamps': {'start': int(time.time())},
            'buttons': [{'label': 'Game website', 'url': 'https://example.com/game'}],
        })
        await asyncio.Event().wait()

asyncio.run(main())
```

The user must enable **Share game activity** and **Share Rich Presence** in Riscord. Sharing stays off until the master game-activity switch is enabled; appearing offline hides activity. Details and state accept up to 128 plain text characters, and up to two public HTTPS buttons are supported. Timestamps use whole Unix seconds, at most seven days in the past. Links open through Riscord’s confirmation flow. Arbitrary artwork, login credentials, window titles and executable paths are not sent.

`await rpc.clear_activity()` removes this connection’s activity, and `await rpc.close()` closes the client. The async context manager closes it automatically. After a lost connection, the SDK waits five seconds between reconnect attempts and restores the latest requested activity after a new handshake. Newer updates and clears supersede an older reconnect attempt. Turning sharing off closes local connections; closing your game or client releases its own activity without clearing another application’s newer activity. `rpc.connected` reports the local connection state; connection alone does not mean the user has made the activity publicly visible.

This uses Windows’ default `asyncio` Proactor event loop and local named pipes, with bounded handshake/acknowledgement waits and a 16 KiB frame limit. It does not connect to a web port or use the bot gateway. Linux, macOS and browser RPC are not available in this release. Set `RISCORD_APPLICATION_ID` and run `examples/rpc.py` for a complete example.
