public SysCord(PokeBotRunner <T> runner) { Runner = runner; Hub = runner.Hub; Manager = new DiscordManager(Hub.Config.Discord); SysCordSettings.Manager = Manager; SysCordSettings.HubConfig = Hub.Config; _client = new DiscordSocketClient(new DiscordSocketConfig { // How much logging do you want to see? LogLevel = LogSeverity.Info, // If you or another service needs to do anything with messages // (eg. checking Reactions, checking the content of edited/deleted messages), // you must set the MessageCacheSize. You may adjust the number as needed. //MessageCacheSize = 50, }); _commands = new CommandService(new CommandServiceConfig { // Again, log level: LogLevel = LogSeverity.Info, // This makes commands get run on the task thread pool instead on the websocket read thread. // This ensures long running logic can't block the websocket connection. DefaultRunMode = Hub.Config.Discord.AsyncCommands ? RunMode.Async : RunMode.Sync, // There's a few more properties you can set, // for example, case-insensitive commands. CaseSensitiveCommands = false, }); // Subscribe the logging handler to both the client and the CommandService. _client.Log += Log; _commands.Log += Log; // Setup your DI container. _services = ConfigureServices(); }
public void TradeFinished(PokeRoutineExecutor routine, PokeTradeDetail <T> info, T result) { OnFinish?.Invoke(routine); var tradedToUser = Data.Species; string message; var hub = new PokeTradeHub <PK8>(new PokeTradeHubConfig()); var qInfo = new TradeQueueInfo <PK8>(hub); if (qInfo.Count != 0) { string gameText = $"{SysCordInstance.Settings.BotGameStatus.Replace("{0}", $"Completed Trade #{info.ID}")}"; Context.Client.SetGameAsync(gameText).ConfigureAwait(false); } else { string gameText = $"{SysCordInstance.Settings.BotGameStatus.Replace("{0}", $"Queue is Empty")}"; Context.Client.SetGameAsync(gameText).ConfigureAwait(false); } if (Data.IsEgg && info.Type == PokeTradeType.EggRoll) { message = tradedToUser != 0 ? $"Trade finished. Enjoy your Mysterious egg!" : "Trade finished!"; } if (Data.IsEgg && info.Type == PokeTradeType.LanRoll) { message = tradedToUser != 0 ? $"Trade finished. Enjoy your Really Illegal Egg!" : "Trade finished!"; } else { message = tradedToUser != 0 ? $"Trade finished. Enjoy your {(Species)tradedToUser}!" : "Trade finished!"; } Trader.SendMessageAsync(message).ConfigureAwait(false); if (result.Species != 0 && Hub.Config.Discord.ReturnPK8s) { Trader.SendPKMAsync(result, $"Here is what you traded me!{(info.Type != PokeTradeType.LanTrade && info.Type != PokeTradeType.LanRoll /* Don't want people thinking Showdown works on LAN */? $"\n{ReusableActions.GetFormattedShowdownText(result)}" : "")}").ConfigureAwait(false); } }
private static void Test <T>() where T : PKM, new() { var cfg = new PokeTradeHubConfig { Distribution = { DistributeWhileIdle = true } }; var hub = new PokeTradeHub <T>(cfg); var pool = hub.Ledy.Pool; var a = new T { Species = 5 }; pool.Add(a); var trade = hub.Queues.TryDequeue(PokeRoutineType.FlexTrade, out _, out _); trade.Should().BeFalse(); var ledy = hub.Queues.TryDequeueLedy(out var detail); ledy.Should().BeTrue(); detail.TradeData.Should().Be(a); }
public SysCord(PokeTradeHub <PK8> hub) { Hub = hub; SysCordInstance.Self = this; // hack SysCordInstance.Manager = new DiscordManager(Hub.Config); AutoLegalityWrapper.EnsureInitialized(Hub.Config.Legality); PriorityUtil.GetInitialCooldowns(); _client = new DiscordSocketClient(new DiscordSocketConfig { // How much logging do you want to see? LogLevel = LogSeverity.Info, // If you or another service needs to do anything with messages // (eg. checking Reactions, checking the content of edited/deleted messages), // you must set the MessageCacheSize. You may adjust the number as needed. //MessageCacheSize = 50, }); _commands = new CommandService(new CommandServiceConfig { // Again, log level: LogLevel = LogSeverity.Info, // There's a few more properties you can set, // for example, case-insensitive commands. CaseSensitiveCommands = false, }); // Subscribe the logging handler to both the client and the CommandService. _client.Log += Log; _commands.Log += Log; // Setup your DI container. _services = ConfigureServices(); }
public YouTubeBot(YouTubeSettings settings, PokeTradeHub <PK8> hub) { Hub = hub; Settings = settings; Logger.LogOccurred += Logger_LogOccurred; try { Task.Run(async() => { var connection = await YouTubeConnection.ConnectViaLocalhostOAuthBrowser(Settings.ClientID, Settings.ClientSecret, Scopes.scopes, true); if (connection != null) { channel = await connection.Channels.GetChannelByID(Settings.ChannelID); if (channel != null) { client = new ChatClient(connection); client.OnMessagesReceived += Client_OnMessagesReceived; if (await client.Connect()) { await Task.Delay(-1); } else { } } } EchoUtil.Forwarders.Add(msg => client.SendMessage(msg)); }); } catch (Exception ex) { LogUtil.LogError(ex.Message, "YouTubeBot"); } }
public void TestEnqueue() { var hub = new PokeTradeHub <PK8>(new PokeTradeHubConfig()); var info = new TradeQueueInfo <PK8>(hub); var queue = info.Hub.Queues.GetQueue(PokeRoutineType.LinkTrade); var t1 = GetTestTrade(info, 1); var t2 = GetTestTrade(info, 2); var t3 = GetTestTrade(info, 3); var s = GetTestTrade(info, 4); var executor = new MockExecutor(new PokeBotConfig()); // Enqueue a bunch var r1 = info.AddToTradeQueue(t1, t1.UserID); r1.Should().Be(QueueResultAdd.Added); var r2 = info.AddToTradeQueue(t2, t2.UserID); r2.Should().Be(QueueResultAdd.Added); var r3 = info.AddToTradeQueue(t3, t3.UserID); r3.Should().Be(QueueResultAdd.Added); // Sudo add with the same ID var id = t1.UserID; var sr = info.AddToTradeQueue(s, id); sr.Should().Be(QueueResultAdd.AlreadyInQueue); sr = info.AddToTradeQueue(s, id, true); sr.Should().Be(QueueResultAdd.Added); var dequeue = queue.TryDequeue(out var first, out uint priority); priority.Should().Be(PokeTradeQueue <PK8> .Tier1); // sudo dequeue.Should().BeTrue(); ReferenceEquals(first, s.Trade).Should().BeTrue(); first.Notifier.TradeInitialize(executor, first); first.Notifier.TradeSearching(executor, first); first.Notifier.TradeFinished(executor, first, new PK8 { Species = 777 }); var status = info.CheckPosition(t1.UserID, PokeRoutineType.LinkTrade); status.Position.Should().Be(1); // not zero indexed var count = info.UserCount(z => z.Type == PokeRoutineType.LinkTrade); count.Should().Be(3); queue.Count.Should().Be(3); dequeue = queue.TryDequeue(out var second, out priority); priority.Should().Be(PokeTradeQueue <PK8> .TierFree); // sudo dequeue.Should().BeTrue(); ReferenceEquals(second, t1.Trade).Should().BeTrue(); second.Notifier.TradeInitialize(executor, second); second.Notifier.TradeSearching(executor, second); second.Notifier.TradeCanceled(executor, second, PokeTradeResult.TrainerTooSlow); status = info.CheckPosition(t1.UserID, PokeRoutineType.LinkTrade); status.Position.Should().Be(-1); count = info.UserCount(z => z.Type == PokeRoutineType.LinkTrade); count.Should().Be(2); queue.Count.Should().Be(2); }
public TwitchBot(TwitchSettings settings, PokeTradeHub <PK8> hub) { Hub = hub; Settings = settings; var credentials = new ConnectionCredentials(settings.Username.ToLower(), settings.Token); var clientOptions = new ClientOptions { MessagesAllowedInPeriod = settings.ThrottleMessages, ThrottlingPeriod = TimeSpan.FromSeconds(settings.ThrottleSeconds), WhispersAllowedInPeriod = settings.ThrottleWhispers, WhisperThrottlingPeriod = TimeSpan.FromSeconds(settings.ThrottleWhispersSeconds), // message queue capacity is managed (10_000 for message & whisper separately) // message send interval is managed (50ms for each message sent) }; Channel = settings.Channel; WebSocketClient customClient = new WebSocketClient(clientOptions); client = new TwitchClient(customClient); var cmd = settings.CommandPrefix; client.Initialize(credentials, Channel, cmd, cmd); client.OnLog += Client_OnLog; client.OnJoinedChannel += Client_OnJoinedChannel; client.OnMessageReceived += Client_OnMessageReceived; client.OnWhisperReceived += Client_OnWhisperReceived; client.OnChatCommandReceived += Client_OnChatCommandReceived; client.OnWhisperCommandReceived += Client_OnWhisperCommandReceived; client.OnNewSubscriber += Client_OnNewSubscriber; client.OnConnected += Client_OnConnected; client.OnDisconnected += Client_OnDisconnected; client.OnLeftChannel += Client_OnLeftChannel; client.OnMessageSent += (_, e) => LogUtil.LogText($"{client.TwitchUsername}] - Message Sent in {e.SentMessage.Channel}: {e.SentMessage.Message}"); client.OnWhisperSent += (_, e) => LogUtil.LogText($"{client.TwitchUsername}] - Whisper Sent to @{e.Receiver}: {e.Message}"); client.OnMessageThrottled += (_, e) => LogUtil.LogError($"Message Throttled: {e.Message}", "TwitchBot"); client.OnWhisperThrottled += (_, e) => LogUtil.LogError($"Whisper Throttled: {e.Message}", "TwitchBot"); client.OnError += (_, e) => LogUtil.LogError(e.Exception.Message + Environment.NewLine + e.Exception.StackTrace, "TwitchBot"); client.OnConnectionError += (_, e) => LogUtil.LogError(e.BotUsername + Environment.NewLine + e.Error.Message, "TwitchBot"); client.Connect(); EchoUtil.Forwarders.Add(msg => client.SendMessage(Channel, msg)); // Turn on if verified // Hub.Queues.Forwarders.Add((bot, detail) => client.SendMessage(Channel, $"{bot.Connection.Name} is now trading (ID {detail.ID}) {detail.Trainer.TrainerName}")); }
// Util for checking subscribers/ mods/ sudos etc. Future expandability?? public static bool IsSudo(this PokeTradeHub <PK8> hub, string username) { var cfg = hub.Config; return(cfg.TwitchSudoList.Contains(username)); }
public YouTubeBot(YouTubeSettings settings, PokeTradeHub <T> hub) { Hub = hub; Settings = settings; Logger.LogOccurred += Logger_LogOccurred; client = default !;
public PokeBotRunnerImpl(PokeTradeHub <T> hub, BotFactory <T> fac) : base(hub, fac) { }
public PokeBotRunnerImpl(PokeTradeHub <PK8> hub) : base(hub) { }
// Util for checking subscribers/ mods/ sudos etc. Future expandability?? public static bool IsSudo(this PokeTradeHub <PK8> hub, string username) { var sudos = hub.Config.TwitchSudoList.Split(new[] { ",", ", ", " " }, StringSplitOptions.RemoveEmptyEntries); return(sudos.Contains(username)); }