Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            using (var streamReader = new StreamReader("config.yaml"))
            {
                var deserializer = new YamlDotNet.Serialization.Deserializer();
                Config = deserializer.Deserialize(streamReader);

                Console.WriteLine("Successfully loaded configuration.");
            }

            new Thread(() =>
            {
                try
                {
                    DiscordSession.Connect();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }).Start();

            new Thread(() =>
            {
                try
                {
                    WikiaSession.GetChatInfo();
                    WikiaSession.ConnectToChat();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }).Start();

            new Thread(() =>
            {
                int time = 1000 * 60 * int.Parse(Config["restart_timer"]);

                Thread.Sleep(time);

                Restart();
            }).Start();
        }
Ejemplo n.º 2
0
        private static async Task StartAsync(string[] args)
        {
            using (var fileStream = new FileStream("config.yaml", FileMode.Open))
                using (var streamReader = new StreamReader(fileStream))
                {
                    var deserializer = new YamlDotNet.Serialization.Deserializer();
                    config = deserializer.Deserialize(streamReader);

                    Console.WriteLine("Successfully loaded configuration.");
                }

            bool useTimestamp = false;

            try
            {
                useTimestamp = bool.TryParse(config["log_timestamp"], out bool value) && value;
            }
            catch (KeyNotFoundException) { }

            Tools.InitLogging(useTimestamp);

            await WikiaSession.Init((string)config["wikia_name"], (string)config["wikia_username"], (string)config["wikia_password"]);

            await WikiaSession.GetChatInfo((string)config["wikia_username"]);

            string botToken       = config["discord_bot_token"];
            ulong  discordChannel = ulong.Parse(config["discord_channel"]);
            string wikiaName      = config["wikia_name"];

            await DiscordSession.Init(botToken, discordChannel, wikiaName);

            cts = new CancellationTokenSource(TimeSpan.FromMinutes(int.Parse(config["restart_timer"])));
            var completionSource = new TaskCompletionSource <object>();

            cts.Token.Register(() => completionSource.TrySetCanceled());
            await Task.WhenAny(WikiaSession.ConnectToChat(), completionSource.Task);
        }
Ejemplo n.º 3
0
        public static void Connect()
        {
            DiscordSession.DiscordClient = new DiscordClient(x =>
            {
                x.AppName = "WikiaDiscordBridge";
            });

            DiscordSession.DiscordClient.ExecuteAndWait(async() =>
            {
                while (true)
                {
                    try
                    {
                        await DiscordClient.Connect(WikiaDiscordBridge.Config["discord_bot_token"], TokenType.Bot);
                        break;
                    }
                    catch (Exception ex)
                    {
                        DiscordClient.Log.Error("Login Failed", ex);
                        await Task.Delay(DiscordClient.Config.FailedReconnectDelay);
                    }
                }

                await Task.Delay(5000); // Not everything is instantly loaded if using a bot account.

                TrackedChannel = DiscordClient.GetChannel(ulong.Parse(WikiaDiscordBridge.Config["discord_channel"]));

                Console.WriteLine($"Connected to Discord as @{DiscordClient.CurrentUser.Name}.");

                DiscordClient.MessageReceived += (s, e) =>
                {
                    if (e.Channel.Id == TrackedChannel.Id)
                    {
                        if (e.User.Id != DiscordClient.CurrentUser.Id)
                        {
                            string displayName;

                            if (e.User.Nickname != null && e.User.Nickname.Trim() != "")
                            {
                                displayName = e.User.Nickname;
                            }
                            else
                            {
                                displayName = e.User.Name;
                            }

                            if (e.Message.Attachments.Count() > 0)
                            {
                                WikiaSession.SendMessage($"{displayName}: {e.Message.Attachments[0].Url}");
                            }
                            else
                            {
                                WikiaSession.SendMessage($"{displayName}: {e.Message.Text}");

                                if (Regex.IsMatch(e.Message.RawText, @"\[\[.+\]\]"))
                                {
                                    var matches = Regex.Matches(e.Message.RawText, @"\[\[(.+?)\]\]");

                                    foreach (Match match in matches)
                                    {
                                        string resourceName = match.Groups[1].Value;
                                        resourceName        = resourceName.Replace(" ", "_");
                                        resourceName        = Uri.EscapeUriString(resourceName);

                                        e.Channel.SendMessage($"<http://swordartonline.wikia.com/wiki/{resourceName}>");
                                    }
                                }
                            }
                        }
                    }
                };
            });
        }
        static DiscordSession()
        {
            client.Connected += () =>
            {
                Tools.Log("Discord", $"Connected to Discord as {client.CurrentUser.Username}#{client.CurrentUser.DiscriminatorValue}.");
                return(Task.CompletedTask);
            };
            client.Log += msg =>
            {
                Tools.Log("Discord", $"{msg.Severity}: {msg.Message}");
                return(Task.CompletedTask);
            };
            client.MessageReceived += async msg =>
            {
                var userMessage = msg as IUserMessage;
                if (userMessage == null)
                {
                    return;
                }

                if (userMessage.Author.Id == client.CurrentUser.Id)
                {
                    return;
                }

                var matches = LinkRegex.Matches(userMessage.Content);
                if (matches.Count > 0)
                {
                    foreach (Match match in matches)
                    {
                        var resourceName = match.Groups[1].Value.Replace(" ", "_");
                        var escapedName  = Uri.EscapeDataString(resourceName);

                        await userMessage.Channel.SendMessageAsync($"<http://{wikiaName}.wikia.com/wiki/{escapedName}>");
                    }
                }


                if (userMessage.Channel.Id != trackedChannelId)
                {
                    return;
                }

                var displayName = string.IsNullOrWhiteSpace((userMessage.Author as IGuildUser)?.Nickname)
                    ? userMessage.Author.Username
                    : ((IGuildUser)userMessage.Author).Nickname;

                if (userMessage.Attachments.Count > 0)
                {
                    foreach (var attachment in userMessage.Attachments)
                    {
                        await WikiaSession.SendMessage($"{displayName}: {attachment.Url}");
                    }
                }

                if (string.IsNullOrWhiteSpace(userMessage.Content))
                {
                    return;
                }

                await WikiaSession.SendMessage($"{displayName}: {userMessage.Resolve()}");
            };
        }