コード例 #1
0
        public TwitchIrcConnection(ITwitchFactory factory, TwitchBot bot, bool whisperServer)
        {
            this.factory = factory;
            this.bot = bot;
            this.whisperServer = whisperServer;

            Reconnect();
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: SSStormy/TwitchBotTests
        public static void Main()
        {
            dynamic config = JObject.Parse(File.ReadAllText("config.json"));
            if (config == null) throw new InvalidOperationException("Failed parsing config.json");

            TwitchBot twitch = new TwitchBot();

            twitch.Connect((string) config.Username, (string) config.Oauth);
            twitch.ChatMessageReceived += (s, e) => Console.WriteLine($"|{e.Message.Channel}| <{e.Message.Username}> {e.Message.Text}");
            twitch.ChannelJoined += (s, e) => Console.WriteLine($"Joined: {e.Channel}");
            twitch.ChannelLeave += (s, e) => Console.WriteLine($"Left: {e.Channel}");

            twitch.JoinChannel("ssstormy");
            twitch.JoinChannel("discordrelay");

            twitch.Wait();
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: notepid/DotDotBot
        static void Main(string[] args)
        {
            var logger = new ConsoleTraceLogger();
            logger.Write($"---- New log started {DateTime.UtcNow} UTC ----");
            try
            {
                logger.Write($"DotDotBot Console version {FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion} started.");

                var config = new ProgramConfig();

                var pluginManager = new PluginManager();
                var bot = new TwitchBot(new SQLiteConnection(new SQLitePlatformWin32(), "DotDotBot.db"), pluginManager, logger, config.BotOwner);

                if (!File.Exists("config.json"))
                {
                    logger.Write("Could not find config.json Please edit config_example.json and rename it to config.json");
            #if DEBUG
                    System.Console.ReadKey();
            #endif
                    return;
                }

                bot.IrcClient.AutoJoinChannels = config.AutoJoinChannels;
                bot.Connect(config.Credentials);
            }
            catch (ReflectionTypeLoadException e)
            {
                logger.Write($"Exception: {e.Message}");
                logger.Write($"LoaderExceptions:");
                foreach (var loaderException in e.LoaderExceptions)
                {
                    logger.WriteIndented($"-> {loaderException.Message}");
                }
                logger.WriteIndented($"Stacktrace: { e.StackTrace}");
                throw;
            }
            catch (Exception e)
            {
                logger.Write($"Exception: {e.Message}");
                logger.WriteIndented($"Stacktrace: { e.StackTrace}");
                throw;
            }

            logger.Write("Press Q to quit program.");
            while (!System.Console.ReadKey().Key.Equals(ConsoleKey.Q));
        }
コード例 #4
0
ファイル: Conection.cs プロジェクト: xxJohnxx/DotDotBot
        public bool LogIn(string user, string nick, string token, ILogger logger, TwitchBot bot)
        {
            try
            {
                //bot = new TwitchBot(new SQLiteConnection(new SQLitePlatformWin32(), "DotDotBot.db"), logger);

                IrcCredentials credentials;
                credentials = new IrcCredentials(token, user);
                bot.Connect(credentials);
            }
            catch
            {
                return false;
            }

            return true;
        }
コード例 #5
0
 static string GetJson(TwitchBot bot, uint limit, uint offset, string path)
 {
     return WebClient.GetHTML("https://api.twitch.tv/kraken/" + path + "&oauth_token=" + bot.oauthPassword + "&limit=" + limit
         + "&offset=" + offset);
 }
コード例 #6
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, AfkCommandType type)
 {
     twitchBot.SendGoingAfk(chatMessage, type);
 }
コード例 #7
0
        void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;
            _twitch = new TwitchBot();

            manager.CreateDynCommands("twitch", PermissionLevel.ChannelModerator, group =>
            {
                group.CreateCommand("connect")
                .Description("Connects this channel to a given twitch channel, relaying the messages between them.")
                .Parameter("channel")
                .Do(async e =>
                {
                    string channel = e.GetArg("channel");

                    if (await IsValidTwitchChannelAndIsStreaming(channel))
                    {
                        int?viewers = await GetViewerCount(channel);

                        if (viewers != null && viewers.Value <= MaxViewsPerChannel)
                        {
                            await Subscribe(channel, e.Channel);
                        }
                        else
                        {
                            await
                            e.Channel.SafeSendMessage(
                                $"{channel}'s view count ({viewers}) is currently over the view barrier ({MaxViewsPerChannel}), therefore, for the sake of not getting a cooldown for spamming Discord, we cannot connect to this channel.");
                        }
                    }
                    else
                    {
                        await e.Channel.SafeSendMessage($"{channel} channel is currently offline.");
                    }
                });

                group.CreateCommand("disconnect")
                .Description("Disconnects this channel from the given twitch channel.")
                .Parameter("channel")
                .Do(async e => { await Unsubscribe(e.GetArg("channel"), e.Channel); });
                group.CreateCommand("list")
                .MinDynPermissions((int)PermissionLevel.User)
                .Description("Lists all the twitch channels this discord channel is connected to.")
                .Do(async e =>
                {
                    List <string> twitchSub = GetTwitchChannels(e.Channel).ToList();

                    if (!twitchSub.Any())
                    {
                        await e.Channel.SafeSendMessage("This channel isin't subscribed to any twitch channels.");
                        return;
                    }

                    StringBuilder builder = new StringBuilder($"**{e.Channel.Name} is subscribed to:**\r\n```");
                    foreach (string twitchChannel in twitchSub)
                    {
                        builder.AppendLine($"* {twitchChannel}");
                    }

                    await e.Channel.SafeSendMessage($"{builder.ToString()}```");
                });
            });

            _twitch.DisconnectFromTwitch +=
                async(s, e) =>
            {
                Logger.FormattedWrite("Twitch", "Disconnected from twitch", ConsoleColor.Red);

                // try to reconnect to twitch
                while (!_twitch.IsConnected)
                {
                    Logger.FormattedWrite("Twitch", "Attempting to reconnect to twitch...", ConsoleColor.Red);
                    await TwitchTryConnect();

                    await Task.Delay(5000);
                }

                Logger.FormattedWrite("Twitch", "Reconnected to twitch.", ConsoleColor.Red);
            };

            _twitch.ChatMessageReceived += async(s, e) =>
            {
                if (!_relays.ContainsKey(e.Message.Channel))
                {
                    return;
                }
                if (e.Message.Username == Config.TwitchUsername)
                {
                    return;
                }

                if (e.Message.Text.StartsWith(EscapePrefix))
                {
                    return;
                }

                foreach (JsonChannel relay in _relays[e.Message.Channel])
                {
                    await relay.Channel.SafeSendMessage($"**Twitch**: `<{e.Message.Username}> {e.Message.Text}`");
                }
            };

            _twitch.ChannelLeave += (s, e) => _relays.Remove(e.Channel);

            _client.MessageReceived += (s, e) =>
            {
                if (e.Message.IsAuthor)
                {
                    return;
                }
                if (e.Message.Text.StartsWith(EscapePrefix))
                {
                    return;
                }

                foreach (string twitchChannel in GetTwitchChannels(e.Channel))
                {
                    _twitch.SendMessage(twitchChannel, $"{e.User.Name}@{e.Channel.Name}: {e.Message.Text}");
                }
            };
        }
