Giter Club home page Giter Club logo

twitchlib.client's Introduction

twitchlib.client's People

Contributors

3ventic avatar bernardosulzbach avatar felk avatar foretack avatar fossilz avatar julandealb avatar julusian avatar kokolihapihvi avatar luckynos7evin avatar mahsaap avatar matte-ek avatar michaeljolley avatar mutilator avatar olivierbas avatar prom3theu5 avatar rrickkert avatar sweethuman avatar swiftyspiffy avatar syzuna avatar tesq0 avatar urantij avatar wreckedarrow avatar zaflu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

twitchlib.client's Issues

"none" is logged

Hey!

I was wondering why "none" showed up in my log a couple of times and i started searching for it, eventually i found it here:

Log(response.OptionalData ?? "none");

Is there a specific reason why it logged "none" instead of just nothing, was this for debugging purposses perhaps?

The sender of the event is not TwitchClient

private void _client_OnError(object sender, ErrorEventArgs e)
{
    OnConnectionError?.Invoke(_client, new OnConnectionErrorArgs { BotUsername = TwitchUsername, Error = new ErrorEvent { Exception = e.Exception, Message = e.Exception.Message } });
    Reconnect();
}

Why is the event sender == _client (may be it should be "this")?

Moved 'Calling client.JoinChannel seems to block joining channels'

This issue was originally created by RickRosendaal. The issue is here.

When creating a new client, initializing it (with or without providing a channel), calling .Connect(), and then client.JoinChannel("name"), will result into the client never joining the channel.
The following example will print "Connected". But not "Joined channel".
Removing the "client.JoinChannel" line, will print "Connected", as well as "Joined channel".
Removing the "DamnICantFly" channel parameter in the Initialize method, will again print "Connected", but not "Joined channel".

private void Start()
{
	Client client = new Client();
	client.OnConnected += OnConnected;
	client.OnJoinedChannel += OnJoinedChannel;
	client.Initialize(new TwitchLib.Client.Models.ConnectionCredentials("DamnICantFly", "oauth_token"), "DamnICantFly");
	client.Connect();
	client.JoinChannel("LuckyNoS7evin");
}

private void OnConnected(object sender, TwitchLib.Client.Events.OnConnectedArgs e)
{
	Debug.Log("Connected");
}

private void OnJoinedChannel(object sender, TwitchLib.Client.Events.OnJoinedChannelArgs e)
{
	Debug.Log("Joined channel");
}

Crashes durring bit wars

in my app, i call "client = New TwitchClient()" in its own thread to keep the UI fluid, but i am finding that when bit wars (gifts) go on between viewers, the thread terminates. I am now running source code compiled in debug to see if i can catch the error in the dll. but from the vb.net side i don't see any feedback upon termination.

test case, multiple gifts in a single chat (5+)

Also, i do not see any gift or bit received events, this would be helpful to trigger sounds, text, or other actions based on gifts.

Gracefully handle VIP user detection

Raw IRC message logs indicate that VIP badges are shown in the IRC message, and since they are a slot 1 (exclusive, non-hideable) badge, they should be parsed, and exposed via ChatMessage as a property.

VIPExt is pretty crap, if we're being honest. This is a much simpler way to check a VIP user.

perhaps .IsVIP similar to .IsBroadcaster etc

RAW MESSAGE: @badge-info=;badges=vip/1;color=;display-name=heph2;emotes=;flags=;id=27b2f778-6651-4efd-96ee-22cc23269b54;mod=0;room-id=29181352;subscriber=0;tmi-sent-ts=1573999776196;turbo=0;user-id=64525781;user-type= :[email protected] PRIVMSG #heph :a s d f 1 2 3 4

^ VIP chat message shown above.

PUT payloads don't seem to be compatible with Twitch

When attempting to follow with the notification flag set(not null), twitch throws:

{"error":"Bad Request","status":400,"message":"Request body was not parsable. Attempted Content-Type: \"application/json\""}

When the flag is set, that causes the request to be sent with a payload. The payload doesn't seem compatible with Twitch, and likely affects all PUT requests that have payloads.

ChatMessage.EmoteReplacedMessage should be populated based on ChatMessage.EmoteSet

Twitch chat doesn't blindly replace all occurrences of emote text with a graphic, for example:
LUL "LUL" will result in
image

However, TwitchLib will show that same line as
image

This happens despite the fact that in TwitchLib, the received ChatMessage.EmoteSet only shows a single replacement should happen. The source code shows that the EmoteSet seems to be completely ignored, and instead a regex is used.

Can't send chat messages

