List<IPlugin> plugins = new List<IPlugin>(); // List of loaded plugins #endregion Fields #region Constructors public ChatProcessor(Bot b, TwitchAPI ta) { bot = b; api = ta; string pluginFolderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Plugins"; // Get the Plugins folder if (!Directory.Exists(pluginFolderPath)) Directory.CreateDirectory(pluginFolderPath); // If the Plugins folder dont exists, create it string[] dllFileNames = Directory.GetFiles(pluginFolderPath, "*.dll", SearchOption.AllDirectories); // Get all the dll files inside the Plugins folder next to the executable List<Assembly> assemblies = new List<Assembly>(); // List of assemblies of these dlls foreach (string dllFileName in dllFileNames) // Foreach dll found { AssemblyName an = AssemblyName.GetAssemblyName(dllFileName); // Get his assemlby name Assembly a = Assembly.Load(an); // Load this assembly assemblies.Add(a); // Add it to the list } Type pluginType = typeof(IPlugin); // Get the type of the Plugin Interface List<Type> pluginTypes = new List<Type>(); // List of the types of the plugins foreach (Assembly assembly in assemblies) // Foreach assembly we found { if (assembly == null) continue; // If the assembly is null, skip Type[] assemblyTypes = assembly.GetTypes(); // Get all the types in this Assembly foreach (Type type in assemblyTypes) // Foreach type we found { if (type.IsInterface || type.IsAbstract) continue; // If the type is an interface or is abtract, skip it if (type.GetInterface(pluginType.FullName) != null) pluginTypes.Add(type); // If the type implements the Plugin Interface, store it } } foreach (Type type in pluginTypes) // Foreach plugin { IPlugin plugin = (IPlugin)Activator.CreateInstance(type); // Inititialize it plugin.Initialize(new IPluginContext { Bot = bot, TwitchAPI = api }); plugins.Add(plugin); // Add it to the list of Plugins } bot.OnMessageReceived += bot_OnMessageReceived; // Bind event }
public void CheckAction(Account user, DateTime lastCheck) { Console.WriteLine("Checking NewSubTwitchAction"); TwitchAPI api = _twitchService.GetApi(user); var currentUser = api.Helix.Users.GetUsersAsync().Result; if (currentUser.Users.Length <= 0) { Console.WriteLine("Current user id not found"); return; } GetUsersFollowsResponse userFollows = api.Helix.Users.GetUsersFollowsAsync("", "", 20, "", currentUser.Users[0].Id).Result; List <string> followerIds = new List <string>(); if (userFollows.Follows.Length <= 0) { Console.WriteLine("No followers for user " + currentUser.Users[0].DisplayName); } for (int i = 0; i < userFollows.Follows.Length; i++) { Console.WriteLine("Follower : " + userFollows.Follows[i].ToUserId); if (userFollows.Follows[i].FollowedAt > lastCheck) { if (_lastTriggerDate == null) { _lastTriggerDate = userFollows.Follows[i].FollowedAt; } else if (_lastTriggerDate < userFollows.Follows[i].FollowedAt) { _lastTriggerDate = userFollows.Follows[i].FollowedAt; } Console.WriteLine("New !"); followerIds.Add(userFollows.Follows[i].FromUserId); } else { Console.WriteLine("Not new"); } } if (followerIds.Count > 0) { _newFollowers = api.Helix.Users.GetUsersAsync(followerIds).Result.Users.ToList(); } }
public TwitchApi(IConfiguration config) { _api = new TwitchAPI(); _api.Settings.ClientId = config["Bot:ClientId"]; _api.Settings.AccessToken = config["Bot:AccessToken"]; var targetChannelNames = config["Bot:ChannelNames"]; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json")); httpClient.DefaultRequestHeaders.Add("Client-ID", config["Bot:ClientId"]); var res = httpClient.GetAsync($"https://api.twitch.tv/kraken/users?login={targetChannelNames}").Result; var json = res.Content.ReadAsStringAsync().Result; var userSearchResult = JsonSerializer.Deserialize <TwitchUserSearchDto>(json); _targetChannels = userSearchResult.Users.Select(x => x.Id.ToString()).ToList(); }
public async void MonitorAsync() { API = new TwitchAPI(); API.Settings.ClientId = "0xw8roszr2iuy665w9xn78g38yjuuy"; API.Settings.AccessToken = "oauth:qdftj9ur5lrsbm42zsjl07aeoo1plx"; LiveStreams streams = new LiveStreams(); var kanaly = await API.V5.Streams.GetLiveStreamsAsync(null, null, null, null, 10, null); int licznik = 0; string[] dobota = new string[10]; foreach (var kanal in kanaly.Streams) { Console.WriteLine("TOP#" + licznik + 1); Console.WriteLine(""); Console.WriteLine("Nazwa: " + kanal.Channel.DisplayName + " " + "Widzowie: " + kanal.Viewers); Console.WriteLine("GRA: " + kanal.Channel.Game); Console.WriteLine("Tytul: " + kanal.Channel.Status); dobota[licznik] = kanal.Channel.DisplayName; licznik++; } foreach (string d in dobota) { Console.WriteLine(d); if (!String.IsNullOrEmpty(d)) { TwitchBOT bOT = new TwitchBOT(); bOT.Bot(d); } else { } } }
private void btnFetchID_Click(object sender, RoutedEventArgs e) { if ((string)btnFetchID.Content == "OK") { DialogResult = true; } else { tbChannelID.Text = "(ID will be populated here)"; btnFetchID.IsEnabled = false; btnFetchID.Content = "Wait..."; _api = new TwitchAPI(); _api.Settings.AccessToken = tbAccessToken.Text; _api.Settings.ClientId = tbClientID.Text; _getChannelID(this._username); } }
// Start the Twitch API service to monitor Livestreams private void StartApi() { TwitchAPI twitchAPI = new TwitchAPI(); twitchAPI.Settings.ClientId = CredentialsKeeper.TwitchId; twitchAPI.Settings.AccessToken = CredentialsKeeper.TwitchSecret; LiveStreamMonitorService monitor = new LiveStreamMonitorService(twitchAPI, 60); Console.WriteLine("Starting Twitch API services"); monitor.SetChannelsByName(UserProvider.GetTwitchUsers()); monitor.OnStreamOnline += _eventHandler.OnStreamOnline; monitor.OnStreamOffline += _eventHandler.OnStreamOffline; monitor.OnServiceStarted += _eventHandler.OnServiceStarted; monitor.Start(); Console.WriteLine("Twitch API services started"); }
public Bot(ILogger logger, IEmoteCache emoteCache, IBadgeCache badgeCache, IMessageFormatManager messageFormatManager, ICredentialsManagement credentialsManagement) { this.logger = logger; this.emoteCache = emoteCache; this.badgeCache = badgeCache; this.messageFormatManager = messageFormatManager; messageConverter = new MessageConverter(this.emoteCache, this.badgeCache); badgeConverter = new BadgeConverter(this.badgeCache); var clientOptions = new ClientOptions { MessagesAllowedInPeriod = 750, ThrottlingPeriod = TimeSpan.FromSeconds(30) }; WebSocketClient customClient = new WebSocketClient(clientOptions); client = new TwitchClient(customClient); twitchAPI = new TwitchAPI(); this.credentialsManagement = credentialsManagement; }
public static void InitializeBot(Secrets secrets) { Secrets = secrets; HostChannelName = secrets.HostChannelName; TMICredentials = new ConnectionCredentials(secrets.HostChannelName, secrets.BotTMIOAuthKey); TwitchClient = new TwitchClient(); TwitchClient.Initialize(TMICredentials, secrets.HostChannelName); if (!TwitchClient.IsInitialized) { Console.WriteLine("Twitch Client did not initialize."); return; } TwitchClient.Connect(); if (!TwitchClient.IsConnected) { Console.WriteLine("Twitch Client was not able to connect."); return; } TwitchClient.JoinChannel(secrets.HostChannelName); BotAPI = new TwitchAPI(); BotAPI.Settings.ClientId = Secrets.BotClientID; BotAPI.Settings.Secret = secrets.BotClientSecret; HostAPI = new TwitchAPI(); HostAPI.Settings.ClientId = Secrets.HostClientID; HostAPI.Settings.Secret = secrets.HostClientSecret; CommandsHandler = new CommandsHandler(); VisitorTracker = new VisitorTracker(); CurrencyHandler = new CurrencyHandler(); TwitchClient.OnLog += OnLog; }
public async Task SendNotification(CommandContext ctx, TwitchAPI api) { //while (token==true) //{ if (this.streamersDictionary.Count > 0) { foreach (Streamers streamers in this.streamersDictionary.Values) { var stream = await api.V5.Streams.GetStreamByUserAsync(streamers.TwitchUserID); if (stream?.Stream?.Channel?.Status != null) { if (streamers.IsLive == false) { streamers.IsLive = true; this.Save(); var emoji1 = DiscordEmoji.FromName(ctx.Client, ":movie_camera:"); await ctx.TriggerTypingAsync(); await ctx.RespondAsync($"{emoji1} {streamers.TwitchName} live! Ha nézni szeretnéd, kattints a linkre: {stream.Stream.Channel.Url}"); } } else { streamers.IsLive = false; this.Save(); } } } else { var emoji1 = DiscordEmoji.FromName(ctx.Client, ":no_entry_sign:"); await ctx.TriggerTypingAsync(); await ctx.RespondAsync($"{emoji1} Nincs mentett streamer."); Console.WriteLine("There are no saved information"); } // System.Threading.Thread.Sleep(120000); //} }
public async void OnNewFollowersDetected_NotRaised_When_NewFollowerOlderThanLatest() { var usersFollowsResponseFirstUserJson = JMock.Of <GetUsersFollowsResponse>(o => o.Follows == new[] { Mock.Of <Follow>(f => f.FromUserId == "FromFirstUserId" && f.FollowedAt == new DateTime(1)) } ); var mockHandler = new Mock <IHttpCallHandler>(); mockHandler .Setup(x => x.GeneralRequest(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Core.Enums.ApiVersion>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(new KeyValuePair <int, string>(200, usersFollowsResponseFirstUserJson)); _api = TwitchLibMock.TwitchApi(mockHandler); var eventExecuteCount = 0; _followerService = new FollowerService(_api); _followerService.SetChannelsById(Utils.CreateListWithEmptyString()); _followerService.OnNewFollowersDetected += (sender, e) => eventExecuteCount++; await _followerService.UpdateLatestFollowersAsync(); var usersFollowsResponseSecondUserJson = JMock.Of <GetUsersFollowsResponse>(o => o.Follows == new[] { Mock.Of <Follow>(f => f.FromUserId == "FromSecondUserId" && f.FollowedAt == new DateTime(0)) } ); mockHandler.Reset(); mockHandler .Setup(x => x.GeneralRequest(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Core.Enums.ApiVersion>(), It.IsAny <string>(), It.IsAny <string>())) .Returns(new KeyValuePair <int, string>(200, usersFollowsResponseSecondUserJson)); await _followerService.UpdateLatestFollowersAsync(); Assert.Equal(1, eventExecuteCount); }
public static void Main(string[] args) { Console.Title = "Twitch Interact"; if (File.Exists(Directory.GetCurrentDirectory() + "/config.ini")) { var parser = new FileIniDataParser(); IniData data = parser.ReadFile("config.ini"); BotName = data["TGM"]["BotName"] ?? "gameruiner9000"; BotOauth = data["TGM"]["BotOauth"]; TwitchChannel = data["TGM"]["TwitchChannel"]; ChatCheckInterval = Convert.ToInt16(data["TGM"]["ConfirmConnectionIntervalInSeconds"]); ChatCheckInterval *= 1000; } else { Console.WriteLine("Enter your bot's name."); BotName = Console.ReadLine(); Console.WriteLine("Now enter your bot's OAuth key. You can paste by right clicking in the console window. (https://www.twitchapps.com/tmi/)"); BotOauth = Console.ReadLine(); Console.WriteLine("What Twitch channel do you want to monitor?"); TwitchChannel = Console.ReadLine(); Console.WriteLine("What's the maximum amount of seconds between any two chat messages in your stream? (If you have frequent chatters, set this to 5 or lower.)"); ChatCheckInterval = Int32.Parse(Console.ReadLine()); var parser = new FileIniDataParser(); IniData data = new IniData(); data["TGM"]["BotName"] = BotName; data["TGM"]["BotOauth"] = BotOauth; data["TGM"]["TwitchChannel"] = TwitchChannel; data["TGM"]["ConfirmConnectionIntervalInSeconds"] = ChatCheckInterval.ToString(); parser.WriteFile("config.ini", data); } API = new TwitchAPI(); API.Settings.AccessToken = BotOauth; Console.CancelKeyPress += (sender, eArgs) => { _quitEvent.Set(); eArgs.Cancel = true; }; TGM_Init(); _quitEvent.WaitOne(); }
public TwitchBot() { client = new TwitchClient(); client.Initialize(credentials, Configuration.TwitchChannelName); TwitchApi = new TwitchAPI(); TwitchApi.Settings.ClientId = Configuration.TwitchClientId; TwitchApi.Settings.AccessToken = Configuration.TwitchBotOAuth; client.OnJoinedChannel += OnJoinedChannel; client.OnMessageReceived += OnMessageReceived; client.Connect(); TwitchApi.Settings.SkipDynamicScopeValidation = true; Console.WriteLine("Twitch bot connected!"); }
public StreamNotifier(DiscordSocketClient discordClient) { Configuration = ConfigurationHost.Current; DiscordClient = discordClient; TwitchAPI = new TwitchAPI(); TwitchAPI.Settings.ClientId = EnvUtils.VariableOrThrow(Constants.Environment.TwitchClientId); TwitchAPI.Settings.AccessToken = EnvUtils.VariableOrThrow(Constants.Environment.TwitchBotToken); LiveStreamMonitor = new LiveStreamMonitorService(TwitchAPI, 20); LiveStreamMonitor.SetChannelsByName(Configuration.TwitchFriends.ToList()); LiveStreamMonitor.OnStreamOnline += async(s, e) => { await LiveStreamMonitor_OnStreamOnline(e); }; ConfigurationHost.ConfigurationChanged += ConfigurationChanged; }
public async void LiveStreams_Contains_UserId_When_ServiceUpdated() { var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o => o.Streams == new[] { Mock.Of <Stream>(u => u.UserId == "UserId") } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/streams", usersFollowsResponseJson) ); _liveStreamMonitor = new LiveStreamMonitorService(_api); _liveStreamMonitor.SetChannelsById(Utils.CreateListWithStrings("UserId")); await _liveStreamMonitor.UpdateLiveStreamersAsync(); Assert.True(_liveStreamMonitor.LiveStreams.ContainsKey("UserId")); }
public static void Init(BaseSocketClient client, IConfiguration config) { var configuration = config; Api = new TwitchAPI(); Api.Settings.ClientId = configuration["client_id"]; Api.Settings.AccessToken = configuration["client_token"]; foreach (var guilds in client.Guilds) { foreach (var channel in guilds.Channels) { if (channel.Name.Equals("streamer-feed")) { _channel = client.GetChannel(channel.Id) as IMessageChannel; } } } _streamers = new List <StreamerInfo>(); }
public TwitchPubSubService(TwitchAPI twitchApiClient, IOptions <TwitchConfig> config, ILogger <TwitchPubSubService> logger) { _logger = logger; _config = config.Value; PubSubClient = new TwitchPubSub(); var user = twitchApiClient.Helix.Users.GetUsersAsync(logins: new List <string> { "vic10usx" }).Result.Users.First(); PubSubClient.OnPubSubServiceConnected += OnPubSubServiceConnected; PubSubClient.ListenToRewards(user.Id); PubSubClient.OnPubSubServiceClosed += (sender, args) => { _logger.LogWarning("The service has closed it's connection... :(", args); }; PubSubClient.OnPubSubServiceError += (sender, args) => { _logger.LogError("The service encountered a critical error... :(", args); }; PubSubClient.Connect(); }
public static void StartUp() { TwitchA = new TwitchAPI(); TwitchA.Settings.ClientId = Shared.ConfigHandler.LoginConfig["TwitchBot"]["ClientId"].ToString(); TwitchA.Settings.AccessToken = Shared.ConfigHandler.LoginConfig["TwitchBot"]["AccessToken"].ToString(); ConnectionCredentials credentials = new ConnectionCredentials(Shared.ConfigHandler.LoginConfig["TwitchBot"]["Username"].ToString(), Shared.ConfigHandler.LoginConfig["TwitchBot"]["0AuthToken"].ToString()); TwitchC = new TwitchClient(); TwitchC.Initialize(credentials, Shared.ConfigHandler.Config["ChannelName"].ToString()); TwitchC.OnMessageReceived += MessageHandler.HandleMessage; TwitchC.OnMessageReceived += Logger.AddToLog; TwitchC.OnGiftedSubscription += Events.SubGifted; TwitchC.OnNewSubscriber += Events.Subbed; TwitchC.OnReSubscriber += Events.ReSubbed; //TwitchC.OnBeingHosted += Events.Hosting; TwitchC.Connect(); Console.WriteLine("TwitchBot Started"); System.Threading.Thread.Sleep(500); new Thread(() => Commands.Drops.Handler()).Start(); }
public async Task GetTopClipsCommand(CommandContext cmdContext, [Description("The amount of clips you want returned.")] int amount, [Description("The channel that you would like the top clips from")] string channelName = null) { var api = new TwitchAPI(); api.Settings.ClientId = _settings.Keys.Twitch.ClientId; try { var clipsResponse = await api.Clips.v5.GetTopClipsAsync(channelName, limit : amount, period : Period.All); clipsResponse.Clips.ForEach(async clip => { await cmdContext.RespondAsync(clip.Url); }); } catch (Exception exception) { Console.WriteLine(exception); throw; } }
public ServiceMonitor(IConfiguration config) { _config = config; var channels = _config.GetSection("Values:Twitch:Channels").Get <List <string> >(); _processFileName = $@"{_config["Values:BotAssembly:Directory"]}\{_config["Values:BotAssembly:Name"]}"; var twitchApi = new TwitchAPI(); twitchApi.Settings.ClientId = config["Values:Twitch:ClientId"]; twitchApi.Settings.AccessToken = config["Values:Twitch:AccessToken"]; _liveStreamMonitorService = new LiveStreamMonitorService(twitchApi); _liveStreamMonitorService.SetChannelsByName(channels); _liveStreamMonitorService.OnStreamOnline += async(s, e) => await LiveStreamMonitorServiceOnOnStreamOnline(s, e); _liveStreamMonitorService.OnStreamOffline += async(s, e) => await LiveStreamMonitorServiceOnOnStreamOffline(s, e); }
/// <summary> /// Creates a new instance for the follower service. StartService has to be calles seperately /// </summary> /// <param name="api">Instance of the twitch api</param> /// <param name="channel">Name of your channel</param> /// <param name="period">time interval to check for new followers in miliseconds</param> public FollowerServiceNew(TwitchAPI api, string channelId, int period) { this.api = api; timerInterval = period; ChannelId = channelId; runningThread = true; logger = LogManager.GetCurrentClassLogger(); thread = new Thread(() => { do { Thread.Sleep(timerInterval); TimerTick().Wait(); } while (runningThread); }); lockObject = new object(); thread.Name = "ChannelListener"; thread.IsBackground = true; }
public static IServiceCollection AddTwitchLibConnection(this IServiceCollection services, TwitchClientSettings twitchClientSettings) { services.AddSingleton <SubscriberHandler>(); services.AddSingleton <IFollowableSystem, FollowableSystem>(); services.AddSingleton <IFollowerService, TwitchFollowerService>(); var api = new TwitchAPI(); api.Settings.ClientId = twitchClientSettings.TwitchClientId; api.Settings.AccessToken = twitchClientSettings.TwitchChannelOAuth; services.AddSingleton <ITwitchAPI>(api); services.AddSingleton <IChatClient, TwitchChatClient>(); services.AddSingleton <IStreamingInfoService, TwitchStreamingInfoService>(); return(services); }
/// <summary> /// Initializes and starts the bot. /// </summary> /// <returns>A Task that can be awaited.</returns> private static async Task BotStartup() { // Attach shutdown handler. AttachCtrlcSigtermShutdown(Program._shutdownCts, Program._done); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; _ = Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // Load settings. _settings = await SettingsDocument.Read().ConfigureAwait(false); // Start Exceptionless session, if enabled. if (Settings.SendExceptions) { // Set Exceptionless to not send GPDR-protected information. ExceptionlessClient.Default.Configuration.IncludeCookies = false; ExceptionlessClient.Default.Configuration.IncludeIpAddress = false; ExceptionlessClient.Default.Configuration.IncludeMachineName = false; ExceptionlessClient.Default.Configuration.IncludePostData = false; ExceptionlessClient.Default.Configuration.IncludeQueryString = false; ExceptionlessClient.Default.Configuration.IncludeUserName = false; ExceptionlessClient.Default.Configuration.IncludePrivateInformation = false; if (Settings.ShowDebugMessages) { ExceptionlessClient.Default.Configuration.UseTraceLogger(Exceptionless.Logging.LogLevel.Debug); } ExceptionlessClient.Default.Configuration.SetUserIdentity(Settings.BotLogin); ExceptionlessClient.Default.Configuration.SetVersion(Version); ExceptionlessClient.Default.Configuration.UseReferenceIds(); ExceptionlessClient.Default.Configuration.UseSessions(); ExceptionlessClient.Default.Startup(); } // Initialize Twitch API. _twitchApi = new TwitchAPI(); _twitchApi.Settings.ClientId = _settings.TwitchApiClientId; _twitchApi.Settings.AccessToken = _settings.BotOAuth; _twitchApi.Settings.Secret = _settings.TwitchApiSecret; }
public async void KnownFollowers_Contains_UserId_When_ServiceUpdated() { var usersFollowsResponseJson = JMock.Of <GetUsersFollowsResponse>(o => o.Follows == new[] { Mock.Of <Follow>(u => u.FromUserId == "UserId" && u.ToUserId == "Id") } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson) ); _followerService = new FollowerService(_api); _followerService.SetChannelsById(Utils.CreateListWithEmptyString()); await _followerService.UpdateLatestFollowersAsync(); Assert.NotNull(_followerService.KnownFollowers[string.Empty].FirstOrDefault(f => f.FromUserId == "UserId")); //Same check for SetChannelsByName var usersResponseJson = JMock.Of <GetUsersResponse>(o => o.Users == new[] { Mock.Of <User>(u => u.Id == "Id" && u.DisplayName == "DisplayName"), }); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/users", usersResponseJson), ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson) ); _followerService = new FollowerService(_api); _followerService.SetChannelsByName(Utils.CreateListWithEmptyString()); await _followerService.UpdateLatestFollowersAsync(); Assert.NotNull(_followerService.KnownFollowers[string.Empty].FirstOrDefault(f => f.FromUserId == "UserId")); }
public void OnServiceTick_Raised_When_ServiceTicked() { var usersFollowsResponseJson = JMock.Of <GetUsersFollowsResponse>(o => o.Follows == new[] { Mock.Of <Follow>() } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson) ); var signalEvent = new ManualResetEvent(false); _followerService = new FollowerService(_api, checkIntervalInSeconds: 1); _followerService.SetChannelsById(Utils.CreateListWithEmptyString()); _followerService.OnServiceTick += (sender, e) => signalEvent.Set(); _followerService.Start(); Assert.True(signalEvent.WaitOne(1500)); }
public static IUnityContainer Create() { var container = new UnityContainer(); var config = ConfigHelper.GetConfig(); var creds = new ConnectionCredentials(config.ChatbotNick, config.ChatbotPass); var client = new TwitchClient(creds, config.StreamerChannel); var api = new TwitchAPI(accessToken: config.ChatbotAccessToken); var followerService = new FollowerService(api, 5); var pubsub = new TwitchPubSub(); container.RegisterInstance(api); container.RegisterInstance(client); container.RegisterInstance(followerService); container.RegisterInstance(pubsub); var commandHelper = new CommandHelper(container); container.RegisterInstance(commandHelper); return(container); }
public async Task <JsonResult> GetGames(string phrase) { Game[] games = new Game[0]; if (phrase.Length <= 3) { return(Json(games)); } var user = ContextService.GetUser(HttpContext.User.Identity.Name); var bs = ContextService.GetBotUserSettingsForUser(user); var twitchApi = new TwitchAPI(); twitchApi.Settings.ClientId = ConfigurationManager.AppSettings["clientId"]; twitchApi.Settings.AccessToken = bs.ChannelToken; var gamesResult = await twitchApi.V5.Search.SearchGamesAsync(phrase, null); var settings = new JsonSerializerSettings(); settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml; return(Json(gamesResult.Games)); }
private async Task ConfigLiveMonitorAsync() { using (var scope = _serviceProvider.CreateScope()) { var guildService = scope.ServiceProvider.GetRequiredService <IGuildService>(); _api = new TwitchAPI(); _api.Settings.ClientId = "d0qgyohqojd71mpvsz7p0ldre5lfic"; _api.Settings.AccessToken = "ciif9s2t2hhrn8tcx92e9p6g8xxpbq"; _monitor = new LiveStreamMonitorService(_api, 60); var guilds = await guildService.GetAllAsync(); var items = guilds.Select(g => g.TwitchPlugin.TwitchChannelSubscriptions).ToList(); var channelsToMonitor = new List <string>(); foreach (var subscription in items .SelectMany(item => item .Where(subscription => !channelsToMonitor.Contains(subscription.StreamerId)))) { channelsToMonitor.Add(subscription.StreamerId); } _monitor.SetChannelsById(channelsToMonitor); _monitor.OnStreamOnline += Monitor_OnStreamOnline; _monitor.OnStreamOffline += Monitor_OnStreamOffline; _monitor.OnStreamUpdate += Monitor_OnStreamUpdate; _monitor.OnServiceStarted += Monitor_OnServiceStarted; _monitor.OnChannelsSet += Monitor_OnChannelsSet; _monitor.Start(); await Task.Delay(-1); } }
public async Task <string> GetChannelId(string channelName) { string channelId = ""; try { API = new TwitchAPI(); API.Settings.ClientId = ClientId; API.Settings.AccessToken = AccessToken; var users = await API.Helix.Users.GetUsersAsync(logins : new List <string>() { channelName }); if (users.Users.Length > 0) { channelId = users.Users[0].Id; } else { throw new Exception("User of the given name not found."); } } catch (Exception ex) { #if DEBUG Trace.WriteLine(ex.Message); #endif } #if DEBUG Trace.WriteLine($"ChannelId for {channelName}: {channelId}"); #endif return(channelId); }
protected override void Load(ContainerBuilder builder) { builder.RegisterType <TwitchSubscriberHandler>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType <TwitchFollowerService>() .WithParameter("settings", _twitchClientSettings) .As <IFollowerService>().SingleInstance(); var api = new TwitchAPI(); api.Settings.ClientId = _twitchClientSettings.TwitchClientId; api.Settings.AccessToken = _twitchClientSettings.TwitchChannelOAuth; builder.RegisterInstance(api).As <ITwitchAPI>().SingleInstance(); builder.RegisterType <TwitchChatClient>() .WithParameter("settings", _twitchClientSettings) .As <IChatClient>().AsSelf().SingleInstance(); builder.RegisterType <TwitchStreamingInfoService>() .As <IStreamingInfoService>().SingleInstance(); }
public async void OnNewFollowersDetected_Raised_When_LatestFollowersUpdated() { var usersFollowsResponseJson = JMock.Of <GetUsersFollowsResponse>(o => o.Follows == new[] { Mock.Of <Follow>() } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson) ); var eventExcecuted = false; _followerService = new FollowerService(_api); _followerService.SetChannelsById(Utils.CreateListWithEmptyString()); _followerService.OnNewFollowersDetected += (sender, e) => eventExcecuted = true; await _followerService.UpdateLatestFollowersAsync(); Assert.True(eventExcecuted); }
//forsens bot internal void Connectforsen() { api = new TwitchAPI(); api.Settings.ClientId = info.ClientId; api.Settings.AccessToken = info.BotToken; TwitchLib.Api.Models.v5.Users.User[] users = api.Users.v5.GetUserByNameAsync(info.Channelforsen).Result.Matches; channelid = users[0].Id; interval = 45; enabled = false; stopwatch = new Stopwatch(); Console.WriteLine("connected to forsens chat, starting stopwatch"); stopwatch.Start(); timeAlive = new Stopwatch(); timeAlive.Start(); client = new TwitchClient(); this.cChannel = info.Channelforsen; client.Initialize(credentials, info.Channelforsen); client.OnMessageReceived += Client_OnMessageReceived; client.OnConnectionError += Client_OnConnectionError; client.OnDisconnected += Client_OnDisconnected; client.Connect(); }