rmsoft1

GoLive.cs

Apr 29th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.86 KB | None | 0 0
  1. //http://rms0.org?a=r1 - Helpful.
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Discord.WebSocket;
  9. using Discord.Commands;
  10. using Discord;
  11. using System.IO;
  12. using Newtonsoft.Json;
  13. namespace GoLive
  14. {
  15.     public class TwitchNotificationService
  16.     {
  17.         DiscordSocketClient _client = null;
  18.         List<UserShout> shoutEntities = new List<UserShout>();
  19.         public bool Initialized = false;
  20.         public TwitchNotificationService(DiscordSocketClient client)
  21.         {
  22.             LogMessage l2 = new LogMessage(LogSeverity.Warning, "GoLive", "TwitchNotificationService constructor called.");
  23.             Client_Log(l2);
  24.             _client = client;
  25.             _client.GuildMemberUpdated += _client_GuildMemberUpdated;
  26.             //Read shouts.json, otherwise create it.
  27.             using (FileStream fs = File.Open("shouts.json", FileMode.OpenOrCreate))
  28.             {
  29.                 using (StreamReader sr = new StreamReader(fs))
  30.                 {
  31.                     string f = sr.ReadToEnd();
  32.                     if (!string.IsNullOrWhiteSpace(f))
  33.                     {
  34.                         JsonSerializerSettings s = new JsonSerializerSettings();
  35.                         s.Formatting = Formatting.Indented;
  36.                         s.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
  37.                         s.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
  38.                         s.TypeNameHandling = TypeNameHandling.Arrays;
  39.                         shoutEntities = ((Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(f,s)).ToObject<List<UserShout>>();
  40.                         if (shoutEntities == null)
  41.                         {
  42.                             shoutEntities = new List<UserShout>();
  43.                             LogMessage l = new LogMessage(LogSeverity.Warning, "GoLive", "WARNING: Shouts.json is null or invalid.");
  44.                             Client_Log(l);
  45.                         }
  46.                     }
  47.                 }
  48.             }
  49.         }
  50.         private Task Client_Log(LogMessage arg)
  51.         {
  52.             Console.WriteLine(arg);
  53.             return Task.Delay(0);
  54.         }
  55.         /// <summary>
  56.         /// Service. Add a new shout entity.
  57.         /// </summary>
  58.         /// <param name="context"></param>
  59.         /// <param name="user"></param>
  60.         /// <param name="SupressEveryone"></param>
  61.         /// <returns></returns>
  62.         public async Task AddShoutEntity(ICommandContext context, SocketGuildUser user, bool SupressEveryone)
  63.         {
  64.             UserShout item = shoutEntities.FirstOrDefault(x => x.userID == user.Id);
  65.             if (item != null)
  66.             {
  67.                 //That user is already in the list. Cool! Check the channel and alter nothing else.
  68.                
  69.                 if(item.ChannelIDs.Contains(context.Channel.Id))
  70.                 {
  71.                     await context.Channel.SendMessageAsync("This channel already has a notification for this user. Please use a different channel.\r\n"+
  72.                         "**Please note: You cannot add multiple twitch accounts to the same user.**");
  73.                     return;//Cancel the operation. NO SAVE.
  74.                 }
  75.                 else
  76.                 {
  77.                     item.AddChannel(context.Channel.Id);//An existing channelID wasn't found. Add it to the list.
  78.                     await context.Channel.SendMessageAsync($"This channel is now subscribed to going live alerts from (Discord user: {user.Username})");
  79.                 }
  80.             }
  81.             else
  82.             {
  83.                 shoutEntities.Add(new UserShout(user.Id, context.Channel.Id, SupressEveryone));
  84.                 //Add a brand new item to our shout list.
  85.                 await context.Channel.SendMessageAsync($"This channel is now subscribed to going live alerts from (Discord user: {user.Username})");
  86.             }
  87.             //Save shouts.json.
  88.             using (FileStream fs = File.Create("shouts.json"))
  89.             {
  90.                 using (StreamWriter sw = new StreamWriter(fs))
  91.                 {
  92.                     sw.WriteLine(JsonConvert.SerializeObject(shoutEntities,Formatting.Indented));//Output and save a file.
  93.                     sw.Flush();
  94.                 }
  95.  
  96.             }
  97.         }
  98.  
  99.         /// <summary>
  100.         /// Service. Removes an entire user's stream alerts.
  101.         /// </summary>
  102.         /// <param name="context"></param>
  103.         /// <param name="user"></param>
  104.         /// <returns></returns>
  105.         public async Task RemoveShoutEntity(ICommandContext context, SocketGuildUser user)
  106.         {
  107.             UserShout item = shoutEntities.FirstOrDefault(x => x.userID == user.Id);
  108.             if (item != null)
  109.             {
  110.                 //That user is already in the list. Cool! Check the channel and alter nothing else.
  111.  
  112.                 shoutEntities.Remove(item);
  113.                 await context.Channel.SendMessageAsync($"Removed {(await context.Guild.GetUserAsync(item.userID)).Username}'s stream alert.");
  114.             }
  115.             else
  116.             {
  117.                 await context.Channel.SendMessageAsync($"Hey! This user doesn't have any stream alerts. Try that again please.");
  118.                 return;
  119.             }
  120.             //Save shouts.json.
  121.             using (FileStream fs = File.Create("shouts.json"))
  122.             {
  123.                 using (StreamWriter sw = new StreamWriter(fs))
  124.                 {
  125.                     sw.WriteLine(JsonConvert.SerializeObject(shoutEntities, Formatting.Indented));//Output and save a file.
  126.                     sw.Flush();
  127.                 }
  128.  
  129.             }
  130.         }
  131.  
  132.         /// <summary>
  133.         /// Service. Remove a channel from a user's stream alert. This must be called from the channel where the alert is set.
  134.         /// </summary>
  135.         /// <param name="context"></param>
  136.         /// <param name="user"></param>
  137.         /// <returns></returns>
  138.         public async Task RemoveEntityChannel(ICommandContext context, SocketGuildUser user)
  139.         {
  140.             UserShout item = shoutEntities.FirstOrDefault(x => x.userID == user.Id);
  141.  
  142.             SocketTextChannel channel = context.Channel as SocketTextChannel;
  143.             if (item != null)
  144.             {
  145.                 //That user is already in the list. Cool! Check the channel and alter nothing else.
  146.  
  147.                 ulong chToRem = item.ChannelIDs.FirstOrDefault(x => x == channel.Id);
  148.                 if(chToRem == 0)
  149.                 {
  150.                     await context.Channel.SendMessageAsync($"A notification for {(await context.Guild.GetUserAsync(item.userID)).Username}'s stream alert does not exist for this channel.");
  151.                     return;
  152.                 }
  153.                 item.ChannelIDs.Remove(chToRem);
  154.                 await context.Channel.SendMessageAsync($"Removed {(await context.Guild.GetUserAsync(item.userID)).Username}'s stream alert. from this channel.");
  155.             }
  156.             else
  157.             {
  158.                 await context.Channel.SendMessageAsync($"Hey! This user doesn't have any stream alerts. Try that again please.");
  159.                 return;
  160.             }
  161.             //Save shouts.json.
  162.             using (FileStream fs = File.Create("shouts.json"))
  163.             {
  164.                 using (StreamWriter sw = new StreamWriter(fs))
  165.                 {
  166.                     sw.WriteLine(JsonConvert.SerializeObject(shoutEntities, Formatting.Indented));//Output and save a file.
  167.                     sw.Flush();
  168.                 }
  169.  
  170.             }
  171.         }
  172.  
  173.         private async Task _client_GuildMemberUpdated(SocketGuildUser arg1, SocketGuildUser arg2)
  174.         {
  175.             if (arg1.Game?.StreamType == StreamType.NotStreaming && arg2.Game?.StreamType == StreamType.Twitch)//Event gets fired for every guild??
  176.             {
  177.                 //add role.
  178.                 await arg2.AddRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  179.                 await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " went live! [Guild: "+arg2.Guild.Name+"]"));
  180.                 UserShout Shout = shoutEntities.FirstOrDefault(x => x.userID == arg2.Id);
  181.                 if (Shout != null)
  182.                 {
  183.                     foreach (var item in Shout.ChannelIDs)
  184.                     {
  185.                         SocketTextChannel ch = _client.GetChannel(item) as SocketTextChannel;
  186.                         string[] array = arg2.Game?.StreamUrl.Split('/');
  187.                         if (ch.Guild == arg2.Guild)
  188.                         {
  189.                             if (Shout.SupressEveryone)
  190.                             {
  191.                                
  192.                                 await ch.SendMessageAsync(array.Last() + " just went live! " + arg2.Game?.StreamUrl);
  193.                             }
  194.                             else
  195.                             {
  196.                                 await ch.SendMessageAsync("@everyone " + array.Last() + " just went live! " + arg2.Game?.StreamUrl);
  197.                             }
  198.                         }
  199.                     }
  200.                 }
  201.  
  202.             }
  203.             if (arg1.Game?.StreamType == StreamType.Twitch && arg2.Game?.StreamType == StreamType.NotStreaming)
  204.             {
  205.                 //remove the role
  206.                 await arg2.RemoveRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  207.                 await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " Ended stream. [Guild: " + arg2.Guild.Name + "]"));
  208.             }
  209.         }
  210.  
  211.         public async Task Initialize()
  212.         {
  213.             Initialized = true;
  214.             await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", "Called Initialization. Checking all users. (This could take a minute)"));
  215.             foreach (SocketGuild guild in _client.Guilds)
  216.             {
  217.                 foreach (SocketGuildUser arg2 in guild.Users)
  218.                 {
  219.                     if (arg2.Game?.StreamType == StreamType.Twitch)//Event gets fired twice??
  220.                     {
  221.                         await arg2.AddRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  222.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " is live!"));
  223.  
  224.  
  225.                     }
  226.                     if (arg2.Game?.StreamType == StreamType.NotStreaming)
  227.                     {
  228.                         await arg2.RemoveRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  229.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " is not live"));
  230.                     }
  231.                 }
  232.             }
  233.             await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", "Operation complete! Listening for further updates."));
  234.  
  235.         }
  236.  
  237.         public async Task ShoutTest(ICommandContext context)
  238.         {
  239.  
  240.             await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", "HEY!!! TEST!"));
  241.             foreach (SocketGuild guild in _client.Guilds)
  242.             {
  243.                 foreach (SocketGuildUser arg2 in guild.Users)
  244.                 {
  245.                     if (arg2.Game?.StreamType == StreamType.Twitch)
  246.                     {
  247.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", "user streamtype twitch."+ arg2.Username));
  248.                         await arg2.AddRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  249.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " is live!"));
  250.                         //add role.
  251.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " went live! [Guild: " + arg2.Guild.Name + "]"));
  252.                         UserShout Shout = shoutEntities.FirstOrDefault(x => x.userID == arg2.Id);
  253.                         if (Shout != null)
  254.                         {
  255.                             foreach (var item in Shout.ChannelIDs)
  256.                             {
  257.                                 SocketTextChannel ch = _client.GetChannel(item) as SocketTextChannel;
  258.                                 string[] array = arg2.Game?.StreamUrl.Split('/');
  259.                                 if (ch.Guild == arg2.Guild)
  260.                                 {
  261.                                     if (Shout.SupressEveryone)
  262.                                     {
  263.  
  264.                                         await ch.SendMessageAsync(array.Last() + " just went live! " + arg2.Game?.StreamUrl);
  265.                                     }
  266.                                     else
  267.                                     {
  268.                                         await ch.SendMessageAsync("@everyone " + array.Last() + " just went live! " + arg2.Game?.StreamUrl);
  269.                                     }
  270.                                 }
  271.                             }
  272.                         }
  273.  
  274.  
  275.                     }
  276.                     if (arg2.Game?.StreamType == StreamType.NotStreaming)
  277.                     {
  278.                         await arg2.RemoveRoleAsync(arg2.Guild.GetRole(arg2.Guild.Roles.FirstOrDefault(x => x.Name == "🔴 Live!").Id));
  279.                         await Client_Log(new LogMessage(LogSeverity.Info, "GoLive", arg2.Username + " is not live"));
  280.                     }
  281.                 }
  282.             }
  283.         }
  284.     }
  285.  
  286.     public class UserShout
  287.     {
  288.         #region Properties
  289.         public ulong userID { get; set; }
  290.         public List<ulong> ChannelIDs { get; set; }
  291.         public bool SupressEveryone { get; set; }
  292.         #endregion
  293.  
  294.         /// <summary>
  295.         /// Create a new UserShout data entry.
  296.         /// </summary>
  297.         /// <param name="User">the ID of the user</param>
  298.         /// <param name="ChannelID">The channel where GoLive shoutouts will be posted</param>
  299.         /// <param name="twitchUsername">The user's twitch username</param>
  300.         /// <param name="supressEveryone">Prevent @everyone from being added to the shoutout.</param>
  301.         public UserShout(ulong User, ulong ChannelID, bool supressEveryone)
  302.         {
  303.             userID = User;
  304.             ChannelIDs = new List<ulong>();
  305.             ChannelIDs.Add(ChannelID);
  306.             SupressEveryone = supressEveryone;
  307.         }
  308.  
  309.         /// <summary>
  310.         /// Adds a channel to the list of channels to send the shoutout.
  311.         /// </summary>
  312.         /// <param name="id"></param>
  313.         public void AddChannel(ulong id)
  314.         {
  315.             ChannelIDs.Add(id);
  316.         }
  317.  
  318.         /// <summary>
  319.         /// Removes a channel from the list of channels to send the shoutout.
  320.         /// </summary>
  321.         /// <param name="id"></param>
  322.         /// <returns></returns>
  323.         public bool DeleteChannel(uint id)
  324.         {
  325.             return ChannelIDs.Remove(id);
  326.         }
  327.     }
  328.  
  329.     public class GoLiveModule: ModuleBase
  330.     {
  331.         DiscordSocketClient _client { get; set; }
  332.         TwitchNotificationService _service { get; set; }
  333.         public GoLiveModule(DiscordSocketClient discord, TwitchNotificationService service)
  334.         {
  335.             _client = discord;
  336.             _service = service;
  337.  
  338.         }
  339.  
  340.         [Command("AddAlert"), RequireUserPermission(GuildPermission.ManageGuild), Remarks("[CMDMgmt]")]
  341.         public async Task AddAlert(IGuildUser user, bool SupressEveryone)
  342.         {
  343.             await _service.AddShoutEntity(Context, user as SocketGuildUser, SupressEveryone);
  344.         }
  345.  
  346.         [Command("RemoveAlertChannel"), RequireUserPermission(GuildPermission.ManageGuild), Remarks("[CMDMgmt]")]
  347.         public async Task delchalert(IGuildUser user)
  348.         {
  349.             await _service.RemoveEntityChannel(Context, user as SocketGuildUser);
  350.         }
  351.         [Command("RemoveAlert"), RequireUserPermission(GuildPermission.ManageGuild), Remarks("[CMDMgmt]")]
  352.         public async Task delAlert(IGuildUser user)
  353.         {
  354.             await _service.RemoveShoutEntity(Context, user as SocketGuildUser);
  355.         }
  356.         [Command("AboutGoLive")]
  357.         public async Task about()
  358.         {
  359.             EmbedBuilder builder = new EmbedBuilder();
  360.             builder.WithAuthor(_client.CurrentUser);
  361.             builder.WithTitle($"GoLive v{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}");
  362.             builder.Description = "A module for the twitch streamer. Offering visibility for other streamers in your guild. Below are supported commands.";
  363.             builder.AddField("AddAlert", $"Users who have permission to manage the guild can add GoingLive alerts to a channel.\r\nUSAGE:`{Context.Message.Content[0].ToString()}AddAlert <discordUser> <TwitchUsername> <SupressEveryone>` where SupressEveryone will turn off @ everyone pings if true.");
  364.             builder.AddField("InitGoLive", $"Add this command to the OnStart.bcmd file, to enable the module when the bot starts. Otherwise, live alerts will not work.\r\nOnStart.bcmd entry: `%p_InitGoLive`");
  365.             builder.AddField("AboutGoLive", "Show this information again.");
  366.             await Context.Channel.SendMessageAsync("",false,builder.Build());
  367.         }
  368.         [Command("InitGoLive",RunMode = RunMode.Async)]
  369.         public async Task Init()
  370.         {
  371.             if(_service.Initialized)
  372.             {
  373.                 await Context.Channel.SendMessageAsync("The GoLive module has already been started. No further action required.");
  374.                 return;
  375.             }
  376.             await _service.Initialize();
  377.         }
  378.         [Command("testGoLive", RunMode = RunMode.Async), RequireUserPermission(GuildPermission.ManageGuild), Remarks("[CMDMgmt]")]
  379.         public async Task TEST_ALL_THINGS()
  380.         {
  381.            
  382.             await _service.ShoutTest(Context);
  383.         }
  384.     }
  385. }
Advertisement
Add Comment
Please, Sign In to add comment