Somehow, almost immediately after the OnJoinedChannel event handler executes, my TwitchClient's JoinedChannels queue is emptied. Despite this, the client still receives messages from the channel it had joined, but it is unable to send any messages, regardless of whether the channel to send a message to is manually defined or retrieved via something like JoinedChannels[0].

The OnLeftChannel and OnDisconnected event handlers never fire, and DisableAutoPong is set to false. Any ideas about why messages can't be sent?

Timeout - Couple changes

Use FromSeconds() instead of TotalSeconds.
Possible some vaildations of the contents submitted for Timespan
Parse result to int (twitch requires a whole number)

Mismatched data types on various subscribers event args

OnNewSubscriberArgs & OnReSubscriberArgs badges are List(of KeyPairValue(of string, string) but OnGiftedSubscriptionArgs, OnAnonGiftedSubscriptionArgs, & OnCommunitySubscriptionArgs badges are strings.

OnNewSubscriberArgs & OnReSubscriberArgs colors are Color but OnGiftedSubscriptionArgs, OnAnonGiftedSubscriptionArgs, & OnCommunitySubscriptionArgs colors are strings.

OnNewSubscriberArgs & OnReSubscriberArgs Emotes are called EmoteSet but OnGiftedSubscriptionArgs, OnAnonGiftedSubscriptionArgs, & OnCommunitySubscriptionArgs emotes are called Emotes.

Gracefully handle a user not able to receive a whisper

Irc message for when a user is unable to receive a whisper from the client:

@msg-id=whisper_restricted_recipient;target-user-id=187514468 :tmi.twitch.tv NOTICE #jtv :That user's settings prevent them from receiving this whisper.

Index Out of Bounds - OnBeingHosted

Hi,

Whenever another user hosts my channel, I get the following error:

  Index was outside the bounds of the array.

Here's the stack trace:

   at TwitchLib.Client.Models.BeingHostedNotification..ctor(String botUsername, IrcMessage ircMessage)
   at TwitchLib.Client.TwitchClient.HandlePrivMsg(IrcMessage ircMessage)
   at TwitchLib.Client.TwitchClient.HandleIrcMessage(IrcMessage ircMessage)
   at TwitchLib.Client.TwitchClient._client_OnMessage(Object sender, MessageReceivedEventArgs e)
   at WebSocket4Net.WebSocket.OnDataReceived(Byte[] data, Int32 offset, Int32 length)
   at SuperSocket.ClientEngine.AsyncTcpSession.ProcessReceive(SocketAsyncEventArgs e)
   at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
   at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Unable to catch loss of connection

I am trying to catch when the connection is lost to create an auto-reconnect method, but the OnConnectionError event handler never gets triggered when connection to the internet is lost.

Invalid parsing of the variable TargetMessageId of the event OnMessageClearedArgs

Describe the bug

If you parse an irc message into a string you will get the following result:

@login=<login>;room-id=;target-msg-id=<target-msg-id>;tmi-sent-ts=-6795364578871 :tmi.twitch.tv CLEARMSG #<channel> :<message>

On deleting a message, the event tries to create the variables as follows

private void HandleClearMsg(IrcMessage ircMessage)
{
OnMessageCleared?.Invoke(this, new OnMessageClearedArgs { Channel = ircMessage.Channel, Message = ircMessage.Message, TargetMessageId = ircMessage.ToString().Split('=')[2].Split(' ')[0] });
}

Since the format of the IrcMessage- string does not correspond to that of the official API, you get a wrong TargetMessageId

To Reproduce

  1. Send a message and note the ID of the sent message
  2. Delete the message with the corresponding ID (/delete <target-msg-id>)
  3. You get the string ";target-msg-id" as target message id of the event (as suspected above)

Additional context
The bug was discovered on the develop branch. An effect on the master branch was not tested.

Add ChatMessage Id field

Would it be possible to expose the message Id on ChatMessage?
I am looking to run multiple instances of this library for reliability, so need to accurately identify messages across each instances to ensure they are only handled once. Time and contents isnt accurate enough I have found, so could really do with the id field to be available for this

Example IRC:

@badges=broadcaster/1,premium/1;color=#20569D;display-name=Julusian;emotes=;id=d67c6f6c-a7e1-4ada-b4f1-82b0da0622dc;mod=0;room-id=79110861;subscriber=0;tmi-sent-ts=1526757334890;turbo=0;user-id=79110861;user-type= :[email protected] PRIVMSG #julusian :dd

TwitchLib.Client/TwitchLib.Client/Events/OnRaidNotificationArgs.cs

Public instance variable RaidNotificaiton should probably have a different name, because that is a horrible misspelling. I recognize that it would otherwise match the class name (which could be renamed BeingRaidedNotification, for example), but being misspelled like that makes me sad.

User data context

Can you add a custom context object property? I need to work with some data in the TwitchClient event handlers (there can be a lot of clients with the single event handler in code), which I'll get somehow like this:

var ctx = ((TwitchClient) sender).Context;
// work with context here

Client.OnMessageReceivedArgs not holding any emote data + other problem

From @Kesiek on April 16, 2018 14:31

Hello. As the title says, in 2.1 API version the Client.OnMessageReceivedArgs.EmotesSet is not holding any data, no matter what and how many emotes there is in message, it always returns 0.

And the second problem is that I'm always getting error when I'm trying to update channel title or game with TwitchAPI.Channels.v5.UpdateChannelAsync() method
Crash message:
Something went wrong during the request! Please try again later

Here is link to stack trace to not overspam this post: https://pastebin.com/fh5gBeCw
And the code for method is:

    public async Task<string> ChangeStreamTitleAsync(string message)
    {
        try
        {
            var a = await twitchAPI.Streams.v5.GetStreamByUserAsync(userId);
            if (a.Stream == null)
                return "offline";

            await twitchAPI.Channels.v5.UpdateChannelAsync(userId, message);
            return "updated";
        }
        catch (Exception ex)
        {
            DebugConsole.DisplayInDebugConsole(ex.StackTrace, error: true);
            DebugConsole.DisplayInDebugConsole(ex.Message, error: true);
            return "error";
        }
    }

Copied from original issue: TwitchLib/TwitchLib#392

Streamer stops streaming notification

I'm using TwtichLib to listen to chat after connecting to a channel and this works. But I'd like to get a notification when the streamer stops streaming. I've tried using OnChannelStateChanged, OnHostingStopped and OnHostLeft but none of these fire when the streamer stops streaming.

Am I using the right callbacks and if so what is the correct usage? If not which should I be using?

Client Leaves Channel Randomly

Ran into something strange with latest Dev Branch:

Client disconnects randomly, not a big issue, able to reconnect fine.

FollowerService & PubSub doesnt disconnect at all.

but recently the client just leaves the channel somehow, doesnt trigger any events (OnLeft Channel/OnError/etc.)

if the client leaves the channel somehow it triggers the exception while trying to send a message:

Must be connected to at least one channel.

if i try catch it, to let it rejoin the channel this sorta works, but sometimes it triggers the Exception:

In order to perform this action, the client must be connected to Twitch. To confirm connection, try performing this action in or after the OnConnected event has been fired.

currently going back to stable branch to see if there is the same issue:

Code is just the usual:

 public async Task RunBot()
        {
            try
            {
                ConnectionCredentials credentials = new ConnectionCredentials("****", OAuth);
                client = new TwitchClient();
                client.Initialize(credentials, joinedchannel);
                client.Connect();
                
                client.OnMessageReceived += OnMessageReceived;
                client.OnDisconnected += OnDisconnected;
                client.OnLeftChannel += OnLeftChannel;
                client.OnError += OnError;

                client.OnJoinedChannel += OnJoinenChannel;
                client.OnConnected += OnConnected;

                await Task.Delay(-1);

            }
        }

private void OnJoinenChannel(object sender, OnJoinedChannelArgs e)
        {
            // ApplyLog("Successfull connected to Live Stream: " + e.Channel + ".");
        }

private void OnError(object sender, OnErrorEventArgs e)
        {
                    client.JoinChannel(joinedchannel);
        }

private void OnLeftChannel(object sender, OnLeftChannelArgs e)
        {
                client.JoinChannel(joinedchannel);
        }

private async void OnConnected(object sender, OnConnectedArgs e)
        {
                //client.JoinChannel(joinedchannel, false);
        }

 private async void OnDisconnected(object sender, TwitchLib.Communication.Events.OnDisconnectedEventArgs e)
        {
                if (!client.IsConnected)
                {
                    ApplyLog("Chatbot disconnected,Connection lost! Trying to Reconnect...");
                  
                        while (!client.IsConnected)
                        {
                            client.Connect();
                            await Task.Delay(5000);
                        }
               }
        }

EmoteSet still empty

I tried to get emotes to work (again) but it seems like the ChatClient is not getting any of them (even after latest fixes in #54 )

So what I've tried was to get the number of emotes in a message in normal Chat and Whispers. The result was that whispers EmoteSet is working and normal chat still ends in "0".

Code I've tried:

public void WhisperReceived(object sender, OnWhisperReceivedArgs e)
{
   Console.WriteLine($"EMOTE COUNT (WHISPER): {e.WhisperMessage.EmoteSet.Emotes.Count}");
}
public void ChatMessageReceived(object sender, OnMessageReceivedArgs e)
{
   Console.WriteLine($"EMOTE COUNT (CHAT): {e.ChatMessage.EmoteSet.Emotes.Count}");
}

Using TwitchLib 2.1.5 (latest NuGet)
Using TwitchClient 2.1.4 (latest NuGet)
Using .NET Framework 4.6.2

I did not tried any console application yet but maybe someone can report back if I missed something.

Gracefully handle whisper_restricted

whisper_restricted is a NOTICE type message from Twitch that indicates whisper settings restrict sending of whispers in some way.

Specifically, the IRC message is:

@msg-id=whisper_restricted;target-user-id=56570810 :tmi.twitch.tv NOTICE #jtv :Your settings prevent you from sending this whisper.

Could Not Load File or Assembly

I just installed this package, but every time I run the client, I get this error. I've tried updating my NuGet packages, and have also tried deleting the bin and obj folders; neither solutions work.
It will only run if I comment out everything to do with TwitchLib.Client.

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.Extensions.Logging.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

The code it seems to be failing on is the following:

private TwitchClient client;

public void Connect()
{
        ConnectionCredentials credentials = new ConnectionCredentials("MadGamerBot", Auth);
            
        client = new TwitchClient();
            
        client.Initialize(credentials, "#itsmike");
            
        client.OnJoinedChannel += onJoinedChannel;
        client.OnMessageReceived += onMessageReceived;
        client.OnDisconnected += onDisconnected;
        client.OnConnected += onConnected;
        client.OnConnectionError += onConnectionError;
            
        client.Connect();
}

What's wrong here?

Console colors in a Library?

Seems a bit unnecessary for a library to be worrying about this. Can we remove this? I can do a PR but wanted feedback from others

        public void SendRaw(string message)
        {
            if (!_initialized) HandleNotInitialized();


            var prevColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Log($"Writing: {message}");
            if (ChatThrottler == null || !ChatThrottler.ApplyThrottlingToRawMessages)
                _client.Send(message);
            OnSendReceiveData?.Invoke(this, new OnSendReceiveDataArgs { Direction = Enums.SendReceiveDirection.Sent, Data = message });
            Console.ForegroundColor = prevColor;
        }

JoinChannel gets stuck if joining suspended account

At startup I am connecting to a bunch of channels, and the library gets stuck after trying to join a channel that has been suspended(more precisely renamed). The following is logged for the offending channel with nothing more occuring after that.

Received: @msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #scorpion1813 :This channel has been suspended.
Unaccounted for: @msg-id=msg_channel_suspended :tmi.twitch.tv NOTICE #scorpion1813 :This channel has been suspended.

The issue looks to be occuring because the lib only allows one JOIN to be inflight at a time and is waiting for a success response but an error is received instead

Shouldn't throw exceptions, but give the developer a warning / log.

If you add a OnBeingHosted event on a new channel that isn't the as the TwitchUsername, it shouldn't an throw Exception and break the app, but rather log a warning.

Same applies on getting moderators, but not listening on OnModeratorsReceived.

This might cause the app to break and stop working without getting any notice if TwitchLib runs on a separate thread. Also these are just good to know, not fatal issues.

Hosting started/stopped event stops working after a while

As of a couple of days ago, hosting started/stopped events stopped working after some time (4-7 mins).
At startup of the 'twitchlib.client' and registering events, it shows all the hosts, after those there will no new hosting messages.
There are no exceptions/errors while this happens.

versions:
TwitchLib.Client 3.0.6-CI-20190707-175305
TwitchLib.Api 3.06-CI-20190707-175300

Reconnecting after disconnect

Hey, my bot has been disconnecting quite a bit recently and is firing the OnDisconnected event but I can't work out exactly how to reconnect to it

Tried with Client.Reconnect(); in the OnDisconnected event but didn't seem to reconnect back to the channel and the OnReconnected event doesn't fire

Any ideas please?

Thanks

SubscribedMonthCount incorrect

The SubscribedMonthCount does not contain the correct amount.
For myself it shows 24 instead of 28.

The Reason might be this code:

foreach (var badge in Badges) { switch (badge.Key) { case "bits": CheerBadge = new CheerBadge(int.Parse(badge.Value)); break; case "subscriber": SubscribedMonthCount = int.Parse(badge.Value); break; } }

Looking in the rawIRC-Message shows following:
@badge-info=subscriber/28;badges=broadcaster/1,subscriber/24;color=#1E90FF;display-name=......

I guess you are using the Index (24) out of the badges-part, instead of the badge_info, which states the correct amount of 28. A bit confusing, but I think this would be the solution.

The 24 stands for "Two-Year-Subscriber", but the 28 are the total months.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.