public void TestTwitchChannelInfo() { Twitch api = new Twitch(new TwitchSettings { ChannelName = "smashgrenoble" }); var a = api.GetChannelInfo(); }
public async void Check(object window) { SaveAll(); var _window = window as MainWindow; if (await Twitch.ChechIfStreamExistsAsync(Name, EnviromentVariables.ClientID)) { Closing(this); TwitchResponseEmoticons _emotes = await Twitch.GetEmotesForStreamAsync(Name, EnviromentVariables.ClientID); TwitchResponseBadges _badges = await Twitch.GetBadgesAsync(Name, EnviromentVariables.ClientID); Message.CarryModeratorIconURL = _badges.mod.image; Message.CarrySubscriberIconURL = _badges.subscriber?.image; _window.Hide(); QueueWindow _queueWindow = new QueueWindow(); (_queueWindow.DataContext as QueueViewModel).Emotes = _emotes; (_queueWindow.DataContext as QueueViewModel).Badges = _badges; _queueWindow.Show(); _queueWindow.Closing += (sender, e) => { _window.Show(); _window.Close(); }; } else { MessageBox.Show("Streamer does not exist."); EnableButton = true; } }
public async Task CanAuthenticateUsingFluentAPI() { var handlerMock = new Mock <HttpMessageHandler>(); handlerMock .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{\"access_token\": \"deadbeef\",\"expires_in\": 1000,\"token_type\": \"bearer\"}"), }) .Verifiable(); var authenticated = Twitch.Authenticate() .FromAppCredentials("test", "test") .WithScope(TwitchConstants.TwitchOAuthScopes.ChatRead) .WithHttpMessageHandler(handlerMock.Object) .Build(); var message = new HttpRequestMessage(); await authenticated.AuthenticateMessageAsync(message); Assert.Equal("Bearer", message.Headers.Authorization.Scheme); Assert.Equal("deadbeef", message.Headers.Authorization.Parameter); }
public Messages() { Discord = new Discord(); Twitch = new Twitch(); RCON = new RCON(); AnnounceIntervalInMinutes = 0; }
public static int CreateTwitch(T startValue, T targetValue, Set <T> set, double duration, TwitchCurve.Shape shape, Object param, TwitchCompleteEvent onComplete, TwitchCompleteEvent onTerminate, bool useGameTime) { // Get the next free twitch. // If none exists, create it. Twitch <T> twitch = null; if (freeList.Count > 0) { twitch = freeList[freeList.Count - 1]; freeList.RemoveAt(freeList.Count - 1); } else { twitch = new Twitch <T>(); } twitch.startValue = startValue; twitch.targetValue = targetValue; twitch.set = set; twitch.duration = duration; twitch.shape = shape; twitch.param = param; twitch.Completed = onComplete; twitch.Terminated = onTerminate; twitch.useGameTime = useGameTime; twitch.handle = gTwitchHandle++; twitch.terminate = false; twitch.startTime = useGameTime ? Time.GameTimeTotalSeconds : Time.WallClockTotalSeconds; // Add the twitch to the active list. activeList.Add(twitch); return(twitch.handle); } // end of CreateTwitch()
public Twitch_Property() { this.twitch = new Twitch(); this.panel = new Twitch_Panel(); //twitch_Chat_Message = new Twitch_Chat_Message(this.twitch); //twitch_Play_Ad = new Twitch_Play_Ad(this.twitch); }
protected override void CheckError(Twitch.ErrorCode err) { if (err != Twitch.ErrorCode.TTV_EC_SUCCESS) { Debug.LogError(err.ToString()); } }
private static void EmoticonDownload(out object e) { var edown = new Twitch(); var req = WebRequest.Create(new Uri($@"https://api.twitch.tv/kraken/chat/emoticons")); //req.Timeout = 3000; Task <WebResponse> resp = req.GetResponseAsync(); try { using (Stream s = resp.Result.GetResponseStream()) using (StreamReader sr = new StreamReader(s)) using (JsonReader reader = new JsonTextReader(sr)) { JsonSerializer serializer = new JsonSerializer(); edown = serializer.Deserialize <Twitch>(reader); } } catch (Exception) { EmoticonDownload(out e); } finally { e = edown; } }
public override void OnEnable() { I18n.Instance.ApplyLanguage(new Language()); srcBili = new BiliBili(); srcTwitch = new Twitch(); base.EventBus.BindEvent <InitCommandEvent>(evt => new BaseCommand(evt.Commands)); base.EventBus.BindEvent <InitSourceEvent>(evt => { evt.Sources.AddSource(srcBili); evt.Sources.AddSource(srcTwitch); }); fltFormat = new DefaultFormat(); fltGift = new GiftReceivePeeker(); fltOnline = new OnlineChangePeeker(); fltDeadunlock = new MessageDeadLoopLimiter(); base.EventBus.BindEvent <InitFilterEvent>(evt => evt.Filters.AddFilters(fltFormat, fltGift, fltOnline, fltDeadunlock)); base.EventBus.BindEvent <LoadCompleteEvent>(DefaultPlugin_onLoadComplete); clientOSU = new DirectOSUIRCBot(); base.EventBus.BindEvent <InitClientEvent>(evt => { evt.Clients.AddAllClient(clientOSU); #if (DEBUG) evt.Clients.AddClient(new ConsoleReciveSendOnlyClient()); #endif }); IO.CurrentIO.WriteColor("Default Plugin by Deliay", ConsoleColor.DarkCyan); }
private static void OnGameLoad() { try { player = ObjectManager.Player; switch (player.CharacterName) { case "Twitch": Twitch.Load(); break; case "Leona": Leona.Load(); break; case "Pyke": Pyke.Load(); break; } } catch (Exception e) { Console.WriteLine("Failed To load: " + e); } }
void HandleTimerCallback(object state) { var preferences = PreferenceManager.GetDefaultSharedPreferences(this); var streamerNames = preferences.GetString("streamer_names", "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var streamersOnline = Twitch.StreamersOnline(streamerNames, configuration); foreach (var entry in streamersOnline) { if (!entry.Value) { continue; } Bundle valuesForActivity = new Bundle(); Intent resultIntent = new Intent(this, typeof(MainActivity)); resultIntent.PutExtras(valuesForActivity); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .SetAutoCancel(true) .SetContentIntent(resultPendingIntent) .SetContentTitle("Streamer online") .SetSmallIcon(Resource.Drawable.Icon) .SetContentText(entry.Key + " is streaming now"); NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService); notificationManager.Notify(ButtonClickNotificationId, builder.Build()); } }
public void TestTwitchUpdateChannelInfo() { Twitch api = new Twitch(new TwitchSettings { ChannelName = "smashgrenoble", OAuthToken = "008iczk72jrmqyt1piaw5591u5scj6" }); api.UpdateChannelInfo("GRE #3 - Tests ... (" + new Random().Next() + ")"); }
public Settings() { Twitch = new Twitch(); Discord = new Discord(); Conan = new Conan(); Update = new Update(); General = new General(); }
protected void HandleAuthTokenRequestComplete(Twitch.ErrorCode result, Twitch.AuthToken authToken) { if (Twitch.Error.Failed(result)) { MessageBox.Show("Auth token request failed, please check your credentials and CA cert file path and try again."); mBroadcastController.ShutdownTwitch(); } }
public TwitchAuthorizationWindow() { InitializeComponent(); browser.FrameLoadEnd += HideProgress; browser.FrameLoadStart += ShowProgress; browser.LoadError += Rofl; browser.Address = Twitch.GetAuthentificationUrl(); }
public MainWindow() { Twitch.InitializeConnections(); InitializeComponent(); statusUpdateTimer = new DispatcherTimer(DispatcherPriority.Send); statusUpdateTimer.Tick += new EventHandler(StatusUpdateHandler); statusUpdateTimer.Interval = TimeSpan.FromMilliseconds(100); HookupTwitchEvents(); }
/// <summary> /// Forces all active twitches to terminated and proceed /// immediately to final value. /// </summary> public static void KillAllTwitches() { for (int i = 0; i < activeList.Count; i++) { Twitch <T> twitch = activeList[i]; twitch.terminate = true; } UpdateActiveList(); }
protected void HandleAuthTokenRequestComplete(Twitch.ErrorCode result, Twitch.AuthToken authToken) { if (Twitch.Error.Failed(result)) { mTwitchUsername = null; mTwitchPassword = null; MessageBox.Show("Login failed, please check your credentials and try again."); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { if (Properties.Settings.Default.twitch_autoconnect) { Twitch.BotConnect(); } LoadConfig(); AddItems(soundObjects); soundObjects.CollectionChanged += SoundObjects_CollectionChanged; }
private void btn_TwitchConnect(object sender, RoutedEventArgs e) { if (Twitch.IsConnected()) { Twitch._client.Disconnect(); } else { Twitch.BotConnect(); } }
protected void HandleIngestListReceived(Twitch.Broadcast.IngestList list) { mIngestListListbox.Items.Clear(); for (int i = 0; i < list.Servers.Length; ++i) { IngestListEntry item = new IngestListEntry(list.Servers[i]); item.Default = item.Server == list.DefaultServer; item.Selected = item.Server == mBroadcastController.IngestServer; mIngestListListbox.Items.Add(item); } }
public Commands(LiteDatabase db, DiscordSocketClient client) { this.client = client; database = db; twitch = new Twitch(); if (UpdateTask == null) { // Run the update and query threads UpdateTask = Task.Factory.StartNew(UpdateAndCheckStreamers); } }
// // TwitchManager class // // c'tor public TwitchManager() { Twitch <float> .Init(); Twitch <Vector2> .Init(); Twitch <Vector3> .Init(); Twitch <Vector4> .Init(); Twitch <Matrix> .Init(); } // end of TwitchManager c'tor
} // end of CreateTwitch() /// <summary> /// Kill the twitch with this handle id /// </summary> /// <param name="handle"></param> public static void KillTwitch(int handle) { for (int i = 0; i < activeList.Count; i++) { Twitch <T> twitch = activeList[i]; if (twitch != null && twitch.handle == handle) { twitch.terminate = true; break; } } }
private void ObsWebsocket_SceneChanged(OBSWebsocket sender, string newSceneName) { activeSceneName = newSceneName; if (newSceneName == "EventReset") { Debugger.Break(); UnHookTwitchEvents(); Twitch.InitializeConnections(); HookupTwitchEvents(); } Console.WriteLine($"Active Scene: {activeSceneName}"); }
} // end of TwitchManager c'tor public void Update() { Twitch <float> .UpdateActiveList(); Twitch <Vector2> .UpdateActiveList(); Twitch <Vector3> .UpdateActiveList(); Twitch <Vector4> .UpdateActiveList(); Twitch <Matrix> .UpdateActiveList(); } // end of TwitchManager Update()
} // end of TwitchManager Update() /// <summary> /// Force all active twitches to immediately terminate. /// </summary> static public void KillAllTwitches() { Twitch <float> .KillAllTwitches(); Twitch <Vector2> .KillAllTwitches(); Twitch <Vector3> .KillAllTwitches(); Twitch <Vector4> .KillAllTwitches(); Twitch <Matrix> .KillAllTwitches(); }
async Task IChannelGrain.Activate(string userToken) { var userAuthenticated = Twitch.Authenticate() .FromOAuthToken(userToken) .Build(); var userClient = TwitchAPIClient.CreateFromBase(_appClient, userAuthenticated); var validated = await userClient.ValidateToken(); if (validated == null || validated.UserId != _channelId || validated.ExpiresIn == 0) { throw new ArgumentException("Could not validate token"); } _userClient = userClient; var channelInfoTask = _userClient.GetChannelInfoAsync(_channelId); List <HelixChannelModerator> moderators = new List <HelixChannelModerator>(); var editorsTask = _userClient.GetHelixChannelEditorsAsync(_channelId); await foreach (var moderator in _userClient.EnumerateChannelModeratorsAsync(_channelId)) { moderators.Add(moderator); } _channelState.State.BroadcasterToken = userToken; _channelState.State.Editors = (await editorsTask).ToList(); _channelState.State.Moderators = moderators.ToList(); await _channelState.WriteStateAsync(); var editorsTasks = _channelState.State.Editors.Select(editor => GrainFactory.GetGrain <IUserGrain>(editor.UserId).SetRole(new UserRole { Role = ChannelRole.Editor, ChannelId = _channelId, ChannelName = _channelInfo.BroadcasterName, }) ); var modsTasks = _channelState.State.Moderators.Select(moderator => GrainFactory.GetGrain <IUserGrain>(moderator.UserId).SetRole(new UserRole { Role = ChannelRole.Moderator, ChannelId = _channelId, ChannelName = _channelInfo.BroadcasterName, }) ); await Task.WhenAll(editorsTasks); await Task.WhenAll(modsTasks); _channelInfo = await channelInfoTask; await RegisterEventSubSubscriptions(CancellationToken.None); }
private void MenuItem_MouseEnter(object sender, MouseEventArgs e) { if (!Twitch.IsConnected()) { btn_twitchConnect.IsEnabled = true; btn_twitchDisconnect.IsEnabled = false; } else { btn_twitchConnect.IsEnabled = false; btn_twitchDisconnect.IsEnabled = true; } }
void Awake() { if (LivecodingOnStart) { Livecoding = gameObject.AddComponent<Livecoding>(); Livecoding.enabled = LivecodingOnStart; } if (TwitchOnStart) { Twitch = gameObject.AddComponent<Twitch>(); Twitch.enabled = TwitchOnStart; } }
//private System.Threading.Tasks.Task HubConnection_Closed(Exception arg) //{ // //} public void Disconnect() { Chat(GetExitMessage()); Twitch.Disconnect(); if (checkChatRoomTimer != null) { checkChatRoomTimer.Dispose(); } if (autoSaveTimer != null) { autoSaveTimer.Dispose(); } allViewers.Save(); obsWebsocket.Disconnect(); }
static async Task Main(string[] args) { IConfiguration configuration = null; var builder = new HostBuilder() .ConfigureLogging(configure => { configure.AddConsole(); configure.SetMinimumLevel(LogLevel.Information); }) .ConfigureAppConfiguration(configure => { configure.AddUserSecrets <Program>(); configure.AddEnvironmentVariables(); configuration = configure.Build(); }) .ConfigureServices((hostContext, services) => { // Configure services services.AddHttpClient(); services.Configure <TwitchApplicationOptions>(configuration.GetSection("twitch")); services.Configure <AzureGameLocalizationStoreOptions>(configuration.GetSection("loc:azure")); services.AddTransient <TwitchAPIClient>(); services.AddTransient <IGDBClient>(); services.AddSingleton <IMemoryCache, MemoryCache>(); services.AddSingleton <SteamStoreClient>(); services.AddSingleton <IAuthenticated>(s => Twitch.Authenticate() .FromAppCredentials( s.GetService <IOptions <TwitchApplicationOptions> >().Value.ClientId, s.GetService <IOptions <TwitchApplicationOptions> >().Value.ClientSecret) .Build() ); services.AddTransient <IGameLocalizationStore>(services => { var options = services.GetRequiredService <IOptions <AzureGameLocalizationStoreOptions> >(); if (string.IsNullOrEmpty(options.Value.StorageConnectionString) || string.IsNullOrEmpty(options.Value.TableName)) { return(null); } return(services.GetRequiredService <AzureStorageGameLocalizationStore>()); }); services.AddSingleton <AzureStorageGameLocalizationStore>(); }) .UseConsoleLifetime(); await builder.RunCommandLineApplicationAsync <Tool>(args); }
public QueueViewModel() { Messages = new List <Message>(); PageIndexCommand = new Command(ChangePageIndex, ChangePagePredicate); _mySettings = MySettings.Load(); _channel = _mySettings.Name; _emote = _mySettings.Emote; _hideCounter = _mySettings.HideCounter; _sameEmoteCount = _mySettings.SameEmoteCount; Message.CarryHideCounter = !_hideCounter; _twitch = new Twitch(EnviromentVariables.BotName, EnviromentVariables.BotToken, _channel); _twitch.OnMessage = OnMessage; PageIndex = 1; }
public virtual void Execute(IHubContext <CodeRushedHub, IOverlayCommands> hub, ChatMessage chatMessage, string cmdText, string args, int showsWatched) { if (commandBecomesArgs) { args = cmdText; } string targetCommand = Translate(cmdText); if (targetCommand != null) { hub.Clients.All.ExecuteCommand(targetCommand, args, UserInfo.FromChatMessage(chatMessage, showsWatched)); } if (chatBackMessage != null) { Twitch.Chat(chatBackMessage); } }
public virtual void Execute(IHubContext <CodeRushedHub, IOverlayCommands> hub, ChatMessage chatMessage, string cmdText, string args) { if (commandBecomesArgs) { args = cmdText; } string targetCommand = Translate(cmdText); if (targetCommand != null) { hub.Clients.All.ExecuteCommand(targetCommand, args, chatMessage.UserId, chatMessage.Username, chatMessage.DisplayName, chatMessage.ColorHex); } if (chatBackMessage != null) { Twitch.Chat(chatBackMessage); } }
protected void HandleBroadcastStateChanged(Twitch.Broadcast.BroadcastController.BroadcastState state) { String stateString = state.ToString(); if (state == Twitch.Broadcast.BroadcastController.BroadcastState.ReadyToBroadcast) { // If reached the ReadyToBroadcast state from "Start Ingest Test" button press if (mBeginIngestTest) { mBeginIngestTest = false; if (BeginIngestTest()) { stateString = "Ingest Testing"; } else { MessageBox.Show("Failed to start ingest tester, please try again"); stateString = "Error"; } } } mStatusLabel.Text = "Status - " + stateString; }
protected void HandleStreamInfoUpdated(Twitch.Broadcast.StreamInfo info) { // TODO: got the stream info, do something with it }
protected void HandleRawMessagesReceived(Twitch.Chat.ChatMessage[] messages) { for (int i = 0; i < messages.Length; ++i) { string line = messages[i].UserName + ": " + messages[i].Message + "\r\n"; mChatMessagesTextbox.Text = mChatMessagesTextbox.Text + line; } }
protected void HandleGameNameListReceived(ErrorCode result, Twitch.Broadcast.GameInfo[] list) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Length; ++i) { if (i > 0) { sb.Append(", "); } sb.Append(list[i].Name); } MessageBox.Show(sb.ToString()); }
protected void HandleBroadcastStateChanged(Twitch.Broadcast.BroadcastController.BroadcastState state) { this.Text = "Twitch Winforms Sample - " + state.ToString(); mSimpleBroadcastGroupbox.Enabled = state == Twitch.Broadcast.BroadcastController.BroadcastState.ReadyToBroadcast; mAdvancedBroadcastGroupbox.Enabled = state == Twitch.Broadcast.BroadcastController.BroadcastState.ReadyToBroadcast; mBroadcastControlsGroupbox.Enabled = state == Twitch.Broadcast.BroadcastController.BroadcastState.Broadcasting || state == Twitch.Broadcast.BroadcastController.BroadcastState.Paused; mIngestTestingGroupbox.Enabled = state == Twitch.Broadcast.BroadcastController.BroadcastState.ReadyToBroadcast || state == Twitch.Broadcast.BroadcastController.BroadcastState.IngestTesting; mAudioGroupbox.Enabled = state == Twitch.Broadcast.BroadcastController.BroadcastState.ReadyToBroadcast || state == Twitch.Broadcast.BroadcastController.BroadcastState.Paused; mGameNameListGroupbox.Enabled = state != Twitch.Broadcast.BroadcastController.BroadcastState.Uninitialized; mLoginGroupbox.Enabled = mBroadcastController.IsInitialized && !mBroadcastController.IsLoggedIn; mBroadcastInfoGroupbox.Enabled = mBroadcastController.IsLoggedIn; mChatConnectionGroupbox.Enabled = mBroadcastController.IsInitialized && mBroadcastController.IsLoggedIn; }
public Configuration() { Twitch = new Twitch(this); }
protected override bool CheckError(Twitch.ErrorCode err) { if (Error.Failed(err)) { System.Windows.Forms.MessageBox.Show(err.ToString()); return false; } return true; }
void mIngestTester_OnTestStateChanged(Twitch.Broadcast.IngestTester source, Twitch.Broadcast.IngestTester.TestState state) { mIngestTestStatusText.Text = "[" + (int)(mIngestTester.TotalProgress * 100) + "%] " + state.ToString(); switch (state) { case Twitch.Broadcast.IngestTester.TestState.ConnectingToServer: { mIngestTestStatusText.Text += ": " + source.CurrentServer.ServerName + "..."; break; } case Twitch.Broadcast.IngestTester.TestState.TestingServer: case Twitch.Broadcast.IngestTester.TestState.DoneTestingServer: { mIngestTestStatusText.Text += ": " + source.CurrentServer.ServerName + "... " + source.CurrentServer.BitrateKbps + " kbps"; break; } case Twitch.Broadcast.IngestTester.TestState.Finished: case Twitch.Broadcast.IngestTester.TestState.Cancelled: { mIngestTester.OnTestStateChanged -= mIngestTester_OnTestStateChanged; mIngestTester = null; break; } default: { break; } } RefreshListbox(mIngestListListbox); }
private static void Main(string[] args) { if (args.Length >= 1) ProcessArgs(args); else return; var initTwitch = new Twitch(_twitchChannel); var twitchController = new TwitchController(); Console.WriteLine("Version: {0}", initTwitch.Configuration.Version); Console.WriteLine("Channel: {0}", initTwitch.Configuration.Channel); // parse that data twitchController.ApiRequest<Chat>($"group/user/{initTwitch.Configuration.Channel}/chatters", TwitchController.RequestType.Tmi); twitchController.ApiRequest<Channel>($"channels/{initTwitch.Configuration.Channel}", TwitchController.RequestType.Kraken); twitchController.ApiRequest<ChatBadges>($"chat/{initTwitch.Configuration.Channel}/badges", TwitchController.RequestType.Kraken); twitchController.ApiRequest<ChatEmoticons>("chat/emoticon_images", TwitchController.RequestType.Kraken); twitchController.ApiRequest<GamesTop>("games/top", TwitchController.RequestType.Kraken); twitchController.ApiRequest<StreamLive>($"streams/{initTwitch.Configuration.Channel}", TwitchController.RequestType.Kraken); twitchController.ApiRequest<IngestServer>("ingests", TwitchController.RequestType.Kraken); twitchController.ApiRequest<User>($"users/{initTwitch.Configuration.Channel}", TwitchController.RequestType.Kraken); twitchController.ApiRequest<UserVideos>($"channels/{initTwitch.Configuration.Channel}/videos?broadcasts=true", TwitchController.RequestType.Kraken); initTwitch = twitchController.Twitch; Console.WriteLine("-----------------------------------------"); // test parsed data (make sure it's not returning null) Console.WriteLine("Chatter Count: {0}", initTwitch.Chat.ChatterCount); Console.WriteLine("Channel Display Name: {0}", initTwitch.Channel.DisplayName); Console.WriteLine("Test Mod Image: {0}", initTwitch.ChatBadges.Mod.Image); Console.WriteLine("Emote: {0}", initTwitch.ChatEmoticons.Emoticons[0].Code); var iGames = initTwitch.GamesTop.Top.Count; Console.Write("Top ({0}) Games: ", iGames); foreach (var game in initTwitch.GamesTop.Top) { if (iGames != 1) Console.Write("{0}, ", game.Game.Name); else Console.WriteLine(game.Game.Name); iGames--; } if (initTwitch.StreamLive.Stream != null) Console.WriteLine("Viewers: {0}", initTwitch.StreamLive.Stream.Viewers); var iIngests = initTwitch.IngestServer.Ingests.Count; Console.Write("Top ({0}) Ingests: ", iIngests); foreach (var server in initTwitch.IngestServer.Ingests) { if (iIngests != 1) Console.Write("\"{0}\", ", server.Name); else Console.WriteLine(server.Name); iIngests--; } Console.WriteLine("Bio: {0}", initTwitch.User.Bio); Console.WriteLine("User Video: {0}", initTwitch.UserVideos.Total); Console.ReadKey(); }
protected void HandleGameNameListReceived(Twitch.ErrorCode result, GameInfo[] list) { // TODO: handle the list of games }
void mIngestTester_OnTestStateChanged(Twitch.Broadcast.IngestTester source, Twitch.Broadcast.IngestTester.TestState state) { mIngestTestStatusText.Text = "[" + (int)(mIngestTester.TotalProgress * 100) + "%] " + state.ToString(); switch (state) { case Twitch.Broadcast.IngestTester.TestState.ConnectingToServer: { mIngestTestStatusText.Text += ": " + source.CurrentServer.ServerName + "..."; break; } case Twitch.Broadcast.IngestTester.TestState.TestingServer: case Twitch.Broadcast.IngestTester.TestState.DoneTestingServer: { mIngestTestStatusText.Text += ": " + source.CurrentServer.ServerName + "... " + source.CurrentServer.BitrateKbps + " kbps"; break; } case Twitch.Broadcast.IngestTester.TestState.Finished: { String bestServerName = ""; float bestBitrate = 0; Twitch.Broadcast.IngestServer curServer = null; for (int i = 0; i < mIngestListListbox.Items.Count; i++) { curServer = ((IngestListEntry) mIngestListListbox.Items[i]).Server; if (curServer.BitrateKbps > bestBitrate) { bestBitrate = curServer.BitrateKbps; bestServerName = curServer.ServerName; } } mBestServerLabel.Text = "Best server - " + bestServerName; mSkipIngestServerButton.Enabled = false; mCancelIngestTestButton.Enabled = false; mIngestTester.OnTestStateChanged -= mIngestTester_OnTestStateChanged; mIngestTester = null; break; } case Twitch.Broadcast.IngestTester.TestState.Cancelled: { mSkipIngestServerButton.Enabled = false; mCancelIngestTestButton.Enabled = false; mIngestTester.OnTestStateChanged -= mIngestTester_OnTestStateChanged; mIngestTester = null; break; } default: { break; } } RefreshListbox(mIngestListListbox); }
private static async Task UpdateFollowedUsers(Twitch.Root user) { if (followedUsers.Count == 0) return; bool followedUsersChanged = false; if (user == null) return; // Check if we've followed another streamer and if so add them to our followed collection foreach (var u in user.follows) { if (followedUsers.Any(i => i.Name == u.channel.display_name) == false) { followedUsersChanged = true; var newUser = await CreateUserFromTwitchFollow(u); followedUsers.Add(newUser); OnFollowed(newUser); } } var toRemove = new List<User>(); // Check for unfollows here foreach (var u in followedUsers) { if (user.follows.Any(i => i.channel.display_name == u.Name) == false) { toRemove.Add(u); followedUsersChanged = true; } } // Remove unfollows if any foreach (var rem in toRemove) { followedUsers.Remove(rem); OnUnfollowed(rem); } if(followedUsersChanged) OnFollowedUsersChanged(); }
private static async Task<User> CreateUserFromTwitchFollow(Twitch.Follow follow) { IsUserLiveData isUserLiveData = await IsUserLiveAsync(follow.channel.display_name); bool isUserLive = isUserLiveData.IsLive; // Remove the date and the trailing Z from the createdAt string if (isUserLiveData.CreatedAt != "") { //var arr = isUserLiveData.CreatedAt.Split('T'); //isUserLiveData.CreatedAt = arr[1].Remove(arr[1].Length - 1); isUserLiveData.CreatedAt = (DateTime.Parse(isUserLiveData.CreatedAt, new CultureInfo("en-GB", true), DateTimeStyles.AssumeUniversal)).ToLongTimeString(); } BitmapImage bm = null; // If user does not have a logo then use the Twitch default if (follow.channel.logo == null) { bm = new BitmapImage(new Uri(@"/TwitchAlert;component/Images/404_user_150x150.png", UriKind.Relative)); } else { // If the Thumbnail (logo) Image has already been cached to file then get it from there. // Else download it. var cachedFilename = ImageSaver.GetCachedImageFilename(follow.channel.logo); bm = (!string.IsNullOrEmpty(cachedFilename) && File.Exists(cachedFilename)) ? new BitmapImage(new Uri(cachedFilename)) : DownloadImage(follow.channel.logo); } return new User { Name = follow.channel.display_name, IsStreaming = isUserLive, NumViewers = isUserLiveData.NumViewers, Game = follow.channel.game, StreamCreatedAt = isUserLiveData.CreatedAt, ThumbnailPath = follow.channel.logo, Thumbnail = bm, Link = follow.channel.url, Status = follow.channel.status }; }
/// <summary> /// Returns all of the people in the 'users' collection who are currently streaming /// </summary> /// <param name="users"></param> /// <returns>Task<TwitchStreamers.RootObject></returns> private static async Task<TwitchStreamers.RootObject> GetStreamers(Twitch.Root users) { string url = "https://api.twitch.tv/kraken/streams?channel="; string userNames = users.follows.Aggregate("", (current, u) => current + u.channel.display_name + ","); url += userNames.Remove(userNames.Length - 1); return JsonConvert.DeserializeObject<TwitchStreamers.RootObject>(await GetAsync(url)); }
protected void HandleTokenizedMessagesReceived(Twitch.Chat.ChatTokenizedMessage[] messages) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.Length; ++i) { Twitch.Chat.ChatTokenizedMessage msg = messages[i]; sb.Append(msg.DisplayName).Append(": "); for (int t = 0; t < msg.Tokens.Length; ++t) { Twitch.Chat.ChatMessageToken token = msg.Tokens[t]; switch (token.Type) { case Twitch.Chat.TTV_ChatMessageTokenType.TTV_CHAT_MSGTOKEN_TEXT: { Twitch.Chat.ChatTextMessageToken mt = token as Twitch.Chat.ChatTextMessageToken; sb.Append(mt.Message); break; } case Twitch.Chat.TTV_ChatMessageTokenType.TTV_CHAT_MSGTOKEN_IMAGE: { Twitch.Chat.ChatImageMessageToken mt = token as Twitch.Chat.ChatImageMessageToken; sb.Append("[emoticon]"); break; } } } sb.AppendLine(); mChatMessagesTextbox.Text = mChatMessagesTextbox.Text + sb.ToString(); sb.Clear(); } }
protected void HandleUsersChanged(Twitch.Chat.ChatUserInfo[] joins, Twitch.Chat.ChatUserInfo[] leaves, Twitch.Chat.ChatUserInfo[] infoChanges) { for (int i = 0; i < leaves.Length; ++i) { mChatUsersListbox.Items.Remove(leaves[i]); } for (int i = 0; i < infoChanges.Length; ++i) { mChatUsersListbox.Items.Remove(infoChanges[i]); mChatUsersListbox.Items.Add(infoChanges[i]); } for (int i = 0; i < joins.Length; ++i) { mChatUsersListbox.Items.Add(joins[i]); } }
protected override bool CheckError(Twitch.ErrorCode err) { if (Error.Failed(err)) { Debug.LogError(err.ToString()); return false; } return true; }
public IngestListEntry(Twitch.Broadcast.IngestServer server) { mServer = server; }
protected void HandleLoginAttemptComplete(Twitch.ErrorCode result) { if (Twitch.Error.Succeeded(result)) { DebugOverlay.Instance.AddViewportText("Logged in, ready to stream", 2); } else { PlayerPrefs.DeleteKey(s_TwitchAuthTokenKey); PlayerPrefs.Save(); DebugOverlay.Instance.AddViewportText("AuthToken invalid, please enter your username and password again", 2); } }
void Start() { Instance = this; if (ConnectOnStart) Connect(); }
protected void HandleAuthTokenRequestComplete(Twitch.ErrorCode result, AuthToken authToken) { if (Twitch.Error.Succeeded(result)) { PlayerPrefs.SetString(s_TwitchAuthTokenKey, authToken.Data); PlayerPrefs.SetString(s_TwitchUserNameKey, m_BroadcastController.UserName); DebugOverlay.Instance.AddViewportText("User authenticated", 2); } else { PlayerPrefs.DeleteKey(s_TwitchAuthTokenKey); PlayerPrefs.DeleteKey(s_TwitchUserNameKey); DebugOverlay.Instance.AddViewportText("Failed to authenticate", 2); } PlayerPrefs.Save(); }
void m_TwitchClient_OnPart(TwitchClient sender, Twitch.Models.TwitchClientOnPartEventArgs args) { }
protected void HandleChatStateChanged(Twitch.Chat.WinFormsChatController.ChatState state) { mChatStateLabel.Text = state.ToString(); switch (state) { case Twitch.Chat.ChatController.ChatState.Uninitialized: break; case Twitch.Chat.ChatController.ChatState.Initializing: break; case Twitch.Chat.ChatController.ChatState.Initialized: break; case Twitch.Chat.ChatController.ChatState.ShuttingDown: break; } }
protected virtual bool CheckError(Twitch.ErrorCode err) { if (Error.Failed(err)) { return false; } return true; }
protected void HandleTokenizedMessagesReceived(string channelName, Twitch.Chat.ChatTokenizedMessage[] messages) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.Length; ++i) { Twitch.Chat.ChatTokenizedMessage msg = messages[i]; sb.Append(msg.DisplayName).Append(": "); for (int t = 0; t < msg.Tokens.Length; ++t) { Twitch.Chat.ChatMessageToken token = msg.Tokens[t]; switch (token.Type) { case Twitch.Chat.TTV_ChatMessageTokenType.TTV_CHAT_MSGTOKEN_TEXT: { Twitch.Chat.ChatTextMessageToken mt = token as Twitch.Chat.ChatTextMessageToken; sb.Append(mt.Message); break; } case Twitch.Chat.TTV_ChatMessageTokenType.TTV_CHAT_MSGTOKEN_TEXTURE_IMAGE: { Twitch.Chat.ChatTextureImageMessageToken mt = token as Twitch.Chat.ChatTextureImageMessageToken; sb.Append(string.Format("[{0},{1},{2},{3},{4}]", mt.SheetIndex, mt.X1, mt.Y1, mt.X2, mt.Y2)); break; } case Twitch.Chat.TTV_ChatMessageTokenType.TTV_CHAT_MSGTOKEN_URL_IMAGE: { Twitch.Chat.ChatUrlImageMessageToken mt = token as Twitch.Chat.ChatUrlImageMessageToken; sb.Append("[").Append(mt.Url).Append("]"); break; } } } sb.AppendLine(); mChatMessagesTextbox.Text = mChatMessagesTextbox.Text + sb.ToString(); sb.Clear(); } }