コード例 #8
0
 public AfkCommandHandler(TwitchBot twitchBot)
 {
     TwitchBot = twitchBot;
 }
コード例 #9
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     if (chatMessage.GetMessage().IsMatch(PatternCreator.Create(alias, PrefixHelper.GetPrefix(chatMessage.Channel), @"\sprefix\s\S{1," + Config.MaxPrefixLength + "}")))
     {
         twitchBot.SendSetPrefix(chatMessage, chatMessage.GetLowerSplit()[2][..(chatMessage.GetLowerSplit()[2].Length > Config.MaxPrefixLength ? Config.MaxPrefixLength : chatMessage.GetLowerSplit()[2].Length)]);
コード例 #10
0
        public static void SendDiscordMessageIfAFK(TwitchBot twitchBot, ChatMessage chatMessage)
        {
#warning not implemented
        }
コード例 #11
0
 protected virtual Task ExecuteTwitch(TwitchChatMessage message, CommandContext context, TwitchBot bot)
 {
     return(Task.CompletedTask);
 }
コード例 #12
0
        public void HostChannel(string channel, string channelToHost)
        {
            TwitchBot twitchBot = new TwitchBot(channel, GetAccessToken(channel));

            twitchBot.SendMessage($".host {channelToHost}");
        }
コード例 #13
0
 protected Handler(TwitchBot twitchBot)
 {
     TwitchBot = twitchBot;
 }
コード例 #14
0
 public SongRequestCommand(TwitchBot twitchBot, TwitchChatMessage chatMessage, string alias)
     : base(twitchBot, chatMessage, alias)
 {
 }
コード例 #15
0
 public TwitchConnection[] GetAllAutoConnectingConnections(TwitchBot bot)
 {
     return(SqlTwitchConnection.GetAllAutoConnectingConnections(bot));
 }
コード例 #16
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     twitchBot.Send(chatMessage.Channel, $"Pongeg, I'm here! {twitchBot.GetSystemInfo()}");
 }
