Browse Source

Merge pull request #40 from 420foxbot/docs-fix-events

Updated existing documentation for 0.9
tags/1.0-rc
RogueException 9 years ago
parent
commit
bbf66ca8db
14 changed files with 251 additions and 74 deletions
  1. +1
    -1
      docs/features/commands.rst
  2. +9
    -11
      docs/features/events.rst
  3. +11
    -5
      docs/features/logging.rst
  4. +23
    -17
      docs/features/permissions.rst
  5. +1
    -1
      docs/features/server-management.rst
  6. +2
    -2
      docs/features/user-management.rst
  7. +171
    -4
      docs/features/voice.rst
  8. +3
    -3
      docs/getting_started.rst
  9. +3
    -1
      docs/global.txt
  10. +7
    -5
      docs/index.rst
  11. +7
    -7
      docs/samples/events.cs
  12. +6
    -3
      docs/samples/getting_started.cs
  13. +2
    -3
      docs/samples/logging.cs
  14. +5
    -11
      docs/samples/permissions.cs

+ 1
- 1
docs/features/commands.rst View File

@@ -1,7 +1,7 @@
|stub| Commands
===============

The `Discord.Net.Commands`_ package DiscordBotClient extends DiscordClient with support for commands.
The `Discord.Net.Commands`_ package extends DiscordClient with a built-in Commands Handler.

.. _Discord.Net.Commands: https://www.nuget.org/packages/Discord.Net.Commands



+ 9
- 11
docs/features/events.rst View File

@@ -3,21 +3,19 @@ Events

Usage
-----
Messages from the Discord server are exposed via events on the DiscordClient class and follow the standard EventHandler<EventArgs> C# pattern.
Messages from the Discord server are exposed via events on the DiscordClient class and follow the standard EventHandler<EventArgs> C# pattern.

.. warning::
Note that all synchronous code in an event handler will run on the gateway socket's thread and should be handled as quickly as possible.
Note that all synchronous code in an event handler will run on the gateway socket's thread and should be handled as quickly as possible.
Using the async-await pattern to let the thread continue immediately is recommended and is demonstrated in the examples below.

Connection State
----------------
Ready
-----

Connection Events will be raised when the Connection State of your client changes.
The Ready Event is raised only once, when your client finishes processing the READY packet from Discord.

This has replaced the previous "Connected" event, and indicates that it is safe to begin retrieving users, channels, or servers from the cache.

.. warning::
You should not use DiscordClient.Connected to run code when your client first connects to Discord.
If you lose connection and automatically reconnect, this code will be ran again, which may lead to unexpected behavior.
Messages
--------

@@ -26,7 +24,7 @@ Messages

Example of MessageReceived:

.. code-block:: c#
.. code-block:: csharp6

// (Preface: Echo Bots are discouraged, make sure your bot is not running in a public server if you use them)

@@ -56,7 +54,7 @@ There are several user events:

Examples:

.. code-block:: c#
.. code-block:: csharp6

