discord-net / discord.net Goto Github PK
View Code? Open in Web Editor NEWAn unofficial .Net wrapper for the Discord API (https://discord.com/)
Home Page: https://discordnet.dev
License: MIT License
An unofficial .Net wrapper for the Discord API (https://discord.com/)
Home Page: https://discordnet.dev
License: MIT License
A lot of these are already in place - specifically binary literals and type switching. They're locked behind the CSHARP7 conditional until we get ASP.Net Core support in VS15.
In console window (OnLogMessage from DiscordBot):
[Gateway] Disconnected: Received close code 4002: Error while decoding payload.
In Visual Studio output window:
Exception thrown: 'Discord.Net.WebSocketException' in Discord.Net.dll
Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in mscorlib.ni.dll
Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in mscorlib.ni.dll
Exception thrown: 'Discord.Net.WebSocketException' in mscorlib.ni.dll
This occurs every 32.5 seconds when there is absolutely no activity in connected channels.
With activity, this does not occur.
After disconnecting, Discord.Net reconnects and, if there is still no activity, it disconnects again after 32.5 seconds.
Guessing it has something to do with the heartbeat.
Using .Net Core RC2. Latest master branch from GitHub.
project.json:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Newtonsoft.Json": "8.0.4-beta1",
"Discord.Net": "0.9.2"
},
"frameworks": {
"netstandard1.5": {
"imports": [
"portable-net451+win81"
]
}
},
"runtimes": {
"win81-x64": { }
}
}
Program.cs:
using System;
using System.Text;
using Discord;
namespace InactivityIssue
{
public class Program
{
public static void Main(string[] args) => new Program().Start();
private DiscordClient _client;
public void Start()
{
_client = new DiscordClient(x =>
{
x.LogLevel = LogSeverity.Debug;
x.LogHandler = OnLogMessage;
});
_client.ExecuteAndWait(async () =>
{
await _client.Connect("BOTTOKEN");
});
}
private void OnLogMessage(object sender, LogMessageEventArgs e)
{
//Color
ConsoleColor color;
switch (e.Severity)
{
case LogSeverity.Error: color = ConsoleColor.Red; break;
case LogSeverity.Warning: color = ConsoleColor.Yellow; break;
case LogSeverity.Info: color = ConsoleColor.White; break;
case LogSeverity.Verbose: color = ConsoleColor.Gray; break;
case LogSeverity.Debug: default: color = ConsoleColor.DarkGray; break;
}
//Exception
string exMessage;
Exception ex = e.Exception;
if (ex != null)
{
while (ex is AggregateException && ex.InnerException != null)
ex = ex.InnerException;
exMessage = ex.Message;
}
else
exMessage = null;
//Source
string sourceName = e.Source?.ToString();
//Text
string text;
if (e.Message == null)
{
text = exMessage ?? "";
exMessage = null;
}
else
text = e.Message;
//Build message
StringBuilder builder = new StringBuilder(text.Length + (sourceName?.Length ?? 0) + (exMessage?.Length ?? 0) + 5);
if (sourceName != null)
{
builder.Append('[');
builder.Append(sourceName);
builder.Append("] ");
}
for (int i = 0; i < text.Length; i++)
{
//Strip control chars
char c = text[i];
if (!char.IsControl(c))
builder.Append(c);
}
if (exMessage != null)
{
builder.Append(": ");
builder.Append(exMessage);
}
text = builder.ToString();
Console.ForegroundColor = color;
Console.WriteLine(text);
}
}
}
Hi,
I've been having an issue with running the bot under mono in Ubuntu 14.04. When it tries to connect:
Disconnected: You must send data by websocket after websocket is opened!
Unhandled Exception:
System.Exception: You must send data by websocket after websocket is opened!
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at Discord.TaskManager.ThrowException () [0x00000] in <filename unknown>:0
at Discord.Net.WebSockets.WebSocket.WaitForConnection (CancellationToken cancelToken) [0x00000] in <filename unknown>:0
at Discord.Net.WebSockets.GatewaySocket.WaitForConnection (CancellationToken cancelToken) [0x00000] in <filename unknown>:0
at Discord.DiscordClient+<BeginConnect>d__76.MoveNext () [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at Discord.DiscordClient+<BeginConnect>d__76.MoveNext () [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in <filename unknown>:0
at Discord.DiscordClient+<Connect>d__74.MoveNext () [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[System.String].GetResult () [0x00000] in <filename unknown>:0
at hammerbot.HammerBot+<InitializeConnection>c__async0.MoveNext () [0x00000] in <filename unknown>:0
I saw that you mentioned here that you were aware of Mono issues but since the post last year I am unsure whether the fix was pushed or not:
I use 0.9.0-rc3-3
The title says it all, when running the following code inside a command's declaration:
await e.Channel.SendMessage(e.Message.Text);
, it will error out saying value cannot be blank.
RawText works though, so I'm using that in the meantime.
Using Discord 0.9.3 on Windows 10, Visual Studio 2015.
Nuget does not show a package for Discord.Net.Audio
Server.FindUsers(expression, false);
will search for exact match only.
Expected behavior when exactMatch = false
should be equal to User.Name.ToLower().Contains(expression.ToLower())
while it seems to behave as User.Name.ToLower() == expression.ToLower()
In other words, It is not case sensitive, but it won't find partial name.
Example of successful search to find user "Rhea the Cookie"
expression = "rhea the cookie";
expression = "Rhea the Cookie";
Example of unsuccessful search:
expression = rhea
expression = Rhea
Suggested solution (please excuse syntax issues, typing it right here..)
public IEnumerable<User> FindUsers(string name, bool exactMatch = false)
{
if( string.IsNullOrEmpty(name) )
throw new ArgumentNullException(nameof(name));
if( exactMatch )
return _users.Values.ToList().FindAll( u => u.Name == name );
return _users.Values.ToList().FindAll( u => u.Name.ToLower().Contains(name.ToLower) );
}
ps. sorry but i can't submit pull right now...
Right now, we lock the highest level bucket, which is excessive. Using bucket ids, we could identify which level needs to be locked.
We should maintain our own subscriber list, rather than generate one every time we raise an event.
Key: mfa_level
Also maybe start SocketClient with a blank DataStore? Shouldn't be null. Added
When trying to get Discord.Net v0.7.3 (or the latest) it throws an error about not being able to resolve the dependency WebSocketSharp.
Error log:
Install-Package Discord.Net -Version 0.7.3
Attempting to resolve dependency 'Newtonsoft.Json (≥ 7.0.1)'.
Attempting to resolve dependency 'RestSharp (≥ 105.2.3)'.
Attempting to resolve dependency 'WebSocketSharp (≥ 1.0.3-rc9)'.
Install-Package : Unable to resolve dependency 'WebSocketSharp (≥ 1.0.3-rc9)'.
At line:1 char:16
Trying to experiment with the possibility of a bot coming in a voice channel and playing a short sample music/sound.
When I try IAudioClient audioClient = AudioExtensions.GetAudioClient(e.Server);
it tells me that there must be an AudioService in the current DiscordClient, so then I try the following right after the bot connected succesfully:
client.AddService<AudioService>();
Console.WriteLine("Audio service initialized");
However when I run it an exception is thrown when adding the service.
An unhandled exception of type 'System.DllNotFoundException' occurred in mscorlib.dll
Additional information: Cannot load DLL 'opus': The specified module is not found (Exception of HRESULT : 0x8007007E)
Port from Khio's 0.9 implementation.
First of all I want to say I love the work done so far with this lib! Thank you all!
My question is how or what event can I use when the bot has Connected and/or 'Ready'?
I've been reading the DiscordBot code since the current documentation is abysmal at best, and I see there is (or once was) an event on the DiscordClient object called 'Ready' (the Twitch module uses it). After looking for documentation, searching the open/closed issues and banging my head against the wall, I've come to the conclusion that it may or may not have been changed to 'Connected' but I don't see this in here either.
DiscordWebSocket internally uses System.Net.WebSockets.ClientWebSocket. Microsoft openly admits sabotaging their own framework by not providing the necessary "websocket.dll" dependency on Windows 7, Vista and Server 2008, thus artificially limiting it to Windows 8 and Windows Server 2012:
(from https://msdn.microsoft.com/library/system.net.websockets.clientwebsocket(v=vs.110).aspx)
Remarks
[...] the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012. The class elements in the System.Net.WebSockets namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 are abstract class elements. [...]
Any chances of dropping this dependency in favor of one of the free WebSocket implementations like
http://sta.github.io/websocket-sharp/
or
http://websocket4net.codeplex.com/
(or rolling your own) and making this project available to a broader audience?
Key: default_message_notifications
Ran into this when creating a UWP for Discord using Discord.NET and .NET Core RC3.
Steps to Reproduce:
The app will throw an exception saying that setting the 'PreAuthenticate' value to 'false' is not supported.
Worked fine with 0.9.3., but broke with 0.9.3.1.
[Gateway] Login successful, gateway: wss://gateway.discord.gg/?encoding=json&v=4
[Gateway] Disconnected: The authentication or decryption has failed.
[Login Failed: System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server.
at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (IAsyncResult asyncResult) <0x73aff990 + 0x0010c> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (IAsyncResult ar, Boolean ignoreEmpty) <0x73aff890 + 0x0002b> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (IAsyncResult result) <0x73af97b8 + 0x001e7> in <filename unknown>:0
--- End of inner exception stack trace ---
at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (IAsyncResult result) <0x73a53b78 + 0x000c0> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) <0x73a53868 + 0x000a3> in <filename unknown>:0
--- End of inner exception stack trace ---
at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (IAsyncResult asyncResult) <0x73a380d0 + 0x00164> in <filename unknown>:0
at System.Net.Security.SslStream.EndAuthenticateAsClient (IAsyncResult asyncResult) <0x72aa41d0 + 0x00047> in <filename unknown>:0
at SuperSocket.ClientEngine.SslStreamTcpSession.OnAuthenticated (IAsyncResult result) <0x72aa3d90 + 0x001bb> in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x74ba4888 + 0x00024> in <filename unknown>:0
at Discord.TaskManager.ThrowException () <0x72aa1858 + 0x0005b> in <filename unknown>:0
at Discord.Net.WebSockets.WebSocket.WaitForConnection (CancellationToken cancelToken) <0x71dacb78 + 0x0009b> in <filename unknown>:0
at Discord.Net.WebSockets.GatewaySocket.WaitForConnection (CancellationToken cancelToken) <0x71dac9e0 + 0x00097> in <filename unknown>:0
at Discord.DiscordClient+<BeginConnect>d__78.MoveNext () <0x76876640 + 0x00dcb> in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x74ba4888 + 0x00024> in <filename unknown>:0
at Discord.DiscordClient+<BeginConnect>d__78.MoveNext () <0x76876640 + 0x0136b> in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x74ba4888 + 0x00024> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) <0x74ba249c + 0x000af> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) <0x74ba2424 + 0x0006f> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) <0x74ba23dc + 0x0003f> in <filename unknown>:0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () <0x74ba28c4 + 0x00017> in <filename unknown>:0
at Discord.DiscordClient+<Connect>d__77.MoveNext () <0x76875ee8 + 0x0022f> in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x74ba4888 + 0x00024> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) <0x74ba249c + 0x000af> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) <0x74ba2424 + 0x0006f> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) <0x74ba23dc + 0x0003f> in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () <0x74ba23bc + 0x00017> in <filename unknown>:0
at Wise_Old_Bot.Program+<<Start>b__4_2>d.MoveNext () <0x76875460 + 0x001eb> in <filename unknown>:0 ] The authentication or decryption has failed.
Hello.
I've been wanting to make a new bot with this API that i've already used before, however there is a new system in place to create bots which is all fancy and dandy.
However, I have my secret token, I put it in my source code when connecting as a token and it gives me "401 (Unauthorized)".
I've tried putting both the appID & the token too but it gives me "400 (Bad Request)" instead.
Anything leading me to the right direction would help, thank you.
As of 0.9.2, I have been unable to set my bot's game to anything. I've attempted to use bot Discord.DiscordClient.SetGame(GameInfo)
and Discord.DiscordClient.SetGame(String game, String Url, GameType)
StaticInfo.GetClient().SetGame(new GameInfo() { Name = p.MainWindowTitle, Url = null, Type = GameType.Default });
StaticInfo.GetClient() returns a copy of the client. I have tested it both within the main application and within my plugin interface with no avail.
If you try to get a message that has previously been deleted, but you have a stored ID for it, the Channel.GetMessage(ulong id);
method will crash and as far as i can tell swallow the exception.
I'm not entirely sure that this is true, since i'm executing the Channel.GetMessage(...);
function inside of the DiscordClient.LoggedIn
event, and i cannot get anything from the exception details due to the Exception occuring in a Task
The stacktrace i'm getting when using the DiscordConfigBuilder.LogHandler
event
Discord.Net.HttpException: The server responded with error 404 (NotFound)
at Discord.Net.Rest.RestSharpEngine.<Send>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Discord.Net.Rest.RestClient.<Send>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Discord.Net.Rest.RestClient.<Send>d__22`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Discord.Net.MessageQueue.<>c__DisplayClass19_0.<<RunEditQueue>b__0>d.MoveNext()
When trying to debug where the Exception even comes from, it leads to DiscordClient.ExecuteAndWait
, but encapsulating the contents of the Action
in a Try { } Catch(...) { }
doesn't really present any new details.
tl;dr: It appears Channel.GetMessage()
swallows an exception and i want to be able to get it, or have null returned so that i can delete the stored message id from storage so that i don't get errors every time it tries to access a dead message id.
An important feature we're missing on the client API side of things. Should get this is in for 1.1.
We're using a hacky method right now, waiting for Discord to add a proper endpoint.
Would make it a hell of a lot easier if the aforementioned objects have a .Mention property, even if it only calls the Mention class internally.
As it stands with the limited Documentation that is around this API, little things like the Mention class can be missed quite easily, if you are not familiar with the internet workings of this library.
// On the user object..
public string Mention {
get { return Mention.User(this); }
}
During the login of my bot it all of a sudden has started giving the following error.
[11:17:21][ERROR] Socket Closed! Code: 4002. Reason: Error while decoding payload.. Clear: True.
Might any of you know what may be causing this?
I place a large amount of data into discord every day through discord.net. It seems like after a few hours of everything working as it should, the queue decides to back up and get stuck, then refuses to send any more messages until the program is restarted.
Has backed up about 600 messages before when left running without observation, each message I place into the queue is under 1000 characters and they sort of trickle in from a game we are piping chat and other things from into a discord channel. I have tried two different bots that both use the latest discord.net as a submodule in their repos and they both show this behavior (stuck queue at random seeming times). The queue does work most of the time, but when the messages back up like this and they are supposed to be being sent we lose some data from the game we are watching.
await channel.SendMessage()
is what im using to send things - I am saying it works until it seems to randomly stop working. (I have made no changes to discord.net) I would be willing to add code and help figure out why it gets stuck to what i'm currently using
when client.DownloadMessages tries to fetch a message that belongs to a user that no longer exists on the server, it will throw a nullreferenceexception.
Can't compile due to Visual Studio throwing errors regarding a missing "Settings" class, not sure if missing dependency or due to missing "Credentials.cs" file.
Imports Discord
Module Module1
Dim Client As New DiscordClient
Sub Main()
Client.Connect("Username","Password")
Client.SetGame("Anything")
Console.ReadKey()
End Sub
End Module
An unhandled exception of type 'System.NullReferenceException' occurred in Discord.Net.dll
Additional information: Object reference not set to an instance of an object.
Line 317 of DiscordClient.cs
private void Bot_MessageReceived(object sender, MessageEventArgs e) { e.Channel.SendFile("test.jpg"); }
after multiple attempts, sending an image that is inside the project does not work Someone else in the discord group seems to have the same problem. And Might as well say that e.Channel.SendTTSMessage is not working either. Am I missing something or those functions are bugged right now?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.