コード例 #17
0
        void IModule.Install(ModuleManager manager)
        {
            _client = manager.Client;
            _twitch = new TwitchBot();

            manager.CreateDynCommands("twitch", PermissionLevel.ChannelModerator, group =>
            {
                group.CreateCommand("connect")
                    .Description("Connects this channel to a given twitch channel, relaying the messages between them.")
                    .Parameter("channel")
                    .Do(async e =>
                    {
                        string channel = e.GetArg("channel");

                        if (await IsValidTwitchChannelAndIsStreaming(channel))
                        {
                            int? viewers = await GetViewerCount(channel);

                            if (viewers != null && viewers.Value <= MaxViewsPerChannel)
                                await Subscribe(channel, e.Channel);
                            else
                                await
                                    e.Channel.SafeSendMessage(
                                        $"{channel}'s view count ({viewers}) is currently over the view barrier ({MaxViewsPerChannel}), therefore, for the sake of not getting a cooldown for spamming Discord, we cannot connect to this channel.");
                        }
                        else
                            await e.Channel.SafeSendMessage($"{channel} channel is currently offline.");
                    });

                group.CreateCommand("disconnect")
                    .Description("Disconnects this channel from the given twitch channel.")
                    .Parameter("channel")
                    .Do(async e => { await Unsubscribe(e.GetArg("channel"), e.Channel); });
                group.CreateCommand("list")
                    .MinDynPermissions((int) PermissionLevel.User)
                    .Description("Lists all the twitch channels this discord channel is connected to.")
                    .Do(async e =>
                    {
                        List<string> twitchSub = GetTwitchChannels(e.Channel).ToList();

                        if (!twitchSub.Any())
                        {
                            await e.Channel.SafeSendMessage("This channel isin't subscribed to any twitch channels.");
                            return;
                        }

                        StringBuilder builder = new StringBuilder($"**{e.Channel.Name} is subscribed to:**\r\n```");
                        foreach (string twitchChannel in twitchSub)
                            builder.AppendLine($"* {twitchChannel}");

                        await e.Channel.SafeSendMessage($"{builder.ToString()}```");
                    });
            });

            _twitch.DisconnectFromTwitch +=
                async (s, e) =>
                {
                    Logger.FormattedWrite("Twitch", "Disconnected from twitch", ConsoleColor.Red);

                    // try to reconnect to twitch
                    while (!_twitch.IsConnected)
                    {
                        Logger.FormattedWrite("Twitch", "Attempting to reconnect to twitch...", ConsoleColor.Red);
                        await TwitchTryConnect();
                        await Task.Delay(5000);
                    }

                    Logger.FormattedWrite("Twitch", "Reconnected to twitch.", ConsoleColor.Red);
                };

            _twitch.ChatMessageReceived += async (s, e) =>
            {
                if (!_relays.ContainsKey(e.Message.Channel)) return;
                if (e.Message.Username == Config.TwitchUsername) return;

                if (e.Message.Text.StartsWith(EscapePrefix)) return;

                foreach (JsonChannel relay in _relays[e.Message.Channel])
                    await relay.Channel.SafeSendMessage($"**Twitch**: `<{e.Message.Username}> {e.Message.Text}`");
            };

            _twitch.ChannelLeave += (s, e) => _relays.Remove(e.Channel);

            _client.MessageReceived += (s, e) =>
            {
                if (e.Message.IsAuthor) return;
                if (e.Message.Text.StartsWith(EscapePrefix)) return;

                foreach (string twitchChannel in GetTwitchChannels(e.Channel))
                    _twitch.SendMessage(twitchChannel, $"{e.User.Name}@{e.Channel.Name}: {e.Message.Text}");
            };
        }