// Register a Hook into the UserBanned event using a Lambda
_client.UserBanned += async (s, e) => {


+ 11
- 5
docs/features/logging.rst View File

@@ -2,12 +2,12 @@ Logging
=======

Discord.Net will log all of its events/exceptions using a built-in LogManager.
This LogManager can be accessed through DiscordClient.Log
This LogManager can be accessed through ``DiscordClient.Log``

Usage
-----

To handle Log Messages through Discord.Net's Logger, you must hook into the Log.Message<LogMessageEventArgs> Event.
To handle Log Messages through Discord.Net's Logger, you must hook into the ``Log.Message<LogMessageEventArgs>`` Event.

The LogManager does not provide a string-based result for the message, you must put your own message format together using the data provided through LogMessageEventArgs
See the Example for a snippet of logging.
@@ -17,19 +17,25 @@ Logging Your Own Data

The LogManager included in Discord.Net can also be used to log your own messages.

You can use DiscordClient.Log.Log(LogSeverity, Source, Message, Exception), or one of the shortcut helpers, to log data.
You can use ``DiscordClient.Log.Log(LogSeverity, Source, Message, [Exception])``, or one of the shortcut helpers, to log data.

Example:
.. code-block:: c#

.. code-block:: csharp6

_client.MessageReceived += async (s, e) {
// Log a new Message with Severity Info, Sourced from 'MessageReceived', with the Message Contents.
_client.Log.Info("MessageReceived", e.Message.Text, null);
};


.. warning::

Starting in Discord.Net 1.0, you will not be able to log your own messages. You will need to create your own Logging manager, or use a pre-existing one.

Example
-------

.. literalinclude:: /samples/logging.cs
:language: c#
:language: csharp6
:tab-width: 2

+ 23
- 17
docs/features/permissions.rst View File

@@ -1,8 +1,21 @@
Permissions
===========

|outdated|

There are two types of permissions: *Channel Permissions* and *Server Permissions*.

Permission Overrides
--------------------

Channel Permissions are expressed using an enum, ``PermValue``.

The three states are fairly straightforward -

``PermValue.Allow``: Allow the user to perform a permission.
``PermValue.Deny``: Deny the user to perform a permission.
``PermValue.Inherit``: The user will inherit the permission from its role.

Channel Permissions
-------------------
Channel Permissions are controlled using a set of flags:
@@ -29,27 +42,24 @@ Speak Voice Speak in a voice channel.
UseVoiceActivation Voice Use Voice Activation in a text channel (for large channels where PTT is preferred)
======================= ======= ==============

If a user has a permission, the value is true. Otherwise, it must be null.

Dual Channel Permissions
------------------------
You may also access a user's permissions in a channel with the DualChannelPermissions class.
Unlike normal ChannelPermissions, DualChannelPermissions hold three values:

If a user has a permission, the value is true. If a user is denied a permission, it will be false. If the permission is not set, the value will return null.
Each flag is a PermValue; see the section above.

Setting Channel Permissions
---------------------------

To set channel permissions, you may use either two ChannelPermissions, or one DualChannelPermissions.
To set channel permissions, create a new ``ChannelPermissionOverrides``, and specify the flags/values that you want to override.

Then, update the user, by doing ``Channel.AddPermissionsRule(_user, _overwrites);``

In the case of using two Channel Permissions, you must create one list of allowed permissions, and one list of denied permissions.
Otherwise, you can use a single DualChannelPermissions.
Roles
-----

Accessing/modifying permissions for roles is done the same way as user permissions, just using the overload for a Role. See above sections.

Server Permissions
------------------

Server Permissions can be accessed by ``Server.GetPermissions(User)``, and updated with ``Server.UpdatePermissions(User, ServerPermissions)``
Server Permissions can be viewed with ``User.ServerPermissions``, but **at the time of this writing** cannot be set.

A user's server permissions also contain the default values for it's channel permissions, so the channel permissions listed above are also valid flags for Server Permissions. There are also a few extra Server Permissions:

@@ -61,11 +71,7 @@ KickMembers Server Kick users from the server. They can still rejoi
ManageRoles Server Manage roles on the server, and their permissions.
ManageChannels Server Manage channels that exist on the server (add, remove them)
ManageServer Server Manage the server settings.

Roles
-----

Managing permissions for roles is much easier than for users in channels. For roles, just access the flag under `Role.Permissions`.
======================= ======= ==============

Example
-------


+ 1
- 1
docs/features/server-management.rst View File

@@ -10,7 +10,7 @@ You can create Channels, Invites, and Roles on a server using the CreateChannel,

You may also edit a server's name, icon, and region.

.. code-block:: c#
.. code-block:: csharp6

// Create a Channel and retrieve the Channel object
var _channel = await _server.CreateChannel("announcements", ChannelType.Text);


+ 2
- 2
docs/features/user-management.rst View File

@@ -6,7 +6,7 @@ Banning

To ban a user, invoke the Ban function on a Server object.

.. code-block:: c#
.. code-block:: csharp6

_server.Ban(_user, 30);

@@ -17,6 +17,6 @@ Kicking

To kick a user, invoke the Kick function on the User.

.. code-block:: c#
.. code-block:: csharp6

_user.Kick();

+ 171
- 4
docs/features/voice.rst View File

@@ -1,13 +1,180 @@
|stub| Voice
=================
Voice
=====

|stub-desc|
Installation
------------

Before setting up the AudioService, you must first install the package `from NuGet`_ or `GitHub`_.

Add the package to your solution, and then import the namespace ``Discord.Audio``.

.. _from NuGet: https://www.nuget.org/packages/Discord.Net.Audio/0.9.0-rc3
.. _GitHub: https://github.com/RogueException/Discord.Net/tree/master/src/Discord.Net.Audio

Setup
-----

To use audio, you must install the AudioService to your DiscordClient.

.. code-block:: csharp6
var _client = new DiscordClient();

_client.UsingAudio(x => // Opens an AudioConfigBuilder so we can configure our AudioService
{
x.Mode = AudioMode.Outgoing; // Tells the AudioService that we will only be sending audio
});

Joining a Channel
-----------------

Joining Voice Channels is pretty straight-forward, and is required to send Audio. This will also allow us to get an IAudioClient, which we will later use to send Audio.

.. code-block:: csharp6
var voiceChannel = _client.FindServers("Music Bot Server").FirstOrDefault().VoiceChannels.FirstOrDefault(); // Finds the first VoiceChannel on the server 'Music Bot Server'

var _vClient = await _client.GetService<AudioService>() // We use GetService to find the AudioService that we installed earlier. In previous versions, this was equivelent to _client.Audio()
.Join(VoiceChannel); // Join the Voice Channel, and return the IAudioClient.

The client will sustain a connection to this channel until it is kicked, disconnected from Discord, or told to Disconnect.

The IAudioClient
----------------

The IAudioClient is used to connect/disconnect to/from a Voice Channel, and to send audio to that Voice Channel.

.. function:: IAudioClient.Disconnect();
Disconnects the IAudioClient from the Voice Server.


.. function:: IAudioClient.Join(Channel);
Moves the IAudioClient to another channel on the Voice Server, or starts a connection if one has already been terminated.

.. note::

Because versions previous to 0.9 do not discretely differentiate between Text and Voice Channels, you may want to ensure that users cannot request the audio client to join a text channel, as this will throw an exception, leading to potentially unexpected behavior
.. function:: IAudioClient.Wait();
Blocks the current thread until the sending audio buffer has cleared out.

.. function:: IAudioClient.Clear();
Clears the sending audio buffer.

.. function:: IAudioClient.Send(byte[] data, int offset, int count);
Adds a stream of data to the Audio Client's internal buffer, to be sent to Discord. Follows the standard c# Stream.Send() format.

Broadcasting
------------

There are multiple approaches to broadcasting audio. Discord.Net will convert your audio packets into Opus format, so the only work you need to do is converting your audio into a format that Discord will accept. The format Discord takes is 16-bit 48000Hz PCM.

Broadcasting with NAudio
------------------------

`NAudio`_ is one of the easiest approaches to sending audio, although it is not multi-platform compatible. The following example will show you how to read an mp3 file, and send it to Discord.
You can `download NAudio from NuGet`_.

.. code-block:: csharp6

using NAudio;
using NAudio.Wave;
using NAudio.CoreAudioApi;
public void SendAudio(string filePath)
{
var channelCount = _client.GetService<AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use.
var OutFormat = new WaveFormat(48000, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports.
using (var MP3Reader = new Mp3FileReader(filePath)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter
using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format
{
resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality
int blockSize = outFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer
byte[] buffer = new byte[blockSize];
int byteCount;

while((byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present
{
if (byteCount < blockSize)
{
// Incomplete Frame
for (int i = byteCount; i < blockSize; i++)
buffer[i] = 0;
}
_vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord
}
}

}

.. _NAudio: https://naudio.codeplex.com/
.. _download NAudio from NuGet: https://www.nuget.org/packages/NAudio/

Broadcasting with FFmpeg
------------------------

`FFmpeg`_ allows for a more advanced approach to sending audio, although it is multiplatform safe. The following example will show you how to stream a file to Discord.

.. code-block:: csharp6

public void SendAudio(string pathOrUrl)
{
var process = Process.Start(new ProcessStartInfo { // FFmpeg requires us to spawn a process and hook into its stdout, so we will create a Process
FileName = "ffmpeg",
Arguments = $"-i {pathOrUrl}" + // Here we provide a list of arguments to feed into FFmpeg. -i means the location of the file/URL it will read from
"-f s16le -ar 48000 -ac 2 pipe:1", // Next, we tell it to output 16-bit 48000Hz PCM, over 2 channels, to stdout.
UseShellExecute = false,
RedirectStandardOutput = true // Capture the stdout of the process
});
Thread.Sleep(2000); // Sleep for a few seconds to FFmpeg can prebuffer.
int blockSize = 3840; // The size of bytes to read per frame; 1920 for mono
byte[] buffer = new byte[blockSize];
int byteCount;

while (true) // Loop forever, so data will always be read
{
byteCount = process.StandardOutput.BaseStream // Access the underlying MemoryStream from the stdout of FFmpeg
.Read(buffer, 0, blockSize); // Read stdout into the buffer

if (byteCount == 0) // FFmpeg did not output anything
break; // Break out of the while(true) loop, since there was nothing to read.

_vClient.Send(buffer, 0, byteCount); // Send our data to Discord
}
_vClient.Wait(); // Wait for the Voice Client to finish sending data, as ffMPEG may have already finished buffering out a song, and it is unsafe to return now.
}

.. _FFmpeg: https://ffmpeg.org/

.. note::
The code-block above assumes that your client is configured to stream 2-channel audio. It also may prematurely end a song. FFmpeg can — especially when streaming from a URL — stop to buffer data from a source, and cause your output stream to read empty data. Because the snippet above does not safely track for failed attempts, or buffers, an empty buffer will cause playback to stop. This is also not 'memory-friendly'.

Multi-Server Broadcasting
-------------------------

.. warning:: Multi-Server broadcasting is not supported by Discord, will cause performance issues for you, and is not encouraged. Proceed with caution.

To prepare for Multi-Server Broadcasting, you must first enable it in your config.

.. code-block::csharp6
_client.UsingAudio(x =>
{
x.Mode = AudioMode.Outgoing;
x.EnableMultiserver = true; // Enable Multiserver
});

From here on, it is as easy as creating an IAudioClient for each server you want to join. See the sections on broadcasting to proceed.


Receiving
---------
---------

**Receiving is not implemented in the latest version of Discord.Net**

+ 3
- 3
docs/getting_started.rst View File

@@ -22,12 +22,12 @@ You can get Discord.Net from NuGet:

If you have trouble installing from NuGet, try installing dependencies manually.

You can also pull the latest source from `GitHub`_
You can also pull the latest source from `GitHub`_

.. _Discord.Net: https://www.nuget.org/packages/Discord.Net
.. _Discord.Net.Commands: https://www.nuget.org/packages/Discord.Net.Commands
.. _Discord.Net.Modules: https://www.nuget.org/packages/Discord.Net.Modules
.. _Discord.Net.Modules: https://www.nuget.org/packages/Discord.Net.Audio
.. _Discord.Net.Audio: https://www.nuget.org/packages/Discord.Net.Audio
.. _GitHub: https://github.com/RogueException/Discord.Net/

Async
@@ -42,7 +42,7 @@ For more information, go to `MSDN's Await-Async section`_.

Example
-------
.. literalinclude:: samples/getting_started.cs
:language: csharp6
:tab-width: 2

+ 3
- 1
docs/global.txt View File

@@ -1,2 +1,4 @@
.. |stub| unicode:: U+1F527
.. |stub-desc| replace:: This page is a placeholder and has not been written yet. It should be coming soon!
.. |stub-desc| replace:: This page is a placeholder and has not been written yet. It should be coming soon!
.. |outdated| replace:: **This page is currently out-of-date. The information below may be inaccurate.**
.. |incomplete| replace:: **This page is incomplete. While the information below is accurate, it should be noted that it is not thorough.**

+ 7
- 5
docs/index.rst View File

@@ -9,13 +9,13 @@ Feel free to join us in the `Discord API chat`_.
.. _Discord chat service: https://discordapp.com
.. _Discord API chat: https://discord.gg/0SBTUU1wZTVjAMPx

.. warn::
.. warning::

This is a beta!
This is a beta!

This library has been built thanks to a community effort reverse engineering the Discord client.
As the API is still unofficial, it may change at any time without notice, breaking this library as well.
Discord.Net itself is still in development (and is currently undergoing a rewrite) and you may encounter breaking changes throughout development until the official Discord API is released.
This library has been built thanks to a community effort reverse engineering the Discord client.
As the API is still unofficial, it may change at any time without notice, breaking this library as well.
Discord.Net itself is still in development (and is currently undergoing a rewrite) and you may encounter breaking changes throughout development until the official Discord API is released.

It is highly recommended that you always use the latest version and please report any bugs you find to our `Discord chat`_.

@@ -23,6 +23,8 @@ It is highly recommended that you always use the latest version and please repor

This Documentation is **currently undergoing a rewrite**. Some pages (marked with a wrench) are not updated, or are not completed yet.

**The documentation is currently being written to reflect ``0.9-rc4``, which can be accessed via the latest git-master.**

.. toctree::
:caption: Documentation
:maxdepth: 2


+ 7
- 7
docs/samples/events.cs View File

@@ -1,20 +1,20 @@
class Program
{
private static DiscordBotClient _client;
private static DiscordClient _client;
static void Main(string[] args)
{
var client = new DiscordClient();
_client = new DiscordClient();

// Handle Events using Lambdas
client.MessageCreated += (s, e) =>
_client.MessageReceived += (s, e) =>
{
if (!e.Message.IsAuthor)
await client.SendMessage(e.Message.ChannelId, "foo");
await e.Channel.SendMessage("foo");
}

// Handle Events using Event Handlers
EventHandler<MessageEventArgs> handler = new EventHandler<MessageEventArgs>(HandleMessageCreated);
client.MessageCreated += handler;
client.MessageReceived += handler;
}


@@ -22,6 +22,6 @@ class Program
static void HandleMessageCreated(object sender, EventArgs e)
{
if (!e.Message.IsAuthor)
await client.SendMessage(e.Message.ChannelId, "foo");
await e.Channel.SendMessage("bar");
}
}
}

+ 6
- 3
docs/samples/getting_started.cs View File

@@ -2,10 +2,13 @@ class Program
{
static void Main(string[] args)
{
var client = new DiscordClient();
var client = new DiscordClient(x =>
{
LogLevel = LogSeverity.Info
});

//Display all log messages in the console
client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");

//Echo back any message received, provided it didn't come from the bot itself
client.MessageReceived += async (s, e) =>
@@ -22,7 +25,7 @@ class Program

//If we are not a member of any server, use our invite code (made beforehand in the official Discord Client)
if (!client.Servers.Any())
await client.AcceptInvite(client.GetInvite("aaabbbcccdddeee"));
await (client.GetInvite("aaabbbcccdddeee")).Accept();
});
}
}

+ 2
- 3
docs/samples/logging.cs View File

@@ -1,6 +1,5 @@
class Program
{
private static DiscordBotClient _client;
static void Main(string[] args)
{
var client = new DiscordClient(x =>
@@ -8,13 +7,13 @@ class Program
LogLevel = LogSeverity.Info
});

_client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");

client.ExecuteAndWait(async () =>
{
await client.Connect("discordtest@email.com", "Password123");
if (!client.Servers.Any())
await client.AcceptInvite("aaabbbcccdddeee");
await (client.GetInvite("aaabbbcccdddeee")).Accept();
});
}
}

+ 5
- 11
docs/samples/permissions.cs View File

@@ -1,14 +1,8 @@
// Find a User's Channel Permissions
var userChannelPermissions = user.GetPermissions(channel);

// Find a User's Server Permissions
var userServerPermissions = user.ServerPermissions();
var userServerPermissions = server.GetPermissions(user);
// Find a User's Channel Permissions
var UserPerms = _channel.GetPermissionsRule(_user);

// Set a User's Channel Permissions (using DualChannelPermissions)
// Set a User's Channel Permissions

var userPerms = user.GetPermissions(channel);
userPerms.ReadMessageHistory = false;
userPerms.AttachFiles = null;
channel.AddPermissionsRule(user, userPerms);
}
var NewOverwrites = new ChannelPermissionOverrides(sendMessages: PermValue.Deny);
await channel.AddPermissionsRule(_user, NewOverwrites);

Loading…
Cancel
Save