コード例 #18
0
ファイル: Manager.cs プロジェクト: Hevedy/GameThis-Community
        public bool Start()
        {
            HEVConsole.LineJump();
            HEVConsole.Print("-- (Settings) --");
            bool settingsLoad = Settings.ConfigRead();

            if (settingsLoad)
            {
                HEVConsole.Print("-> Loaded.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> Failed.", EPrintType.eError);
            }
            HEVConsole.LineJump();
            HEVConsole.Print("-- (Config) --");
            bool configLoad = Config.ConfigRead();

            if (configLoad)
            {
                HEVConsole.Print("-> Loaded.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> Failed.", EPrintType.eError);
            }
            HEVConsole.LineJump();
            HEVConsole.Print("-- (Discord) --");
            Instance.DiscordSDKReady = DiscordSDK.ConfigValidate();
            if (Instance.DiscordSDKReady)
            {
                HEVConsole.Print("-> User Enabled.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> User Disabled.", EPrintType.eWarning);
            }
            Instance.DiscordBotReady = DiscordBot.ConfigValidate();
            if (Instance.DiscordBotReady)
            {
                HEVConsole.Print("-> Bot Enabled.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> Bot Disabled.", EPrintType.eWarning);
            }
            HEVConsole.LineJump();

            // Not implemented
            HEVConsole.Print("-- (Twitch) --");
            Instance.TwitchSDKReady = TwitchSDK.ConfigValidate();
            if (Instance.TwitchSDKReady)
            {
                HEVConsole.Print("-> User Enabled.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> User Disabled.", EPrintType.eWarning);
            }
            Instance.TwitchBotReady = TwitchBot.ConfigValidate();
            if (Instance.TwitchBotReady)
            {
                HEVConsole.Print("-> Bot Enabled.", EPrintType.eSuccess);
            }
            else
            {
                HEVConsole.Print("-> Bot Disabled.", EPrintType.eWarning);
            }
            HEVConsole.LineJump();

            // Now checks every one before

            if (!settingsLoad)
            {
                return(false);
            }
            if (!Settings.ConfigValidate())
            {
                return(false);
            }

            if (!configLoad)
            {
                return(false);
            }
            if (!Config.ConfigValidate())
            {
                return(false);
            }

            Chat = new ChatManager();
            Chat.Start();

            return(true);
        }
コード例 #19
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     twitchBot.TwitchClient.TimeoutUser(chatMessage.Channel, chatMessage.Username, TimeSpan.FromSeconds(1));
 }
コード例 #20
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     twitchBot.SendMathResult(chatMessage);
 }
コード例 #21
0
 public TwitchConnection[] GetAllAutoConnectingConnections(TwitchBot bot)
 {
     return SqlTwitchConnection.GetAllAutoConnectingConnections(bot);
 }
コード例 #22
0
 public CoinflipCommand(TwitchBot twitchBot, TwitchChatMessage chatMessage, string alias)
     : base(twitchBot, chatMessage, alias)
 {
 }
コード例 #23
0
 public ChatResponseBotCommandHandler(TwitchBot bot, string message)
 {
     this.message = message;
     this.bot     = bot;
 }
コード例 #24
0
ファイル: Hooky.cs プロジェクト: calledude/calledudeBot
 public Hooky(TwitchBot twitchBot, ILogger <Hooky> logger)
 {
     _logger    = logger;
     _twitchBot = twitchBot;
 }
コード例 #25
0
        public static bool ConfigRead()
        {
            bool    status = false;
            IniData data   = null;

            if (!SetupConfig())
            {
                return(false);
            }
            (data, status) = HEVIO.FileINIRead(Instance.FileConfig);
            if (!status)
            {
                if (!ConfigWrite())
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }

            HEVConsole.Print("1");


            if (!data.DataINIReadWrite("Profile", "UserName", ref Instance.ConfUserName))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Profile", "Website", ref Instance.ConfWebsite))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "Language", ref Instance.ConfLanguage))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "DiscordUser", ref Instance.ConfDiscordSDK))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "DiscordBot", ref Instance.ConfDiscordBot))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "TwitchUser", ref Instance.ConfTwitchSDK))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "TwitchBot", ref Instance.ConfTwitchBot))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "ComputerRank", ref Instance.ConfComputerRank))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "UserBlackListString", ref Instance.UserBlackList))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "BotBlackListString", ref Instance.BotBlackList))
            {
                status = false;
            }
            if (!data.DataINIReadWrite("Configuration", "RPGGame", ref Instance.ConfRPGGame))
            {
                status = false;
            }

            if (!status)
            {
                status = HEVIO.FileINIWrite(Instance.FileConfig, data);
            }

            // Get the settings of every system
            if (!DiscordSDK.ConfigRead())
            {
                return(false);
            }
            if (!DiscordBot.ConfigRead())
            {
                return(false);
            }
            if (!TwitchSDK.ConfigRead())
            {
                return(false);
            }
            if (!TwitchBot.ConfigRead())
            {
                return(false);
            }
            return(status);
        }
コード例 #26
0
 public LeaveChannelCommand(TwitchBot bot, Level AccessLevel)
 {
     this.bot         = bot;
     this.AccessLevel = AccessLevel;
 }
コード例 #27
0
 public Chatterino7Command(TwitchBot twitchBot, TwitchChatMessage chatMessage, string alias)
     : base(twitchBot, chatMessage, alias)
 {
     Response = $"Website: 7tv.app || Releases: github.com/SevenTV/chatterino7/releases";
 }
コード例 #28
0
 public void SetBot(TwitchBot bot)
 {
     this.bot = bot;
 }
コード例 #29
0
 public UnsubCommand(TwitchBot twitchBot, TwitchChatMessage chatMessage, string alias)
     : base(twitchBot, chatMessage, alias)
 {
 }
コード例 #30
0
 public TwitchMessageHandler(ILogger <TwitchMessageHandler> logger, TwitchBot bot, MessageDispatcher dispatcher)
     : base(logger, bot, dispatcher)
 {
 }
コード例 #31
0
 public CommandHandler(TwitchBot twitchBot)
     : base(twitchBot)
 {
     AfkCommandHandler = new(twitchBot);
 }
コード例 #32
0
ファイル: BotInfo.cs プロジェクト: PatrickHollweck/Creative
 public static BotInfo FromBot(TwitchBot bot)
 {
     return(new BotInfo(bot.StartTime, DateTime.Now, bot.Channel));
 }
コード例 #33
0
        protected override async Task ExecuteTwitch(TwitchChatMessage message, CommandContext context, TwitchBot bot)
        {
            CommandParser parser = CommandParser.TryCreate(message.Content);

            string userName;

            try
            {
                userName = parser?.ParseOptionalWord();
            }
            catch (CommandParseError error)
            {
                bot.SendMessage(error.Message, context);
                bot.SendMessage(Usage, context);

                return;
            }

            string fromId;

            if (userName == null)
            {
                fromId = message.Sender.Id.ToString();
            }
            else
            {
                fromId = TwitchUser.GetByName(userName).Id.ToString();
            }

            GetUsersFollowsResponse follow = await TwitchBot.TwitchApi.Helix.Users.GetUsersFollowsAsync(fromId : fromId, toId : TwitchBot.CurrentChannel.Id);

            if (follow.Follows.Length == 0)
            {
                if (userName == null)
                {
                    bot.SendMessage($"@{message.Sender.UserName} You are not following the channel.", context);
                }
                else
                {
                    bot.SendMessage($"@{message.Sender.UserName} {userName} is not following the channel.", context);
                }
            }
            else
            {
                TimeSpan followage = DateTime.UtcNow - follow.Follows[0].FollowedAt;

                if (userName == null)
                {
                    bot.SendMessage($"@{message.Sender.UserName} You have been following the channel for {Helpers.FormatTimeSpan(followage)}.", context);
                }
                else
                {
                    bot.SendMessage($"@{message.Sender.UserName} {userName} has been following the channel for {Helpers.FormatTimeSpan(followage)}.", context);
                }
            }
        }
コード例 #34
0
 static string GetJson(TwitchBot bot, uint limit, uint offset, string path)
 {
     return(WebClient.GetHTML("https://api.twitch.tv/kraken/" + path + "&oauth_token=" + bot.oauthPassword + "&limit=" + limit
                              + "&offset=" + offset));
 }
コード例 #35
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     twitchBot.SendCoinFlip(chatMessage);
 }
コード例 #36
0
 public static void Handle(TwitchBot twitchBot, ChatMessage chatMessage, string alias)
 {
     twitchBot.SendRandomCookie(chatMessage);
 }
コード例 #37
0
 public SqlTwitchConnection(TwitchBot bot, TwitchChannel channel, bool autoConnectToChat = false)
     : base(new object[] { bot.user.id, channel.user.id, autoConnectToChat })
 {
     this.bot     = bot;
     this.channel = channel;
 }